diff --git a/go.mod b/go.mod index 1a6cd25fd..4fcca705b 100644 --- a/go.mod +++ b/go.mod @@ -45,7 +45,7 @@ require ( github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect github.com/AzureAD/microsoft-authentication-library-for-go v1.7.2 // indirect github.com/alecthomas/units v0.0.0-20240927000941-0f3dac36c52b // indirect - github.com/anthropics/anthropic-sdk-go v1.37.0 // indirect + github.com/anthropics/anthropic-sdk-go v1.67.0 // indirect github.com/aws/aws-sdk-go-v2 v1.43.0 // indirect github.com/aws/aws-sdk-go-v2/config v1.32.31 // indirect github.com/aws/aws-sdk-go-v2/credentials v1.19.30 // indirect @@ -121,6 +121,7 @@ require ( github.com/grafana/regexp v0.0.0-20250905093917-f7b3be9d1853 // indirect github.com/hashicorp/go-version v1.9.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect + github.com/invopop/jsonschema v0.14.0 // indirect github.com/jpillora/backoff v1.0.0 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/julienschmidt/httprouter v1.3.0 // indirect @@ -158,6 +159,7 @@ require ( github.com/puzpuzpuz/xsync/v4 v4.5.0 // indirect github.com/santhosh-tekuri/jsonschema/v6 v6.0.2 // indirect github.com/spf13/pflag v1.0.10 // indirect + github.com/standard-webhooks/standard-webhooks/libraries v0.0.1 // indirect github.com/tidwall/gjson v1.19.0 // indirect github.com/tidwall/match v1.2.0 // indirect github.com/tidwall/pretty v1.2.1 // indirect diff --git a/go.sum b/go.sum index a7c8344a6..d0f212a4d 100644 --- a/go.sum +++ b/go.sum @@ -33,8 +33,8 @@ github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERo github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU= github.com/alecthomas/units v0.0.0-20240927000941-0f3dac36c52b h1:mimo19zliBX/vSQ6PWWSL9lK8qwHozUj03+zLoEB8O0= github.com/alecthomas/units v0.0.0-20240927000941-0f3dac36c52b/go.mod h1:fvzegU4vN3H1qMT+8wDmzjAcDONcgo2/SZ/TyfdUOFs= -github.com/anthropics/anthropic-sdk-go v1.37.0 h1:yBKUaBG3TCRb6das/Q5qNB9Fsafon09gu2yYVgvapKE= -github.com/anthropics/anthropic-sdk-go v1.37.0/go.mod h1:dSIO7kSrOI7MA4fE6RRVaw8tyWP7HNQU5/H/KS4cax8= +github.com/anthropics/anthropic-sdk-go v1.67.0 h1:tTsVSR+YD6R+1EPoMyZ9im7YKEjJpYGZk5klcDi9HRg= +github.com/anthropics/anthropic-sdk-go v1.67.0/go.mod h1:3EfIfmFqxH6rbiLcIP4tPFyXL/IHakx2wDG4OU+TIEI= github.com/antlr4-go/antlr/v4 v4.13.0 h1:lxCg3LAv+EUK6t1i0y1V6/SLeUi0eKEKdhQAlS8TVTI= github.com/antlr4-go/antlr/v4 v4.13.0/go.mod h1:pfChB/xh/Unjila75QW7+VU4TSnWnnk9UTnmpPaOR2g= github.com/armon/go-metrics v0.4.1 h1:hR91U9KYmb6bLBYLQjyM+3j+rcd/UhE+G78SFnF8gJA= @@ -313,6 +313,8 @@ github.com/hetznercloud/hcloud-go/v2 v2.36.0/go.mod h1:MnN/QJEa/RYNQiiVoJjNHPntM github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= +github.com/invopop/jsonschema v0.14.0 h1:MHQqLhvpNUZfw+hM3AZDYK7jxO8FZoQeQM77g8iyZjg= +github.com/invopop/jsonschema v0.14.0/go.mod h1:ygm6C2EaVNMBDPpaPlnOA2pFAxBnxGjFlMZABxm9n2I= github.com/ionos-cloud/sdk-go/v6 v6.3.6 h1:l/TtKgdQ1wUH3DDe2SfFD78AW+TJWdEbDpQhHkWd6CM= github.com/ionos-cloud/sdk-go/v6 v6.3.6/go.mod h1:nUGHP4kZHAZngCVr4v6C8nuargFrtvt7GrzH/hqn7c4= github.com/jpillora/backoff v1.0.0 h1:uvFg412JmmHBHw7iwprIxkPMI+sGQ4kzOWsMeHnm2EA= @@ -468,6 +470,8 @@ github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/stackitcloud/stackit-sdk-go/core v0.23.0 h1:zPrOhf3Xe47rKRs1fg/AqKYUiJJRYjdcv+3qsS50mEs= github.com/stackitcloud/stackit-sdk-go/core v0.23.0/go.mod h1:osMglDby4csGZ5sIfhNyYq1bS1TxIdPY88+skE/kkmI= +github.com/standard-webhooks/standard-webhooks/libraries v0.0.1 h1:uOfcYT+3QungH6tIGSVCR/Y3KJmgJiHcojJbMTPDZAI= +github.com/standard-webhooks/standard-webhooks/libraries v0.0.1/go.mod h1:L1MQhA6x4dn9r007T033lsaZMv9EmBAdXyU/+EF40fo= github.com/stoewer/go-strcase v1.3.0 h1:g0eASXYtp+yvN9fK8sH94oCIk0fau9uV1/ZdJ0AVEzs= github.com/stoewer/go-strcase v1.3.0/go.mod h1:fAH5hQ5pehh+j3nZfvwdk2RgEgQjAoM8wodgtPmh1xo= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/.gitignore b/vendor/github.com/anthropics/anthropic-sdk-go/.gitignore index 8554affe5..e50d9fab5 100644 --- a/vendor/github.com/anthropics/anthropic-sdk-go/.gitignore +++ b/vendor/github.com/anthropics/anthropic-sdk-go/.gitignore @@ -1,4 +1,3 @@ -.prism.log .stdy.log codegen.log Brewfile.lock.json diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/.release-please-manifest.json b/vendor/github.com/anthropics/anthropic-sdk-go/.release-please-manifest.json index 3ab81460f..0eac89a36 100644 --- a/vendor/github.com/anthropics/anthropic-sdk-go/.release-please-manifest.json +++ b/vendor/github.com/anthropics/anthropic-sdk-go/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.37.0" + ".": "1.67.0" } diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/.stats.yml b/vendor/github.com/anthropics/anthropic-sdk-go/.stats.yml index d44995adf..089f13d71 100644 --- a/vendor/github.com/anthropics/anthropic-sdk-go/.stats.yml +++ b/vendor/github.com/anthropics/anthropic-sdk-go/.stats.yml @@ -1,4 +1,4 @@ -configured_endpoints: 77 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/anthropic%2Fanthropic-e0696f59ae07dc1a9c5a8fc87a4eb05eb35afabaac0b5ff0ea38810fa9dd4a74.yml -openapi_spec_hash: 69278ebbb0d1aa0b322bbbd5128bcec5 -config_hash: b0dbd234c2752507397c139a416f6cba +configured_endpoints: 200 +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/anthropic/anthropic-446ddab751d9f0172400b17fc72736e9353d3b49780317f90c24aa98357fd39e.yml +openapi_spec_hash: f05934667b8dd6e84a29590f11f8737c +config_hash: 50dc950c023a11d2acda828a2b614ad1 diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/CHANGELOG.md b/vendor/github.com/anthropics/anthropic-sdk-go/CHANGELOG.md index 6ea8f178e..6357499de 100644 --- a/vendor/github.com/anthropics/anthropic-sdk-go/CHANGELOG.md +++ b/vendor/github.com/anthropics/anthropic-sdk-go/CHANGELOG.md @@ -1,5 +1,522 @@ # Changelog +## 1.67.0 (2026-08-26) + +Full Changelog: [v1.66.0...v1.67.0](https://github.com/anthropics/anthropic-sdk-go/compare/v1.66.0...v1.67.0) + +### Features + +* **api:** add `updates` thinking display mode (beta) ([44fa7a6](https://github.com/anthropics/anthropic-sdk-go/commit/44fa7a6b087cb1b4355647b7ecb42c46eb6f1dba)) +* **api:** add missing anthropic-beta values ([118b499](https://github.com/anthropics/anthropic-sdk-go/commit/118b499229b44363152577e2bbf45d2f90ef3983)) +* **api:** add support for Organization API endpoints ([713c567](https://github.com/anthropics/anthropic-sdk-go/commit/713c567ef716aa62f9b0fadb24b3aaf8fb506095)) + + +### Bug Fixes + +* **messages:** add missing ToParam methods and exhaustiveness test ([#245](https://github.com/anthropics/anthropic-sdk-go/issues/245)) ([e385915](https://github.com/anthropics/anthropic-sdk-go/commit/e385915879ab975b0c31476088bdac6d59a9fc4f)) +* **tools:** keep the tool runner going on pause_turn ([#250](https://github.com/anthropics/anthropic-sdk-go/issues/250)) ([2fa015b](https://github.com/anthropics/anthropic-sdk-go/commit/2fa015bb89d7a07bbeb416aec85246f353eb4c98)) + + +### Chores + +* **docs:** clarify skill version `latest` support and memory version retention ([c5d5ac4](https://github.com/anthropics/anthropic-sdk-go/commit/c5d5ac46543c149dfd9ec5948ab99421104572aa)) +* **internal:** cancel superseded CI runs ([5413684](https://github.com/anthropics/anthropic-sdk-go/commit/541368421db45277ee3cea803c1a1705fdcfe2f2)) + + +### Documentation + +* **api:** clarify session thread agent and usage.iterations compaction descriptions (beta) ([e017f63](https://github.com/anthropics/anthropic-sdk-go/commit/e017f63e48aad5fef6f98ebdd5f9cbf93db33845)) + +## 1.66.0 (2026-08-19) + +Full Changelog: [v1.65.0...v1.66.0](https://github.com/anthropics/anthropic-sdk-go/compare/v1.65.0...v1.66.0) + +### Features + +* **api:** managed agents web search config and self hosted sandbox memory ([694b03a](https://github.com/anthropics/anthropic-sdk-go/commit/694b03a4a6e3318b0a6175ff988f635049187f29)) + +## 1.65.0 (2026-08-19) + +Full Changelog: [v1.64.0...v1.65.0](https://github.com/anthropics/anthropic-sdk-go/compare/v1.64.0...v1.65.0) + +### Features + +* **api:** Files and Skills APIs are now GA; add computer use and browser use toolsets ([e7be7af](https://github.com/anthropics/anthropic-sdk-go/commit/e7be7af468408ca98adae858777d47a71487c4f8)) + +## 1.64.0 (2026-08-18) + +Full Changelog: [v1.63.1...v1.64.0](https://github.com/anthropics/anthropic-sdk-go/compare/v1.63.1...v1.64.0) + +### Features + +* **api:** additions to files and memory stores ([5c105da](https://github.com/anthropics/anthropic-sdk-go/commit/5c105daf4a37f0731775cbd7ec273d54b743ad40)) +* **api:** updates to skill, files, and user profiles ([a0061d6](https://github.com/anthropics/anthropic-sdk-go/commit/a0061d65983357dc4957eed0d3db767a565ba806)) + + +### Bug Fixes + +* **api:** remove unsupported mid_conv_system content block ([bced0f9](https://github.com/anthropics/anthropic-sdk-go/commit/bced0f9ac92c24943141bb3b12c93b3bd4f6416e)) +* **session-runner:** retry tool-result sends for at least the lease TTL ([#299](https://github.com/anthropics/anthropic-sdk-go/issues/299)) ([ebc9533](https://github.com/anthropics/anthropic-sdk-go/commit/ebc9533f6f2769d77621e9baabbcc32600b7b050)) +* **tool-runner:** forward the server-assigned container on follow-up requests ([#277](https://github.com/anthropics/anthropic-sdk-go/issues/277)) ([860620c](https://github.com/anthropics/anthropic-sdk-go/commit/860620c47a6a38bb6156321e29faa9fd4462c0b1)) +* **toolrunner:** don't yield the final message twice from All() ([#314](https://github.com/anthropics/anthropic-sdk-go/issues/314)) ([1e418f0](https://github.com/anthropics/anthropic-sdk-go/commit/1e418f091d043f68e252bfef91b1e1e37a95cb6d)) + + +### Chores + +* **internal:** remove leftover prism references ([a1d9eab](https://github.com/anthropics/anthropic-sdk-go/commit/a1d9eabf77975e8242f5b7623e202abae7547fe5)) + +## 1.63.1 (2026-08-13) + +Full Changelog: [v1.63.0...v1.63.1](https://github.com/anthropics/anthropic-sdk-go/compare/v1.63.0...v1.63.1) + +### Bug Fixes + +* **auth:** pin token exchange to the configured base URL and skip auth for other origins ([#258](https://github.com/anthropics/anthropic-sdk-go/issues/258)) ([6e4141c](https://github.com/anthropics/anthropic-sdk-go/commit/6e4141c68b5da647436ec07f76b69efd3cb87ed4)) +* **client:** apply stop_details from every message_delta when accumulating ([#253](https://github.com/anthropics/anthropic-sdk-go/issues/253)) ([c197a64](https://github.com/anthropics/anthropic-sdk-go/commit/c197a64a24952321446ca9353dfa5c6b4744d53f)) +* **client:** properly render maxLength and maxItems in generated schemas ([84a57f5](https://github.com/anthropics/anthropic-sdk-go/commit/84a57f524e1ff5a861a1a4a94f7f2b80fde7cd10)) +* **sessions:** post "(no output)" for empty text tool results instead of an empty text block ([#236](https://github.com/anthropics/anthropic-sdk-go/issues/236)) ([a588842](https://github.com/anthropics/anthropic-sdk-go/commit/a5888424590b0e02304fb70e4f35fdeeb9dceb93)) + + +### Chores + +* **ci:** run breaking-change detection as a ci.yml job on every push ([29aebdb](https://github.com/anthropics/anthropic-sdk-go/commit/29aebdb5be201df32a4a3a71352f1a2f69ed2768)) + + +### Documentation + +* **api:** clarify that user profile name is optional for resold profiles ([1039f95](https://github.com/anthropics/anthropic-sdk-go/commit/1039f956732621fb1d533d9ea277291e4dec4bee)) + +## 1.63.0 (2026-08-10) + +Full Changelog: [v1.62.0...v1.63.0](https://github.com/anthropics/anthropic-sdk-go/compare/v1.62.0...v1.63.0) + +### Features + +* **api:** add output_behavior to dream creation (create a new memory store or update the input store in place) ([ba999d5](https://github.com/anthropics/anthropic-sdk-go/commit/ba999d5edc6711e43e35ee2c2eb25c75fa478ebf)) + + +### Bug Fixes + +* **client:** add models ([a662a31](https://github.com/anthropics/anthropic-sdk-go/commit/a662a3168902606ef12dfc0bafbe68c04cbe21a1)) +* symlink-loop paths, special archive members, and 409 retry in the agent toolset and environment worker ([#226](https://github.com/anthropics/anthropic-sdk-go/issues/226)) ([82aa034](https://github.com/anthropics/anthropic-sdk-go/commit/82aa034b6cc238b2edbd88c451899f9f7bf1b02b)) +* **vertex:** preserve a user-supplied HTTP client by wrapping its transport with Google auth ([#242](https://github.com/anthropics/anthropic-sdk-go/issues/242)) ([8e85a8e](https://github.com/anthropics/anthropic-sdk-go/commit/8e85a8e7a522138521d7a0091b7bad9da131f4f2)) + +## 1.62.0 (2026-08-06) + +Full Changelog: [v1.61.0...v1.62.0](https://github.com/anthropics/anthropic-sdk-go/compare/v1.61.0...v1.62.0) + +### Features + +* **api:** add `mid-conversation-tool-changes-2026-07-01` beta ([f53c3d3](https://github.com/anthropics/anthropic-sdk-go/commit/f53c3d36b9bca3ea057b25b85be2ac62c0d18125)) +* **api:** add support for session budgets, advisor tool, pinned inference location and skills auto-loading from GitHub ([89c04c2](https://github.com/anthropics/anthropic-sdk-go/commit/89c04c2e2b10a5a7c3b6601a52c280c12b5fda41)) + + +### Bug Fixes + +* **client:** preserve wire-faithful JSON in accumulated streaming messages ([#197](https://github.com/anthropics/anthropic-sdk-go/issues/197)) ([9a01ac0](https://github.com/anthropics/anthropic-sdk-go/commit/9a01ac02821ec5e5b4d248121a8518eafb10389d)) +* **jsonl:** prevent silent truncation of large results, and don't panic on close ([#203](https://github.com/anthropics/anthropic-sdk-go/issues/203)) ([77dd33d](https://github.com/anthropics/anthropic-sdk-go/commit/77dd33d1ee59db8a02cab29c91f746671152c566)) +* **tools:** name tool refusals and a dead shell so they can be matched ([#213](https://github.com/anthropics/anthropic-sdk-go/issues/213)) ([da87d4d](https://github.com/anthropics/anthropic-sdk-go/commit/da87d4dc2782efe7f73a502a65375820aaed226e)) + + +### Chores + +* **api:** remove retired Claude Opus 4.1 models ([85fdf3b](https://github.com/anthropics/anthropic-sdk-go/commit/85fdf3b214891bcd0f14a08fdf4aca7b884e1132)) +* **docs:** small updates to descriptions ([487e6ea](https://github.com/anthropics/anthropic-sdk-go/commit/487e6ea4e4e0ca8faf20c999f127ac8a0578e9a6)) +* **docs:** updates to a few documentation strings ([03dc511](https://github.com/anthropics/anthropic-sdk-go/commit/03dc511df2319f61a2988a73bfce54262d0ced6d)) + +## 1.61.0 (2026-07-24) + +Full Changelog: [v1.60.0...v1.61.0](https://github.com/anthropics/anthropic-sdk-go/compare/v1.60.0...v1.61.0) + +### Features + +* **api:** add claude-opus-5 model ([bb7dc83](https://github.com/anthropics/anthropic-sdk-go/commit/bb7dc8379e9acf920d865c3a63eedfdbabf8f976)) +* **api:** add tool addition/removal blocks and tool_change events ([bb7dc83](https://github.com/anthropics/anthropic-sdk-go/commit/bb7dc8379e9acf920d865c3a63eedfdbabf8f976)) +* **api:** expand client-side fallback credit token types and add server-side fallbacks default option ([bb7dc83](https://github.com/anthropics/anthropic-sdk-go/commit/bb7dc8379e9acf920d865c3a63eedfdbabf8f976)) + +## 1.60.0 (2026-07-23) + +Full Changelog: [v1.59.0...v1.60.0](https://github.com/anthropics/anthropic-sdk-go/compare/v1.59.0...v1.60.0) + +### Features + +* **api:** add new stop reason 'model_context_window_exceeded' ([94caa5d](https://github.com/anthropics/anthropic-sdk-go/commit/94caa5dd2c259b4fac101f4ee44632157669fa23)) + + +### Bug Fixes + +* **apijson:** correct unmarshaling for param types ([#73](https://github.com/anthropics/anthropic-sdk-go/issues/73)) ([661be2e](https://github.com/anthropics/anthropic-sdk-go/commit/661be2e4d0e956585ca0d5474675d55dfc6a079a)) +* **client:** escape HTML in RawJSON overrides of nested properties ([3b163e2](https://github.com/anthropics/anthropic-sdk-go/commit/3b163e2c1453b127801abe67745d6109c6ee0b2c)) +* refer to the CLI as `ant` in auth error messages ([#194](https://github.com/anthropics/anthropic-sdk-go/issues/194)) ([d6508c7](https://github.com/anthropics/anthropic-sdk-go/commit/d6508c729ea131600b758bd140a49548c6d30946)) + +## 1.59.0 (2026-07-22) + +Full Changelog: [v1.58.1...v1.59.0](https://github.com/anthropics/anthropic-sdk-go/compare/v1.58.1...v1.59.0) + +### Features + +* **api:** add support for Managed Agents model effort, initial session events, and threads delta streaming ([abca19a](https://github.com/anthropics/anthropic-sdk-go/commit/abca19a766bd7dadcd3cdb12a97d62c4861b29dd)) + +## 1.58.1 (2026-07-21) + +Full Changelog: [v1.58.0...v1.58.1](https://github.com/anthropics/anthropic-sdk-go/compare/v1.58.0...v1.58.1) + +### Bug Fixes + +* **client:** copy all citation fields in ToParam conversions ([#191](https://github.com/anthropics/anthropic-sdk-go/issues/191)) ([26ac1f9](https://github.com/anthropics/anthropic-sdk-go/commit/26ac1f9c150b980b5df4c0b3c826ecde38f2affe)) +* **vertex:** default to the cloud-platform scope in WithGoogleAuth ([#190](https://github.com/anthropics/anthropic-sdk-go/issues/190)) ([7931e70](https://github.com/anthropics/anthropic-sdk-go/commit/7931e705abad1f245d7362cbc17ef281647b0bb9)) + + +### Chores + +* **api:** add support for new refusal category ([f77159c](https://github.com/anthropics/anthropic-sdk-go/commit/f77159cf64b7965f6c6be42ae2d25fb690c134c2)) +* **docs:** small updates ([576dc36](https://github.com/anthropics/anthropic-sdk-go/commit/576dc36ce84f1a842a728fcb11636342407b3f63)) +* **docs:** small updates ([f618082](https://github.com/anthropics/anthropic-sdk-go/commit/f6180825ac983aebfb0d0e09e3784145698d4cdc)) +* **internal:** codegen related update ([03fee5d](https://github.com/anthropics/anthropic-sdk-go/commit/03fee5d99295612792d12d60e5fca0a798e723d5)) + +## 1.58.0 (2026-07-16) + +Full Changelog: [v1.57.0...v1.58.0](https://github.com/anthropics/anthropic-sdk-go/compare/v1.57.0...v1.58.0) + +### Features + +* **api:** add support for MCP Tunnels ([3465b89](https://github.com/anthropics/anthropic-sdk-go/commit/3465b897f12872663b0f61c0c3edb277e2efbe44)) + +## 1.57.0 (2026-07-10) + +Full Changelog: [v1.56.0...v1.57.0](https://github.com/anthropics/anthropic-sdk-go/compare/v1.56.0...v1.57.0) + +### Features + +* **api:** add support for dreaming ([3736bf0](https://github.com/anthropics/anthropic-sdk-go/commit/3736bf0740c2b88d72f478df5fb7f13856f4beaa)) +* **tools:** gate session tool calls on evaluated_permission ([#151](https://github.com/anthropics/anthropic-sdk-go/issues/151)) ([4d85a6f](https://github.com/anthropics/anthropic-sdk-go/commit/4d85a6f2b0629b35630cf7560bc24d9d8cc8fa45)) + + +### Bug Fixes + +* **helpers:** distinguish canonical agent.message events from open previews ([#118](https://github.com/anthropics/anthropic-sdk-go/issues/118)) ([c49c17c](https://github.com/anthropics/anthropic-sdk-go/commit/c49c17c06ba2e646d5dd54c7614a7fa05becabd1)) + + +### Chores + +* **docs:** small updates to field descriptions ([61bc396](https://github.com/anthropics/anthropic-sdk-go/commit/61bc39690bc241eb4747626c0f0344e9b9e1b11f)) +* **docs:** update model example ([937a29c](https://github.com/anthropics/anthropic-sdk-go/commit/937a29cb229173f5009bda6a1b71889ed6a8103a)) +* **docs:** updates to descriptions and examples ([2c59f79](https://github.com/anthropics/anthropic-sdk-go/commit/2c59f7908e86a5dfc1f702120b56bbe2a07ae020)) + +## 1.56.0 (2026-07-02) + +Full Changelog: [v1.55.1...v1.56.0](https://github.com/anthropics/anthropic-sdk-go/compare/v1.55.1...v1.56.0) + +### Features + +* **api:** add agent-memory-2026-07-22 beta header ([5bcfda4](https://github.com/anthropics/anthropic-sdk-go/commit/5bcfda43d70d05ea124f6b6efa678807b8aba064)) + +## 1.55.1 (2026-07-01) + +Full Changelog: [v1.55.0...v1.55.1](https://github.com/anthropics/anthropic-sdk-go/compare/v1.55.0...v1.55.1) + +### Chores + +* **api:** remove some nonfunctional types from the SDKs ([9bd3d09](https://github.com/anthropics/anthropic-sdk-go/commit/9bd3d099c5c5cb69f7011376a63a882216d30fcb)) + +## 1.55.0 (2026-06-30) + +Full Changelog: [v1.54.0...v1.55.0](https://github.com/anthropics/anthropic-sdk-go/compare/v1.54.0...v1.55.0) + +### Features + +* **api:** add support for Managed Agents event delta streaming, agent overrides, reverse pagination, vault credential injection scoping, and agent and deployment webhook events ([021ef45](https://github.com/anthropics/anthropic-sdk-go/commit/021ef45adcc13691ce8e8f234b9b5ae387a565ae)) + +## 1.54.0 (2026-06-30) + +Full Changelog: [v1.53.0...v1.54.0](https://github.com/anthropics/anthropic-sdk-go/compare/v1.53.0...v1.54.0) + +### Features + +* **api:** add support for claude-sonnet-5 ([232cfe6](https://github.com/anthropics/anthropic-sdk-go/commit/232cfe6f8889dc30dd759a4027e95f5c9ece46d1)) + + +### Bug Fixes + +* **agenttoolset:** allow absolute paths that resolve inside workdir ([#93](https://github.com/anthropics/anthropic-sdk-go/issues/93)) ([3735258](https://github.com/anthropics/anthropic-sdk-go/commit/3735258e449804336781339ef25fa7008fc8717f)) + +## 1.53.0 (2026-06-29) + +Full Changelog: [v1.52.0...v1.53.0](https://github.com/anthropics/anthropic-sdk-go/compare/v1.52.0...v1.53.0) + +### Features + +* **api:** add support for 20260318 web fetch and support tools ([6396455](https://github.com/anthropics/anthropic-sdk-go/commit/6396455a220b3e37cc87ce44b6d1e615d6386c74)) + + +### Chores + +* **api:** accept user profile ID's when counting tokens ([d31ba27](https://github.com/anthropics/anthropic-sdk-go/commit/d31ba27f74d9a39dcaaabe8dc0d37b5b811c150c)) +* **docs:** updates to descriptions and example values ([cb00f34](https://github.com/anthropics/anthropic-sdk-go/commit/cb00f34a3c75e9f183d569321ff2de6da8efc29c)) + +## 1.52.0 (2026-06-24) + +Full Changelog: [v1.51.1...v1.52.0](https://github.com/anthropics/anthropic-sdk-go/compare/v1.51.1...v1.52.0) + +### Features + +* **client:** add support for system.message streaming events ([7bb296d](https://github.com/anthropics/anthropic-sdk-go/commit/7bb296db56de13140605495642cf72889f829ed8)) + + +### Chores + +* **api:** add support for new refusal category ([46f8625](https://github.com/anthropics/anthropic-sdk-go/commit/46f86259a94c1d43a21b3d44dd5eb40e9d4b3e13)) +* **api:** add support for sending User Profile ID in request headers ([5cab486](https://github.com/anthropics/anthropic-sdk-go/commit/5cab486af669c06349d03bb66f0214557422561c)) + +## 1.51.1 (2026-06-18) + +Full Changelog: [v1.51.0...v1.51.1](https://github.com/anthropics/anthropic-sdk-go/compare/v1.51.0...v1.51.1) + +### Bug Fixes + +* **helpers:** single source for x-stainless-helper, append semantics, and tag the fallback middleware ([#88](https://github.com/anthropics/anthropic-sdk-go/issues/88)) ([ebbdb7d](https://github.com/anthropics/anthropic-sdk-go/commit/ebbdb7dea37b15cdd055c53806a51e06422847fe)) + +## 1.51.0 (2026-06-18) + +Full Changelog: [v1.50.2...v1.51.0](https://github.com/anthropics/anthropic-sdk-go/compare/v1.50.2...v1.51.0) + +### Features + +* **api:** add support for new code_execution_20260120 tool ([f54a4a8](https://github.com/anthropics/anthropic-sdk-go/commit/f54a4a8e6f9c271b2b31e0cf504cdab8005f28c4)) + +## 1.50.2 (2026-06-15) + +Full Changelog: [v1.50.1...v1.50.2](https://github.com/anthropics/anthropic-sdk-go/compare/v1.50.1...v1.50.2) + +### Chores + +* **api:** remove retired models from API and SDKs ([11f5c82](https://github.com/anthropics/anthropic-sdk-go/commit/11f5c8239cb11351c5f42aac6bb12c0dc8fdccd2)) + +## 1.50.1 (2026-06-09) + +Full Changelog: [v1.50.0...v1.50.1](https://github.com/anthropics/anthropic-sdk-go/compare/v1.50.0...v1.50.1) + +### Bug Fixes + +* **api:** add `frontier_llm` refusal category ([9ebbaf7](https://github.com/anthropics/anthropic-sdk-go/commit/9ebbaf76a334618a062f787bd4937e3370cb117c)) + +## 1.50.0 (2026-06-09) + +Full Changelog: [v1.49.0...v1.50.0](https://github.com/anthropics/anthropic-sdk-go/compare/v1.49.0...v1.50.0) + +### Features + +* **api:** add support for Managed Agents deployments and environment variable credentials ([f72e1d8](https://github.com/anthropics/anthropic-sdk-go/commit/f72e1d84cf3b6d2319c083d8ae814dcae236f217)) + +## 1.49.0 (2026-06-09) + +Full Changelog: [v1.48.0...v1.49.0](https://github.com/anthropics/anthropic-sdk-go/compare/v1.48.0...v1.49.0) + +### Features + +* **api:** add support for claude-mythos-5 and claude-fable-5, with support for server-side fallbacks on refusal ([782f223](https://github.com/anthropics/anthropic-sdk-go/commit/782f2239803f6c0b65a9b23a7efe7e12059ac8a0)) +* **client:** adds client-side fallbacks middleware for API providers that do not support server-side fallbacks ([782f223](https://github.com/anthropics/anthropic-sdk-go/commit/782f2239803f6c0b65a9b23a7efe7e12059ac8a0)) + + +### Bug Fixes + +* 3p middleware ordering ([#38](https://github.com/anthropics/anthropic-sdk-go/issues/38)) ([8f47086](https://github.com/anthropics/anthropic-sdk-go/commit/8f47086cb6094c7c6ba06a7b9d94d56ead5ba295)) + +## 1.48.0 (2026-06-06) + +Full Changelog: [v1.47.0...v1.48.0](https://github.com/anthropics/anthropic-sdk-go/compare/v1.47.0...v1.48.0) + +### Features + +* **api:** small updates to Managed Agents types ([3ebeea5](https://github.com/anthropics/anthropic-sdk-go/commit/3ebeea5856ea9a024ff77d22847f0109da2dd334)) + +## 1.47.0 (2026-06-05) + +Full Changelog: [v1.46.0...v1.47.0](https://github.com/anthropics/anthropic-sdk-go/compare/v1.46.0...v1.47.0) + +### Features + +* **api:** mark Claude Opus 4.1 as deprecated ([64b20dc](https://github.com/anthropics/anthropic-sdk-go/commit/64b20dc87c2062ece15e2a46904eac00e6eae737)) +* require Go 1.24 ([#11](https://github.com/anthropics/anthropic-sdk-go/issues/11)) ([00fae19](https://github.com/anthropics/anthropic-sdk-go/commit/00fae190db05135e3de11acd30c5ed30f2f94811)) + + +### Bug Fixes + +* **streaming:** accumulate content block events by index ([#6](https://github.com/anthropics/anthropic-sdk-go/issues/6)) ([2161a38](https://github.com/anthropics/anthropic-sdk-go/commit/2161a381e70df6e5a00c00f841711151ab170ef9)) +* **streaming:** carry encrypted_content through beta compaction accumulator ([#875](https://github.com/anthropics/anthropic-sdk-go/issues/875)) ([13fa611](https://github.com/anthropics/anthropic-sdk-go/commit/13fa61165159653ee1f3cc63a4df2d1c5dab7970)) +* **streaming:** carry stop_details and usage fields through beta message_delta ([#879](https://github.com/anthropics/anthropic-sdk-go/issues/879)) ([d432c9f](https://github.com/anthropics/anthropic-sdk-go/commit/d432c9fb538442ccce72bfbee4f4d69d18d1acf2)) +* **streaming:** carry stop_details and usage fields through message_delta ([#877](https://github.com/anthropics/anthropic-sdk-go/issues/877)) ([e2fcc35](https://github.com/anthropics/anthropic-sdk-go/commit/e2fcc3583f9a9fa37ce5b1a1fc5f55391c2e9199)) +* support invopop/jsonschema v0.14.0 (switch to pb33f/ordered-map) ([#10](https://github.com/anthropics/anthropic-sdk-go/issues/10)) ([af018a7](https://github.com/anthropics/anthropic-sdk-go/commit/af018a7c71e0edc0c84561f0fe2a68e81627b38c)) + + +### Chores + +* **internal:** fix artifact url ([fd4cde3](https://github.com/anthropics/anthropic-sdk-go/commit/fd4cde3e00290d169e6435ae098dd73f57ac8991)) +* **internal:** fix branch names ([e1730cd](https://github.com/anthropics/anthropic-sdk-go/commit/e1730cd3865db09b5be7e5a32d9c57a94ba6e27f)) +* **internal:** update private repo name ([29f7468](https://github.com/anthropics/anthropic-sdk-go/commit/29f7468ec0d2bda6fe9c84e00be04e3d7ad34d25)) + + +### Documentation + +* point security reports to Anthropic's HackerOne program ([#9](https://github.com/anthropics/anthropic-sdk-go/issues/9)) ([c143385](https://github.com/anthropics/anthropic-sdk-go/commit/c143385a80838daaa3d416ce553c23f6a18f7657)) + +## 1.46.0 (2026-05-28) + +Full Changelog: [v1.45.0...v1.46.0](https://github.com/anthropics/anthropic-sdk-go/compare/v1.45.0...v1.46.0) + +### Features + +* **api:** Add support for claude-opus-4-8, mid-conversation system blocks, and usage.output_tokens_details ([4cd860b](https://github.com/anthropics/anthropic-sdk-go/commit/4cd860b8bd5365709f7f86466f449797a5f01875)) +* support custom file size caps ([#876](https://github.com/anthropics/anthropic-sdk-go/issues/876)) ([99634e8](https://github.com/anthropics/anthropic-sdk-go/commit/99634e85815be2215a8beb05f2deeec895133b3b)) + + +### Chores + +* **examples:** rename managed-agents private-sandbox-worker to self-hosted-sandbox-worker ([#873](https://github.com/anthropics/anthropic-sdk-go/issues/873)) ([07d3e46](https://github.com/anthropics/anthropic-sdk-go/commit/07d3e461f094d40a1bcf25fa8cefee7a90835193)) + + +### Documentation + +* replace literal newlines ([cbb7ea5](https://github.com/anthropics/anthropic-sdk-go/commit/cbb7ea55b131f492753ce9fdcfc73df2847daafd)) + +## 1.45.0 (2026-05-21) + +Full Changelog: [v1.44.1...v1.45.0](https://github.com/anthropics/anthropic-sdk-go/compare/v1.44.1...v1.45.0) + +### Features + +* **api:** Add support for thinking-token-count beta for estimated tokens in thinking block deltas when streaming ([dedeb6d](https://github.com/anthropics/anthropic-sdk-go/commit/dedeb6d263a651d63c95bd360befbd53dd26ec12)) + +## 1.44.1 (2026-05-19) + +Full Changelog: [v1.44.0...v1.44.1](https://github.com/anthropics/anthropic-sdk-go/compare/v1.44.0...v1.44.1) + +### Bug Fixes + +* **runner:** skip tool calls SessionToolRunner does not own ([93afc65](https://github.com/anthropics/anthropic-sdk-go/commit/93afc65f2f1b811d760f2e5149e13dd5eb328f79)) + +## 1.44.0 (2026-05-19) + +Full Changelog: [v1.43.0...v1.44.0](https://github.com/anthropics/anthropic-sdk-go/compare/v1.43.0...v1.44.0) + +### Features + +* **client:** Add support for self-hosted sandboxes in CMA with sandbox helpers ([34354c4](https://github.com/anthropics/anthropic-sdk-go/commit/34354c43f329852a88682bb6665a1453754d61be)) + +## 1.43.0 (2026-05-13) + +Full Changelog: [v1.42.0...v1.43.0](https://github.com/anthropics/anthropic-sdk-go/compare/v1.42.0...v1.43.0) + +### Features + +* **api:** Add BetaManagedAgentsSearchResultBlock types ([498fafc](https://github.com/anthropics/anthropic-sdk-go/commit/498fafcadd46be3a53e24ca2e7c40d00da6361bd)) +* **api:** Add support for cache diagnostics beta ([eac032f](https://github.com/anthropics/anthropic-sdk-go/commit/eac032f440e19fe9407d856dc4494029c606cd3d)) +* **client:** add compatibility aliases for old type names ([38e1f89](https://github.com/anthropics/anthropic-sdk-go/commit/38e1f89eeffeb40295a5796c97d9966ab1a8703b)) +* **client:** add compatibility aliases for old type names ([a98b0fb](https://github.com/anthropics/anthropic-sdk-go/commit/a98b0fb44693ee6c4bcd7575414b1cab0fc114c7)) +* **client:** optimize json encoder for internal types ([f379c42](https://github.com/anthropics/anthropic-sdk-go/commit/f379c4255c6485a02afb8136d84f1cf995794a08)) + + +### Bug Fixes + +* **structured outputs:** allowlist enum, const, pattern, allOf in transformSchema ([#823](https://github.com/anthropics/anthropic-sdk-go/issues/823)) ([d368786](https://github.com/anthropics/anthropic-sdk-go/commit/d3687868eb9c40427c731b12e9291ddeeb74f557)) + + +### Chores + +* **api:** spec updates ([502b9f1](https://github.com/anthropics/anthropic-sdk-go/commit/502b9f13f72a691c3b440c66d964a25caf2db8e1)) +* fix standard webhooks version ([#842](https://github.com/anthropics/anthropic-sdk-go/issues/842)) ([1fdda46](https://github.com/anthropics/anthropic-sdk-go/commit/1fdda46d63004bfec8c977319554cb609a0b4041)) +* **internal:** simplify release-please config ([69da3d6](https://github.com/anthropics/anthropic-sdk-go/commit/69da3d60e46540256c75fc2a0d1b1814ed608dfc)) + +## 1.42.0 (2026-05-11) + +Full Changelog: [v1.41.0...v1.42.0](https://github.com/anthropics/anthropic-sdk-go/compare/v1.41.0...v1.42.0) + +### Features + +* **aws:** Add AWS client for Claude Platform on AWS ([596baf4](https://github.com/anthropics/anthropic-sdk-go/commit/596baf4d3811bc48d24f3e298573581c861384b1)) + + +### Bug Fixes + +* **examples:** update examples dependencies ([e832b79](https://github.com/anthropics/anthropic-sdk-go/commit/e832b79299ddee8c48cc8f77c83203f58e17b9ec)) +* **go:** avoid panic when http.DefaultTransport is wrapped ([6b75bef](https://github.com/anthropics/anthropic-sdk-go/commit/6b75bef5a2cd15a969b5d787498e550f6f039719)) + + +### Chores + +* **client:** update dependency checksums ([64c1d95](https://github.com/anthropics/anthropic-sdk-go/commit/64c1d9502775801539ea492f29784a89535226bd)) +* go mod tidy ([#816](https://github.com/anthropics/anthropic-sdk-go/issues/816)) ([09b5f9c](https://github.com/anthropics/anthropic-sdk-go/commit/09b5f9cc4965ed3ca5b458996db3c030d66482c4)) +* **internal:** codegen related update ([6e83495](https://github.com/anthropics/anthropic-sdk-go/commit/6e83495da8dfb2efb905213204627483b4afc3e2)) +* **internal:** codegen related update ([34d1379](https://github.com/anthropics/anthropic-sdk-go/commit/34d1379207570fd26f7a262a960c424adf8d265d)) +* **internal:** codegen related update ([c068475](https://github.com/anthropics/anthropic-sdk-go/commit/c068475a5c67c7b0d544195b4a62187c4e35c578)) +* redact api-key headers in debug logs ([46a074f](https://github.com/anthropics/anthropic-sdk-go/commit/46a074f588c30c2a88e6f46093be606b37dd3fef)) +* redact api-key headers in debug logs ([1fe2ebb](https://github.com/anthropics/anthropic-sdk-go/commit/1fe2ebbb5d1f458f7013aec5c61e31ae2b52e619)) + +## 1.41.0 (2026-05-06) + +Full Changelog: [v1.40.0...v1.41.0](https://github.com/anthropics/anthropic-sdk-go/compare/v1.40.0...v1.41.0) + +### Features + +* **api:** add support for Managed Agents multiagents and outcomes, webhooks, vault validation ([33762b0](https://github.com/anthropics/anthropic-sdk-go/commit/33762b055b2ef20d09a3764bb69d183fcf283b18)) +* **mcp:** add mcp tool helpers ([#752](https://github.com/anthropics/anthropic-sdk-go/issues/752)) ([4edf9f5](https://github.com/anthropics/anthropic-sdk-go/commit/4edf9f5cbc10f0acc7e11ae6b248c20be606ac63)) + + +### Bug Fixes + +* **api:** Adjust webhook configuration ([8b2f194](https://github.com/anthropics/anthropic-sdk-go/commit/8b2f194315cc5bc9d723ea682e94a2a216ed57cd)) + +## 1.40.0 (2026-05-05) + +Full Changelog: [v1.39.0...v1.40.0](https://github.com/anthropics/anthropic-sdk-go/compare/v1.39.0...v1.40.0) + +### Features + +* **client:** allow targeting a workspace for OIDC federation token exchange ([6bf66ac](https://github.com/anthropics/anthropic-sdk-go/commit/6bf66ac19fa598800549ea188e849d0d45f632ea)) + +## 1.39.0 (2026-05-04) + +Full Changelog: [v1.38.0...v1.39.0](https://github.com/anthropics/anthropic-sdk-go/compare/v1.38.0...v1.39.0) + +### Features + +* **api:** improve Managed Agents APIs ([eadf509](https://github.com/anthropics/anthropic-sdk-go/commit/eadf509d8ea79d3f0db7cbdbf3ade6f24aaeb76f)) +* **client:** add Workload Identity Federation, interactive OAuth, and auth profiles ([0f0cc01](https://github.com/anthropics/anthropic-sdk-go/commit/0f0cc0191f3bc059f22939644a0584662c469305)) +* **go:** add default http client with timeout ([b81c287](https://github.com/anthropics/anthropic-sdk-go/commit/b81c28758ee76db006216b771ff3803adf4cbefb)) +* support setting headers via env ([641015d](https://github.com/anthropics/anthropic-sdk-go/commit/641015da9ea17c4ef2696857d6b4eb4cdb4f854e)) + + +### Bug Fixes + +* **client:** add 10 min timeout ([#770](https://github.com/anthropics/anthropic-sdk-go/issues/770)) ([917fe19](https://github.com/anthropics/anthropic-sdk-go/commit/917fe19c2591586d9c14fd5916bb95f713ab0c8f)) + + +### Chores + +* avoid embedding reflect.Type for dead code elimination ([11168b4](https://github.com/anthropics/anthropic-sdk-go/commit/11168b403a3b3ab2d7b3edc023faf214d9eededd)) + +## 1.38.0 (2026-04-23) + +Full Changelog: [v1.37.0...v1.38.0](https://github.com/anthropics/anthropic-sdk-go/compare/v1.37.0...v1.38.0) + +### Features + +* add Type() method to API errors for error kind identification ([#676](https://github.com/anthropics/anthropic-sdk-go/issues/676)) ([0db1712](https://github.com/anthropics/anthropic-sdk-go/commit/0db1712b237930416461c2411d263e6d1150d957)) +* **api:** CMA Memory public beta ([180e00c](https://github.com/anthropics/anthropic-sdk-go/commit/180e00cdc4863a6a64986e03fed9eb4a04117f40)) +* structured outputs via Schema any with auto-parse ([#759](https://github.com/anthropics/anthropic-sdk-go/issues/759)) ([46073d8](https://github.com/anthropics/anthropic-sdk-go/commit/46073d8f489a88fdf5ebf33163e4f0d364759eae)) + + +### Bug Fixes + +* **api:** fix errors in api spec ([e47c178](https://github.com/anthropics/anthropic-sdk-go/commit/e47c178b3ee1b5c47834239635b5a3abdff9a432)) +* **api:** restore missing features ([0fc6fac](https://github.com/anthropics/anthropic-sdk-go/commit/0fc6fac141980cfce023ce2d0b30175980741db0)) + + +### Chores + +* **internal:** more robust bootstrap script ([5bde204](https://github.com/anthropics/anthropic-sdk-go/commit/5bde204d267187622a5228330235c9c048abeae1)) +* **tests:** bump steady to v0.22.1 ([4578c15](https://github.com/anthropics/anthropic-sdk-go/commit/4578c15e9a2f6ed05a05acfa608083c3a893d6dd)) + ## 1.37.0 (2026-04-16) Full Changelog: [v1.36.0...v1.37.0](https://github.com/anthropics/anthropic-sdk-go/compare/v1.36.0...v1.37.0) diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/README.md b/vendor/github.com/anthropics/anthropic-sdk-go/README.md index 3d209fb8b..ef3dc374c 100644 --- a/vendor/github.com/anthropics/anthropic-sdk-go/README.md +++ b/vendor/github.com/anthropics/anthropic-sdk-go/README.md @@ -29,7 +29,7 @@ Or explicitly add the dependency: ```sh -go get -u 'github.com/anthropics/anthropic-sdk-go@v1.37.0' +go get -u 'github.com/anthropics/anthropic-sdk-go@v1.67.0' ``` @@ -67,7 +67,7 @@ func main() { ## Requirements -Go 1.22+ +Go 1.24+ ## Contributing diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/SECURITY.md b/vendor/github.com/anthropics/anthropic-sdk-go/SECURITY.md index 49f2cc770..95b204aa3 100644 --- a/vendor/github.com/anthropics/anthropic-sdk-go/SECURITY.md +++ b/vendor/github.com/anthropics/anthropic-sdk-go/SECURITY.md @@ -1,27 +1,15 @@ # Security Policy -## Reporting Security Issues - -This SDK is generated by [Stainless Software Inc](http://stainless.com). Stainless takes security seriously, and encourages you to report any security vulnerability promptly so that appropriate action can be taken. - -To report a security issue, please contact the Stainless team at security@stainless.com. - -## Responsible Disclosure - -We appreciate the efforts of security researchers and individuals who help us maintain the security of -SDKs we generate. If you believe you have found a security vulnerability, please adhere to responsible -disclosure practices by allowing us a reasonable amount of time to investigate and address the issue -before making any information public. +Thank you for helping us keep the SDKs and systems they interact with secure. -## Reporting Non-SDK Related Security Issues +## Reporting Security Issues -If you encounter security issues that are not directly related to SDKs but pertain to the services -or products provided by Anthropic, please follow the respective company's security reporting guidelines. +This SDK is maintained by [Anthropic](https://www.anthropic.com/). -### Anthropic Terms and Policies +The security of our systems and user data is Anthropic’s top priority. We appreciate the work of security researchers acting in good faith in identifying and reporting potential vulnerabilities. -Please contact support@anthropic.com for any questions or concerns regarding the security of our services. +Our security program is managed on HackerOne and we ask that any validated vulnerability in this functionality be reported through their [submission form](https://hackerone.com/4f1f16ba-10d3-4d09-9ecc-c721aad90f24/embedded_submissions/new). ---- +## Anthropic Bug Bounty -Thank you for helping us keep the SDKs and systems they interact with secure. +Our Bug Bounty Program Guidelines are defined on our [HackerOne program page](https://hackerone.com/anthropic). diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/aliases.go b/vendor/github.com/anthropics/anthropic-sdk-go/aliases.go index 379d75f4c..dc5d1dac2 100644 --- a/vendor/github.com/anthropics/anthropic-sdk-go/aliases.go +++ b/vendor/github.com/anthropics/anthropic-sdk-go/aliases.go @@ -100,3 +100,7 @@ const WebSearchToolResultErrorErrorCodeMaxUsesExceeded = WebSearchToolResultErro const WebSearchToolResultErrorErrorCodeTooManyRequests = WebSearchToolResultErrorCodeTooManyRequests const WebSearchToolResultErrorErrorCodeQueryTooLong = WebSearchToolResultErrorCodeQueryTooLong const WebSearchToolResultErrorErrorCodeRequestTooLarge = WebSearchToolResultErrorCodeRequestTooLarge + +// Deprecated: use [BetaCurrencyUSD]. Kept so code written before the USD +// initialism casing continues to compile. +const BetaCurrencyUsd = BetaCurrencyUSD diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/api.md b/vendor/github.com/anthropics/anthropic-sdk-go/api.md index 8b10083a1..5a9d25530 100644 --- a/vendor/github.com/anthropics/anthropic-sdk-go/api.md +++ b/vendor/github.com/anthropics/anthropic-sdk-go/api.md @@ -28,6 +28,46 @@ Params Types: - anthropic.BashCodeExecutionToolResultBlockParam - anthropic.BashCodeExecutionToolResultErrorCode - anthropic.BashCodeExecutionToolResultErrorParam +- anthropic.BrowserCloseTabConfigParam +- anthropic.BrowserDoubleClickConfigParam +- anthropic.BrowserFileUploadConfigParam +- anthropic.BrowserFindConfigParam +- anthropic.BrowserFormInputConfigParam +- anthropic.BrowserGetPageTextConfigParam +- anthropic.BrowserHoldKeyConfigParam +- anthropic.BrowserHoverConfigParam +- anthropic.BrowserJavascriptExecConfigParam +- anthropic.BrowserKeyConfigParam +- anthropic.BrowserLeftClickConfigParam +- anthropic.BrowserLeftClickDragConfigParam +- anthropic.BrowserLeftMouseDownConfigParam +- anthropic.BrowserLeftMouseUpConfigParam +- anthropic.BrowserListTabsConfigParam +- anthropic.BrowserMiddleClickConfigParam +- anthropic.BrowserMouseMoveConfigParam +- anthropic.BrowserNavigateConfigParam +- anthropic.BrowserNewTabConfigParam +- anthropic.BrowserReadConsoleConfigParam +- anthropic.BrowserReadNetworkConfigParam +- anthropic.BrowserReadPageConfigParam +- anthropic.BrowserRightClickConfigParam +- anthropic.BrowserScreenshotConfigParam +- anthropic.BrowserScrollConfigParam +- anthropic.BrowserScrollToConfigParam +- anthropic.BrowserStateBlockParam +- anthropic.BrowserStateChangeUnionParam +- anthropic.BrowserStateChangeDownloadCompletedParam +- anthropic.BrowserStateChangeDownloadFailedParam +- anthropic.BrowserStateChangeDownloadStartedParam +- anthropic.BrowserStateChangeTabOpenedParam +- anthropic.BrowserStateTabEntryParam +- anthropic.BrowserSwitchTabConfigParam +- anthropic.BrowserToolset20260801Param +- anthropic.BrowserToolsetConfigsParam +- anthropic.BrowserTripleClickConfigParam +- anthropic.BrowserTypeConfigParam +- anthropic.BrowserWaitConfigParam +- anthropic.BrowserZoomConfigParam - anthropic.CacheControlEphemeralParam - anthropic.CitationCharLocationParam - anthropic.CitationContentBlockLocationParam @@ -40,10 +80,31 @@ Params Types: - anthropic.CodeExecutionTool20250522Param - anthropic.CodeExecutionTool20250825Param - anthropic.CodeExecutionTool20260120Param +- anthropic.CodeExecutionTool20260521Param - anthropic.CodeExecutionToolResultBlockParam - anthropic.CodeExecutionToolResultBlockParamContentUnion - anthropic.CodeExecutionToolResultErrorCode - anthropic.CodeExecutionToolResultErrorParam +- anthropic.ComputerCursorPositionConfigParam +- anthropic.ComputerDoubleClickConfigParam +- anthropic.ComputerHoldKeyConfigParam +- anthropic.ComputerKeyConfigParam +- anthropic.ComputerLeftClickConfigParam +- anthropic.ComputerLeftClickDragConfigParam +- anthropic.ComputerLeftMouseDownConfigParam +- anthropic.ComputerLeftMouseUpConfigParam +- anthropic.ComputerMiddleClickConfigParam +- anthropic.ComputerMouseMoveConfigParam +- anthropic.ComputerRightClickConfigParam +- anthropic.ComputerScreenshotConfigParam +- anthropic.ComputerScrollConfigParam +- anthropic.ComputerToolset20260801Param +- anthropic.ComputerToolsetConfigsParam +- anthropic.ComputerTripleClickConfigParam +- anthropic.ComputerTypeConfigParam +- anthropic.ComputerWaitConfigParam +- anthropic.ComputerZoomConfigParam +- anthropic.ContainerParams - anthropic.ContainerUploadBlockParam - anthropic.ContentBlockParamUnion - anthropic.ContentBlockSourceParam @@ -51,10 +112,14 @@ Params Types: - anthropic.DirectCallerParam - anthropic.DocumentBlockParam - anthropic.EncryptedCodeExecutionResultBlockParam +- anthropic.FileDocumentSourceParam +- anthropic.FileImageSourceParam - anthropic.ImageBlockParam +- anthropic.ImageTransformationsParam - anthropic.JSONOutputFormatParam - anthropic.MemoryTool20250818Param - anthropic.MessageCountTokensToolUnionParam +- anthropic.MessageCreateParamsContainerUnion - anthropic.MessageParam - anthropic.MetadataParam - anthropic.Model @@ -65,6 +130,7 @@ Params Types: - anthropic.ServerToolCallerParam - anthropic.ServerToolCaller20260120Param - anthropic.ServerToolUseBlockParam +- anthropic.SkillParams - anthropic.TextBlockParam - anthropic.TextCitationParamUnion - anthropic.TextEditorCodeExecutionCreateResultBlockParam @@ -105,12 +171,14 @@ Params Types: - anthropic.WebFetchTool20250910Param - anthropic.WebFetchTool20260209Param - anthropic.WebFetchTool20260309Param +- anthropic.WebFetchTool20260318Param - anthropic.WebFetchToolResultBlockParam - anthropic.WebFetchToolResultErrorBlockParam - anthropic.WebFetchToolResultErrorCode - anthropic.WebSearchResultBlockParam - anthropic.WebSearchTool20250305Param - anthropic.WebSearchTool20260209Param +- anthropic.WebSearchTool20260318Param - anthropic.WebSearchToolRequestErrorParam - anthropic.WebSearchToolResultBlockParam - anthropic.WebSearchToolResultBlockParamContentUnion @@ -139,6 +207,7 @@ Response Types: - anthropic.CodeExecutionToolResultError - anthropic.CodeExecutionToolResultErrorCode - anthropic.Container +- anthropic.ContainerSkill - anthropic.ContainerUploadBlock - anthropic.ContentBlockUnion - anthropic.DirectCaller @@ -149,6 +218,7 @@ Response Types: - anthropic.MessageDeltaUsage - anthropic.MessageTokensCount - anthropic.Model +- anthropic.OutputTokensDetails - anthropic.PlainTextSource - anthropic.RawContentBlockDeltaUnion - anthropic.ContentBlockDeltaEvent @@ -196,8 +266,8 @@ Response Types: Methods: -- client.Messages.New(ctx context.Context, body anthropic.MessageNewParams) (\*anthropic.Message, error) -- client.Messages.CountTokens(ctx context.Context, body anthropic.MessageCountTokensParams) (\*anthropic.MessageTokensCount, error) +- client.Messages.New(ctx context.Context, params anthropic.MessageNewParams) (\*anthropic.Message, error) +- client.Messages.CountTokens(ctx context.Context, params anthropic.MessageCountTokensParams) (\*anthropic.MessageTokensCount, error) ## Batches @@ -215,7 +285,7 @@ Response Types: Methods: -- client.Messages.Batches.New(ctx context.Context, body anthropic.MessageBatchNewParams) (\*anthropic.MessageBatch, error) +- client.Messages.Batches.New(ctx context.Context, params anthropic.MessageBatchNewParams) (\*anthropic.MessageBatch, error) - client.Messages.Batches.Get(ctx context.Context, messageBatchID string) (\*anthropic.MessageBatch, error) - client.Messages.Batches.List(ctx context.Context, query anthropic.MessageBatchListParams) (\*pagination.Page[anthropic.MessageBatch], error) - client.Messages.Batches.Delete(ctx context.Context, messageBatchID string) (\*anthropic.DeletedMessageBatch, error) @@ -239,21 +309,69 @@ Methods: - client.Models.Get(ctx context.Context, modelID string, query anthropic.ModelGetParams) (\*anthropic.ModelInfo, error) - client.Models.List(ctx context.Context, params anthropic.ModelListParams) (\*pagination.Page[anthropic.ModelInfo], error) +# Files + +Response Types: + +- anthropic.DeletedFile +- anthropic.FileMetadata + +Methods: + +- client.Files.List(ctx context.Context, query anthropic.FileListParams) (\*pagination.PageCursor[anthropic.FileMetadata], error) +- client.Files.Delete(ctx context.Context, fileID string) (\*anthropic.DeletedFile, error) +- client.Files.Download(ctx context.Context, fileID string) (\*http.Response, error) +- client.Files.GetMetadata(ctx context.Context, fileID string) (\*anthropic.FileMetadata, error) +- client.Files.Upload(ctx context.Context, body anthropic.FileUploadParams) (\*anthropic.FileMetadata, error) + +# Skills + +Response Types: + +- anthropic.DeletedSkill +- anthropic.Skill +- anthropic.SkillSource + +Methods: + +- client.Skills.New(ctx context.Context, body anthropic.SkillNewParams) (\*anthropic.Skill, error) +- client.Skills.Get(ctx context.Context, skillID string) (\*anthropic.Skill, error) +- client.Skills.List(ctx context.Context, query anthropic.SkillListParams) (\*pagination.PageCursor[anthropic.Skill], error) +- client.Skills.Delete(ctx context.Context, skillID string) (\*anthropic.DeletedSkill, error) + +## Versions + +Response Types: + +- anthropic.DeletedSkillVersion +- anthropic.SkillVersion + +Methods: + +- client.Skills.Versions.New(ctx context.Context, skillID string, body anthropic.SkillVersionNewParams) (\*anthropic.SkillVersion, error) +- client.Skills.Versions.Get(ctx context.Context, version string, query anthropic.SkillVersionGetParams) (\*anthropic.SkillVersion, error) +- client.Skills.Versions.List(ctx context.Context, skillID string, query anthropic.SkillVersionListParams) (\*pagination.PageCursor[anthropic.SkillVersion], error) +- client.Skills.Versions.Delete(ctx context.Context, version string, body anthropic.SkillVersionDeleteParams) (\*anthropic.DeletedSkillVersion, error) + # Beta Params Types: - anthropic.AnthropicBeta +- anthropic.BetaCurrency +- anthropic.BetaMonetaryAmountParam Response Types: - anthropic.BetaAPIError - anthropic.BetaAuthenticationError - anthropic.BetaBillingError +- anthropic.BetaCurrency - anthropic.BetaErrorUnion - anthropic.BetaErrorResponse - anthropic.BetaGatewayTimeoutError - anthropic.BetaInvalidRequestError +- anthropic.BetaMonetaryAmount - anthropic.BetaNotFoundError - anthropic.BetaOverloadedError - anthropic.BetaPermissionError @@ -292,6 +410,46 @@ Params Types: - anthropic.BetaBashCodeExecutionResultBlockParam - anthropic.BetaBashCodeExecutionToolResultBlockParam - anthropic.BetaBashCodeExecutionToolResultErrorParam +- anthropic.BetaBrowserCloseTabConfigParam +- anthropic.BetaBrowserDoubleClickConfigParam +- anthropic.BetaBrowserFileUploadConfigParam +- anthropic.BetaBrowserFindConfigParam +- anthropic.BetaBrowserFormInputConfigParam +- anthropic.BetaBrowserGetPageTextConfigParam +- anthropic.BetaBrowserHoldKeyConfigParam +- anthropic.BetaBrowserHoverConfigParam +- anthropic.BetaBrowserJavascriptExecConfigParam +- anthropic.BetaBrowserKeyConfigParam +- anthropic.BetaBrowserLeftClickConfigParam +- anthropic.BetaBrowserLeftClickDragConfigParam +- anthropic.BetaBrowserLeftMouseDownConfigParam +- anthropic.BetaBrowserLeftMouseUpConfigParam +- anthropic.BetaBrowserListTabsConfigParam +- anthropic.BetaBrowserMiddleClickConfigParam +- anthropic.BetaBrowserMouseMoveConfigParam +- anthropic.BetaBrowserNavigateConfigParam +- anthropic.BetaBrowserNewTabConfigParam +- anthropic.BetaBrowserReadConsoleConfigParam +- anthropic.BetaBrowserReadNetworkConfigParam +- anthropic.BetaBrowserReadPageConfigParam +- anthropic.BetaBrowserRightClickConfigParam +- anthropic.BetaBrowserScreenshotConfigParam +- anthropic.BetaBrowserScrollConfigParam +- anthropic.BetaBrowserScrollToConfigParam +- anthropic.BetaBrowserStateBlockParam +- anthropic.BetaBrowserStateChangeUnionParam +- anthropic.BetaBrowserStateChangeDownloadCompletedParam +- anthropic.BetaBrowserStateChangeDownloadFailedParam +- anthropic.BetaBrowserStateChangeDownloadStartedParam +- anthropic.BetaBrowserStateChangeTabOpenedParam +- anthropic.BetaBrowserStateTabEntryParam +- anthropic.BetaBrowserSwitchTabConfigParam +- anthropic.BetaBrowserToolset20260801Param +- anthropic.BetaBrowserToolsetConfigsParam +- anthropic.BetaBrowserTripleClickConfigParam +- anthropic.BetaBrowserTypeConfigParam +- anthropic.BetaBrowserWaitConfigParam +- anthropic.BetaBrowserZoomConfigParam - anthropic.BetaCacheControlEphemeralParam - anthropic.BetaCitationCharLocationParam - anthropic.BetaCitationContentBlockLocationParam @@ -306,23 +464,50 @@ Params Types: - anthropic.BetaCodeExecutionTool20250522Param - anthropic.BetaCodeExecutionTool20250825Param - anthropic.BetaCodeExecutionTool20260120Param +- anthropic.BetaCodeExecutionTool20260521Param - anthropic.BetaCodeExecutionToolResultBlockParam - anthropic.BetaCodeExecutionToolResultBlockParamContentUnion - anthropic.BetaCodeExecutionToolResultErrorCode - anthropic.BetaCodeExecutionToolResultErrorParam - anthropic.BetaCompact20260112EditParam - anthropic.BetaCompactionBlockParam +- anthropic.BetaComputerCursorPositionConfigParam +- anthropic.BetaComputerDoubleClickConfigParam +- anthropic.BetaComputerHoldKeyConfigParam +- anthropic.BetaComputerKeyConfigParam +- anthropic.BetaComputerLeftClickConfigParam +- anthropic.BetaComputerLeftClickDragConfigParam +- anthropic.BetaComputerLeftMouseDownConfigParam +- anthropic.BetaComputerLeftMouseUpConfigParam +- anthropic.BetaComputerMiddleClickConfigParam +- anthropic.BetaComputerMouseMoveConfigParam +- anthropic.BetaComputerRightClickConfigParam +- anthropic.BetaComputerScreenshotConfigParam +- anthropic.BetaComputerScrollConfigParam +- anthropic.BetaComputerToolset20260801Param +- anthropic.BetaComputerToolsetConfigsParam +- anthropic.BetaComputerTripleClickConfigParam +- anthropic.BetaComputerTypeConfigParam +- anthropic.BetaComputerWaitConfigParam +- anthropic.BetaComputerZoomConfigParam - anthropic.BetaContainerParams - anthropic.BetaContainerUploadBlockParam - anthropic.BetaContentBlockParamUnion - anthropic.BetaContentBlockSourceParam - anthropic.BetaContentBlockSourceContentUnionParam - anthropic.BetaContextManagementConfigParam +- anthropic.BetaDiagnosticsParam - anthropic.BetaDirectCallerParam - anthropic.BetaEncryptedCodeExecutionResultBlockParam +- anthropic.BetaFallbackBlockParam +- anthropic.BetaFallbackCreditTokenParam +- anthropic.BetaFallbackInfoParam +- anthropic.BetaFallbackParam +- anthropic.BetaFallbacksParamUnion - anthropic.BetaFileDocumentSourceParam - anthropic.BetaFileImageSourceParam - anthropic.BetaImageBlockParam +- anthropic.BetaImageTransformationsParam - anthropic.BetaInputTokensClearAtLeastParam - anthropic.BetaInputTokensTriggerParam - anthropic.BetaJSONOutputFormatParam @@ -340,6 +525,8 @@ Params Types: - anthropic.BetaRequestMCPServerToolConfigurationParam - anthropic.BetaRequestMCPServerURLDefinitionParam - anthropic.BetaRequestMCPToolResultBlockParam +- anthropic.BetaRequestToolAdditionBlockParam +- anthropic.BetaRequestToolRemovalBlockParam - anthropic.BetaSearchResultBlockParam - anthropic.BetaServerToolCallerParam - anthropic.BetaServerToolCaller20260120Param @@ -362,6 +549,9 @@ Params Types: - anthropic.BetaToolParam - anthropic.BetaToolBash20241022Param - anthropic.BetaToolBash20250124Param +- anthropic.BetaToolChangeMCPToolReferenceParam +- anthropic.BetaToolChangeMCPToolsetReferenceParam +- anthropic.BetaToolChangeToolReferenceParam - anthropic.BetaToolChoiceUnionParam - anthropic.BetaToolChoiceAnyParam - anthropic.BetaToolChoiceAutoParam @@ -392,12 +582,14 @@ Params Types: - anthropic.BetaWebFetchTool20250910Param - anthropic.BetaWebFetchTool20260209Param - anthropic.BetaWebFetchTool20260309Param +- anthropic.BetaWebFetchTool20260318Param - anthropic.BetaWebFetchToolResultBlockParam - anthropic.BetaWebFetchToolResultErrorBlockParam - anthropic.BetaWebFetchToolResultErrorCode - anthropic.BetaWebSearchResultBlockParam - anthropic.BetaWebSearchTool20250305Param - anthropic.BetaWebSearchTool20260209Param +- anthropic.BetaWebSearchTool20260318Param - anthropic.BetaWebSearchToolRequestErrorParam - anthropic.BetaWebSearchToolResultBlockParam - anthropic.BetaWebSearchToolResultBlockParamContentUnion @@ -416,6 +608,12 @@ Response Types: - anthropic.BetaBashCodeExecutionToolResultBlock - anthropic.BetaBashCodeExecutionToolResultError - anthropic.BetaCacheCreation +- anthropic.BetaCacheMissMessagesChanged +- anthropic.BetaCacheMissModelChanged +- anthropic.BetaCacheMissPreviousMessageNotFound +- anthropic.BetaCacheMissSystemChanged +- anthropic.BetaCacheMissToolsChanged +- anthropic.BetaCacheMissUnavailable - anthropic.BetaCitationCharLocation - anthropic.BetaCitationConfig - anthropic.BetaCitationContentBlockLocation @@ -439,9 +637,17 @@ Response Types: - anthropic.BetaContentBlockUnion - anthropic.BetaContextManagementResponse - anthropic.BetaCountTokensContextManagementResponse +- anthropic.BetaDiagnostics - anthropic.BetaDirectCaller - anthropic.BetaDocumentBlock - anthropic.BetaEncryptedCodeExecutionResultBlock +- anthropic.BetaFallbackBlock +- anthropic.BetaFallbackCreditNotApplied +- anthropic.BetaFallbackCreditRedeemed +- anthropic.BetaFallbackCreditUsage +- anthropic.BetaFallbackInfo +- anthropic.BetaFallbackMessageIterationUsage +- anthropic.BetaFallbackRefusalTrigger - anthropic.BetaInputJSONDelta - anthropic.BetaIterationsUsage - anthropic.BetaMCPToolResultBlock @@ -457,6 +663,7 @@ Response Types: - anthropic.BetaMessageDeltaUsage - anthropic.BetaMessageIterationUsage - anthropic.BetaMessageTokensCount +- anthropic.BetaOutputTokensDetails - anthropic.BetaPlainTextSource - anthropic.BetaRawContentBlockDeltaUnion - anthropic.BetaRawContentBlockDeltaEvent @@ -533,41 +740,79 @@ Methods: Params Types: -- anthropic.BetaManagedAgentsAgentToolConfigParams +- anthropic.BetaManagedAgentsAgentToolConfigParamsUnion - anthropic.BetaManagedAgentsAgentToolsetDefaultConfigParams - anthropic.BetaManagedAgentsAgentToolset20260401Params - anthropic.BetaManagedAgentsAlwaysAllowPolicyParam - anthropic.BetaManagedAgentsAlwaysAskPolicyParam - anthropic.BetaManagedAgentsAnthropicSkillParams +- anthropic.BetaManagedAgentsBashToolConfigParams - anthropic.BetaManagedAgentsCustomSkillParams - anthropic.BetaManagedAgentsCustomToolInputSchemaParam - anthropic.BetaManagedAgentsCustomToolParams +- anthropic.BetaManagedAgentsEditToolConfigParams +- anthropic.BetaManagedAgentsEffortHighParam +- anthropic.BetaManagedAgentsEffortLowParam +- anthropic.BetaManagedAgentsEffortMaxParam +- anthropic.BetaManagedAgentsEffortMediumParam +- anthropic.BetaManagedAgentsEffortXhighParam +- anthropic.BetaManagedAgentsGlobToolConfigParams +- anthropic.BetaManagedAgentsGrepToolConfigParams - anthropic.BetaManagedAgentsMCPToolConfigParams - anthropic.BetaManagedAgentsMCPToolsetDefaultConfigParams - anthropic.BetaManagedAgentsMCPToolsetParams - anthropic.BetaManagedAgentsModel - anthropic.BetaManagedAgentsModelConfigParams +- anthropic.BetaManagedAgentsMultiagentSelfParams +- anthropic.BetaManagedAgentsReadToolConfigParams - anthropic.BetaManagedAgentsSkillParamsUnion - anthropic.BetaManagedAgentsURLMCPServerParams +- anthropic.BetaManagedAgentsUserLocationParam +- anthropic.BetaManagedAgentsWebFetchToolConfigParams +- anthropic.BetaManagedAgentsWebSearchToolConfigParams +- anthropic.BetaManagedAgentsWriteToolConfigParams Response Types: +- anthropic.BetaManagedAgentsAdvisor - anthropic.BetaManagedAgentsAgent -- anthropic.BetaManagedAgentsAgentToolConfig +- anthropic.BetaManagedAgentsAgentReference +- anthropic.BetaManagedAgentsAgentToolConfigUnion - anthropic.BetaManagedAgentsAgentToolsetDefaultConfig - anthropic.BetaManagedAgentsAgentToolset20260401 +- anthropic.BetaManagedAgentsAgentToolset20260401BashInput +- anthropic.BetaManagedAgentsAgentToolset20260401EditInput +- anthropic.BetaManagedAgentsAgentToolset20260401GlobInput +- anthropic.BetaManagedAgentsAgentToolset20260401GrepInput +- anthropic.BetaManagedAgentsAgentToolset20260401ReadInput +- anthropic.BetaManagedAgentsAgentToolset20260401WriteInput - anthropic.BetaManagedAgentsAlwaysAllowPolicy - anthropic.BetaManagedAgentsAlwaysAskPolicy - anthropic.BetaManagedAgentsAnthropicSkill +- anthropic.BetaManagedAgentsBashToolConfig - anthropic.BetaManagedAgentsCustomSkill - anthropic.BetaManagedAgentsCustomTool - anthropic.BetaManagedAgentsCustomToolInputSchema +- anthropic.BetaManagedAgentsEditToolConfig +- anthropic.BetaManagedAgentsEffortHigh +- anthropic.BetaManagedAgentsEffortLow +- anthropic.BetaManagedAgentsEffortMax +- anthropic.BetaManagedAgentsEffortMedium +- anthropic.BetaManagedAgentsEffortXhigh +- anthropic.BetaManagedAgentsGlobToolConfig +- anthropic.BetaManagedAgentsGrepToolConfig - anthropic.BetaManagedAgentsMCPServerURLDefinition - anthropic.BetaManagedAgentsMCPToolConfig - anthropic.BetaManagedAgentsMCPToolset - anthropic.BetaManagedAgentsMCPToolsetDefaultConfig - anthropic.BetaManagedAgentsModel - anthropic.BetaManagedAgentsModelConfig +- anthropic.BetaManagedAgentsReadToolConfig +- anthropic.BetaManagedAgentsSessionThreadAgent +- anthropic.BetaManagedAgentsUserLocation +- anthropic.BetaManagedAgentsWebFetchToolConfig +- anthropic.BetaManagedAgentsWebSearchToolConfig +- anthropic.BetaManagedAgentsWriteToolConfig Methods: @@ -590,6 +835,7 @@ Params Types: - anthropic.BetaCloudConfigParams - anthropic.BetaLimitedNetworkParams - anthropic.BetaPackagesParams +- anthropic.BetaSelfHostedConfigParams - anthropic.BetaUnrestrictedNetworkParam Response Types: @@ -599,6 +845,7 @@ Response Types: - anthropic.BetaEnvironmentDeleteResponse - anthropic.BetaLimitedNetwork - anthropic.BetaPackages +- anthropic.BetaSelfHostedConfig - anthropic.BetaUnrestrictedNetwork Methods: @@ -610,33 +857,84 @@ Methods: - client.Beta.Environments.Delete(ctx context.Context, environmentID string, body anthropic.BetaEnvironmentDeleteParams) (\*anthropic.BetaEnvironmentDeleteResponse, error) - client.Beta.Environments.Archive(ctx context.Context, environmentID string, body anthropic.BetaEnvironmentArchiveParams) (\*anthropic.BetaEnvironment, error) +### Work + +Params Types: + +- anthropic.BetaSelfHostedWorkStopRequestParam +- anthropic.BetaSelfHostedWorkUpdateRequestParam + +Response Types: + +- anthropic.BetaSelfHostedWork +- anthropic.BetaSelfHostedWorkHeartbeatResponse +- anthropic.BetaSelfHostedWorkListResponse +- anthropic.BetaSelfHostedWorkQueueStats +- anthropic.BetaSessionWorkData + +Methods: + +- client.Beta.Environments.Work.Get(ctx context.Context, workID string, params anthropic.BetaEnvironmentWorkGetParams) (\*anthropic.BetaSelfHostedWork, error) +- client.Beta.Environments.Work.Update(ctx context.Context, workID string, params anthropic.BetaEnvironmentWorkUpdateParams) (\*anthropic.BetaSelfHostedWork, error) +- client.Beta.Environments.Work.List(ctx context.Context, environmentID string, params anthropic.BetaEnvironmentWorkListParams) (\*pagination.PageCursor[anthropic.BetaSelfHostedWork], error) +- client.Beta.Environments.Work.Ack(ctx context.Context, workID string, params anthropic.BetaEnvironmentWorkAckParams) (\*anthropic.BetaSelfHostedWork, error) +- client.Beta.Environments.Work.Heartbeat(ctx context.Context, workID string, params anthropic.BetaEnvironmentWorkHeartbeatParams) (\*anthropic.BetaSelfHostedWorkHeartbeatResponse, error) +- client.Beta.Environments.Work.Poll(ctx context.Context, environmentID string, params anthropic.BetaEnvironmentWorkPollParams) (\*anthropic.BetaSelfHostedWork, error) +- client.Beta.Environments.Work.Stats(ctx context.Context, environmentID string, query anthropic.BetaEnvironmentWorkStatsParams) (\*anthropic.BetaSelfHostedWorkQueueStats, error) +- client.Beta.Environments.Work.Stop(ctx context.Context, workID string, params anthropic.BetaEnvironmentWorkStopParams) (\*anthropic.BetaSelfHostedWork, error) + ## Sessions Params Types: +- anthropic.BetaManagedAgentsAdvisorParams - anthropic.BetaManagedAgentsAgentParams +- anthropic.BetaManagedAgentsAgentWithOverridesParams - anthropic.BetaManagedAgentsBranchCheckoutParam +- anthropic.BetaManagedAgentsBudgetLimitParam - anthropic.BetaManagedAgentsCommitCheckoutParam +- anthropic.BetaManagedAgentsDeltaType - anthropic.BetaManagedAgentsFileResourceParams - anthropic.BetaManagedAgentsGitHubRepositoryResourceParams +- anthropic.BetaManagedAgentsMemoryStoreResourceParam +- anthropic.BetaManagedAgentsMultiagentParams +- anthropic.BetaManagedAgentsMultiagentRosterEntryParamsUnion +- anthropic.BetaManagedAgentsSessionAgentUpdateParam +- anthropic.BetaManagedAgentsSystemContentBlockParam Response Types: +- anthropic.BetaManagedAgentsAgentMessagePreview +- anthropic.BetaManagedAgentsAgentThinkingPreview - anthropic.BetaManagedAgentsBranchCheckout +- anthropic.BetaManagedAgentsBudgetLimit - anthropic.BetaManagedAgentsCacheCreationUsage - anthropic.BetaManagedAgentsCommitCheckout - anthropic.BetaManagedAgentsDeletedSession +- anthropic.BetaManagedAgentsDeltaContent +- anthropic.BetaManagedAgentsDeltaEvent +- anthropic.BetaManagedAgentsMultiagent +- anthropic.BetaManagedAgentsOutcomeEvaluationResource +- anthropic.BetaManagedAgentsServerToolUsage - anthropic.BetaManagedAgentsSession - anthropic.BetaManagedAgentsSessionAgent +- anthropic.BetaManagedAgentsSessionMultiagentCoordinator - anthropic.BetaManagedAgentsSessionStats +- anthropic.BetaManagedAgentsSessionUpdatedEvent - anthropic.BetaManagedAgentsSessionUsage +- anthropic.BetaManagedAgentsSessionUsageEvent +- anthropic.BetaManagedAgentsStartEvent +- anthropic.BetaManagedAgentsStartEventPreviewUnion +- anthropic.BetaManagedAgentsSystemContentBlock +- anthropic.BetaManagedAgentsSystemMessageEvent +- anthropic.BetaManagedAgentsUserToolResultEvent Methods: - client.Beta.Sessions.New(ctx context.Context, params anthropic.BetaSessionNewParams) (\*anthropic.BetaManagedAgentsSession, error) - client.Beta.Sessions.Get(ctx context.Context, sessionID string, query anthropic.BetaSessionGetParams) (\*anthropic.BetaManagedAgentsSession, error) - client.Beta.Sessions.Update(ctx context.Context, sessionID string, params anthropic.BetaSessionUpdateParams) (\*anthropic.BetaManagedAgentsSession, error) -- client.Beta.Sessions.List(ctx context.Context, params anthropic.BetaSessionListParams) (\*pagination.PageCursor[anthropic.BetaManagedAgentsSession], error) +- client.Beta.Sessions.List(ctx context.Context, params anthropic.BetaSessionListParams) (\*pagination.BidirectionalPageCursor[anthropic.BetaManagedAgentsSession], error) - client.Beta.Sessions.Delete(ctx context.Context, sessionID string, body anthropic.BetaSessionDeleteParams) (\*anthropic.BetaManagedAgentsDeletedSession, error) - client.Beta.Sessions.Archive(ctx context.Context, sessionID string, body anthropic.BetaSessionArchiveParams) (\*anthropic.BetaManagedAgentsSession, error) @@ -650,15 +948,24 @@ Params Types: - anthropic.BetaManagedAgentsEventParamsUnion - anthropic.BetaManagedAgentsFileDocumentSourceParam - anthropic.BetaManagedAgentsFileImageSourceParam +- anthropic.BetaManagedAgentsFileRubricParams - anthropic.BetaManagedAgentsImageBlockParam - anthropic.BetaManagedAgentsPlainTextDocumentSourceParam +- anthropic.BetaManagedAgentsRedactedBlockParam +- anthropic.BetaManagedAgentsSearchResultBlockParam +- anthropic.BetaManagedAgentsSearchResultCitationsParam +- anthropic.BetaManagedAgentsSearchResultContentParam +- anthropic.BetaManagedAgentsSystemMessageEventParams - anthropic.BetaManagedAgentsTextBlockParam +- anthropic.BetaManagedAgentsTextRubricParams - anthropic.BetaManagedAgentsURLDocumentSourceParam - anthropic.BetaManagedAgentsURLImageSourceParam - anthropic.BetaManagedAgentsUserCustomToolResultEventParams +- anthropic.BetaManagedAgentsUserDefineOutcomeEventParams - anthropic.BetaManagedAgentsUserInterruptEventParams - anthropic.BetaManagedAgentsUserMessageEventParams - anthropic.BetaManagedAgentsUserToolConfirmationEventParams +- anthropic.BetaManagedAgentsUserToolResultEventParams Response Types: @@ -668,14 +975,18 @@ Response Types: - anthropic.BetaManagedAgentsAgentMessageEvent - anthropic.BetaManagedAgentsAgentThinkingEvent - anthropic.BetaManagedAgentsAgentThreadContextCompactedEvent +- anthropic.BetaManagedAgentsAgentThreadMessageReceivedEvent +- anthropic.BetaManagedAgentsAgentThreadMessageSentEvent - anthropic.BetaManagedAgentsAgentToolResultEvent - anthropic.BetaManagedAgentsAgentToolUseEvent - anthropic.BetaManagedAgentsBase64DocumentSource - anthropic.BetaManagedAgentsBase64ImageSource - anthropic.BetaManagedAgentsBillingError +- anthropic.BetaManagedAgentsCredentialHostUnreachableError - anthropic.BetaManagedAgentsDocumentBlock - anthropic.BetaManagedAgentsFileDocumentSource - anthropic.BetaManagedAgentsFileImageSource +- anthropic.BetaManagedAgentsFileRubric - anthropic.BetaManagedAgentsImageBlock - anthropic.BetaManagedAgentsMCPAuthenticationFailedError - anthropic.BetaManagedAgentsMCPConnectionFailedError @@ -683,10 +994,15 @@ Response Types: - anthropic.BetaManagedAgentsModelRateLimitedError - anthropic.BetaManagedAgentsModelRequestFailedError - anthropic.BetaManagedAgentsPlainTextDocumentSource +- anthropic.BetaManagedAgentsRedactedBlock - anthropic.BetaManagedAgentsRetryStatusExhausted - anthropic.BetaManagedAgentsRetryStatusRetrying - anthropic.BetaManagedAgentsRetryStatusTerminal +- anthropic.BetaManagedAgentsSearchResultBlock +- anthropic.BetaManagedAgentsSearchResultCitations +- anthropic.BetaManagedAgentsSearchResultContent - anthropic.BetaManagedAgentsSendSessionEvents +- anthropic.BetaManagedAgentsSessionBudgetReached - anthropic.BetaManagedAgentsSessionDeletedEvent - anthropic.BetaManagedAgentsSessionEndTurn - anthropic.BetaManagedAgentsSessionErrorEvent @@ -697,15 +1013,26 @@ Response Types: - anthropic.BetaManagedAgentsSessionStatusRescheduledEvent - anthropic.BetaManagedAgentsSessionStatusRunningEvent - anthropic.BetaManagedAgentsSessionStatusTerminatedEvent +- anthropic.BetaManagedAgentsSessionThreadCreatedEvent +- anthropic.BetaManagedAgentsSessionThreadStatusIdleEvent +- anthropic.BetaManagedAgentsSessionThreadStatusRescheduledEvent +- anthropic.BetaManagedAgentsSessionThreadStatusRunningEvent +- anthropic.BetaManagedAgentsSessionThreadStatusTerminatedEvent +- anthropic.BetaManagedAgentsSessionUsageSnapshot - anthropic.BetaManagedAgentsSpanModelRequestEndEvent - anthropic.BetaManagedAgentsSpanModelRequestStartEvent - anthropic.BetaManagedAgentsSpanModelUsage +- anthropic.BetaManagedAgentsSpanOutcomeEvaluationEndEvent +- anthropic.BetaManagedAgentsSpanOutcomeEvaluationOngoingEvent +- anthropic.BetaManagedAgentsSpanOutcomeEvaluationStartEvent - anthropic.BetaManagedAgentsStreamSessionEventsUnion - anthropic.BetaManagedAgentsTextBlock +- anthropic.BetaManagedAgentsTextRubric - anthropic.BetaManagedAgentsUnknownError - anthropic.BetaManagedAgentsURLDocumentSource - anthropic.BetaManagedAgentsURLImageSource - anthropic.BetaManagedAgentsUserCustomToolResultEvent +- anthropic.BetaManagedAgentsUserDefineOutcomeEvent - anthropic.BetaManagedAgentsUserInterruptEvent - anthropic.BetaManagedAgentsUserMessageEvent - anthropic.BetaManagedAgentsUserToolConfirmationEvent @@ -714,7 +1041,7 @@ Methods: - client.Beta.Sessions.Events.List(ctx context.Context, sessionID string, params anthropic.BetaSessionEventListParams) (\*pagination.PageCursor[anthropic.BetaManagedAgentsSessionEventUnion], error) - client.Beta.Sessions.Events.Send(ctx context.Context, sessionID string, params anthropic.BetaSessionEventSendParams) (\*anthropic.BetaManagedAgentsSendSessionEvents, error) -- client.Beta.Sessions.Events.Stream(ctx context.Context, sessionID string, query anthropic.BetaSessionEventStreamParams) (\*anthropic.BetaManagedAgentsStreamSessionEventsUnion, error) +- client.Beta.Sessions.Events.Stream(ctx context.Context, sessionID string, params anthropic.BetaSessionEventStreamParams) (\*anthropic.BetaManagedAgentsStreamSessionEventsUnion, error) ### Resources @@ -723,6 +1050,7 @@ Response Types: - anthropic.BetaManagedAgentsDeleteSessionResource - anthropic.BetaManagedAgentsFileResource - anthropic.BetaManagedAgentsGitHubRepositoryResource +- anthropic.BetaManagedAgentsMemoryStoreResource - anthropic.BetaManagedAgentsSessionResourceUnion - anthropic.BetaSessionResourceGetResponseUnion - anthropic.BetaSessionResourceUpdateResponseUnion @@ -735,6 +1063,114 @@ Methods: - client.Beta.Sessions.Resources.Delete(ctx context.Context, resourceID string, params anthropic.BetaSessionResourceDeleteParams) (\*anthropic.BetaManagedAgentsDeleteSessionResource, error) - client.Beta.Sessions.Resources.Add(ctx context.Context, sessionID string, params anthropic.BetaSessionResourceAddParams) (\*anthropic.BetaManagedAgentsFileResource, error) +### Threads + +Response Types: + +- anthropic.BetaManagedAgentsSessionThread +- anthropic.BetaManagedAgentsSessionThreadStats +- anthropic.BetaManagedAgentsSessionThreadStatus +- anthropic.BetaManagedAgentsSessionThreadUsage +- anthropic.BetaManagedAgentsStreamSessionThreadEventsUnion + +Methods: + +- client.Beta.Sessions.Threads.Get(ctx context.Context, threadID string, params anthropic.BetaSessionThreadGetParams) (\*anthropic.BetaManagedAgentsSessionThread, error) +- client.Beta.Sessions.Threads.List(ctx context.Context, sessionID string, params anthropic.BetaSessionThreadListParams) (\*pagination.PageCursor[anthropic.BetaManagedAgentsSessionThread], error) +- client.Beta.Sessions.Threads.Archive(ctx context.Context, threadID string, params anthropic.BetaSessionThreadArchiveParams) (\*anthropic.BetaManagedAgentsSessionThread, error) + +#### Events + +Methods: + +- client.Beta.Sessions.Threads.Events.List(ctx context.Context, threadID string, params anthropic.BetaSessionThreadEventListParams) (\*pagination.PageCursor[anthropic.BetaManagedAgentsSessionEventUnion], error) +- client.Beta.Sessions.Threads.Events.Stream(ctx context.Context, threadID string, params anthropic.BetaSessionThreadEventStreamParams) (\*anthropic.BetaManagedAgentsStreamSessionThreadEventsUnion, error) + +## Deployments + +Params Types: + +- anthropic.BetaManagedAgentsDeploymentInitialEventParamsUnion +- anthropic.BetaManagedAgentsDeploymentStatus +- anthropic.BetaManagedAgentsScheduleParams + +Response Types: + +- anthropic.BetaManagedAgentsAgentArchivedDeploymentPausedReasonError +- anthropic.BetaManagedAgentsDeployment +- anthropic.BetaManagedAgentsDeploymentInitialEventUnion +- anthropic.BetaManagedAgentsDeploymentPausedReasonUnion +- anthropic.BetaManagedAgentsDeploymentPausedReasonErrorUnion +- anthropic.BetaManagedAgentsDeploymentStatus +- anthropic.BetaManagedAgentsDeploymentSystemMessageEvent +- anthropic.BetaManagedAgentsDeploymentUserDefineOutcomeEvent +- anthropic.BetaManagedAgentsDeploymentUserMessageEvent +- anthropic.BetaManagedAgentsEnvironmentArchivedDeploymentPausedReasonError +- anthropic.BetaManagedAgentsEnvironmentNotFoundDeploymentPausedReasonError +- anthropic.BetaManagedAgentsErrorDeploymentPausedReason +- anthropic.BetaManagedAgentsFileNotFoundDeploymentPausedReasonError +- anthropic.BetaManagedAgentsFileResourceConfig +- anthropic.BetaManagedAgentsGitHubRepositoryResourceConfig +- anthropic.BetaManagedAgentsManualDeploymentPausedReason +- anthropic.BetaManagedAgentsMCPEgressBlockedDeploymentPausedReasonError +- anthropic.BetaManagedAgentsMemoryStoreArchivedDeploymentPausedReasonError +- anthropic.BetaManagedAgentsMemoryStoreResourceConfig +- anthropic.BetaManagedAgentsOrganizationDisabledDeploymentPausedReasonError +- anthropic.BetaManagedAgentsSchedule +- anthropic.BetaManagedAgentsSelfHostedResourcesUnsupportedDeploymentPausedReasonError +- anthropic.BetaManagedAgentsSessionResourceConfigUnion +- anthropic.BetaManagedAgentsSessionResourceNotFoundDeploymentPausedReasonError +- anthropic.BetaManagedAgentsSkillNotFoundDeploymentPausedReasonError +- anthropic.BetaManagedAgentsUnknownDeploymentPausedReasonError +- anthropic.BetaManagedAgentsVaultArchivedDeploymentPausedReasonError +- anthropic.BetaManagedAgentsVaultNotFoundDeploymentPausedReasonError +- anthropic.BetaManagedAgentsWorkspaceArchivedDeploymentPausedReasonError + +Methods: + +- client.Beta.Deployments.New(ctx context.Context, params anthropic.BetaDeploymentNewParams) (\*anthropic.BetaManagedAgentsDeployment, error) +- client.Beta.Deployments.Get(ctx context.Context, deploymentID string, query anthropic.BetaDeploymentGetParams) (\*anthropic.BetaManagedAgentsDeployment, error) +- client.Beta.Deployments.Update(ctx context.Context, deploymentID string, params anthropic.BetaDeploymentUpdateParams) (\*anthropic.BetaManagedAgentsDeployment, error) +- client.Beta.Deployments.List(ctx context.Context, params anthropic.BetaDeploymentListParams) (\*pagination.PageCursor[anthropic.BetaManagedAgentsDeployment], error) +- client.Beta.Deployments.Archive(ctx context.Context, deploymentID string, body anthropic.BetaDeploymentArchiveParams) (\*anthropic.BetaManagedAgentsDeployment, error) +- client.Beta.Deployments.Pause(ctx context.Context, deploymentID string, body anthropic.BetaDeploymentPauseParams) (\*anthropic.BetaManagedAgentsDeployment, error) +- client.Beta.Deployments.Run(ctx context.Context, deploymentID string, body anthropic.BetaDeploymentRunParams) (\*anthropic.BetaManagedAgentsDeploymentRun, error) +- client.Beta.Deployments.Unpause(ctx context.Context, deploymentID string, body anthropic.BetaDeploymentUnpauseParams) (\*anthropic.BetaManagedAgentsDeployment, error) + +## DeploymentRuns + +Params Types: + +- anthropic.BetaManagedAgentsTriggerType + +Response Types: + +- anthropic.BetaManagedAgentsAgentArchivedRunError +- anthropic.BetaManagedAgentsDeploymentRun +- anthropic.BetaManagedAgentsEnvironmentArchivedRunError +- anthropic.BetaManagedAgentsEnvironmentNotFoundRunError +- anthropic.BetaManagedAgentsFileNotFoundRunError +- anthropic.BetaManagedAgentsManualTriggerContext +- anthropic.BetaManagedAgentsMCPEgressBlockedRunError +- anthropic.BetaManagedAgentsMemoryStoreArchivedRunError +- anthropic.BetaManagedAgentsOrganizationDisabledRunError +- anthropic.BetaManagedAgentsScheduleTriggerContext +- anthropic.BetaManagedAgentsSelfHostedResourcesUnsupportedRunError +- anthropic.BetaManagedAgentsSessionCreationRejectedRunError +- anthropic.BetaManagedAgentsSessionRateLimitedRunError +- anthropic.BetaManagedAgentsSessionResourceNotFoundRunError +- anthropic.BetaManagedAgentsSkillNotFoundRunError +- anthropic.BetaManagedAgentsTriggerContextUnion +- anthropic.BetaManagedAgentsUnknownRunError +- anthropic.BetaManagedAgentsVaultArchivedRunError +- anthropic.BetaManagedAgentsVaultNotFoundRunError +- anthropic.BetaManagedAgentsWorkspaceArchivedRunError + +Methods: + +- client.Beta.DeploymentRuns.Get(ctx context.Context, deploymentRunID string, query anthropic.BetaDeploymentRunGetParams) (\*anthropic.BetaManagedAgentsDeploymentRun, error) +- client.Beta.DeploymentRuns.List(ctx context.Context, params anthropic.BetaDeploymentRunListParams) (\*pagination.PageCursor[anthropic.BetaManagedAgentsDeploymentRun], error) + ## Vaults Response Types: @@ -755,6 +1191,12 @@ Methods: Params Types: +- anthropic.BetaManagedAgentsCredentialNetworkingParamsUnion +- anthropic.BetaManagedAgentsEnvironmentVariableCreateParams +- anthropic.BetaManagedAgentsEnvironmentVariableUpdateParams +- anthropic.BetaManagedAgentsInjectionLocationParams +- anthropic.BetaManagedAgentsInjectionLocationUpdateParams +- anthropic.BetaManagedAgentsLimitedCredentialNetworkingParams - anthropic.BetaManagedAgentsMCPOAuthCreateParams - anthropic.BetaManagedAgentsMCPOAuthRefreshParams - anthropic.BetaManagedAgentsMCPOAuthRefreshUpdateParams @@ -766,17 +1208,27 @@ Params Types: - anthropic.BetaManagedAgentsTokenEndpointAuthNoneParam - anthropic.BetaManagedAgentsTokenEndpointAuthPostParam - anthropic.BetaManagedAgentsTokenEndpointAuthPostUpdateParam +- anthropic.BetaManagedAgentsUnrestrictedCredentialNetworkingParams Response Types: - anthropic.BetaManagedAgentsCredential +- anthropic.BetaManagedAgentsCredentialValidation +- anthropic.BetaManagedAgentsCredentialValidationStatus - anthropic.BetaManagedAgentsDeletedCredential +- anthropic.BetaManagedAgentsEnvironmentVariableAuthResponse +- anthropic.BetaManagedAgentsInjectionLocationResponse +- anthropic.BetaManagedAgentsLimitedCredentialNetworkingResponse - anthropic.BetaManagedAgentsMCPOAuthAuthResponse - anthropic.BetaManagedAgentsMCPOAuthRefreshResponse +- anthropic.BetaManagedAgentsMCPProbe +- anthropic.BetaManagedAgentsRefreshHTTPResponse +- anthropic.BetaManagedAgentsRefreshObject - anthropic.BetaManagedAgentsStaticBearerAuthResponse - anthropic.BetaManagedAgentsTokenEndpointAuthBasicResponse - anthropic.BetaManagedAgentsTokenEndpointAuthNoneResponse - anthropic.BetaManagedAgentsTokenEndpointAuthPostResponse +- anthropic.BetaManagedAgentsUnrestrictedCredentialNetworkingResponse Methods: @@ -786,22 +1238,83 @@ Methods: - client.Beta.Vaults.Credentials.List(ctx context.Context, vaultID string, params anthropic.BetaVaultCredentialListParams) (\*pagination.PageCursor[anthropic.BetaManagedAgentsCredential], error) - client.Beta.Vaults.Credentials.Delete(ctx context.Context, credentialID string, params anthropic.BetaVaultCredentialDeleteParams) (\*anthropic.BetaManagedAgentsDeletedCredential, error) - client.Beta.Vaults.Credentials.Archive(ctx context.Context, credentialID string, params anthropic.BetaVaultCredentialArchiveParams) (\*anthropic.BetaManagedAgentsCredential, error) +- client.Beta.Vaults.Credentials.MCPOAuthValidate(ctx context.Context, credentialID string, params anthropic.BetaVaultCredentialMCPOAuthValidateParams) (\*anthropic.BetaManagedAgentsCredentialValidation, error) + +## MemoryStores + +Response Types: + +- anthropic.BetaManagedAgentsDeletedMemoryStore +- anthropic.BetaManagedAgentsMemoryStore + +Methods: + +- client.Beta.MemoryStores.New(ctx context.Context, params anthropic.BetaMemoryStoreNewParams) (\*anthropic.BetaManagedAgentsMemoryStore, error) +- client.Beta.MemoryStores.Get(ctx context.Context, memoryStoreID string, query anthropic.BetaMemoryStoreGetParams) (\*anthropic.BetaManagedAgentsMemoryStore, error) +- client.Beta.MemoryStores.Update(ctx context.Context, memoryStoreID string, params anthropic.BetaMemoryStoreUpdateParams) (\*anthropic.BetaManagedAgentsMemoryStore, error) +- client.Beta.MemoryStores.List(ctx context.Context, params anthropic.BetaMemoryStoreListParams) (\*pagination.PageCursor[anthropic.BetaManagedAgentsMemoryStore], error) +- client.Beta.MemoryStores.Delete(ctx context.Context, memoryStoreID string, body anthropic.BetaMemoryStoreDeleteParams) (\*anthropic.BetaManagedAgentsDeletedMemoryStore, error) +- client.Beta.MemoryStores.Archive(ctx context.Context, memoryStoreID string, body anthropic.BetaMemoryStoreArchiveParams) (\*anthropic.BetaManagedAgentsMemoryStore, error) + +### Memories + +Params Types: + +- anthropic.BetaManagedAgentsMemoryView +- anthropic.BetaManagedAgentsPreconditionParam + +Response Types: + +- anthropic.BetaManagedAgentsDeletedMemory +- anthropic.BetaManagedAgentsMemory +- anthropic.BetaManagedAgentsMemoryListItemUnion +- anthropic.BetaManagedAgentsMemoryPrefix + +Methods: + +- client.Beta.MemoryStores.Memories.New(ctx context.Context, memoryStoreID string, params anthropic.BetaMemoryStoreMemoryNewParams) (\*anthropic.BetaManagedAgentsMemory, error) +- client.Beta.MemoryStores.Memories.Get(ctx context.Context, memoryID string, params anthropic.BetaMemoryStoreMemoryGetParams) (\*anthropic.BetaManagedAgentsMemory, error) +- client.Beta.MemoryStores.Memories.Update(ctx context.Context, memoryID string, params anthropic.BetaMemoryStoreMemoryUpdateParams) (\*anthropic.BetaManagedAgentsMemory, error) +- client.Beta.MemoryStores.Memories.List(ctx context.Context, memoryStoreID string, params anthropic.BetaMemoryStoreMemoryListParams) (\*pagination.PageCursor[anthropic.BetaManagedAgentsMemoryListItemUnion], error) +- client.Beta.MemoryStores.Memories.Delete(ctx context.Context, memoryID string, params anthropic.BetaMemoryStoreMemoryDeleteParams) (\*anthropic.BetaManagedAgentsDeletedMemory, error) + +### MemoryVersions + +Params Types: + +- anthropic.BetaManagedAgentsMemoryVersionOperation + +Response Types: + +- anthropic.BetaManagedAgentsActorUnion +- anthropic.BetaManagedAgentsAPIActor +- anthropic.BetaManagedAgentsMemoryVersion +- anthropic.BetaManagedAgentsMemoryVersionOperation +- anthropic.BetaManagedAgentsServiceAccountActor +- anthropic.BetaManagedAgentsSessionActor +- anthropic.BetaManagedAgentsUserActor + +Methods: + +- client.Beta.MemoryStores.MemoryVersions.Get(ctx context.Context, memoryVersionID string, params anthropic.BetaMemoryStoreMemoryVersionGetParams) (\*anthropic.BetaManagedAgentsMemoryVersion, error) +- client.Beta.MemoryStores.MemoryVersions.List(ctx context.Context, memoryStoreID string, params anthropic.BetaMemoryStoreMemoryVersionListParams) (\*pagination.PageCursor[anthropic.BetaManagedAgentsMemoryVersion], error) +- client.Beta.MemoryStores.MemoryVersions.Redact(ctx context.Context, memoryVersionID string, params anthropic.BetaMemoryStoreMemoryVersionRedactParams) (\*anthropic.BetaManagedAgentsMemoryVersion, error) ## Files Response Types: +- anthropic.BetaDeletedFile +- anthropic.BetaFileMetadata - anthropic.BetaFileScope -- anthropic.DeletedFile -- anthropic.FileMetadata Methods: -- client.Beta.Files.List(ctx context.Context, params anthropic.BetaFileListParams) (\*pagination.Page[anthropic.FileMetadata], error) -- client.Beta.Files.Delete(ctx context.Context, fileID string, body anthropic.BetaFileDeleteParams) (\*anthropic.DeletedFile, error) +- client.Beta.Files.List(ctx context.Context, params anthropic.BetaFileListParams) (\*pagination.Page[anthropic.BetaFileMetadata], error) +- client.Beta.Files.Delete(ctx context.Context, fileID string, body anthropic.BetaFileDeleteParams) (\*anthropic.BetaDeletedFile, error) - client.Beta.Files.Download(ctx context.Context, fileID string, query anthropic.BetaFileDownloadParams) (\*http.Response, error) -- client.Beta.Files.GetMetadata(ctx context.Context, fileID string, query anthropic.BetaFileGetMetadataParams) (\*anthropic.FileMetadata, error) -- client.Beta.Files.Upload(ctx context.Context, params anthropic.BetaFileUploadParams) (\*anthropic.FileMetadata, error) +- client.Beta.Files.GetMetadata(ctx context.Context, fileID string, query anthropic.BetaFileGetMetadataParams) (\*anthropic.BetaFileMetadata, error) +- client.Beta.Files.Upload(ctx context.Context, params anthropic.BetaFileUploadParams) (\*anthropic.BetaFileMetadata, error) ## Skills @@ -834,6 +1347,58 @@ Methods: - client.Beta.Skills.Versions.Get(ctx context.Context, version string, params anthropic.BetaSkillVersionGetParams) (\*anthropic.BetaSkillVersionGetResponse, error) - client.Beta.Skills.Versions.List(ctx context.Context, skillID string, params anthropic.BetaSkillVersionListParams) (\*pagination.PageCursor[anthropic.BetaSkillVersionListResponse], error) - client.Beta.Skills.Versions.Delete(ctx context.Context, version string, params anthropic.BetaSkillVersionDeleteParams) (\*anthropic.BetaSkillVersionDeleteResponse, error) +- client.Beta.Skills.Versions.Download(ctx context.Context, version string, params anthropic.BetaSkillVersionDownloadParams) (\*http.Response, error) + +## Webhooks + +Response Types: + +- anthropic.BetaWebhookAgentArchivedEventData +- anthropic.BetaWebhookAgentCreatedEventData +- anthropic.BetaWebhookAgentDeletedEventData +- anthropic.BetaWebhookAgentUpdatedEventData +- anthropic.BetaWebhookDeploymentArchivedEventData +- anthropic.BetaWebhookDeploymentCreatedEventData +- anthropic.BetaWebhookDeploymentDeletedEventData +- anthropic.BetaWebhookDeploymentPausedEventData +- anthropic.BetaWebhookDeploymentRunFailedEventData +- anthropic.BetaWebhookDeploymentRunStartedEventData +- anthropic.BetaWebhookDeploymentRunSucceededEventData +- anthropic.BetaWebhookDeploymentUnpausedEventData +- anthropic.BetaWebhookDeploymentUpdatedEventData +- anthropic.BetaWebhookEnvironmentArchivedEventData +- anthropic.BetaWebhookEnvironmentCreatedEventData +- anthropic.BetaWebhookEnvironmentDeletedEventData +- anthropic.BetaWebhookEnvironmentUpdatedEventData +- anthropic.BetaWebhookEventDataUnion +- anthropic.BetaWebhookMemoryStoreArchivedEventData +- anthropic.BetaWebhookMemoryStoreCreatedEventData +- anthropic.BetaWebhookMemoryStoreDeletedEventData +- anthropic.BetaWebhookSessionArchivedEventData +- anthropic.BetaWebhookSessionBudgetReachedEventData +- anthropic.BetaWebhookSessionCreatedEventData +- anthropic.BetaWebhookSessionDeletedEventData +- anthropic.BetaWebhookSessionIdledEventData +- anthropic.BetaWebhookSessionOutcomeEvaluationEndedEventData +- anthropic.BetaWebhookSessionPendingEventData +- anthropic.BetaWebhookSessionRequiresActionEventData +- anthropic.BetaWebhookSessionRunningEventData +- anthropic.BetaWebhookSessionStatusIdledEventData +- anthropic.BetaWebhookSessionStatusRescheduledEventData +- anthropic.BetaWebhookSessionStatusRunStartedEventData +- anthropic.BetaWebhookSessionStatusTerminatedEventData +- anthropic.BetaWebhookSessionThreadCreatedEventData +- anthropic.BetaWebhookSessionThreadIdledEventData +- anthropic.BetaWebhookSessionThreadTerminatedEventData +- anthropic.BetaWebhookSessionUpdatedEventData +- anthropic.BetaWebhookVaultArchivedEventData +- anthropic.BetaWebhookVaultCreatedEventData +- anthropic.BetaWebhookVaultCredentialArchivedEventData +- anthropic.BetaWebhookVaultCredentialCreatedEventData +- anthropic.BetaWebhookVaultCredentialDeletedEventData +- anthropic.BetaWebhookVaultCredentialRefreshFailedEventData +- anthropic.BetaWebhookVaultDeletedEventData +- anthropic.UnwrapWebhookEvent ## UserProfiles @@ -850,3 +1415,314 @@ Methods: - client.Beta.UserProfiles.Update(ctx context.Context, userProfileID string, params anthropic.BetaUserProfileUpdateParams) (\*anthropic.BetaUserProfile, error) - client.Beta.UserProfiles.List(ctx context.Context, params anthropic.BetaUserProfileListParams) (\*pagination.PageCursor[anthropic.BetaUserProfile], error) - client.Beta.UserProfiles.NewEnrollmentURL(ctx context.Context, userProfileID string, body anthropic.BetaUserProfileNewEnrollmentURLParams) (\*anthropic.BetaUserProfileEnrollmentURL, error) + +## Dreams + +Params Types: + +- anthropic.BetaDreamInputUnionParam +- anthropic.BetaDreamMemoryStoreInputParam +- anthropic.BetaDreamModelConfigParam +- anthropic.BetaDreamSessionsInputParam +- anthropic.BetaDreamStatus +- anthropic.BetaOutputBehaviorUnionParam +- anthropic.BetaOutputBehaviorCreateNewParam +- anthropic.BetaOutputBehaviorUpdateExistingParam + +Response Types: + +- anthropic.BetaDream +- anthropic.BetaDreamError +- anthropic.BetaDreamInputUnion +- anthropic.BetaDreamMemoryStoreInput +- anthropic.BetaDreamModelConfig +- anthropic.BetaDreamOutput +- anthropic.BetaDreamSessionsInput +- anthropic.BetaDreamStatus +- anthropic.BetaDreamUsage +- anthropic.BetaOutputBehaviorUnion +- anthropic.BetaOutputBehaviorCreateNew +- anthropic.BetaOutputBehaviorUpdateExisting + +Methods: + +- client.Beta.Dreams.New(ctx context.Context, params anthropic.BetaDreamNewParams) (\*anthropic.BetaDream, error) +- client.Beta.Dreams.Get(ctx context.Context, dreamID string, query anthropic.BetaDreamGetParams) (\*anthropic.BetaDream, error) +- client.Beta.Dreams.List(ctx context.Context, params anthropic.BetaDreamListParams) (\*pagination.PageCursor[anthropic.BetaDream], error) +- client.Beta.Dreams.Archive(ctx context.Context, dreamID string, body anthropic.BetaDreamArchiveParams) (\*anthropic.BetaDream, error) +- client.Beta.Dreams.Cancel(ctx context.Context, dreamID string, body anthropic.BetaDreamCancelParams) (\*anthropic.BetaDream, error) + +## Tunnels + +Response Types: + +- anthropic.BetaTunnel +- anthropic.BetaTunnelToken + +Methods: + +- client.Beta.Tunnels.New(ctx context.Context, params anthropic.BetaTunnelNewParams) (\*anthropic.BetaTunnel, error) +- client.Beta.Tunnels.Get(ctx context.Context, tunnelID string, query anthropic.BetaTunnelGetParams) (\*anthropic.BetaTunnel, error) +- client.Beta.Tunnels.List(ctx context.Context, params anthropic.BetaTunnelListParams) (\*pagination.PageCursor[anthropic.BetaTunnel], error) +- client.Beta.Tunnels.Archive(ctx context.Context, tunnelID string, body anthropic.BetaTunnelArchiveParams) (\*anthropic.BetaTunnel, error) +- client.Beta.Tunnels.RevealToken(ctx context.Context, tunnelID string, body anthropic.BetaTunnelRevealTokenParams) (\*anthropic.BetaTunnelToken, error) +- client.Beta.Tunnels.RotateToken(ctx context.Context, tunnelID string, params anthropic.BetaTunnelRotateTokenParams) (\*anthropic.BetaTunnelToken, error) + +### Certificates + +Response Types: + +- anthropic.BetaTunnelCertificate + +Methods: + +- client.Beta.Tunnels.Certificates.New(ctx context.Context, tunnelID string, params anthropic.BetaTunnelCertificateNewParams) (\*anthropic.BetaTunnelCertificate, error) +- client.Beta.Tunnels.Certificates.Get(ctx context.Context, certificateID string, params anthropic.BetaTunnelCertificateGetParams) (\*anthropic.BetaTunnelCertificate, error) +- client.Beta.Tunnels.Certificates.List(ctx context.Context, tunnelID string, params anthropic.BetaTunnelCertificateListParams) (\*pagination.PageCursor[anthropic.BetaTunnelCertificate], error) +- client.Beta.Tunnels.Certificates.Archive(ctx context.Context, certificateID string, params anthropic.BetaTunnelCertificateArchiveParams) (\*anthropic.BetaTunnelCertificate, error) + +## Organization + +Response Types: + +- anthropic.BetaOrganization +- anthropic.BetaOrganizationRole + +Methods: + +- client.Beta.Organization.Get(ctx context.Context) (\*anthropic.BetaOrganization, error) + +### APIKeys + +Response Types: + +- anthropic.BetaAPIKey +- anthropic.BetaAPIKeyCreatedBy +- anthropic.BetaAPIKeyOrganizationScope +- anthropic.BetaAPIKeyServiceAccountActor +- anthropic.BetaAPIKeyUserActor +- anthropic.BetaAPIKeyWorkspaceScope + +Methods: + +- client.Beta.Organization.APIKeys.Get(ctx context.Context, apiKeyID string) (\*anthropic.BetaAPIKey, error) +- client.Beta.Organization.APIKeys.Update(ctx context.Context, apiKeyID string, body anthropic.BetaOrganizationAPIKeyUpdateParams) (\*anthropic.BetaAPIKey, error) +- client.Beta.Organization.APIKeys.List(ctx context.Context, query anthropic.BetaOrganizationAPIKeyListParams) (\*pagination.Page[anthropic.BetaAPIKey], error) + +### ExternalKeys + +Params Types: + +- anthropic.BetaAWSExternalKeyConfigParam +- anthropic.BetaAzureExternalKeyConfigParam +- anthropic.BetaGCPExternalKeyConfigParam + +Response Types: + +- anthropic.BetaAWSExternalKeyConfig +- anthropic.BetaAzureExternalKeyConfig +- anthropic.BetaExternalKey +- anthropic.BetaExternalKeyAttachedAttachment +- anthropic.BetaExternalKeyUnattachedAttachment +- anthropic.BetaGCPExternalKeyConfig +- anthropic.BetaOrganizationExternalKeyDeleteResponse +- anthropic.BetaOrganizationExternalKeyValidateResponse + +Methods: + +- client.Beta.Organization.ExternalKeys.New(ctx context.Context, body anthropic.BetaOrganizationExternalKeyNewParams) (\*anthropic.BetaExternalKey, error) +- client.Beta.Organization.ExternalKeys.Get(ctx context.Context, externalKeyID string) (\*anthropic.BetaExternalKey, error) +- client.Beta.Organization.ExternalKeys.Update(ctx context.Context, externalKeyID string, body anthropic.BetaOrganizationExternalKeyUpdateParams) (\*anthropic.BetaExternalKey, error) +- client.Beta.Organization.ExternalKeys.List(ctx context.Context, query anthropic.BetaOrganizationExternalKeyListParams) (\*pagination.PageCursor[anthropic.BetaExternalKey], error) +- client.Beta.Organization.ExternalKeys.Delete(ctx context.Context, externalKeyID string) (\*anthropic.BetaOrganizationExternalKeyDeleteResponse, error) +- client.Beta.Organization.ExternalKeys.Validate(ctx context.Context, externalKeyID string) (\*anthropic.BetaOrganizationExternalKeyValidateResponse, error) + +### Federation + +#### Issuers + +Params Types: + +- anthropic.BetaJWKSDiscoveryParam +- anthropic.BetaJWKSExplicitURLParam +- anthropic.BetaJWKSInlineParam + +Response Types: + +- anthropic.BetaFederationIssuer +- anthropic.BetaFederationIssuerPollStatus +- anthropic.BetaJWKSDiscovery +- anthropic.BetaJWKSExplicitURL +- anthropic.BetaJWKSInline + +Methods: + +- client.Beta.Organization.Federation.Issuers.New(ctx context.Context, params anthropic.BetaOrganizationFederationIssuerNewParams) (\*anthropic.BetaFederationIssuer, error) +- client.Beta.Organization.Federation.Issuers.Get(ctx context.Context, federationIssuerID string, query anthropic.BetaOrganizationFederationIssuerGetParams) (\*anthropic.BetaFederationIssuer, error) +- client.Beta.Organization.Federation.Issuers.Update(ctx context.Context, federationIssuerID string, params anthropic.BetaOrganizationFederationIssuerUpdateParams) (\*anthropic.BetaFederationIssuer, error) +- client.Beta.Organization.Federation.Issuers.List(ctx context.Context, params anthropic.BetaOrganizationFederationIssuerListParams) (\*pagination.PageCursor[anthropic.BetaFederationIssuer], error) +- client.Beta.Organization.Federation.Issuers.Archive(ctx context.Context, federationIssuerID string, body anthropic.BetaOrganizationFederationIssuerArchiveParams) (\*anthropic.BetaFederationIssuer, error) + +#### Rules + +Params Types: + +- anthropic.BetaFederationRuleMatchParam +- anthropic.BetaServiceAccountTargetParam + +Response Types: + +- anthropic.BetaFederationRule +- anthropic.BetaFederationRuleMatch +- anthropic.BetaFederationRuleWorkspace +- anthropic.BetaServiceAccountTarget + +Methods: + +- client.Beta.Organization.Federation.Rules.New(ctx context.Context, params anthropic.BetaOrganizationFederationRuleNewParams) (\*anthropic.BetaFederationRule, error) +- client.Beta.Organization.Federation.Rules.Get(ctx context.Context, federationRuleID string, query anthropic.BetaOrganizationFederationRuleGetParams) (\*anthropic.BetaFederationRule, error) +- client.Beta.Organization.Federation.Rules.Update(ctx context.Context, federationRuleID string, params anthropic.BetaOrganizationFederationRuleUpdateParams) (\*anthropic.BetaFederationRule, error) +- client.Beta.Organization.Federation.Rules.List(ctx context.Context, params anthropic.BetaOrganizationFederationRuleListParams) (\*pagination.PageCursor[anthropic.BetaFederationRule], error) +- client.Beta.Organization.Federation.Rules.Archive(ctx context.Context, federationRuleID string, body anthropic.BetaOrganizationFederationRuleArchiveParams) (\*anthropic.BetaFederationRule, error) + +##### Workspaces + +Response Types: + +- anthropic.BetaOrganizationFederationRuleWorkspaceRemoveResponse + +Methods: + +- client.Beta.Organization.Federation.Rules.Workspaces.List(ctx context.Context, federationRuleID string, params anthropic.BetaOrganizationFederationRuleWorkspaceListParams) (\*pagination.PageCursor[anthropic.BetaFederationRuleWorkspace], error) +- client.Beta.Organization.Federation.Rules.Workspaces.Add(ctx context.Context, federationRuleID string, params anthropic.BetaOrganizationFederationRuleWorkspaceAddParams) (\*anthropic.BetaFederationRuleWorkspace, error) +- client.Beta.Organization.Federation.Rules.Workspaces.Remove(ctx context.Context, workspaceID string, params anthropic.BetaOrganizationFederationRuleWorkspaceRemoveParams) (\*anthropic.BetaOrganizationFederationRuleWorkspaceRemoveResponse, error) + +### Invites + +Response Types: + +- anthropic.BetaOrganizationInvite +- anthropic.BetaOrganizationInviteDeleteResponse + +Methods: + +- client.Beta.Organization.Invites.New(ctx context.Context, body anthropic.BetaOrganizationInviteNewParams) (\*anthropic.BetaOrganizationInvite, error) +- client.Beta.Organization.Invites.Get(ctx context.Context, inviteID string) (\*anthropic.BetaOrganizationInvite, error) +- client.Beta.Organization.Invites.List(ctx context.Context, query anthropic.BetaOrganizationInviteListParams) (\*pagination.Page[anthropic.BetaOrganizationInvite], error) +- client.Beta.Organization.Invites.Delete(ctx context.Context, inviteID string) (\*anthropic.BetaOrganizationInviteDeleteResponse, error) + +### ServiceAccounts + +Response Types: + +- anthropic.BetaServiceAccount +- anthropic.BetaServiceAccountWorkspaceMember + +Methods: + +- client.Beta.Organization.ServiceAccounts.New(ctx context.Context, params anthropic.BetaOrganizationServiceAccountNewParams) (\*anthropic.BetaServiceAccount, error) +- client.Beta.Organization.ServiceAccounts.Get(ctx context.Context, serviceAccountID string, query anthropic.BetaOrganizationServiceAccountGetParams) (\*anthropic.BetaServiceAccount, error) +- client.Beta.Organization.ServiceAccounts.Update(ctx context.Context, serviceAccountID string, params anthropic.BetaOrganizationServiceAccountUpdateParams) (\*anthropic.BetaServiceAccount, error) +- client.Beta.Organization.ServiceAccounts.List(ctx context.Context, params anthropic.BetaOrganizationServiceAccountListParams) (\*pagination.PageCursor[anthropic.BetaServiceAccount], error) +- client.Beta.Organization.ServiceAccounts.Archive(ctx context.Context, serviceAccountID string, body anthropic.BetaOrganizationServiceAccountArchiveParams) (\*anthropic.BetaServiceAccount, error) + +#### Workspaces + +Response Types: + +- anthropic.BetaOrganizationServiceAccountWorkspaceRemoveResponse + +Methods: + +- client.Beta.Organization.ServiceAccounts.Workspaces.List(ctx context.Context, serviceAccountID string, params anthropic.BetaOrganizationServiceAccountWorkspaceListParams) (\*pagination.PageCursor[anthropic.BetaServiceAccountWorkspaceMember], error) +- client.Beta.Organization.ServiceAccounts.Workspaces.Add(ctx context.Context, serviceAccountID string, params anthropic.BetaOrganizationServiceAccountWorkspaceAddParams) (\*anthropic.BetaServiceAccountWorkspaceMember, error) +- client.Beta.Organization.ServiceAccounts.Workspaces.Remove(ctx context.Context, workspaceID string, params anthropic.BetaOrganizationServiceAccountWorkspaceRemoveParams) (\*anthropic.BetaOrganizationServiceAccountWorkspaceRemoveResponse, error) + +### Users + +Response Types: + +- anthropic.BetaOrganizationUser +- anthropic.BetaOrganizationUserRemoveResponse + +Methods: + +- client.Beta.Organization.Users.Get(ctx context.Context, userID string) (\*anthropic.BetaOrganizationUser, error) +- client.Beta.Organization.Users.Update(ctx context.Context, userID string, body anthropic.BetaOrganizationUserUpdateParams) (\*anthropic.BetaOrganizationUser, error) +- client.Beta.Organization.Users.List(ctx context.Context, query anthropic.BetaOrganizationUserListParams) (\*pagination.Page[anthropic.BetaOrganizationUser], error) +- client.Beta.Organization.Users.Remove(ctx context.Context, userID string) (\*anthropic.BetaOrganizationUserRemoveResponse, error) + +### Workspaces + +Params Types: + +- anthropic.BetaAllowedInferenceGeo +- anthropic.BetaDataResidencyCreateConfigParam +- anthropic.BetaDataResidencyUpdateConfigParam +- anthropic.BetaNoBillingWorkspaceRole +- anthropic.BetaWorkspaceRole + +Response Types: + +- anthropic.BetaDataResidency +- anthropic.BetaWorkspace +- anthropic.BetaWorkspaceMember +- anthropic.BetaWorkspaceRole + +Methods: + +- client.Beta.Organization.Workspaces.New(ctx context.Context, params anthropic.BetaOrganizationWorkspaceNewParams) (\*anthropic.BetaWorkspace, error) +- client.Beta.Organization.Workspaces.Get(ctx context.Context, workspaceID string) (\*anthropic.BetaWorkspace, error) +- client.Beta.Organization.Workspaces.Update(ctx context.Context, workspaceID string, body anthropic.BetaOrganizationWorkspaceUpdateParams) (\*anthropic.BetaWorkspace, error) +- client.Beta.Organization.Workspaces.List(ctx context.Context, query anthropic.BetaOrganizationWorkspaceListParams) (\*pagination.Page[anthropic.BetaWorkspace], error) +- client.Beta.Organization.Workspaces.Archive(ctx context.Context, workspaceID string) (\*anthropic.BetaWorkspace, error) + +#### RateLimits + +Response Types: + +- anthropic.BetaWorkspaceRateLimit +- anthropic.BetaWorkspaceRateLimitValue + +Methods: + +- client.Beta.Organization.Workspaces.RateLimits.List(ctx context.Context, workspaceID string, query anthropic.BetaOrganizationWorkspaceRateLimitListParams) (\*pagination.PageCursor[anthropic.BetaWorkspaceRateLimit], error) + +#### Members + +Response Types: + +- anthropic.BetaOrganizationWorkspaceMemberRemoveResponse + +Methods: + +- client.Beta.Organization.Workspaces.Members.Get(ctx context.Context, userID string, query anthropic.BetaOrganizationWorkspaceMemberGetParams) (\*anthropic.BetaWorkspaceMember, error) +- client.Beta.Organization.Workspaces.Members.Update(ctx context.Context, userID string, params anthropic.BetaOrganizationWorkspaceMemberUpdateParams) (\*anthropic.BetaWorkspaceMember, error) +- client.Beta.Organization.Workspaces.Members.List(ctx context.Context, workspaceID string, query anthropic.BetaOrganizationWorkspaceMemberListParams) (\*pagination.Page[anthropic.BetaWorkspaceMember], error) +- client.Beta.Organization.Workspaces.Members.Add(ctx context.Context, workspaceID string, body anthropic.BetaOrganizationWorkspaceMemberAddParams) (\*anthropic.BetaWorkspaceMember, error) +- client.Beta.Organization.Workspaces.Members.Remove(ctx context.Context, userID string, body anthropic.BetaOrganizationWorkspaceMemberRemoveParams) (\*anthropic.BetaOrganizationWorkspaceMemberRemoveResponse, error) + +#### ServiceAccounts + +Response Types: + +- anthropic.BetaOrganizationWorkspaceServiceAccountRemoveResponse + +Methods: + +- client.Beta.Organization.Workspaces.ServiceAccounts.Get(ctx context.Context, serviceAccountID string, params anthropic.BetaOrganizationWorkspaceServiceAccountGetParams) (\*anthropic.BetaServiceAccountWorkspaceMember, error) +- client.Beta.Organization.Workspaces.ServiceAccounts.Update(ctx context.Context, serviceAccountID string, params anthropic.BetaOrganizationWorkspaceServiceAccountUpdateParams) (\*anthropic.BetaServiceAccountWorkspaceMember, error) +- client.Beta.Organization.Workspaces.ServiceAccounts.List(ctx context.Context, workspaceID string, params anthropic.BetaOrganizationWorkspaceServiceAccountListParams) (\*pagination.PageCursor[anthropic.BetaServiceAccountWorkspaceMember], error) +- client.Beta.Organization.Workspaces.ServiceAccounts.Add(ctx context.Context, workspaceID string, params anthropic.BetaOrganizationWorkspaceServiceAccountAddParams) (\*anthropic.BetaServiceAccountWorkspaceMember, error) +- client.Beta.Organization.Workspaces.ServiceAccounts.Remove(ctx context.Context, serviceAccountID string, params anthropic.BetaOrganizationWorkspaceServiceAccountRemoveParams) (\*anthropic.BetaOrganizationWorkspaceServiceAccountRemoveResponse, error) + +### RateLimits + +Response Types: + +- anthropic.BetaOrganizationRateLimit +- anthropic.BetaOrganizationRateLimitValue + +Methods: + +- client.Beta.Organization.RateLimits.List(ctx context.Context, query anthropic.BetaOrganizationRateLimitListParams) (\*pagination.PageCursor[anthropic.BetaOrganizationRateLimit], error) diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/beta.go b/vendor/github.com/anthropics/anthropic-sdk-go/beta.go index 4bf0bdd0e..cafc1325b 100644 --- a/vendor/github.com/anthropics/anthropic-sdk-go/beta.go +++ b/vendor/github.com/anthropics/anthropic-sdk-go/beta.go @@ -7,6 +7,7 @@ import ( "github.com/anthropics/anthropic-sdk-go/internal/apijson" "github.com/anthropics/anthropic-sdk-go/option" + "github.com/anthropics/anthropic-sdk-go/packages/param" "github.com/anthropics/anthropic-sdk-go/packages/respjson" "github.com/anthropics/anthropic-sdk-go/shared/constant" ) @@ -18,16 +19,23 @@ import ( // automatically. You should not instantiate this service directly, and instead use // the [NewBetaService] method instead. type BetaService struct { - Options []option.RequestOption - Models BetaModelService - Messages BetaMessageService - Agents BetaAgentService - Environments BetaEnvironmentService - Sessions BetaSessionService - Vaults BetaVaultService - Files BetaFileService - Skills BetaSkillService - UserProfiles BetaUserProfileService + Options []option.RequestOption + Models BetaModelService + Messages BetaMessageService + Agents BetaAgentService + Environments BetaEnvironmentService + Sessions BetaSessionService + Deployments BetaDeploymentService + DeploymentRuns BetaDeploymentRunService + Vaults BetaVaultService + MemoryStores BetaMemoryStoreService + Files BetaFileService + Skills BetaSkillService + Webhooks BetaWebhookService + UserProfiles BetaUserProfileService + Dreams BetaDreamService + Tunnels BetaTunnelService + Organization BetaOrganizationService } // NewBetaService generates a new service that applies the given options to each @@ -41,10 +49,17 @@ func NewBetaService(opts ...option.RequestOption) (r BetaService) { r.Agents = NewBetaAgentService(opts...) r.Environments = NewBetaEnvironmentService(opts...) r.Sessions = NewBetaSessionService(opts...) + r.Deployments = NewBetaDeploymentService(opts...) + r.DeploymentRuns = NewBetaDeploymentRunService(opts...) r.Vaults = NewBetaVaultService(opts...) + r.MemoryStores = NewBetaMemoryStoreService(opts...) r.Files = NewBetaFileService(opts...) r.Skills = NewBetaSkillService(opts...) + r.Webhooks = NewBetaWebhookService(opts...) r.UserProfiles = NewBetaUserProfileService(opts...) + r.Dreams = NewBetaDreamService(opts...) + r.Tunnels = NewBetaTunnelService(opts...) + r.Organization = NewBetaOrganizationService(opts...) return } @@ -72,8 +87,26 @@ const ( AnthropicBetaSkills2025_10_02 AnthropicBeta = "skills-2025-10-02" AnthropicBetaFastMode2026_02_01 AnthropicBeta = "fast-mode-2026-02-01" AnthropicBetaOutput300k2026_03_24 AnthropicBeta = "output-300k-2026-03-24" - AnthropicBetaAdvisorTool2026_03_01 AnthropicBeta = "advisor-tool-2026-03-01" AnthropicBetaUserProfiles2026_03_24 AnthropicBeta = "user-profiles-2026-03-24" + AnthropicBetaUserProfiles2026_08_18 AnthropicBeta = "user-profiles-2026-08-18" + AnthropicBetaAdvisorTool2026_03_01 AnthropicBeta = "advisor-tool-2026-03-01" + AnthropicBetaManagedAgents2026_04_01 AnthropicBeta = "managed-agents-2026-04-01" + AnthropicBetaCacheDiagnosis2026_04_07 AnthropicBeta = "cache-diagnosis-2026-04-07" + AnthropicBetaDreaming2026_04_21 AnthropicBeta = "dreaming-2026-04-21" + AnthropicBetaThinkingTokenCount2026_05_13 AnthropicBeta = "thinking-token-count-2026-05-13" + AnthropicBetaServerSideFallback2026_06_01 AnthropicBeta = "server-side-fallback-2026-06-01" + AnthropicBetaServerSideFallback2026_07_01 AnthropicBeta = "server-side-fallback-2026-07-01" + AnthropicBetaFallbackCredit2026_06_01 AnthropicBeta = "fallback-credit-2026-06-01" + AnthropicBetaFallbackCredit2026_07_01 AnthropicBeta = "fallback-credit-2026-07-01" + AnthropicBetaAgentMemory2026_07_22 AnthropicBeta = "agent-memory-2026-07-22" + AnthropicBetaMidConversationToolChanges2026_07_01 AnthropicBeta = "mid-conversation-tool-changes-2026-07-01" + AnthropicBetaCompact2026_01_12 AnthropicBeta = "compact-2026-01-12" + AnthropicBetaComputerUse2025_11_24 AnthropicBeta = "computer-use-2025-11-24" + AnthropicBetaMCPTunnels2026_06_22 AnthropicBeta = "mcp-tunnels-2026-06-22" + AnthropicBetaStructuredOutputs2025_11_13 AnthropicBeta = "structured-outputs-2025-11-13" + AnthropicBetaTaskBudgets2026_03_13 AnthropicBeta = "task-budgets-2026-03-13" + AnthropicBetaThinkingDisplayUpdates2026_08_18 AnthropicBeta = "thinking-display-updates-2026-08-18" + AnthropicBetaCEUserManagement2026_07_13 AnthropicBeta = "ce-user-management-2026-07-13" ) type BetaAPIError struct { @@ -130,6 +163,12 @@ func (r *BetaBillingError) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } +type BetaCurrency string + +const ( + BetaCurrencyUSD BetaCurrency = "USD" +) + // BetaErrorUnion contains all possible properties and values from // [BetaInvalidRequestError], [BetaAuthenticationError], [BetaBillingError], // [BetaPermissionError], [BetaNotFoundError], [BetaRateLimitError], @@ -314,6 +353,67 @@ func (r *BetaInvalidRequestError) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } +// A monetary amount in a specific currency. +type BetaMonetaryAmount struct { + // Amount in minor units of the currency, as an integer decimal string with no + // leading zeros: "2500" is $25.00 and "50" is fifty cents. A string rather than a + // number so no float rounding is ever applied. + Amount string `json:"amount" api:"required"` + // Uppercase ISO-4217 currency code. `USD` is the only currency currently + // supported; the accepted set is closed and grows only when a new currency is + // priced. + // + // Any of "USD". + Currency BetaCurrency `json:"currency" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Amount respjson.Field + Currency respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaMonetaryAmount) RawJSON() string { return r.JSON.raw } +func (r *BetaMonetaryAmount) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// ToParam converts this BetaMonetaryAmount to a BetaMonetaryAmountParam. +// +// Warning: the fields of the param type will not be present. ToParam should only +// be used at the last possible moment before sending a request. Test for this with +// BetaMonetaryAmountParam.Overrides() +func (r BetaMonetaryAmount) ToParam() BetaMonetaryAmountParam { + return param.Override[BetaMonetaryAmountParam](json.RawMessage(r.RawJSON())) +} + +// A monetary amount in a specific currency. +// +// The properties Amount, Currency are required. +type BetaMonetaryAmountParam struct { + // Amount in minor units of the currency, as an integer decimal string with no + // leading zeros: "2500" is $25.00 and "50" is fifty cents. A string rather than a + // number so no float rounding is ever applied. + Amount string `json:"amount" api:"required"` + // Uppercase ISO-4217 currency code. `USD` is the only currency currently + // supported; the accepted set is closed and grows only when a new currency is + // priced. + // + // Any of "USD". + Currency BetaCurrency `json:"currency,omitzero" api:"required"` + paramObj +} + +func (r BetaMonetaryAmountParam) MarshalJSON() (data []byte, err error) { + type shadow BetaMonetaryAmountParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaMonetaryAmountParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + type BetaNotFoundError struct { Message string `json:"message" api:"required"` Type constant.NotFoundError `json:"type" default:"not_found_error"` diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/betaagent.go b/vendor/github.com/anthropics/anthropic-sdk-go/betaagent.go index 81adb56e7..6d1ac48d1 100644 --- a/vendor/github.com/anthropics/anthropic-sdk-go/betaagent.go +++ b/vendor/github.com/anthropics/anthropic-sdk-go/betaagent.go @@ -20,6 +20,7 @@ import ( "github.com/anthropics/anthropic-sdk-go/packages/pagination" "github.com/anthropics/anthropic-sdk-go/packages/param" "github.com/anthropics/anthropic-sdk-go/packages/respjson" + "github.com/anthropics/anthropic-sdk-go/shared/constant" ) // BetaAgentService contains methods and other services that help with interacting @@ -129,6 +130,34 @@ func (r *BetaAgentService) Archive(ctx context.Context, agentID string, body Bet return res, err } +// Platform advisor roster entry: a model the session's primary thread may consult +// mid-turn. +type BetaManagedAgentsAdvisor struct { + // The advisor model id. + Model string `json:"model" api:"required"` + // Any of "advisor". + Type BetaManagedAgentsAdvisorType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Model respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsAdvisor) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsAdvisor) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsAdvisorType string + +const ( + BetaManagedAgentsAdvisorTypeAdvisor BetaManagedAgentsAdvisorType = "advisor" +) + // A Managed Agents `agent`. type BetaManagedAgentsAgent struct { ID string `json:"id" api:"required"` @@ -140,11 +169,13 @@ type BetaManagedAgentsAgent struct { MCPServers []BetaManagedAgentsMCPServerURLDefinition `json:"mcp_servers" api:"required"` Metadata map[string]string `json:"metadata" api:"required"` // Model identifier and configuration. - Model BetaManagedAgentsModelConfig `json:"model" api:"required"` - Name string `json:"name" api:"required"` - Skills []BetaManagedAgentsAgentSkillUnion `json:"skills" api:"required"` - System string `json:"system" api:"required"` - Tools []BetaManagedAgentsAgentToolUnion `json:"tools" api:"required"` + Model BetaManagedAgentsModelConfig `json:"model" api:"required"` + // Resolved coordinator topology with a concrete agent roster. + Multiagent BetaManagedAgentsMultiagent `json:"multiagent" api:"required"` + Name string `json:"name" api:"required"` + Skills []BetaManagedAgentsAgentSkillUnion `json:"skills" api:"required"` + System string `json:"system" api:"required"` + Tools []BetaManagedAgentsAgentToolUnion `json:"tools" api:"required"` // Any of "agent". Type BetaManagedAgentsAgentType `json:"type" api:"required"` // A timestamp in RFC 3339 format @@ -161,6 +192,7 @@ type BetaManagedAgentsAgent struct { MCPServers respjson.Field Metadata respjson.Field Model respjson.Field + Multiagent respjson.Field Name respjson.Field Skills respjson.Field System respjson.Field @@ -252,7 +284,7 @@ func (r *BetaManagedAgentsAgentSkillUnion) UnmarshalJSON(data []byte) error { // // Use the methods beginning with 'As' to cast the union to one of its variants. type BetaManagedAgentsAgentToolUnion struct { - // This field is a union of [[]BetaManagedAgentsAgentToolConfig], + // This field is a union of [[]BetaManagedAgentsAgentToolConfigUnion], // [[]BetaManagedAgentsMCPToolConfig] Configs BetaManagedAgentsAgentToolUnionConfigs `json:"configs"` // This field is a union of [BetaManagedAgentsAgentToolsetDefaultConfig], @@ -346,8 +378,8 @@ func (r *BetaManagedAgentsAgentToolUnion) UnmarshalJSON(data []byte) error { // OfBetaManagedAgentsMCPToolConfigArray] type BetaManagedAgentsAgentToolUnionConfigs struct { // This field will be present if the value is a - // [[]BetaManagedAgentsAgentToolConfig] instead of an object. - OfBetaManagedAgentsAgentToolConfigArray []BetaManagedAgentsAgentToolConfig `json:",inline"` + // [[]BetaManagedAgentsAgentToolConfigUnion] instead of an object. + OfBetaManagedAgentsAgentToolConfigArray []BetaManagedAgentsAgentToolConfigUnion `json:",inline"` // This field will be present if the value is a [[]BetaManagedAgentsMCPToolConfig] // instead of an object. OfBetaManagedAgentsMCPToolConfigArray []BetaManagedAgentsMCPToolConfig `json:",inline"` @@ -410,189 +442,423 @@ const ( BetaManagedAgentsAgentTypeAgent BetaManagedAgentsAgentType = "agent" ) -// Configuration for a specific agent tool. -type BetaManagedAgentsAgentToolConfig struct { - Enabled bool `json:"enabled" api:"required"` - // Built-in agent tool identifier. - // - // Any of "bash", "edit", "read", "write", "glob", "grep", "web_fetch", - // "web_search". - Name BetaManagedAgentsAgentToolConfigName `json:"name" api:"required"` - // Permission policy for tool execution. - PermissionPolicy BetaManagedAgentsAgentToolConfigPermissionPolicyUnion `json:"permission_policy" api:"required"` +// A resolved agent reference with a concrete version. +type BetaManagedAgentsAgentReference struct { + ID string `json:"id" api:"required"` + // Any of "agent". + Type BetaManagedAgentsAgentReferenceType `json:"type" api:"required"` + Version int64 `json:"version" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { - Enabled respjson.Field - Name respjson.Field - PermissionPolicy respjson.Field - ExtraFields map[string]respjson.Field - raw string + ID respjson.Field + Type respjson.Field + Version respjson.Field + ExtraFields map[string]respjson.Field + raw string } `json:"-"` } // Returns the unmodified JSON received from the API -func (r BetaManagedAgentsAgentToolConfig) RawJSON() string { return r.JSON.raw } -func (r *BetaManagedAgentsAgentToolConfig) UnmarshalJSON(data []byte) error { +func (r BetaManagedAgentsAgentReference) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsAgentReference) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// Built-in agent tool identifier. -type BetaManagedAgentsAgentToolConfigName string +type BetaManagedAgentsAgentReferenceType string const ( - BetaManagedAgentsAgentToolConfigNameBash BetaManagedAgentsAgentToolConfigName = "bash" - BetaManagedAgentsAgentToolConfigNameEdit BetaManagedAgentsAgentToolConfigName = "edit" - BetaManagedAgentsAgentToolConfigNameRead BetaManagedAgentsAgentToolConfigName = "read" - BetaManagedAgentsAgentToolConfigNameWrite BetaManagedAgentsAgentToolConfigName = "write" - BetaManagedAgentsAgentToolConfigNameGlob BetaManagedAgentsAgentToolConfigName = "glob" - BetaManagedAgentsAgentToolConfigNameGrep BetaManagedAgentsAgentToolConfigName = "grep" - BetaManagedAgentsAgentToolConfigNameWebFetch BetaManagedAgentsAgentToolConfigName = "web_fetch" - BetaManagedAgentsAgentToolConfigNameWebSearch BetaManagedAgentsAgentToolConfigName = "web_search" + BetaManagedAgentsAgentReferenceTypeAgent BetaManagedAgentsAgentReferenceType = "agent" ) -// BetaManagedAgentsAgentToolConfigPermissionPolicyUnion contains all possible -// properties and values from [BetaManagedAgentsAlwaysAllowPolicy], -// [BetaManagedAgentsAlwaysAskPolicy]. +// BetaManagedAgentsAgentToolConfigUnion contains all possible properties and +// values from [BetaManagedAgentsBashToolConfig], +// [BetaManagedAgentsEditToolConfig], [BetaManagedAgentsReadToolConfig], +// [BetaManagedAgentsWriteToolConfig], [BetaManagedAgentsGlobToolConfig], +// [BetaManagedAgentsGrepToolConfig], [BetaManagedAgentsWebFetchToolConfig], +// [BetaManagedAgentsWebSearchToolConfig]. // -// Use the [BetaManagedAgentsAgentToolConfigPermissionPolicyUnion.AsAny] method to -// switch on the variant. +// Use the [BetaManagedAgentsAgentToolConfigUnion.AsAny] method to switch on the +// variant. // // Use the methods beginning with 'As' to cast the union to one of its variants. -type BetaManagedAgentsAgentToolConfigPermissionPolicyUnion struct { - // Any of "always_allow", "always_ask". - Type string `json:"type"` - JSON struct { - Type respjson.Field - raw string +type BetaManagedAgentsAgentToolConfigUnion struct { + Enabled bool `json:"enabled"` + Name string `json:"name"` + // This field is a union of [BetaManagedAgentsBashToolConfigPermissionPolicyUnion], + // [BetaManagedAgentsEditToolConfigPermissionPolicyUnion], + // [BetaManagedAgentsReadToolConfigPermissionPolicyUnion], + // [BetaManagedAgentsWriteToolConfigPermissionPolicyUnion], + // [BetaManagedAgentsGlobToolConfigPermissionPolicyUnion], + // [BetaManagedAgentsGrepToolConfigPermissionPolicyUnion], + // [BetaManagedAgentsWebFetchToolConfigPermissionPolicyUnion], + // [BetaManagedAgentsWebSearchToolConfigPermissionPolicyUnion] + PermissionPolicy BetaManagedAgentsAgentToolConfigUnionPermissionPolicy `json:"permission_policy"` + // Any of "bash", "edit", "read", "write", "glob", "grep", "web_fetch", + // "web_search". + Type string `json:"type"` + AllowedDomains []string `json:"allowed_domains"` + BlockedDomains []string `json:"blocked_domains"` + // This field is from variant [BetaManagedAgentsWebFetchToolConfig]. + MaxContentTokens int64 `json:"max_content_tokens"` + // This field is from variant [BetaManagedAgentsWebSearchToolConfig]. + UserLocation BetaManagedAgentsUserLocation `json:"user_location"` + JSON struct { + Enabled respjson.Field + Name respjson.Field + PermissionPolicy respjson.Field + Type respjson.Field + AllowedDomains respjson.Field + BlockedDomains respjson.Field + MaxContentTokens respjson.Field + UserLocation respjson.Field + raw string } `json:"-"` } -// anyBetaManagedAgentsAgentToolConfigPermissionPolicy is implemented by each -// variant of [BetaManagedAgentsAgentToolConfigPermissionPolicyUnion] to add type -// safety for the return type of -// [BetaManagedAgentsAgentToolConfigPermissionPolicyUnion.AsAny] -type anyBetaManagedAgentsAgentToolConfigPermissionPolicy interface { - implBetaManagedAgentsAgentToolConfigPermissionPolicyUnion() +// anyBetaManagedAgentsAgentToolConfig is implemented by each variant of +// [BetaManagedAgentsAgentToolConfigUnion] to add type safety for the return type +// of [BetaManagedAgentsAgentToolConfigUnion.AsAny] +type anyBetaManagedAgentsAgentToolConfig interface { + implBetaManagedAgentsAgentToolConfigUnion() } -func (BetaManagedAgentsAlwaysAllowPolicy) implBetaManagedAgentsAgentToolConfigPermissionPolicyUnion() { -} -func (BetaManagedAgentsAlwaysAskPolicy) implBetaManagedAgentsAgentToolConfigPermissionPolicyUnion() {} +func (BetaManagedAgentsBashToolConfig) implBetaManagedAgentsAgentToolConfigUnion() {} +func (BetaManagedAgentsEditToolConfig) implBetaManagedAgentsAgentToolConfigUnion() {} +func (BetaManagedAgentsReadToolConfig) implBetaManagedAgentsAgentToolConfigUnion() {} +func (BetaManagedAgentsWriteToolConfig) implBetaManagedAgentsAgentToolConfigUnion() {} +func (BetaManagedAgentsGlobToolConfig) implBetaManagedAgentsAgentToolConfigUnion() {} +func (BetaManagedAgentsGrepToolConfig) implBetaManagedAgentsAgentToolConfigUnion() {} +func (BetaManagedAgentsWebFetchToolConfig) implBetaManagedAgentsAgentToolConfigUnion() {} +func (BetaManagedAgentsWebSearchToolConfig) implBetaManagedAgentsAgentToolConfigUnion() {} // Use the following switch statement to find the correct variant // -// switch variant := BetaManagedAgentsAgentToolConfigPermissionPolicyUnion.AsAny().(type) { -// case anthropic.BetaManagedAgentsAlwaysAllowPolicy: -// case anthropic.BetaManagedAgentsAlwaysAskPolicy: +// switch variant := BetaManagedAgentsAgentToolConfigUnion.AsAny().(type) { +// case anthropic.BetaManagedAgentsBashToolConfig: +// case anthropic.BetaManagedAgentsEditToolConfig: +// case anthropic.BetaManagedAgentsReadToolConfig: +// case anthropic.BetaManagedAgentsWriteToolConfig: +// case anthropic.BetaManagedAgentsGlobToolConfig: +// case anthropic.BetaManagedAgentsGrepToolConfig: +// case anthropic.BetaManagedAgentsWebFetchToolConfig: +// case anthropic.BetaManagedAgentsWebSearchToolConfig: // default: // fmt.Errorf("no variant present") // } -func (u BetaManagedAgentsAgentToolConfigPermissionPolicyUnion) AsAny() anyBetaManagedAgentsAgentToolConfigPermissionPolicy { +func (u BetaManagedAgentsAgentToolConfigUnion) AsAny() anyBetaManagedAgentsAgentToolConfig { switch u.Type { - case "always_allow": - return u.AsAlwaysAllow() - case "always_ask": - return u.AsAlwaysAsk() + case "bash": + return u.AsBash() + case "edit": + return u.AsEdit() + case "read": + return u.AsRead() + case "write": + return u.AsWrite() + case "glob": + return u.AsGlob() + case "grep": + return u.AsGrep() + case "web_fetch": + return u.AsWebFetch() + case "web_search": + return u.AsWebSearch() } return nil } -func (u BetaManagedAgentsAgentToolConfigPermissionPolicyUnion) AsAlwaysAllow() (v BetaManagedAgentsAlwaysAllowPolicy) { +func (u BetaManagedAgentsAgentToolConfigUnion) AsBash() (v BetaManagedAgentsBashToolConfig) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return } -func (u BetaManagedAgentsAgentToolConfigPermissionPolicyUnion) AsAlwaysAsk() (v BetaManagedAgentsAlwaysAskPolicy) { +func (u BetaManagedAgentsAgentToolConfigUnion) AsEdit() (v BetaManagedAgentsEditToolConfig) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return } -// Returns the unmodified JSON received from the API -func (u BetaManagedAgentsAgentToolConfigPermissionPolicyUnion) RawJSON() string { return u.JSON.raw } +func (u BetaManagedAgentsAgentToolConfigUnion) AsRead() (v BetaManagedAgentsReadToolConfig) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} -func (r *BetaManagedAgentsAgentToolConfigPermissionPolicyUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +func (u BetaManagedAgentsAgentToolConfigUnion) AsWrite() (v BetaManagedAgentsWriteToolConfig) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -// Configuration override for a specific tool within a toolset. -// -// The property Name is required. -type BetaManagedAgentsAgentToolConfigParams struct { - // Built-in agent tool identifier. - // - // Any of "bash", "edit", "read", "write", "glob", "grep", "web_fetch", - // "web_search". - Name BetaManagedAgentsAgentToolConfigParamsName `json:"name,omitzero" api:"required"` - // Whether this tool is enabled and available to Claude. Overrides the - // default_config setting. - Enabled param.Opt[bool] `json:"enabled,omitzero"` - // Permission policy for tool execution. - PermissionPolicy BetaManagedAgentsAgentToolConfigParamsPermissionPolicyUnion `json:"permission_policy,omitzero"` - paramObj +func (u BetaManagedAgentsAgentToolConfigUnion) AsGlob() (v BetaManagedAgentsGlobToolConfig) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -func (r BetaManagedAgentsAgentToolConfigParams) MarshalJSON() (data []byte, err error) { - type shadow BetaManagedAgentsAgentToolConfigParams - return param.MarshalObject(r, (*shadow)(&r)) +func (u BetaManagedAgentsAgentToolConfigUnion) AsGrep() (v BetaManagedAgentsGrepToolConfig) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsAgentToolConfigUnion) AsWebFetch() (v BetaManagedAgentsWebFetchToolConfig) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsAgentToolConfigUnion) AsWebSearch() (v BetaManagedAgentsWebSearchToolConfig) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -func (r *BetaManagedAgentsAgentToolConfigParams) UnmarshalJSON(data []byte) error { + +// Returns the unmodified JSON received from the API +func (u BetaManagedAgentsAgentToolConfigUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaManagedAgentsAgentToolConfigUnion) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// Built-in agent tool identifier. -type BetaManagedAgentsAgentToolConfigParamsName string +// BetaManagedAgentsAgentToolConfigUnionPermissionPolicy is an implicit subunion of +// [BetaManagedAgentsAgentToolConfigUnion]. +// BetaManagedAgentsAgentToolConfigUnionPermissionPolicy provides convenient access +// to the sub-properties of the union. +// +// For type safety it is recommended to directly use a variant of the +// [BetaManagedAgentsAgentToolConfigUnion]. +type BetaManagedAgentsAgentToolConfigUnionPermissionPolicy struct { + Type string `json:"type"` + JSON struct { + Type respjson.Field + raw string + } `json:"-"` +} -const ( - BetaManagedAgentsAgentToolConfigParamsNameBash BetaManagedAgentsAgentToolConfigParamsName = "bash" - BetaManagedAgentsAgentToolConfigParamsNameEdit BetaManagedAgentsAgentToolConfigParamsName = "edit" - BetaManagedAgentsAgentToolConfigParamsNameRead BetaManagedAgentsAgentToolConfigParamsName = "read" - BetaManagedAgentsAgentToolConfigParamsNameWrite BetaManagedAgentsAgentToolConfigParamsName = "write" - BetaManagedAgentsAgentToolConfigParamsNameGlob BetaManagedAgentsAgentToolConfigParamsName = "glob" - BetaManagedAgentsAgentToolConfigParamsNameGrep BetaManagedAgentsAgentToolConfigParamsName = "grep" - BetaManagedAgentsAgentToolConfigParamsNameWebFetch BetaManagedAgentsAgentToolConfigParamsName = "web_fetch" - BetaManagedAgentsAgentToolConfigParamsNameWebSearch BetaManagedAgentsAgentToolConfigParamsName = "web_search" -) +func (r *BetaManagedAgentsAgentToolConfigUnionPermissionPolicy) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} // Only one field can be non-zero. // // Use [param.IsOmitted] to confirm if a field is set. -type BetaManagedAgentsAgentToolConfigParamsPermissionPolicyUnion struct { - OfAlwaysAllow *BetaManagedAgentsAlwaysAllowPolicyParam `json:",omitzero,inline"` - OfAlwaysAsk *BetaManagedAgentsAlwaysAskPolicyParam `json:",omitzero,inline"` +type BetaManagedAgentsAgentToolConfigParamsUnion struct { + OfBash *BetaManagedAgentsBashToolConfigParams `json:",omitzero,inline"` + OfEdit *BetaManagedAgentsEditToolConfigParams `json:",omitzero,inline"` + OfRead *BetaManagedAgentsReadToolConfigParams `json:",omitzero,inline"` + OfWrite *BetaManagedAgentsWriteToolConfigParams `json:",omitzero,inline"` + OfGlob *BetaManagedAgentsGlobToolConfigParams `json:",omitzero,inline"` + OfGrep *BetaManagedAgentsGrepToolConfigParams `json:",omitzero,inline"` + OfWebFetch *BetaManagedAgentsWebFetchToolConfigParams `json:",omitzero,inline"` + OfWebSearch *BetaManagedAgentsWebSearchToolConfigParams `json:",omitzero,inline"` paramUnion } -func (u BetaManagedAgentsAgentToolConfigParamsPermissionPolicyUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfAlwaysAllow, u.OfAlwaysAsk) +func (u BetaManagedAgentsAgentToolConfigParamsUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfBash, + u.OfEdit, + u.OfRead, + u.OfWrite, + u.OfGlob, + u.OfGrep, + u.OfWebFetch, + u.OfWebSearch) } -func (u *BetaManagedAgentsAgentToolConfigParamsPermissionPolicyUnion) UnmarshalJSON(data []byte) error { +func (u *BetaManagedAgentsAgentToolConfigParamsUnion) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, u) } -func (u *BetaManagedAgentsAgentToolConfigParamsPermissionPolicyUnion) asAny() any { - if !param.IsOmitted(u.OfAlwaysAllow) { - return u.OfAlwaysAllow - } else if !param.IsOmitted(u.OfAlwaysAsk) { - return u.OfAlwaysAsk +func (u *BetaManagedAgentsAgentToolConfigParamsUnion) asAny() any { + if !param.IsOmitted(u.OfBash) { + return u.OfBash + } else if !param.IsOmitted(u.OfEdit) { + return u.OfEdit + } else if !param.IsOmitted(u.OfRead) { + return u.OfRead + } else if !param.IsOmitted(u.OfWrite) { + return u.OfWrite + } else if !param.IsOmitted(u.OfGlob) { + return u.OfGlob + } else if !param.IsOmitted(u.OfGrep) { + return u.OfGrep + } else if !param.IsOmitted(u.OfWebFetch) { + return u.OfWebFetch + } else if !param.IsOmitted(u.OfWebSearch) { + return u.OfWebSearch } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u BetaManagedAgentsAgentToolConfigParamsPermissionPolicyUnion) GetType() *string { - if vt := u.OfAlwaysAllow; vt != nil { +func (u BetaManagedAgentsAgentToolConfigParamsUnion) GetMaxContentTokens() *int64 { + if vt := u.OfWebFetch; vt != nil && vt.MaxContentTokens.Valid() { + return &vt.MaxContentTokens.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaManagedAgentsAgentToolConfigParamsUnion) GetUserLocation() *BetaManagedAgentsUserLocationParam { + if vt := u.OfWebSearch; vt != nil { + return &vt.UserLocation + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaManagedAgentsAgentToolConfigParamsUnion) GetName() *string { + if vt := u.OfBash; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfEdit; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfRead; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfWrite; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfGlob; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfGrep; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfWebFetch; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfWebSearch; vt != nil { + return (*string)(&vt.Name) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaManagedAgentsAgentToolConfigParamsUnion) GetEnabled() *bool { + if vt := u.OfBash; vt != nil && vt.Enabled.Valid() { + return &vt.Enabled.Value + } else if vt := u.OfEdit; vt != nil && vt.Enabled.Valid() { + return &vt.Enabled.Value + } else if vt := u.OfRead; vt != nil && vt.Enabled.Valid() { + return &vt.Enabled.Value + } else if vt := u.OfWrite; vt != nil && vt.Enabled.Valid() { + return &vt.Enabled.Value + } else if vt := u.OfGlob; vt != nil && vt.Enabled.Valid() { + return &vt.Enabled.Value + } else if vt := u.OfGrep; vt != nil && vt.Enabled.Valid() { + return &vt.Enabled.Value + } else if vt := u.OfWebFetch; vt != nil && vt.Enabled.Valid() { + return &vt.Enabled.Value + } else if vt := u.OfWebSearch; vt != nil && vt.Enabled.Valid() { + return &vt.Enabled.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaManagedAgentsAgentToolConfigParamsUnion) GetType() *string { + if vt := u.OfBash; vt != nil { return (*string)(&vt.Type) - } else if vt := u.OfAlwaysAsk; vt != nil { + } else if vt := u.OfEdit; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfRead; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfWrite; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfGlob; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfGrep; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfWebFetch; vt != nil { return (*string)(&vt.Type) + } else if vt := u.OfWebSearch; vt != nil { + return (*string)(&vt.Type) + } + return nil +} + +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u BetaManagedAgentsAgentToolConfigParamsUnion) GetPermissionPolicy() (res betaManagedAgentsAgentToolConfigParamsUnionPermissionPolicy) { + if vt := u.OfBash; vt != nil { + res.any = vt.PermissionPolicy.asAny() + } else if vt := u.OfEdit; vt != nil { + res.any = vt.PermissionPolicy.asAny() + } else if vt := u.OfRead; vt != nil { + res.any = vt.PermissionPolicy.asAny() + } else if vt := u.OfWrite; vt != nil { + res.any = vt.PermissionPolicy.asAny() + } else if vt := u.OfGlob; vt != nil { + res.any = vt.PermissionPolicy.asAny() + } else if vt := u.OfGrep; vt != nil { + res.any = vt.PermissionPolicy.asAny() + } else if vt := u.OfWebFetch; vt != nil { + res.any = vt.PermissionPolicy.asAny() + } else if vt := u.OfWebSearch; vt != nil { + res.any = vt.PermissionPolicy.asAny() + } + return +} + +// Can have the runtime types [*BetaManagedAgentsAlwaysAllowPolicyParam], +// [*BetaManagedAgentsAlwaysAskPolicyParam] +type betaManagedAgentsAgentToolConfigParamsUnionPermissionPolicy struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BetaManagedAgentsAlwaysAllowPolicyParam: +// case *anthropic.BetaManagedAgentsAlwaysAskPolicyParam: +// default: +// fmt.Errorf("not present") +// } +func (u betaManagedAgentsAgentToolConfigParamsUnionPermissionPolicy) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u betaManagedAgentsAgentToolConfigParamsUnionPermissionPolicy) GetType() *string { + switch vt := u.any.(type) { + case *BetaManagedAgentsBashToolConfigParamsPermissionPolicyUnion: + return vt.GetType() + case *BetaManagedAgentsEditToolConfigParamsPermissionPolicyUnion: + return vt.GetType() + case *BetaManagedAgentsReadToolConfigParamsPermissionPolicyUnion: + return vt.GetType() + case *BetaManagedAgentsWriteToolConfigParamsPermissionPolicyUnion: + return vt.GetType() + case *BetaManagedAgentsGlobToolConfigParamsPermissionPolicyUnion: + return vt.GetType() + case *BetaManagedAgentsGrepToolConfigParamsPermissionPolicyUnion: + return vt.GetType() + case *BetaManagedAgentsWebFetchToolConfigParamsPermissionPolicyUnion: + return vt.GetType() + case *BetaManagedAgentsWebSearchToolConfigParamsPermissionPolicyUnion: + return vt.GetType() + } + return nil +} + +// Returns a pointer to the underlying variant's AllowedDomains property, if +// present. +func (u BetaManagedAgentsAgentToolConfigParamsUnion) GetAllowedDomains() []string { + if vt := u.OfWebFetch; vt != nil { + return vt.AllowedDomains + } else if vt := u.OfWebSearch; vt != nil { + return vt.AllowedDomains + } + return nil +} + +// Returns a pointer to the underlying variant's BlockedDomains property, if +// present. +func (u BetaManagedAgentsAgentToolConfigParamsUnion) GetBlockedDomains() []string { + if vt := u.OfWebFetch; vt != nil { + return vt.BlockedDomains + } else if vt := u.OfWebSearch; vt != nil { + return vt.BlockedDomains } return nil } func init() { - apijson.RegisterUnion[BetaManagedAgentsAgentToolConfigParamsPermissionPolicyUnion]( + apijson.RegisterUnion[BetaManagedAgentsAgentToolConfigParamsUnion]( "type", - apijson.Discriminator[BetaManagedAgentsAlwaysAllowPolicyParam]("always_allow"), - apijson.Discriminator[BetaManagedAgentsAlwaysAskPolicyParam]("always_ask"), + apijson.Discriminator[BetaManagedAgentsBashToolConfigParams]("bash"), + apijson.Discriminator[BetaManagedAgentsEditToolConfigParams]("edit"), + apijson.Discriminator[BetaManagedAgentsReadToolConfigParams]("read"), + apijson.Discriminator[BetaManagedAgentsWriteToolConfigParams]("write"), + apijson.Discriminator[BetaManagedAgentsGlobToolConfigParams]("glob"), + apijson.Discriminator[BetaManagedAgentsGrepToolConfigParams]("grep"), + apijson.Discriminator[BetaManagedAgentsWebFetchToolConfigParams]("web_fetch"), + apijson.Discriminator[BetaManagedAgentsWebSearchToolConfigParams]("web_search"), ) } @@ -746,7 +1012,7 @@ func init() { } type BetaManagedAgentsAgentToolset20260401 struct { - Configs []BetaManagedAgentsAgentToolConfig `json:"configs" api:"required"` + Configs []BetaManagedAgentsAgentToolConfigUnion `json:"configs" api:"required"` // Resolved default configuration for agent tools. DefaultConfig BetaManagedAgentsAgentToolsetDefaultConfig `json:"default_config" api:"required"` // Any of "agent_toolset_20260401". @@ -773,6 +1039,110 @@ const ( BetaManagedAgentsAgentToolset20260401TypeAgentToolset20260401 BetaManagedAgentsAgentToolset20260401Type = "agent_toolset_20260401" ) +// Input payload for the `bash` tool of the `agent_toolset_20260401` toolset. All +// fields are optional; a normal invocation supplies `command`, while +// `restart=true` (with no `command`) reboots the runner-side bash session. +type BetaManagedAgentsAgentToolset20260401BashInput struct { + // Shell command to execute. Omit only when `restart` is true. + Command string `json:"command"` + // When true, restart the persistent bash session instead of running a command. + // Subsequent calls without `restart` will run against the fresh session. + Restart bool `json:"restart"` + // Per-call timeout in milliseconds. Defaults to the runner-wide tool timeout when + // omitted or zero. + TimeoutMs int64 `json:"timeout_ms"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Command respjson.Field + Restart respjson.Field + TimeoutMs respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsAgentToolset20260401BashInput) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsAgentToolset20260401BashInput) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Input payload for the `edit` tool. Performs a string replacement in the named +// file; by default `old_string` must occur exactly once. +type BetaManagedAgentsAgentToolset20260401EditInput struct { + // Path of the file to edit. + FilePath string `json:"file_path" api:"required"` + // Replacement text. + NewString string `json:"new_string" api:"required"` + // Substring to find and replace. + OldString string `json:"old_string" api:"required"` + // When true, replace every occurrence of `old_string` instead of requiring a + // unique match. + ReplaceAll bool `json:"replace_all"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + FilePath respjson.Field + NewString respjson.Field + OldString respjson.Field + ReplaceAll respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsAgentToolset20260401EditInput) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsAgentToolset20260401EditInput) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Input payload for the `glob` tool. Returns paths matching a doublestar glob +// pattern, newest first. +type BetaManagedAgentsAgentToolset20260401GlobInput struct { + // Doublestar glob pattern (e.g. `**/*.go`). Absolute patterns are only permitted + // when the runner is configured to allow them. + Pattern string `json:"pattern" api:"required"` + // Optional directory root to search under. Defaults to the runner's working + // directory. + Path string `json:"path"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Pattern respjson.Field + Path respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsAgentToolset20260401GlobInput) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsAgentToolset20260401GlobInput) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Input payload for the `grep` tool. Searches file contents for a regular +// expression, returning matching lines. +type BetaManagedAgentsAgentToolset20260401GrepInput struct { + // Regular expression to search for. + Pattern string `json:"pattern" api:"required"` + // Optional directory root to search under. Defaults to the runner's working + // directory. + Path string `json:"path"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Pattern respjson.Field + Path respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsAgentToolset20260401GrepInput) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsAgentToolset20260401GrepInput) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + // Configuration for built-in agent tools. Use this to enable or disable groups of // tools available to the agent. // @@ -781,7 +1151,7 @@ type BetaManagedAgentsAgentToolset20260401Params struct { // Any of "agent_toolset_20260401". Type BetaManagedAgentsAgentToolset20260401ParamsType `json:"type,omitzero" api:"required"` // Per-tool configuration overrides. - Configs []BetaManagedAgentsAgentToolConfigParams `json:"configs,omitzero"` + Configs []BetaManagedAgentsAgentToolConfigParamsUnion `json:"configs,omitzero"` // Default configuration for all tools in a toolset. DefaultConfig BetaManagedAgentsAgentToolsetDefaultConfigParams `json:"default_config,omitzero"` paramObj @@ -801,6 +1171,51 @@ const ( BetaManagedAgentsAgentToolset20260401ParamsTypeAgentToolset20260401 BetaManagedAgentsAgentToolset20260401ParamsType = "agent_toolset_20260401" ) +// Input payload for the `read` tool. Reads file contents relative to the runner's +// working directory (or absolute when the runner permits). +type BetaManagedAgentsAgentToolset20260401ReadInput struct { + // Path of the file to read. + FilePath string `json:"file_path" api:"required"` + // Optional `[start_line, end_line]` 1-indexed inclusive range. When omitted the + // entire file is returned. `end_line` of 0 or negative means "to end of file". + ViewRange []int64 `json:"view_range"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + FilePath respjson.Field + ViewRange respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsAgentToolset20260401ReadInput) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsAgentToolset20260401ReadInput) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Input payload for the `write` tool. Writes (overwriting) the entire file +// contents. +type BetaManagedAgentsAgentToolset20260401WriteInput struct { + // Full file contents to write. + Content string `json:"content" api:"required"` + // Path of the file to write. + FilePath string `json:"file_path" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Content respjson.Field + FilePath respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsAgentToolset20260401WriteInput) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsAgentToolset20260401WriteInput) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + // Tool calls are automatically approved without user confirmation. type BetaManagedAgentsAlwaysAllowPolicy struct { // Any of "always_allow". @@ -958,17 +1373,180 @@ const ( BetaManagedAgentsAnthropicSkillParamsTypeAnthropic BetaManagedAgentsAnthropicSkillParamsType = "anthropic" ) -// A resolved user-created custom skill. -type BetaManagedAgentsCustomSkill struct { - SkillID string `json:"skill_id" api:"required"` - // Any of "custom". - Type BetaManagedAgentsCustomSkillType `json:"type" api:"required"` - Version string `json:"version" api:"required"` +// Configuration for the bash tool. +type BetaManagedAgentsBashToolConfig struct { + Enabled bool `json:"enabled" api:"required"` + Name constant.Bash `json:"name" default:"bash"` + // Permission policy for tool execution. + PermissionPolicy BetaManagedAgentsBashToolConfigPermissionPolicyUnion `json:"permission_policy" api:"required"` + Type constant.Bash `json:"type" default:"bash"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { - SkillID respjson.Field - Type respjson.Field - Version respjson.Field + Enabled respjson.Field + Name respjson.Field + PermissionPolicy respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsBashToolConfig) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsBashToolConfig) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaManagedAgentsBashToolConfigPermissionPolicyUnion contains all possible +// properties and values from [BetaManagedAgentsAlwaysAllowPolicy], +// [BetaManagedAgentsAlwaysAskPolicy]. +// +// Use the [BetaManagedAgentsBashToolConfigPermissionPolicyUnion.AsAny] method to +// switch on the variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaManagedAgentsBashToolConfigPermissionPolicyUnion struct { + // Any of "always_allow", "always_ask". + Type string `json:"type"` + JSON struct { + Type respjson.Field + raw string + } `json:"-"` +} + +// anyBetaManagedAgentsBashToolConfigPermissionPolicy is implemented by each +// variant of [BetaManagedAgentsBashToolConfigPermissionPolicyUnion] to add type +// safety for the return type of +// [BetaManagedAgentsBashToolConfigPermissionPolicyUnion.AsAny] +type anyBetaManagedAgentsBashToolConfigPermissionPolicy interface { + implBetaManagedAgentsBashToolConfigPermissionPolicyUnion() +} + +func (BetaManagedAgentsAlwaysAllowPolicy) implBetaManagedAgentsBashToolConfigPermissionPolicyUnion() { +} +func (BetaManagedAgentsAlwaysAskPolicy) implBetaManagedAgentsBashToolConfigPermissionPolicyUnion() {} + +// Use the following switch statement to find the correct variant +// +// switch variant := BetaManagedAgentsBashToolConfigPermissionPolicyUnion.AsAny().(type) { +// case anthropic.BetaManagedAgentsAlwaysAllowPolicy: +// case anthropic.BetaManagedAgentsAlwaysAskPolicy: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaManagedAgentsBashToolConfigPermissionPolicyUnion) AsAny() anyBetaManagedAgentsBashToolConfigPermissionPolicy { + switch u.Type { + case "always_allow": + return u.AsAlwaysAllow() + case "always_ask": + return u.AsAlwaysAsk() + } + return nil +} + +func (u BetaManagedAgentsBashToolConfigPermissionPolicyUnion) AsAlwaysAllow() (v BetaManagedAgentsAlwaysAllowPolicy) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsBashToolConfigPermissionPolicyUnion) AsAlwaysAsk() (v BetaManagedAgentsAlwaysAskPolicy) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u BetaManagedAgentsBashToolConfigPermissionPolicyUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaManagedAgentsBashToolConfigPermissionPolicyUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Configuration override for the bash tool. +// +// The property Name is required. +type BetaManagedAgentsBashToolConfigParams struct { + // Whether this tool is enabled and available to Claude. Overrides the + // default_config setting. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + // Permission policy for tool execution. + PermissionPolicy BetaManagedAgentsBashToolConfigParamsPermissionPolicyUnion `json:"permission_policy,omitzero"` + // Any of "bash". + Type BetaManagedAgentsBashToolConfigParamsType `json:"type,omitzero"` + // Must be "bash". + // + // This field can be elided, and will marshal its zero value as "bash". + Name constant.Bash `json:"name" default:"bash"` + paramObj +} + +func (r BetaManagedAgentsBashToolConfigParams) MarshalJSON() (data []byte, err error) { + type shadow BetaManagedAgentsBashToolConfigParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaManagedAgentsBashToolConfigParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaManagedAgentsBashToolConfigParamsPermissionPolicyUnion struct { + OfAlwaysAllow *BetaManagedAgentsAlwaysAllowPolicyParam `json:",omitzero,inline"` + OfAlwaysAsk *BetaManagedAgentsAlwaysAskPolicyParam `json:",omitzero,inline"` + paramUnion +} + +func (u BetaManagedAgentsBashToolConfigParamsPermissionPolicyUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfAlwaysAllow, u.OfAlwaysAsk) +} +func (u *BetaManagedAgentsBashToolConfigParamsPermissionPolicyUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *BetaManagedAgentsBashToolConfigParamsPermissionPolicyUnion) asAny() any { + if !param.IsOmitted(u.OfAlwaysAllow) { + return u.OfAlwaysAllow + } else if !param.IsOmitted(u.OfAlwaysAsk) { + return u.OfAlwaysAsk + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaManagedAgentsBashToolConfigParamsPermissionPolicyUnion) GetType() *string { + if vt := u.OfAlwaysAllow; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfAlwaysAsk; vt != nil { + return (*string)(&vt.Type) + } + return nil +} + +func init() { + apijson.RegisterUnion[BetaManagedAgentsBashToolConfigParamsPermissionPolicyUnion]( + "type", + apijson.Discriminator[BetaManagedAgentsAlwaysAllowPolicyParam]("always_allow"), + apijson.Discriminator[BetaManagedAgentsAlwaysAskPolicyParam]("always_ask"), + ) +} + +type BetaManagedAgentsBashToolConfigParamsType string + +const ( + BetaManagedAgentsBashToolConfigParamsTypeBash BetaManagedAgentsBashToolConfigParamsType = "bash" +) + +// A resolved user-created custom skill. +type BetaManagedAgentsCustomSkill struct { + SkillID string `json:"skill_id" api:"required"` + // Any of "custom". + Type BetaManagedAgentsCustomSkillType `json:"type" api:"required"` + Version string `json:"version" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + SkillID respjson.Field + Type respjson.Field + Version respjson.Field ExtraFields map[string]respjson.Field raw string } `json:"-"` @@ -1046,19 +1624,15 @@ const ( // JSON Schema for custom tool input parameters. type BetaManagedAgentsCustomToolInputSchema struct { - // JSON Schema properties defining the tool's input parameters. - Properties map[string]any `json:"properties" api:"nullable"` - // List of required property names. - Required []string `json:"required"` - // Must be 'object' for tool input schemas. - // - // Any of "object". - Type BetaManagedAgentsCustomToolInputSchemaType `json:"type"` + Type constant.Object `json:"type" default:"object"` + Properties map[string]any `json:"properties" api:"nullable"` + Required []string `json:"required" api:"nullable"` + ExtraFields map[string]any `json:"" api:"extrafields"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { + Type respjson.Field Properties respjson.Field Required respjson.Field - Type respjson.Field ExtraFields map[string]respjson.Field raw string } `json:"-"` @@ -1080,29 +1654,21 @@ func (r BetaManagedAgentsCustomToolInputSchema) ToParam() BetaManagedAgentsCusto return param.Override[BetaManagedAgentsCustomToolInputSchemaParam](json.RawMessage(r.RawJSON())) } -// Must be 'object' for tool input schemas. -type BetaManagedAgentsCustomToolInputSchemaType string - -const ( - BetaManagedAgentsCustomToolInputSchemaTypeObject BetaManagedAgentsCustomToolInputSchemaType = "object" -) - // JSON Schema for custom tool input parameters. +// +// The property Type is required. type BetaManagedAgentsCustomToolInputSchemaParam struct { - // JSON Schema properties defining the tool's input parameters. Properties map[string]any `json:"properties,omitzero"` - // List of required property names. - Required []string `json:"required,omitzero"` - // Must be 'object' for tool input schemas. - // - // Any of "object". - Type BetaManagedAgentsCustomToolInputSchemaType `json:"type,omitzero"` + Required []string `json:"required,omitzero"` + // This field can be elided, and will marshal its zero value as "object". + Type constant.Object `json:"type" default:"object"` + ExtraFields map[string]any `json:"-"` paramObj } func (r BetaManagedAgentsCustomToolInputSchemaParam) MarshalJSON() (data []byte, err error) { type shadow BetaManagedAgentsCustomToolInputSchemaParam - return param.MarshalObject(r, (*shadow)(&r)) + return param.MarshalWithExtras(r, (*shadow)(&r), r.ExtraFields) } func (r *BetaManagedAgentsCustomToolInputSchemaParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) @@ -1116,7 +1682,7 @@ func (r *BetaManagedAgentsCustomToolInputSchemaParam) UnmarshalJSON(data []byte) // The properties Description, InputSchema, Name, Type are required. type BetaManagedAgentsCustomToolParams struct { // Description of what the tool does, shown to the agent to help it decide when to - // use the tool. 1-1024 characters. + // use the tool. Description string `json:"description" api:"required"` // JSON Schema for custom tool input parameters. InputSchema BetaManagedAgentsCustomToolInputSchemaParam `json:"input_schema,omitzero" api:"required"` @@ -1142,65 +1708,39 @@ const ( BetaManagedAgentsCustomToolParamsTypeCustom BetaManagedAgentsCustomToolParamsType = "custom" ) -// URL-based MCP server connection as returned in API responses. -type BetaManagedAgentsMCPServerURLDefinition struct { - Name string `json:"name" api:"required"` - // Any of "url". - Type BetaManagedAgentsMCPServerURLDefinitionType `json:"type" api:"required"` - URL string `json:"url" api:"required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Name respjson.Field - Type respjson.Field - URL respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r BetaManagedAgentsMCPServerURLDefinition) RawJSON() string { return r.JSON.raw } -func (r *BetaManagedAgentsMCPServerURLDefinition) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type BetaManagedAgentsMCPServerURLDefinitionType string - -const ( - BetaManagedAgentsMCPServerURLDefinitionTypeURL BetaManagedAgentsMCPServerURLDefinitionType = "url" -) - -// Resolved configuration for a specific MCP tool. -type BetaManagedAgentsMCPToolConfig struct { - Enabled bool `json:"enabled" api:"required"` - Name string `json:"name" api:"required"` +// Configuration for the edit tool. +type BetaManagedAgentsEditToolConfig struct { + Enabled bool `json:"enabled" api:"required"` + Name constant.Edit `json:"name" default:"edit"` // Permission policy for tool execution. - PermissionPolicy BetaManagedAgentsMCPToolConfigPermissionPolicyUnion `json:"permission_policy" api:"required"` + PermissionPolicy BetaManagedAgentsEditToolConfigPermissionPolicyUnion `json:"permission_policy" api:"required"` + Type constant.Edit `json:"type" default:"edit"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { Enabled respjson.Field Name respjson.Field PermissionPolicy respjson.Field + Type respjson.Field ExtraFields map[string]respjson.Field raw string } `json:"-"` } // Returns the unmodified JSON received from the API -func (r BetaManagedAgentsMCPToolConfig) RawJSON() string { return r.JSON.raw } -func (r *BetaManagedAgentsMCPToolConfig) UnmarshalJSON(data []byte) error { +func (r BetaManagedAgentsEditToolConfig) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsEditToolConfig) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// BetaManagedAgentsMCPToolConfigPermissionPolicyUnion contains all possible +// BetaManagedAgentsEditToolConfigPermissionPolicyUnion contains all possible // properties and values from [BetaManagedAgentsAlwaysAllowPolicy], // [BetaManagedAgentsAlwaysAskPolicy]. // -// Use the [BetaManagedAgentsMCPToolConfigPermissionPolicyUnion.AsAny] method to +// Use the [BetaManagedAgentsEditToolConfigPermissionPolicyUnion.AsAny] method to // switch on the variant. // // Use the methods beginning with 'As' to cast the union to one of its variants. -type BetaManagedAgentsMCPToolConfigPermissionPolicyUnion struct { +type BetaManagedAgentsEditToolConfigPermissionPolicyUnion struct { // Any of "always_allow", "always_ask". Type string `json:"type"` JSON struct { @@ -1209,25 +1749,27 @@ type BetaManagedAgentsMCPToolConfigPermissionPolicyUnion struct { } `json:"-"` } -// anyBetaManagedAgentsMCPToolConfigPermissionPolicy is implemented by each variant -// of [BetaManagedAgentsMCPToolConfigPermissionPolicyUnion] to add type safety for -// the return type of [BetaManagedAgentsMCPToolConfigPermissionPolicyUnion.AsAny] -type anyBetaManagedAgentsMCPToolConfigPermissionPolicy interface { - implBetaManagedAgentsMCPToolConfigPermissionPolicyUnion() +// anyBetaManagedAgentsEditToolConfigPermissionPolicy is implemented by each +// variant of [BetaManagedAgentsEditToolConfigPermissionPolicyUnion] to add type +// safety for the return type of +// [BetaManagedAgentsEditToolConfigPermissionPolicyUnion.AsAny] +type anyBetaManagedAgentsEditToolConfigPermissionPolicy interface { + implBetaManagedAgentsEditToolConfigPermissionPolicyUnion() } -func (BetaManagedAgentsAlwaysAllowPolicy) implBetaManagedAgentsMCPToolConfigPermissionPolicyUnion() {} -func (BetaManagedAgentsAlwaysAskPolicy) implBetaManagedAgentsMCPToolConfigPermissionPolicyUnion() {} +func (BetaManagedAgentsAlwaysAllowPolicy) implBetaManagedAgentsEditToolConfigPermissionPolicyUnion() { +} +func (BetaManagedAgentsAlwaysAskPolicy) implBetaManagedAgentsEditToolConfigPermissionPolicyUnion() {} // Use the following switch statement to find the correct variant // -// switch variant := BetaManagedAgentsMCPToolConfigPermissionPolicyUnion.AsAny().(type) { +// switch variant := BetaManagedAgentsEditToolConfigPermissionPolicyUnion.AsAny().(type) { // case anthropic.BetaManagedAgentsAlwaysAllowPolicy: // case anthropic.BetaManagedAgentsAlwaysAskPolicy: // default: // fmt.Errorf("no variant present") // } -func (u BetaManagedAgentsMCPToolConfigPermissionPolicyUnion) AsAny() anyBetaManagedAgentsMCPToolConfigPermissionPolicy { +func (u BetaManagedAgentsEditToolConfigPermissionPolicyUnion) AsAny() anyBetaManagedAgentsEditToolConfigPermissionPolicy { switch u.Type { case "always_allow": return u.AsAlwaysAllow() @@ -1237,61 +1779,66 @@ func (u BetaManagedAgentsMCPToolConfigPermissionPolicyUnion) AsAny() anyBetaMana return nil } -func (u BetaManagedAgentsMCPToolConfigPermissionPolicyUnion) AsAlwaysAllow() (v BetaManagedAgentsAlwaysAllowPolicy) { +func (u BetaManagedAgentsEditToolConfigPermissionPolicyUnion) AsAlwaysAllow() (v BetaManagedAgentsAlwaysAllowPolicy) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return } -func (u BetaManagedAgentsMCPToolConfigPermissionPolicyUnion) AsAlwaysAsk() (v BetaManagedAgentsAlwaysAskPolicy) { +func (u BetaManagedAgentsEditToolConfigPermissionPolicyUnion) AsAlwaysAsk() (v BetaManagedAgentsAlwaysAskPolicy) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return } // Returns the unmodified JSON received from the API -func (u BetaManagedAgentsMCPToolConfigPermissionPolicyUnion) RawJSON() string { return u.JSON.raw } +func (u BetaManagedAgentsEditToolConfigPermissionPolicyUnion) RawJSON() string { return u.JSON.raw } -func (r *BetaManagedAgentsMCPToolConfigPermissionPolicyUnion) UnmarshalJSON(data []byte) error { +func (r *BetaManagedAgentsEditToolConfigPermissionPolicyUnion) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// Configuration override for a specific MCP tool. +// Configuration override for the edit tool. // // The property Name is required. -type BetaManagedAgentsMCPToolConfigParams struct { - // Name of the MCP tool to configure. 1-128 characters. - Name string `json:"name" api:"required"` - // Whether this tool is enabled. Overrides the `default_config` setting. +type BetaManagedAgentsEditToolConfigParams struct { + // Whether this tool is enabled and available to Claude. Overrides the + // default_config setting. Enabled param.Opt[bool] `json:"enabled,omitzero"` // Permission policy for tool execution. - PermissionPolicy BetaManagedAgentsMCPToolConfigParamsPermissionPolicyUnion `json:"permission_policy,omitzero"` + PermissionPolicy BetaManagedAgentsEditToolConfigParamsPermissionPolicyUnion `json:"permission_policy,omitzero"` + // Any of "edit". + Type BetaManagedAgentsEditToolConfigParamsType `json:"type,omitzero"` + // Must be "edit". + // + // This field can be elided, and will marshal its zero value as "edit". + Name constant.Edit `json:"name" default:"edit"` paramObj } -func (r BetaManagedAgentsMCPToolConfigParams) MarshalJSON() (data []byte, err error) { - type shadow BetaManagedAgentsMCPToolConfigParams +func (r BetaManagedAgentsEditToolConfigParams) MarshalJSON() (data []byte, err error) { + type shadow BetaManagedAgentsEditToolConfigParams return param.MarshalObject(r, (*shadow)(&r)) } -func (r *BetaManagedAgentsMCPToolConfigParams) UnmarshalJSON(data []byte) error { +func (r *BetaManagedAgentsEditToolConfigParams) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } // Only one field can be non-zero. // // Use [param.IsOmitted] to confirm if a field is set. -type BetaManagedAgentsMCPToolConfigParamsPermissionPolicyUnion struct { +type BetaManagedAgentsEditToolConfigParamsPermissionPolicyUnion struct { OfAlwaysAllow *BetaManagedAgentsAlwaysAllowPolicyParam `json:",omitzero,inline"` OfAlwaysAsk *BetaManagedAgentsAlwaysAskPolicyParam `json:",omitzero,inline"` paramUnion } -func (u BetaManagedAgentsMCPToolConfigParamsPermissionPolicyUnion) MarshalJSON() ([]byte, error) { +func (u BetaManagedAgentsEditToolConfigParamsPermissionPolicyUnion) MarshalJSON() ([]byte, error) { return param.MarshalUnion(u, u.OfAlwaysAllow, u.OfAlwaysAsk) } -func (u *BetaManagedAgentsMCPToolConfigParamsPermissionPolicyUnion) UnmarshalJSON(data []byte) error { +func (u *BetaManagedAgentsEditToolConfigParamsPermissionPolicyUnion) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, u) } -func (u *BetaManagedAgentsMCPToolConfigParamsPermissionPolicyUnion) asAny() any { +func (u *BetaManagedAgentsEditToolConfigParamsPermissionPolicyUnion) asAny() any { if !param.IsOmitted(u.OfAlwaysAllow) { return u.OfAlwaysAllow } else if !param.IsOmitted(u.OfAlwaysAsk) { @@ -1301,7 +1848,7 @@ func (u *BetaManagedAgentsMCPToolConfigParamsPermissionPolicyUnion) asAny() any } // Returns a pointer to the underlying variant's property, if present. -func (u BetaManagedAgentsMCPToolConfigParamsPermissionPolicyUnion) GetType() *string { +func (u BetaManagedAgentsEditToolConfigParamsPermissionPolicyUnion) GetType() *string { if vt := u.OfAlwaysAllow; vt != nil { return (*string)(&vt.Type) } else if vt := u.OfAlwaysAsk; vt != nil { @@ -1311,72 +1858,1928 @@ func (u BetaManagedAgentsMCPToolConfigParamsPermissionPolicyUnion) GetType() *st } func init() { - apijson.RegisterUnion[BetaManagedAgentsMCPToolConfigParamsPermissionPolicyUnion]( + apijson.RegisterUnion[BetaManagedAgentsEditToolConfigParamsPermissionPolicyUnion]( "type", apijson.Discriminator[BetaManagedAgentsAlwaysAllowPolicyParam]("always_allow"), apijson.Discriminator[BetaManagedAgentsAlwaysAskPolicyParam]("always_ask"), ) } -type BetaManagedAgentsMCPToolset struct { - Configs []BetaManagedAgentsMCPToolConfig `json:"configs" api:"required"` - // Resolved default configuration for all tools from an MCP server. - DefaultConfig BetaManagedAgentsMCPToolsetDefaultConfig `json:"default_config" api:"required"` - MCPServerName string `json:"mcp_server_name" api:"required"` - // Any of "mcp_toolset". - Type BetaManagedAgentsMCPToolsetType `json:"type" api:"required"` +type BetaManagedAgentsEditToolConfigParamsType string + +const ( + BetaManagedAgentsEditToolConfigParamsTypeEdit BetaManagedAgentsEditToolConfigParamsType = "edit" +) + +// High effort. Favors reasoning depth. +type BetaManagedAgentsEffortHigh struct { + // Any of "high". + Type BetaManagedAgentsEffortHighType `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { - Configs respjson.Field - DefaultConfig respjson.Field - MCPServerName respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string } `json:"-"` } // Returns the unmodified JSON received from the API -func (r BetaManagedAgentsMCPToolset) RawJSON() string { return r.JSON.raw } -func (r *BetaManagedAgentsMCPToolset) UnmarshalJSON(data []byte) error { +func (r BetaManagedAgentsEffortHigh) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsEffortHigh) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type BetaManagedAgentsMCPToolsetType string +// ToParam converts this BetaManagedAgentsEffortHigh to a +// BetaManagedAgentsEffortHighParam. +// +// Warning: the fields of the param type will not be present. ToParam should only +// be used at the last possible moment before sending a request. Test for this with +// BetaManagedAgentsEffortHighParam.Overrides() +func (r BetaManagedAgentsEffortHigh) ToParam() BetaManagedAgentsEffortHighParam { + return param.Override[BetaManagedAgentsEffortHighParam](json.RawMessage(r.RawJSON())) +} + +type BetaManagedAgentsEffortHighType string const ( - BetaManagedAgentsMCPToolsetTypeMCPToolset BetaManagedAgentsMCPToolsetType = "mcp_toolset" + BetaManagedAgentsEffortHighTypeHigh BetaManagedAgentsEffortHighType = "high" ) -// Resolved default configuration for all tools from an MCP server. -type BetaManagedAgentsMCPToolsetDefaultConfig struct { - Enabled bool `json:"enabled" api:"required"` - // Permission policy for tool execution. - PermissionPolicy BetaManagedAgentsMCPToolsetDefaultConfigPermissionPolicyUnion `json:"permission_policy" api:"required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Enabled respjson.Field - PermissionPolicy respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +// High effort. Favors reasoning depth. +// +// The property Type is required. +type BetaManagedAgentsEffortHighParam struct { + // Any of "high". + Type BetaManagedAgentsEffortHighType `json:"type,omitzero" api:"required"` + paramObj } -// Returns the unmodified JSON received from the API -func (r BetaManagedAgentsMCPToolsetDefaultConfig) RawJSON() string { return r.JSON.raw } -func (r *BetaManagedAgentsMCPToolsetDefaultConfig) UnmarshalJSON(data []byte) error { +func (r BetaManagedAgentsEffortHighParam) MarshalJSON() (data []byte, err error) { + type shadow BetaManagedAgentsEffortHighParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaManagedAgentsEffortHighParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Low effort. Favors latency over reasoning depth. +type BetaManagedAgentsEffortLow struct { + // Any of "low". + Type BetaManagedAgentsEffortLowType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsEffortLow) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsEffortLow) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// ToParam converts this BetaManagedAgentsEffortLow to a +// BetaManagedAgentsEffortLowParam. +// +// Warning: the fields of the param type will not be present. ToParam should only +// be used at the last possible moment before sending a request. Test for this with +// BetaManagedAgentsEffortLowParam.Overrides() +func (r BetaManagedAgentsEffortLow) ToParam() BetaManagedAgentsEffortLowParam { + return param.Override[BetaManagedAgentsEffortLowParam](json.RawMessage(r.RawJSON())) +} + +type BetaManagedAgentsEffortLowType string + +const ( + BetaManagedAgentsEffortLowTypeLow BetaManagedAgentsEffortLowType = "low" +) + +// Low effort. Favors latency over reasoning depth. +// +// The property Type is required. +type BetaManagedAgentsEffortLowParam struct { + // Any of "low". + Type BetaManagedAgentsEffortLowType `json:"type,omitzero" api:"required"` + paramObj +} + +func (r BetaManagedAgentsEffortLowParam) MarshalJSON() (data []byte, err error) { + type shadow BetaManagedAgentsEffortLowParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaManagedAgentsEffortLowParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Maximum effort. Favors reasoning depth over latency. +type BetaManagedAgentsEffortMax struct { + // Any of "max". + Type BetaManagedAgentsEffortMaxType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsEffortMax) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsEffortMax) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// ToParam converts this BetaManagedAgentsEffortMax to a +// BetaManagedAgentsEffortMaxParam. +// +// Warning: the fields of the param type will not be present. ToParam should only +// be used at the last possible moment before sending a request. Test for this with +// BetaManagedAgentsEffortMaxParam.Overrides() +func (r BetaManagedAgentsEffortMax) ToParam() BetaManagedAgentsEffortMaxParam { + return param.Override[BetaManagedAgentsEffortMaxParam](json.RawMessage(r.RawJSON())) +} + +type BetaManagedAgentsEffortMaxType string + +const ( + BetaManagedAgentsEffortMaxTypeMax BetaManagedAgentsEffortMaxType = "max" +) + +// Maximum effort. Favors reasoning depth over latency. +// +// The property Type is required. +type BetaManagedAgentsEffortMaxParam struct { + // Any of "max". + Type BetaManagedAgentsEffortMaxType `json:"type,omitzero" api:"required"` + paramObj +} + +func (r BetaManagedAgentsEffortMaxParam) MarshalJSON() (data []byte, err error) { + type shadow BetaManagedAgentsEffortMaxParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaManagedAgentsEffortMaxParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Medium effort. Balances latency and reasoning depth. +type BetaManagedAgentsEffortMedium struct { + // Any of "medium". + Type BetaManagedAgentsEffortMediumType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsEffortMedium) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsEffortMedium) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// ToParam converts this BetaManagedAgentsEffortMedium to a +// BetaManagedAgentsEffortMediumParam. +// +// Warning: the fields of the param type will not be present. ToParam should only +// be used at the last possible moment before sending a request. Test for this with +// BetaManagedAgentsEffortMediumParam.Overrides() +func (r BetaManagedAgentsEffortMedium) ToParam() BetaManagedAgentsEffortMediumParam { + return param.Override[BetaManagedAgentsEffortMediumParam](json.RawMessage(r.RawJSON())) +} + +type BetaManagedAgentsEffortMediumType string + +const ( + BetaManagedAgentsEffortMediumTypeMedium BetaManagedAgentsEffortMediumType = "medium" +) + +// Medium effort. Balances latency and reasoning depth. +// +// The property Type is required. +type BetaManagedAgentsEffortMediumParam struct { + // Any of "medium". + Type BetaManagedAgentsEffortMediumType `json:"type,omitzero" api:"required"` + paramObj +} + +func (r BetaManagedAgentsEffortMediumParam) MarshalJSON() (data []byte, err error) { + type shadow BetaManagedAgentsEffortMediumParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaManagedAgentsEffortMediumParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Extra-high effort. Not all models accept this level. +type BetaManagedAgentsEffortXhigh struct { + // Any of "xhigh". + Type BetaManagedAgentsEffortXhighType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsEffortXhigh) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsEffortXhigh) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// ToParam converts this BetaManagedAgentsEffortXhigh to a +// BetaManagedAgentsEffortXhighParam. +// +// Warning: the fields of the param type will not be present. ToParam should only +// be used at the last possible moment before sending a request. Test for this with +// BetaManagedAgentsEffortXhighParam.Overrides() +func (r BetaManagedAgentsEffortXhigh) ToParam() BetaManagedAgentsEffortXhighParam { + return param.Override[BetaManagedAgentsEffortXhighParam](json.RawMessage(r.RawJSON())) +} + +type BetaManagedAgentsEffortXhighType string + +const ( + BetaManagedAgentsEffortXhighTypeXhigh BetaManagedAgentsEffortXhighType = "xhigh" +) + +// Extra-high effort. Not all models accept this level. +// +// The property Type is required. +type BetaManagedAgentsEffortXhighParam struct { + // Any of "xhigh". + Type BetaManagedAgentsEffortXhighType `json:"type,omitzero" api:"required"` + paramObj +} + +func (r BetaManagedAgentsEffortXhighParam) MarshalJSON() (data []byte, err error) { + type shadow BetaManagedAgentsEffortXhighParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaManagedAgentsEffortXhighParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Configuration for the glob tool. +type BetaManagedAgentsGlobToolConfig struct { + Enabled bool `json:"enabled" api:"required"` + Name constant.Glob `json:"name" default:"glob"` + // Permission policy for tool execution. + PermissionPolicy BetaManagedAgentsGlobToolConfigPermissionPolicyUnion `json:"permission_policy" api:"required"` + Type constant.Glob `json:"type" default:"glob"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Enabled respjson.Field + Name respjson.Field + PermissionPolicy respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsGlobToolConfig) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsGlobToolConfig) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaManagedAgentsGlobToolConfigPermissionPolicyUnion contains all possible +// properties and values from [BetaManagedAgentsAlwaysAllowPolicy], +// [BetaManagedAgentsAlwaysAskPolicy]. +// +// Use the [BetaManagedAgentsGlobToolConfigPermissionPolicyUnion.AsAny] method to +// switch on the variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaManagedAgentsGlobToolConfigPermissionPolicyUnion struct { + // Any of "always_allow", "always_ask". + Type string `json:"type"` + JSON struct { + Type respjson.Field + raw string + } `json:"-"` +} + +// anyBetaManagedAgentsGlobToolConfigPermissionPolicy is implemented by each +// variant of [BetaManagedAgentsGlobToolConfigPermissionPolicyUnion] to add type +// safety for the return type of +// [BetaManagedAgentsGlobToolConfigPermissionPolicyUnion.AsAny] +type anyBetaManagedAgentsGlobToolConfigPermissionPolicy interface { + implBetaManagedAgentsGlobToolConfigPermissionPolicyUnion() +} + +func (BetaManagedAgentsAlwaysAllowPolicy) implBetaManagedAgentsGlobToolConfigPermissionPolicyUnion() { +} +func (BetaManagedAgentsAlwaysAskPolicy) implBetaManagedAgentsGlobToolConfigPermissionPolicyUnion() {} + +// Use the following switch statement to find the correct variant +// +// switch variant := BetaManagedAgentsGlobToolConfigPermissionPolicyUnion.AsAny().(type) { +// case anthropic.BetaManagedAgentsAlwaysAllowPolicy: +// case anthropic.BetaManagedAgentsAlwaysAskPolicy: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaManagedAgentsGlobToolConfigPermissionPolicyUnion) AsAny() anyBetaManagedAgentsGlobToolConfigPermissionPolicy { + switch u.Type { + case "always_allow": + return u.AsAlwaysAllow() + case "always_ask": + return u.AsAlwaysAsk() + } + return nil +} + +func (u BetaManagedAgentsGlobToolConfigPermissionPolicyUnion) AsAlwaysAllow() (v BetaManagedAgentsAlwaysAllowPolicy) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsGlobToolConfigPermissionPolicyUnion) AsAlwaysAsk() (v BetaManagedAgentsAlwaysAskPolicy) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u BetaManagedAgentsGlobToolConfigPermissionPolicyUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaManagedAgentsGlobToolConfigPermissionPolicyUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Configuration override for the glob tool. +// +// The property Name is required. +type BetaManagedAgentsGlobToolConfigParams struct { + // Whether this tool is enabled and available to Claude. Overrides the + // default_config setting. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + // Permission policy for tool execution. + PermissionPolicy BetaManagedAgentsGlobToolConfigParamsPermissionPolicyUnion `json:"permission_policy,omitzero"` + // Any of "glob". + Type BetaManagedAgentsGlobToolConfigParamsType `json:"type,omitzero"` + // Must be "glob". + // + // This field can be elided, and will marshal its zero value as "glob". + Name constant.Glob `json:"name" default:"glob"` + paramObj +} + +func (r BetaManagedAgentsGlobToolConfigParams) MarshalJSON() (data []byte, err error) { + type shadow BetaManagedAgentsGlobToolConfigParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaManagedAgentsGlobToolConfigParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaManagedAgentsGlobToolConfigParamsPermissionPolicyUnion struct { + OfAlwaysAllow *BetaManagedAgentsAlwaysAllowPolicyParam `json:",omitzero,inline"` + OfAlwaysAsk *BetaManagedAgentsAlwaysAskPolicyParam `json:",omitzero,inline"` + paramUnion +} + +func (u BetaManagedAgentsGlobToolConfigParamsPermissionPolicyUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfAlwaysAllow, u.OfAlwaysAsk) +} +func (u *BetaManagedAgentsGlobToolConfigParamsPermissionPolicyUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *BetaManagedAgentsGlobToolConfigParamsPermissionPolicyUnion) asAny() any { + if !param.IsOmitted(u.OfAlwaysAllow) { + return u.OfAlwaysAllow + } else if !param.IsOmitted(u.OfAlwaysAsk) { + return u.OfAlwaysAsk + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaManagedAgentsGlobToolConfigParamsPermissionPolicyUnion) GetType() *string { + if vt := u.OfAlwaysAllow; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfAlwaysAsk; vt != nil { + return (*string)(&vt.Type) + } + return nil +} + +func init() { + apijson.RegisterUnion[BetaManagedAgentsGlobToolConfigParamsPermissionPolicyUnion]( + "type", + apijson.Discriminator[BetaManagedAgentsAlwaysAllowPolicyParam]("always_allow"), + apijson.Discriminator[BetaManagedAgentsAlwaysAskPolicyParam]("always_ask"), + ) +} + +type BetaManagedAgentsGlobToolConfigParamsType string + +const ( + BetaManagedAgentsGlobToolConfigParamsTypeGlob BetaManagedAgentsGlobToolConfigParamsType = "glob" +) + +// Configuration for the grep tool. +type BetaManagedAgentsGrepToolConfig struct { + Enabled bool `json:"enabled" api:"required"` + Name constant.Grep `json:"name" default:"grep"` + // Permission policy for tool execution. + PermissionPolicy BetaManagedAgentsGrepToolConfigPermissionPolicyUnion `json:"permission_policy" api:"required"` + Type constant.Grep `json:"type" default:"grep"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Enabled respjson.Field + Name respjson.Field + PermissionPolicy respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsGrepToolConfig) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsGrepToolConfig) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaManagedAgentsGrepToolConfigPermissionPolicyUnion contains all possible +// properties and values from [BetaManagedAgentsAlwaysAllowPolicy], +// [BetaManagedAgentsAlwaysAskPolicy]. +// +// Use the [BetaManagedAgentsGrepToolConfigPermissionPolicyUnion.AsAny] method to +// switch on the variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaManagedAgentsGrepToolConfigPermissionPolicyUnion struct { + // Any of "always_allow", "always_ask". + Type string `json:"type"` + JSON struct { + Type respjson.Field + raw string + } `json:"-"` +} + +// anyBetaManagedAgentsGrepToolConfigPermissionPolicy is implemented by each +// variant of [BetaManagedAgentsGrepToolConfigPermissionPolicyUnion] to add type +// safety for the return type of +// [BetaManagedAgentsGrepToolConfigPermissionPolicyUnion.AsAny] +type anyBetaManagedAgentsGrepToolConfigPermissionPolicy interface { + implBetaManagedAgentsGrepToolConfigPermissionPolicyUnion() +} + +func (BetaManagedAgentsAlwaysAllowPolicy) implBetaManagedAgentsGrepToolConfigPermissionPolicyUnion() { +} +func (BetaManagedAgentsAlwaysAskPolicy) implBetaManagedAgentsGrepToolConfigPermissionPolicyUnion() {} + +// Use the following switch statement to find the correct variant +// +// switch variant := BetaManagedAgentsGrepToolConfigPermissionPolicyUnion.AsAny().(type) { +// case anthropic.BetaManagedAgentsAlwaysAllowPolicy: +// case anthropic.BetaManagedAgentsAlwaysAskPolicy: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaManagedAgentsGrepToolConfigPermissionPolicyUnion) AsAny() anyBetaManagedAgentsGrepToolConfigPermissionPolicy { + switch u.Type { + case "always_allow": + return u.AsAlwaysAllow() + case "always_ask": + return u.AsAlwaysAsk() + } + return nil +} + +func (u BetaManagedAgentsGrepToolConfigPermissionPolicyUnion) AsAlwaysAllow() (v BetaManagedAgentsAlwaysAllowPolicy) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsGrepToolConfigPermissionPolicyUnion) AsAlwaysAsk() (v BetaManagedAgentsAlwaysAskPolicy) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u BetaManagedAgentsGrepToolConfigPermissionPolicyUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaManagedAgentsGrepToolConfigPermissionPolicyUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Configuration override for the grep tool. +// +// The property Name is required. +type BetaManagedAgentsGrepToolConfigParams struct { + // Whether this tool is enabled and available to Claude. Overrides the + // default_config setting. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + // Permission policy for tool execution. + PermissionPolicy BetaManagedAgentsGrepToolConfigParamsPermissionPolicyUnion `json:"permission_policy,omitzero"` + // Any of "grep". + Type BetaManagedAgentsGrepToolConfigParamsType `json:"type,omitzero"` + // Must be "grep". + // + // This field can be elided, and will marshal its zero value as "grep". + Name constant.Grep `json:"name" default:"grep"` + paramObj +} + +func (r BetaManagedAgentsGrepToolConfigParams) MarshalJSON() (data []byte, err error) { + type shadow BetaManagedAgentsGrepToolConfigParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaManagedAgentsGrepToolConfigParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaManagedAgentsGrepToolConfigParamsPermissionPolicyUnion struct { + OfAlwaysAllow *BetaManagedAgentsAlwaysAllowPolicyParam `json:",omitzero,inline"` + OfAlwaysAsk *BetaManagedAgentsAlwaysAskPolicyParam `json:",omitzero,inline"` + paramUnion +} + +func (u BetaManagedAgentsGrepToolConfigParamsPermissionPolicyUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfAlwaysAllow, u.OfAlwaysAsk) +} +func (u *BetaManagedAgentsGrepToolConfigParamsPermissionPolicyUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *BetaManagedAgentsGrepToolConfigParamsPermissionPolicyUnion) asAny() any { + if !param.IsOmitted(u.OfAlwaysAllow) { + return u.OfAlwaysAllow + } else if !param.IsOmitted(u.OfAlwaysAsk) { + return u.OfAlwaysAsk + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaManagedAgentsGrepToolConfigParamsPermissionPolicyUnion) GetType() *string { + if vt := u.OfAlwaysAllow; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfAlwaysAsk; vt != nil { + return (*string)(&vt.Type) + } + return nil +} + +func init() { + apijson.RegisterUnion[BetaManagedAgentsGrepToolConfigParamsPermissionPolicyUnion]( + "type", + apijson.Discriminator[BetaManagedAgentsAlwaysAllowPolicyParam]("always_allow"), + apijson.Discriminator[BetaManagedAgentsAlwaysAskPolicyParam]("always_ask"), + ) +} + +type BetaManagedAgentsGrepToolConfigParamsType string + +const ( + BetaManagedAgentsGrepToolConfigParamsTypeGrep BetaManagedAgentsGrepToolConfigParamsType = "grep" +) + +// URL-based MCP server connection as returned in API responses. +type BetaManagedAgentsMCPServerURLDefinition struct { + Name string `json:"name" api:"required"` + // Any of "url". + Type BetaManagedAgentsMCPServerURLDefinitionType `json:"type" api:"required"` + URL string `json:"url" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Name respjson.Field + Type respjson.Field + URL respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsMCPServerURLDefinition) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsMCPServerURLDefinition) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsMCPServerURLDefinitionType string + +const ( + BetaManagedAgentsMCPServerURLDefinitionTypeURL BetaManagedAgentsMCPServerURLDefinitionType = "url" +) + +// Resolved configuration for a specific MCP tool. +type BetaManagedAgentsMCPToolConfig struct { + Enabled bool `json:"enabled" api:"required"` + Name string `json:"name" api:"required"` + // Permission policy for tool execution. + PermissionPolicy BetaManagedAgentsMCPToolConfigPermissionPolicyUnion `json:"permission_policy" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Enabled respjson.Field + Name respjson.Field + PermissionPolicy respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsMCPToolConfig) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsMCPToolConfig) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaManagedAgentsMCPToolConfigPermissionPolicyUnion contains all possible +// properties and values from [BetaManagedAgentsAlwaysAllowPolicy], +// [BetaManagedAgentsAlwaysAskPolicy]. +// +// Use the [BetaManagedAgentsMCPToolConfigPermissionPolicyUnion.AsAny] method to +// switch on the variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaManagedAgentsMCPToolConfigPermissionPolicyUnion struct { + // Any of "always_allow", "always_ask". + Type string `json:"type"` + JSON struct { + Type respjson.Field + raw string + } `json:"-"` +} + +// anyBetaManagedAgentsMCPToolConfigPermissionPolicy is implemented by each variant +// of [BetaManagedAgentsMCPToolConfigPermissionPolicyUnion] to add type safety for +// the return type of [BetaManagedAgentsMCPToolConfigPermissionPolicyUnion.AsAny] +type anyBetaManagedAgentsMCPToolConfigPermissionPolicy interface { + implBetaManagedAgentsMCPToolConfigPermissionPolicyUnion() +} + +func (BetaManagedAgentsAlwaysAllowPolicy) implBetaManagedAgentsMCPToolConfigPermissionPolicyUnion() {} +func (BetaManagedAgentsAlwaysAskPolicy) implBetaManagedAgentsMCPToolConfigPermissionPolicyUnion() {} + +// Use the following switch statement to find the correct variant +// +// switch variant := BetaManagedAgentsMCPToolConfigPermissionPolicyUnion.AsAny().(type) { +// case anthropic.BetaManagedAgentsAlwaysAllowPolicy: +// case anthropic.BetaManagedAgentsAlwaysAskPolicy: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaManagedAgentsMCPToolConfigPermissionPolicyUnion) AsAny() anyBetaManagedAgentsMCPToolConfigPermissionPolicy { + switch u.Type { + case "always_allow": + return u.AsAlwaysAllow() + case "always_ask": + return u.AsAlwaysAsk() + } + return nil +} + +func (u BetaManagedAgentsMCPToolConfigPermissionPolicyUnion) AsAlwaysAllow() (v BetaManagedAgentsAlwaysAllowPolicy) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsMCPToolConfigPermissionPolicyUnion) AsAlwaysAsk() (v BetaManagedAgentsAlwaysAskPolicy) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u BetaManagedAgentsMCPToolConfigPermissionPolicyUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaManagedAgentsMCPToolConfigPermissionPolicyUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Configuration override for a specific MCP tool. +// +// The property Name is required. +type BetaManagedAgentsMCPToolConfigParams struct { + // Name of the MCP tool to configure. 1-128 characters. + Name string `json:"name" api:"required"` + // Whether this tool is enabled. Overrides the `default_config` setting. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + // Permission policy for tool execution. + PermissionPolicy BetaManagedAgentsMCPToolConfigParamsPermissionPolicyUnion `json:"permission_policy,omitzero"` + paramObj +} + +func (r BetaManagedAgentsMCPToolConfigParams) MarshalJSON() (data []byte, err error) { + type shadow BetaManagedAgentsMCPToolConfigParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaManagedAgentsMCPToolConfigParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaManagedAgentsMCPToolConfigParamsPermissionPolicyUnion struct { + OfAlwaysAllow *BetaManagedAgentsAlwaysAllowPolicyParam `json:",omitzero,inline"` + OfAlwaysAsk *BetaManagedAgentsAlwaysAskPolicyParam `json:",omitzero,inline"` + paramUnion +} + +func (u BetaManagedAgentsMCPToolConfigParamsPermissionPolicyUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfAlwaysAllow, u.OfAlwaysAsk) +} +func (u *BetaManagedAgentsMCPToolConfigParamsPermissionPolicyUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *BetaManagedAgentsMCPToolConfigParamsPermissionPolicyUnion) asAny() any { + if !param.IsOmitted(u.OfAlwaysAllow) { + return u.OfAlwaysAllow + } else if !param.IsOmitted(u.OfAlwaysAsk) { + return u.OfAlwaysAsk + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaManagedAgentsMCPToolConfigParamsPermissionPolicyUnion) GetType() *string { + if vt := u.OfAlwaysAllow; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfAlwaysAsk; vt != nil { + return (*string)(&vt.Type) + } + return nil +} + +func init() { + apijson.RegisterUnion[BetaManagedAgentsMCPToolConfigParamsPermissionPolicyUnion]( + "type", + apijson.Discriminator[BetaManagedAgentsAlwaysAllowPolicyParam]("always_allow"), + apijson.Discriminator[BetaManagedAgentsAlwaysAskPolicyParam]("always_ask"), + ) +} + +type BetaManagedAgentsMCPToolset struct { + Configs []BetaManagedAgentsMCPToolConfig `json:"configs" api:"required"` + // Resolved default configuration for all tools from an MCP server. + DefaultConfig BetaManagedAgentsMCPToolsetDefaultConfig `json:"default_config" api:"required"` + MCPServerName string `json:"mcp_server_name" api:"required"` + // Any of "mcp_toolset". + Type BetaManagedAgentsMCPToolsetType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Configs respjson.Field + DefaultConfig respjson.Field + MCPServerName respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsMCPToolset) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsMCPToolset) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsMCPToolsetType string + +const ( + BetaManagedAgentsMCPToolsetTypeMCPToolset BetaManagedAgentsMCPToolsetType = "mcp_toolset" +) + +// Resolved default configuration for all tools from an MCP server. +type BetaManagedAgentsMCPToolsetDefaultConfig struct { + Enabled bool `json:"enabled" api:"required"` + // Permission policy for tool execution. + PermissionPolicy BetaManagedAgentsMCPToolsetDefaultConfigPermissionPolicyUnion `json:"permission_policy" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Enabled respjson.Field + PermissionPolicy respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsMCPToolsetDefaultConfig) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsMCPToolsetDefaultConfig) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaManagedAgentsMCPToolsetDefaultConfigPermissionPolicyUnion contains all +// possible properties and values from [BetaManagedAgentsAlwaysAllowPolicy], +// [BetaManagedAgentsAlwaysAskPolicy]. +// +// Use the [BetaManagedAgentsMCPToolsetDefaultConfigPermissionPolicyUnion.AsAny] +// method to switch on the variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaManagedAgentsMCPToolsetDefaultConfigPermissionPolicyUnion struct { + // Any of "always_allow", "always_ask". + Type string `json:"type"` + JSON struct { + Type respjson.Field + raw string + } `json:"-"` +} + +// anyBetaManagedAgentsMCPToolsetDefaultConfigPermissionPolicy is implemented by +// each variant of [BetaManagedAgentsMCPToolsetDefaultConfigPermissionPolicyUnion] +// to add type safety for the return type of +// [BetaManagedAgentsMCPToolsetDefaultConfigPermissionPolicyUnion.AsAny] +type anyBetaManagedAgentsMCPToolsetDefaultConfigPermissionPolicy interface { + implBetaManagedAgentsMCPToolsetDefaultConfigPermissionPolicyUnion() +} + +func (BetaManagedAgentsAlwaysAllowPolicy) implBetaManagedAgentsMCPToolsetDefaultConfigPermissionPolicyUnion() { +} +func (BetaManagedAgentsAlwaysAskPolicy) implBetaManagedAgentsMCPToolsetDefaultConfigPermissionPolicyUnion() { +} + +// Use the following switch statement to find the correct variant +// +// switch variant := BetaManagedAgentsMCPToolsetDefaultConfigPermissionPolicyUnion.AsAny().(type) { +// case anthropic.BetaManagedAgentsAlwaysAllowPolicy: +// case anthropic.BetaManagedAgentsAlwaysAskPolicy: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaManagedAgentsMCPToolsetDefaultConfigPermissionPolicyUnion) AsAny() anyBetaManagedAgentsMCPToolsetDefaultConfigPermissionPolicy { + switch u.Type { + case "always_allow": + return u.AsAlwaysAllow() + case "always_ask": + return u.AsAlwaysAsk() + } + return nil +} + +func (u BetaManagedAgentsMCPToolsetDefaultConfigPermissionPolicyUnion) AsAlwaysAllow() (v BetaManagedAgentsAlwaysAllowPolicy) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsMCPToolsetDefaultConfigPermissionPolicyUnion) AsAlwaysAsk() (v BetaManagedAgentsAlwaysAskPolicy) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u BetaManagedAgentsMCPToolsetDefaultConfigPermissionPolicyUnion) RawJSON() string { + return u.JSON.raw +} + +func (r *BetaManagedAgentsMCPToolsetDefaultConfigPermissionPolicyUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Default configuration for all tools from an MCP server. +type BetaManagedAgentsMCPToolsetDefaultConfigParams struct { + // Whether tools are enabled by default. Defaults to true if not specified. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + // Permission policy for tool execution. + PermissionPolicy BetaManagedAgentsMCPToolsetDefaultConfigParamsPermissionPolicyUnion `json:"permission_policy,omitzero"` + paramObj +} + +func (r BetaManagedAgentsMCPToolsetDefaultConfigParams) MarshalJSON() (data []byte, err error) { + type shadow BetaManagedAgentsMCPToolsetDefaultConfigParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaManagedAgentsMCPToolsetDefaultConfigParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaManagedAgentsMCPToolsetDefaultConfigParamsPermissionPolicyUnion struct { + OfAlwaysAllow *BetaManagedAgentsAlwaysAllowPolicyParam `json:",omitzero,inline"` + OfAlwaysAsk *BetaManagedAgentsAlwaysAskPolicyParam `json:",omitzero,inline"` + paramUnion +} + +func (u BetaManagedAgentsMCPToolsetDefaultConfigParamsPermissionPolicyUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfAlwaysAllow, u.OfAlwaysAsk) +} +func (u *BetaManagedAgentsMCPToolsetDefaultConfigParamsPermissionPolicyUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *BetaManagedAgentsMCPToolsetDefaultConfigParamsPermissionPolicyUnion) asAny() any { + if !param.IsOmitted(u.OfAlwaysAllow) { + return u.OfAlwaysAllow + } else if !param.IsOmitted(u.OfAlwaysAsk) { + return u.OfAlwaysAsk + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaManagedAgentsMCPToolsetDefaultConfigParamsPermissionPolicyUnion) GetType() *string { + if vt := u.OfAlwaysAllow; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfAlwaysAsk; vt != nil { + return (*string)(&vt.Type) + } + return nil +} + +func init() { + apijson.RegisterUnion[BetaManagedAgentsMCPToolsetDefaultConfigParamsPermissionPolicyUnion]( + "type", + apijson.Discriminator[BetaManagedAgentsAlwaysAllowPolicyParam]("always_allow"), + apijson.Discriminator[BetaManagedAgentsAlwaysAskPolicyParam]("always_ask"), + ) +} + +// Configuration for tools from an MCP server defined in `mcp_servers`. +// +// The properties MCPServerName, Type are required. +type BetaManagedAgentsMCPToolsetParams struct { + // Name of the MCP server. Must match a server name from the mcp_servers array. + // 1-255 characters. + MCPServerName string `json:"mcp_server_name" api:"required"` + // Any of "mcp_toolset". + Type BetaManagedAgentsMCPToolsetParamsType `json:"type,omitzero" api:"required"` + // Per-tool configuration overrides. + Configs []BetaManagedAgentsMCPToolConfigParams `json:"configs,omitzero"` + // Default configuration for all tools from an MCP server. + DefaultConfig BetaManagedAgentsMCPToolsetDefaultConfigParams `json:"default_config,omitzero"` + paramObj +} + +func (r BetaManagedAgentsMCPToolsetParams) MarshalJSON() (data []byte, err error) { + type shadow BetaManagedAgentsMCPToolsetParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaManagedAgentsMCPToolsetParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsMCPToolsetParamsType string + +const ( + BetaManagedAgentsMCPToolsetParamsTypeMCPToolset BetaManagedAgentsMCPToolsetParamsType = "mcp_toolset" +) + +// The model that will power your agent. +// +// See [models](https://docs.anthropic.com/en/docs/models-overview) for additional +// details and options. +type BetaManagedAgentsModel = string + +const ( + BetaManagedAgentsModelClaudeSonnet5 BetaManagedAgentsModel = "claude-sonnet-5" + BetaManagedAgentsModelClaudeFable5 BetaManagedAgentsModel = "claude-fable-5" + BetaManagedAgentsModelClaudeOpus5 BetaManagedAgentsModel = "claude-opus-5" + BetaManagedAgentsModelClaudeOpus4_8 BetaManagedAgentsModel = "claude-opus-4-8" + BetaManagedAgentsModelClaudeOpus4_7 BetaManagedAgentsModel = "claude-opus-4-7" + BetaManagedAgentsModelClaudeOpus4_6 BetaManagedAgentsModel = "claude-opus-4-6" + BetaManagedAgentsModelClaudeSonnet4_6 BetaManagedAgentsModel = "claude-sonnet-4-6" + BetaManagedAgentsModelClaudeHaiku4_5 BetaManagedAgentsModel = "claude-haiku-4-5" + BetaManagedAgentsModelClaudeHaiku4_5_20251001 BetaManagedAgentsModel = "claude-haiku-4-5-20251001" + BetaManagedAgentsModelClaudeOpus4_5 BetaManagedAgentsModel = "claude-opus-4-5" + BetaManagedAgentsModelClaudeOpus4_5_20251101 BetaManagedAgentsModel = "claude-opus-4-5-20251101" + BetaManagedAgentsModelClaudeSonnet4_5 BetaManagedAgentsModel = "claude-sonnet-4-5" + BetaManagedAgentsModelClaudeSonnet4_5_20250929 BetaManagedAgentsModel = "claude-sonnet-4-5-20250929" +) + +// Model identifier and configuration. +type BetaManagedAgentsModelConfig struct { + // The model that will power your agent. + // + // See [models](https://docs.anthropic.com/en/docs/models-overview) for additional + // details and options. + ID BetaManagedAgentsModel `json:"id" api:"required"` + // How hard Claude works on each turn. Sets `output_config.effort` on every + // Messages call the session makes. + Effort BetaManagedAgentsModelConfigEffortUnion `json:"effort"` + // Geographic region for model inference. When unset, requests fall through to the + // workspace's default_inference_geo. + InferenceGeo string `json:"inference_geo"` + // Inference speed mode. `fast` provides significantly faster output token + // generation at premium pricing. Not all models support `fast`; invalid + // combinations are rejected at create time. + // + // Any of "standard", "fast". + Speed BetaManagedAgentsModelConfigSpeed `json:"speed"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + Effort respjson.Field + InferenceGeo respjson.Field + Speed respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsModelConfig) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsModelConfig) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaManagedAgentsModelConfigEffortUnion contains all possible properties and +// values from [BetaManagedAgentsEffortLow], [BetaManagedAgentsEffortMedium], +// [BetaManagedAgentsEffortHigh], [BetaManagedAgentsEffortXhigh], +// [BetaManagedAgentsEffortMax]. +// +// Use the [BetaManagedAgentsModelConfigEffortUnion.AsAny] method to switch on the +// variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaManagedAgentsModelConfigEffortUnion struct { + // Any of "low", "medium", "high", "xhigh", "max". + Type string `json:"type"` + JSON struct { + Type respjson.Field + raw string + } `json:"-"` +} + +// anyBetaManagedAgentsModelConfigEffort is implemented by each variant of +// [BetaManagedAgentsModelConfigEffortUnion] to add type safety for the return type +// of [BetaManagedAgentsModelConfigEffortUnion.AsAny] +type anyBetaManagedAgentsModelConfigEffort interface { + implBetaManagedAgentsModelConfigEffortUnion() +} + +func (BetaManagedAgentsEffortLow) implBetaManagedAgentsModelConfigEffortUnion() {} +func (BetaManagedAgentsEffortMedium) implBetaManagedAgentsModelConfigEffortUnion() {} +func (BetaManagedAgentsEffortHigh) implBetaManagedAgentsModelConfigEffortUnion() {} +func (BetaManagedAgentsEffortXhigh) implBetaManagedAgentsModelConfigEffortUnion() {} +func (BetaManagedAgentsEffortMax) implBetaManagedAgentsModelConfigEffortUnion() {} + +// Use the following switch statement to find the correct variant +// +// switch variant := BetaManagedAgentsModelConfigEffortUnion.AsAny().(type) { +// case anthropic.BetaManagedAgentsEffortLow: +// case anthropic.BetaManagedAgentsEffortMedium: +// case anthropic.BetaManagedAgentsEffortHigh: +// case anthropic.BetaManagedAgentsEffortXhigh: +// case anthropic.BetaManagedAgentsEffortMax: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaManagedAgentsModelConfigEffortUnion) AsAny() anyBetaManagedAgentsModelConfigEffort { + switch u.Type { + case "low": + return u.AsLow() + case "medium": + return u.AsMedium() + case "high": + return u.AsHigh() + case "xhigh": + return u.AsXhigh() + case "max": + return u.AsMax() + } + return nil +} + +func (u BetaManagedAgentsModelConfigEffortUnion) AsLow() (v BetaManagedAgentsEffortLow) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsModelConfigEffortUnion) AsMedium() (v BetaManagedAgentsEffortMedium) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsModelConfigEffortUnion) AsHigh() (v BetaManagedAgentsEffortHigh) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsModelConfigEffortUnion) AsXhigh() (v BetaManagedAgentsEffortXhigh) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsModelConfigEffortUnion) AsMax() (v BetaManagedAgentsEffortMax) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u BetaManagedAgentsModelConfigEffortUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaManagedAgentsModelConfigEffortUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Inference speed mode. `fast` provides significantly faster output token +// generation at premium pricing. Not all models support `fast`; invalid +// combinations are rejected at create time. +type BetaManagedAgentsModelConfigSpeed string + +const ( + BetaManagedAgentsModelConfigSpeedStandard BetaManagedAgentsModelConfigSpeed = "standard" + BetaManagedAgentsModelConfigSpeedFast BetaManagedAgentsModelConfigSpeed = "fast" +) + +// An object that defines additional configuration control over model use +// +// The property ID is required. +type BetaManagedAgentsModelConfigParams struct { + // The model that will power your agent. + // + // See [models](https://docs.anthropic.com/en/docs/models-overview) for additional + // details and options. + ID BetaManagedAgentsModel `json:"id,omitzero" api:"required"` + // Geographic region for model inference. When unset, requests fall through to the + // workspace's default_inference_geo. On update, `model` is whole-object + // replacement — omitting inference_geo clears it. + InferenceGeo param.Opt[string] `json:"inference_geo,omitzero"` + // How hard Claude works on each inference call. Accepts a bare level string + // (`"high"`) or `{"type": "high"}`. On create, omitting it resolves the per-model + // default; on update, omitting it leaves the stored value unchanged. + Effort BetaManagedAgentsModelConfigParamsEffortUnion `json:"effort,omitzero"` + // Inference speed mode. `fast` provides significantly faster output token + // generation at premium pricing. Not all models support `fast`; invalid + // combinations are rejected at create time. + // + // Any of "standard", "fast". + Speed BetaManagedAgentsModelConfigParamsSpeed `json:"speed,omitzero"` + paramObj +} + +func (r BetaManagedAgentsModelConfigParams) MarshalJSON() (data []byte, err error) { + type shadow BetaManagedAgentsModelConfigParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaManagedAgentsModelConfigParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaManagedAgentsModelConfigParamsEffortUnion struct { + // Check if union is this variant with + // !param.IsOmitted(union.OfBetaManagedAgentsModelConfigsEffortBetaManagedAgentsEffortLevel) + OfBetaManagedAgentsModelConfigsEffortBetaManagedAgentsEffortLevel param.Opt[string] `json:",omitzero,inline"` + OfBetaManagedAgentsEffortLow *BetaManagedAgentsEffortLowParam `json:",omitzero,inline"` + OfBetaManagedAgentsEffortMedium *BetaManagedAgentsEffortMediumParam `json:",omitzero,inline"` + OfBetaManagedAgentsEffortHigh *BetaManagedAgentsEffortHighParam `json:",omitzero,inline"` + OfBetaManagedAgentsEffortXhigh *BetaManagedAgentsEffortXhighParam `json:",omitzero,inline"` + OfBetaManagedAgentsEffortMax *BetaManagedAgentsEffortMaxParam `json:",omitzero,inline"` + paramUnion +} + +func (u BetaManagedAgentsModelConfigParamsEffortUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfBetaManagedAgentsModelConfigsEffortBetaManagedAgentsEffortLevel, + u.OfBetaManagedAgentsEffortLow, + u.OfBetaManagedAgentsEffortMedium, + u.OfBetaManagedAgentsEffortHigh, + u.OfBetaManagedAgentsEffortXhigh, + u.OfBetaManagedAgentsEffortMax) +} +func (u *BetaManagedAgentsModelConfigParamsEffortUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *BetaManagedAgentsModelConfigParamsEffortUnion) asAny() any { + if !param.IsOmitted(u.OfBetaManagedAgentsModelConfigsEffortBetaManagedAgentsEffortLevel) { + return &u.OfBetaManagedAgentsModelConfigsEffortBetaManagedAgentsEffortLevel + } else if !param.IsOmitted(u.OfBetaManagedAgentsEffortLow) { + return u.OfBetaManagedAgentsEffortLow + } else if !param.IsOmitted(u.OfBetaManagedAgentsEffortMedium) { + return u.OfBetaManagedAgentsEffortMedium + } else if !param.IsOmitted(u.OfBetaManagedAgentsEffortHigh) { + return u.OfBetaManagedAgentsEffortHigh + } else if !param.IsOmitted(u.OfBetaManagedAgentsEffortXhigh) { + return u.OfBetaManagedAgentsEffortXhigh + } else if !param.IsOmitted(u.OfBetaManagedAgentsEffortMax) { + return u.OfBetaManagedAgentsEffortMax + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaManagedAgentsModelConfigParamsEffortUnion) GetType() *string { + if vt := u.OfBetaManagedAgentsEffortLow; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfBetaManagedAgentsEffortMedium; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfBetaManagedAgentsEffortHigh; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfBetaManagedAgentsEffortXhigh; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfBetaManagedAgentsEffortMax; vt != nil { + return (*string)(&vt.Type) + } + return nil +} + +// How hard Claude works on each turn. Higher levels favor reasoning depth over +// latency. Not all models accept every level; invalid combinations are rejected at +// create time. +type BetaManagedAgentsModelConfigParamsEffortBetaManagedAgentsEffortLevel string + +const ( + BetaManagedAgentsModelConfigParamsEffortBetaManagedAgentsEffortLevelLow BetaManagedAgentsModelConfigParamsEffortBetaManagedAgentsEffortLevel = "low" + BetaManagedAgentsModelConfigParamsEffortBetaManagedAgentsEffortLevelMedium BetaManagedAgentsModelConfigParamsEffortBetaManagedAgentsEffortLevel = "medium" + BetaManagedAgentsModelConfigParamsEffortBetaManagedAgentsEffortLevelHigh BetaManagedAgentsModelConfigParamsEffortBetaManagedAgentsEffortLevel = "high" + BetaManagedAgentsModelConfigParamsEffortBetaManagedAgentsEffortLevelXhigh BetaManagedAgentsModelConfigParamsEffortBetaManagedAgentsEffortLevel = "xhigh" + BetaManagedAgentsModelConfigParamsEffortBetaManagedAgentsEffortLevelMax BetaManagedAgentsModelConfigParamsEffortBetaManagedAgentsEffortLevel = "max" +) + +// Inference speed mode. `fast` provides significantly faster output token +// generation at premium pricing. Not all models support `fast`; invalid +// combinations are rejected at create time. +type BetaManagedAgentsModelConfigParamsSpeed string + +const ( + BetaManagedAgentsModelConfigParamsSpeedStandard BetaManagedAgentsModelConfigParamsSpeed = "standard" + BetaManagedAgentsModelConfigParamsSpeedFast BetaManagedAgentsModelConfigParamsSpeed = "fast" +) + +// Sentinel roster entry meaning "the agent that owns this configuration". Resolved +// server-side to a concrete agent reference. +// +// The property Type is required. +type BetaManagedAgentsMultiagentSelfParams struct { + // Any of "self". + Type BetaManagedAgentsMultiagentSelfParamsType `json:"type,omitzero" api:"required"` + paramObj +} + +func (r BetaManagedAgentsMultiagentSelfParams) MarshalJSON() (data []byte, err error) { + type shadow BetaManagedAgentsMultiagentSelfParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaManagedAgentsMultiagentSelfParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsMultiagentSelfParamsType string + +const ( + BetaManagedAgentsMultiagentSelfParamsTypeSelf BetaManagedAgentsMultiagentSelfParamsType = "self" +) + +// Configuration for the read tool. +type BetaManagedAgentsReadToolConfig struct { + Enabled bool `json:"enabled" api:"required"` + Name constant.Read `json:"name" default:"read"` + // Permission policy for tool execution. + PermissionPolicy BetaManagedAgentsReadToolConfigPermissionPolicyUnion `json:"permission_policy" api:"required"` + Type constant.Read `json:"type" default:"read"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Enabled respjson.Field + Name respjson.Field + PermissionPolicy respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsReadToolConfig) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsReadToolConfig) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaManagedAgentsReadToolConfigPermissionPolicyUnion contains all possible +// properties and values from [BetaManagedAgentsAlwaysAllowPolicy], +// [BetaManagedAgentsAlwaysAskPolicy]. +// +// Use the [BetaManagedAgentsReadToolConfigPermissionPolicyUnion.AsAny] method to +// switch on the variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaManagedAgentsReadToolConfigPermissionPolicyUnion struct { + // Any of "always_allow", "always_ask". + Type string `json:"type"` + JSON struct { + Type respjson.Field + raw string + } `json:"-"` +} + +// anyBetaManagedAgentsReadToolConfigPermissionPolicy is implemented by each +// variant of [BetaManagedAgentsReadToolConfigPermissionPolicyUnion] to add type +// safety for the return type of +// [BetaManagedAgentsReadToolConfigPermissionPolicyUnion.AsAny] +type anyBetaManagedAgentsReadToolConfigPermissionPolicy interface { + implBetaManagedAgentsReadToolConfigPermissionPolicyUnion() +} + +func (BetaManagedAgentsAlwaysAllowPolicy) implBetaManagedAgentsReadToolConfigPermissionPolicyUnion() { +} +func (BetaManagedAgentsAlwaysAskPolicy) implBetaManagedAgentsReadToolConfigPermissionPolicyUnion() {} + +// Use the following switch statement to find the correct variant +// +// switch variant := BetaManagedAgentsReadToolConfigPermissionPolicyUnion.AsAny().(type) { +// case anthropic.BetaManagedAgentsAlwaysAllowPolicy: +// case anthropic.BetaManagedAgentsAlwaysAskPolicy: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaManagedAgentsReadToolConfigPermissionPolicyUnion) AsAny() anyBetaManagedAgentsReadToolConfigPermissionPolicy { + switch u.Type { + case "always_allow": + return u.AsAlwaysAllow() + case "always_ask": + return u.AsAlwaysAsk() + } + return nil +} + +func (u BetaManagedAgentsReadToolConfigPermissionPolicyUnion) AsAlwaysAllow() (v BetaManagedAgentsAlwaysAllowPolicy) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsReadToolConfigPermissionPolicyUnion) AsAlwaysAsk() (v BetaManagedAgentsAlwaysAskPolicy) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u BetaManagedAgentsReadToolConfigPermissionPolicyUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaManagedAgentsReadToolConfigPermissionPolicyUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Configuration override for the read tool. +// +// The property Name is required. +type BetaManagedAgentsReadToolConfigParams struct { + // Whether this tool is enabled and available to Claude. Overrides the + // default_config setting. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + // Permission policy for tool execution. + PermissionPolicy BetaManagedAgentsReadToolConfigParamsPermissionPolicyUnion `json:"permission_policy,omitzero"` + // Any of "read". + Type BetaManagedAgentsReadToolConfigParamsType `json:"type,omitzero"` + // Must be "read". + // + // This field can be elided, and will marshal its zero value as "read". + Name constant.Read `json:"name" default:"read"` + paramObj +} + +func (r BetaManagedAgentsReadToolConfigParams) MarshalJSON() (data []byte, err error) { + type shadow BetaManagedAgentsReadToolConfigParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaManagedAgentsReadToolConfigParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaManagedAgentsReadToolConfigParamsPermissionPolicyUnion struct { + OfAlwaysAllow *BetaManagedAgentsAlwaysAllowPolicyParam `json:",omitzero,inline"` + OfAlwaysAsk *BetaManagedAgentsAlwaysAskPolicyParam `json:",omitzero,inline"` + paramUnion +} + +func (u BetaManagedAgentsReadToolConfigParamsPermissionPolicyUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfAlwaysAllow, u.OfAlwaysAsk) +} +func (u *BetaManagedAgentsReadToolConfigParamsPermissionPolicyUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *BetaManagedAgentsReadToolConfigParamsPermissionPolicyUnion) asAny() any { + if !param.IsOmitted(u.OfAlwaysAllow) { + return u.OfAlwaysAllow + } else if !param.IsOmitted(u.OfAlwaysAsk) { + return u.OfAlwaysAsk + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaManagedAgentsReadToolConfigParamsPermissionPolicyUnion) GetType() *string { + if vt := u.OfAlwaysAllow; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfAlwaysAsk; vt != nil { + return (*string)(&vt.Type) + } + return nil +} + +func init() { + apijson.RegisterUnion[BetaManagedAgentsReadToolConfigParamsPermissionPolicyUnion]( + "type", + apijson.Discriminator[BetaManagedAgentsAlwaysAllowPolicyParam]("always_allow"), + apijson.Discriminator[BetaManagedAgentsAlwaysAskPolicyParam]("always_ask"), + ) +} + +type BetaManagedAgentsReadToolConfigParamsType string + +const ( + BetaManagedAgentsReadToolConfigParamsTypeRead BetaManagedAgentsReadToolConfigParamsType = "read" +) + +// Resolved `agent` definition for a single `session_thread`. Snapshot of the agent +// at thread creation time. The multiagent roster is not repeated here; read it +// from `Session.agent`. +type BetaManagedAgentsSessionThreadAgent struct { + ID string `json:"id" api:"required"` + Description string `json:"description" api:"required"` + MCPServers []BetaManagedAgentsMCPServerURLDefinition `json:"mcp_servers" api:"required"` + // Model identifier and configuration. + Model BetaManagedAgentsModelConfig `json:"model" api:"required"` + Name string `json:"name" api:"required"` + Skills []BetaManagedAgentsSessionThreadAgentSkillUnion `json:"skills" api:"required"` + System string `json:"system" api:"required"` + Tools []BetaManagedAgentsSessionThreadAgentToolUnion `json:"tools" api:"required"` + // Any of "agent". + Type BetaManagedAgentsSessionThreadAgentType `json:"type" api:"required"` + Version int64 `json:"version" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + Description respjson.Field + MCPServers respjson.Field + Model respjson.Field + Name respjson.Field + Skills respjson.Field + System respjson.Field + Tools respjson.Field + Type respjson.Field + Version respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsSessionThreadAgent) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsSessionThreadAgent) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaManagedAgentsSessionThreadAgentSkillUnion contains all possible properties +// and values from [BetaManagedAgentsAnthropicSkill], +// [BetaManagedAgentsCustomSkill]. +// +// Use the [BetaManagedAgentsSessionThreadAgentSkillUnion.AsAny] method to switch +// on the variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaManagedAgentsSessionThreadAgentSkillUnion struct { + SkillID string `json:"skill_id"` + // Any of "anthropic", "custom". + Type string `json:"type"` + Version string `json:"version"` + JSON struct { + SkillID respjson.Field + Type respjson.Field + Version respjson.Field + raw string + } `json:"-"` +} + +// anyBetaManagedAgentsSessionThreadAgentSkill is implemented by each variant of +// [BetaManagedAgentsSessionThreadAgentSkillUnion] to add type safety for the +// return type of [BetaManagedAgentsSessionThreadAgentSkillUnion.AsAny] +type anyBetaManagedAgentsSessionThreadAgentSkill interface { + implBetaManagedAgentsSessionThreadAgentSkillUnion() +} + +func (BetaManagedAgentsAnthropicSkill) implBetaManagedAgentsSessionThreadAgentSkillUnion() {} +func (BetaManagedAgentsCustomSkill) implBetaManagedAgentsSessionThreadAgentSkillUnion() {} + +// Use the following switch statement to find the correct variant +// +// switch variant := BetaManagedAgentsSessionThreadAgentSkillUnion.AsAny().(type) { +// case anthropic.BetaManagedAgentsAnthropicSkill: +// case anthropic.BetaManagedAgentsCustomSkill: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaManagedAgentsSessionThreadAgentSkillUnion) AsAny() anyBetaManagedAgentsSessionThreadAgentSkill { + switch u.Type { + case "anthropic": + return u.AsAnthropic() + case "custom": + return u.AsCustom() + } + return nil +} + +func (u BetaManagedAgentsSessionThreadAgentSkillUnion) AsAnthropic() (v BetaManagedAgentsAnthropicSkill) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsSessionThreadAgentSkillUnion) AsCustom() (v BetaManagedAgentsCustomSkill) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u BetaManagedAgentsSessionThreadAgentSkillUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaManagedAgentsSessionThreadAgentSkillUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaManagedAgentsSessionThreadAgentToolUnion contains all possible properties +// and values from [BetaManagedAgentsAgentToolset20260401], +// [BetaManagedAgentsMCPToolset], [BetaManagedAgentsCustomTool]. +// +// Use the [BetaManagedAgentsSessionThreadAgentToolUnion.AsAny] method to switch on +// the variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaManagedAgentsSessionThreadAgentToolUnion struct { + // This field is a union of [[]BetaManagedAgentsAgentToolConfigUnion], + // [[]BetaManagedAgentsMCPToolConfig] + Configs BetaManagedAgentsSessionThreadAgentToolUnionConfigs `json:"configs"` + // This field is a union of [BetaManagedAgentsAgentToolsetDefaultConfig], + // [BetaManagedAgentsMCPToolsetDefaultConfig] + DefaultConfig BetaManagedAgentsSessionThreadAgentToolUnionDefaultConfig `json:"default_config"` + // Any of "agent_toolset_20260401", "mcp_toolset", "custom". + Type string `json:"type"` + // This field is from variant [BetaManagedAgentsMCPToolset]. + MCPServerName string `json:"mcp_server_name"` + // This field is from variant [BetaManagedAgentsCustomTool]. + Description string `json:"description"` + // This field is from variant [BetaManagedAgentsCustomTool]. + InputSchema BetaManagedAgentsCustomToolInputSchema `json:"input_schema"` + // This field is from variant [BetaManagedAgentsCustomTool]. + Name string `json:"name"` + JSON struct { + Configs respjson.Field + DefaultConfig respjson.Field + Type respjson.Field + MCPServerName respjson.Field + Description respjson.Field + InputSchema respjson.Field + Name respjson.Field + raw string + } `json:"-"` +} + +// anyBetaManagedAgentsSessionThreadAgentTool is implemented by each variant of +// [BetaManagedAgentsSessionThreadAgentToolUnion] to add type safety for the return +// type of [BetaManagedAgentsSessionThreadAgentToolUnion.AsAny] +type anyBetaManagedAgentsSessionThreadAgentTool interface { + implBetaManagedAgentsSessionThreadAgentToolUnion() +} + +func (BetaManagedAgentsAgentToolset20260401) implBetaManagedAgentsSessionThreadAgentToolUnion() {} +func (BetaManagedAgentsMCPToolset) implBetaManagedAgentsSessionThreadAgentToolUnion() {} +func (BetaManagedAgentsCustomTool) implBetaManagedAgentsSessionThreadAgentToolUnion() {} + +// Use the following switch statement to find the correct variant +// +// switch variant := BetaManagedAgentsSessionThreadAgentToolUnion.AsAny().(type) { +// case anthropic.BetaManagedAgentsAgentToolset20260401: +// case anthropic.BetaManagedAgentsMCPToolset: +// case anthropic.BetaManagedAgentsCustomTool: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaManagedAgentsSessionThreadAgentToolUnion) AsAny() anyBetaManagedAgentsSessionThreadAgentTool { + switch u.Type { + case "agent_toolset_20260401": + return u.AsAgentToolset20260401() + case "mcp_toolset": + return u.AsMCPToolset() + case "custom": + return u.AsCustom() + } + return nil +} + +func (u BetaManagedAgentsSessionThreadAgentToolUnion) AsAgentToolset20260401() (v BetaManagedAgentsAgentToolset20260401) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsSessionThreadAgentToolUnion) AsMCPToolset() (v BetaManagedAgentsMCPToolset) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsSessionThreadAgentToolUnion) AsCustom() (v BetaManagedAgentsCustomTool) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u BetaManagedAgentsSessionThreadAgentToolUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaManagedAgentsSessionThreadAgentToolUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaManagedAgentsSessionThreadAgentToolUnionConfigs is an implicit subunion of +// [BetaManagedAgentsSessionThreadAgentToolUnion]. +// BetaManagedAgentsSessionThreadAgentToolUnionConfigs provides convenient access +// to the sub-properties of the union. +// +// For type safety it is recommended to directly use a variant of the +// [BetaManagedAgentsSessionThreadAgentToolUnion]. +// +// If the underlying value is not a json object, one of the following properties +// will be valid: OfBetaManagedAgentsAgentToolConfigArray +// OfBetaManagedAgentsMCPToolConfigArray] +type BetaManagedAgentsSessionThreadAgentToolUnionConfigs struct { + // This field will be present if the value is a + // [[]BetaManagedAgentsAgentToolConfigUnion] instead of an object. + OfBetaManagedAgentsAgentToolConfigArray []BetaManagedAgentsAgentToolConfigUnion `json:",inline"` + // This field will be present if the value is a [[]BetaManagedAgentsMCPToolConfig] + // instead of an object. + OfBetaManagedAgentsMCPToolConfigArray []BetaManagedAgentsMCPToolConfig `json:",inline"` + JSON struct { + OfBetaManagedAgentsAgentToolConfigArray respjson.Field + OfBetaManagedAgentsMCPToolConfigArray respjson.Field + raw string + } `json:"-"` +} + +func (r *BetaManagedAgentsSessionThreadAgentToolUnionConfigs) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaManagedAgentsSessionThreadAgentToolUnionDefaultConfig is an implicit +// subunion of [BetaManagedAgentsSessionThreadAgentToolUnion]. +// BetaManagedAgentsSessionThreadAgentToolUnionDefaultConfig provides convenient +// access to the sub-properties of the union. +// +// For type safety it is recommended to directly use a variant of the +// [BetaManagedAgentsSessionThreadAgentToolUnion]. +type BetaManagedAgentsSessionThreadAgentToolUnionDefaultConfig struct { + Enabled bool `json:"enabled"` + // This field is a union of + // [BetaManagedAgentsAgentToolsetDefaultConfigPermissionPolicyUnion], + // [BetaManagedAgentsMCPToolsetDefaultConfigPermissionPolicyUnion] + PermissionPolicy BetaManagedAgentsSessionThreadAgentToolUnionDefaultConfigPermissionPolicy `json:"permission_policy"` + JSON struct { + Enabled respjson.Field + PermissionPolicy respjson.Field + raw string + } `json:"-"` +} + +func (r *BetaManagedAgentsSessionThreadAgentToolUnionDefaultConfig) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaManagedAgentsSessionThreadAgentToolUnionDefaultConfigPermissionPolicy is an +// implicit subunion of [BetaManagedAgentsSessionThreadAgentToolUnion]. +// BetaManagedAgentsSessionThreadAgentToolUnionDefaultConfigPermissionPolicy +// provides convenient access to the sub-properties of the union. +// +// For type safety it is recommended to directly use a variant of the +// [BetaManagedAgentsSessionThreadAgentToolUnion]. +type BetaManagedAgentsSessionThreadAgentToolUnionDefaultConfigPermissionPolicy struct { + Type string `json:"type"` + JSON struct { + Type respjson.Field + raw string + } `json:"-"` +} + +func (r *BetaManagedAgentsSessionThreadAgentToolUnionDefaultConfigPermissionPolicy) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsSessionThreadAgentType string + +const ( + BetaManagedAgentsSessionThreadAgentTypeAgent BetaManagedAgentsSessionThreadAgentType = "agent" +) + +func BetaManagedAgentsSkillParamsOfAnthropic(skillID string) BetaManagedAgentsSkillParamsUnion { + var anthropic BetaManagedAgentsAnthropicSkillParams + anthropic.SkillID = skillID + return BetaManagedAgentsSkillParamsUnion{OfAnthropic: &anthropic} +} + +func BetaManagedAgentsSkillParamsOfCustom(skillID string) BetaManagedAgentsSkillParamsUnion { + var custom BetaManagedAgentsCustomSkillParams + custom.SkillID = skillID + return BetaManagedAgentsSkillParamsUnion{OfCustom: &custom} +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaManagedAgentsSkillParamsUnion struct { + OfAnthropic *BetaManagedAgentsAnthropicSkillParams `json:",omitzero,inline"` + OfCustom *BetaManagedAgentsCustomSkillParams `json:",omitzero,inline"` + paramUnion +} + +func (u BetaManagedAgentsSkillParamsUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfAnthropic, u.OfCustom) +} +func (u *BetaManagedAgentsSkillParamsUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *BetaManagedAgentsSkillParamsUnion) asAny() any { + if !param.IsOmitted(u.OfAnthropic) { + return u.OfAnthropic + } else if !param.IsOmitted(u.OfCustom) { + return u.OfCustom + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaManagedAgentsSkillParamsUnion) GetSkillID() *string { + if vt := u.OfAnthropic; vt != nil { + return (*string)(&vt.SkillID) + } else if vt := u.OfCustom; vt != nil { + return (*string)(&vt.SkillID) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaManagedAgentsSkillParamsUnion) GetType() *string { + if vt := u.OfAnthropic; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfCustom; vt != nil { + return (*string)(&vt.Type) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaManagedAgentsSkillParamsUnion) GetVersion() *string { + if vt := u.OfAnthropic; vt != nil && vt.Version.Valid() { + return &vt.Version.Value + } else if vt := u.OfCustom; vt != nil && vt.Version.Valid() { + return &vt.Version.Value + } + return nil +} + +func init() { + apijson.RegisterUnion[BetaManagedAgentsSkillParamsUnion]( + "type", + apijson.Discriminator[BetaManagedAgentsAnthropicSkillParams]("anthropic"), + apijson.Discriminator[BetaManagedAgentsCustomSkillParams]("custom"), + ) +} + +// URL-based MCP server connection. +// +// The properties Name, Type, URL are required. +type BetaManagedAgentsURLMCPServerParams struct { + // Unique name for this server, referenced by mcp_toolset configurations. 1-255 + // characters. + Name string `json:"name" api:"required"` + // Any of "url". + Type BetaManagedAgentsURLMCPServerParamsType `json:"type,omitzero" api:"required"` + // Endpoint URL for the MCP server. + URL string `json:"url" api:"required"` + paramObj +} + +func (r BetaManagedAgentsURLMCPServerParams) MarshalJSON() (data []byte, err error) { + type shadow BetaManagedAgentsURLMCPServerParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaManagedAgentsURLMCPServerParams) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// BetaManagedAgentsMCPToolsetDefaultConfigPermissionPolicyUnion contains all -// possible properties and values from [BetaManagedAgentsAlwaysAllowPolicy], +type BetaManagedAgentsURLMCPServerParamsType string + +const ( + BetaManagedAgentsURLMCPServerParamsTypeURL BetaManagedAgentsURLMCPServerParamsType = "url" +) + +// Approximate user location for search result localization. +type BetaManagedAgentsUserLocation struct { + // Location precision. Only "approximate" is supported. + Type constant.Approximate `json:"type" default:"approximate"` + // City name. + City string `json:"city" api:"nullable"` + // Two-letter ISO 3166-1 country code, uppercase. + Country string `json:"country" api:"nullable"` + // Region or state name. + Region string `json:"region" api:"nullable"` + // IANA timezone identifier, e.g. "America/Los_Angeles". + Timezone string `json:"timezone" api:"nullable"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Type respjson.Field + City respjson.Field + Country respjson.Field + Region respjson.Field + Timezone respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsUserLocation) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsUserLocation) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// ToParam converts this BetaManagedAgentsUserLocation to a +// BetaManagedAgentsUserLocationParam. +// +// Warning: the fields of the param type will not be present. ToParam should only +// be used at the last possible moment before sending a request. Test for this with +// BetaManagedAgentsUserLocationParam.Overrides() +func (r BetaManagedAgentsUserLocation) ToParam() BetaManagedAgentsUserLocationParam { + return param.Override[BetaManagedAgentsUserLocationParam](json.RawMessage(r.RawJSON())) +} + +// Approximate user location for search result localization. +// +// The property Type is required. +type BetaManagedAgentsUserLocationParam struct { + // City name. + City param.Opt[string] `json:"city,omitzero"` + // Two-letter ISO 3166-1 country code, uppercase. + Country param.Opt[string] `json:"country,omitzero"` + // Region or state name. + Region param.Opt[string] `json:"region,omitzero"` + // IANA timezone identifier, e.g. "America/Los_Angeles". + Timezone param.Opt[string] `json:"timezone,omitzero"` + // Location precision. Only "approximate" is supported. + // + // This field can be elided, and will marshal its zero value as "approximate". + Type constant.Approximate `json:"type" default:"approximate"` + paramObj +} + +func (r BetaManagedAgentsUserLocationParam) MarshalJSON() (data []byte, err error) { + type shadow BetaManagedAgentsUserLocationParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaManagedAgentsUserLocationParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Configuration for the web_fetch tool. +type BetaManagedAgentsWebFetchToolConfig struct { + Enabled bool `json:"enabled" api:"required"` + Name constant.WebFetch `json:"name" default:"web_fetch"` + // Permission policy for tool execution. + PermissionPolicy BetaManagedAgentsWebFetchToolConfigPermissionPolicyUnion `json:"permission_policy" api:"required"` + Type constant.WebFetch `json:"type" default:"web_fetch"` + AllowedDomains []string `json:"allowed_domains"` + BlockedDomains []string `json:"blocked_domains"` + MaxContentTokens int64 `json:"max_content_tokens" api:"nullable"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Enabled respjson.Field + Name respjson.Field + PermissionPolicy respjson.Field + Type respjson.Field + AllowedDomains respjson.Field + BlockedDomains respjson.Field + MaxContentTokens respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsWebFetchToolConfig) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsWebFetchToolConfig) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaManagedAgentsWebFetchToolConfigPermissionPolicyUnion contains all possible +// properties and values from [BetaManagedAgentsAlwaysAllowPolicy], // [BetaManagedAgentsAlwaysAskPolicy]. // -// Use the [BetaManagedAgentsMCPToolsetDefaultConfigPermissionPolicyUnion.AsAny] -// method to switch on the variant. +// Use the [BetaManagedAgentsWebFetchToolConfigPermissionPolicyUnion.AsAny] method +// to switch on the variant. // // Use the methods beginning with 'As' to cast the union to one of its variants. -type BetaManagedAgentsMCPToolsetDefaultConfigPermissionPolicyUnion struct { +type BetaManagedAgentsWebFetchToolConfigPermissionPolicyUnion struct { // Any of "always_allow", "always_ask". Type string `json:"type"` JSON struct { @@ -1385,28 +3788,212 @@ type BetaManagedAgentsMCPToolsetDefaultConfigPermissionPolicyUnion struct { } `json:"-"` } -// anyBetaManagedAgentsMCPToolsetDefaultConfigPermissionPolicy is implemented by -// each variant of [BetaManagedAgentsMCPToolsetDefaultConfigPermissionPolicyUnion] -// to add type safety for the return type of -// [BetaManagedAgentsMCPToolsetDefaultConfigPermissionPolicyUnion.AsAny] -type anyBetaManagedAgentsMCPToolsetDefaultConfigPermissionPolicy interface { - implBetaManagedAgentsMCPToolsetDefaultConfigPermissionPolicyUnion() +// anyBetaManagedAgentsWebFetchToolConfigPermissionPolicy is implemented by each +// variant of [BetaManagedAgentsWebFetchToolConfigPermissionPolicyUnion] to add +// type safety for the return type of +// [BetaManagedAgentsWebFetchToolConfigPermissionPolicyUnion.AsAny] +type anyBetaManagedAgentsWebFetchToolConfigPermissionPolicy interface { + implBetaManagedAgentsWebFetchToolConfigPermissionPolicyUnion() +} + +func (BetaManagedAgentsAlwaysAllowPolicy) implBetaManagedAgentsWebFetchToolConfigPermissionPolicyUnion() { +} +func (BetaManagedAgentsAlwaysAskPolicy) implBetaManagedAgentsWebFetchToolConfigPermissionPolicyUnion() { +} + +// Use the following switch statement to find the correct variant +// +// switch variant := BetaManagedAgentsWebFetchToolConfigPermissionPolicyUnion.AsAny().(type) { +// case anthropic.BetaManagedAgentsAlwaysAllowPolicy: +// case anthropic.BetaManagedAgentsAlwaysAskPolicy: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaManagedAgentsWebFetchToolConfigPermissionPolicyUnion) AsAny() anyBetaManagedAgentsWebFetchToolConfigPermissionPolicy { + switch u.Type { + case "always_allow": + return u.AsAlwaysAllow() + case "always_ask": + return u.AsAlwaysAsk() + } + return nil +} + +func (u BetaManagedAgentsWebFetchToolConfigPermissionPolicyUnion) AsAlwaysAllow() (v BetaManagedAgentsAlwaysAllowPolicy) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsWebFetchToolConfigPermissionPolicyUnion) AsAlwaysAsk() (v BetaManagedAgentsAlwaysAskPolicy) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u BetaManagedAgentsWebFetchToolConfigPermissionPolicyUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaManagedAgentsWebFetchToolConfigPermissionPolicyUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Configuration override for the web_fetch tool. +// +// The property Name is required. +type BetaManagedAgentsWebFetchToolConfigParams struct { + // Whether this tool is enabled and available to Claude. Overrides the + // default_config setting. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + // Maximum number of tokens of fetched text content to include in context per call. + // Does not apply to binary content such as PDFs. + MaxContentTokens param.Opt[int64] `json:"max_content_tokens,omitzero"` + // Permission policy for tool execution. + PermissionPolicy BetaManagedAgentsWebFetchToolConfigParamsPermissionPolicyUnion `json:"permission_policy,omitzero"` + // Only fetch URLs whose host is one of these domains or a subdomain of one. Each + // entry is a plain hostname like "docs.example.com" (no scheme, port, or path). At + // most 64 entries; an empty list is rejected (omit the field instead). Cannot be + // combined with blocked_domains. + AllowedDomains []string `json:"allowed_domains,omitzero"` + // Never fetch URLs whose host is one of these domains or a subdomain of one. Each + // entry is a plain hostname like "ads.example.com" (no scheme, port, or path). At + // most 64 entries; an empty list is rejected (omit the field instead). Cannot be + // combined with allowed_domains. + BlockedDomains []string `json:"blocked_domains,omitzero"` + // Any of "web_fetch". + Type BetaManagedAgentsWebFetchToolConfigParamsType `json:"type,omitzero"` + // Must be "web_fetch". + // + // This field can be elided, and will marshal its zero value as "web_fetch". + Name constant.WebFetch `json:"name" default:"web_fetch"` + paramObj +} + +func (r BetaManagedAgentsWebFetchToolConfigParams) MarshalJSON() (data []byte, err error) { + type shadow BetaManagedAgentsWebFetchToolConfigParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaManagedAgentsWebFetchToolConfigParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaManagedAgentsWebFetchToolConfigParamsPermissionPolicyUnion struct { + OfAlwaysAllow *BetaManagedAgentsAlwaysAllowPolicyParam `json:",omitzero,inline"` + OfAlwaysAsk *BetaManagedAgentsAlwaysAskPolicyParam `json:",omitzero,inline"` + paramUnion +} + +func (u BetaManagedAgentsWebFetchToolConfigParamsPermissionPolicyUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfAlwaysAllow, u.OfAlwaysAsk) +} +func (u *BetaManagedAgentsWebFetchToolConfigParamsPermissionPolicyUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *BetaManagedAgentsWebFetchToolConfigParamsPermissionPolicyUnion) asAny() any { + if !param.IsOmitted(u.OfAlwaysAllow) { + return u.OfAlwaysAllow + } else if !param.IsOmitted(u.OfAlwaysAsk) { + return u.OfAlwaysAsk + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaManagedAgentsWebFetchToolConfigParamsPermissionPolicyUnion) GetType() *string { + if vt := u.OfAlwaysAllow; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfAlwaysAsk; vt != nil { + return (*string)(&vt.Type) + } + return nil +} + +func init() { + apijson.RegisterUnion[BetaManagedAgentsWebFetchToolConfigParamsPermissionPolicyUnion]( + "type", + apijson.Discriminator[BetaManagedAgentsAlwaysAllowPolicyParam]("always_allow"), + apijson.Discriminator[BetaManagedAgentsAlwaysAskPolicyParam]("always_ask"), + ) +} + +type BetaManagedAgentsWebFetchToolConfigParamsType string + +const ( + BetaManagedAgentsWebFetchToolConfigParamsTypeWebFetch BetaManagedAgentsWebFetchToolConfigParamsType = "web_fetch" +) + +// Configuration for the web_search tool. +type BetaManagedAgentsWebSearchToolConfig struct { + Enabled bool `json:"enabled" api:"required"` + Name constant.WebSearch `json:"name" default:"web_search"` + // Permission policy for tool execution. + PermissionPolicy BetaManagedAgentsWebSearchToolConfigPermissionPolicyUnion `json:"permission_policy" api:"required"` + Type constant.WebSearch `json:"type" default:"web_search"` + AllowedDomains []string `json:"allowed_domains"` + BlockedDomains []string `json:"blocked_domains"` + // Approximate user location for search result localization. + UserLocation BetaManagedAgentsUserLocation `json:"user_location" api:"nullable"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Enabled respjson.Field + Name respjson.Field + PermissionPolicy respjson.Field + Type respjson.Field + AllowedDomains respjson.Field + BlockedDomains respjson.Field + UserLocation respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsWebSearchToolConfig) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsWebSearchToolConfig) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaManagedAgentsWebSearchToolConfigPermissionPolicyUnion contains all possible +// properties and values from [BetaManagedAgentsAlwaysAllowPolicy], +// [BetaManagedAgentsAlwaysAskPolicy]. +// +// Use the [BetaManagedAgentsWebSearchToolConfigPermissionPolicyUnion.AsAny] method +// to switch on the variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaManagedAgentsWebSearchToolConfigPermissionPolicyUnion struct { + // Any of "always_allow", "always_ask". + Type string `json:"type"` + JSON struct { + Type respjson.Field + raw string + } `json:"-"` } -func (BetaManagedAgentsAlwaysAllowPolicy) implBetaManagedAgentsMCPToolsetDefaultConfigPermissionPolicyUnion() { +// anyBetaManagedAgentsWebSearchToolConfigPermissionPolicy is implemented by each +// variant of [BetaManagedAgentsWebSearchToolConfigPermissionPolicyUnion] to add +// type safety for the return type of +// [BetaManagedAgentsWebSearchToolConfigPermissionPolicyUnion.AsAny] +type anyBetaManagedAgentsWebSearchToolConfigPermissionPolicy interface { + implBetaManagedAgentsWebSearchToolConfigPermissionPolicyUnion() } -func (BetaManagedAgentsAlwaysAskPolicy) implBetaManagedAgentsMCPToolsetDefaultConfigPermissionPolicyUnion() { + +func (BetaManagedAgentsAlwaysAllowPolicy) implBetaManagedAgentsWebSearchToolConfigPermissionPolicyUnion() { +} +func (BetaManagedAgentsAlwaysAskPolicy) implBetaManagedAgentsWebSearchToolConfigPermissionPolicyUnion() { } // Use the following switch statement to find the correct variant // -// switch variant := BetaManagedAgentsMCPToolsetDefaultConfigPermissionPolicyUnion.AsAny().(type) { +// switch variant := BetaManagedAgentsWebSearchToolConfigPermissionPolicyUnion.AsAny().(type) { // case anthropic.BetaManagedAgentsAlwaysAllowPolicy: // case anthropic.BetaManagedAgentsAlwaysAskPolicy: // default: // fmt.Errorf("no variant present") // } -func (u BetaManagedAgentsMCPToolsetDefaultConfigPermissionPolicyUnion) AsAny() anyBetaManagedAgentsMCPToolsetDefaultConfigPermissionPolicy { +func (u BetaManagedAgentsWebSearchToolConfigPermissionPolicyUnion) AsAny() anyBetaManagedAgentsWebSearchToolConfigPermissionPolicy { switch u.Type { case "always_allow": return u.AsAlwaysAllow() @@ -1416,59 +4003,80 @@ func (u BetaManagedAgentsMCPToolsetDefaultConfigPermissionPolicyUnion) AsAny() a return nil } -func (u BetaManagedAgentsMCPToolsetDefaultConfigPermissionPolicyUnion) AsAlwaysAllow() (v BetaManagedAgentsAlwaysAllowPolicy) { +func (u BetaManagedAgentsWebSearchToolConfigPermissionPolicyUnion) AsAlwaysAllow() (v BetaManagedAgentsAlwaysAllowPolicy) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return } -func (u BetaManagedAgentsMCPToolsetDefaultConfigPermissionPolicyUnion) AsAlwaysAsk() (v BetaManagedAgentsAlwaysAskPolicy) { +func (u BetaManagedAgentsWebSearchToolConfigPermissionPolicyUnion) AsAlwaysAsk() (v BetaManagedAgentsAlwaysAskPolicy) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return } // Returns the unmodified JSON received from the API -func (u BetaManagedAgentsMCPToolsetDefaultConfigPermissionPolicyUnion) RawJSON() string { +func (u BetaManagedAgentsWebSearchToolConfigPermissionPolicyUnion) RawJSON() string { return u.JSON.raw } -func (r *BetaManagedAgentsMCPToolsetDefaultConfigPermissionPolicyUnion) UnmarshalJSON(data []byte) error { +func (r *BetaManagedAgentsWebSearchToolConfigPermissionPolicyUnion) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// Default configuration for all tools from an MCP server. -type BetaManagedAgentsMCPToolsetDefaultConfigParams struct { - // Whether tools are enabled by default. Defaults to true if not specified. +// Configuration override for the web_search tool. +// +// The property Name is required. +type BetaManagedAgentsWebSearchToolConfigParams struct { + // Whether this tool is enabled and available to Claude. Overrides the + // default_config setting. Enabled param.Opt[bool] `json:"enabled,omitzero"` // Permission policy for tool execution. - PermissionPolicy BetaManagedAgentsMCPToolsetDefaultConfigParamsPermissionPolicyUnion `json:"permission_policy,omitzero"` + PermissionPolicy BetaManagedAgentsWebSearchToolConfigParamsPermissionPolicyUnion `json:"permission_policy,omitzero"` + // Only return search results whose host is one of these domains or a subdomain of + // one. Each entry is a plain hostname like "docs.example.com" (no scheme or port; + // an optional path suffix is accepted). At most 64 entries; an empty list is + // rejected (omit the field instead). Cannot be combined with blocked_domains. + AllowedDomains []string `json:"allowed_domains,omitzero"` + // Never return search results whose host is one of these domains or a subdomain of + // one. Each entry is a plain hostname like "ads.example.com" (no scheme or port; + // an optional path suffix is accepted). At most 64 entries; an empty list is + // rejected (omit the field instead). Cannot be combined with allowed_domains. + BlockedDomains []string `json:"blocked_domains,omitzero"` + // Any of "web_search". + Type BetaManagedAgentsWebSearchToolConfigParamsType `json:"type,omitzero"` + // Approximate user location for search result localization. + UserLocation BetaManagedAgentsUserLocationParam `json:"user_location,omitzero"` + // Must be "web_search". + // + // This field can be elided, and will marshal its zero value as "web_search". + Name constant.WebSearch `json:"name" default:"web_search"` paramObj } -func (r BetaManagedAgentsMCPToolsetDefaultConfigParams) MarshalJSON() (data []byte, err error) { - type shadow BetaManagedAgentsMCPToolsetDefaultConfigParams +func (r BetaManagedAgentsWebSearchToolConfigParams) MarshalJSON() (data []byte, err error) { + type shadow BetaManagedAgentsWebSearchToolConfigParams return param.MarshalObject(r, (*shadow)(&r)) } -func (r *BetaManagedAgentsMCPToolsetDefaultConfigParams) UnmarshalJSON(data []byte) error { +func (r *BetaManagedAgentsWebSearchToolConfigParams) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } // Only one field can be non-zero. // // Use [param.IsOmitted] to confirm if a field is set. -type BetaManagedAgentsMCPToolsetDefaultConfigParamsPermissionPolicyUnion struct { +type BetaManagedAgentsWebSearchToolConfigParamsPermissionPolicyUnion struct { OfAlwaysAllow *BetaManagedAgentsAlwaysAllowPolicyParam `json:",omitzero,inline"` OfAlwaysAsk *BetaManagedAgentsAlwaysAskPolicyParam `json:",omitzero,inline"` paramUnion } -func (u BetaManagedAgentsMCPToolsetDefaultConfigParamsPermissionPolicyUnion) MarshalJSON() ([]byte, error) { +func (u BetaManagedAgentsWebSearchToolConfigParamsPermissionPolicyUnion) MarshalJSON() ([]byte, error) { return param.MarshalUnion(u, u.OfAlwaysAllow, u.OfAlwaysAsk) } -func (u *BetaManagedAgentsMCPToolsetDefaultConfigParamsPermissionPolicyUnion) UnmarshalJSON(data []byte) error { +func (u *BetaManagedAgentsWebSearchToolConfigParamsPermissionPolicyUnion) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, u) } -func (u *BetaManagedAgentsMCPToolsetDefaultConfigParamsPermissionPolicyUnion) asAny() any { +func (u *BetaManagedAgentsWebSearchToolConfigParamsPermissionPolicyUnion) asAny() any { if !param.IsOmitted(u.OfAlwaysAllow) { return u.OfAlwaysAllow } else if !param.IsOmitted(u.OfAlwaysAsk) { @@ -1478,7 +4086,7 @@ func (u *BetaManagedAgentsMCPToolsetDefaultConfigParamsPermissionPolicyUnion) as } // Returns a pointer to the underlying variant's property, if present. -func (u BetaManagedAgentsMCPToolsetDefaultConfigParamsPermissionPolicyUnion) GetType() *string { +func (u BetaManagedAgentsWebSearchToolConfigParamsPermissionPolicyUnion) GetType() *string { if vt := u.OfAlwaysAllow; vt != nil { return (*string)(&vt.Type) } else if vt := u.OfAlwaysAsk; vt != nil { @@ -1488,254 +4096,206 @@ func (u BetaManagedAgentsMCPToolsetDefaultConfigParamsPermissionPolicyUnion) Get } func init() { - apijson.RegisterUnion[BetaManagedAgentsMCPToolsetDefaultConfigParamsPermissionPolicyUnion]( + apijson.RegisterUnion[BetaManagedAgentsWebSearchToolConfigParamsPermissionPolicyUnion]( "type", apijson.Discriminator[BetaManagedAgentsAlwaysAllowPolicyParam]("always_allow"), apijson.Discriminator[BetaManagedAgentsAlwaysAskPolicyParam]("always_ask"), ) } -// Configuration for tools from an MCP server defined in `mcp_servers`. -// -// The properties MCPServerName, Type are required. -type BetaManagedAgentsMCPToolsetParams struct { - // Name of the MCP server. Must match a server name from the mcp_servers array. - // 1-255 characters. - MCPServerName string `json:"mcp_server_name" api:"required"` - // Any of "mcp_toolset". - Type BetaManagedAgentsMCPToolsetParamsType `json:"type,omitzero" api:"required"` - // Per-tool configuration overrides. - Configs []BetaManagedAgentsMCPToolConfigParams `json:"configs,omitzero"` - // Default configuration for all tools from an MCP server. - DefaultConfig BetaManagedAgentsMCPToolsetDefaultConfigParams `json:"default_config,omitzero"` - paramObj -} - -func (r BetaManagedAgentsMCPToolsetParams) MarshalJSON() (data []byte, err error) { - type shadow BetaManagedAgentsMCPToolsetParams - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaManagedAgentsMCPToolsetParams) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type BetaManagedAgentsMCPToolsetParamsType string - -const ( - BetaManagedAgentsMCPToolsetParamsTypeMCPToolset BetaManagedAgentsMCPToolsetParamsType = "mcp_toolset" -) - -// The model that will power your agent.\n\nSee -// [models](https://docs.anthropic.com/en/docs/models-overview) for additional -// details and options. -type BetaManagedAgentsModel = string +type BetaManagedAgentsWebSearchToolConfigParamsType string const ( - BetaManagedAgentsModelClaudeOpus4_7 BetaManagedAgentsModel = "claude-opus-4-7" - BetaManagedAgentsModelClaudeOpus4_6 BetaManagedAgentsModel = "claude-opus-4-6" - BetaManagedAgentsModelClaudeSonnet4_6 BetaManagedAgentsModel = "claude-sonnet-4-6" - BetaManagedAgentsModelClaudeHaiku4_5 BetaManagedAgentsModel = "claude-haiku-4-5" - BetaManagedAgentsModelClaudeHaiku4_5_20251001 BetaManagedAgentsModel = "claude-haiku-4-5-20251001" - BetaManagedAgentsModelClaudeOpus4_5 BetaManagedAgentsModel = "claude-opus-4-5" - BetaManagedAgentsModelClaudeOpus4_5_20251101 BetaManagedAgentsModel = "claude-opus-4-5-20251101" - BetaManagedAgentsModelClaudeSonnet4_5 BetaManagedAgentsModel = "claude-sonnet-4-5" - BetaManagedAgentsModelClaudeSonnet4_5_20250929 BetaManagedAgentsModel = "claude-sonnet-4-5-20250929" + BetaManagedAgentsWebSearchToolConfigParamsTypeWebSearch BetaManagedAgentsWebSearchToolConfigParamsType = "web_search" ) -// Model identifier and configuration. -type BetaManagedAgentsModelConfig struct { - // The model that will power your agent.\n\nSee - // [models](https://docs.anthropic.com/en/docs/models-overview) for additional - // details and options. - ID BetaManagedAgentsModel `json:"id" api:"required"` - // Inference speed mode. `fast` provides significantly faster output token - // generation at premium pricing. Not all models support `fast`; invalid - // combinations are rejected at create time. - // - // Any of "standard", "fast". - Speed BetaManagedAgentsModelConfigSpeed `json:"speed"` +// Configuration for the write tool. +type BetaManagedAgentsWriteToolConfig struct { + Enabled bool `json:"enabled" api:"required"` + Name constant.Write `json:"name" default:"write"` + // Permission policy for tool execution. + PermissionPolicy BetaManagedAgentsWriteToolConfigPermissionPolicyUnion `json:"permission_policy" api:"required"` + Type constant.Write `json:"type" default:"write"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { - ID respjson.Field - Speed respjson.Field - ExtraFields map[string]respjson.Field - raw string + Enabled respjson.Field + Name respjson.Field + PermissionPolicy respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string } `json:"-"` } // Returns the unmodified JSON received from the API -func (r BetaManagedAgentsModelConfig) RawJSON() string { return r.JSON.raw } -func (r *BetaManagedAgentsModelConfig) UnmarshalJSON(data []byte) error { +func (r BetaManagedAgentsWriteToolConfig) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsWriteToolConfig) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// Inference speed mode. `fast` provides significantly faster output token -// generation at premium pricing. Not all models support `fast`; invalid -// combinations are rejected at create time. -type BetaManagedAgentsModelConfigSpeed string +// BetaManagedAgentsWriteToolConfigPermissionPolicyUnion contains all possible +// properties and values from [BetaManagedAgentsAlwaysAllowPolicy], +// [BetaManagedAgentsAlwaysAskPolicy]. +// +// Use the [BetaManagedAgentsWriteToolConfigPermissionPolicyUnion.AsAny] method to +// switch on the variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaManagedAgentsWriteToolConfigPermissionPolicyUnion struct { + // Any of "always_allow", "always_ask". + Type string `json:"type"` + JSON struct { + Type respjson.Field + raw string + } `json:"-"` +} -const ( - BetaManagedAgentsModelConfigSpeedStandard BetaManagedAgentsModelConfigSpeed = "standard" - BetaManagedAgentsModelConfigSpeedFast BetaManagedAgentsModelConfigSpeed = "fast" -) +// anyBetaManagedAgentsWriteToolConfigPermissionPolicy is implemented by each +// variant of [BetaManagedAgentsWriteToolConfigPermissionPolicyUnion] to add type +// safety for the return type of +// [BetaManagedAgentsWriteToolConfigPermissionPolicyUnion.AsAny] +type anyBetaManagedAgentsWriteToolConfigPermissionPolicy interface { + implBetaManagedAgentsWriteToolConfigPermissionPolicyUnion() +} -// An object that defines additional configuration control over model use +func (BetaManagedAgentsAlwaysAllowPolicy) implBetaManagedAgentsWriteToolConfigPermissionPolicyUnion() { +} +func (BetaManagedAgentsAlwaysAskPolicy) implBetaManagedAgentsWriteToolConfigPermissionPolicyUnion() {} + +// Use the following switch statement to find the correct variant // -// The property ID is required. -type BetaManagedAgentsModelConfigParams struct { - // The model that will power your agent.\n\nSee - // [models](https://docs.anthropic.com/en/docs/models-overview) for additional - // details and options. - ID BetaManagedAgentsModel `json:"id,omitzero" api:"required"` - // Inference speed mode. `fast` provides significantly faster output token - // generation at premium pricing. Not all models support `fast`; invalid - // combinations are rejected at create time. - // - // Any of "standard", "fast". - Speed BetaManagedAgentsModelConfigParamsSpeed `json:"speed,omitzero"` - paramObj +// switch variant := BetaManagedAgentsWriteToolConfigPermissionPolicyUnion.AsAny().(type) { +// case anthropic.BetaManagedAgentsAlwaysAllowPolicy: +// case anthropic.BetaManagedAgentsAlwaysAskPolicy: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaManagedAgentsWriteToolConfigPermissionPolicyUnion) AsAny() anyBetaManagedAgentsWriteToolConfigPermissionPolicy { + switch u.Type { + case "always_allow": + return u.AsAlwaysAllow() + case "always_ask": + return u.AsAlwaysAsk() + } + return nil } -func (r BetaManagedAgentsModelConfigParams) MarshalJSON() (data []byte, err error) { - type shadow BetaManagedAgentsModelConfigParams - return param.MarshalObject(r, (*shadow)(&r)) +func (u BetaManagedAgentsWriteToolConfigPermissionPolicyUnion) AsAlwaysAllow() (v BetaManagedAgentsAlwaysAllowPolicy) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -func (r *BetaManagedAgentsModelConfigParams) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) + +func (u BetaManagedAgentsWriteToolConfigPermissionPolicyUnion) AsAlwaysAsk() (v BetaManagedAgentsAlwaysAskPolicy) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -// Inference speed mode. `fast` provides significantly faster output token -// generation at premium pricing. Not all models support `fast`; invalid -// combinations are rejected at create time. -type BetaManagedAgentsModelConfigParamsSpeed string +// Returns the unmodified JSON received from the API +func (u BetaManagedAgentsWriteToolConfigPermissionPolicyUnion) RawJSON() string { return u.JSON.raw } -const ( - BetaManagedAgentsModelConfigParamsSpeedStandard BetaManagedAgentsModelConfigParamsSpeed = "standard" - BetaManagedAgentsModelConfigParamsSpeedFast BetaManagedAgentsModelConfigParamsSpeed = "fast" -) +func (r *BetaManagedAgentsWriteToolConfigPermissionPolicyUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} -func BetaManagedAgentsSkillParamsOfAnthropic(skillID string) BetaManagedAgentsSkillParamsUnion { - var anthropic BetaManagedAgentsAnthropicSkillParams - anthropic.SkillID = skillID - return BetaManagedAgentsSkillParamsUnion{OfAnthropic: &anthropic} +// Configuration override for the write tool. +// +// The property Name is required. +type BetaManagedAgentsWriteToolConfigParams struct { + // Whether this tool is enabled and available to Claude. Overrides the + // default_config setting. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + // Permission policy for tool execution. + PermissionPolicy BetaManagedAgentsWriteToolConfigParamsPermissionPolicyUnion `json:"permission_policy,omitzero"` + // Any of "write". + Type BetaManagedAgentsWriteToolConfigParamsType `json:"type,omitzero"` + // Must be "write". + // + // This field can be elided, and will marshal its zero value as "write". + Name constant.Write `json:"name" default:"write"` + paramObj } -func BetaManagedAgentsSkillParamsOfCustom(skillID string) BetaManagedAgentsSkillParamsUnion { - var custom BetaManagedAgentsCustomSkillParams - custom.SkillID = skillID - return BetaManagedAgentsSkillParamsUnion{OfCustom: &custom} +func (r BetaManagedAgentsWriteToolConfigParams) MarshalJSON() (data []byte, err error) { + type shadow BetaManagedAgentsWriteToolConfigParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaManagedAgentsWriteToolConfigParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } // Only one field can be non-zero. // // Use [param.IsOmitted] to confirm if a field is set. -type BetaManagedAgentsSkillParamsUnion struct { - OfAnthropic *BetaManagedAgentsAnthropicSkillParams `json:",omitzero,inline"` - OfCustom *BetaManagedAgentsCustomSkillParams `json:",omitzero,inline"` +type BetaManagedAgentsWriteToolConfigParamsPermissionPolicyUnion struct { + OfAlwaysAllow *BetaManagedAgentsAlwaysAllowPolicyParam `json:",omitzero,inline"` + OfAlwaysAsk *BetaManagedAgentsAlwaysAskPolicyParam `json:",omitzero,inline"` paramUnion } -func (u BetaManagedAgentsSkillParamsUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfAnthropic, u.OfCustom) +func (u BetaManagedAgentsWriteToolConfigParamsPermissionPolicyUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfAlwaysAllow, u.OfAlwaysAsk) } -func (u *BetaManagedAgentsSkillParamsUnion) UnmarshalJSON(data []byte) error { +func (u *BetaManagedAgentsWriteToolConfigParamsPermissionPolicyUnion) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, u) } -func (u *BetaManagedAgentsSkillParamsUnion) asAny() any { - if !param.IsOmitted(u.OfAnthropic) { - return u.OfAnthropic - } else if !param.IsOmitted(u.OfCustom) { - return u.OfCustom - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u BetaManagedAgentsSkillParamsUnion) GetSkillID() *string { - if vt := u.OfAnthropic; vt != nil { - return (*string)(&vt.SkillID) - } else if vt := u.OfCustom; vt != nil { - return (*string)(&vt.SkillID) +func (u *BetaManagedAgentsWriteToolConfigParamsPermissionPolicyUnion) asAny() any { + if !param.IsOmitted(u.OfAlwaysAllow) { + return u.OfAlwaysAllow + } else if !param.IsOmitted(u.OfAlwaysAsk) { + return u.OfAlwaysAsk } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u BetaManagedAgentsSkillParamsUnion) GetType() *string { - if vt := u.OfAnthropic; vt != nil { +func (u BetaManagedAgentsWriteToolConfigParamsPermissionPolicyUnion) GetType() *string { + if vt := u.OfAlwaysAllow; vt != nil { return (*string)(&vt.Type) - } else if vt := u.OfCustom; vt != nil { + } else if vt := u.OfAlwaysAsk; vt != nil { return (*string)(&vt.Type) } return nil } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaManagedAgentsSkillParamsUnion) GetVersion() *string { - if vt := u.OfAnthropic; vt != nil && vt.Version.Valid() { - return &vt.Version.Value - } else if vt := u.OfCustom; vt != nil && vt.Version.Valid() { - return &vt.Version.Value - } - return nil -} - func init() { - apijson.RegisterUnion[BetaManagedAgentsSkillParamsUnion]( + apijson.RegisterUnion[BetaManagedAgentsWriteToolConfigParamsPermissionPolicyUnion]( "type", - apijson.Discriminator[BetaManagedAgentsAnthropicSkillParams]("anthropic"), - apijson.Discriminator[BetaManagedAgentsCustomSkillParams]("custom"), + apijson.Discriminator[BetaManagedAgentsAlwaysAllowPolicyParam]("always_allow"), + apijson.Discriminator[BetaManagedAgentsAlwaysAskPolicyParam]("always_ask"), ) } -// URL-based MCP server connection. -// -// The properties Name, Type, URL are required. -type BetaManagedAgentsURLMCPServerParams struct { - // Unique name for this server, referenced by mcp_toolset configurations. 1-255 - // characters. - Name string `json:"name" api:"required"` - // Any of "url". - Type BetaManagedAgentsURLMCPServerParamsType `json:"type,omitzero" api:"required"` - // Endpoint URL for the MCP server. - URL string `json:"url" api:"required"` - paramObj -} - -func (r BetaManagedAgentsURLMCPServerParams) MarshalJSON() (data []byte, err error) { - type shadow BetaManagedAgentsURLMCPServerParams - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaManagedAgentsURLMCPServerParams) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type BetaManagedAgentsURLMCPServerParamsType string +type BetaManagedAgentsWriteToolConfigParamsType string const ( - BetaManagedAgentsURLMCPServerParamsTypeURL BetaManagedAgentsURLMCPServerParamsType = "url" + BetaManagedAgentsWriteToolConfigParamsTypeWrite BetaManagedAgentsWriteToolConfigParamsType = "write" ) type BetaAgentNewParams struct { // Model identifier. Accepts the // [model string](https://platform.claude.com/docs/en/about-claude/models/overview#latest-models-comparison), - // e.g. `claude-opus-4-6`, or a `model_config` object for additional configuration + // e.g. `claude-opus-5`, or a `model_config` object for additional configuration // control Model BetaManagedAgentsModelConfigParams `json:"model,omitzero" api:"required"` - // Human-readable name for the agent. 1-256 characters. + // Human-readable name for the agent. Name string `json:"name" api:"required"` - // Description of what the agent does. Up to 2048 characters. + // Description of what the agent does. Description param.Opt[string] `json:"description,omitzero"` - // System prompt for the agent. Up to 100,000 characters. + // System prompt for the agent. System param.Opt[string] `json:"system,omitzero"` // MCP servers this agent connects to. Maximum 20. Names must be unique within the - // array. + // array. Every server must be referenced by an `mcp_toolset` in `tools`; + // unreferenced servers are rejected. See the + // [MCP connector guide](https://platform.claude.com/docs/en/managed-agents/mcp-connector). MCPServers []BetaManagedAgentsURLMCPServerParams `json:"mcp_servers,omitzero"` // Arbitrary key-value metadata. Maximum 16 pairs, keys up to 64 chars, values up // to 512 chars. Metadata map[string]string `json:"metadata,omitzero"` - // Skills available to the agent. Maximum 20. + // A coordinator topology: the session's primary thread orchestrates work by + // spawning session threads, each running an agent drawn from the `agents` roster. + Multiagent BetaManagedAgentsMultiagentParams `json:"multiagent,omitzero"` + // Skills available to the agent. Skills []BetaManagedAgentsSkillParamsUnion `json:"skills,omitzero"` // Tool configurations available to the agent. Maximum of 128 tools across all // toolsets allowed. @@ -1837,14 +4397,14 @@ func (u BetaAgentNewParamsToolUnion) GetConfigs() (res betaAgentNewParamsToolUni return } -// Can have the runtime types [_[]BetaManagedAgentsAgentToolConfigParams], +// Can have the runtime types [_[]BetaManagedAgentsAgentToolConfigParamsUnion], // [_[]BetaManagedAgentsMCPToolConfigParams] type betaAgentNewParamsToolUnionConfigs struct{ any } // Use the following switch statement to get the type of the union: // // switch u.AsAny().(type) { -// case *[]anthropic.BetaManagedAgentsAgentToolConfigParams: +// case *[]anthropic.BetaManagedAgentsAgentToolConfigParamsUnion: // case *[]anthropic.BetaManagedAgentsMCPToolConfigParams: // default: // fmt.Errorf("not present") @@ -1947,33 +4507,34 @@ type BetaAgentGetParams struct { // URLQuery serializes [BetaAgentGetParams]'s query parameters as `url.Values`. func (r BetaAgentGetParams) URLQuery() (v url.Values, err error) { return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ - ArrayFormat: apiquery.ArrayQueryFormatComma, + ArrayFormat: apiquery.ArrayQueryFormatBrackets, NestedFormat: apiquery.NestedQueryFormatBrackets, }) } type BetaAgentUpdateParams struct { - // The agent's current version, used to prevent concurrent overwrites. Obtain this - // value from a create or retrieve response. The request fails if this does not - // match the server's current version. - Version int64 `json:"version" api:"required"` - // Description. Up to 2048 characters. Omit to preserve; send empty string or null - // to clear. + // Description. Omit to preserve; send empty string or null to clear. Description param.Opt[string] `json:"description,omitzero"` - // System prompt. Up to 100,000 characters. Omit to preserve; send empty string or - // null to clear. + // System prompt. Omit to preserve; send empty string or null to clear. System param.Opt[string] `json:"system,omitzero"` - // Human-readable name. 1-256 characters. Omit to preserve. Cannot be cleared. + // Human-readable name. Must be non-empty. Omit to preserve. Cannot be cleared. Name param.Opt[string] `json:"name,omitzero"` - // MCP servers. Full replacement. Omit to preserve; send empty array or null to - // clear. Names must be unique. Maximum 20. + // The agent's current version, used to prevent concurrent overwrites. Obtain this + // value from a create or retrieve response. Must be at least 1 if specified. When + // supplied, the request fails if it does not match the server's current version; + // omit to apply the update unconditionally. + Version param.Opt[int64] `json:"version,omitzero"` + // MCP servers. Full replacement. Omit to preserve; send empty array or `null` to + // clear. Names must be unique. Maximum 20. Every server must be referenced by an + // `mcp_toolset` in the agent's resulting `tools`; unreferenced servers are + // rejected. See the + // [MCP connector guide](https://platform.claude.com/docs/en/managed-agents/mcp-connector). MCPServers []BetaManagedAgentsURLMCPServerParams `json:"mcp_servers,omitzero"` // Metadata patch. Set a key to a string to upsert it, or to null to delete it. // Omit the field to preserve. The stored bag is limited to 16 keys (up to 64 chars // each) with values up to 512 chars. Metadata map[string]string `json:"metadata,omitzero"` // Skills. Full replacement. Omit to preserve; send empty array or null to clear. - // Maximum 20. Skills []BetaManagedAgentsSkillParamsUnion `json:"skills,omitzero"` // Tool configurations available to the agent. Full replacement. Omit to preserve; // send empty array or null to clear. Maximum of 128 tools across all toolsets @@ -1981,9 +4542,12 @@ type BetaAgentUpdateParams struct { Tools []BetaAgentUpdateParamsToolUnion `json:"tools,omitzero"` // Model identifier. Accepts the // [model string](https://platform.claude.com/docs/en/about-claude/models/overview#latest-models-comparison), - // e.g. `claude-opus-4-6`, or a `model_config` object for additional configuration + // e.g. `claude-opus-5`, or a `model_config` object for additional configuration // control. Omit to preserve. Cannot be cleared. Model BetaManagedAgentsModelConfigParams `json:"model,omitzero"` + // A coordinator topology: the session's primary thread orchestrates work by + // spawning session threads, each running an agent drawn from the `agents` roster. + Multiagent BetaManagedAgentsMultiagentParams `json:"multiagent,omitzero"` // Optional header to specify the beta version(s) you want to use. Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` paramObj @@ -2081,14 +4645,14 @@ func (u BetaAgentUpdateParamsToolUnion) GetConfigs() (res betaAgentUpdateParamsT return } -// Can have the runtime types [_[]BetaManagedAgentsAgentToolConfigParams], +// Can have the runtime types [_[]BetaManagedAgentsAgentToolConfigParamsUnion], // [_[]BetaManagedAgentsMCPToolConfigParams] type betaAgentUpdateParamsToolUnionConfigs struct{ any } // Use the following switch statement to get the type of the union: // // switch u.AsAny().(type) { -// case *[]anthropic.BetaManagedAgentsAgentToolConfigParams: +// case *[]anthropic.BetaManagedAgentsAgentToolConfigParamsUnion: // case *[]anthropic.BetaManagedAgentsMCPToolConfigParams: // default: // fmt.Errorf("not present") @@ -2198,7 +4762,7 @@ type BetaAgentListParams struct { // URLQuery serializes [BetaAgentListParams]'s query parameters as `url.Values`. func (r BetaAgentListParams) URLQuery() (v url.Values, err error) { return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ - ArrayFormat: apiquery.ArrayQueryFormatComma, + ArrayFormat: apiquery.ArrayQueryFormatBrackets, NestedFormat: apiquery.NestedQueryFormatBrackets, }) } diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/betaagentversion.go b/vendor/github.com/anthropics/anthropic-sdk-go/betaagentversion.go index 84f06e0a2..bc5192f1b 100644 --- a/vendor/github.com/anthropics/anthropic-sdk-go/betaagentversion.go +++ b/vendor/github.com/anthropics/anthropic-sdk-go/betaagentversion.go @@ -80,7 +80,7 @@ type BetaAgentVersionListParams struct { // `url.Values`. func (r BetaAgentVersionListParams) URLQuery() (v url.Values, err error) { return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ - ArrayFormat: apiquery.ArrayQueryFormatComma, + ArrayFormat: apiquery.ArrayQueryFormatBrackets, NestedFormat: apiquery.NestedQueryFormatBrackets, }) } diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/betadeployment.go b/vendor/github.com/anthropics/anthropic-sdk-go/betadeployment.go new file mode 100644 index 000000000..69cdf6c04 --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/betadeployment.go @@ -0,0 +1,2255 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +package anthropic + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/url" + "slices" + "time" + + "github.com/anthropics/anthropic-sdk-go/internal/apijson" + "github.com/anthropics/anthropic-sdk-go/internal/apiquery" + "github.com/anthropics/anthropic-sdk-go/internal/requestconfig" + "github.com/anthropics/anthropic-sdk-go/option" + "github.com/anthropics/anthropic-sdk-go/packages/pagination" + "github.com/anthropics/anthropic-sdk-go/packages/param" + "github.com/anthropics/anthropic-sdk-go/packages/respjson" +) + +// BetaDeploymentService contains methods and other services that help with +// interacting with the anthropic API. +// +// Note, unlike clients, this service does not read variables from the environment +// automatically. You should not instantiate this service directly, and instead use +// the [NewBetaDeploymentService] method instead. +type BetaDeploymentService struct { + Options []option.RequestOption +} + +// NewBetaDeploymentService generates a new service that applies the given options +// to each request. These options are applied after the parent client's options (if +// there is one), and before any request-specific options. +func NewBetaDeploymentService(opts ...option.RequestOption) (r BetaDeploymentService) { + r = BetaDeploymentService{} + r.Options = opts + return +} + +// Create Deployment +func (r *BetaDeploymentService) New(ctx context.Context, params BetaDeploymentNewParams, opts ...option.RequestOption) (res *BetaManagedAgentsDeployment, err error) { + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "managed-agents-2026-04-01")}, opts...) + path := "v1/deployments?beta=true" + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, params, &res, opts...) + return res, err +} + +// Get Deployment +func (r *BetaDeploymentService) Get(ctx context.Context, deploymentID string, query BetaDeploymentGetParams, opts ...option.RequestOption) (res *BetaManagedAgentsDeployment, err error) { + for _, v := range query.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "managed-agents-2026-04-01")}, opts...) + if deploymentID == "" { + err = errors.New("missing required deployment_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/deployments/%s?beta=true", deploymentID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...) + return res, err +} + +// Update Deployment +func (r *BetaDeploymentService) Update(ctx context.Context, deploymentID string, params BetaDeploymentUpdateParams, opts ...option.RequestOption) (res *BetaManagedAgentsDeployment, err error) { + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "managed-agents-2026-04-01")}, opts...) + if deploymentID == "" { + err = errors.New("missing required deployment_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/deployments/%s?beta=true", deploymentID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, params, &res, opts...) + return res, err +} + +// List Deployments +func (r *BetaDeploymentService) List(ctx context.Context, params BetaDeploymentListParams, opts ...option.RequestOption) (res *pagination.PageCursor[BetaManagedAgentsDeployment], err error) { + var raw *http.Response + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "managed-agents-2026-04-01"), option.WithResponseInto(&raw)}, opts...) + path := "v1/deployments?beta=true" + cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, params, &res, opts...) + if err != nil { + return nil, err + } + err = cfg.Execute() + if err != nil { + return nil, err + } + res.SetPageConfig(cfg, raw) + return res, nil +} + +// List Deployments +func (r *BetaDeploymentService) ListAutoPaging(ctx context.Context, params BetaDeploymentListParams, opts ...option.RequestOption) *pagination.PageCursorAutoPager[BetaManagedAgentsDeployment] { + return pagination.NewPageCursorAutoPager(r.List(ctx, params, opts...)) +} + +// Archive Deployment +func (r *BetaDeploymentService) Archive(ctx context.Context, deploymentID string, body BetaDeploymentArchiveParams, opts ...option.RequestOption) (res *BetaManagedAgentsDeployment, err error) { + for _, v := range body.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "managed-agents-2026-04-01")}, opts...) + if deploymentID == "" { + err = errors.New("missing required deployment_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/deployments/%s/archive?beta=true", deploymentID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, nil, &res, opts...) + return res, err +} + +// Pause Deployment +func (r *BetaDeploymentService) Pause(ctx context.Context, deploymentID string, body BetaDeploymentPauseParams, opts ...option.RequestOption) (res *BetaManagedAgentsDeployment, err error) { + for _, v := range body.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "managed-agents-2026-04-01")}, opts...) + if deploymentID == "" { + err = errors.New("missing required deployment_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/deployments/%s/pause?beta=true", deploymentID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, nil, &res, opts...) + return res, err +} + +// Run Deployment Now +func (r *BetaDeploymentService) Run(ctx context.Context, deploymentID string, body BetaDeploymentRunParams, opts ...option.RequestOption) (res *BetaManagedAgentsDeploymentRun, err error) { + for _, v := range body.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "managed-agents-2026-04-01")}, opts...) + if deploymentID == "" { + err = errors.New("missing required deployment_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/deployments/%s/run?beta=true", deploymentID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, nil, &res, opts...) + return res, err +} + +// Unpause Deployment +func (r *BetaDeploymentService) Unpause(ctx context.Context, deploymentID string, body BetaDeploymentUnpauseParams, opts ...option.RequestOption) (res *BetaManagedAgentsDeployment, err error) { + for _, v := range body.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "managed-agents-2026-04-01")}, opts...) + if deploymentID == "" { + err = errors.New("missing required deployment_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/deployments/%s/unpause?beta=true", deploymentID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, nil, &res, opts...) + return res, err +} + +// The deployment's agent was archived. +type BetaManagedAgentsAgentArchivedDeploymentPausedReasonError struct { + // Any of "agent_archived_error". + Type BetaManagedAgentsAgentArchivedDeploymentPausedReasonErrorType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsAgentArchivedDeploymentPausedReasonError) RawJSON() string { + return r.JSON.raw +} +func (r *BetaManagedAgentsAgentArchivedDeploymentPausedReasonError) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsAgentArchivedDeploymentPausedReasonErrorType string + +const ( + BetaManagedAgentsAgentArchivedDeploymentPausedReasonErrorTypeAgentArchivedError BetaManagedAgentsAgentArchivedDeploymentPausedReasonErrorType = "agent_archived_error" +) + +// A deployment is a configured instance of an agent — it binds the agent to +// everything needed to run it autonomously: an environment, credentials, initial +// events, and an optional schedule. +type BetaManagedAgentsDeployment struct { + // Unique identifier for this deployment. + ID string `json:"id" api:"required"` + // A resolved agent reference with a concrete version. + Agent BetaManagedAgentsAgentReference `json:"agent" api:"required"` + // A timestamp in RFC 3339 format + ArchivedAt time.Time `json:"archived_at" api:"required" format:"date-time"` + // A timestamp in RFC 3339 format + CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"` + // Description of what the deployment does. + Description string `json:"description" api:"required"` + // ID of the `environment` where sessions run. + EnvironmentID string `json:"environment_id" api:"required"` + // Events sent to each session immediately after creation. + InitialEvents []BetaManagedAgentsDeploymentInitialEventUnion `json:"initial_events" api:"required"` + // Arbitrary key-value metadata. Maximum 16 pairs. + Metadata map[string]string `json:"metadata" api:"required"` + // Human-readable name. + Name string `json:"name" api:"required"` + // Why a deployment is paused. Non-null exactly when `status` is `paused`. + PausedReason BetaManagedAgentsDeploymentPausedReasonUnion `json:"paused_reason" api:"required"` + // Resources attached to sessions created from this deployment. Echoes the input + // minus write-only credentials. + Resources []BetaManagedAgentsSessionResourceConfigUnion `json:"resources" api:"required"` + // 5-field POSIX cron schedule with computed runtime timestamps. + Schedule BetaManagedAgentsSchedule `json:"schedule" api:"required"` + // Lifecycle status of a deployment. + // + // Any of "active", "paused". + Status BetaManagedAgentsDeploymentStatus `json:"status" api:"required"` + // Any of "deployment". + Type BetaManagedAgentsDeploymentType `json:"type" api:"required"` + // A timestamp in RFC 3339 format + UpdatedAt time.Time `json:"updated_at" api:"required" format:"date-time"` + // Vault IDs supplying stored credentials for sessions created from this + // deployment. + VaultIDs []string `json:"vault_ids" api:"required"` + // A hard spend ceiling. The session stops issuing new model requests once the + // tracked list cost reaches `max_list_cost`. + Budget BetaManagedAgentsBudgetLimit `json:"budget" api:"nullable"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + Agent respjson.Field + ArchivedAt respjson.Field + CreatedAt respjson.Field + Description respjson.Field + EnvironmentID respjson.Field + InitialEvents respjson.Field + Metadata respjson.Field + Name respjson.Field + PausedReason respjson.Field + Resources respjson.Field + Schedule respjson.Field + Status respjson.Field + Type respjson.Field + UpdatedAt respjson.Field + VaultIDs respjson.Field + Budget respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsDeployment) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsDeployment) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsDeploymentType string + +const ( + BetaManagedAgentsDeploymentTypeDeployment BetaManagedAgentsDeploymentType = "deployment" +) + +// BetaManagedAgentsDeploymentInitialEventUnion contains all possible properties +// and values from [BetaManagedAgentsDeploymentUserMessageEvent], +// [BetaManagedAgentsDeploymentUserDefineOutcomeEvent], +// [BetaManagedAgentsDeploymentSystemMessageEvent]. +// +// Use the [BetaManagedAgentsDeploymentInitialEventUnion.AsAny] method to switch on +// the variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaManagedAgentsDeploymentInitialEventUnion struct { + // This field is a union of + // [[]BetaManagedAgentsDeploymentUserMessageEventContentUnion], + // [[]BetaManagedAgentsSystemContentBlock] + Content BetaManagedAgentsDeploymentInitialEventUnionContent `json:"content"` + // Any of "user.message", "user.define_outcome", "system.message". + Type string `json:"type"` + // This field is from variant [BetaManagedAgentsDeploymentUserDefineOutcomeEvent]. + Description string `json:"description"` + // This field is from variant [BetaManagedAgentsDeploymentUserDefineOutcomeEvent]. + Rubric BetaManagedAgentsDeploymentUserDefineOutcomeEventRubricUnion `json:"rubric"` + // This field is from variant [BetaManagedAgentsDeploymentUserDefineOutcomeEvent]. + MaxIterations int64 `json:"max_iterations"` + JSON struct { + Content respjson.Field + Type respjson.Field + Description respjson.Field + Rubric respjson.Field + MaxIterations respjson.Field + raw string + } `json:"-"` +} + +// anyBetaManagedAgentsDeploymentInitialEvent is implemented by each variant of +// [BetaManagedAgentsDeploymentInitialEventUnion] to add type safety for the return +// type of [BetaManagedAgentsDeploymentInitialEventUnion.AsAny] +type anyBetaManagedAgentsDeploymentInitialEvent interface { + implBetaManagedAgentsDeploymentInitialEventUnion() +} + +func (BetaManagedAgentsDeploymentUserMessageEvent) implBetaManagedAgentsDeploymentInitialEventUnion() { +} +func (BetaManagedAgentsDeploymentUserDefineOutcomeEvent) implBetaManagedAgentsDeploymentInitialEventUnion() { +} +func (BetaManagedAgentsDeploymentSystemMessageEvent) implBetaManagedAgentsDeploymentInitialEventUnion() { +} + +// Use the following switch statement to find the correct variant +// +// switch variant := BetaManagedAgentsDeploymentInitialEventUnion.AsAny().(type) { +// case anthropic.BetaManagedAgentsDeploymentUserMessageEvent: +// case anthropic.BetaManagedAgentsDeploymentUserDefineOutcomeEvent: +// case anthropic.BetaManagedAgentsDeploymentSystemMessageEvent: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaManagedAgentsDeploymentInitialEventUnion) AsAny() anyBetaManagedAgentsDeploymentInitialEvent { + switch u.Type { + case "user.message": + return u.AsUserMessage() + case "user.define_outcome": + return u.AsUserDefineOutcome() + case "system.message": + return u.AsSystemMessage() + } + return nil +} + +func (u BetaManagedAgentsDeploymentInitialEventUnion) AsUserMessage() (v BetaManagedAgentsDeploymentUserMessageEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsDeploymentInitialEventUnion) AsUserDefineOutcome() (v BetaManagedAgentsDeploymentUserDefineOutcomeEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsDeploymentInitialEventUnion) AsSystemMessage() (v BetaManagedAgentsDeploymentSystemMessageEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u BetaManagedAgentsDeploymentInitialEventUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaManagedAgentsDeploymentInitialEventUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaManagedAgentsDeploymentInitialEventUnionContent is an implicit subunion of +// [BetaManagedAgentsDeploymentInitialEventUnion]. +// BetaManagedAgentsDeploymentInitialEventUnionContent provides convenient access +// to the sub-properties of the union. +// +// For type safety it is recommended to directly use a variant of the +// [BetaManagedAgentsDeploymentInitialEventUnion]. +// +// If the underlying value is not a json object, one of the following properties +// will be valid: OfBetaManagedAgentsDeploymentUserMessageEventContentArray +// OfBetaManagedAgentsSystemContentBlockArray] +type BetaManagedAgentsDeploymentInitialEventUnionContent struct { + // This field will be present if the value is a + // [[]BetaManagedAgentsDeploymentUserMessageEventContentUnion] instead of an + // object. + OfBetaManagedAgentsDeploymentUserMessageEventContentArray []BetaManagedAgentsDeploymentUserMessageEventContentUnion `json:",inline"` + // This field will be present if the value is a + // [[]BetaManagedAgentsSystemContentBlock] instead of an object. + OfBetaManagedAgentsSystemContentBlockArray []BetaManagedAgentsSystemContentBlock `json:",inline"` + JSON struct { + OfBetaManagedAgentsDeploymentUserMessageEventContentArray respjson.Field + OfBetaManagedAgentsSystemContentBlockArray respjson.Field + raw string + } `json:"-"` +} + +func (r *BetaManagedAgentsDeploymentInitialEventUnionContent) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +func BetaManagedAgentsDeploymentInitialEventParamsOfUserMessage(content []BetaManagedAgentsUserMessageEventParamsContentUnion) BetaManagedAgentsDeploymentInitialEventParamsUnion { + var userMessage BetaManagedAgentsUserMessageEventParams + userMessage.Content = content + return BetaManagedAgentsDeploymentInitialEventParamsUnion{OfUserMessage: &userMessage} +} + +func BetaManagedAgentsDeploymentInitialEventParamsOfUserDefineOutcome[ + T BetaManagedAgentsFileRubricParams | BetaManagedAgentsTextRubricParams, +](description string, rubric T, type_ BetaManagedAgentsUserDefineOutcomeEventParamsType) BetaManagedAgentsDeploymentInitialEventParamsUnion { + var userDefineOutcome BetaManagedAgentsUserDefineOutcomeEventParams + userDefineOutcome.Description = description + switch v := any(rubric).(type) { + case BetaManagedAgentsFileRubricParams: + userDefineOutcome.Rubric.OfFile = &v + case BetaManagedAgentsTextRubricParams: + userDefineOutcome.Rubric.OfText = &v + } + userDefineOutcome.Type = type_ + return BetaManagedAgentsDeploymentInitialEventParamsUnion{OfUserDefineOutcome: &userDefineOutcome} +} + +func BetaManagedAgentsDeploymentInitialEventParamsOfSystemMessage(content []BetaManagedAgentsSystemContentBlockParam) BetaManagedAgentsDeploymentInitialEventParamsUnion { + var systemMessage BetaManagedAgentsSystemMessageEventParams + systemMessage.Content = content + return BetaManagedAgentsDeploymentInitialEventParamsUnion{OfSystemMessage: &systemMessage} +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaManagedAgentsDeploymentInitialEventParamsUnion struct { + OfUserMessage *BetaManagedAgentsUserMessageEventParams `json:",omitzero,inline"` + OfUserDefineOutcome *BetaManagedAgentsUserDefineOutcomeEventParams `json:",omitzero,inline"` + OfSystemMessage *BetaManagedAgentsSystemMessageEventParams `json:",omitzero,inline"` + paramUnion +} + +func (u BetaManagedAgentsDeploymentInitialEventParamsUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfUserMessage, u.OfUserDefineOutcome, u.OfSystemMessage) +} +func (u *BetaManagedAgentsDeploymentInitialEventParamsUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *BetaManagedAgentsDeploymentInitialEventParamsUnion) asAny() any { + if !param.IsOmitted(u.OfUserMessage) { + return u.OfUserMessage + } else if !param.IsOmitted(u.OfUserDefineOutcome) { + return u.OfUserDefineOutcome + } else if !param.IsOmitted(u.OfSystemMessage) { + return u.OfSystemMessage + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaManagedAgentsDeploymentInitialEventParamsUnion) GetDescription() *string { + if vt := u.OfUserDefineOutcome; vt != nil { + return &vt.Description + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaManagedAgentsDeploymentInitialEventParamsUnion) GetRubric() *BetaManagedAgentsUserDefineOutcomeEventParamsRubricUnion { + if vt := u.OfUserDefineOutcome; vt != nil { + return &vt.Rubric + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaManagedAgentsDeploymentInitialEventParamsUnion) GetMaxIterations() *int64 { + if vt := u.OfUserDefineOutcome; vt != nil && vt.MaxIterations.Valid() { + return &vt.MaxIterations.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaManagedAgentsDeploymentInitialEventParamsUnion) GetType() *string { + if vt := u.OfUserMessage; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfUserDefineOutcome; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfSystemMessage; vt != nil { + return (*string)(&vt.Type) + } + return nil +} + +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u BetaManagedAgentsDeploymentInitialEventParamsUnion) GetContent() (res betaManagedAgentsDeploymentInitialEventParamsUnionContent) { + if vt := u.OfUserMessage; vt != nil { + res.any = &vt.Content + } else if vt := u.OfSystemMessage; vt != nil { + res.any = &vt.Content + } + return +} + +// Can have the runtime types +// [_[]BetaManagedAgentsUserMessageEventParamsContentUnion], +// [_[]BetaManagedAgentsSystemContentBlockParam] +type betaManagedAgentsDeploymentInitialEventParamsUnionContent struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *[]anthropic.BetaManagedAgentsUserMessageEventParamsContentUnion: +// case *[]anthropic.BetaManagedAgentsSystemContentBlockParam: +// default: +// fmt.Errorf("not present") +// } +func (u betaManagedAgentsDeploymentInitialEventParamsUnionContent) AsAny() any { return u.any } + +func init() { + apijson.RegisterUnion[BetaManagedAgentsDeploymentInitialEventParamsUnion]( + "type", + apijson.Discriminator[BetaManagedAgentsUserMessageEventParams]("user.message"), + apijson.Discriminator[BetaManagedAgentsUserDefineOutcomeEventParams]("user.define_outcome"), + apijson.Discriminator[BetaManagedAgentsSystemMessageEventParams]("system.message"), + ) +} + +// BetaManagedAgentsDeploymentPausedReasonUnion contains all possible properties +// and values from [BetaManagedAgentsManualDeploymentPausedReason], +// [BetaManagedAgentsErrorDeploymentPausedReason]. +// +// Use the [BetaManagedAgentsDeploymentPausedReasonUnion.AsAny] method to switch on +// the variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaManagedAgentsDeploymentPausedReasonUnion struct { + // Any of "manual", "error". + Type string `json:"type"` + // This field is from variant [BetaManagedAgentsErrorDeploymentPausedReason]. + Error BetaManagedAgentsDeploymentPausedReasonErrorUnion `json:"error"` + JSON struct { + Type respjson.Field + Error respjson.Field + raw string + } `json:"-"` +} + +// anyBetaManagedAgentsDeploymentPausedReason is implemented by each variant of +// [BetaManagedAgentsDeploymentPausedReasonUnion] to add type safety for the return +// type of [BetaManagedAgentsDeploymentPausedReasonUnion.AsAny] +type anyBetaManagedAgentsDeploymentPausedReason interface { + implBetaManagedAgentsDeploymentPausedReasonUnion() +} + +func (BetaManagedAgentsManualDeploymentPausedReason) implBetaManagedAgentsDeploymentPausedReasonUnion() { +} +func (BetaManagedAgentsErrorDeploymentPausedReason) implBetaManagedAgentsDeploymentPausedReasonUnion() { +} + +// Use the following switch statement to find the correct variant +// +// switch variant := BetaManagedAgentsDeploymentPausedReasonUnion.AsAny().(type) { +// case anthropic.BetaManagedAgentsManualDeploymentPausedReason: +// case anthropic.BetaManagedAgentsErrorDeploymentPausedReason: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaManagedAgentsDeploymentPausedReasonUnion) AsAny() anyBetaManagedAgentsDeploymentPausedReason { + switch u.Type { + case "manual": + return u.AsManual() + case "error": + return u.AsError() + } + return nil +} + +func (u BetaManagedAgentsDeploymentPausedReasonUnion) AsManual() (v BetaManagedAgentsManualDeploymentPausedReason) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsDeploymentPausedReasonUnion) AsError() (v BetaManagedAgentsErrorDeploymentPausedReason) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u BetaManagedAgentsDeploymentPausedReasonUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaManagedAgentsDeploymentPausedReasonUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaManagedAgentsDeploymentPausedReasonErrorUnion contains all possible +// properties and values from +// [BetaManagedAgentsEnvironmentArchivedDeploymentPausedReasonError], +// [BetaManagedAgentsAgentArchivedDeploymentPausedReasonError], +// [BetaManagedAgentsEnvironmentNotFoundDeploymentPausedReasonError], +// [BetaManagedAgentsVaultNotFoundDeploymentPausedReasonError], +// [BetaManagedAgentsFileNotFoundDeploymentPausedReasonError], +// [BetaManagedAgentsSessionResourceNotFoundDeploymentPausedReasonError], +// [BetaManagedAgentsWorkspaceArchivedDeploymentPausedReasonError], +// [BetaManagedAgentsOrganizationDisabledDeploymentPausedReasonError], +// [BetaManagedAgentsMemoryStoreArchivedDeploymentPausedReasonError], +// [BetaManagedAgentsSkillNotFoundDeploymentPausedReasonError], +// [BetaManagedAgentsVaultArchivedDeploymentPausedReasonError], +// [BetaManagedAgentsUnknownDeploymentPausedReasonError], +// [BetaManagedAgentsSelfHostedResourcesUnsupportedDeploymentPausedReasonError], +// [BetaManagedAgentsMCPEgressBlockedDeploymentPausedReasonError]. +// +// Use the [BetaManagedAgentsDeploymentPausedReasonErrorUnion.AsAny] method to +// switch on the variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaManagedAgentsDeploymentPausedReasonErrorUnion struct { + // Any of "environment_archived_error", "agent_archived_error", + // "environment_not_found_error", "vault_not_found_error", "file_not_found_error", + // "session_resource_not_found_error", "workspace_archived_error", + // "organization_disabled_error", "memory_store_archived_error", + // "skill_not_found_error", "vault_archived_error", "unknown_error", + // "self_hosted_resources_unsupported_error", "mcp_egress_blocked_error". + Type string `json:"type"` + JSON struct { + Type respjson.Field + raw string + } `json:"-"` +} + +// anyBetaManagedAgentsDeploymentPausedReasonError is implemented by each variant +// of [BetaManagedAgentsDeploymentPausedReasonErrorUnion] to add type safety for +// the return type of [BetaManagedAgentsDeploymentPausedReasonErrorUnion.AsAny] +type anyBetaManagedAgentsDeploymentPausedReasonError interface { + implBetaManagedAgentsDeploymentPausedReasonErrorUnion() +} + +func (BetaManagedAgentsEnvironmentArchivedDeploymentPausedReasonError) implBetaManagedAgentsDeploymentPausedReasonErrorUnion() { +} +func (BetaManagedAgentsAgentArchivedDeploymentPausedReasonError) implBetaManagedAgentsDeploymentPausedReasonErrorUnion() { +} +func (BetaManagedAgentsEnvironmentNotFoundDeploymentPausedReasonError) implBetaManagedAgentsDeploymentPausedReasonErrorUnion() { +} +func (BetaManagedAgentsVaultNotFoundDeploymentPausedReasonError) implBetaManagedAgentsDeploymentPausedReasonErrorUnion() { +} +func (BetaManagedAgentsFileNotFoundDeploymentPausedReasonError) implBetaManagedAgentsDeploymentPausedReasonErrorUnion() { +} +func (BetaManagedAgentsSessionResourceNotFoundDeploymentPausedReasonError) implBetaManagedAgentsDeploymentPausedReasonErrorUnion() { +} +func (BetaManagedAgentsWorkspaceArchivedDeploymentPausedReasonError) implBetaManagedAgentsDeploymentPausedReasonErrorUnion() { +} +func (BetaManagedAgentsOrganizationDisabledDeploymentPausedReasonError) implBetaManagedAgentsDeploymentPausedReasonErrorUnion() { +} +func (BetaManagedAgentsMemoryStoreArchivedDeploymentPausedReasonError) implBetaManagedAgentsDeploymentPausedReasonErrorUnion() { +} +func (BetaManagedAgentsSkillNotFoundDeploymentPausedReasonError) implBetaManagedAgentsDeploymentPausedReasonErrorUnion() { +} +func (BetaManagedAgentsVaultArchivedDeploymentPausedReasonError) implBetaManagedAgentsDeploymentPausedReasonErrorUnion() { +} +func (BetaManagedAgentsUnknownDeploymentPausedReasonError) implBetaManagedAgentsDeploymentPausedReasonErrorUnion() { +} +func (BetaManagedAgentsSelfHostedResourcesUnsupportedDeploymentPausedReasonError) implBetaManagedAgentsDeploymentPausedReasonErrorUnion() { +} +func (BetaManagedAgentsMCPEgressBlockedDeploymentPausedReasonError) implBetaManagedAgentsDeploymentPausedReasonErrorUnion() { +} + +// Use the following switch statement to find the correct variant +// +// switch variant := BetaManagedAgentsDeploymentPausedReasonErrorUnion.AsAny().(type) { +// case anthropic.BetaManagedAgentsEnvironmentArchivedDeploymentPausedReasonError: +// case anthropic.BetaManagedAgentsAgentArchivedDeploymentPausedReasonError: +// case anthropic.BetaManagedAgentsEnvironmentNotFoundDeploymentPausedReasonError: +// case anthropic.BetaManagedAgentsVaultNotFoundDeploymentPausedReasonError: +// case anthropic.BetaManagedAgentsFileNotFoundDeploymentPausedReasonError: +// case anthropic.BetaManagedAgentsSessionResourceNotFoundDeploymentPausedReasonError: +// case anthropic.BetaManagedAgentsWorkspaceArchivedDeploymentPausedReasonError: +// case anthropic.BetaManagedAgentsOrganizationDisabledDeploymentPausedReasonError: +// case anthropic.BetaManagedAgentsMemoryStoreArchivedDeploymentPausedReasonError: +// case anthropic.BetaManagedAgentsSkillNotFoundDeploymentPausedReasonError: +// case anthropic.BetaManagedAgentsVaultArchivedDeploymentPausedReasonError: +// case anthropic.BetaManagedAgentsUnknownDeploymentPausedReasonError: +// case anthropic.BetaManagedAgentsSelfHostedResourcesUnsupportedDeploymentPausedReasonError: +// case anthropic.BetaManagedAgentsMCPEgressBlockedDeploymentPausedReasonError: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaManagedAgentsDeploymentPausedReasonErrorUnion) AsAny() anyBetaManagedAgentsDeploymentPausedReasonError { + switch u.Type { + case "environment_archived_error": + return u.AsEnvironmentArchivedError() + case "agent_archived_error": + return u.AsAgentArchivedError() + case "environment_not_found_error": + return u.AsEnvironmentNotFoundError() + case "vault_not_found_error": + return u.AsVaultNotFoundError() + case "file_not_found_error": + return u.AsFileNotFoundError() + case "session_resource_not_found_error": + return u.AsSessionResourceNotFoundError() + case "workspace_archived_error": + return u.AsWorkspaceArchivedError() + case "organization_disabled_error": + return u.AsOrganizationDisabledError() + case "memory_store_archived_error": + return u.AsMemoryStoreArchivedError() + case "skill_not_found_error": + return u.AsSkillNotFoundError() + case "vault_archived_error": + return u.AsVaultArchivedError() + case "unknown_error": + return u.AsUnknownError() + case "self_hosted_resources_unsupported_error": + return u.AsSelfHostedResourcesUnsupportedError() + case "mcp_egress_blocked_error": + return u.AsMCPEgressBlockedError() + } + return nil +} + +func (u BetaManagedAgentsDeploymentPausedReasonErrorUnion) AsEnvironmentArchivedError() (v BetaManagedAgentsEnvironmentArchivedDeploymentPausedReasonError) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsDeploymentPausedReasonErrorUnion) AsAgentArchivedError() (v BetaManagedAgentsAgentArchivedDeploymentPausedReasonError) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsDeploymentPausedReasonErrorUnion) AsEnvironmentNotFoundError() (v BetaManagedAgentsEnvironmentNotFoundDeploymentPausedReasonError) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsDeploymentPausedReasonErrorUnion) AsVaultNotFoundError() (v BetaManagedAgentsVaultNotFoundDeploymentPausedReasonError) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsDeploymentPausedReasonErrorUnion) AsFileNotFoundError() (v BetaManagedAgentsFileNotFoundDeploymentPausedReasonError) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsDeploymentPausedReasonErrorUnion) AsSessionResourceNotFoundError() (v BetaManagedAgentsSessionResourceNotFoundDeploymentPausedReasonError) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsDeploymentPausedReasonErrorUnion) AsWorkspaceArchivedError() (v BetaManagedAgentsWorkspaceArchivedDeploymentPausedReasonError) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsDeploymentPausedReasonErrorUnion) AsOrganizationDisabledError() (v BetaManagedAgentsOrganizationDisabledDeploymentPausedReasonError) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsDeploymentPausedReasonErrorUnion) AsMemoryStoreArchivedError() (v BetaManagedAgentsMemoryStoreArchivedDeploymentPausedReasonError) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsDeploymentPausedReasonErrorUnion) AsSkillNotFoundError() (v BetaManagedAgentsSkillNotFoundDeploymentPausedReasonError) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsDeploymentPausedReasonErrorUnion) AsVaultArchivedError() (v BetaManagedAgentsVaultArchivedDeploymentPausedReasonError) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsDeploymentPausedReasonErrorUnion) AsUnknownError() (v BetaManagedAgentsUnknownDeploymentPausedReasonError) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsDeploymentPausedReasonErrorUnion) AsSelfHostedResourcesUnsupportedError() (v BetaManagedAgentsSelfHostedResourcesUnsupportedDeploymentPausedReasonError) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsDeploymentPausedReasonErrorUnion) AsMCPEgressBlockedError() (v BetaManagedAgentsMCPEgressBlockedDeploymentPausedReasonError) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u BetaManagedAgentsDeploymentPausedReasonErrorUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaManagedAgentsDeploymentPausedReasonErrorUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Lifecycle status of a deployment. +type BetaManagedAgentsDeploymentStatus string + +const ( + BetaManagedAgentsDeploymentStatusActive BetaManagedAgentsDeploymentStatus = "active" + BetaManagedAgentsDeploymentStatusPaused BetaManagedAgentsDeploymentStatus = "paused" +) + +// Privileged context for the accompanying turn and all subsequent turns, appended +// to the session's system context as a `role: "system"` turn rather than replacing +// the top-level system prompt. +type BetaManagedAgentsDeploymentSystemMessageEvent struct { + // System content blocks to append. Text-only. + Content []BetaManagedAgentsSystemContentBlock `json:"content" api:"required"` + // Any of "system.message". + Type BetaManagedAgentsDeploymentSystemMessageEventType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Content respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsDeploymentSystemMessageEvent) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsDeploymentSystemMessageEvent) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsDeploymentSystemMessageEventType string + +const ( + BetaManagedAgentsDeploymentSystemMessageEventTypeSystemMessage BetaManagedAgentsDeploymentSystemMessageEventType = "system.message" +) + +// An outcome the agent should work toward. The agent begins work on receipt. +type BetaManagedAgentsDeploymentUserDefineOutcomeEvent struct { + // What the agent should produce. This is the task specification. + Description string `json:"description" api:"required"` + // Rubric for grading the quality of an outcome. + Rubric BetaManagedAgentsDeploymentUserDefineOutcomeEventRubricUnion `json:"rubric" api:"required"` + // Any of "user.define_outcome". + Type BetaManagedAgentsDeploymentUserDefineOutcomeEventType `json:"type" api:"required"` + // Eval→revision cycles before giving up. Default 3, max 20. + MaxIterations int64 `json:"max_iterations" api:"nullable"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Description respjson.Field + Rubric respjson.Field + Type respjson.Field + MaxIterations respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsDeploymentUserDefineOutcomeEvent) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsDeploymentUserDefineOutcomeEvent) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaManagedAgentsDeploymentUserDefineOutcomeEventRubricUnion contains all +// possible properties and values from [BetaManagedAgentsFileRubric], +// [BetaManagedAgentsTextRubric]. +// +// Use the [BetaManagedAgentsDeploymentUserDefineOutcomeEventRubricUnion.AsAny] +// method to switch on the variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaManagedAgentsDeploymentUserDefineOutcomeEventRubricUnion struct { + // This field is from variant [BetaManagedAgentsFileRubric]. + FileID string `json:"file_id"` + // Any of "file", "text". + Type string `json:"type"` + // This field is from variant [BetaManagedAgentsTextRubric]. + Content string `json:"content"` + JSON struct { + FileID respjson.Field + Type respjson.Field + Content respjson.Field + raw string + } `json:"-"` +} + +// anyBetaManagedAgentsDeploymentUserDefineOutcomeEventRubric is implemented by +// each variant of [BetaManagedAgentsDeploymentUserDefineOutcomeEventRubricUnion] +// to add type safety for the return type of +// [BetaManagedAgentsDeploymentUserDefineOutcomeEventRubricUnion.AsAny] +type anyBetaManagedAgentsDeploymentUserDefineOutcomeEventRubric interface { + implBetaManagedAgentsDeploymentUserDefineOutcomeEventRubricUnion() +} + +func (BetaManagedAgentsFileRubric) implBetaManagedAgentsDeploymentUserDefineOutcomeEventRubricUnion() { +} +func (BetaManagedAgentsTextRubric) implBetaManagedAgentsDeploymentUserDefineOutcomeEventRubricUnion() { +} + +// Use the following switch statement to find the correct variant +// +// switch variant := BetaManagedAgentsDeploymentUserDefineOutcomeEventRubricUnion.AsAny().(type) { +// case anthropic.BetaManagedAgentsFileRubric: +// case anthropic.BetaManagedAgentsTextRubric: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaManagedAgentsDeploymentUserDefineOutcomeEventRubricUnion) AsAny() anyBetaManagedAgentsDeploymentUserDefineOutcomeEventRubric { + switch u.Type { + case "file": + return u.AsFile() + case "text": + return u.AsText() + } + return nil +} + +func (u BetaManagedAgentsDeploymentUserDefineOutcomeEventRubricUnion) AsFile() (v BetaManagedAgentsFileRubric) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsDeploymentUserDefineOutcomeEventRubricUnion) AsText() (v BetaManagedAgentsTextRubric) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u BetaManagedAgentsDeploymentUserDefineOutcomeEventRubricUnion) RawJSON() string { + return u.JSON.raw +} + +func (r *BetaManagedAgentsDeploymentUserDefineOutcomeEventRubricUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsDeploymentUserDefineOutcomeEventType string + +const ( + BetaManagedAgentsDeploymentUserDefineOutcomeEventTypeUserDefineOutcome BetaManagedAgentsDeploymentUserDefineOutcomeEventType = "user.define_outcome" +) + +// A user message sent to the session. +type BetaManagedAgentsDeploymentUserMessageEvent struct { + // Array of content blocks for the user message. + Content []BetaManagedAgentsDeploymentUserMessageEventContentUnion `json:"content" api:"required"` + // Any of "user.message". + Type BetaManagedAgentsDeploymentUserMessageEventType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Content respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsDeploymentUserMessageEvent) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsDeploymentUserMessageEvent) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaManagedAgentsDeploymentUserMessageEventContentUnion contains all possible +// properties and values from [BetaManagedAgentsTextBlock], +// [BetaManagedAgentsImageBlock], [BetaManagedAgentsDocumentBlock], +// [BetaManagedAgentsRedactedBlock]. +// +// Use the [BetaManagedAgentsDeploymentUserMessageEventContentUnion.AsAny] method +// to switch on the variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaManagedAgentsDeploymentUserMessageEventContentUnion struct { + // This field is from variant [BetaManagedAgentsTextBlock]. + Text string `json:"text"` + // Any of "text", "image", "document", "redacted". + Type string `json:"type"` + // This field is a union of [BetaManagedAgentsImageBlockSourceUnion], + // [BetaManagedAgentsDocumentBlockSourceUnion] + Source BetaManagedAgentsDeploymentUserMessageEventContentUnionSource `json:"source"` + // This field is from variant [BetaManagedAgentsDocumentBlock]. + Context string `json:"context"` + // This field is from variant [BetaManagedAgentsDocumentBlock]. + Title string `json:"title"` + JSON struct { + Text respjson.Field + Type respjson.Field + Source respjson.Field + Context respjson.Field + Title respjson.Field + raw string + } `json:"-"` +} + +// anyBetaManagedAgentsDeploymentUserMessageEventContent is implemented by each +// variant of [BetaManagedAgentsDeploymentUserMessageEventContentUnion] to add type +// safety for the return type of +// [BetaManagedAgentsDeploymentUserMessageEventContentUnion.AsAny] +type anyBetaManagedAgentsDeploymentUserMessageEventContent interface { + implBetaManagedAgentsDeploymentUserMessageEventContentUnion() +} + +func (BetaManagedAgentsTextBlock) implBetaManagedAgentsDeploymentUserMessageEventContentUnion() {} +func (BetaManagedAgentsImageBlock) implBetaManagedAgentsDeploymentUserMessageEventContentUnion() {} +func (BetaManagedAgentsDocumentBlock) implBetaManagedAgentsDeploymentUserMessageEventContentUnion() {} +func (BetaManagedAgentsRedactedBlock) implBetaManagedAgentsDeploymentUserMessageEventContentUnion() {} + +// Use the following switch statement to find the correct variant +// +// switch variant := BetaManagedAgentsDeploymentUserMessageEventContentUnion.AsAny().(type) { +// case anthropic.BetaManagedAgentsTextBlock: +// case anthropic.BetaManagedAgentsImageBlock: +// case anthropic.BetaManagedAgentsDocumentBlock: +// case anthropic.BetaManagedAgentsRedactedBlock: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaManagedAgentsDeploymentUserMessageEventContentUnion) AsAny() anyBetaManagedAgentsDeploymentUserMessageEventContent { + switch u.Type { + case "text": + return u.AsText() + case "image": + return u.AsImage() + case "document": + return u.AsDocument() + case "redacted": + return u.AsRedacted() + } + return nil +} + +func (u BetaManagedAgentsDeploymentUserMessageEventContentUnion) AsText() (v BetaManagedAgentsTextBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsDeploymentUserMessageEventContentUnion) AsImage() (v BetaManagedAgentsImageBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsDeploymentUserMessageEventContentUnion) AsDocument() (v BetaManagedAgentsDocumentBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsDeploymentUserMessageEventContentUnion) AsRedacted() (v BetaManagedAgentsRedactedBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u BetaManagedAgentsDeploymentUserMessageEventContentUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaManagedAgentsDeploymentUserMessageEventContentUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaManagedAgentsDeploymentUserMessageEventContentUnionSource is an implicit +// subunion of [BetaManagedAgentsDeploymentUserMessageEventContentUnion]. +// BetaManagedAgentsDeploymentUserMessageEventContentUnionSource provides +// convenient access to the sub-properties of the union. +// +// For type safety it is recommended to directly use a variant of the +// [BetaManagedAgentsDeploymentUserMessageEventContentUnion]. +type BetaManagedAgentsDeploymentUserMessageEventContentUnionSource struct { + Data string `json:"data"` + MediaType string `json:"media_type"` + Type string `json:"type"` + URL string `json:"url"` + FileID string `json:"file_id"` + JSON struct { + Data respjson.Field + MediaType respjson.Field + Type respjson.Field + URL respjson.Field + FileID respjson.Field + raw string + } `json:"-"` +} + +func (r *BetaManagedAgentsDeploymentUserMessageEventContentUnionSource) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsDeploymentUserMessageEventType string + +const ( + BetaManagedAgentsDeploymentUserMessageEventTypeUserMessage BetaManagedAgentsDeploymentUserMessageEventType = "user.message" +) + +// The deployment's environment was archived. +type BetaManagedAgentsEnvironmentArchivedDeploymentPausedReasonError struct { + // Any of "environment_archived_error". + Type BetaManagedAgentsEnvironmentArchivedDeploymentPausedReasonErrorType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsEnvironmentArchivedDeploymentPausedReasonError) RawJSON() string { + return r.JSON.raw +} +func (r *BetaManagedAgentsEnvironmentArchivedDeploymentPausedReasonError) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsEnvironmentArchivedDeploymentPausedReasonErrorType string + +const ( + BetaManagedAgentsEnvironmentArchivedDeploymentPausedReasonErrorTypeEnvironmentArchivedError BetaManagedAgentsEnvironmentArchivedDeploymentPausedReasonErrorType = "environment_archived_error" +) + +// The deployment's environment no longer exists. +type BetaManagedAgentsEnvironmentNotFoundDeploymentPausedReasonError struct { + // Any of "environment_not_found_error". + Type BetaManagedAgentsEnvironmentNotFoundDeploymentPausedReasonErrorType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsEnvironmentNotFoundDeploymentPausedReasonError) RawJSON() string { + return r.JSON.raw +} +func (r *BetaManagedAgentsEnvironmentNotFoundDeploymentPausedReasonError) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsEnvironmentNotFoundDeploymentPausedReasonErrorType string + +const ( + BetaManagedAgentsEnvironmentNotFoundDeploymentPausedReasonErrorTypeEnvironmentNotFoundError BetaManagedAgentsEnvironmentNotFoundDeploymentPausedReasonErrorType = "environment_not_found_error" +) + +// A scheduled fire recorded a failed run whose error auto-pauses the deployment. +type BetaManagedAgentsErrorDeploymentPausedReason struct { + // The error that triggered an auto-pause. Matches the failed run's `error.type`. + Error BetaManagedAgentsDeploymentPausedReasonErrorUnion `json:"error" api:"required"` + // Any of "error". + Type BetaManagedAgentsErrorDeploymentPausedReasonType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Error respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsErrorDeploymentPausedReason) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsErrorDeploymentPausedReason) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsErrorDeploymentPausedReasonType string + +const ( + BetaManagedAgentsErrorDeploymentPausedReasonTypeError BetaManagedAgentsErrorDeploymentPausedReasonType = "error" +) + +// A file resource referenced by the deployment no longer exists. +type BetaManagedAgentsFileNotFoundDeploymentPausedReasonError struct { + // Any of "file_not_found_error". + Type BetaManagedAgentsFileNotFoundDeploymentPausedReasonErrorType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsFileNotFoundDeploymentPausedReasonError) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsFileNotFoundDeploymentPausedReasonError) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsFileNotFoundDeploymentPausedReasonErrorType string + +const ( + BetaManagedAgentsFileNotFoundDeploymentPausedReasonErrorTypeFileNotFoundError BetaManagedAgentsFileNotFoundDeploymentPausedReasonErrorType = "file_not_found_error" +) + +// A file mounted into each session's container. +type BetaManagedAgentsFileResourceConfig struct { + // ID of a previously uploaded file. + FileID string `json:"file_id" api:"required"` + // Any of "file". + Type BetaManagedAgentsFileResourceConfigType `json:"type" api:"required"` + // Mount path in the container. Defaults to `/mnt/session/uploads/`. + MountPath string `json:"mount_path" api:"nullable"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + FileID respjson.Field + Type respjson.Field + MountPath respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsFileResourceConfig) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsFileResourceConfig) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsFileResourceConfigType string + +const ( + BetaManagedAgentsFileResourceConfigTypeFile BetaManagedAgentsFileResourceConfigType = "file" +) + +// A GitHub repository mounted into each session's container. The authorization +// token is write-only and never returned. +type BetaManagedAgentsGitHubRepositoryResourceConfig struct { + // Any of "github_repository". + Type BetaManagedAgentsGitHubRepositoryResourceConfigType `json:"type" api:"required"` + // Github URL of the repository + URL string `json:"url" api:"required"` + // Branch or commit to check out. Defaults to the repository's default branch. + Checkout BetaManagedAgentsGitHubRepositoryResourceConfigCheckoutUnion `json:"checkout" api:"nullable"` + // Mount path in the container. Defaults to `/workspace/`. + MountPath string `json:"mount_path" api:"nullable"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Type respjson.Field + URL respjson.Field + Checkout respjson.Field + MountPath respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsGitHubRepositoryResourceConfig) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsGitHubRepositoryResourceConfig) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsGitHubRepositoryResourceConfigType string + +const ( + BetaManagedAgentsGitHubRepositoryResourceConfigTypeGitHubRepository BetaManagedAgentsGitHubRepositoryResourceConfigType = "github_repository" +) + +// BetaManagedAgentsGitHubRepositoryResourceConfigCheckoutUnion contains all +// possible properties and values from [BetaManagedAgentsBranchCheckout], +// [BetaManagedAgentsCommitCheckout]. +// +// Use the [BetaManagedAgentsGitHubRepositoryResourceConfigCheckoutUnion.AsAny] +// method to switch on the variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaManagedAgentsGitHubRepositoryResourceConfigCheckoutUnion struct { + // This field is from variant [BetaManagedAgentsBranchCheckout]. + Name string `json:"name"` + // Any of "branch", "commit". + Type string `json:"type"` + // This field is from variant [BetaManagedAgentsCommitCheckout]. + Sha string `json:"sha"` + JSON struct { + Name respjson.Field + Type respjson.Field + Sha respjson.Field + raw string + } `json:"-"` +} + +// anyBetaManagedAgentsGitHubRepositoryResourceConfigCheckout is implemented by +// each variant of [BetaManagedAgentsGitHubRepositoryResourceConfigCheckoutUnion] +// to add type safety for the return type of +// [BetaManagedAgentsGitHubRepositoryResourceConfigCheckoutUnion.AsAny] +type anyBetaManagedAgentsGitHubRepositoryResourceConfigCheckout interface { + implBetaManagedAgentsGitHubRepositoryResourceConfigCheckoutUnion() +} + +func (BetaManagedAgentsBranchCheckout) implBetaManagedAgentsGitHubRepositoryResourceConfigCheckoutUnion() { +} +func (BetaManagedAgentsCommitCheckout) implBetaManagedAgentsGitHubRepositoryResourceConfigCheckoutUnion() { +} + +// Use the following switch statement to find the correct variant +// +// switch variant := BetaManagedAgentsGitHubRepositoryResourceConfigCheckoutUnion.AsAny().(type) { +// case anthropic.BetaManagedAgentsBranchCheckout: +// case anthropic.BetaManagedAgentsCommitCheckout: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaManagedAgentsGitHubRepositoryResourceConfigCheckoutUnion) AsAny() anyBetaManagedAgentsGitHubRepositoryResourceConfigCheckout { + switch u.Type { + case "branch": + return u.AsBranch() + case "commit": + return u.AsCommit() + } + return nil +} + +func (u BetaManagedAgentsGitHubRepositoryResourceConfigCheckoutUnion) AsBranch() (v BetaManagedAgentsBranchCheckout) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsGitHubRepositoryResourceConfigCheckoutUnion) AsCommit() (v BetaManagedAgentsCommitCheckout) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u BetaManagedAgentsGitHubRepositoryResourceConfigCheckoutUnion) RawJSON() string { + return u.JSON.raw +} + +func (r *BetaManagedAgentsGitHubRepositoryResourceConfigCheckoutUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The caller invoked the pause endpoint on the deployment. +type BetaManagedAgentsManualDeploymentPausedReason struct { + // Any of "manual". + Type BetaManagedAgentsManualDeploymentPausedReasonType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsManualDeploymentPausedReason) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsManualDeploymentPausedReason) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsManualDeploymentPausedReasonType string + +const ( + BetaManagedAgentsManualDeploymentPausedReasonTypeManual BetaManagedAgentsManualDeploymentPausedReasonType = "manual" +) + +// An MCP server host used by the deployment's agent is blocked by the +// environment's network policy. +type BetaManagedAgentsMCPEgressBlockedDeploymentPausedReasonError struct { + // Any of "mcp_egress_blocked_error". + Type BetaManagedAgentsMCPEgressBlockedDeploymentPausedReasonErrorType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsMCPEgressBlockedDeploymentPausedReasonError) RawJSON() string { + return r.JSON.raw +} +func (r *BetaManagedAgentsMCPEgressBlockedDeploymentPausedReasonError) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsMCPEgressBlockedDeploymentPausedReasonErrorType string + +const ( + BetaManagedAgentsMCPEgressBlockedDeploymentPausedReasonErrorTypeMCPEgressBlockedError BetaManagedAgentsMCPEgressBlockedDeploymentPausedReasonErrorType = "mcp_egress_blocked_error" +) + +// A memory store referenced by the deployment is archived. +type BetaManagedAgentsMemoryStoreArchivedDeploymentPausedReasonError struct { + // Any of "memory_store_archived_error". + Type BetaManagedAgentsMemoryStoreArchivedDeploymentPausedReasonErrorType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsMemoryStoreArchivedDeploymentPausedReasonError) RawJSON() string { + return r.JSON.raw +} +func (r *BetaManagedAgentsMemoryStoreArchivedDeploymentPausedReasonError) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsMemoryStoreArchivedDeploymentPausedReasonErrorType string + +const ( + BetaManagedAgentsMemoryStoreArchivedDeploymentPausedReasonErrorTypeMemoryStoreArchivedError BetaManagedAgentsMemoryStoreArchivedDeploymentPausedReasonErrorType = "memory_store_archived_error" +) + +// A memory store attached to each session created from this deployment. +type BetaManagedAgentsMemoryStoreResourceConfig struct { + // The memory store ID (memstore\_...). Must belong to the caller's organization + // and workspace. + MemoryStoreID string `json:"memory_store_id" api:"required"` + // Any of "memory_store". + Type BetaManagedAgentsMemoryStoreResourceConfigType `json:"type" api:"required"` + // Access mode for an attached memory store. + // + // Any of "read_write", "read_only". + Access BetaManagedAgentsMemoryStoreResourceConfigAccess `json:"access" api:"nullable"` + // Per-attachment guidance for the agent on how to use this store. Rendered into + // the memory section of the system prompt. Max 4096 chars. + Instructions string `json:"instructions" api:"nullable"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + MemoryStoreID respjson.Field + Type respjson.Field + Access respjson.Field + Instructions respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsMemoryStoreResourceConfig) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsMemoryStoreResourceConfig) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsMemoryStoreResourceConfigType string + +const ( + BetaManagedAgentsMemoryStoreResourceConfigTypeMemoryStore BetaManagedAgentsMemoryStoreResourceConfigType = "memory_store" +) + +// Access mode for an attached memory store. +type BetaManagedAgentsMemoryStoreResourceConfigAccess string + +const ( + BetaManagedAgentsMemoryStoreResourceConfigAccessReadWrite BetaManagedAgentsMemoryStoreResourceConfigAccess = "read_write" + BetaManagedAgentsMemoryStoreResourceConfigAccessReadOnly BetaManagedAgentsMemoryStoreResourceConfigAccess = "read_only" +) + +// The deployment's organization is disabled. +type BetaManagedAgentsOrganizationDisabledDeploymentPausedReasonError struct { + // Any of "organization_disabled_error". + Type BetaManagedAgentsOrganizationDisabledDeploymentPausedReasonErrorType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsOrganizationDisabledDeploymentPausedReasonError) RawJSON() string { + return r.JSON.raw +} +func (r *BetaManagedAgentsOrganizationDisabledDeploymentPausedReasonError) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsOrganizationDisabledDeploymentPausedReasonErrorType string + +const ( + BetaManagedAgentsOrganizationDisabledDeploymentPausedReasonErrorTypeOrganizationDisabledError BetaManagedAgentsOrganizationDisabledDeploymentPausedReasonErrorType = "organization_disabled_error" +) + +// 5-field POSIX cron schedule with computed runtime timestamps. +type BetaManagedAgentsSchedule struct { + // 5-field POSIX cron expression: minute hour day-of-month month day-of-week (e.g., + // "0 9 \* \* 1-5" for weekdays at 9am). Day-of-week is 0-7 where 0 and 7 both mean + // Sunday. Extended cron syntax - seconds or year fields, and the special + // characters L, W, #, and ? - is not supported, nor are predefined shortcuts + // (@daily). + Expression string `json:"expression" api:"required"` + // IANA timezone identifier (e.g., "America/Los_Angeles", "UTC"). + Timezone string `json:"timezone" api:"required"` + // Any of "cron". + Type BetaManagedAgentsScheduleType `json:"type" api:"required"` + // A timestamp in RFC 3339 format + LastRunAt time.Time `json:"last_run_at" api:"nullable" format:"date-time"` + // Up to 5 timestamps of upcoming cron occurrences. Non-empty for active and paused + // deployments (reflects what the schedule would do if unpaused); empty once the + // deployment is archived (`archived_at` set). Each fire is offset by a small + // per-schedule jitter, so a run will actually start at or shortly after its listed + // time. + UpcomingRunsAt []time.Time `json:"upcoming_runs_at" format:"date-time"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Expression respjson.Field + Timezone respjson.Field + Type respjson.Field + LastRunAt respjson.Field + UpcomingRunsAt respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsSchedule) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsSchedule) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsScheduleType string + +const ( + BetaManagedAgentsScheduleTypeCron BetaManagedAgentsScheduleType = "cron" +) + +// 5-field POSIX cron schedule. Literal wall-clock matching in the configured +// timezone. +// +// The properties Expression, Timezone, Type are required. +type BetaManagedAgentsScheduleParams struct { + // 5-field POSIX cron expression: minute hour day-of-month month day-of-week (e.g., + // "0 9 \* \* 1-5" for weekdays at 9am). Day-of-week is 0-7 where 0 and 7 both mean + // Sunday. Extended cron syntax - seconds or year fields, and the special + // characters L, W, #, and ? - is not supported, nor are predefined shortcuts + // (@daily). + Expression string `json:"expression" api:"required"` + // Required. IANA timezone identifier (e.g., "America/Los_Angeles", "UTC"). + // Validated against the IANA timezone database. + Timezone string `json:"timezone" api:"required"` + // Any of "cron". + Type BetaManagedAgentsScheduleParamsType `json:"type,omitzero" api:"required"` + paramObj +} + +func (r BetaManagedAgentsScheduleParams) MarshalJSON() (data []byte, err error) { + type shadow BetaManagedAgentsScheduleParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaManagedAgentsScheduleParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsScheduleParamsType string + +const ( + BetaManagedAgentsScheduleParamsTypeCron BetaManagedAgentsScheduleParamsType = "cron" +) + +// The deployment configures resources, but its environment is self-hosted and +// cannot mount them. +type BetaManagedAgentsSelfHostedResourcesUnsupportedDeploymentPausedReasonError struct { + // Any of "self_hosted_resources_unsupported_error". + Type BetaManagedAgentsSelfHostedResourcesUnsupportedDeploymentPausedReasonErrorType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsSelfHostedResourcesUnsupportedDeploymentPausedReasonError) RawJSON() string { + return r.JSON.raw +} +func (r *BetaManagedAgentsSelfHostedResourcesUnsupportedDeploymentPausedReasonError) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsSelfHostedResourcesUnsupportedDeploymentPausedReasonErrorType string + +const ( + BetaManagedAgentsSelfHostedResourcesUnsupportedDeploymentPausedReasonErrorTypeSelfHostedResourcesUnsupportedError BetaManagedAgentsSelfHostedResourcesUnsupportedDeploymentPausedReasonErrorType = "self_hosted_resources_unsupported_error" +) + +// BetaManagedAgentsSessionResourceConfigUnion contains all possible properties and +// values from [BetaManagedAgentsGitHubRepositoryResourceConfig], +// [BetaManagedAgentsFileResourceConfig], +// [BetaManagedAgentsMemoryStoreResourceConfig]. +// +// Use the [BetaManagedAgentsSessionResourceConfigUnion.AsAny] method to switch on +// the variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaManagedAgentsSessionResourceConfigUnion struct { + // Any of "github_repository", "file", "memory_store". + Type string `json:"type"` + // This field is from variant [BetaManagedAgentsGitHubRepositoryResourceConfig]. + URL string `json:"url"` + // This field is from variant [BetaManagedAgentsGitHubRepositoryResourceConfig]. + Checkout BetaManagedAgentsGitHubRepositoryResourceConfigCheckoutUnion `json:"checkout"` + MountPath string `json:"mount_path"` + // This field is from variant [BetaManagedAgentsFileResourceConfig]. + FileID string `json:"file_id"` + // This field is from variant [BetaManagedAgentsMemoryStoreResourceConfig]. + MemoryStoreID string `json:"memory_store_id"` + // This field is from variant [BetaManagedAgentsMemoryStoreResourceConfig]. + Access BetaManagedAgentsMemoryStoreResourceConfigAccess `json:"access"` + // This field is from variant [BetaManagedAgentsMemoryStoreResourceConfig]. + Instructions string `json:"instructions"` + JSON struct { + Type respjson.Field + URL respjson.Field + Checkout respjson.Field + MountPath respjson.Field + FileID respjson.Field + MemoryStoreID respjson.Field + Access respjson.Field + Instructions respjson.Field + raw string + } `json:"-"` +} + +// anyBetaManagedAgentsSessionResourceConfig is implemented by each variant of +// [BetaManagedAgentsSessionResourceConfigUnion] to add type safety for the return +// type of [BetaManagedAgentsSessionResourceConfigUnion.AsAny] +type anyBetaManagedAgentsSessionResourceConfig interface { + implBetaManagedAgentsSessionResourceConfigUnion() +} + +func (BetaManagedAgentsGitHubRepositoryResourceConfig) implBetaManagedAgentsSessionResourceConfigUnion() { +} +func (BetaManagedAgentsFileResourceConfig) implBetaManagedAgentsSessionResourceConfigUnion() {} +func (BetaManagedAgentsMemoryStoreResourceConfig) implBetaManagedAgentsSessionResourceConfigUnion() {} + +// Use the following switch statement to find the correct variant +// +// switch variant := BetaManagedAgentsSessionResourceConfigUnion.AsAny().(type) { +// case anthropic.BetaManagedAgentsGitHubRepositoryResourceConfig: +// case anthropic.BetaManagedAgentsFileResourceConfig: +// case anthropic.BetaManagedAgentsMemoryStoreResourceConfig: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaManagedAgentsSessionResourceConfigUnion) AsAny() anyBetaManagedAgentsSessionResourceConfig { + switch u.Type { + case "github_repository": + return u.AsGitHubRepository() + case "file": + return u.AsFile() + case "memory_store": + return u.AsMemoryStore() + } + return nil +} + +func (u BetaManagedAgentsSessionResourceConfigUnion) AsGitHubRepository() (v BetaManagedAgentsGitHubRepositoryResourceConfig) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsSessionResourceConfigUnion) AsFile() (v BetaManagedAgentsFileResourceConfig) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsSessionResourceConfigUnion) AsMemoryStore() (v BetaManagedAgentsMemoryStoreResourceConfig) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u BetaManagedAgentsSessionResourceConfigUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaManagedAgentsSessionResourceConfigUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// A referenced resource no longer exists and its kind was not reported. +type BetaManagedAgentsSessionResourceNotFoundDeploymentPausedReasonError struct { + // Any of "session_resource_not_found_error". + Type BetaManagedAgentsSessionResourceNotFoundDeploymentPausedReasonErrorType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsSessionResourceNotFoundDeploymentPausedReasonError) RawJSON() string { + return r.JSON.raw +} +func (r *BetaManagedAgentsSessionResourceNotFoundDeploymentPausedReasonError) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsSessionResourceNotFoundDeploymentPausedReasonErrorType string + +const ( + BetaManagedAgentsSessionResourceNotFoundDeploymentPausedReasonErrorTypeSessionResourceNotFoundError BetaManagedAgentsSessionResourceNotFoundDeploymentPausedReasonErrorType = "session_resource_not_found_error" +) + +// A skill referenced by the deployment's agent no longer exists. +type BetaManagedAgentsSkillNotFoundDeploymentPausedReasonError struct { + // Any of "skill_not_found_error". + Type BetaManagedAgentsSkillNotFoundDeploymentPausedReasonErrorType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsSkillNotFoundDeploymentPausedReasonError) RawJSON() string { + return r.JSON.raw +} +func (r *BetaManagedAgentsSkillNotFoundDeploymentPausedReasonError) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsSkillNotFoundDeploymentPausedReasonErrorType string + +const ( + BetaManagedAgentsSkillNotFoundDeploymentPausedReasonErrorTypeSkillNotFoundError BetaManagedAgentsSkillNotFoundDeploymentPausedReasonErrorType = "skill_not_found_error" +) + +// An unrecognized error auto-paused the deployment. A fallback variant; matches a +// run whose `error.type` is `unknown_error`. +type BetaManagedAgentsUnknownDeploymentPausedReasonError struct { + // Any of "unknown_error". + Type BetaManagedAgentsUnknownDeploymentPausedReasonErrorType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsUnknownDeploymentPausedReasonError) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsUnknownDeploymentPausedReasonError) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsUnknownDeploymentPausedReasonErrorType string + +const ( + BetaManagedAgentsUnknownDeploymentPausedReasonErrorTypeUnknownError BetaManagedAgentsUnknownDeploymentPausedReasonErrorType = "unknown_error" +) + +// A vault referenced by the deployment is archived. +type BetaManagedAgentsVaultArchivedDeploymentPausedReasonError struct { + // Any of "vault_archived_error". + Type BetaManagedAgentsVaultArchivedDeploymentPausedReasonErrorType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsVaultArchivedDeploymentPausedReasonError) RawJSON() string { + return r.JSON.raw +} +func (r *BetaManagedAgentsVaultArchivedDeploymentPausedReasonError) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsVaultArchivedDeploymentPausedReasonErrorType string + +const ( + BetaManagedAgentsVaultArchivedDeploymentPausedReasonErrorTypeVaultArchivedError BetaManagedAgentsVaultArchivedDeploymentPausedReasonErrorType = "vault_archived_error" +) + +// A vault referenced by the deployment no longer exists. +type BetaManagedAgentsVaultNotFoundDeploymentPausedReasonError struct { + // Any of "vault_not_found_error". + Type BetaManagedAgentsVaultNotFoundDeploymentPausedReasonErrorType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsVaultNotFoundDeploymentPausedReasonError) RawJSON() string { + return r.JSON.raw +} +func (r *BetaManagedAgentsVaultNotFoundDeploymentPausedReasonError) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsVaultNotFoundDeploymentPausedReasonErrorType string + +const ( + BetaManagedAgentsVaultNotFoundDeploymentPausedReasonErrorTypeVaultNotFoundError BetaManagedAgentsVaultNotFoundDeploymentPausedReasonErrorType = "vault_not_found_error" +) + +// The deployment's workspace was archived. +type BetaManagedAgentsWorkspaceArchivedDeploymentPausedReasonError struct { + // Any of "workspace_archived_error". + Type BetaManagedAgentsWorkspaceArchivedDeploymentPausedReasonErrorType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsWorkspaceArchivedDeploymentPausedReasonError) RawJSON() string { + return r.JSON.raw +} +func (r *BetaManagedAgentsWorkspaceArchivedDeploymentPausedReasonError) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsWorkspaceArchivedDeploymentPausedReasonErrorType string + +const ( + BetaManagedAgentsWorkspaceArchivedDeploymentPausedReasonErrorTypeWorkspaceArchivedError BetaManagedAgentsWorkspaceArchivedDeploymentPausedReasonErrorType = "workspace_archived_error" +) + +type BetaDeploymentNewParams struct { + // Agent to deploy. Accepts the `agent` ID string, which pins the latest version, + // or an `agent` object with both id and version specified. The agent must exist + // and not be archived. + Agent BetaDeploymentNewParamsAgentUnion `json:"agent,omitzero" api:"required"` + // ID of the `environment` defining the container configuration for sessions + // created from this deployment. + EnvironmentID string `json:"environment_id" api:"required"` + // Events to send to each session immediately after creation. At least 1, + // maximum 50. + InitialEvents []BetaManagedAgentsDeploymentInitialEventParamsUnion `json:"initial_events,omitzero" api:"required"` + // Human-readable name for the deployment. + Name string `json:"name" api:"required"` + // Description of what the deployment does. + Description param.Opt[string] `json:"description,omitzero"` + // A hard spend ceiling. The session stops issuing new model requests once the + // tracked list cost reaches `max_list_cost`. + Budget BetaManagedAgentsBudgetLimitParam `json:"budget,omitzero"` + // Arbitrary key-value metadata. Maximum 16 pairs, keys up to 64 chars, values up + // to 512 chars. + Metadata map[string]string `json:"metadata,omitzero"` + // Resources (e.g. repositories, files) to mount into each session's container. + // Maximum 500. + Resources []BetaDeploymentNewParamsResourceUnion `json:"resources,omitzero"` + // 5-field POSIX cron schedule. Literal wall-clock matching in the configured + // timezone. + Schedule BetaManagedAgentsScheduleParams `json:"schedule,omitzero"` + // Vault IDs for stored credentials the agent can use during sessions created from + // this deployment. Maximum 50. + VaultIDs []string `json:"vault_ids,omitzero"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +func (r BetaDeploymentNewParams) MarshalJSON() (data []byte, err error) { + type shadow BetaDeploymentNewParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaDeploymentNewParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaDeploymentNewParamsAgentUnion struct { + OfString param.Opt[string] `json:",omitzero,inline"` + OfBetaManagedAgentsAgents *BetaManagedAgentsAgentParams `json:",omitzero,inline"` + paramUnion +} + +func (u BetaDeploymentNewParamsAgentUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfString, u.OfBetaManagedAgentsAgents) +} +func (u *BetaDeploymentNewParamsAgentUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *BetaDeploymentNewParamsAgentUnion) asAny() any { + if !param.IsOmitted(u.OfString) { + return &u.OfString.Value + } else if !param.IsOmitted(u.OfBetaManagedAgentsAgents) { + return u.OfBetaManagedAgentsAgents + } + return nil +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaDeploymentNewParamsResourceUnion struct { + OfGitHubRepository *BetaManagedAgentsGitHubRepositoryResourceParams `json:",omitzero,inline"` + OfFile *BetaManagedAgentsFileResourceParams `json:",omitzero,inline"` + OfMemoryStore *BetaManagedAgentsMemoryStoreResourceParam `json:",omitzero,inline"` + paramUnion +} + +func (u BetaDeploymentNewParamsResourceUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfGitHubRepository, u.OfFile, u.OfMemoryStore) +} +func (u *BetaDeploymentNewParamsResourceUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *BetaDeploymentNewParamsResourceUnion) asAny() any { + if !param.IsOmitted(u.OfGitHubRepository) { + return u.OfGitHubRepository + } else if !param.IsOmitted(u.OfFile) { + return u.OfFile + } else if !param.IsOmitted(u.OfMemoryStore) { + return u.OfMemoryStore + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaDeploymentNewParamsResourceUnion) GetAuthorizationToken() *string { + if vt := u.OfGitHubRepository; vt != nil { + return &vt.AuthorizationToken + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaDeploymentNewParamsResourceUnion) GetURL() *string { + if vt := u.OfGitHubRepository; vt != nil { + return &vt.URL + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaDeploymentNewParamsResourceUnion) GetCheckout() *BetaManagedAgentsGitHubRepositoryResourceParamsCheckoutUnion { + if vt := u.OfGitHubRepository; vt != nil { + return &vt.Checkout + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaDeploymentNewParamsResourceUnion) GetFileID() *string { + if vt := u.OfFile; vt != nil { + return &vt.FileID + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaDeploymentNewParamsResourceUnion) GetMemoryStoreID() *string { + if vt := u.OfMemoryStore; vt != nil { + return &vt.MemoryStoreID + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaDeploymentNewParamsResourceUnion) GetAccess() *string { + if vt := u.OfMemoryStore; vt != nil { + return (*string)(&vt.Access) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaDeploymentNewParamsResourceUnion) GetInstructions() *string { + if vt := u.OfMemoryStore; vt != nil && vt.Instructions.Valid() { + return &vt.Instructions.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaDeploymentNewParamsResourceUnion) GetType() *string { + if vt := u.OfGitHubRepository; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfFile; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfMemoryStore; vt != nil { + return (*string)(&vt.Type) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaDeploymentNewParamsResourceUnion) GetMountPath() *string { + if vt := u.OfGitHubRepository; vt != nil && vt.MountPath.Valid() { + return &vt.MountPath.Value + } else if vt := u.OfFile; vt != nil && vt.MountPath.Valid() { + return &vt.MountPath.Value + } + return nil +} + +func init() { + apijson.RegisterUnion[BetaDeploymentNewParamsResourceUnion]( + "type", + apijson.Discriminator[BetaManagedAgentsGitHubRepositoryResourceParams]("github_repository"), + apijson.Discriminator[BetaManagedAgentsFileResourceParams]("file"), + apijson.Discriminator[BetaManagedAgentsMemoryStoreResourceParam]("memory_store"), + ) +} + +type BetaDeploymentGetParams struct { + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +type BetaDeploymentUpdateParams struct { + // Description. Omit to preserve; send empty string or null to clear. + Description param.Opt[string] `json:"description,omitzero"` + // ID of the `environment` where sessions run. Omit to preserve. Cannot be cleared. + EnvironmentID param.Opt[string] `json:"environment_id,omitzero"` + // Human-readable name. Must be non-empty. Omit to preserve. Cannot be cleared. + Name param.Opt[string] `json:"name,omitzero"` + // Metadata patch. Set a key to a string to upsert it, or to null to delete it. + // Omit the field to preserve. The stored bag is limited to 16 keys (up to 64 chars + // each) with values up to 512 chars. + Metadata map[string]string `json:"metadata,omitzero"` + // Session resources. Full replacement. Omit to preserve; send empty array or null + // to clear. Maximum 500. + Resources []BetaDeploymentUpdateParamsResourceUnion `json:"resources,omitzero"` + // Vault IDs. Full replacement. Omit to preserve; send empty array or null to + // clear. Maximum 50. + VaultIDs []string `json:"vault_ids,omitzero"` + // Agent to deploy. Accepts the `agent` ID string, which re-pins to the latest + // version, or an `agent` object with both id and version specified. Omit to + // preserve. Cannot be cleared. + Agent BetaDeploymentUpdateParamsAgentUnion `json:"agent,omitzero"` + // A hard spend ceiling. The session stops issuing new model requests once the + // tracked list cost reaches `max_list_cost`. + Budget BetaManagedAgentsBudgetLimitParam `json:"budget,omitzero"` + // Initial events. Full replacement. Omit to preserve. Cannot be cleared. At least + // 1, maximum 50. + InitialEvents []BetaManagedAgentsDeploymentInitialEventParamsUnion `json:"initial_events,omitzero"` + // 5-field POSIX cron schedule. Literal wall-clock matching in the configured + // timezone. + Schedule BetaManagedAgentsScheduleParams `json:"schedule,omitzero"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +func (r BetaDeploymentUpdateParams) MarshalJSON() (data []byte, err error) { + type shadow BetaDeploymentUpdateParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaDeploymentUpdateParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaDeploymentUpdateParamsAgentUnion struct { + OfString param.Opt[string] `json:",omitzero,inline"` + OfBetaManagedAgentsAgents *BetaManagedAgentsAgentParams `json:",omitzero,inline"` + paramUnion +} + +func (u BetaDeploymentUpdateParamsAgentUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfString, u.OfBetaManagedAgentsAgents) +} +func (u *BetaDeploymentUpdateParamsAgentUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *BetaDeploymentUpdateParamsAgentUnion) asAny() any { + if !param.IsOmitted(u.OfString) { + return &u.OfString.Value + } else if !param.IsOmitted(u.OfBetaManagedAgentsAgents) { + return u.OfBetaManagedAgentsAgents + } + return nil +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaDeploymentUpdateParamsResourceUnion struct { + OfGitHubRepository *BetaManagedAgentsGitHubRepositoryResourceParams `json:",omitzero,inline"` + OfFile *BetaManagedAgentsFileResourceParams `json:",omitzero,inline"` + OfMemoryStore *BetaManagedAgentsMemoryStoreResourceParam `json:",omitzero,inline"` + paramUnion +} + +func (u BetaDeploymentUpdateParamsResourceUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfGitHubRepository, u.OfFile, u.OfMemoryStore) +} +func (u *BetaDeploymentUpdateParamsResourceUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *BetaDeploymentUpdateParamsResourceUnion) asAny() any { + if !param.IsOmitted(u.OfGitHubRepository) { + return u.OfGitHubRepository + } else if !param.IsOmitted(u.OfFile) { + return u.OfFile + } else if !param.IsOmitted(u.OfMemoryStore) { + return u.OfMemoryStore + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaDeploymentUpdateParamsResourceUnion) GetAuthorizationToken() *string { + if vt := u.OfGitHubRepository; vt != nil { + return &vt.AuthorizationToken + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaDeploymentUpdateParamsResourceUnion) GetURL() *string { + if vt := u.OfGitHubRepository; vt != nil { + return &vt.URL + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaDeploymentUpdateParamsResourceUnion) GetCheckout() *BetaManagedAgentsGitHubRepositoryResourceParamsCheckoutUnion { + if vt := u.OfGitHubRepository; vt != nil { + return &vt.Checkout + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaDeploymentUpdateParamsResourceUnion) GetFileID() *string { + if vt := u.OfFile; vt != nil { + return &vt.FileID + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaDeploymentUpdateParamsResourceUnion) GetMemoryStoreID() *string { + if vt := u.OfMemoryStore; vt != nil { + return &vt.MemoryStoreID + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaDeploymentUpdateParamsResourceUnion) GetAccess() *string { + if vt := u.OfMemoryStore; vt != nil { + return (*string)(&vt.Access) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaDeploymentUpdateParamsResourceUnion) GetInstructions() *string { + if vt := u.OfMemoryStore; vt != nil && vt.Instructions.Valid() { + return &vt.Instructions.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaDeploymentUpdateParamsResourceUnion) GetType() *string { + if vt := u.OfGitHubRepository; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfFile; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfMemoryStore; vt != nil { + return (*string)(&vt.Type) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaDeploymentUpdateParamsResourceUnion) GetMountPath() *string { + if vt := u.OfGitHubRepository; vt != nil && vt.MountPath.Valid() { + return &vt.MountPath.Value + } else if vt := u.OfFile; vt != nil && vt.MountPath.Valid() { + return &vt.MountPath.Value + } + return nil +} + +func init() { + apijson.RegisterUnion[BetaDeploymentUpdateParamsResourceUnion]( + "type", + apijson.Discriminator[BetaManagedAgentsGitHubRepositoryResourceParams]("github_repository"), + apijson.Discriminator[BetaManagedAgentsFileResourceParams]("file"), + apijson.Discriminator[BetaManagedAgentsMemoryStoreResourceParam]("memory_store"), + ) +} + +type BetaDeploymentListParams struct { + // Filter by agent ID. + AgentID param.Opt[string] `query:"agent_id,omitzero" json:"-"` + // Return deployments created at or after this time (inclusive). + CreatedAtGte param.Opt[time.Time] `query:"created_at[gte],omitzero" format:"date-time" json:"-"` + // Return deployments created at or before this time (inclusive). + CreatedAtLte param.Opt[time.Time] `query:"created_at[lte],omitzero" format:"date-time" json:"-"` + // When true, includes archived deployments. Default: false (exclude archived). + IncludeArchived param.Opt[bool] `query:"include_archived,omitzero" json:"-"` + // Maximum results per page. Default 20, maximum 100. + Limit param.Opt[int64] `query:"limit,omitzero" json:"-"` + // Opaque pagination cursor. + Page param.Opt[string] `query:"page,omitzero" json:"-"` + // Filter by status: active or paused. Omit for both. To include archived + // deployments, use include_archived instead; the two cannot be combined. + // + // Any of "active", "paused". + Status BetaManagedAgentsDeploymentStatus `query:"status,omitzero" json:"-"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +// URLQuery serializes [BetaDeploymentListParams]'s query parameters as +// `url.Values`. +func (r BetaDeploymentListParams) URLQuery() (v url.Values, err error) { + return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ + ArrayFormat: apiquery.ArrayQueryFormatBrackets, + NestedFormat: apiquery.NestedQueryFormatBrackets, + }) +} + +type BetaDeploymentArchiveParams struct { + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +type BetaDeploymentPauseParams struct { + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +type BetaDeploymentRunParams struct { + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +type BetaDeploymentUnpauseParams struct { + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/betadeploymentrun.go b/vendor/github.com/anthropics/anthropic-sdk-go/betadeploymentrun.go new file mode 100644 index 000000000..31fd3b13e --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/betadeploymentrun.go @@ -0,0 +1,950 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +package anthropic + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/url" + "slices" + "time" + + "github.com/anthropics/anthropic-sdk-go/internal/apijson" + "github.com/anthropics/anthropic-sdk-go/internal/apiquery" + "github.com/anthropics/anthropic-sdk-go/internal/requestconfig" + "github.com/anthropics/anthropic-sdk-go/option" + "github.com/anthropics/anthropic-sdk-go/packages/pagination" + "github.com/anthropics/anthropic-sdk-go/packages/param" + "github.com/anthropics/anthropic-sdk-go/packages/respjson" +) + +// BetaDeploymentRunService contains methods and other services that help with +// interacting with the anthropic API. +// +// Note, unlike clients, this service does not read variables from the environment +// automatically. You should not instantiate this service directly, and instead use +// the [NewBetaDeploymentRunService] method instead. +type BetaDeploymentRunService struct { + Options []option.RequestOption +} + +// NewBetaDeploymentRunService generates a new service that applies the given +// options to each request. These options are applied after the parent client's +// options (if there is one), and before any request-specific options. +func NewBetaDeploymentRunService(opts ...option.RequestOption) (r BetaDeploymentRunService) { + r = BetaDeploymentRunService{} + r.Options = opts + return +} + +// Get Deployment Run +func (r *BetaDeploymentRunService) Get(ctx context.Context, deploymentRunID string, query BetaDeploymentRunGetParams, opts ...option.RequestOption) (res *BetaManagedAgentsDeploymentRun, err error) { + for _, v := range query.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "managed-agents-2026-04-01")}, opts...) + if deploymentRunID == "" { + err = errors.New("missing required deployment_run_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/deployment_runs/%s?beta=true", deploymentRunID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...) + return res, err +} + +// List Deployment Runs +func (r *BetaDeploymentRunService) List(ctx context.Context, params BetaDeploymentRunListParams, opts ...option.RequestOption) (res *pagination.PageCursor[BetaManagedAgentsDeploymentRun], err error) { + var raw *http.Response + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "managed-agents-2026-04-01"), option.WithResponseInto(&raw)}, opts...) + path := "v1/deployment_runs?beta=true" + cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, params, &res, opts...) + if err != nil { + return nil, err + } + err = cfg.Execute() + if err != nil { + return nil, err + } + res.SetPageConfig(cfg, raw) + return res, nil +} + +// List Deployment Runs +func (r *BetaDeploymentRunService) ListAutoPaging(ctx context.Context, params BetaDeploymentRunListParams, opts ...option.RequestOption) *pagination.PageCursorAutoPager[BetaManagedAgentsDeploymentRun] { + return pagination.NewPageCursorAutoPager(r.List(ctx, params, opts...)) +} + +// The deployment's agent was archived. +type BetaManagedAgentsAgentArchivedRunError struct { + // Human-readable error description. + Message string `json:"message" api:"required"` + // Any of "agent_archived_error". + Type BetaManagedAgentsAgentArchivedRunErrorType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Message respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsAgentArchivedRunError) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsAgentArchivedRunError) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsAgentArchivedRunErrorType string + +const ( + BetaManagedAgentsAgentArchivedRunErrorTypeAgentArchivedError BetaManagedAgentsAgentArchivedRunErrorType = "agent_archived_error" +) + +// A persistent, append-only record of a single deployment execution. Records +// session creation success or failure — no session lifecycle tracking. +type BetaManagedAgentsDeploymentRun struct { + // Unique identifier for this run (`drun_...`). + ID string `json:"id" api:"required"` + // A resolved agent reference with a concrete version. + Agent BetaManagedAgentsAgentReference `json:"agent" api:"required"` + // A timestamp in RFC 3339 format + CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"` + // ID of the deployment that produced this run. + DeploymentID string `json:"deployment_id" api:"required"` + // Why the run failed to create a session. The type identifies the failure; message + // is human-readable detail. + Error BetaManagedAgentsDeploymentRunErrorUnion `json:"error" api:"required"` + // Populated on success. Null on creation failure. Exactly one of session_id or + // error is non-null. + SessionID string `json:"session_id" api:"required"` + // Describes what triggered a deployment run, with trigger-specific metadata. + TriggerContext BetaManagedAgentsTriggerContextUnion `json:"trigger_context" api:"required"` + // Any of "deployment_run". + Type BetaManagedAgentsDeploymentRunType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + Agent respjson.Field + CreatedAt respjson.Field + DeploymentID respjson.Field + Error respjson.Field + SessionID respjson.Field + TriggerContext respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsDeploymentRun) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsDeploymentRun) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaManagedAgentsDeploymentRunErrorUnion contains all possible properties and +// values from [BetaManagedAgentsEnvironmentArchivedRunError], +// [BetaManagedAgentsAgentArchivedRunError], +// [BetaManagedAgentsEnvironmentNotFoundRunError], +// [BetaManagedAgentsVaultNotFoundRunError], +// [BetaManagedAgentsVaultArchivedRunError], +// [BetaManagedAgentsFileNotFoundRunError], +// [BetaManagedAgentsMemoryStoreArchivedRunError], +// [BetaManagedAgentsSkillNotFoundRunError], +// [BetaManagedAgentsSessionResourceNotFoundRunError], +// [BetaManagedAgentsWorkspaceArchivedRunError], +// [BetaManagedAgentsOrganizationDisabledRunError], +// [BetaManagedAgentsSessionRateLimitedRunError], +// [BetaManagedAgentsSessionCreationRejectedRunError], +// [BetaManagedAgentsUnknownRunError], +// [BetaManagedAgentsSelfHostedResourcesUnsupportedRunError], +// [BetaManagedAgentsMCPEgressBlockedRunError]. +// +// Use the [BetaManagedAgentsDeploymentRunErrorUnion.AsAny] method to switch on the +// variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaManagedAgentsDeploymentRunErrorUnion struct { + Message string `json:"message"` + // Any of "environment_archived_error", "agent_archived_error", + // "environment_not_found_error", "vault_not_found_error", "vault_archived_error", + // "file_not_found_error", "memory_store_archived_error", "skill_not_found_error", + // "session_resource_not_found_error", "workspace_archived_error", + // "organization_disabled_error", "session_rate_limited_error", + // "session_creation_rejected_error", "unknown_error", + // "self_hosted_resources_unsupported_error", "mcp_egress_blocked_error". + Type string `json:"type"` + JSON struct { + Message respjson.Field + Type respjson.Field + raw string + } `json:"-"` +} + +// anyBetaManagedAgentsDeploymentRunError is implemented by each variant of +// [BetaManagedAgentsDeploymentRunErrorUnion] to add type safety for the return +// type of [BetaManagedAgentsDeploymentRunErrorUnion.AsAny] +type anyBetaManagedAgentsDeploymentRunError interface { + implBetaManagedAgentsDeploymentRunErrorUnion() +} + +func (BetaManagedAgentsEnvironmentArchivedRunError) implBetaManagedAgentsDeploymentRunErrorUnion() {} +func (BetaManagedAgentsAgentArchivedRunError) implBetaManagedAgentsDeploymentRunErrorUnion() {} +func (BetaManagedAgentsEnvironmentNotFoundRunError) implBetaManagedAgentsDeploymentRunErrorUnion() {} +func (BetaManagedAgentsVaultNotFoundRunError) implBetaManagedAgentsDeploymentRunErrorUnion() {} +func (BetaManagedAgentsVaultArchivedRunError) implBetaManagedAgentsDeploymentRunErrorUnion() {} +func (BetaManagedAgentsFileNotFoundRunError) implBetaManagedAgentsDeploymentRunErrorUnion() {} +func (BetaManagedAgentsMemoryStoreArchivedRunError) implBetaManagedAgentsDeploymentRunErrorUnion() {} +func (BetaManagedAgentsSkillNotFoundRunError) implBetaManagedAgentsDeploymentRunErrorUnion() {} +func (BetaManagedAgentsSessionResourceNotFoundRunError) implBetaManagedAgentsDeploymentRunErrorUnion() { +} +func (BetaManagedAgentsWorkspaceArchivedRunError) implBetaManagedAgentsDeploymentRunErrorUnion() {} +func (BetaManagedAgentsOrganizationDisabledRunError) implBetaManagedAgentsDeploymentRunErrorUnion() {} +func (BetaManagedAgentsSessionRateLimitedRunError) implBetaManagedAgentsDeploymentRunErrorUnion() {} +func (BetaManagedAgentsSessionCreationRejectedRunError) implBetaManagedAgentsDeploymentRunErrorUnion() { +} +func (BetaManagedAgentsUnknownRunError) implBetaManagedAgentsDeploymentRunErrorUnion() {} +func (BetaManagedAgentsSelfHostedResourcesUnsupportedRunError) implBetaManagedAgentsDeploymentRunErrorUnion() { +} +func (BetaManagedAgentsMCPEgressBlockedRunError) implBetaManagedAgentsDeploymentRunErrorUnion() {} + +// Use the following switch statement to find the correct variant +// +// switch variant := BetaManagedAgentsDeploymentRunErrorUnion.AsAny().(type) { +// case anthropic.BetaManagedAgentsEnvironmentArchivedRunError: +// case anthropic.BetaManagedAgentsAgentArchivedRunError: +// case anthropic.BetaManagedAgentsEnvironmentNotFoundRunError: +// case anthropic.BetaManagedAgentsVaultNotFoundRunError: +// case anthropic.BetaManagedAgentsVaultArchivedRunError: +// case anthropic.BetaManagedAgentsFileNotFoundRunError: +// case anthropic.BetaManagedAgentsMemoryStoreArchivedRunError: +// case anthropic.BetaManagedAgentsSkillNotFoundRunError: +// case anthropic.BetaManagedAgentsSessionResourceNotFoundRunError: +// case anthropic.BetaManagedAgentsWorkspaceArchivedRunError: +// case anthropic.BetaManagedAgentsOrganizationDisabledRunError: +// case anthropic.BetaManagedAgentsSessionRateLimitedRunError: +// case anthropic.BetaManagedAgentsSessionCreationRejectedRunError: +// case anthropic.BetaManagedAgentsUnknownRunError: +// case anthropic.BetaManagedAgentsSelfHostedResourcesUnsupportedRunError: +// case anthropic.BetaManagedAgentsMCPEgressBlockedRunError: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaManagedAgentsDeploymentRunErrorUnion) AsAny() anyBetaManagedAgentsDeploymentRunError { + switch u.Type { + case "environment_archived_error": + return u.AsEnvironmentArchivedError() + case "agent_archived_error": + return u.AsAgentArchivedError() + case "environment_not_found_error": + return u.AsEnvironmentNotFoundError() + case "vault_not_found_error": + return u.AsVaultNotFoundError() + case "vault_archived_error": + return u.AsVaultArchivedError() + case "file_not_found_error": + return u.AsFileNotFoundError() + case "memory_store_archived_error": + return u.AsMemoryStoreArchivedError() + case "skill_not_found_error": + return u.AsSkillNotFoundError() + case "session_resource_not_found_error": + return u.AsSessionResourceNotFoundError() + case "workspace_archived_error": + return u.AsWorkspaceArchivedError() + case "organization_disabled_error": + return u.AsOrganizationDisabledError() + case "session_rate_limited_error": + return u.AsSessionRateLimitedError() + case "session_creation_rejected_error": + return u.AsSessionCreationRejectedError() + case "unknown_error": + return u.AsUnknownError() + case "self_hosted_resources_unsupported_error": + return u.AsSelfHostedResourcesUnsupportedError() + case "mcp_egress_blocked_error": + return u.AsMCPEgressBlockedError() + } + return nil +} + +func (u BetaManagedAgentsDeploymentRunErrorUnion) AsEnvironmentArchivedError() (v BetaManagedAgentsEnvironmentArchivedRunError) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsDeploymentRunErrorUnion) AsAgentArchivedError() (v BetaManagedAgentsAgentArchivedRunError) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsDeploymentRunErrorUnion) AsEnvironmentNotFoundError() (v BetaManagedAgentsEnvironmentNotFoundRunError) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsDeploymentRunErrorUnion) AsVaultNotFoundError() (v BetaManagedAgentsVaultNotFoundRunError) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsDeploymentRunErrorUnion) AsVaultArchivedError() (v BetaManagedAgentsVaultArchivedRunError) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsDeploymentRunErrorUnion) AsFileNotFoundError() (v BetaManagedAgentsFileNotFoundRunError) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsDeploymentRunErrorUnion) AsMemoryStoreArchivedError() (v BetaManagedAgentsMemoryStoreArchivedRunError) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsDeploymentRunErrorUnion) AsSkillNotFoundError() (v BetaManagedAgentsSkillNotFoundRunError) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsDeploymentRunErrorUnion) AsSessionResourceNotFoundError() (v BetaManagedAgentsSessionResourceNotFoundRunError) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsDeploymentRunErrorUnion) AsWorkspaceArchivedError() (v BetaManagedAgentsWorkspaceArchivedRunError) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsDeploymentRunErrorUnion) AsOrganizationDisabledError() (v BetaManagedAgentsOrganizationDisabledRunError) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsDeploymentRunErrorUnion) AsSessionRateLimitedError() (v BetaManagedAgentsSessionRateLimitedRunError) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsDeploymentRunErrorUnion) AsSessionCreationRejectedError() (v BetaManagedAgentsSessionCreationRejectedRunError) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsDeploymentRunErrorUnion) AsUnknownError() (v BetaManagedAgentsUnknownRunError) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsDeploymentRunErrorUnion) AsSelfHostedResourcesUnsupportedError() (v BetaManagedAgentsSelfHostedResourcesUnsupportedRunError) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsDeploymentRunErrorUnion) AsMCPEgressBlockedError() (v BetaManagedAgentsMCPEgressBlockedRunError) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u BetaManagedAgentsDeploymentRunErrorUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaManagedAgentsDeploymentRunErrorUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsDeploymentRunType string + +const ( + BetaManagedAgentsDeploymentRunTypeDeploymentRun BetaManagedAgentsDeploymentRunType = "deployment_run" +) + +// The deployment's environment was archived. +type BetaManagedAgentsEnvironmentArchivedRunError struct { + // Human-readable error description. + Message string `json:"message" api:"required"` + // Any of "environment_archived_error". + Type BetaManagedAgentsEnvironmentArchivedRunErrorType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Message respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsEnvironmentArchivedRunError) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsEnvironmentArchivedRunError) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsEnvironmentArchivedRunErrorType string + +const ( + BetaManagedAgentsEnvironmentArchivedRunErrorTypeEnvironmentArchivedError BetaManagedAgentsEnvironmentArchivedRunErrorType = "environment_archived_error" +) + +// The deployment's environment no longer exists. +type BetaManagedAgentsEnvironmentNotFoundRunError struct { + // Human-readable error description. + Message string `json:"message" api:"required"` + // Any of "environment_not_found_error". + Type BetaManagedAgentsEnvironmentNotFoundRunErrorType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Message respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsEnvironmentNotFoundRunError) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsEnvironmentNotFoundRunError) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsEnvironmentNotFoundRunErrorType string + +const ( + BetaManagedAgentsEnvironmentNotFoundRunErrorTypeEnvironmentNotFoundError BetaManagedAgentsEnvironmentNotFoundRunErrorType = "environment_not_found_error" +) + +// A file resource referenced by the deployment no longer exists. +type BetaManagedAgentsFileNotFoundRunError struct { + // Human-readable error description. + Message string `json:"message" api:"required"` + // Any of "file_not_found_error". + Type BetaManagedAgentsFileNotFoundRunErrorType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Message respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsFileNotFoundRunError) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsFileNotFoundRunError) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsFileNotFoundRunErrorType string + +const ( + BetaManagedAgentsFileNotFoundRunErrorTypeFileNotFoundError BetaManagedAgentsFileNotFoundRunErrorType = "file_not_found_error" +) + +// The run was started manually by creating a session directly against the +// deployment. +type BetaManagedAgentsManualTriggerContext struct { + // Any of "manual". + Type BetaManagedAgentsManualTriggerContextType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsManualTriggerContext) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsManualTriggerContext) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsManualTriggerContextType string + +const ( + BetaManagedAgentsManualTriggerContextTypeManual BetaManagedAgentsManualTriggerContextType = "manual" +) + +// An MCP server host used by the deployment's agent is blocked by the +// environment's network policy. +type BetaManagedAgentsMCPEgressBlockedRunError struct { + // Human-readable error description. + Message string `json:"message" api:"required"` + // Any of "mcp_egress_blocked_error". + Type BetaManagedAgentsMCPEgressBlockedRunErrorType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Message respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsMCPEgressBlockedRunError) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsMCPEgressBlockedRunError) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsMCPEgressBlockedRunErrorType string + +const ( + BetaManagedAgentsMCPEgressBlockedRunErrorTypeMCPEgressBlockedError BetaManagedAgentsMCPEgressBlockedRunErrorType = "mcp_egress_blocked_error" +) + +// A memory store referenced by the deployment is archived. +type BetaManagedAgentsMemoryStoreArchivedRunError struct { + // Human-readable error description. + Message string `json:"message" api:"required"` + // Any of "memory_store_archived_error". + Type BetaManagedAgentsMemoryStoreArchivedRunErrorType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Message respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsMemoryStoreArchivedRunError) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsMemoryStoreArchivedRunError) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsMemoryStoreArchivedRunErrorType string + +const ( + BetaManagedAgentsMemoryStoreArchivedRunErrorTypeMemoryStoreArchivedError BetaManagedAgentsMemoryStoreArchivedRunErrorType = "memory_store_archived_error" +) + +// The deployment's organization is disabled. +type BetaManagedAgentsOrganizationDisabledRunError struct { + // Human-readable error description. + Message string `json:"message" api:"required"` + // Any of "organization_disabled_error". + Type BetaManagedAgentsOrganizationDisabledRunErrorType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Message respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsOrganizationDisabledRunError) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsOrganizationDisabledRunError) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsOrganizationDisabledRunErrorType string + +const ( + BetaManagedAgentsOrganizationDisabledRunErrorTypeOrganizationDisabledError BetaManagedAgentsOrganizationDisabledRunErrorType = "organization_disabled_error" +) + +// The run was fired by the deployment's cron schedule. +type BetaManagedAgentsScheduleTriggerContext struct { + // A timestamp in RFC 3339 format + ScheduledAt time.Time `json:"scheduled_at" api:"required" format:"date-time"` + // Any of "schedule". + Type BetaManagedAgentsScheduleTriggerContextType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ScheduledAt respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsScheduleTriggerContext) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsScheduleTriggerContext) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsScheduleTriggerContextType string + +const ( + BetaManagedAgentsScheduleTriggerContextTypeSchedule BetaManagedAgentsScheduleTriggerContextType = "schedule" +) + +// The deployment configures resources, but its environment is self-hosted and +// cannot mount them. +type BetaManagedAgentsSelfHostedResourcesUnsupportedRunError struct { + // Human-readable error description. + Message string `json:"message" api:"required"` + // Any of "self_hosted_resources_unsupported_error". + Type BetaManagedAgentsSelfHostedResourcesUnsupportedRunErrorType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Message respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsSelfHostedResourcesUnsupportedRunError) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsSelfHostedResourcesUnsupportedRunError) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsSelfHostedResourcesUnsupportedRunErrorType string + +const ( + BetaManagedAgentsSelfHostedResourcesUnsupportedRunErrorTypeSelfHostedResourcesUnsupportedError BetaManagedAgentsSelfHostedResourcesUnsupportedRunErrorType = "self_hosted_resources_unsupported_error" +) + +// The session create request was rejected with a non-retryable validation error. +type BetaManagedAgentsSessionCreationRejectedRunError struct { + // Human-readable error description. + Message string `json:"message" api:"required"` + // Any of "session_creation_rejected_error". + Type BetaManagedAgentsSessionCreationRejectedRunErrorType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Message respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsSessionCreationRejectedRunError) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsSessionCreationRejectedRunError) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsSessionCreationRejectedRunErrorType string + +const ( + BetaManagedAgentsSessionCreationRejectedRunErrorTypeSessionCreationRejectedError BetaManagedAgentsSessionCreationRejectedRunErrorType = "session_creation_rejected_error" +) + +// Session creation was rejected due to rate limiting. The schedule keeps firing; +// subsequent runs may succeed. +type BetaManagedAgentsSessionRateLimitedRunError struct { + // Human-readable error description. + Message string `json:"message" api:"required"` + // Any of "session_rate_limited_error". + Type BetaManagedAgentsSessionRateLimitedRunErrorType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Message respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsSessionRateLimitedRunError) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsSessionRateLimitedRunError) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsSessionRateLimitedRunErrorType string + +const ( + BetaManagedAgentsSessionRateLimitedRunErrorTypeSessionRateLimitedError BetaManagedAgentsSessionRateLimitedRunErrorType = "session_rate_limited_error" +) + +// A referenced resource no longer exists and its kind was not reported. +type BetaManagedAgentsSessionResourceNotFoundRunError struct { + // Human-readable error description. + Message string `json:"message" api:"required"` + // Any of "session_resource_not_found_error". + Type BetaManagedAgentsSessionResourceNotFoundRunErrorType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Message respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsSessionResourceNotFoundRunError) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsSessionResourceNotFoundRunError) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsSessionResourceNotFoundRunErrorType string + +const ( + BetaManagedAgentsSessionResourceNotFoundRunErrorTypeSessionResourceNotFoundError BetaManagedAgentsSessionResourceNotFoundRunErrorType = "session_resource_not_found_error" +) + +// A skill referenced by the deployment's agent no longer exists. +type BetaManagedAgentsSkillNotFoundRunError struct { + // Human-readable error description. + Message string `json:"message" api:"required"` + // Any of "skill_not_found_error". + Type BetaManagedAgentsSkillNotFoundRunErrorType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Message respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsSkillNotFoundRunError) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsSkillNotFoundRunError) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsSkillNotFoundRunErrorType string + +const ( + BetaManagedAgentsSkillNotFoundRunErrorTypeSkillNotFoundError BetaManagedAgentsSkillNotFoundRunErrorType = "skill_not_found_error" +) + +// BetaManagedAgentsTriggerContextUnion contains all possible properties and values +// from [BetaManagedAgentsScheduleTriggerContext], +// [BetaManagedAgentsManualTriggerContext]. +// +// Use the [BetaManagedAgentsTriggerContextUnion.AsAny] method to switch on the +// variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaManagedAgentsTriggerContextUnion struct { + // This field is from variant [BetaManagedAgentsScheduleTriggerContext]. + ScheduledAt time.Time `json:"scheduled_at"` + // Any of "schedule", "manual". + Type string `json:"type"` + JSON struct { + ScheduledAt respjson.Field + Type respjson.Field + raw string + } `json:"-"` +} + +// anyBetaManagedAgentsTriggerContext is implemented by each variant of +// [BetaManagedAgentsTriggerContextUnion] to add type safety for the return type of +// [BetaManagedAgentsTriggerContextUnion.AsAny] +type anyBetaManagedAgentsTriggerContext interface { + implBetaManagedAgentsTriggerContextUnion() +} + +func (BetaManagedAgentsScheduleTriggerContext) implBetaManagedAgentsTriggerContextUnion() {} +func (BetaManagedAgentsManualTriggerContext) implBetaManagedAgentsTriggerContextUnion() {} + +// Use the following switch statement to find the correct variant +// +// switch variant := BetaManagedAgentsTriggerContextUnion.AsAny().(type) { +// case anthropic.BetaManagedAgentsScheduleTriggerContext: +// case anthropic.BetaManagedAgentsManualTriggerContext: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaManagedAgentsTriggerContextUnion) AsAny() anyBetaManagedAgentsTriggerContext { + switch u.Type { + case "schedule": + return u.AsSchedule() + case "manual": + return u.AsManual() + } + return nil +} + +func (u BetaManagedAgentsTriggerContextUnion) AsSchedule() (v BetaManagedAgentsScheduleTriggerContext) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsTriggerContextUnion) AsManual() (v BetaManagedAgentsManualTriggerContext) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u BetaManagedAgentsTriggerContextUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaManagedAgentsTriggerContextUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// What triggered a deployment run. +type BetaManagedAgentsTriggerType string + +const ( + BetaManagedAgentsTriggerTypeSchedule BetaManagedAgentsTriggerType = "schedule" + BetaManagedAgentsTriggerTypeManual BetaManagedAgentsTriggerType = "manual" +) + +// An unknown or unexpected error caused the run to fail. A fallback variant; +// clients that do not recognize a new error type can match on message alone. +type BetaManagedAgentsUnknownRunError struct { + // Human-readable error description. + Message string `json:"message" api:"required"` + // Any of "unknown_error". + Type BetaManagedAgentsUnknownRunErrorType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Message respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsUnknownRunError) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsUnknownRunError) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsUnknownRunErrorType string + +const ( + BetaManagedAgentsUnknownRunErrorTypeUnknownError BetaManagedAgentsUnknownRunErrorType = "unknown_error" +) + +// A vault referenced by the deployment is archived. +type BetaManagedAgentsVaultArchivedRunError struct { + // Human-readable error description. + Message string `json:"message" api:"required"` + // Any of "vault_archived_error". + Type BetaManagedAgentsVaultArchivedRunErrorType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Message respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsVaultArchivedRunError) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsVaultArchivedRunError) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsVaultArchivedRunErrorType string + +const ( + BetaManagedAgentsVaultArchivedRunErrorTypeVaultArchivedError BetaManagedAgentsVaultArchivedRunErrorType = "vault_archived_error" +) + +// A vault referenced by the deployment no longer exists. +type BetaManagedAgentsVaultNotFoundRunError struct { + // Human-readable error description. + Message string `json:"message" api:"required"` + // Any of "vault_not_found_error". + Type BetaManagedAgentsVaultNotFoundRunErrorType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Message respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsVaultNotFoundRunError) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsVaultNotFoundRunError) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsVaultNotFoundRunErrorType string + +const ( + BetaManagedAgentsVaultNotFoundRunErrorTypeVaultNotFoundError BetaManagedAgentsVaultNotFoundRunErrorType = "vault_not_found_error" +) + +// The deployment's workspace was archived. +type BetaManagedAgentsWorkspaceArchivedRunError struct { + // Human-readable error description. + Message string `json:"message" api:"required"` + // Any of "workspace_archived_error". + Type BetaManagedAgentsWorkspaceArchivedRunErrorType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Message respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsWorkspaceArchivedRunError) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsWorkspaceArchivedRunError) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsWorkspaceArchivedRunErrorType string + +const ( + BetaManagedAgentsWorkspaceArchivedRunErrorTypeWorkspaceArchivedError BetaManagedAgentsWorkspaceArchivedRunErrorType = "workspace_archived_error" +) + +type BetaDeploymentRunGetParams struct { + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +type BetaDeploymentRunListParams struct { + // Return runs created strictly after this time (exclusive). + CreatedAtGt param.Opt[time.Time] `query:"created_at[gt],omitzero" format:"date-time" json:"-"` + // Return runs created at or after this time (inclusive). + CreatedAtGte param.Opt[time.Time] `query:"created_at[gte],omitzero" format:"date-time" json:"-"` + // Return runs created strictly before this time (exclusive). + CreatedAtLt param.Opt[time.Time] `query:"created_at[lt],omitzero" format:"date-time" json:"-"` + // Return runs created at or before this time (inclusive). + CreatedAtLte param.Opt[time.Time] `query:"created_at[lte],omitzero" format:"date-time" json:"-"` + // Filter to a specific deployment. Omit to list across all deployments in the + // workspace. Filtering by a non-existent deployment_id returns 200 with empty + // data. + DeploymentID param.Opt[string] `query:"deployment_id,omitzero" json:"-"` + // Filter: true for runs with non-null error, false for runs with non-null + // session_id. Omit for all. + HasError param.Opt[bool] `query:"has_error,omitzero" json:"-"` + // Maximum results per page. Default 20, maximum 1000. + Limit param.Opt[int64] `query:"limit,omitzero" json:"-"` + // Opaque pagination cursor. Pass next_page from the previous response. Invalid or + // expired cursors return 400. + Page param.Opt[string] `query:"page,omitzero" json:"-"` + // Filter runs by what triggered them. Omit to return all runs. + // + // Any of "schedule", "manual". + TriggerType BetaManagedAgentsTriggerType `query:"trigger_type,omitzero" json:"-"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +// URLQuery serializes [BetaDeploymentRunListParams]'s query parameters as +// `url.Values`. +func (r BetaDeploymentRunListParams) URLQuery() (v url.Values, err error) { + return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ + ArrayFormat: apiquery.ArrayQueryFormatBrackets, + NestedFormat: apiquery.NestedQueryFormatBrackets, + }) +} diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/betadream.go b/vendor/github.com/anthropics/anthropic-sdk-go/betadream.go new file mode 100644 index 000000000..d01a6a1fd --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/betadream.go @@ -0,0 +1,945 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +package anthropic + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/url" + "slices" + "time" + + "github.com/anthropics/anthropic-sdk-go/internal/apijson" + "github.com/anthropics/anthropic-sdk-go/internal/apiquery" + "github.com/anthropics/anthropic-sdk-go/internal/requestconfig" + "github.com/anthropics/anthropic-sdk-go/option" + "github.com/anthropics/anthropic-sdk-go/packages/pagination" + "github.com/anthropics/anthropic-sdk-go/packages/param" + "github.com/anthropics/anthropic-sdk-go/packages/respjson" +) + +// BetaDreamService contains methods and other services that help with interacting +// with the anthropic API. +// +// Note, unlike clients, this service does not read variables from the environment +// automatically. You should not instantiate this service directly, and instead use +// the [NewBetaDreamService] method instead. +type BetaDreamService struct { + Options []option.RequestOption +} + +// NewBetaDreamService generates a new service that applies the given options to +// each request. These options are applied after the parent client's options (if +// there is one), and before any request-specific options. +func NewBetaDreamService(opts ...option.RequestOption) (r BetaDreamService) { + r = BetaDreamService{} + r.Options = opts + return +} + +// Create a Dream +func (r *BetaDreamService) New(ctx context.Context, params BetaDreamNewParams, opts ...option.RequestOption) (res *BetaDream, err error) { + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "dreaming-2026-04-21")}, opts...) + path := "v1/dreams?beta=true" + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, params, &res, opts...) + return res, err +} + +// Get a Dream +func (r *BetaDreamService) Get(ctx context.Context, dreamID string, query BetaDreamGetParams, opts ...option.RequestOption) (res *BetaDream, err error) { + for _, v := range query.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "dreaming-2026-04-21")}, opts...) + if dreamID == "" { + err = errors.New("missing required dream_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/dreams/%s?beta=true", dreamID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...) + return res, err +} + +// List Dreams +func (r *BetaDreamService) List(ctx context.Context, params BetaDreamListParams, opts ...option.RequestOption) (res *pagination.PageCursor[BetaDream], err error) { + var raw *http.Response + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "dreaming-2026-04-21"), option.WithResponseInto(&raw)}, opts...) + path := "v1/dreams?beta=true" + cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, params, &res, opts...) + if err != nil { + return nil, err + } + err = cfg.Execute() + if err != nil { + return nil, err + } + res.SetPageConfig(cfg, raw) + return res, nil +} + +// List Dreams +func (r *BetaDreamService) ListAutoPaging(ctx context.Context, params BetaDreamListParams, opts ...option.RequestOption) *pagination.PageCursorAutoPager[BetaDream] { + return pagination.NewPageCursorAutoPager(r.List(ctx, params, opts...)) +} + +// Archive a Dream +func (r *BetaDreamService) Archive(ctx context.Context, dreamID string, body BetaDreamArchiveParams, opts ...option.RequestOption) (res *BetaDream, err error) { + for _, v := range body.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "dreaming-2026-04-21")}, opts...) + if dreamID == "" { + err = errors.New("missing required dream_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/dreams/%s/archive?beta=true", dreamID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, nil, &res, opts...) + return res, err +} + +// Cancel a Dream +func (r *BetaDreamService) Cancel(ctx context.Context, dreamID string, body BetaDreamCancelParams, opts ...option.RequestOption) (res *BetaDream, err error) { + for _, v := range body.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "dreaming-2026-04-21")}, opts...) + if dreamID == "" { + err = errors.New("missing required dream_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/dreams/%s/cancel?beta=true", dreamID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, nil, &res, opts...) + return res, err +} + +// An asynchronous memory-consolidation job that reads a memory store plus a set of +// session transcripts and writes consolidated memories into an output memory store +// — a new store by default, or an existing store chosen via output_behavior. The +// Dreams API is in research preview: the request and response shapes are volatile +// and may change without the deprecation period that applies to +// generally-available endpoints. +type BetaDream struct { + ID string `json:"id" api:"required"` + // A timestamp in RFC 3339 format + ArchivedAt time.Time `json:"archived_at" api:"required" format:"date-time"` + // A timestamp in RFC 3339 format + CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"` + // A timestamp in RFC 3339 format + EndedAt time.Time `json:"ended_at" api:"required" format:"date-time"` + // Failure detail for a Dream whose `status` is `failed`. + Error BetaDreamError `json:"error" api:"required"` + Inputs []BetaDreamInputUnion `json:"inputs" api:"required"` + Instructions string `json:"instructions" api:"required"` + // Model identifier and configuration applied to every pipeline stage. Same wire + // shape as the Agents API ModelConfig. + Model BetaDreamModelConfig `json:"model" api:"required"` + // The default destination: the job creates a new output memory store as a clone of + // the memory_store input and writes the consolidated memories into it. The input + // store is never mutated. + OutputBehavior BetaOutputBehaviorUnion `json:"output_behavior" api:"required"` + Outputs []BetaDreamOutput `json:"outputs" api:"required"` + SessionID string `json:"session_id" api:"required"` + // Lifecycle status of a Dream. + // + // Any of "pending", "running", "completed", "failed", "canceled". + Status BetaDreamStatus `json:"status" api:"required"` + // Any of "dream". + Type BetaDreamType `json:"type" api:"required"` + // Cumulative token usage for the dream across every pipeline stage. + Usage BetaDreamUsage `json:"usage" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + ArchivedAt respjson.Field + CreatedAt respjson.Field + EndedAt respjson.Field + Error respjson.Field + Inputs respjson.Field + Instructions respjson.Field + Model respjson.Field + OutputBehavior respjson.Field + Outputs respjson.Field + SessionID respjson.Field + Status respjson.Field + Type respjson.Field + Usage respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaDream) RawJSON() string { return r.JSON.raw } +func (r *BetaDream) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaDreamType string + +const ( + BetaDreamTypeDream BetaDreamType = "dream" +) + +// Failure detail for a Dream whose `status` is `failed`. +type BetaDreamError struct { + Message string `json:"message" api:"required"` + Type string `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Message respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaDreamError) RawJSON() string { return r.JSON.raw } +func (r *BetaDreamError) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaDreamInputUnion contains all possible properties and values from +// [BetaDreamMemoryStoreInput], [BetaDreamSessionsInput]. +// +// Use the [BetaDreamInputUnion.AsAny] method to switch on the variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaDreamInputUnion struct { + // This field is from variant [BetaDreamMemoryStoreInput]. + MemoryStoreID string `json:"memory_store_id"` + // Any of "memory_store", "sessions". + Type string `json:"type"` + // This field is from variant [BetaDreamSessionsInput]. + SessionIDs []string `json:"session_ids"` + JSON struct { + MemoryStoreID respjson.Field + Type respjson.Field + SessionIDs respjson.Field + raw string + } `json:"-"` +} + +// anyBetaDreamInput is implemented by each variant of [BetaDreamInputUnion] to add +// type safety for the return type of [BetaDreamInputUnion.AsAny] +type anyBetaDreamInput interface { + implBetaDreamInputUnion() +} + +func (BetaDreamMemoryStoreInput) implBetaDreamInputUnion() {} +func (BetaDreamSessionsInput) implBetaDreamInputUnion() {} + +// Use the following switch statement to find the correct variant +// +// switch variant := BetaDreamInputUnion.AsAny().(type) { +// case anthropic.BetaDreamMemoryStoreInput: +// case anthropic.BetaDreamSessionsInput: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaDreamInputUnion) AsAny() anyBetaDreamInput { + switch u.Type { + case "memory_store": + return u.AsMemoryStore() + case "sessions": + return u.AsSessions() + } + return nil +} + +func (u BetaDreamInputUnion) AsMemoryStore() (v BetaDreamMemoryStoreInput) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaDreamInputUnion) AsSessions() (v BetaDreamSessionsInput) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u BetaDreamInputUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaDreamInputUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// ToParam converts this BetaDreamInputUnion to a BetaDreamInputUnionParam. +// +// Warning: the fields of the param type will not be present. ToParam should only +// be used at the last possible moment before sending a request. Test for this with +// BetaDreamInputUnionParam.Overrides() +func (r BetaDreamInputUnion) ToParam() BetaDreamInputUnionParam { + return param.Override[BetaDreamInputUnionParam](json.RawMessage(r.RawJSON())) +} + +func BetaDreamInputParamOfMemoryStore(memoryStoreID string) BetaDreamInputUnionParam { + var memoryStore BetaDreamMemoryStoreInputParam + memoryStore.MemoryStoreID = memoryStoreID + return BetaDreamInputUnionParam{OfMemoryStore: &memoryStore} +} + +func BetaDreamInputParamOfSessions(sessionIDs []string) BetaDreamInputUnionParam { + var sessions BetaDreamSessionsInputParam + sessions.SessionIDs = sessionIDs + return BetaDreamInputUnionParam{OfSessions: &sessions} +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaDreamInputUnionParam struct { + OfMemoryStore *BetaDreamMemoryStoreInputParam `json:",omitzero,inline"` + OfSessions *BetaDreamSessionsInputParam `json:",omitzero,inline"` + paramUnion +} + +func (u BetaDreamInputUnionParam) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfMemoryStore, u.OfSessions) +} +func (u *BetaDreamInputUnionParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *BetaDreamInputUnionParam) asAny() any { + if !param.IsOmitted(u.OfMemoryStore) { + return u.OfMemoryStore + } else if !param.IsOmitted(u.OfSessions) { + return u.OfSessions + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaDreamInputUnionParam) GetMemoryStoreID() *string { + if vt := u.OfMemoryStore; vt != nil { + return &vt.MemoryStoreID + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaDreamInputUnionParam) GetSessionIDs() []string { + if vt := u.OfSessions; vt != nil { + return vt.SessionIDs + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaDreamInputUnionParam) GetType() *string { + if vt := u.OfMemoryStore; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfSessions; vt != nil { + return (*string)(&vt.Type) + } + return nil +} + +func init() { + apijson.RegisterUnion[BetaDreamInputUnionParam]( + "type", + apijson.Discriminator[BetaDreamMemoryStoreInputParam]("memory_store"), + apijson.Discriminator[BetaDreamSessionsInputParam]("sessions"), + ) +} + +// An input memory store the dream reads from. The dream never mutates this store +// unless it is also the destination: with output_behavior {type: +// "update_existing"} the job consolidates this store in place. +type BetaDreamMemoryStoreInput struct { + MemoryStoreID string `json:"memory_store_id" api:"required"` + // Any of "memory_store". + Type BetaDreamMemoryStoreInputType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + MemoryStoreID respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaDreamMemoryStoreInput) RawJSON() string { return r.JSON.raw } +func (r *BetaDreamMemoryStoreInput) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// ToParam converts this BetaDreamMemoryStoreInput to a +// BetaDreamMemoryStoreInputParam. +// +// Warning: the fields of the param type will not be present. ToParam should only +// be used at the last possible moment before sending a request. Test for this with +// BetaDreamMemoryStoreInputParam.Overrides() +func (r BetaDreamMemoryStoreInput) ToParam() BetaDreamMemoryStoreInputParam { + return param.Override[BetaDreamMemoryStoreInputParam](json.RawMessage(r.RawJSON())) +} + +type BetaDreamMemoryStoreInputType string + +const ( + BetaDreamMemoryStoreInputTypeMemoryStore BetaDreamMemoryStoreInputType = "memory_store" +) + +// An input memory store the dream reads from. The dream never mutates this store +// unless it is also the destination: with output_behavior {type: +// "update_existing"} the job consolidates this store in place. +// +// The properties MemoryStoreID, Type are required. +type BetaDreamMemoryStoreInputParam struct { + MemoryStoreID string `json:"memory_store_id" api:"required"` + // Any of "memory_store". + Type BetaDreamMemoryStoreInputType `json:"type,omitzero" api:"required"` + paramObj +} + +func (r BetaDreamMemoryStoreInputParam) MarshalJSON() (data []byte, err error) { + type shadow BetaDreamMemoryStoreInputParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaDreamMemoryStoreInputParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Model identifier and configuration applied to every pipeline stage. Same wire +// shape as the Agents API ModelConfig. +type BetaDreamModelConfig struct { + // Model identifier, e.g. "claude-opus-5". 1-256 characters. + ID string `json:"id" api:"required"` + // Inference speed mode. `fast` provides significantly faster output token + // generation at premium pricing. Not all models support `fast`; invalid + // combinations are rejected at create time. + // + // Any of "standard", "fast". + Speed BetaDreamModelConfigSpeed `json:"speed"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + Speed respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaDreamModelConfig) RawJSON() string { return r.JSON.raw } +func (r *BetaDreamModelConfig) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Inference speed mode. `fast` provides significantly faster output token +// generation at premium pricing. Not all models support `fast`; invalid +// combinations are rejected at create time. +type BetaDreamModelConfigSpeed string + +const ( + BetaDreamModelConfigSpeedStandard BetaDreamModelConfigSpeed = "standard" + BetaDreamModelConfigSpeedFast BetaDreamModelConfigSpeed = "fast" +) + +// Model identifier and configuration applied to every pipeline stage. +// +// The property ID is required. +type BetaDreamModelConfigParam struct { + // Model identifier, e.g. "claude-opus-5". 1-256 characters. + ID string `json:"id" api:"required"` + // Inference speed mode. `fast` provides significantly faster output token + // generation at premium pricing. Not all models support `fast`; invalid + // combinations are rejected at create time. + // + // Any of "standard", "fast". + Speed BetaDreamModelConfigParamSpeed `json:"speed,omitzero"` + paramObj +} + +func (r BetaDreamModelConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaDreamModelConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaDreamModelConfigParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Inference speed mode. `fast` provides significantly faster output token +// generation at premium pricing. Not all models support `fast`; invalid +// combinations are rejected at create time. +type BetaDreamModelConfigParamSpeed string + +const ( + BetaDreamModelConfigParamSpeedStandard BetaDreamModelConfigParamSpeed = "standard" + BetaDreamModelConfigParamSpeedFast BetaDreamModelConfigParamSpeed = "fast" +) + +// An output memory store the dream writes consolidated memories into. +type BetaDreamOutput struct { + MemoryStoreID string `json:"memory_store_id" api:"required"` + // Any of "memory_store". + Type BetaDreamOutputType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + MemoryStoreID respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaDreamOutput) RawJSON() string { return r.JSON.raw } +func (r *BetaDreamOutput) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaDreamOutputType string + +const ( + BetaDreamOutputTypeMemoryStore BetaDreamOutputType = "memory_store" +) + +// Input session transcripts the dream reads. +type BetaDreamSessionsInput struct { + SessionIDs []string `json:"session_ids" api:"required"` + // Any of "sessions". + Type BetaDreamSessionsInputType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + SessionIDs respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaDreamSessionsInput) RawJSON() string { return r.JSON.raw } +func (r *BetaDreamSessionsInput) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// ToParam converts this BetaDreamSessionsInput to a BetaDreamSessionsInputParam. +// +// Warning: the fields of the param type will not be present. ToParam should only +// be used at the last possible moment before sending a request. Test for this with +// BetaDreamSessionsInputParam.Overrides() +func (r BetaDreamSessionsInput) ToParam() BetaDreamSessionsInputParam { + return param.Override[BetaDreamSessionsInputParam](json.RawMessage(r.RawJSON())) +} + +type BetaDreamSessionsInputType string + +const ( + BetaDreamSessionsInputTypeSessions BetaDreamSessionsInputType = "sessions" +) + +// Input session transcripts the dream reads. +// +// The properties SessionIDs, Type are required. +type BetaDreamSessionsInputParam struct { + SessionIDs []string `json:"session_ids,omitzero" api:"required"` + // Any of "sessions". + Type BetaDreamSessionsInputType `json:"type,omitzero" api:"required"` + paramObj +} + +func (r BetaDreamSessionsInputParam) MarshalJSON() (data []byte, err error) { + type shadow BetaDreamSessionsInputParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaDreamSessionsInputParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Lifecycle status of a Dream. +type BetaDreamStatus string + +const ( + BetaDreamStatusPending BetaDreamStatus = "pending" + BetaDreamStatusRunning BetaDreamStatus = "running" + BetaDreamStatusCompleted BetaDreamStatus = "completed" + BetaDreamStatusFailed BetaDreamStatus = "failed" + BetaDreamStatusCanceled BetaDreamStatus = "canceled" +) + +// Cumulative token usage for the dream across every pipeline stage. +type BetaDreamUsage struct { + // Total tokens used to create prompt-cache entries (sum of all TTL tiers). + CacheCreationInputTokens int64 `json:"cache_creation_input_tokens" api:"required"` + // Total tokens read from prompt cache. + CacheReadInputTokens int64 `json:"cache_read_input_tokens" api:"required"` + // Total uncached input tokens consumed across every pipeline stage. + InputTokens int64 `json:"input_tokens" api:"required"` + // Total output tokens generated across every pipeline stage. + OutputTokens int64 `json:"output_tokens" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + CacheCreationInputTokens respjson.Field + CacheReadInputTokens respjson.Field + InputTokens respjson.Field + OutputTokens respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaDreamUsage) RawJSON() string { return r.JSON.raw } +func (r *BetaDreamUsage) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaOutputBehaviorUnion contains all possible properties and values from +// [BetaOutputBehaviorCreateNew], [BetaOutputBehaviorUpdateExisting]. +// +// Use the [BetaOutputBehaviorUnion.AsAny] method to switch on the variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaOutputBehaviorUnion struct { + // Any of "create_new", "update_existing". + Type string `json:"type"` + // This field is from variant [BetaOutputBehaviorUpdateExisting]. + MemoryStoreID string `json:"memory_store_id"` + JSON struct { + Type respjson.Field + MemoryStoreID respjson.Field + raw string + } `json:"-"` +} + +// anyBetaOutputBehavior is implemented by each variant of +// [BetaOutputBehaviorUnion] to add type safety for the return type of +// [BetaOutputBehaviorUnion.AsAny] +type anyBetaOutputBehavior interface { + implBetaOutputBehaviorUnion() +} + +func (BetaOutputBehaviorCreateNew) implBetaOutputBehaviorUnion() {} +func (BetaOutputBehaviorUpdateExisting) implBetaOutputBehaviorUnion() {} + +// Use the following switch statement to find the correct variant +// +// switch variant := BetaOutputBehaviorUnion.AsAny().(type) { +// case anthropic.BetaOutputBehaviorCreateNew: +// case anthropic.BetaOutputBehaviorUpdateExisting: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaOutputBehaviorUnion) AsAny() anyBetaOutputBehavior { + switch u.Type { + case "create_new": + return u.AsCreateNew() + case "update_existing": + return u.AsUpdateExisting() + } + return nil +} + +func (u BetaOutputBehaviorUnion) AsCreateNew() (v BetaOutputBehaviorCreateNew) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaOutputBehaviorUnion) AsUpdateExisting() (v BetaOutputBehaviorUpdateExisting) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u BetaOutputBehaviorUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaOutputBehaviorUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// ToParam converts this BetaOutputBehaviorUnion to a BetaOutputBehaviorUnionParam. +// +// Warning: the fields of the param type will not be present. ToParam should only +// be used at the last possible moment before sending a request. Test for this with +// BetaOutputBehaviorUnionParam.Overrides() +func (r BetaOutputBehaviorUnion) ToParam() BetaOutputBehaviorUnionParam { + return param.Override[BetaOutputBehaviorUnionParam](json.RawMessage(r.RawJSON())) +} + +func BetaOutputBehaviorParamOfCreateNew(type_ BetaOutputBehaviorCreateNewType) BetaOutputBehaviorUnionParam { + var createNew BetaOutputBehaviorCreateNewParam + createNew.Type = type_ + return BetaOutputBehaviorUnionParam{OfCreateNew: &createNew} +} + +func BetaOutputBehaviorParamOfUpdateExisting(memoryStoreID string) BetaOutputBehaviorUnionParam { + var updateExisting BetaOutputBehaviorUpdateExistingParam + updateExisting.MemoryStoreID = memoryStoreID + return BetaOutputBehaviorUnionParam{OfUpdateExisting: &updateExisting} +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaOutputBehaviorUnionParam struct { + OfCreateNew *BetaOutputBehaviorCreateNewParam `json:",omitzero,inline"` + OfUpdateExisting *BetaOutputBehaviorUpdateExistingParam `json:",omitzero,inline"` + paramUnion +} + +func (u BetaOutputBehaviorUnionParam) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfCreateNew, u.OfUpdateExisting) +} +func (u *BetaOutputBehaviorUnionParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *BetaOutputBehaviorUnionParam) asAny() any { + if !param.IsOmitted(u.OfCreateNew) { + return u.OfCreateNew + } else if !param.IsOmitted(u.OfUpdateExisting) { + return u.OfUpdateExisting + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaOutputBehaviorUnionParam) GetMemoryStoreID() *string { + if vt := u.OfUpdateExisting; vt != nil { + return &vt.MemoryStoreID + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaOutputBehaviorUnionParam) GetType() *string { + if vt := u.OfCreateNew; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfUpdateExisting; vt != nil { + return (*string)(&vt.Type) + } + return nil +} + +func init() { + apijson.RegisterUnion[BetaOutputBehaviorUnionParam]( + "type", + apijson.Discriminator[BetaOutputBehaviorCreateNewParam]("create_new"), + apijson.Discriminator[BetaOutputBehaviorUpdateExistingParam]("update_existing"), + ) +} + +// The default destination: the job creates a new output memory store as a clone of +// the memory_store input and writes the consolidated memories into it. The input +// store is never mutated. +type BetaOutputBehaviorCreateNew struct { + // Any of "create_new". + Type BetaOutputBehaviorCreateNewType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaOutputBehaviorCreateNew) RawJSON() string { return r.JSON.raw } +func (r *BetaOutputBehaviorCreateNew) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// ToParam converts this BetaOutputBehaviorCreateNew to a +// BetaOutputBehaviorCreateNewParam. +// +// Warning: the fields of the param type will not be present. ToParam should only +// be used at the last possible moment before sending a request. Test for this with +// BetaOutputBehaviorCreateNewParam.Overrides() +func (r BetaOutputBehaviorCreateNew) ToParam() BetaOutputBehaviorCreateNewParam { + return param.Override[BetaOutputBehaviorCreateNewParam](json.RawMessage(r.RawJSON())) +} + +type BetaOutputBehaviorCreateNewType string + +const ( + BetaOutputBehaviorCreateNewTypeCreateNew BetaOutputBehaviorCreateNewType = "create_new" +) + +// The default destination: the job creates a new output memory store as a clone of +// the memory_store input and writes the consolidated memories into it. The input +// store is never mutated. +// +// The property Type is required. +type BetaOutputBehaviorCreateNewParam struct { + // Any of "create_new". + Type BetaOutputBehaviorCreateNewType `json:"type,omitzero" api:"required"` + paramObj +} + +func (r BetaOutputBehaviorCreateNewParam) MarshalJSON() (data []byte, err error) { + type shadow BetaOutputBehaviorCreateNewParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaOutputBehaviorCreateNewParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The job writes the consolidated memories into this existing memory store instead +// of creating one. In EAP the store must be the job's own memory_store input, so +// the job consolidates the store in place. +type BetaOutputBehaviorUpdateExisting struct { + MemoryStoreID string `json:"memory_store_id" api:"required"` + // Any of "update_existing". + Type BetaOutputBehaviorUpdateExistingType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + MemoryStoreID respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaOutputBehaviorUpdateExisting) RawJSON() string { return r.JSON.raw } +func (r *BetaOutputBehaviorUpdateExisting) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// ToParam converts this BetaOutputBehaviorUpdateExisting to a +// BetaOutputBehaviorUpdateExistingParam. +// +// Warning: the fields of the param type will not be present. ToParam should only +// be used at the last possible moment before sending a request. Test for this with +// BetaOutputBehaviorUpdateExistingParam.Overrides() +func (r BetaOutputBehaviorUpdateExisting) ToParam() BetaOutputBehaviorUpdateExistingParam { + return param.Override[BetaOutputBehaviorUpdateExistingParam](json.RawMessage(r.RawJSON())) +} + +type BetaOutputBehaviorUpdateExistingType string + +const ( + BetaOutputBehaviorUpdateExistingTypeUpdateExisting BetaOutputBehaviorUpdateExistingType = "update_existing" +) + +// The job writes the consolidated memories into this existing memory store instead +// of creating one. In EAP the store must be the job's own memory_store input, so +// the job consolidates the store in place. +// +// The properties MemoryStoreID, Type are required. +type BetaOutputBehaviorUpdateExistingParam struct { + MemoryStoreID string `json:"memory_store_id" api:"required"` + // Any of "update_existing". + Type BetaOutputBehaviorUpdateExistingType `json:"type,omitzero" api:"required"` + paramObj +} + +func (r BetaOutputBehaviorUpdateExistingParam) MarshalJSON() (data []byte, err error) { + type shadow BetaOutputBehaviorUpdateExistingParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaOutputBehaviorUpdateExistingParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaDreamNewParams struct { + Inputs []BetaDreamInputUnionParam `json:"inputs,omitzero" api:"required"` + // Model identifier and configuration applied to every pipeline stage. + Model BetaDreamNewParamsModelUnion `json:"model,omitzero" api:"required"` + Instructions param.Opt[string] `json:"instructions,omitzero"` + // The default destination: the job creates a new output memory store as a clone of + // the memory_store input and writes the consolidated memories into it. The input + // store is never mutated. + OutputBehavior BetaOutputBehaviorUnionParam `json:"output_behavior,omitzero"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +func (r BetaDreamNewParams) MarshalJSON() (data []byte, err error) { + type shadow BetaDreamNewParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaDreamNewParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaDreamNewParamsModelUnion struct { + OfString param.Opt[string] `json:",omitzero,inline"` + OfBetaDreamModelConfig *BetaDreamModelConfigParam `json:",omitzero,inline"` + paramUnion +} + +func (u BetaDreamNewParamsModelUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfString, u.OfBetaDreamModelConfig) +} +func (u *BetaDreamNewParamsModelUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *BetaDreamNewParamsModelUnion) asAny() any { + if !param.IsOmitted(u.OfString) { + return &u.OfString.Value + } else if !param.IsOmitted(u.OfBetaDreamModelConfig) { + return u.OfBetaDreamModelConfig + } + return nil +} + +type BetaDreamGetParams struct { + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +type BetaDreamListParams struct { + // Return dreams with `created_at` strictly after this timestamp (exclusive lower + // bound, RFC 3339). Unset applies no lower bound. + CreatedAtGt param.Opt[time.Time] `query:"created_at[gt],omitzero" format:"date-time" json:"-"` + // Return dreams with `created_at` strictly before this timestamp (exclusive upper + // bound, RFC 3339). Unset applies no upper bound. + CreatedAtLt param.Opt[time.Time] `query:"created_at[lt],omitzero" format:"date-time" json:"-"` + // Query parameter for include_archived + IncludeArchived param.Opt[bool] `query:"include_archived,omitzero" json:"-"` + // Query parameter for limit + Limit param.Opt[int64] `query:"limit,omitzero" json:"-"` + // Query parameter for page + Page param.Opt[string] `query:"page,omitzero" json:"-"` + // Filter by lifecycle status. Repeat the parameter to match any of multiple + // statuses. Empty applies no status filter. + Statuses []BetaDreamStatus `query:"statuses,omitzero" json:"-"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +// URLQuery serializes [BetaDreamListParams]'s query parameters as `url.Values`. +func (r BetaDreamListParams) URLQuery() (v url.Values, err error) { + return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ + ArrayFormat: apiquery.ArrayQueryFormatBrackets, + NestedFormat: apiquery.NestedQueryFormatBrackets, + }) +} + +type BetaDreamArchiveParams struct { + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +type BetaDreamCancelParams struct { + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/betaenvironment.go b/vendor/github.com/anthropics/anthropic-sdk-go/betaenvironment.go index e64ff1cba..2feccc8f3 100644 --- a/vendor/github.com/anthropics/anthropic-sdk-go/betaenvironment.go +++ b/vendor/github.com/anthropics/anthropic-sdk-go/betaenvironment.go @@ -29,6 +29,7 @@ import ( // the [NewBetaEnvironmentService] method instead. type BetaEnvironmentService struct { Options []option.RequestOption + Work BetaEnvironmentWorkService } // NewBetaEnvironmentService generates a new service that applies the given options @@ -37,6 +38,7 @@ type BetaEnvironmentService struct { func NewBetaEnvironmentService(opts ...option.RequestOption) (r BetaEnvironmentService) { r = BetaEnvironmentService{} r.Options = opts + r.Work = NewBetaEnvironmentWorkService(opts...) return } @@ -249,6 +251,9 @@ type BetaCloudConfigParams struct { // When versioning, use the version semantics relevant for the package manager, // e.g. for `pip` use `package==1.0.0`. You are responsible for validating the // package and version exist. Unversioned installs the latest. + // + // Under `limited` networking, requires `networking.allow_package_managers` to be + // `true`. Packages BetaPackagesParams `json:"packages,omitzero"` // Environment type // @@ -332,17 +337,17 @@ func init() { ) } -// Unified Environment resource for both cloud and BYOC environments. +// Unified Environment resource for both cloud and self-hosted environments. type BetaEnvironment struct { // Environment identifier (e.g., 'env\_...') ID string `json:"id" api:"required"` // RFC 3339 timestamp when environment was archived, or null if not archived ArchivedAt string `json:"archived_at" api:"required"` - // `cloud` environment configuration. - Config BetaCloudConfig `json:"config" api:"required"` + // Environment configuration (either Anthropic Cloud or self-hosted) + Config BetaEnvironmentConfigUnion `json:"config" api:"required"` // RFC 3339 timestamp when environment was created CreatedAt string `json:"created_at" api:"required"` - // User-provided description for the environment + // User-provided description for the environment; null when unset Description string `json:"description" api:"required"` // User-provided metadata key-value pairs Metadata map[string]string `json:"metadata" api:"required"` @@ -352,6 +357,11 @@ type BetaEnvironment struct { Type constant.Environment `json:"type" default:"environment"` // RFC 3339 timestamp when environment was last updated UpdatedAt string `json:"updated_at" api:"required"` + // The visibility scope for this environment. 'organization' means visible to all + // accounts. 'account' means visible only to the owning account. + // + // Any of "organization", "account". + Scope BetaEnvironmentScope `json:"scope"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ID respjson.Field @@ -363,6 +373,7 @@ type BetaEnvironment struct { Name respjson.Field Type respjson.Field UpdatedAt respjson.Field + Scope respjson.Field ExtraFields map[string]respjson.Field raw string } `json:"-"` @@ -374,12 +385,89 @@ func (r *BetaEnvironment) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } +// BetaEnvironmentConfigUnion contains all possible properties and values from +// [BetaCloudConfig], [BetaSelfHostedConfig]. +// +// Use the [BetaEnvironmentConfigUnion.AsAny] method to switch on the variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaEnvironmentConfigUnion struct { + // This field is from variant [BetaCloudConfig]. + Networking BetaCloudConfigNetworkingUnion `json:"networking"` + // This field is from variant [BetaCloudConfig]. + Packages BetaPackages `json:"packages"` + // Any of "cloud", "self_hosted". + Type string `json:"type"` + JSON struct { + Networking respjson.Field + Packages respjson.Field + Type respjson.Field + raw string + } `json:"-"` +} + +// anyBetaEnvironmentConfig is implemented by each variant of +// [BetaEnvironmentConfigUnion] to add type safety for the return type of +// [BetaEnvironmentConfigUnion.AsAny] +type anyBetaEnvironmentConfig interface { + implBetaEnvironmentConfigUnion() +} + +func (BetaCloudConfig) implBetaEnvironmentConfigUnion() {} +func (BetaSelfHostedConfig) implBetaEnvironmentConfigUnion() {} + +// Use the following switch statement to find the correct variant +// +// switch variant := BetaEnvironmentConfigUnion.AsAny().(type) { +// case anthropic.BetaCloudConfig: +// case anthropic.BetaSelfHostedConfig: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaEnvironmentConfigUnion) AsAny() anyBetaEnvironmentConfig { + switch u.Type { + case "cloud": + return u.AsCloud() + case "self_hosted": + return u.AsSelfHosted() + } + return nil +} + +func (u BetaEnvironmentConfigUnion) AsCloud() (v BetaCloudConfig) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaEnvironmentConfigUnion) AsSelfHosted() (v BetaSelfHostedConfig) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u BetaEnvironmentConfigUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaEnvironmentConfigUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The visibility scope for this environment. 'organization' means visible to all +// accounts. 'account' means visible only to the owning account. +type BetaEnvironmentScope string + +const ( + BetaEnvironmentScopeOrganization BetaEnvironmentScope = "organization" + BetaEnvironmentScopeAccount BetaEnvironmentScope = "account" +) + // Response after deleting an environment. type BetaEnvironmentDeleteResponse struct { // Environment identifier ID string `json:"id" api:"required"` // The type of response - Type constant.EnvironmentDeleted `json:"type" default:"environment_deleted"` + // + // Any of "environment_deleted". + Type BetaEnvironmentDeleteResponseType `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ID respjson.Field @@ -395,6 +483,13 @@ func (r *BetaEnvironmentDeleteResponse) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } +// The type of response +type BetaEnvironmentDeleteResponseType string + +const ( + BetaEnvironmentDeleteResponseTypeEnvironmentDeleted BetaEnvironmentDeleteResponseType = "environment_deleted" +) + // Limited network access. type BetaLimitedNetwork struct { // Permits outbound access to MCP server endpoints configured on the agent, beyond @@ -434,7 +529,8 @@ type BetaLimitedNetworkParams struct { // those listed in the `allowed_hosts` array. Defaults to `false`. AllowMCPServers param.Opt[bool] `json:"allow_mcp_servers,omitzero"` // Permits outbound access to public package registries (PyPI, npm, etc.) beyond - // those listed in the `allowed_hosts` array. Defaults to `false`. + // those listed in the `allowed_hosts` array. Defaults to `false` on creation. Must + // be `true` when `packages` are specified. AllowPackageManagers param.Opt[bool] `json:"allow_package_managers,omitzero"` // Specifies domains the container can reach. AllowedHosts []string `json:"allowed_hosts,omitzero"` @@ -503,6 +599,9 @@ const ( // When versioning, use the version semantics relevant for the package manager, // e.g. for `pip` use `package==1.0.0`. You are responsible for validating the // package and version exist. Unversioned installs the latest. +// +// Under `limited` networking, requires `networking.allow_package_managers` to be +// `true`. type BetaPackagesParams struct { // Ubuntu/Debian packages to install Apt []string `json:"apt,omitzero"` @@ -538,6 +637,48 @@ const ( BetaPackagesParamsTypePackages BetaPackagesParamsType = "packages" ) +// Configuration for self-hosted environments. +type BetaSelfHostedConfig struct { + // Environment type + Type constant.SelfHosted `json:"type" default:"self_hosted"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaSelfHostedConfig) RawJSON() string { return r.JSON.raw } +func (r *BetaSelfHostedConfig) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +func NewBetaSelfHostedConfigParams() BetaSelfHostedConfigParams { + return BetaSelfHostedConfigParams{ + Type: "self_hosted", + } +} + +// Request params for `self_hosted` environment configuration. +// +// This struct has a constant value, construct it with +// [NewBetaSelfHostedConfigParams]. +type BetaSelfHostedConfigParams struct { + // Environment type + Type constant.SelfHosted `json:"type" default:"self_hosted"` + paramObj +} + +func (r BetaSelfHostedConfigParams) MarshalJSON() (data []byte, err error) { + type shadow BetaSelfHostedConfigParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaSelfHostedConfigParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + // Unrestricted network access. type BetaUnrestrictedNetwork struct { // Network policy type @@ -594,10 +735,15 @@ type BetaEnvironmentNewParams struct { Name string `json:"name" api:"required"` // Optional description of the environment Description param.Opt[string] `json:"description,omitzero"` - // Request params for `cloud` environment configuration. + // Environment configuration + Config BetaEnvironmentNewParamsConfigUnion `json:"config,omitzero"` + // The visibility scope for this environment. 'organization' makes the environment + // visible to all accounts. 'account' restricts visibility to the owning account + // only. Only applicable for self-hosted environments. If not specified, defaults + // based on organization type. // - // Fields default to null; on update, omitted fields preserve the existing value. - Config BetaCloudConfigParams `json:"config,omitzero"` + // Any of "organization", "account". + Scope BetaEnvironmentNewParamsScope `json:"scope,omitzero"` // User-provided metadata key-value pairs Metadata map[string]string `json:"metadata,omitzero"` // Optional header to specify the beta version(s) you want to use. @@ -613,6 +759,76 @@ func (r *BetaEnvironmentNewParams) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaEnvironmentNewParamsConfigUnion struct { + OfCloud *BetaCloudConfigParams `json:",omitzero,inline"` + OfSelfHosted *BetaSelfHostedConfigParams `json:",omitzero,inline"` + paramUnion +} + +func (u BetaEnvironmentNewParamsConfigUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfCloud, u.OfSelfHosted) +} +func (u *BetaEnvironmentNewParamsConfigUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *BetaEnvironmentNewParamsConfigUnion) asAny() any { + if !param.IsOmitted(u.OfCloud) { + return u.OfCloud + } else if !param.IsOmitted(u.OfSelfHosted) { + return u.OfSelfHosted + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaEnvironmentNewParamsConfigUnion) GetNetworking() *BetaCloudConfigParamsNetworkingUnion { + if vt := u.OfCloud; vt != nil { + return &vt.Networking + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaEnvironmentNewParamsConfigUnion) GetPackages() *BetaPackagesParams { + if vt := u.OfCloud; vt != nil { + return &vt.Packages + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaEnvironmentNewParamsConfigUnion) GetType() *string { + if vt := u.OfCloud; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfSelfHosted; vt != nil { + return (*string)(&vt.Type) + } + return nil +} + +func init() { + apijson.RegisterUnion[BetaEnvironmentNewParamsConfigUnion]( + "type", + apijson.Discriminator[BetaCloudConfigParams]("cloud"), + apijson.Discriminator[BetaSelfHostedConfigParams]("self_hosted"), + ) +} + +// The visibility scope for this environment. 'organization' makes the environment +// visible to all accounts. 'account' restricts visibility to the owning account +// only. Only applicable for self-hosted environments. If not specified, defaults +// based on organization type. +type BetaEnvironmentNewParamsScope string + +const ( + BetaEnvironmentNewParamsScopeOrganization BetaEnvironmentNewParamsScope = "organization" + BetaEnvironmentNewParamsScopeAccount BetaEnvironmentNewParamsScope = "account" +) + type BetaEnvironmentGetParams struct { // Optional header to specify the beta version(s) you want to use. Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` @@ -620,14 +836,19 @@ type BetaEnvironmentGetParams struct { } type BetaEnvironmentUpdateParams struct { - // Updated description of the environment + // Updated description of the environment. Omit to preserve; null clears to null; + // an empty string is stored as an empty string. Description param.Opt[string] `json:"description,omitzero"` // Updated name for the environment Name param.Opt[string] `json:"name,omitzero"` - // Request params for `cloud` environment configuration. + // Updated environment configuration + Config BetaEnvironmentUpdateParamsConfigUnion `json:"config,omitzero"` + // The visibility scope for this environment. 'organization' makes the environment + // visible to all accounts. 'account' restricts visibility to the owning account + // only. // - // Fields default to null; on update, omitted fields preserve the existing value. - Config BetaCloudConfigParams `json:"config,omitzero"` + // Any of "organization", "account". + Scope BetaEnvironmentUpdateParamsScope `json:"scope,omitzero"` // User-provided metadata key-value pairs. Set a value to null or empty string to // delete the key. Metadata map[string]string `json:"metadata,omitzero"` @@ -644,6 +865,75 @@ func (r *BetaEnvironmentUpdateParams) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaEnvironmentUpdateParamsConfigUnion struct { + OfCloud *BetaCloudConfigParams `json:",omitzero,inline"` + OfSelfHosted *BetaSelfHostedConfigParams `json:",omitzero,inline"` + paramUnion +} + +func (u BetaEnvironmentUpdateParamsConfigUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfCloud, u.OfSelfHosted) +} +func (u *BetaEnvironmentUpdateParamsConfigUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *BetaEnvironmentUpdateParamsConfigUnion) asAny() any { + if !param.IsOmitted(u.OfCloud) { + return u.OfCloud + } else if !param.IsOmitted(u.OfSelfHosted) { + return u.OfSelfHosted + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaEnvironmentUpdateParamsConfigUnion) GetNetworking() *BetaCloudConfigParamsNetworkingUnion { + if vt := u.OfCloud; vt != nil { + return &vt.Networking + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaEnvironmentUpdateParamsConfigUnion) GetPackages() *BetaPackagesParams { + if vt := u.OfCloud; vt != nil { + return &vt.Packages + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaEnvironmentUpdateParamsConfigUnion) GetType() *string { + if vt := u.OfCloud; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfSelfHosted; vt != nil { + return (*string)(&vt.Type) + } + return nil +} + +func init() { + apijson.RegisterUnion[BetaEnvironmentUpdateParamsConfigUnion]( + "type", + apijson.Discriminator[BetaCloudConfigParams]("cloud"), + apijson.Discriminator[BetaSelfHostedConfigParams]("self_hosted"), + ) +} + +// The visibility scope for this environment. 'organization' makes the environment +// visible to all accounts. 'account' restricts visibility to the owning account +// only. +type BetaEnvironmentUpdateParamsScope string + +const ( + BetaEnvironmentUpdateParamsScopeOrganization BetaEnvironmentUpdateParamsScope = "organization" + BetaEnvironmentUpdateParamsScopeAccount BetaEnvironmentUpdateParamsScope = "account" +) + type BetaEnvironmentListParams struct { // Opaque cursor from previous response for pagination. Pass the `next_page` value // from the previous response. @@ -661,7 +951,7 @@ type BetaEnvironmentListParams struct { // `url.Values`. func (r BetaEnvironmentListParams) URLQuery() (v url.Values, err error) { return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ - ArrayFormat: apiquery.ArrayQueryFormatComma, + ArrayFormat: apiquery.ArrayQueryFormatBrackets, NestedFormat: apiquery.NestedQueryFormatBrackets, }) } diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/betaenvironmentwork.go b/vendor/github.com/anthropics/anthropic-sdk-go/betaenvironmentwork.go new file mode 100644 index 000000000..21d7e68ec --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/betaenvironmentwork.go @@ -0,0 +1,627 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +package anthropic + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "slices" + + "github.com/anthropics/anthropic-sdk-go/internal/apijson" + "github.com/anthropics/anthropic-sdk-go/internal/apiquery" + shimjson "github.com/anthropics/anthropic-sdk-go/internal/encoding/json" + "github.com/anthropics/anthropic-sdk-go/internal/requestconfig" + "github.com/anthropics/anthropic-sdk-go/option" + "github.com/anthropics/anthropic-sdk-go/packages/pagination" + "github.com/anthropics/anthropic-sdk-go/packages/param" + "github.com/anthropics/anthropic-sdk-go/packages/respjson" + "github.com/anthropics/anthropic-sdk-go/shared/constant" +) + +// BetaEnvironmentWorkService contains methods and other services that help with +// interacting with the anthropic API. +// +// Note, unlike clients, this service does not read variables from the environment +// automatically. You should not instantiate this service directly, and instead use +// the [NewBetaEnvironmentWorkService] method instead. +type BetaEnvironmentWorkService struct { + Options []option.RequestOption +} + +// NewBetaEnvironmentWorkService generates a new service that applies the given +// options to each request. These options are applied after the parent client's +// options (if there is one), and before any request-specific options. +func NewBetaEnvironmentWorkService(opts ...option.RequestOption) (r BetaEnvironmentWorkService) { + r = BetaEnvironmentWorkService{} + r.Options = opts + return +} + +// Note: these endpoints are called automatically by the pre-built environment +// worker provided in the SDKs and CLI, for orchestrating sessions with self-hosted +// sandbox environments. They are included here as a reference; you do not need to +// invoke them directly. +// +// Retrieve detailed information about a specific work item. +func (r *BetaEnvironmentWorkService) Get(ctx context.Context, workID string, params BetaEnvironmentWorkGetParams, opts ...option.RequestOption) (res *BetaSelfHostedWork, err error) { + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "managed-agents-2026-04-01")}, opts...) + if params.EnvironmentID == "" { + err = errors.New("missing required environment_id parameter") + return nil, err + } + if workID == "" { + err = errors.New("missing required work_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/environments/%s/work/%s?beta=true", params.EnvironmentID, workID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...) + return res, err +} + +// Note: these endpoints are called automatically by the pre-built environment +// worker provided in the SDKs and CLI, for orchestrating sessions with self-hosted +// sandbox environments. They are included here as a reference; you do not need to +// invoke them directly. +// +// Update work item metadata with merge semantics. +func (r *BetaEnvironmentWorkService) Update(ctx context.Context, workID string, params BetaEnvironmentWorkUpdateParams, opts ...option.RequestOption) (res *BetaSelfHostedWork, err error) { + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "managed-agents-2026-04-01")}, opts...) + if params.EnvironmentID == "" { + err = errors.New("missing required environment_id parameter") + return nil, err + } + if workID == "" { + err = errors.New("missing required work_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/environments/%s/work/%s?beta=true", params.EnvironmentID, workID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, params, &res, opts...) + return res, err +} + +// Note: these endpoints are called automatically by the pre-built environment +// worker provided in the SDKs and CLI, for orchestrating sessions with self-hosted +// sandbox environments. They are included here as a reference; you do not need to +// invoke them directly. +// +// List work items in an environment. +func (r *BetaEnvironmentWorkService) List(ctx context.Context, environmentID string, params BetaEnvironmentWorkListParams, opts ...option.RequestOption) (res *pagination.PageCursor[BetaSelfHostedWork], err error) { + var raw *http.Response + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "managed-agents-2026-04-01"), option.WithResponseInto(&raw)}, opts...) + if environmentID == "" { + err = errors.New("missing required environment_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/environments/%s/work?beta=true", environmentID) + cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, params, &res, opts...) + if err != nil { + return nil, err + } + err = cfg.Execute() + if err != nil { + return nil, err + } + res.SetPageConfig(cfg, raw) + return res, nil +} + +// Note: these endpoints are called automatically by the pre-built environment +// worker provided in the SDKs and CLI, for orchestrating sessions with self-hosted +// sandbox environments. They are included here as a reference; you do not need to +// invoke them directly. +// +// List work items in an environment. +func (r *BetaEnvironmentWorkService) ListAutoPaging(ctx context.Context, environmentID string, params BetaEnvironmentWorkListParams, opts ...option.RequestOption) *pagination.PageCursorAutoPager[BetaSelfHostedWork] { + return pagination.NewPageCursorAutoPager(r.List(ctx, environmentID, params, opts...)) +} + +// Note: these endpoints are called automatically by the pre-built environment +// worker provided in the SDKs and CLI, for orchestrating sessions with self-hosted +// sandbox environments. They are included here as a reference; you do not need to +// invoke them directly. +// +// Acknowledge receipt of a work item, transitioning it from 'queued' to 'starting' +// and removing it from the queue. +func (r *BetaEnvironmentWorkService) Ack(ctx context.Context, workID string, params BetaEnvironmentWorkAckParams, opts ...option.RequestOption) (res *BetaSelfHostedWork, err error) { + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "managed-agents-2026-04-01")}, opts...) + if params.EnvironmentID == "" { + err = errors.New("missing required environment_id parameter") + return nil, err + } + if workID == "" { + err = errors.New("missing required work_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/environments/%s/work/%s/ack?beta=true", params.EnvironmentID, workID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, nil, &res, opts...) + return res, err +} + +// Note: these endpoints are called automatically by the pre-built environment +// worker provided in the SDKs and CLI, for orchestrating sessions with self-hosted +// sandbox environments. They are included here as a reference; you do not need to +// invoke them directly. +// +// Record a heartbeat for a work item to maintain the lease. +func (r *BetaEnvironmentWorkService) Heartbeat(ctx context.Context, workID string, params BetaEnvironmentWorkHeartbeatParams, opts ...option.RequestOption) (res *BetaSelfHostedWorkHeartbeatResponse, err error) { + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "managed-agents-2026-04-01")}, opts...) + if params.EnvironmentID == "" { + err = errors.New("missing required environment_id parameter") + return nil, err + } + if workID == "" { + err = errors.New("missing required work_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/environments/%s/work/%s/heartbeat?beta=true", params.EnvironmentID, workID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, params, &res, opts...) + return res, err +} + +// Note: these endpoints are called automatically by the pre-built environment +// worker provided in the SDKs and CLI, for orchestrating sessions with self-hosted +// sandbox environments. They are included here as a reference; you do not need to +// invoke them directly. +// +// Long poll for work items in the queue. +func (r *BetaEnvironmentWorkService) Poll(ctx context.Context, environmentID string, params BetaEnvironmentWorkPollParams, opts ...option.RequestOption) (res *BetaSelfHostedWork, err error) { + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + if !param.IsOmitted(params.AnthropicWorkerID) { + opts = append(opts, option.WithHeader("Anthropic-Worker-ID", fmt.Sprintf("%v", params.AnthropicWorkerID.Value))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "managed-agents-2026-04-01")}, opts...) + if environmentID == "" { + err = errors.New("missing required environment_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/environments/%s/work/poll?beta=true", environmentID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, params, &res, opts...) + return res, err +} + +// Get statistics about the work queue for an environment. +func (r *BetaEnvironmentWorkService) Stats(ctx context.Context, environmentID string, query BetaEnvironmentWorkStatsParams, opts ...option.RequestOption) (res *BetaSelfHostedWorkQueueStats, err error) { + for _, v := range query.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "managed-agents-2026-04-01")}, opts...) + if environmentID == "" { + err = errors.New("missing required environment_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/environments/%s/work/stats?beta=true", environmentID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...) + return res, err +} + +// Note: these endpoints are called automatically by the pre-built environment +// worker provided in the SDKs and CLI, for orchestrating sessions with self-hosted +// sandbox environments. They are included here as a reference; you do not need to +// invoke them directly. +// +// Stop a work item, initiating graceful or forced shutdown. +func (r *BetaEnvironmentWorkService) Stop(ctx context.Context, workID string, params BetaEnvironmentWorkStopParams, opts ...option.RequestOption) (res *BetaSelfHostedWork, err error) { + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "managed-agents-2026-04-01")}, opts...) + if params.EnvironmentID == "" { + err = errors.New("missing required environment_id parameter") + return nil, err + } + if workID == "" { + err = errors.New("missing required work_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/environments/%s/work/%s/stop?beta=true", params.EnvironmentID, workID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, params, &res, opts...) + return res, err +} + +// Work data for environment health checks. +// +// This resource type is used for assessing the health of containers where work +// occurs. The data is opaque to users; the runner handles the health check by +// probing connectivity to required services. +type BetaHealthCheckWorkData struct { + // Health check identifier + ID string `json:"id" api:"required"` + // Type of work data + // + // Any of "healthcheck". + Type BetaHealthCheckWorkDataType `json:"type"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaHealthCheckWorkData) RawJSON() string { return r.JSON.raw } +func (r *BetaHealthCheckWorkData) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Type of work data +type BetaHealthCheckWorkDataType string + +const ( + BetaHealthCheckWorkDataTypeHealthcheck BetaHealthCheckWorkDataType = "healthcheck" +) + +// Work resource representing a unit of work in a self-hosted environment. +// +// Work items are queued when sessions are created or when long-dormant sessions +// receive new messages. The Environment Manager polls for work items and executes +// them on customer-hosted infrastructure. +type BetaSelfHostedWork struct { + // Work identifier (e.g., 'work\_...') + ID string `json:"id" api:"required"` + // RFC 3339 timestamp when work was acknowledged by Environment Manager + AcknowledgedAt string `json:"acknowledged_at" api:"required"` + // RFC 3339 timestamp when work was created + CreatedAt string `json:"created_at" api:"required"` + // The actual work to be performed + Data BetaSessionWorkData `json:"data" api:"required"` + // Environment identifier this work belongs to (e.g., `env_...`) + EnvironmentID string `json:"environment_id" api:"required"` + // RFC 3339 timestamp of the most recent heartbeat + LatestHeartbeatAt string `json:"latest_heartbeat_at" api:"required"` + // User-provided metadata key-value pairs associated with this work item + Metadata map[string]string `json:"metadata" api:"required"` + // Credential payload used by the environment worker to execute this work item. May + // be populated when polling for work; null on all other retrieval paths. + Secret string `json:"secret" api:"required"` + // RFC 3339 timestamp when work execution started + StartedAt string `json:"started_at" api:"required"` + // Current state of the work item + // + // Any of "queued", "starting", "active", "stopping", "stopped". + State BetaSelfHostedWorkState `json:"state" api:"required"` + // RFC 3339 timestamp when stop was requested + StopRequestedAt string `json:"stop_requested_at" api:"required"` + // RFC 3339 timestamp when work execution stopped + StoppedAt string `json:"stopped_at" api:"required"` + // The type of object (always 'work') + Type constant.Work `json:"type" default:"work"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + AcknowledgedAt respjson.Field + CreatedAt respjson.Field + Data respjson.Field + EnvironmentID respjson.Field + LatestHeartbeatAt respjson.Field + Metadata respjson.Field + Secret respjson.Field + StartedAt respjson.Field + State respjson.Field + StopRequestedAt respjson.Field + StoppedAt respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaSelfHostedWork) RawJSON() string { return r.JSON.raw } +func (r *BetaSelfHostedWork) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Current state of the work item +type BetaSelfHostedWorkState string + +const ( + BetaSelfHostedWorkStateQueued BetaSelfHostedWorkState = "queued" + BetaSelfHostedWorkStateStarting BetaSelfHostedWorkState = "starting" + BetaSelfHostedWorkStateActive BetaSelfHostedWorkState = "active" + BetaSelfHostedWorkStateStopping BetaSelfHostedWorkState = "stopping" + BetaSelfHostedWorkStateStopped BetaSelfHostedWorkState = "stopped" +) + +// Response after recording a heartbeat for a work item. +type BetaSelfHostedWorkHeartbeatResponse struct { + // RFC 3339 timestamp of the actual heartbeat from DB + LastHeartbeat string `json:"last_heartbeat" api:"required"` + // Whether the heartbeat succeeded in extending the lease + LeaseExtended bool `json:"lease_extended" api:"required"` + // Current state of the work item (active/stopping/stopped) + // + // Any of "queued", "starting", "active", "stopping", "stopped". + State BetaSelfHostedWorkHeartbeatResponseState `json:"state" api:"required"` + // Effective TTL applied to the lease + TTLSeconds int64 `json:"ttl_seconds" api:"required"` + // The type of response + Type constant.WorkHeartbeat `json:"type" default:"work_heartbeat"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + LastHeartbeat respjson.Field + LeaseExtended respjson.Field + State respjson.Field + TTLSeconds respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaSelfHostedWorkHeartbeatResponse) RawJSON() string { return r.JSON.raw } +func (r *BetaSelfHostedWorkHeartbeatResponse) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Current state of the work item (active/stopping/stopped) +type BetaSelfHostedWorkHeartbeatResponseState string + +const ( + BetaSelfHostedWorkHeartbeatResponseStateQueued BetaSelfHostedWorkHeartbeatResponseState = "queued" + BetaSelfHostedWorkHeartbeatResponseStateStarting BetaSelfHostedWorkHeartbeatResponseState = "starting" + BetaSelfHostedWorkHeartbeatResponseStateActive BetaSelfHostedWorkHeartbeatResponseState = "active" + BetaSelfHostedWorkHeartbeatResponseStateStopping BetaSelfHostedWorkHeartbeatResponseState = "stopping" + BetaSelfHostedWorkHeartbeatResponseStateStopped BetaSelfHostedWorkHeartbeatResponseState = "stopped" +) + +// Response when listing work items with cursor-based pagination. +type BetaSelfHostedWorkListResponse struct { + // List of work items + Data []BetaSelfHostedWork `json:"data" api:"required"` + // Opaque cursor for fetching the next page of results + NextPage string `json:"next_page" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Data respjson.Field + NextPage respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaSelfHostedWorkListResponse) RawJSON() string { return r.JSON.raw } +func (r *BetaSelfHostedWorkListResponse) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Statistics about the work queue for an environment. +// +// Uses Redis Stream consumer group metrics for O(1) queries. +type BetaSelfHostedWorkQueueStats struct { + // Number of work items waiting to be picked up (lag from consumer group) + Depth int64 `json:"depth" api:"required"` + // RFC 3339 timestamp of oldest item in the work stream (includes both queued and + // pending items), null if stream empty + OldestQueuedAt string `json:"oldest_queued_at" api:"required"` + // Number of work items being processed (polled but not acknowledged) + Pending int64 `json:"pending" api:"required"` + // The type of object + Type constant.WorkQueueStats `json:"type" default:"work_queue_stats"` + // Number of workers that have polled for work in the last 30 seconds. Requires + // worker_id to be sent with poll requests. + WorkersPolling int64 `json:"workers_polling" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Depth respjson.Field + OldestQueuedAt respjson.Field + Pending respjson.Field + Type respjson.Field + WorkersPolling respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaSelfHostedWorkQueueStats) RawJSON() string { return r.JSON.raw } +func (r *BetaSelfHostedWorkQueueStats) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Request to stop a work item. +type BetaSelfHostedWorkStopRequestParam struct { + // If true, immediately stop work without graceful shutdown + Force param.Opt[bool] `json:"force,omitzero"` + paramObj +} + +func (r BetaSelfHostedWorkStopRequestParam) MarshalJSON() (data []byte, err error) { + type shadow BetaSelfHostedWorkStopRequestParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaSelfHostedWorkStopRequestParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Request to update work item metadata. +// +// The property Metadata is required. +type BetaSelfHostedWorkUpdateRequestParam struct { + // Metadata patch. Set a key to a string to upsert it, or to null to delete it. + // Omit the field to preserve existing metadata. + Metadata map[string]string `json:"metadata,omitzero" api:"required"` + paramObj +} + +func (r BetaSelfHostedWorkUpdateRequestParam) MarshalJSON() (data []byte, err error) { + type shadow BetaSelfHostedWorkUpdateRequestParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaSelfHostedWorkUpdateRequestParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Work data for session work items. +// +// This resource type is used when work represents a session that needs to be +// executed in a self-hosted environment. +type BetaSessionWorkData struct { + // Session identifier (e.g., 'session\_...') + ID string `json:"id" api:"required"` + // Type of work data + Type constant.Session `json:"type" default:"session"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaSessionWorkData) RawJSON() string { return r.JSON.raw } +func (r *BetaSessionWorkData) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaEnvironmentWorkGetParams struct { + EnvironmentID string `path:"environment_id" api:"required" json:"-"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +type BetaEnvironmentWorkUpdateParams struct { + EnvironmentID string `path:"environment_id" api:"required" json:"-"` + // Request to update work item metadata. + BetaSelfHostedWorkUpdateRequest BetaSelfHostedWorkUpdateRequestParam + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +func (r BetaEnvironmentWorkUpdateParams) MarshalJSON() (data []byte, err error) { + return shimjson.Marshal(r.BetaSelfHostedWorkUpdateRequest) +} +func (r *BetaEnvironmentWorkUpdateParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaEnvironmentWorkListParams struct { + // Opaque cursor from previous response for pagination + Page param.Opt[string] `query:"page,omitzero" json:"-"` + // Maximum number of work items to return + Limit param.Opt[int64] `query:"limit,omitzero" json:"-"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +// URLQuery serializes [BetaEnvironmentWorkListParams]'s query parameters as +// `url.Values`. +func (r BetaEnvironmentWorkListParams) URLQuery() (v url.Values, err error) { + return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ + ArrayFormat: apiquery.ArrayQueryFormatBrackets, + NestedFormat: apiquery.NestedQueryFormatBrackets, + }) +} + +type BetaEnvironmentWorkAckParams struct { + EnvironmentID string `path:"environment_id" api:"required" json:"-"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +type BetaEnvironmentWorkHeartbeatParams struct { + EnvironmentID string `path:"environment_id" api:"required" json:"-"` + // Desired TTL in seconds + DesiredTTLSeconds param.Opt[int64] `query:"desired_ttl_seconds,omitzero" json:"-"` + // Expected last_heartbeat for conditional update (optimistic concurrency). Use + // literal 'NO_HEARTBEAT' to claim an unclaimed lease (first heartbeat). For + // subsequent heartbeats, echo the server's previous last_heartbeat value exactly. + // Returns 412 Precondition Failed if the actual value doesn't match. + ExpectedLastHeartbeat param.Opt[string] `query:"expected_last_heartbeat,omitzero" json:"-"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +// URLQuery serializes [BetaEnvironmentWorkHeartbeatParams]'s query parameters as +// `url.Values`. +func (r BetaEnvironmentWorkHeartbeatParams) URLQuery() (v url.Values, err error) { + return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ + ArrayFormat: apiquery.ArrayQueryFormatBrackets, + NestedFormat: apiquery.NestedQueryFormatBrackets, + }) +} + +type BetaEnvironmentWorkPollParams struct { + // How long to wait for work to arrive before returning. Must be 1-999 in + // milliseconds. Defaults to non-blocking (returns immediately if no work is + // available). + BlockMs param.Opt[int64] `query:"block_ms,omitzero" json:"-"` + // Reclaim unacknowledged work items older than this many milliseconds. If omitted, + // uses the default (5000ms). + ReclaimOlderThanMs param.Opt[int64] `query:"reclaim_older_than_ms,omitzero" json:"-"` + // Unique identifier for the specific worker polling, used to track aggregated + // environment-level work metrics in Console + AnthropicWorkerID param.Opt[string] `header:"Anthropic-Worker-ID,omitzero" json:"-"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +// URLQuery serializes [BetaEnvironmentWorkPollParams]'s query parameters as +// `url.Values`. +func (r BetaEnvironmentWorkPollParams) URLQuery() (v url.Values, err error) { + return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ + ArrayFormat: apiquery.ArrayQueryFormatBrackets, + NestedFormat: apiquery.NestedQueryFormatBrackets, + }) +} + +type BetaEnvironmentWorkStatsParams struct { + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +type BetaEnvironmentWorkStopParams struct { + EnvironmentID string `path:"environment_id" api:"required" json:"-"` + // Request to stop a work item. + BetaSelfHostedWorkStopRequest BetaSelfHostedWorkStopRequestParam + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +func (r BetaEnvironmentWorkStopParams) MarshalJSON() (data []byte, err error) { + return shimjson.Marshal(r.BetaSelfHostedWorkStopRequest) +} +func (r *BetaEnvironmentWorkStopParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/betafile.go b/vendor/github.com/anthropics/anthropic-sdk-go/betafile.go index c8ac03227..b96bc5fc6 100644 --- a/vendor/github.com/anthropics/anthropic-sdk-go/betafile.go +++ b/vendor/github.com/anthropics/anthropic-sdk-go/betafile.go @@ -45,7 +45,7 @@ func NewBetaFileService(opts ...option.RequestOption) (r BetaFileService) { } // List Files -func (r *BetaFileService) List(ctx context.Context, params BetaFileListParams, opts ...option.RequestOption) (res *pagination.Page[FileMetadata], err error) { +func (r *BetaFileService) List(ctx context.Context, params BetaFileListParams, opts ...option.RequestOption) (res *pagination.Page[BetaFileMetadata], err error) { var raw *http.Response for _, v := range params.Betas { opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) @@ -66,12 +66,12 @@ func (r *BetaFileService) List(ctx context.Context, params BetaFileListParams, o } // List Files -func (r *BetaFileService) ListAutoPaging(ctx context.Context, params BetaFileListParams, opts ...option.RequestOption) *pagination.PageAutoPager[FileMetadata] { +func (r *BetaFileService) ListAutoPaging(ctx context.Context, params BetaFileListParams, opts ...option.RequestOption) *pagination.PageAutoPager[BetaFileMetadata] { return pagination.NewPageAutoPager(r.List(ctx, params, opts...)) } // Delete File -func (r *BetaFileService) Delete(ctx context.Context, fileID string, body BetaFileDeleteParams, opts ...option.RequestOption) (res *DeletedFile, err error) { +func (r *BetaFileService) Delete(ctx context.Context, fileID string, body BetaFileDeleteParams, opts ...option.RequestOption) (res *BetaDeletedFile, err error) { for _, v := range body.Betas { opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) } @@ -103,7 +103,7 @@ func (r *BetaFileService) Download(ctx context.Context, fileID string, query Bet } // Get File Metadata -func (r *BetaFileService) GetMetadata(ctx context.Context, fileID string, query BetaFileGetMetadataParams, opts ...option.RequestOption) (res *FileMetadata, err error) { +func (r *BetaFileService) GetMetadata(ctx context.Context, fileID string, query BetaFileGetMetadataParams, opts ...option.RequestOption) (res *BetaFileMetadata, err error) { for _, v := range query.Betas { opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) } @@ -119,7 +119,7 @@ func (r *BetaFileService) GetMetadata(ctx context.Context, fileID string, query } // Upload File -func (r *BetaFileService) Upload(ctx context.Context, params BetaFileUploadParams, opts ...option.RequestOption) (res *FileMetadata, err error) { +func (r *BetaFileService) Upload(ctx context.Context, params BetaFileUploadParams, opts ...option.RequestOption) (res *BetaFileMetadata, err error) { for _, v := range params.Betas { opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) } @@ -130,27 +130,7 @@ func (r *BetaFileService) Upload(ctx context.Context, params BetaFileUploadParam return res, err } -type BetaFileScope struct { - // The ID of the scoping resource (e.g., the session ID). - ID string `json:"id" api:"required"` - // The type of scope (e.g., `"session"`). - Type constant.Session `json:"type" default:"session"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ID respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r BetaFileScope) RawJSON() string { return r.JSON.raw } -func (r *BetaFileScope) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type DeletedFile struct { +type BetaDeletedFile struct { // ID of the deleted file. ID string `json:"id" api:"required"` // Deleted object type. @@ -158,7 +138,7 @@ type DeletedFile struct { // For file deletion, this is always `"file_deleted"`. // // Any of "file_deleted". - Type DeletedFileType `json:"type"` + Type BetaDeletedFileType `json:"type"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ID respjson.Field @@ -169,21 +149,21 @@ type DeletedFile struct { } // Returns the unmodified JSON received from the API -func (r DeletedFile) RawJSON() string { return r.JSON.raw } -func (r *DeletedFile) UnmarshalJSON(data []byte) error { +func (r BetaDeletedFile) RawJSON() string { return r.JSON.raw } +func (r *BetaDeletedFile) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } // Deleted object type. // // For file deletion, this is always `"file_deleted"`. -type DeletedFileType string +type BetaDeletedFileType string const ( - DeletedFileTypeFileDeleted DeletedFileType = "file_deleted" + BetaDeletedFileTypeFileDeleted BetaDeletedFileType = "file_deleted" ) -type FileMetadata struct { +type BetaFileMetadata struct { // Unique object identifier. // // The format and length of IDs may change over time. @@ -221,8 +201,28 @@ type FileMetadata struct { } // Returns the unmodified JSON received from the API -func (r FileMetadata) RawJSON() string { return r.JSON.raw } -func (r *FileMetadata) UnmarshalJSON(data []byte) error { +func (r BetaFileMetadata) RawJSON() string { return r.JSON.raw } +func (r *BetaFileMetadata) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaFileScope struct { + // The ID of the scoping resource (e.g., the session ID). + ID string `json:"id" api:"required"` + // The type of scope (e.g., `"session"`). + Type constant.Session `json:"type" default:"session"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaFileScope) RawJSON() string { return r.JSON.raw } +func (r *BetaFileScope) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } @@ -248,7 +248,7 @@ type BetaFileListParams struct { // URLQuery serializes [BetaFileListParams]'s query parameters as `url.Values`. func (r BetaFileListParams) URLQuery() (v url.Values, err error) { return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ - ArrayFormat: apiquery.ArrayQueryFormatComma, + ArrayFormat: apiquery.ArrayQueryFormatBrackets, NestedFormat: apiquery.NestedQueryFormatBrackets, }) } diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/betamemorystore.go b/vendor/github.com/anthropics/anthropic-sdk-go/betamemorystore.go new file mode 100644 index 000000000..fb308693a --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/betamemorystore.go @@ -0,0 +1,328 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +package anthropic + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "slices" + "time" + + "github.com/anthropics/anthropic-sdk-go/internal/apijson" + "github.com/anthropics/anthropic-sdk-go/internal/apiquery" + "github.com/anthropics/anthropic-sdk-go/internal/requestconfig" + "github.com/anthropics/anthropic-sdk-go/option" + "github.com/anthropics/anthropic-sdk-go/packages/pagination" + "github.com/anthropics/anthropic-sdk-go/packages/param" + "github.com/anthropics/anthropic-sdk-go/packages/respjson" +) + +// BetaMemoryStoreService contains methods and other services that help with +// interacting with the anthropic API. +// +// Note, unlike clients, this service does not read variables from the environment +// automatically. You should not instantiate this service directly, and instead use +// the [NewBetaMemoryStoreService] method instead. +type BetaMemoryStoreService struct { + Options []option.RequestOption + Memories BetaMemoryStoreMemoryService + MemoryVersions BetaMemoryStoreMemoryVersionService +} + +// NewBetaMemoryStoreService generates a new service that applies the given options +// to each request. These options are applied after the parent client's options (if +// there is one), and before any request-specific options. +func NewBetaMemoryStoreService(opts ...option.RequestOption) (r BetaMemoryStoreService) { + r = BetaMemoryStoreService{} + r.Options = opts + r.Memories = NewBetaMemoryStoreMemoryService(opts...) + r.MemoryVersions = NewBetaMemoryStoreMemoryVersionService(opts...) + return +} + +// Create a memory store +func (r *BetaMemoryStoreService) New(ctx context.Context, params BetaMemoryStoreNewParams, opts ...option.RequestOption) (res *BetaManagedAgentsMemoryStore, err error) { + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "agent-memory-2026-07-22")}, opts...) + path := "v1/memory_stores?beta=true" + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, params, &res, opts...) + return res, err +} + +// Retrieve a memory store +func (r *BetaMemoryStoreService) Get(ctx context.Context, memoryStoreID string, query BetaMemoryStoreGetParams, opts ...option.RequestOption) (res *BetaManagedAgentsMemoryStore, err error) { + for _, v := range query.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "agent-memory-2026-07-22")}, opts...) + if memoryStoreID == "" { + err = errors.New("missing required memory_store_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/memory_stores/%s?beta=true", memoryStoreID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...) + return res, err +} + +// Update a memory store +func (r *BetaMemoryStoreService) Update(ctx context.Context, memoryStoreID string, params BetaMemoryStoreUpdateParams, opts ...option.RequestOption) (res *BetaManagedAgentsMemoryStore, err error) { + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "agent-memory-2026-07-22")}, opts...) + if memoryStoreID == "" { + err = errors.New("missing required memory_store_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/memory_stores/%s?beta=true", memoryStoreID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, params, &res, opts...) + return res, err +} + +// List memory stores +func (r *BetaMemoryStoreService) List(ctx context.Context, params BetaMemoryStoreListParams, opts ...option.RequestOption) (res *pagination.PageCursor[BetaManagedAgentsMemoryStore], err error) { + var raw *http.Response + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "agent-memory-2026-07-22"), option.WithResponseInto(&raw)}, opts...) + path := "v1/memory_stores?beta=true" + cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, params, &res, opts...) + if err != nil { + return nil, err + } + err = cfg.Execute() + if err != nil { + return nil, err + } + res.SetPageConfig(cfg, raw) + return res, nil +} + +// List memory stores +func (r *BetaMemoryStoreService) ListAutoPaging(ctx context.Context, params BetaMemoryStoreListParams, opts ...option.RequestOption) *pagination.PageCursorAutoPager[BetaManagedAgentsMemoryStore] { + return pagination.NewPageCursorAutoPager(r.List(ctx, params, opts...)) +} + +// Delete a memory store +func (r *BetaMemoryStoreService) Delete(ctx context.Context, memoryStoreID string, body BetaMemoryStoreDeleteParams, opts ...option.RequestOption) (res *BetaManagedAgentsDeletedMemoryStore, err error) { + for _, v := range body.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "agent-memory-2026-07-22")}, opts...) + if memoryStoreID == "" { + err = errors.New("missing required memory_store_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/memory_stores/%s?beta=true", memoryStoreID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodDelete, path, nil, &res, opts...) + return res, err +} + +// Archive a memory store +func (r *BetaMemoryStoreService) Archive(ctx context.Context, memoryStoreID string, body BetaMemoryStoreArchiveParams, opts ...option.RequestOption) (res *BetaManagedAgentsMemoryStore, err error) { + for _, v := range body.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "agent-memory-2026-07-22")}, opts...) + if memoryStoreID == "" { + err = errors.New("missing required memory_store_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/memory_stores/%s/archive?beta=true", memoryStoreID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, nil, &res, opts...) + return res, err +} + +// Confirmation that a `memory_store` was deleted. +type BetaManagedAgentsDeletedMemoryStore struct { + // ID of the deleted memory store (a `memstore_...` identifier). The store and all + // its memories and versions are no longer retrievable. + ID string `json:"id" api:"required"` + // Any of "memory_store_deleted". + Type BetaManagedAgentsDeletedMemoryStoreType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsDeletedMemoryStore) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsDeletedMemoryStore) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsDeletedMemoryStoreType string + +const ( + BetaManagedAgentsDeletedMemoryStoreTypeMemoryStoreDeleted BetaManagedAgentsDeletedMemoryStoreType = "memory_store_deleted" +) + +// A `memory_store`: a named container for agent memories, scoped to a workspace. +// Attach a store to a session via `resources[]` to mount it as a directory the +// agent can read and write. +type BetaManagedAgentsMemoryStore struct { + // Unique identifier for the memory store (a `memstore_...` tagged ID). Use this + // when attaching the store to a session, or in the `{memory_store_id}` path + // parameter of subsequent calls. + ID string `json:"id" api:"required"` + // A timestamp in RFC 3339 format + CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"` + // Human-readable name for the store. 1–255 characters. The store's mount-path slug + // under `/mnt/memory/` is derived from this name. + Name string `json:"name" api:"required"` + // Any of "memory_store". + Type BetaManagedAgentsMemoryStoreType `json:"type" api:"required"` + // A timestamp in RFC 3339 format + UpdatedAt time.Time `json:"updated_at" api:"required" format:"date-time"` + // A timestamp in RFC 3339 format + ArchivedAt time.Time `json:"archived_at" api:"nullable" format:"date-time"` + // Free-text description of what the store contains, up to 1024 characters. + // Included in the agent's system prompt when the store is attached, so word it to + // be useful to the agent. Empty string when unset. + Description string `json:"description"` + // Arbitrary key-value tags for your own bookkeeping (such as the end user a store + // belongs to). Up to 16 pairs; keys 1–64 characters; values up to 512 characters. + // Returned on retrieve/list but not filterable. + Metadata map[string]string `json:"metadata"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + CreatedAt respjson.Field + Name respjson.Field + Type respjson.Field + UpdatedAt respjson.Field + ArchivedAt respjson.Field + Description respjson.Field + Metadata respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsMemoryStore) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsMemoryStore) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsMemoryStoreType string + +const ( + BetaManagedAgentsMemoryStoreTypeMemoryStore BetaManagedAgentsMemoryStoreType = "memory_store" +) + +type BetaMemoryStoreNewParams struct { + // Human-readable name for the store. Required; 1–255 characters; no control + // characters. The mount-path slug under `/mnt/memory/` is derived from this name + // (lowercased, non-alphanumeric runs collapsed to a hyphen). Names need not be + // unique within a workspace. + Name string `json:"name" api:"required"` + // Free-text description of what the store contains, up to 1024 characters. + // Included in the agent's system prompt when the store is attached, so word it to + // be useful to the agent. + Description param.Opt[string] `json:"description,omitzero"` + // Arbitrary key-value tags for your own bookkeeping (such as the end user a store + // belongs to). Up to 16 pairs; keys 1–64 characters; values up to 512 characters. + // Not visible to the agent. + Metadata map[string]string `json:"metadata,omitzero"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +func (r BetaMemoryStoreNewParams) MarshalJSON() (data []byte, err error) { + type shadow BetaMemoryStoreNewParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaMemoryStoreNewParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaMemoryStoreGetParams struct { + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +type BetaMemoryStoreUpdateParams struct { + // New description for the store, up to 1024 characters. Pass an empty string to + // clear it. + Description param.Opt[string] `json:"description,omitzero"` + // New human-readable name for the store. 1–255 characters; no control characters. + // Renaming changes the slug used for the store's `mount_path` in sessions created + // after the update. + Name param.Opt[string] `json:"name,omitzero"` + // Metadata patch. Set a key to a string to upsert it, or to null to delete it. + // Omit the field to preserve. The stored bag is limited to 16 keys (up to 64 chars + // each) with values up to 512 chars. + Metadata map[string]string `json:"metadata,omitzero"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +func (r BetaMemoryStoreUpdateParams) MarshalJSON() (data []byte, err error) { + type shadow BetaMemoryStoreUpdateParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaMemoryStoreUpdateParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaMemoryStoreListParams struct { + // Return only stores whose `created_at` is at or after this time (inclusive). Sent + // on the wire as `created_at[gte]`. + CreatedAtGte param.Opt[time.Time] `query:"created_at[gte],omitzero" format:"date-time" json:"-"` + // Return only stores whose `created_at` is at or before this time (inclusive). + // Sent on the wire as `created_at[lte]`. + CreatedAtLte param.Opt[time.Time] `query:"created_at[lte],omitzero" format:"date-time" json:"-"` + // When `true`, archived stores are included in the results. Defaults to `false` + // (archived stores are excluded). + IncludeArchived param.Opt[bool] `query:"include_archived,omitzero" json:"-"` + // Maximum number of stores to return per page. Must be between 1 and 100. Defaults + // to 20 when omitted. + Limit param.Opt[int64] `query:"limit,omitzero" json:"-"` + // Opaque pagination cursor (a `page_...` value). Pass the `next_page` value from a + // previous response to fetch the next page; omit for the first page. + Page param.Opt[string] `query:"page,omitzero" json:"-"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +// URLQuery serializes [BetaMemoryStoreListParams]'s query parameters as +// `url.Values`. +func (r BetaMemoryStoreListParams) URLQuery() (v url.Values, err error) { + return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ + ArrayFormat: apiquery.ArrayQueryFormatBrackets, + NestedFormat: apiquery.NestedQueryFormatBrackets, + }) +} + +type BetaMemoryStoreDeleteParams struct { + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +type BetaMemoryStoreArchiveParams struct { + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/betamemorystorememory.go b/vendor/github.com/anthropics/anthropic-sdk-go/betamemorystorememory.go new file mode 100644 index 000000000..1a865496c --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/betamemorystorememory.go @@ -0,0 +1,566 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +package anthropic + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/url" + "slices" + "time" + + "github.com/anthropics/anthropic-sdk-go/internal/apijson" + "github.com/anthropics/anthropic-sdk-go/internal/apiquery" + "github.com/anthropics/anthropic-sdk-go/internal/requestconfig" + "github.com/anthropics/anthropic-sdk-go/option" + "github.com/anthropics/anthropic-sdk-go/packages/pagination" + "github.com/anthropics/anthropic-sdk-go/packages/param" + "github.com/anthropics/anthropic-sdk-go/packages/respjson" +) + +// BetaMemoryStoreMemoryService contains methods and other services that help with +// interacting with the anthropic API. +// +// Note, unlike clients, this service does not read variables from the environment +// automatically. You should not instantiate this service directly, and instead use +// the [NewBetaMemoryStoreMemoryService] method instead. +type BetaMemoryStoreMemoryService struct { + Options []option.RequestOption +} + +// NewBetaMemoryStoreMemoryService generates a new service that applies the given +// options to each request. These options are applied after the parent client's +// options (if there is one), and before any request-specific options. +func NewBetaMemoryStoreMemoryService(opts ...option.RequestOption) (r BetaMemoryStoreMemoryService) { + r = BetaMemoryStoreMemoryService{} + r.Options = opts + return +} + +// Create a memory +func (r *BetaMemoryStoreMemoryService) New(ctx context.Context, memoryStoreID string, params BetaMemoryStoreMemoryNewParams, opts ...option.RequestOption) (res *BetaManagedAgentsMemory, err error) { + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "agent-memory-2026-07-22")}, opts...) + if memoryStoreID == "" { + err = errors.New("missing required memory_store_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/memory_stores/%s/memories?beta=true", memoryStoreID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, params, &res, opts...) + return res, err +} + +// Retrieve a memory +func (r *BetaMemoryStoreMemoryService) Get(ctx context.Context, memoryID string, params BetaMemoryStoreMemoryGetParams, opts ...option.RequestOption) (res *BetaManagedAgentsMemory, err error) { + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "agent-memory-2026-07-22")}, opts...) + if params.MemoryStoreID == "" { + err = errors.New("missing required memory_store_id parameter") + return nil, err + } + if memoryID == "" { + err = errors.New("missing required memory_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/memory_stores/%s/memories/%s?beta=true", params.MemoryStoreID, memoryID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, params, &res, opts...) + return res, err +} + +// Update a memory +func (r *BetaMemoryStoreMemoryService) Update(ctx context.Context, memoryID string, params BetaMemoryStoreMemoryUpdateParams, opts ...option.RequestOption) (res *BetaManagedAgentsMemory, err error) { + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "agent-memory-2026-07-22")}, opts...) + if params.MemoryStoreID == "" { + err = errors.New("missing required memory_store_id parameter") + return nil, err + } + if memoryID == "" { + err = errors.New("missing required memory_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/memory_stores/%s/memories/%s?beta=true", params.MemoryStoreID, memoryID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, params, &res, opts...) + return res, err +} + +// List memories +func (r *BetaMemoryStoreMemoryService) List(ctx context.Context, memoryStoreID string, params BetaMemoryStoreMemoryListParams, opts ...option.RequestOption) (res *pagination.PageCursor[BetaManagedAgentsMemoryListItemUnion], err error) { + var raw *http.Response + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "agent-memory-2026-07-22"), option.WithResponseInto(&raw)}, opts...) + if memoryStoreID == "" { + err = errors.New("missing required memory_store_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/memory_stores/%s/memories?beta=true", memoryStoreID) + cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, params, &res, opts...) + if err != nil { + return nil, err + } + err = cfg.Execute() + if err != nil { + return nil, err + } + res.SetPageConfig(cfg, raw) + return res, nil +} + +// List memories +func (r *BetaMemoryStoreMemoryService) ListAutoPaging(ctx context.Context, memoryStoreID string, params BetaMemoryStoreMemoryListParams, opts ...option.RequestOption) *pagination.PageCursorAutoPager[BetaManagedAgentsMemoryListItemUnion] { + return pagination.NewPageCursorAutoPager(r.List(ctx, memoryStoreID, params, opts...)) +} + +// Delete a memory +func (r *BetaMemoryStoreMemoryService) Delete(ctx context.Context, memoryID string, params BetaMemoryStoreMemoryDeleteParams, opts ...option.RequestOption) (res *BetaManagedAgentsDeletedMemory, err error) { + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "agent-memory-2026-07-22")}, opts...) + if params.MemoryStoreID == "" { + err = errors.New("missing required memory_store_id parameter") + return nil, err + } + if memoryID == "" { + err = errors.New("missing required memory_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/memory_stores/%s/memories/%s?beta=true", params.MemoryStoreID, memoryID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodDelete, path, params, &res, opts...) + return res, err +} + +// Tombstone returned by +// [Delete a memory](/en/api/beta/memory_stores/memories/delete). Deleting a memory +// does not erase its version history: its versions remain listable via +// [List memory versions](/en/api/beta/memory_stores/memory_versions/list) while +// they are retained (each version is kept for at least the version retention +// period after it was written, unless the store itself is deleted). +type BetaManagedAgentsDeletedMemory struct { + // ID of the deleted memory (a `mem_...` value). + ID string `json:"id" api:"required"` + // Any of "memory_deleted". + Type BetaManagedAgentsDeletedMemoryType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsDeletedMemory) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsDeletedMemory) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsDeletedMemoryType string + +const ( + BetaManagedAgentsDeletedMemoryTypeMemoryDeleted BetaManagedAgentsDeletedMemoryType = "memory_deleted" +) + +// A `memory` object: a single text document at a hierarchical path inside a memory +// store. The `content` field is populated when `view=full` and `null` when +// `view=basic`; the `content_size_bytes` and `content_sha256` fields are always +// populated so sync clients can diff without fetching content. Memories are +// addressed by their `mem_...` ID; the path is the create key and can be changed +// via update. +type BetaManagedAgentsMemory struct { + // Unique identifier for this memory (a `mem_...` value). Stable across renames; + // use this ID, not the path, to read, update, or delete the memory. + ID string `json:"id" api:"required"` + // Lowercase hex SHA-256 digest of the UTF-8 `content` bytes (64 characters). The + // server applies no normalization, so clients can compute the same hash locally + // for staleness checks and as the value for a `content_sha256` precondition on + // update. Always populated, regardless of `view`. + ContentSha256 string `json:"content_sha256" api:"required"` + // Size of `content` in bytes (the UTF-8 plaintext length). Always populated, + // regardless of `view`. + ContentSizeBytes int64 `json:"content_size_bytes" api:"required"` + // A timestamp in RFC 3339 format + CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"` + // ID of the memory store this memory belongs to (a `memstore_...` value). + MemoryStoreID string `json:"memory_store_id" api:"required"` + // ID of the `memory_version` representing this memory's current content (a + // `memver_...` value). This is the authoritative head pointer; `memory_version` + // objects do not carry an `is_latest` flag, so compare against this field instead. + // Enumerate the history via + // [List memory versions](/en/api/beta/memory_stores/memory_versions/list). + MemoryVersionID string `json:"memory_version_id" api:"required"` + // Hierarchical path of the memory within the store, e.g. `/projects/foo/notes.md`. + // Always starts with `/`. Paths are case-sensitive and unique within a store. + // Maximum 1,024 bytes. + Path string `json:"path" api:"required"` + // Any of "memory". + Type BetaManagedAgentsMemoryType `json:"type" api:"required"` + // A timestamp in RFC 3339 format + UpdatedAt time.Time `json:"updated_at" api:"required" format:"date-time"` + // The memory's UTF-8 text content. Populated when `view=full`; `null` when + // `view=basic`. Maximum 100 kB (102,400 bytes). + Content string `json:"content" api:"nullable"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + ContentSha256 respjson.Field + ContentSizeBytes respjson.Field + CreatedAt respjson.Field + MemoryStoreID respjson.Field + MemoryVersionID respjson.Field + Path respjson.Field + Type respjson.Field + UpdatedAt respjson.Field + Content respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsMemory) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsMemory) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsMemoryType string + +const ( + BetaManagedAgentsMemoryTypeMemory BetaManagedAgentsMemoryType = "memory" +) + +// BetaManagedAgentsMemoryListItemUnion contains all possible properties and values +// from [BetaManagedAgentsMemory], [BetaManagedAgentsMemoryPrefix]. +// +// Use the [BetaManagedAgentsMemoryListItemUnion.AsAny] method to switch on the +// variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaManagedAgentsMemoryListItemUnion struct { + // This field is from variant [BetaManagedAgentsMemory]. + ID string `json:"id"` + // This field is from variant [BetaManagedAgentsMemory]. + ContentSha256 string `json:"content_sha256"` + // This field is from variant [BetaManagedAgentsMemory]. + ContentSizeBytes int64 `json:"content_size_bytes"` + // This field is from variant [BetaManagedAgentsMemory]. + CreatedAt time.Time `json:"created_at"` + // This field is from variant [BetaManagedAgentsMemory]. + MemoryStoreID string `json:"memory_store_id"` + // This field is from variant [BetaManagedAgentsMemory]. + MemoryVersionID string `json:"memory_version_id"` + Path string `json:"path"` + // Any of "memory", "memory_prefix". + Type string `json:"type"` + // This field is from variant [BetaManagedAgentsMemory]. + UpdatedAt time.Time `json:"updated_at"` + // This field is from variant [BetaManagedAgentsMemory]. + Content string `json:"content"` + JSON struct { + ID respjson.Field + ContentSha256 respjson.Field + ContentSizeBytes respjson.Field + CreatedAt respjson.Field + MemoryStoreID respjson.Field + MemoryVersionID respjson.Field + Path respjson.Field + Type respjson.Field + UpdatedAt respjson.Field + Content respjson.Field + raw string + } `json:"-"` +} + +// anyBetaManagedAgentsMemoryListItem is implemented by each variant of +// [BetaManagedAgentsMemoryListItemUnion] to add type safety for the return type of +// [BetaManagedAgentsMemoryListItemUnion.AsAny] +type anyBetaManagedAgentsMemoryListItem interface { + implBetaManagedAgentsMemoryListItemUnion() +} + +func (BetaManagedAgentsMemory) implBetaManagedAgentsMemoryListItemUnion() {} +func (BetaManagedAgentsMemoryPrefix) implBetaManagedAgentsMemoryListItemUnion() {} + +// Use the following switch statement to find the correct variant +// +// switch variant := BetaManagedAgentsMemoryListItemUnion.AsAny().(type) { +// case anthropic.BetaManagedAgentsMemory: +// case anthropic.BetaManagedAgentsMemoryPrefix: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaManagedAgentsMemoryListItemUnion) AsAny() anyBetaManagedAgentsMemoryListItem { + switch u.Type { + case "memory": + return u.AsMemory() + case "memory_prefix": + return u.AsMemoryPrefix() + } + return nil +} + +func (u BetaManagedAgentsMemoryListItemUnion) AsMemory() (v BetaManagedAgentsMemory) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsMemoryListItemUnion) AsMemoryPrefix() (v BetaManagedAgentsMemoryPrefix) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u BetaManagedAgentsMemoryListItemUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaManagedAgentsMemoryListItemUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// A rolled-up directory marker returned by +// [List memories](/en/api/beta/memory_stores/memories/list) when `depth` is set. +// Indicates that one or more memories exist deeper than the requested depth under +// this prefix. This is a list-time rollup, not a stored resource; it has no ID and +// no lifecycle. Each prefix counts toward the page `limit` and interleaves with +// `memory` items in path order. +type BetaManagedAgentsMemoryPrefix struct { + // The rolled-up path prefix, including a trailing `/` (e.g. `/projects/foo/`). + // Pass this value as `path_prefix` on a subsequent list call to drill into the + // directory. + Path string `json:"path" api:"required"` + // Any of "memory_prefix". + Type BetaManagedAgentsMemoryPrefixType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Path respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsMemoryPrefix) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsMemoryPrefix) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsMemoryPrefixType string + +const ( + BetaManagedAgentsMemoryPrefixTypeMemoryPrefix BetaManagedAgentsMemoryPrefixType = "memory_prefix" +) + +// Selects which projection of a `memory` or `memory_version` the server returns. +// `basic` returns the object with `content` set to `null`; `full` populates +// `content`. When omitted, the default is endpoint-specific: retrieve operations +// default to `full`; list, create, and update operations default to `basic`. +// Listing with `view=full` caps `limit` at 20. +type BetaManagedAgentsMemoryView string + +const ( + BetaManagedAgentsMemoryViewBasic BetaManagedAgentsMemoryView = "basic" + BetaManagedAgentsMemoryViewFull BetaManagedAgentsMemoryView = "full" +) + +// Optimistic-concurrency precondition: the update applies only if the memory's +// stored `content_sha256` equals the supplied value. On mismatch, the request +// returns `memory_precondition_failed_error` (HTTP 409); re-read the memory and +// retry against the fresh state. If the precondition fails but the stored state +// already exactly matches the requested `content` and `path`, the server returns +// 200 instead of 409. +// +// The property Type is required. +type BetaManagedAgentsPreconditionParam struct { + // Any of "content_sha256". + Type BetaManagedAgentsPreconditionType `json:"type,omitzero" api:"required"` + // Expected `content_sha256` of the stored memory (64 lowercase hexadecimal + // characters). Typically the `content_sha256` returned by a prior read or list + // call. Because the server applies no content normalization, clients can also + // compute this locally as the SHA-256 of the UTF-8 content bytes. + ContentSha256 param.Opt[string] `json:"content_sha256,omitzero"` + paramObj +} + +func (r BetaManagedAgentsPreconditionParam) MarshalJSON() (data []byte, err error) { + type shadow BetaManagedAgentsPreconditionParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaManagedAgentsPreconditionParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsPreconditionType string + +const ( + BetaManagedAgentsPreconditionTypeContentSha256 BetaManagedAgentsPreconditionType = "content_sha256" +) + +type BetaMemoryStoreMemoryNewParams struct { + // UTF-8 text content for the new memory. Maximum 100 kB (102,400 bytes). Required; + // pass `""` explicitly to create an empty memory. + Content param.Opt[string] `json:"content,omitzero" api:"required"` + // Hierarchical path for the new memory, e.g. `/projects/foo/notes.md`. Must start + // with `/`, contain at least one non-empty segment, and be at most 1,024 bytes. + // Must not contain empty segments, `.` or `..` segments, control or format + // characters, and must be NFC-normalized. Paths are case-sensitive. + Path string `json:"path" api:"required"` + // Query parameter for view + // + // Any of "basic", "full". + View BetaManagedAgentsMemoryView `query:"view,omitzero" json:"-"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +func (r BetaMemoryStoreMemoryNewParams) MarshalJSON() (data []byte, err error) { + type shadow BetaMemoryStoreMemoryNewParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaMemoryStoreMemoryNewParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// URLQuery serializes [BetaMemoryStoreMemoryNewParams]'s query parameters as +// `url.Values`. +func (r BetaMemoryStoreMemoryNewParams) URLQuery() (v url.Values, err error) { + return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ + ArrayFormat: apiquery.ArrayQueryFormatBrackets, + NestedFormat: apiquery.NestedQueryFormatBrackets, + }) +} + +type BetaMemoryStoreMemoryGetParams struct { + MemoryStoreID string `path:"memory_store_id" api:"required" json:"-"` + // Query parameter for view + // + // Any of "basic", "full". + View BetaManagedAgentsMemoryView `query:"view,omitzero" json:"-"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +// URLQuery serializes [BetaMemoryStoreMemoryGetParams]'s query parameters as +// `url.Values`. +func (r BetaMemoryStoreMemoryGetParams) URLQuery() (v url.Values, err error) { + return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ + ArrayFormat: apiquery.ArrayQueryFormatBrackets, + NestedFormat: apiquery.NestedQueryFormatBrackets, + }) +} + +type BetaMemoryStoreMemoryUpdateParams struct { + MemoryStoreID string `path:"memory_store_id" api:"required" json:"-"` + // New UTF-8 text content for the memory. Maximum 100 kB (102,400 bytes). Omit to + // leave the content unchanged (e.g., for a rename-only update). + Content param.Opt[string] `json:"content,omitzero"` + // New path for the memory (a rename). Must start with `/`, contain at least one + // non-empty segment, and be at most 1,024 bytes. Must not contain empty segments, + // `.` or `..` segments, control or format characters, and must be NFC-normalized. + // Paths are case-sensitive. The memory's `id` is preserved across renames. Omit to + // leave the path unchanged. + Path param.Opt[string] `json:"path,omitzero"` + // Query parameter for view + // + // Any of "basic", "full". + View BetaManagedAgentsMemoryView `query:"view,omitzero" json:"-"` + // Optimistic-concurrency precondition: the update applies only if the memory's + // stored `content_sha256` equals the supplied value. On mismatch, the request + // returns `memory_precondition_failed_error` (HTTP 409); re-read the memory and + // retry against the fresh state. If the precondition fails but the stored state + // already exactly matches the requested `content` and `path`, the server returns + // 200 instead of 409. + Precondition BetaManagedAgentsPreconditionParam `json:"precondition,omitzero"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +func (r BetaMemoryStoreMemoryUpdateParams) MarshalJSON() (data []byte, err error) { + type shadow BetaMemoryStoreMemoryUpdateParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaMemoryStoreMemoryUpdateParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// URLQuery serializes [BetaMemoryStoreMemoryUpdateParams]'s query parameters as +// `url.Values`. +func (r BetaMemoryStoreMemoryUpdateParams) URLQuery() (v url.Values, err error) { + return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ + ArrayFormat: apiquery.ArrayQueryFormatBrackets, + NestedFormat: apiquery.NestedQueryFormatBrackets, + }) +} + +type BetaMemoryStoreMemoryListParams struct { + // `0` (or omitted) returns all descendants below `path_prefix` (recursive). `1` + // returns immediate children only; deeper entries roll up as `memory_prefix` + // items. `depth=1` behaves like `ls`; omitting `depth` behaves like `find`. + Depth param.Opt[int64] `query:"depth,omitzero" json:"-"` + // Maximum number of items to return per page. Must be between 1 and 100. Defaults + // to 20 when omitted. Capped at 20 when `view=full`. Both `memory` and + // `memory_prefix` items count toward the limit. + Limit param.Opt[int64] `query:"limit,omitzero" json:"-"` + // Opaque pagination cursor (a `page_...` value). Pass the `next_page` value from a + // previous response to fetch the next page; omit for the first page. + Page param.Opt[string] `query:"page,omitzero" json:"-"` + // Optional path prefix filter. Must end with `/` (segment-aligned), e.g., + // `/notes/`. This value appears in request URLs. Do not include secrets or + // personally identifiable information. + PathPrefix param.Opt[string] `query:"path_prefix,omitzero" json:"-"` + // Which projection of each `memory` to return. Defaults to `basic` (content + // omitted). `full` populates `content` on each item and caps `limit` at 20; use + // this as the bulk-read path for export and sync. + // + // Any of "basic", "full". + View BetaManagedAgentsMemoryView `query:"view,omitzero" json:"-"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +// URLQuery serializes [BetaMemoryStoreMemoryListParams]'s query parameters as +// `url.Values`. +func (r BetaMemoryStoreMemoryListParams) URLQuery() (v url.Values, err error) { + return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ + ArrayFormat: apiquery.ArrayQueryFormatBrackets, + NestedFormat: apiquery.NestedQueryFormatBrackets, + }) +} + +type BetaMemoryStoreMemoryDeleteParams struct { + MemoryStoreID string `path:"memory_store_id" api:"required" json:"-"` + // Query parameter for expected_content_sha256 + ExpectedContentSha256 param.Opt[string] `query:"expected_content_sha256,omitzero" json:"-"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +// URLQuery serializes [BetaMemoryStoreMemoryDeleteParams]'s query parameters as +// `url.Values`. +func (r BetaMemoryStoreMemoryDeleteParams) URLQuery() (v url.Values, err error) { + return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ + ArrayFormat: apiquery.ArrayQueryFormatBrackets, + NestedFormat: apiquery.NestedQueryFormatBrackets, + }) +} diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/betamemorystorememoryversion.go b/vendor/github.com/anthropics/anthropic-sdk-go/betamemorystorememoryversion.go new file mode 100644 index 000000000..dd4034588 --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/betamemorystorememoryversion.go @@ -0,0 +1,473 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +package anthropic + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/url" + "slices" + "time" + + "github.com/anthropics/anthropic-sdk-go/internal/apijson" + "github.com/anthropics/anthropic-sdk-go/internal/apiquery" + "github.com/anthropics/anthropic-sdk-go/internal/requestconfig" + "github.com/anthropics/anthropic-sdk-go/option" + "github.com/anthropics/anthropic-sdk-go/packages/pagination" + "github.com/anthropics/anthropic-sdk-go/packages/param" + "github.com/anthropics/anthropic-sdk-go/packages/respjson" + "github.com/anthropics/anthropic-sdk-go/shared/constant" +) + +// BetaMemoryStoreMemoryVersionService contains methods and other services that +// help with interacting with the anthropic API. +// +// Note, unlike clients, this service does not read variables from the environment +// automatically. You should not instantiate this service directly, and instead use +// the [NewBetaMemoryStoreMemoryVersionService] method instead. +type BetaMemoryStoreMemoryVersionService struct { + Options []option.RequestOption +} + +// NewBetaMemoryStoreMemoryVersionService generates a new service that applies the +// given options to each request. These options are applied after the parent +// client's options (if there is one), and before any request-specific options. +func NewBetaMemoryStoreMemoryVersionService(opts ...option.RequestOption) (r BetaMemoryStoreMemoryVersionService) { + r = BetaMemoryStoreMemoryVersionService{} + r.Options = opts + return +} + +// Retrieve a memory version +func (r *BetaMemoryStoreMemoryVersionService) Get(ctx context.Context, memoryVersionID string, params BetaMemoryStoreMemoryVersionGetParams, opts ...option.RequestOption) (res *BetaManagedAgentsMemoryVersion, err error) { + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "agent-memory-2026-07-22")}, opts...) + if params.MemoryStoreID == "" { + err = errors.New("missing required memory_store_id parameter") + return nil, err + } + if memoryVersionID == "" { + err = errors.New("missing required memory_version_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/memory_stores/%s/memory_versions/%s?beta=true", params.MemoryStoreID, memoryVersionID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, params, &res, opts...) + return res, err +} + +// List memory versions +func (r *BetaMemoryStoreMemoryVersionService) List(ctx context.Context, memoryStoreID string, params BetaMemoryStoreMemoryVersionListParams, opts ...option.RequestOption) (res *pagination.PageCursor[BetaManagedAgentsMemoryVersion], err error) { + var raw *http.Response + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "agent-memory-2026-07-22"), option.WithResponseInto(&raw)}, opts...) + if memoryStoreID == "" { + err = errors.New("missing required memory_store_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/memory_stores/%s/memory_versions?beta=true", memoryStoreID) + cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, params, &res, opts...) + if err != nil { + return nil, err + } + err = cfg.Execute() + if err != nil { + return nil, err + } + res.SetPageConfig(cfg, raw) + return res, nil +} + +// List memory versions +func (r *BetaMemoryStoreMemoryVersionService) ListAutoPaging(ctx context.Context, memoryStoreID string, params BetaMemoryStoreMemoryVersionListParams, opts ...option.RequestOption) *pagination.PageCursorAutoPager[BetaManagedAgentsMemoryVersion] { + return pagination.NewPageCursorAutoPager(r.List(ctx, memoryStoreID, params, opts...)) +} + +// Redact a memory version +func (r *BetaMemoryStoreMemoryVersionService) Redact(ctx context.Context, memoryVersionID string, params BetaMemoryStoreMemoryVersionRedactParams, opts ...option.RequestOption) (res *BetaManagedAgentsMemoryVersion, err error) { + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "agent-memory-2026-07-22")}, opts...) + if params.MemoryStoreID == "" { + err = errors.New("missing required memory_store_id parameter") + return nil, err + } + if memoryVersionID == "" { + err = errors.New("missing required memory_version_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/memory_stores/%s/memory_versions/%s/redact?beta=true", params.MemoryStoreID, memoryVersionID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, nil, &res, opts...) + return res, err +} + +// BetaManagedAgentsActorUnion contains all possible properties and values from +// [BetaManagedAgentsSessionActor], [BetaManagedAgentsAPIActor], +// [BetaManagedAgentsUserActor], [BetaManagedAgentsServiceAccountActor]. +// +// Use the [BetaManagedAgentsActorUnion.AsAny] method to switch on the variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaManagedAgentsActorUnion struct { + // This field is from variant [BetaManagedAgentsSessionActor]. + SessionID string `json:"session_id"` + // Any of "session_actor", "api_actor", "user_actor", "service_account_actor". + Type string `json:"type"` + // This field is from variant [BetaManagedAgentsAPIActor]. + APIKeyID string `json:"api_key_id"` + // This field is from variant [BetaManagedAgentsUserActor]. + UserID string `json:"user_id"` + // This field is from variant [BetaManagedAgentsServiceAccountActor]. + ServiceAccountID string `json:"service_account_id"` + JSON struct { + SessionID respjson.Field + Type respjson.Field + APIKeyID respjson.Field + UserID respjson.Field + ServiceAccountID respjson.Field + raw string + } `json:"-"` +} + +// anyBetaManagedAgentsActor is implemented by each variant of +// [BetaManagedAgentsActorUnion] to add type safety for the return type of +// [BetaManagedAgentsActorUnion.AsAny] +type anyBetaManagedAgentsActor interface { + implBetaManagedAgentsActorUnion() +} + +func (BetaManagedAgentsSessionActor) implBetaManagedAgentsActorUnion() {} +func (BetaManagedAgentsAPIActor) implBetaManagedAgentsActorUnion() {} +func (BetaManagedAgentsUserActor) implBetaManagedAgentsActorUnion() {} +func (BetaManagedAgentsServiceAccountActor) implBetaManagedAgentsActorUnion() {} + +// Use the following switch statement to find the correct variant +// +// switch variant := BetaManagedAgentsActorUnion.AsAny().(type) { +// case anthropic.BetaManagedAgentsSessionActor: +// case anthropic.BetaManagedAgentsAPIActor: +// case anthropic.BetaManagedAgentsUserActor: +// case anthropic.BetaManagedAgentsServiceAccountActor: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaManagedAgentsActorUnion) AsAny() anyBetaManagedAgentsActor { + switch u.Type { + case "session_actor": + return u.AsSessionActor() + case "api_actor": + return u.AsAPIActor() + case "user_actor": + return u.AsUserActor() + case "service_account_actor": + return u.AsServiceAccountActor() + } + return nil +} + +func (u BetaManagedAgentsActorUnion) AsSessionActor() (v BetaManagedAgentsSessionActor) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsActorUnion) AsAPIActor() (v BetaManagedAgentsAPIActor) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsActorUnion) AsUserActor() (v BetaManagedAgentsUserActor) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsActorUnion) AsServiceAccountActor() (v BetaManagedAgentsServiceAccountActor) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u BetaManagedAgentsActorUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaManagedAgentsActorUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Attribution for a write made directly via the public API (outside of any +// session). +type BetaManagedAgentsAPIActor struct { + // ID of the API key that performed the write. This identifies the key, not the + // secret. + APIKeyID string `json:"api_key_id" api:"required"` + // Any of "api_actor". + Type BetaManagedAgentsAPIActorType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + APIKeyID respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsAPIActor) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsAPIActor) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsAPIActorType string + +const ( + BetaManagedAgentsAPIActorTypeAPIActor BetaManagedAgentsAPIActorType = "api_actor" +) + +// A `memory_version` object: one immutable, attributed row in a memory's +// append-only history. Every non-no-op mutation to a memory produces a new +// version. Versions belong to the store (not the individual memory) and are not +// deleted with the memory; each version is retained for at least the version +// retention period after it was written, unless the store itself is deleted. +// Retrieving a redacted version returns 200 with `content`, `path`, +// `content_size_bytes`, and `content_sha256` set to `null`; branch on +// `redacted_at`, not HTTP status. +type BetaManagedAgentsMemoryVersion struct { + // Unique identifier for this version (a `memver_...` value). + ID string `json:"id" api:"required"` + // A timestamp in RFC 3339 format + CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"` + // ID of the memory this version snapshots (a `mem_...` value). Remains valid after + // the memory is deleted; pass it as `memory_id` to + // [List memory versions](/en/api/beta/memory_stores/memory_versions/list) to + // retrieve the memory's retained versions, including the `deleted` row while the + // lineage is retained. + MemoryID string `json:"memory_id" api:"required"` + // ID of the memory store this version belongs to (a `memstore_...` value). + MemoryStoreID string `json:"memory_store_id" api:"required"` + // The kind of mutation a `memory_version` records. Every non-no-op mutation to a + // memory appends exactly one version row with one of these values. + // + // Any of "created", "modified", "deleted". + Operation BetaManagedAgentsMemoryVersionOperation `json:"operation" api:"required"` + // Any of "memory_version". + Type BetaManagedAgentsMemoryVersionType `json:"type" api:"required"` + // The memory's UTF-8 text content as of this version. `null` when `view=basic`, + // when `operation` is `deleted`, or when `redacted_at` is set. + Content string `json:"content" api:"nullable"` + // Lowercase hex SHA-256 digest of `content` as of this version (64 characters). + // `null` when `redacted_at` is set or `operation` is `deleted`. Populated + // regardless of `view` otherwise. + ContentSha256 string `json:"content_sha256" api:"nullable"` + // Size of `content` in bytes as of this version. `null` when `redacted_at` is set + // or `operation` is `deleted`. Populated regardless of `view` otherwise. + ContentSizeBytes int64 `json:"content_size_bytes" api:"nullable"` + // Identifies who performed a write or redact operation. Captured at write time on + // the `memory_version` row. The API key that created a session is not recorded on + // agent writes; attribution answers who made the write, not who is ultimately + // responsible. Look up session provenance separately via the + // [Sessions API](/en/api/sessions-retrieve). + CreatedBy BetaManagedAgentsActorUnion `json:"created_by"` + // The memory's path at the time of this write. `null` if and only if `redacted_at` + // is set. + Path string `json:"path" api:"nullable"` + // A timestamp in RFC 3339 format + RedactedAt time.Time `json:"redacted_at" api:"nullable" format:"date-time"` + // Identifies who performed a write or redact operation. Captured at write time on + // the `memory_version` row. The API key that created a session is not recorded on + // agent writes; attribution answers who made the write, not who is ultimately + // responsible. Look up session provenance separately via the + // [Sessions API](/en/api/sessions-retrieve). + RedactedBy BetaManagedAgentsActorUnion `json:"redacted_by"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + CreatedAt respjson.Field + MemoryID respjson.Field + MemoryStoreID respjson.Field + Operation respjson.Field + Type respjson.Field + Content respjson.Field + ContentSha256 respjson.Field + ContentSizeBytes respjson.Field + CreatedBy respjson.Field + Path respjson.Field + RedactedAt respjson.Field + RedactedBy respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsMemoryVersion) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsMemoryVersion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsMemoryVersionType string + +const ( + BetaManagedAgentsMemoryVersionTypeMemoryVersion BetaManagedAgentsMemoryVersionType = "memory_version" +) + +// The kind of mutation a `memory_version` records. Every non-no-op mutation to a +// memory appends exactly one version row with one of these values. +type BetaManagedAgentsMemoryVersionOperation string + +const ( + BetaManagedAgentsMemoryVersionOperationCreated BetaManagedAgentsMemoryVersionOperation = "created" + BetaManagedAgentsMemoryVersionOperationModified BetaManagedAgentsMemoryVersionOperation = "modified" + BetaManagedAgentsMemoryVersionOperationDeleted BetaManagedAgentsMemoryVersionOperation = "deleted" +) + +// Attribution for a write made by a workload authenticated as a service account, +// for example via Workload Identity Federation. +type BetaManagedAgentsServiceAccountActor struct { + // ID of the service account that performed the write (a `svac_...` value). + ServiceAccountID string `json:"service_account_id" api:"required"` + Type constant.ServiceAccountActor `json:"type" default:"service_account_actor"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ServiceAccountID respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsServiceAccountActor) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsServiceAccountActor) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Attribution for a write made by an agent during a session, through the mounted +// filesystem at `/mnt/memory/`. +type BetaManagedAgentsSessionActor struct { + // ID of the session that performed the write (a `sesn_...` value). Look up the + // session via [Retrieve a session](/en/api/sessions-retrieve) for further + // provenance. + SessionID string `json:"session_id" api:"required"` + // Any of "session_actor". + Type BetaManagedAgentsSessionActorType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + SessionID respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsSessionActor) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsSessionActor) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsSessionActorType string + +const ( + BetaManagedAgentsSessionActorTypeSessionActor BetaManagedAgentsSessionActorType = "session_actor" +) + +// Attribution for a write made by a human user through the Anthropic Console. +type BetaManagedAgentsUserActor struct { + // Any of "user_actor". + Type BetaManagedAgentsUserActorType `json:"type" api:"required"` + // ID of the user who performed the write (a `user_...` value). + UserID string `json:"user_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Type respjson.Field + UserID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsUserActor) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsUserActor) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsUserActorType string + +const ( + BetaManagedAgentsUserActorTypeUserActor BetaManagedAgentsUserActorType = "user_actor" +) + +type BetaMemoryStoreMemoryVersionGetParams struct { + MemoryStoreID string `path:"memory_store_id" api:"required" json:"-"` + // Query parameter for view + // + // Any of "basic", "full". + View BetaManagedAgentsMemoryView `query:"view,omitzero" json:"-"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +// URLQuery serializes [BetaMemoryStoreMemoryVersionGetParams]'s query parameters +// as `url.Values`. +func (r BetaMemoryStoreMemoryVersionGetParams) URLQuery() (v url.Values, err error) { + return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ + ArrayFormat: apiquery.ArrayQueryFormatBrackets, + NestedFormat: apiquery.NestedQueryFormatBrackets, + }) +} + +type BetaMemoryStoreMemoryVersionListParams struct { + // Query parameter for api_key_id + APIKeyID param.Opt[string] `query:"api_key_id,omitzero" json:"-"` + // Return versions created at or after this time (inclusive). + CreatedAtGte param.Opt[time.Time] `query:"created_at[gte],omitzero" format:"date-time" json:"-"` + // Return versions created at or before this time (inclusive). + CreatedAtLte param.Opt[time.Time] `query:"created_at[lte],omitzero" format:"date-time" json:"-"` + // Query parameter for limit + Limit param.Opt[int64] `query:"limit,omitzero" json:"-"` + // Query parameter for memory_id + MemoryID param.Opt[string] `query:"memory_id,omitzero" json:"-"` + // Query parameter for page + Page param.Opt[string] `query:"page,omitzero" json:"-"` + // Query parameter for service_account_id + ServiceAccountID param.Opt[string] `query:"service_account_id,omitzero" json:"-"` + // Query parameter for session_id + SessionID param.Opt[string] `query:"session_id,omitzero" json:"-"` + // Query parameter for operation + // + // Any of "created", "modified", "deleted". + Operation BetaManagedAgentsMemoryVersionOperation `query:"operation,omitzero" json:"-"` + // Query parameter for view + // + // Any of "basic", "full". + View BetaManagedAgentsMemoryView `query:"view,omitzero" json:"-"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +// URLQuery serializes [BetaMemoryStoreMemoryVersionListParams]'s query parameters +// as `url.Values`. +func (r BetaMemoryStoreMemoryVersionListParams) URLQuery() (v url.Values, err error) { + return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ + ArrayFormat: apiquery.ArrayQueryFormatBrackets, + NestedFormat: apiquery.NestedQueryFormatBrackets, + }) +} + +type BetaMemoryStoreMemoryVersionRedactParams struct { + MemoryStoreID string `path:"memory_store_id" api:"required" json:"-"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/betamessage.go b/vendor/github.com/anthropics/anthropic-sdk-go/betamessage.go index cde291184..7af939c0f 100644 --- a/vendor/github.com/anthropics/anthropic-sdk-go/betamessage.go +++ b/vendor/github.com/anthropics/anthropic-sdk-go/betamessage.go @@ -48,13 +48,16 @@ func NewBetaMessageService(opts ...option.RequestOption) (r BetaMessageService) // conversations. // // Learn more about the Messages API in our -// [user guide](https://docs.claude.com/en/docs/initial-setup) +// [user guide](https://platform.claude.com/docs/en/get-started) // // Note: If you choose to set a timeout for this request, we recommend 10 minutes. func (r *BetaMessageService) New(ctx context.Context, params BetaMessageNewParams, opts ...option.RequestOption) (res *BetaMessage, err error) { for _, v := range params.Betas { opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) } + if !param.IsOmitted(params.UserProfileID) { + opts = append(opts, option.WithHeader("anthropic-user-profile-id", fmt.Sprintf("%v", params.UserProfileID.Value))) + } opts = slices.Concat(r.Options, opts) warnIfThinkingEnabled(params.Model, params.Thinking.OfEnabled != nil) @@ -68,6 +71,14 @@ func (r *BetaMessageService) New(ctx context.Context, params BetaMessageNewParam path := "v1/messages?beta=true" err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, params, &res, opts...) + if err != nil { + return nil, err + } + if dest, ok := outputFormatDest(params); ok { + if parseErr := parseOutputContent(res, dest); parseErr != nil { + return res, parseErr + } + } return res, err } @@ -78,7 +89,7 @@ func (r *BetaMessageService) New(ctx context.Context, params BetaMessageNewParam // conversations. // // Learn more about the Messages API in our -// [user guide](https://docs.claude.com/en/docs/initial-setup) +// [user guide](https://platform.claude.com/docs/en/get-started) // // Note: If you choose to set a timeout for this request, we recommend 10 minutes. func (r *BetaMessageService) NewStreaming(ctx context.Context, params BetaMessageNewParams, opts ...option.RequestOption) (stream *ssestream.Stream[BetaRawMessageStreamEventUnion]) { @@ -89,6 +100,9 @@ func (r *BetaMessageService) NewStreaming(ctx context.Context, params BetaMessag for _, v := range params.Betas { opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) } + if !param.IsOmitted(params.UserProfileID) { + opts = append(opts, option.WithHeader("anthropic-user-profile-id", fmt.Sprintf("%v", params.UserProfileID.Value))) + } opts = slices.Concat(r.Options, opts) warnIfThinkingEnabled(params.Model, params.Thinking.OfEnabled != nil) opts = append(opts, option.WithJSONSet("stream", true)) @@ -103,11 +117,14 @@ func (r *BetaMessageService) NewStreaming(ctx context.Context, params BetaMessag // including tools, images, and documents, without creating it. // // Learn more about token counting in our -// [user guide](https://docs.claude.com/en/docs/build-with-claude/token-counting) +// [user guide](https://platform.claude.com/docs/en/build-with-claude/token-counting) func (r *BetaMessageService) CountTokens(ctx context.Context, params BetaMessageCountTokensParams, opts ...option.RequestOption) (res *BetaMessageTokensCount, err error) { for _, v := range params.Betas { opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) } + if !param.IsOmitted(params.UserProfileID) { + opts = append(opts, option.WithHeader("anthropic-user-profile-id", fmt.Sprintf("%v", params.UserProfileID.Value))) + } opts = slices.Concat(r.Options, opts) path := "v1/messages/count_tokens?beta=true" err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, params, &res, opts...) @@ -124,8 +141,9 @@ type BetaAdvisorMessageIterationUsage struct { CacheReadInputTokens int64 `json:"cache_read_input_tokens" api:"required"` // The number of input tokens which were used. InputTokens int64 `json:"input_tokens" api:"required"` - // The model that will complete your prompt.\n\nSee - // [models](https://docs.anthropic.com/en/docs/models-overview) for additional + // The model that will complete your prompt. + // + // See [models](https://docs.anthropic.com/en/docs/models-overview) for additional // details and options. Model Model `json:"model" api:"required"` // The number of output tokens which were used. @@ -155,11 +173,15 @@ func (r *BetaAdvisorMessageIterationUsage) UnmarshalJSON(data []byte) error { type BetaAdvisorRedactedResultBlock struct { // Opaque blob containing the advisor's output. Round-trip verbatim; do not inspect // or modify. - EncryptedContent string `json:"encrypted_content" api:"required"` - Type constant.AdvisorRedactedResult `json:"type" default:"advisor_redacted_result"` + EncryptedContent string `json:"encrypted_content" api:"required"` + // The advisor sub-inference's stop reason (same values as the top-level message + // `stop_reason`). + StopReason string `json:"stop_reason" api:"required"` + Type constant.AdvisorRedactedResult `json:"type" default:"advisor_redacted_result"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { EncryptedContent respjson.Field + StopReason respjson.Field Type respjson.Field ExtraFields map[string]respjson.Field raw string @@ -175,7 +197,8 @@ func (r *BetaAdvisorRedactedResultBlock) UnmarshalJSON(data []byte) error { // The properties EncryptedContent, Type are required. type BetaAdvisorRedactedResultBlockParam struct { // Opaque blob produced by a prior response; must be round-tripped verbatim. - EncryptedContent string `json:"encrypted_content" api:"required"` + EncryptedContent string `json:"encrypted_content" api:"required"` + StopReason param.Opt[string] `json:"stop_reason,omitzero"` // This field can be elided, and will marshal its zero value as // "advisor_redacted_result". Type constant.AdvisorRedactedResult `json:"type" default:"advisor_redacted_result"` @@ -191,10 +214,15 @@ func (r *BetaAdvisorRedactedResultBlockParam) UnmarshalJSON(data []byte) error { } type BetaAdvisorResultBlock struct { - Text string `json:"text" api:"required"` - Type constant.AdvisorResult `json:"type" default:"advisor_result"` + // The advisor sub-inference's stop reason (same values as the top-level message + // `stop_reason`). `max_tokens` indicates the advisor's output was truncated at the + // tool's `max_tokens` value or the advisor model's policy cap. + StopReason string `json:"stop_reason" api:"required"` + Text string `json:"text" api:"required"` + Type constant.AdvisorResult `json:"type" default:"advisor_result"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { + StopReason respjson.Field Text respjson.Field Type respjson.Field ExtraFields map[string]respjson.Field @@ -210,7 +238,8 @@ func (r *BetaAdvisorResultBlock) UnmarshalJSON(data []byte) error { // The properties Text, Type are required. type BetaAdvisorResultBlockParam struct { - Text string `json:"text" api:"required"` + Text string `json:"text" api:"required"` + StopReason param.Opt[string] `json:"stop_reason,omitzero"` // This field can be elided, and will marshal its zero value as "advisor_result". Type constant.AdvisorResult `json:"type" default:"advisor_result"` paramObj @@ -226,10 +255,19 @@ func (r *BetaAdvisorResultBlockParam) UnmarshalJSON(data []byte) error { // The properties Model, Name, Type are required. type BetaAdvisorTool20260301Param struct { - // The model that will complete your prompt.\n\nSee - // [models](https://docs.anthropic.com/en/docs/models-overview) for additional + // The model that will complete your prompt. + // + // See [models](https://docs.anthropic.com/en/docs/models-overview) for additional // details and options. Model Model `json:"model,omitzero" api:"required"` + // Bounds the advisor's total output (thinking + text) per call. When the advisor + // hits this cap, the returned advisor_result or advisor_redacted_result block + // carries stop_reason='max_tokens', and a truncation note is appended to the + // advice text the worker model sees (inside the encrypted blob in redacted mode). + // When set, the server also emits a remaining-tokens budget block in the advisor's + // prompt so the advisor self-shapes toward the cap. When omitted, the advisor + // model's default output cap applies and no budget block is emitted. + MaxTokens param.Opt[int64] `json:"max_tokens,omitzero"` // Maximum number of times the tool can be used in the API request. MaxUses param.Opt[int64] `json:"max_uses,omitzero"` // If true, tool will not be included in initial system prompt. Only loaded when @@ -237,7 +275,8 @@ type BetaAdvisorTool20260301Param struct { DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` // When true, guarantees schema validation on tool names and inputs Strict param.Opt[bool] `json:"strict,omitzero"` - // Any of "direct", "code_execution_20250825", "code_execution_20260120". + // Any of "direct", "code_execution_20250825", "code_execution_20260120", + // "code_execution_20260521". AllowedCallers []string `json:"allowed_callers,omitzero"` // Create a cache control breakpoint at this content block. CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` @@ -291,8 +330,9 @@ func (r *BetaAdvisorToolResultBlock) UnmarshalJSON(data []byte) error { // Use the methods beginning with 'As' to cast the union to one of its variants. type BetaAdvisorToolResultBlockContentUnion struct { // This field is from variant [BetaAdvisorToolResultError]. - ErrorCode BetaAdvisorToolResultErrorErrorCode `json:"error_code"` - Type string `json:"type"` + ErrorCode BetaAdvisorToolResultErrorErrorCode `json:"error_code"` + Type string `json:"type"` + StopReason string `json:"stop_reason"` // This field is from variant [BetaAdvisorResultBlock]. Text string `json:"text"` // This field is from variant [BetaAdvisorRedactedResultBlock]. @@ -300,6 +340,7 @@ type BetaAdvisorToolResultBlockContentUnion struct { JSON struct { ErrorCode respjson.Field Type respjson.Field + StopReason respjson.Field Text respjson.Field EncryptedContent respjson.Field raw string @@ -412,9 +453,19 @@ func (u BetaAdvisorToolResultBlockParamContentUnion) GetType() *string { return nil } +// Returns a pointer to the underlying variant's property, if present. +func (u BetaAdvisorToolResultBlockParamContentUnion) GetStopReason() *string { + if vt := u.OfRequestAdvisorResultBlock; vt != nil && vt.StopReason.Valid() { + return &vt.StopReason.Value + } else if vt := u.OfRequestAdvisorRedactedResultBlock; vt != nil && vt.StopReason.Valid() { + return &vt.StopReason.Value + } + return nil +} + type BetaAdvisorToolResultError struct { // Any of "max_uses_exceeded", "prompt_too_long", "too_many_requests", - // "overloaded", "unavailable", "execution_time_exceeded". + // "overloaded", "unavailable", "execution_time_exceeded", "model_not_found". ErrorCode BetaAdvisorToolResultErrorErrorCode `json:"error_code" api:"required"` Type constant.AdvisorToolResultError `json:"type" default:"advisor_tool_result_error"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. @@ -441,12 +492,13 @@ const ( BetaAdvisorToolResultErrorErrorCodeOverloaded BetaAdvisorToolResultErrorErrorCode = "overloaded" BetaAdvisorToolResultErrorErrorCodeUnavailable BetaAdvisorToolResultErrorErrorCode = "unavailable" BetaAdvisorToolResultErrorErrorCodeExecutionTimeExceeded BetaAdvisorToolResultErrorErrorCode = "execution_time_exceeded" + BetaAdvisorToolResultErrorErrorCodeModelNotFound BetaAdvisorToolResultErrorErrorCode = "model_not_found" ) // The properties ErrorCode, Type are required. type BetaAdvisorToolResultErrorParam struct { // Any of "max_uses_exceeded", "prompt_too_long", "too_many_requests", - // "overloaded", "unavailable", "execution_time_exceeded". + // "overloaded", "unavailable", "execution_time_exceeded", "model_not_found". ErrorCode BetaAdvisorToolResultErrorParamErrorCode `json:"error_code,omitzero" api:"required"` // This field can be elided, and will marshal its zero value as // "advisor_tool_result_error". @@ -471,6 +523,7 @@ const ( BetaAdvisorToolResultErrorParamErrorCodeOverloaded BetaAdvisorToolResultErrorParamErrorCode = "overloaded" BetaAdvisorToolResultErrorParamErrorCodeUnavailable BetaAdvisorToolResultErrorParamErrorCode = "unavailable" BetaAdvisorToolResultErrorParamErrorCodeExecutionTimeExceeded BetaAdvisorToolResultErrorParamErrorCode = "execution_time_exceeded" + BetaAdvisorToolResultErrorParamErrorCodeModelNotFound BetaAdvisorToolResultErrorParamErrorCode = "model_not_found" ) func NewBetaAllThinkingTurnsParam() BetaAllThinkingTurnsParam { @@ -866,1083 +919,1150 @@ const ( BetaBashCodeExecutionToolResultErrorParamErrorCodeOutputFileTooLarge BetaBashCodeExecutionToolResultErrorParamErrorCode = "output_file_too_large" ) -func NewBetaCacheControlEphemeralParam() BetaCacheControlEphemeralParam { - return BetaCacheControlEphemeralParam{ - Type: "ephemeral", - } -} - -// This struct has a constant value, construct it with -// [NewBetaCacheControlEphemeralParam]. -type BetaCacheControlEphemeralParam struct { - // The time-to-live for the cache control breakpoint. - // - // This may be one the following values: - // - // - `5m`: 5 minutes - // - `1h`: 1 hour - // - // Defaults to `5m`. - // - // Any of "5m", "1h". - TTL BetaCacheControlEphemeralTTL `json:"ttl,omitzero"` - Type constant.Ephemeral `json:"type" default:"ephemeral"` +// `close_tab`'s config overrides. +type BetaBrowserCloseTabConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` paramObj } -func (r BetaCacheControlEphemeralParam) MarshalJSON() (data []byte, err error) { - type shadow BetaCacheControlEphemeralParam +func (r BetaBrowserCloseTabConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaBrowserCloseTabConfigParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *BetaCacheControlEphemeralParam) UnmarshalJSON(data []byte) error { +func (r *BetaBrowserCloseTabConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The time-to-live for the cache control breakpoint. -// -// This may be one the following values: -// -// - `5m`: 5 minutes -// - `1h`: 1 hour -// -// Defaults to `5m`. -type BetaCacheControlEphemeralTTL string +// `double_click`'s config overrides. +type BetaBrowserDoubleClickConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj +} -const ( - BetaCacheControlEphemeralTTLTTL5m BetaCacheControlEphemeralTTL = "5m" - BetaCacheControlEphemeralTTLTTL1h BetaCacheControlEphemeralTTL = "1h" -) +func (r BetaBrowserDoubleClickConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaBrowserDoubleClickConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaBrowserDoubleClickConfigParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} -type BetaCacheCreation struct { - // The number of input tokens used to create the 1 hour cache entry. - Ephemeral1hInputTokens int64 `json:"ephemeral_1h_input_tokens" api:"required"` - // The number of input tokens used to create the 5 minute cache entry. - Ephemeral5mInputTokens int64 `json:"ephemeral_5m_input_tokens" api:"required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Ephemeral1hInputTokens respjson.Field - Ephemeral5mInputTokens respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +// `file_upload`'s config overrides. +type BetaBrowserFileUploadConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -// Returns the unmodified JSON received from the API -func (r BetaCacheCreation) RawJSON() string { return r.JSON.raw } -func (r *BetaCacheCreation) UnmarshalJSON(data []byte) error { +func (r BetaBrowserFileUploadConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaBrowserFileUploadConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaBrowserFileUploadConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type BetaCitationCharLocation struct { - CitedText string `json:"cited_text" api:"required"` - DocumentIndex int64 `json:"document_index" api:"required"` - DocumentTitle string `json:"document_title" api:"required"` - EndCharIndex int64 `json:"end_char_index" api:"required"` - FileID string `json:"file_id" api:"required"` - StartCharIndex int64 `json:"start_char_index" api:"required"` - Type constant.CharLocation `json:"type" default:"char_location"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - CitedText respjson.Field - DocumentIndex respjson.Field - DocumentTitle respjson.Field - EndCharIndex respjson.Field - FileID respjson.Field - StartCharIndex respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +// `find`'s config overrides. +type BetaBrowserFindConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -// Returns the unmodified JSON received from the API -func (r BetaCitationCharLocation) RawJSON() string { return r.JSON.raw } -func (r *BetaCitationCharLocation) UnmarshalJSON(data []byte) error { +func (r BetaBrowserFindConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaBrowserFindConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaBrowserFindConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The properties CitedText, DocumentIndex, DocumentTitle, EndCharIndex, -// StartCharIndex, Type are required. -type BetaCitationCharLocationParam struct { - DocumentTitle param.Opt[string] `json:"document_title,omitzero" api:"required"` - CitedText string `json:"cited_text" api:"required"` - DocumentIndex int64 `json:"document_index" api:"required"` - EndCharIndex int64 `json:"end_char_index" api:"required"` - StartCharIndex int64 `json:"start_char_index" api:"required"` - // This field can be elided, and will marshal its zero value as "char_location". - Type constant.CharLocation `json:"type" default:"char_location"` +// `form_input`'s config overrides. +type BetaBrowserFormInputConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` paramObj } -func (r BetaCitationCharLocationParam) MarshalJSON() (data []byte, err error) { - type shadow BetaCitationCharLocationParam +func (r BetaBrowserFormInputConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaBrowserFormInputConfigParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *BetaCitationCharLocationParam) UnmarshalJSON(data []byte) error { +func (r *BetaBrowserFormInputConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type BetaCitationConfig struct { - Enabled bool `json:"enabled" api:"required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Enabled respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +// `get_page_text`'s config overrides. +type BetaBrowserGetPageTextConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -// Returns the unmodified JSON received from the API -func (r BetaCitationConfig) RawJSON() string { return r.JSON.raw } -func (r *BetaCitationConfig) UnmarshalJSON(data []byte) error { +func (r BetaBrowserGetPageTextConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaBrowserGetPageTextConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaBrowserGetPageTextConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type BetaCitationContentBlockLocation struct { - CitedText string `json:"cited_text" api:"required"` - DocumentIndex int64 `json:"document_index" api:"required"` - DocumentTitle string `json:"document_title" api:"required"` - EndBlockIndex int64 `json:"end_block_index" api:"required"` - FileID string `json:"file_id" api:"required"` - StartBlockIndex int64 `json:"start_block_index" api:"required"` - Type constant.ContentBlockLocation `json:"type" default:"content_block_location"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - CitedText respjson.Field - DocumentIndex respjson.Field - DocumentTitle respjson.Field - EndBlockIndex respjson.Field - FileID respjson.Field - StartBlockIndex respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +// `hold_key`'s config overrides. +type BetaBrowserHoldKeyConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -// Returns the unmodified JSON received from the API -func (r BetaCitationContentBlockLocation) RawJSON() string { return r.JSON.raw } -func (r *BetaCitationContentBlockLocation) UnmarshalJSON(data []byte) error { +func (r BetaBrowserHoldKeyConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaBrowserHoldKeyConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaBrowserHoldKeyConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The properties CitedText, DocumentIndex, DocumentTitle, EndBlockIndex, -// StartBlockIndex, Type are required. -type BetaCitationContentBlockLocationParam struct { - DocumentTitle param.Opt[string] `json:"document_title,omitzero" api:"required"` - CitedText string `json:"cited_text" api:"required"` - DocumentIndex int64 `json:"document_index" api:"required"` - EndBlockIndex int64 `json:"end_block_index" api:"required"` - StartBlockIndex int64 `json:"start_block_index" api:"required"` - // This field can be elided, and will marshal its zero value as - // "content_block_location". - Type constant.ContentBlockLocation `json:"type" default:"content_block_location"` +// `hover`'s config overrides. +type BetaBrowserHoverConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` paramObj } -func (r BetaCitationContentBlockLocationParam) MarshalJSON() (data []byte, err error) { - type shadow BetaCitationContentBlockLocationParam +func (r BetaBrowserHoverConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaBrowserHoverConfigParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *BetaCitationContentBlockLocationParam) UnmarshalJSON(data []byte) error { +func (r *BetaBrowserHoverConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type BetaCitationPageLocation struct { - CitedText string `json:"cited_text" api:"required"` - DocumentIndex int64 `json:"document_index" api:"required"` - DocumentTitle string `json:"document_title" api:"required"` - EndPageNumber int64 `json:"end_page_number" api:"required"` - FileID string `json:"file_id" api:"required"` - StartPageNumber int64 `json:"start_page_number" api:"required"` - Type constant.PageLocation `json:"type" default:"page_location"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - CitedText respjson.Field - DocumentIndex respjson.Field - DocumentTitle respjson.Field - EndPageNumber respjson.Field - FileID respjson.Field - StartPageNumber respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +// `javascript_exec`'s config overrides. +type BetaBrowserJavascriptExecConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -// Returns the unmodified JSON received from the API -func (r BetaCitationPageLocation) RawJSON() string { return r.JSON.raw } -func (r *BetaCitationPageLocation) UnmarshalJSON(data []byte) error { +func (r BetaBrowserJavascriptExecConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaBrowserJavascriptExecConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaBrowserJavascriptExecConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The properties CitedText, DocumentIndex, DocumentTitle, EndPageNumber, -// StartPageNumber, Type are required. -type BetaCitationPageLocationParam struct { - DocumentTitle param.Opt[string] `json:"document_title,omitzero" api:"required"` - CitedText string `json:"cited_text" api:"required"` - DocumentIndex int64 `json:"document_index" api:"required"` - EndPageNumber int64 `json:"end_page_number" api:"required"` - StartPageNumber int64 `json:"start_page_number" api:"required"` - // This field can be elided, and will marshal its zero value as "page_location". - Type constant.PageLocation `json:"type" default:"page_location"` +// `key`'s config overrides. +type BetaBrowserKeyConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` paramObj } -func (r BetaCitationPageLocationParam) MarshalJSON() (data []byte, err error) { - type shadow BetaCitationPageLocationParam +func (r BetaBrowserKeyConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaBrowserKeyConfigParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *BetaCitationPageLocationParam) UnmarshalJSON(data []byte) error { +func (r *BetaBrowserKeyConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type BetaCitationSearchResultLocation struct { - CitedText string `json:"cited_text" api:"required"` - EndBlockIndex int64 `json:"end_block_index" api:"required"` - SearchResultIndex int64 `json:"search_result_index" api:"required"` - Source string `json:"source" api:"required"` - StartBlockIndex int64 `json:"start_block_index" api:"required"` - Title string `json:"title" api:"required"` - Type constant.SearchResultLocation `json:"type" default:"search_result_location"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - CitedText respjson.Field - EndBlockIndex respjson.Field - SearchResultIndex respjson.Field - Source respjson.Field - StartBlockIndex respjson.Field - Title respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +// `left_click`'s config overrides. +type BetaBrowserLeftClickConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -// Returns the unmodified JSON received from the API -func (r BetaCitationSearchResultLocation) RawJSON() string { return r.JSON.raw } -func (r *BetaCitationSearchResultLocation) UnmarshalJSON(data []byte) error { +func (r BetaBrowserLeftClickConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaBrowserLeftClickConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaBrowserLeftClickConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The properties CitedText, EndBlockIndex, SearchResultIndex, Source, -// StartBlockIndex, Title, Type are required. -type BetaCitationSearchResultLocationParam struct { - Title param.Opt[string] `json:"title,omitzero" api:"required"` - CitedText string `json:"cited_text" api:"required"` - EndBlockIndex int64 `json:"end_block_index" api:"required"` - SearchResultIndex int64 `json:"search_result_index" api:"required"` - Source string `json:"source" api:"required"` - StartBlockIndex int64 `json:"start_block_index" api:"required"` - // This field can be elided, and will marshal its zero value as - // "search_result_location". - Type constant.SearchResultLocation `json:"type" default:"search_result_location"` +// `left_click_drag`'s config overrides. +type BetaBrowserLeftClickDragConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` paramObj } -func (r BetaCitationSearchResultLocationParam) MarshalJSON() (data []byte, err error) { - type shadow BetaCitationSearchResultLocationParam +func (r BetaBrowserLeftClickDragConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaBrowserLeftClickDragConfigParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *BetaCitationSearchResultLocationParam) UnmarshalJSON(data []byte) error { +func (r *BetaBrowserLeftClickDragConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The properties CitedText, EncryptedIndex, Title, Type, URL are required. -type BetaCitationWebSearchResultLocationParam struct { - Title param.Opt[string] `json:"title,omitzero" api:"required"` - CitedText string `json:"cited_text" api:"required"` - EncryptedIndex string `json:"encrypted_index" api:"required"` - URL string `json:"url" api:"required"` - // This field can be elided, and will marshal its zero value as - // "web_search_result_location". - Type constant.WebSearchResultLocation `json:"type" default:"web_search_result_location"` +// `left_mouse_down`'s config overrides. +type BetaBrowserLeftMouseDownConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` paramObj } -func (r BetaCitationWebSearchResultLocationParam) MarshalJSON() (data []byte, err error) { - type shadow BetaCitationWebSearchResultLocationParam +func (r BetaBrowserLeftMouseDownConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaBrowserLeftMouseDownConfigParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *BetaCitationWebSearchResultLocationParam) UnmarshalJSON(data []byte) error { +func (r *BetaBrowserLeftMouseDownConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type BetaCitationsConfigParam struct { +// `left_mouse_up`'s config overrides. +type BetaBrowserLeftMouseUpConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. Enabled param.Opt[bool] `json:"enabled,omitzero"` paramObj } -func (r BetaCitationsConfigParam) MarshalJSON() (data []byte, err error) { - type shadow BetaCitationsConfigParam +func (r BetaBrowserLeftMouseUpConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaBrowserLeftMouseUpConfigParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *BetaCitationsConfigParam) UnmarshalJSON(data []byte) error { +func (r *BetaBrowserLeftMouseUpConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type BetaCitationsDelta struct { - Citation BetaCitationsDeltaCitationUnion `json:"citation" api:"required"` - Type constant.CitationsDelta `json:"type" default:"citations_delta"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Citation respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +// `list_tabs`'s config overrides. +type BetaBrowserListTabsConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -// Returns the unmodified JSON received from the API -func (r BetaCitationsDelta) RawJSON() string { return r.JSON.raw } -func (r *BetaCitationsDelta) UnmarshalJSON(data []byte) error { +func (r BetaBrowserListTabsConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaBrowserListTabsConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaBrowserListTabsConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// BetaCitationsDeltaCitationUnion contains all possible properties and values from -// [BetaCitationCharLocation], [BetaCitationPageLocation], -// [BetaCitationContentBlockLocation], [BetaCitationsWebSearchResultLocation], -// [BetaCitationSearchResultLocation]. -// -// Use the [BetaCitationsDeltaCitationUnion.AsAny] method to switch on the variant. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -type BetaCitationsDeltaCitationUnion struct { - CitedText string `json:"cited_text"` - DocumentIndex int64 `json:"document_index"` - DocumentTitle string `json:"document_title"` - // This field is from variant [BetaCitationCharLocation]. - EndCharIndex int64 `json:"end_char_index"` - FileID string `json:"file_id"` - // This field is from variant [BetaCitationCharLocation]. - StartCharIndex int64 `json:"start_char_index"` - // Any of "char_location", "page_location", "content_block_location", - // "web_search_result_location", "search_result_location". - Type string `json:"type"` - // This field is from variant [BetaCitationPageLocation]. - EndPageNumber int64 `json:"end_page_number"` - // This field is from variant [BetaCitationPageLocation]. - StartPageNumber int64 `json:"start_page_number"` - EndBlockIndex int64 `json:"end_block_index"` - StartBlockIndex int64 `json:"start_block_index"` - // This field is from variant [BetaCitationsWebSearchResultLocation]. - EncryptedIndex string `json:"encrypted_index"` - Title string `json:"title"` - // This field is from variant [BetaCitationsWebSearchResultLocation]. - URL string `json:"url"` - // This field is from variant [BetaCitationSearchResultLocation]. - SearchResultIndex int64 `json:"search_result_index"` - // This field is from variant [BetaCitationSearchResultLocation]. - Source string `json:"source"` - JSON struct { - CitedText respjson.Field - DocumentIndex respjson.Field - DocumentTitle respjson.Field - EndCharIndex respjson.Field - FileID respjson.Field - StartCharIndex respjson.Field - Type respjson.Field - EndPageNumber respjson.Field - StartPageNumber respjson.Field - EndBlockIndex respjson.Field - StartBlockIndex respjson.Field - EncryptedIndex respjson.Field - Title respjson.Field - URL respjson.Field - SearchResultIndex respjson.Field - Source respjson.Field - raw string - } `json:"-"` +// `middle_click`'s config overrides. +type BetaBrowserMiddleClickConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -// anyBetaCitationsDeltaCitation is implemented by each variant of -// [BetaCitationsDeltaCitationUnion] to add type safety for the return type of -// [BetaCitationsDeltaCitationUnion.AsAny] -type anyBetaCitationsDeltaCitation interface { - implBetaCitationsDeltaCitationUnion() +func (r BetaBrowserMiddleClickConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaBrowserMiddleClickConfigParam + return param.MarshalObject(r, (*shadow)(&r)) } - -func (BetaCitationCharLocation) implBetaCitationsDeltaCitationUnion() {} -func (BetaCitationPageLocation) implBetaCitationsDeltaCitationUnion() {} -func (BetaCitationContentBlockLocation) implBetaCitationsDeltaCitationUnion() {} -func (BetaCitationsWebSearchResultLocation) implBetaCitationsDeltaCitationUnion() {} -func (BetaCitationSearchResultLocation) implBetaCitationsDeltaCitationUnion() {} - -// Use the following switch statement to find the correct variant -// -// switch variant := BetaCitationsDeltaCitationUnion.AsAny().(type) { -// case anthropic.BetaCitationCharLocation: -// case anthropic.BetaCitationPageLocation: -// case anthropic.BetaCitationContentBlockLocation: -// case anthropic.BetaCitationsWebSearchResultLocation: -// case anthropic.BetaCitationSearchResultLocation: -// default: -// fmt.Errorf("no variant present") -// } -func (u BetaCitationsDeltaCitationUnion) AsAny() anyBetaCitationsDeltaCitation { - switch u.Type { - case "char_location": - return u.AsCharLocation() - case "page_location": - return u.AsPageLocation() - case "content_block_location": - return u.AsContentBlockLocation() - case "web_search_result_location": - return u.AsWebSearchResultLocation() - case "search_result_location": - return u.AsSearchResultLocation() - } - return nil +func (r *BetaBrowserMiddleClickConfigParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func (u BetaCitationsDeltaCitationUnion) AsCharLocation() (v BetaCitationCharLocation) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +// `mouse_move`'s config overrides. +type BetaBrowserMouseMoveConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -func (u BetaCitationsDeltaCitationUnion) AsPageLocation() (v BetaCitationPageLocation) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +func (r BetaBrowserMouseMoveConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaBrowserMouseMoveConfigParam + return param.MarshalObject(r, (*shadow)(&r)) } - -func (u BetaCitationsDeltaCitationUnion) AsContentBlockLocation() (v BetaCitationContentBlockLocation) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +func (r *BetaBrowserMouseMoveConfigParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func (u BetaCitationsDeltaCitationUnion) AsWebSearchResultLocation() (v BetaCitationsWebSearchResultLocation) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +// `navigate`'s config overrides. +type BetaBrowserNavigateConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -func (u BetaCitationsDeltaCitationUnion) AsSearchResultLocation() (v BetaCitationSearchResultLocation) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +func (r BetaBrowserNavigateConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaBrowserNavigateConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaBrowserNavigateConfigParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns the unmodified JSON received from the API -func (u BetaCitationsDeltaCitationUnion) RawJSON() string { return u.JSON.raw } +// `new_tab`'s config overrides. +type BetaBrowserNewTabConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj +} -func (r *BetaCitationsDeltaCitationUnion) UnmarshalJSON(data []byte) error { +func (r BetaBrowserNewTabConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaBrowserNewTabConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaBrowserNewTabConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type BetaCitationsWebSearchResultLocation struct { - CitedText string `json:"cited_text" api:"required"` - EncryptedIndex string `json:"encrypted_index" api:"required"` - Title string `json:"title" api:"required"` - Type constant.WebSearchResultLocation `json:"type" default:"web_search_result_location"` - URL string `json:"url" api:"required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - CitedText respjson.Field - EncryptedIndex respjson.Field - Title respjson.Field - Type respjson.Field - URL respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +// `read_console`'s config overrides. +type BetaBrowserReadConsoleConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -// Returns the unmodified JSON received from the API -func (r BetaCitationsWebSearchResultLocation) RawJSON() string { return r.JSON.raw } -func (r *BetaCitationsWebSearchResultLocation) UnmarshalJSON(data []byte) error { +func (r BetaBrowserReadConsoleConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaBrowserReadConsoleConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaBrowserReadConsoleConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The property Type is required. -type BetaClearThinking20251015EditParam struct { - // Number of most recent assistant turns to keep thinking blocks for. Older turns - // will have their thinking blocks removed. - Keep BetaClearThinking20251015EditKeepUnionParam `json:"keep,omitzero"` - // This field can be elided, and will marshal its zero value as - // "clear_thinking_20251015". - Type constant.ClearThinking20251015 `json:"type" default:"clear_thinking_20251015"` +// `read_network`'s config overrides. +type BetaBrowserReadNetworkConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` paramObj } -func (r BetaClearThinking20251015EditParam) MarshalJSON() (data []byte, err error) { - type shadow BetaClearThinking20251015EditParam +func (r BetaBrowserReadNetworkConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaBrowserReadNetworkConfigParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *BetaClearThinking20251015EditParam) UnmarshalJSON(data []byte) error { +func (r *BetaBrowserReadNetworkConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type BetaClearThinking20251015EditKeepUnionParam struct { - OfThinkingTurns *BetaThinkingTurnsParam `json:",omitzero,inline"` - OfAllThinkingTurns *BetaAllThinkingTurnsParam `json:",omitzero,inline"` - // Construct this variant with constant.ValueOf[constant.All]() - OfAll constant.All `json:",omitzero,inline"` - paramUnion +// `read_page`'s config overrides. +type BetaBrowserReadPageConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -func (u BetaClearThinking20251015EditKeepUnionParam) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfThinkingTurns, u.OfAllThinkingTurns, u.OfAll) +func (r BetaBrowserReadPageConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaBrowserReadPageConfigParam + return param.MarshalObject(r, (*shadow)(&r)) } -func (u *BetaClearThinking20251015EditKeepUnionParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) +func (r *BetaBrowserReadPageConfigParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func (u *BetaClearThinking20251015EditKeepUnionParam) asAny() any { - if !param.IsOmitted(u.OfThinkingTurns) { - return u.OfThinkingTurns - } else if !param.IsOmitted(u.OfAllThinkingTurns) { - return u.OfAllThinkingTurns - } else if !param.IsOmitted(u.OfAll) { - return &u.OfAll - } - return nil +// `right_click`'s config overrides. +type BetaBrowserRightClickConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaClearThinking20251015EditKeepUnionParam) GetValue() *int64 { - if vt := u.OfThinkingTurns; vt != nil { - return &vt.Value - } - return nil +func (r BetaBrowserRightClickConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaBrowserRightClickConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaBrowserRightClickConfigParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaClearThinking20251015EditKeepUnionParam) GetType() *string { - if vt := u.OfThinkingTurns; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfAllThinkingTurns; vt != nil { - return (*string)(&vt.Type) - } - return nil +// `screenshot`'s config overrides. +type BetaBrowserScreenshotConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -type BetaClearThinking20251015EditResponse struct { - // Number of input tokens cleared by this edit. - ClearedInputTokens int64 `json:"cleared_input_tokens" api:"required"` - // Number of thinking turns that were cleared. - ClearedThinkingTurns int64 `json:"cleared_thinking_turns" api:"required"` - // The type of context management edit applied. - Type constant.ClearThinking20251015 `json:"type" default:"clear_thinking_20251015"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ClearedInputTokens respjson.Field - ClearedThinkingTurns respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +func (r BetaBrowserScreenshotConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaBrowserScreenshotConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaBrowserScreenshotConfigParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns the unmodified JSON received from the API -func (r BetaClearThinking20251015EditResponse) RawJSON() string { return r.JSON.raw } -func (r *BetaClearThinking20251015EditResponse) UnmarshalJSON(data []byte) error { +// `scroll`'s config overrides. +type BetaBrowserScrollConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj +} + +func (r BetaBrowserScrollConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaBrowserScrollConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaBrowserScrollConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The property Type is required. -type BetaClearToolUses20250919EditParam struct { - // Whether to clear all tool inputs (bool) or specific tool inputs to clear (list) - ClearToolInputs BetaClearToolUses20250919EditClearToolInputsUnionParam `json:"clear_tool_inputs,omitzero"` - // Tool names whose uses are preserved from clearing - ExcludeTools []string `json:"exclude_tools,omitzero"` - // Minimum number of tokens that must be cleared when triggered. Context will only - // be modified if at least this many tokens can be removed. - ClearAtLeast BetaInputTokensClearAtLeastParam `json:"clear_at_least,omitzero"` - // Number of tool uses to retain in the conversation - Keep BetaToolUsesKeepParam `json:"keep,omitzero"` - // Condition that triggers the context management strategy - Trigger BetaClearToolUses20250919EditTriggerUnionParam `json:"trigger,omitzero"` - // This field can be elided, and will marshal its zero value as - // "clear_tool_uses_20250919". - Type constant.ClearToolUses20250919 `json:"type" default:"clear_tool_uses_20250919"` +// `scroll_to`'s config overrides. +type BetaBrowserScrollToConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` paramObj } -func (r BetaClearToolUses20250919EditParam) MarshalJSON() (data []byte, err error) { - type shadow BetaClearToolUses20250919EditParam +func (r BetaBrowserScrollToConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaBrowserScrollToConfigParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *BetaClearToolUses20250919EditParam) UnmarshalJSON(data []byte) error { +func (r *BetaBrowserScrollToConfigParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The caller's browser state after a browser toolset member call — the full +// inventory of open tabs, which tab is active, and any side effects (tabs opened, +// download state changes) the call produced. +// +// At most one per `tool_result`, only on a non-error result answering a browser +// toolset member `tool_use`. The server renders the model-visible text from it; +// the model never sees the raw fields. +// +// The properties Tabs, Type are required. +type BetaBrowserStateBlockParam struct { + // All tabs open in the browser after this call — the full inventory, not a delta. + // May be empty. Whenever non-empty, exactly one entry carries `active: true`. + Tabs []BetaBrowserStateTabEntryParam `json:"tabs,omitzero" api:"required"` + // Tabs opened and download state changes during this call. "Nothing to report" is + // expressed by omitting the field, never by an empty list. + StateChanges []BetaBrowserStateChangeUnionParam `json:"state_changes,omitzero"` + // Create a cache control breakpoint at this content block. + CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` + // This field can be elided, and will marshal its zero value as "browser_state". + Type constant.BrowserState `json:"type" default:"browser_state"` + paramObj +} + +func (r BetaBrowserStateBlockParam) MarshalJSON() (data []byte, err error) { + type shadow BetaBrowserStateBlockParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaBrowserStateBlockParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } +func BetaBrowserStateChangeParamOfTabOpened(tabID string) BetaBrowserStateChangeUnionParam { + var tabOpened BetaBrowserStateChangeTabOpenedParam + tabOpened.TabID = tabID + return BetaBrowserStateChangeUnionParam{OfTabOpened: &tabOpened} +} + +func BetaBrowserStateChangeParamOfDownloadStarted(downloadID string, url string) BetaBrowserStateChangeUnionParam { + var downloadStarted BetaBrowserStateChangeDownloadStartedParam + downloadStarted.DownloadID = downloadID + downloadStarted.URL = url + return BetaBrowserStateChangeUnionParam{OfDownloadStarted: &downloadStarted} +} + +func BetaBrowserStateChangeParamOfDownloadCompleted(downloadID string, url string) BetaBrowserStateChangeUnionParam { + var downloadCompleted BetaBrowserStateChangeDownloadCompletedParam + downloadCompleted.DownloadID = downloadID + downloadCompleted.URL = url + return BetaBrowserStateChangeUnionParam{OfDownloadCompleted: &downloadCompleted} +} + +func BetaBrowserStateChangeParamOfDownloadFailed(downloadID string, url string) BetaBrowserStateChangeUnionParam { + var downloadFailed BetaBrowserStateChangeDownloadFailedParam + downloadFailed.DownloadID = downloadID + downloadFailed.URL = url + return BetaBrowserStateChangeUnionParam{OfDownloadFailed: &downloadFailed} +} + // Only one field can be non-zero. // // Use [param.IsOmitted] to confirm if a field is set. -type BetaClearToolUses20250919EditClearToolInputsUnionParam struct { - OfBool param.Opt[bool] `json:",omitzero,inline"` - OfStringArray []string `json:",omitzero,inline"` +type BetaBrowserStateChangeUnionParam struct { + OfTabOpened *BetaBrowserStateChangeTabOpenedParam `json:",omitzero,inline"` + OfDownloadStarted *BetaBrowserStateChangeDownloadStartedParam `json:",omitzero,inline"` + OfDownloadCompleted *BetaBrowserStateChangeDownloadCompletedParam `json:",omitzero,inline"` + OfDownloadFailed *BetaBrowserStateChangeDownloadFailedParam `json:",omitzero,inline"` paramUnion } -func (u BetaClearToolUses20250919EditClearToolInputsUnionParam) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfBool, u.OfStringArray) +func (u BetaBrowserStateChangeUnionParam) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfTabOpened, u.OfDownloadStarted, u.OfDownloadCompleted, u.OfDownloadFailed) } -func (u *BetaClearToolUses20250919EditClearToolInputsUnionParam) UnmarshalJSON(data []byte) error { +func (u *BetaBrowserStateChangeUnionParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, u) } -func (u *BetaClearToolUses20250919EditClearToolInputsUnionParam) asAny() any { - if !param.IsOmitted(u.OfBool) { - return &u.OfBool.Value - } else if !param.IsOmitted(u.OfStringArray) { - return &u.OfStringArray +func (u *BetaBrowserStateChangeUnionParam) asAny() any { + if !param.IsOmitted(u.OfTabOpened) { + return u.OfTabOpened + } else if !param.IsOmitted(u.OfDownloadStarted) { + return u.OfDownloadStarted + } else if !param.IsOmitted(u.OfDownloadCompleted) { + return u.OfDownloadCompleted + } else if !param.IsOmitted(u.OfDownloadFailed) { + return u.OfDownloadFailed } return nil } -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type BetaClearToolUses20250919EditTriggerUnionParam struct { - OfInputTokens *BetaInputTokensTriggerParam `json:",omitzero,inline"` - OfToolUses *BetaToolUsesTriggerParam `json:",omitzero,inline"` - paramUnion +// Returns a pointer to the underlying variant's property, if present. +func (u BetaBrowserStateChangeUnionParam) GetTabID() *string { + if vt := u.OfTabOpened; vt != nil { + return &vt.TabID + } + return nil } -func (u BetaClearToolUses20250919EditTriggerUnionParam) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfInputTokens, u.OfToolUses) +// Returns a pointer to the underlying variant's property, if present. +func (u BetaBrowserStateChangeUnionParam) GetPath() *string { + if vt := u.OfDownloadCompleted; vt != nil && vt.Path.Valid() { + return &vt.Path.Value + } + return nil } -func (u *BetaClearToolUses20250919EditTriggerUnionParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaBrowserStateChangeUnionParam) GetSizeBytes() *int64 { + if vt := u.OfDownloadCompleted; vt != nil && vt.SizeBytes.Valid() { + return &vt.SizeBytes.Value + } + return nil } -func (u *BetaClearToolUses20250919EditTriggerUnionParam) asAny() any { - if !param.IsOmitted(u.OfInputTokens) { - return u.OfInputTokens - } else if !param.IsOmitted(u.OfToolUses) { - return u.OfToolUses +// Returns a pointer to the underlying variant's property, if present. +func (u BetaBrowserStateChangeUnionParam) GetError() *string { + if vt := u.OfDownloadFailed; vt != nil && vt.Error.Valid() { + return &vt.Error.Value } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u BetaClearToolUses20250919EditTriggerUnionParam) GetType() *string { - if vt := u.OfInputTokens; vt != nil { +func (u BetaBrowserStateChangeUnionParam) GetType() *string { + if vt := u.OfTabOpened; vt != nil { return (*string)(&vt.Type) - } else if vt := u.OfToolUses; vt != nil { + } else if vt := u.OfDownloadStarted; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfDownloadCompleted; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfDownloadFailed; vt != nil { return (*string)(&vt.Type) } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u BetaClearToolUses20250919EditTriggerUnionParam) GetValue() *int64 { - if vt := u.OfInputTokens; vt != nil { - return (*int64)(&vt.Value) - } else if vt := u.OfToolUses; vt != nil { - return (*int64)(&vt.Value) +func (u BetaBrowserStateChangeUnionParam) GetDownloadID() *string { + if vt := u.OfDownloadStarted; vt != nil { + return (*string)(&vt.DownloadID) + } else if vt := u.OfDownloadCompleted; vt != nil { + return (*string)(&vt.DownloadID) + } else if vt := u.OfDownloadFailed; vt != nil { + return (*string)(&vt.DownloadID) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaBrowserStateChangeUnionParam) GetURL() *string { + if vt := u.OfDownloadStarted; vt != nil { + return (*string)(&vt.URL) + } else if vt := u.OfDownloadCompleted; vt != nil { + return (*string)(&vt.URL) + } else if vt := u.OfDownloadFailed; vt != nil { + return (*string)(&vt.URL) } return nil } func init() { - apijson.RegisterUnion[BetaClearToolUses20250919EditTriggerUnionParam]( + apijson.RegisterUnion[BetaBrowserStateChangeUnionParam]( "type", - apijson.Discriminator[BetaInputTokensTriggerParam]("input_tokens"), - apijson.Discriminator[BetaToolUsesTriggerParam]("tool_uses"), + apijson.Discriminator[BetaBrowserStateChangeTabOpenedParam]("tab_opened"), + apijson.Discriminator[BetaBrowserStateChangeDownloadStartedParam]("download_started"), + apijson.Discriminator[BetaBrowserStateChangeDownloadCompletedParam]("download_completed"), + apijson.Discriminator[BetaBrowserStateChangeDownloadFailedParam]("download_failed"), ) } -type BetaClearToolUses20250919EditResponse struct { - // Number of input tokens cleared by this edit. - ClearedInputTokens int64 `json:"cleared_input_tokens" api:"required"` - // Number of tool uses that were cleared. - ClearedToolUses int64 `json:"cleared_tool_uses" api:"required"` - // The type of context management edit applied. - Type constant.ClearToolUses20250919 `json:"type" default:"clear_tool_uses_20250919"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ClearedInputTokens respjson.Field - ClearedToolUses respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +// A file download that finished during this call, reported with the same +// `download_id` as its `download_started` — or without a prior `download_started`, +// when the download finished during the call that started it (at most one state +// change per `download_id` per result). +// +// The properties DownloadID, Type, URL are required. +type BetaBrowserStateChangeDownloadCompletedParam struct { + // The caller-assigned identifier for this download, stable across the state + // changes reporting it. + DownloadID string `json:"download_id" api:"required"` + // The final post-redirect URL the download was served from. + URL string `json:"url" api:"required"` + // Where the executor saved the file, on the executor's filesystem. Only included + // when another tool in the same environment can read the file at that path. + Path param.Opt[string] `json:"path,omitzero"` + // The completed download's size. + SizeBytes param.Opt[int64] `json:"size_bytes,omitzero"` + // This field can be elided, and will marshal its zero value as + // "download_completed". + Type constant.DownloadCompleted `json:"type" default:"download_completed"` + paramObj } -// Returns the unmodified JSON received from the API -func (r BetaClearToolUses20250919EditResponse) RawJSON() string { return r.JSON.raw } -func (r *BetaClearToolUses20250919EditResponse) UnmarshalJSON(data []byte) error { +func (r BetaBrowserStateChangeDownloadCompletedParam) MarshalJSON() (data []byte, err error) { + type shadow BetaBrowserStateChangeDownloadCompletedParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaBrowserStateChangeDownloadCompletedParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type BetaCodeExecutionOutputBlock struct { - FileID string `json:"file_id" api:"required"` - Type constant.CodeExecutionOutput `json:"type" default:"code_execution_output"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - FileID respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +// A file download that failed — or was cancelled — during this call. +// +// The properties DownloadID, Type, URL are required. +type BetaBrowserStateChangeDownloadFailedParam struct { + // The caller-assigned identifier for this download, stable across the state + // changes reporting it. + DownloadID string `json:"download_id" api:"required"` + // The final post-redirect URL the download was served from. + URL string `json:"url" api:"required"` + // The failure or cancellation detail, when known. + Error param.Opt[string] `json:"error,omitzero"` + // This field can be elided, and will marshal its zero value as "download_failed". + Type constant.DownloadFailed `json:"type" default:"download_failed"` + paramObj } -// Returns the unmodified JSON received from the API -func (r BetaCodeExecutionOutputBlock) RawJSON() string { return r.JSON.raw } -func (r *BetaCodeExecutionOutputBlock) UnmarshalJSON(data []byte) error { +func (r BetaBrowserStateChangeDownloadFailedParam) MarshalJSON() (data []byte, err error) { + type shadow BetaBrowserStateChangeDownloadFailedParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaBrowserStateChangeDownloadFailedParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The properties FileID, Type are required. -type BetaCodeExecutionOutputBlockParam struct { - FileID string `json:"file_id" api:"required"` - // This field can be elided, and will marshal its zero value as - // "code_execution_output". - Type constant.CodeExecutionOutput `json:"type" default:"code_execution_output"` +// A file download that started during this call. +// +// The properties DownloadID, Type, URL are required. +type BetaBrowserStateChangeDownloadStartedParam struct { + // The caller-assigned identifier for this download, stable across the state + // changes reporting it. + DownloadID string `json:"download_id" api:"required"` + // The final post-redirect URL the download was served from. + URL string `json:"url" api:"required"` + // This field can be elided, and will marshal its zero value as "download_started". + Type constant.DownloadStarted `json:"type" default:"download_started"` paramObj } -func (r BetaCodeExecutionOutputBlockParam) MarshalJSON() (data []byte, err error) { - type shadow BetaCodeExecutionOutputBlockParam +func (r BetaBrowserStateChangeDownloadStartedParam) MarshalJSON() (data []byte, err error) { + type shadow BetaBrowserStateChangeDownloadStartedParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *BetaCodeExecutionOutputBlockParam) UnmarshalJSON(data []byte) error { +func (r *BetaBrowserStateChangeDownloadStartedParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type BetaCodeExecutionResultBlock struct { - Content []BetaCodeExecutionOutputBlock `json:"content" api:"required"` - ReturnCode int64 `json:"return_code" api:"required"` - Stderr string `json:"stderr" api:"required"` - Stdout string `json:"stdout" api:"required"` - Type constant.CodeExecutionResult `json:"type" default:"code_execution_result"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Content respjson.Field - ReturnCode respjson.Field - Stderr respjson.Field - Stdout respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +// A tab this call's execution opened that remains open at its end — the creation +// delta of the `tabs` inventory, not an event log. +// +// Carries only the `tab_id`; the tab's `title` and `url` live on its `tabs` entry, +// which must include the same `tab_id`. A tab opened during a failed call gets no +// deferred `tab_opened`; it simply appears in the next result's `tabs` inventory. +// +// The properties TabID, Type are required. +type BetaBrowserStateChangeTabOpenedParam struct { + // The `tab_id` of the opened tab, present in `tabs`. + TabID string `json:"tab_id" api:"required"` + // This field can be elided, and will marshal its zero value as "tab_opened". + Type constant.TabOpened `json:"type" default:"tab_opened"` + paramObj } -// Returns the unmodified JSON received from the API -func (r BetaCodeExecutionResultBlock) RawJSON() string { return r.JSON.raw } -func (r *BetaCodeExecutionResultBlock) UnmarshalJSON(data []byte) error { +func (r BetaBrowserStateChangeTabOpenedParam) MarshalJSON() (data []byte, err error) { + type shadow BetaBrowserStateChangeTabOpenedParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaBrowserStateChangeTabOpenedParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The properties Content, ReturnCode, Stderr, Stdout, Type are required. -type BetaCodeExecutionResultBlockParam struct { - Content []BetaCodeExecutionOutputBlockParam `json:"content,omitzero" api:"required"` - ReturnCode int64 `json:"return_code" api:"required"` - Stderr string `json:"stderr" api:"required"` - Stdout string `json:"stdout" api:"required"` - // This field can be elided, and will marshal its zero value as - // "code_execution_result". - Type constant.CodeExecutionResult `json:"type" default:"code_execution_result"` +// One open browser tab reported in a `browser_state` block's `tabs` inventory. +// +// `tab_id` is the caller-assigned identifier for the tab; `title` and `url` +// describe the page the tab is currently showing and may be empty strings (a blank +// tab legitimately has both empty). `active` marks the tab that is active after +// this call; whenever `tabs` is non-empty, exactly one entry is marked. +// +// The properties TabID, Title, URL are required. +type BetaBrowserStateTabEntryParam struct { + // The caller-assigned identifier for this tab, unique within the inventory. + TabID string `json:"tab_id" api:"required"` + // The title of the page the tab is showing. May be empty. + Title string `json:"title" api:"required"` + // The URL of the page the tab is showing. May be empty. + URL string `json:"url" api:"required"` + // Whether this tab is the active tab after this call. Whenever `tabs` is + // non-empty, exactly one entry is marked `active: true`. + Active param.Opt[bool] `json:"active,omitzero"` paramObj } -func (r BetaCodeExecutionResultBlockParam) MarshalJSON() (data []byte, err error) { - type shadow BetaCodeExecutionResultBlockParam +func (r BetaBrowserStateTabEntryParam) MarshalJSON() (data []byte, err error) { + type shadow BetaBrowserStateTabEntryParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *BetaCodeExecutionResultBlockParam) UnmarshalJSON(data []byte) error { +func (r *BetaBrowserStateTabEntryParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The properties Name, Type are required. -type BetaCodeExecutionTool20250522Param struct { - // If true, tool will not be included in initial system prompt. Only loaded when - // returned via tool_reference from tool search. +// `switch_tab`'s config overrides. +type BetaBrowserSwitchTabConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` - // When true, guarantees schema validation on tool names and inputs - Strict param.Opt[bool] `json:"strict,omitzero"` - // Any of "direct", "code_execution_20250825", "code_execution_20260120". - AllowedCallers []string `json:"allowed_callers,omitzero"` - // Create a cache control breakpoint at this content block. - CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` - // Name of the tool. - // - // This is how the tool will be called by the model and in `tool_use` blocks. - // - // This field can be elided, and will marshal its zero value as "code_execution". - Name constant.CodeExecution `json:"name" default:"code_execution"` - // This field can be elided, and will marshal its zero value as - // "code_execution_20250522". - Type constant.CodeExecution20250522 `json:"type" default:"code_execution_20250522"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` paramObj } -func (r BetaCodeExecutionTool20250522Param) MarshalJSON() (data []byte, err error) { - type shadow BetaCodeExecutionTool20250522Param +func (r BetaBrowserSwitchTabConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaBrowserSwitchTabConfigParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *BetaCodeExecutionTool20250522Param) UnmarshalJSON(data []byte) error { +func (r *BetaBrowserSwitchTabConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The properties Name, Type are required. -type BetaCodeExecutionTool20250825Param struct { - // If true, tool will not be included in initial system prompt. Only loaded when - // returned via tool_reference from tool search. - DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` - // When true, guarantees schema validation on tool names and inputs - Strict param.Opt[bool] `json:"strict,omitzero"` - // Any of "direct", "code_execution_20250825", "code_execution_20260120". +// The browser toolset: a single `tools[]` entry (carrying no `name`) that declares +// the browser tool family. The model is served the family's tool with any members +// disabled via `configs` removed from its schema. +// +// The property Type is required. +type BetaBrowserToolset20260801Param struct { + // Any of "direct", "code_execution_20250825", "code_execution_20260120", + // "code_execution_20260521". AllowedCallers []string `json:"allowed_callers,omitzero"` // Create a cache control breakpoint at this content block. CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` - // Name of the tool. - // - // This is how the tool will be called by the model and in `tool_use` blocks. - // - // This field can be elided, and will marshal its zero value as "code_execution". - Name constant.CodeExecution `json:"name" default:"code_execution"` + // Per-member configuration for `browser_toolset_20260801`: one optional field per + // member tool, keyed by the member name — the same name the member's `tool_use` + // blocks carry. Every member is an accepted key, and a member's defaults apply + // wherever its key is absent. Unknown keys are rejected: the field set is this + // toolset version's complete member set. + Configs BetaBrowserToolsetConfigsParam `json:"configs,omitzero"` // This field can be elided, and will marshal its zero value as - // "code_execution_20250825". - Type constant.CodeExecution20250825 `json:"type" default:"code_execution_20250825"` + // "browser_toolset_20260801". + Type constant.BrowserToolset20260801 `json:"type" default:"browser_toolset_20260801"` paramObj } -func (r BetaCodeExecutionTool20250825Param) MarshalJSON() (data []byte, err error) { - type shadow BetaCodeExecutionTool20250825Param +func (r BetaBrowserToolset20260801Param) MarshalJSON() (data []byte, err error) { + type shadow BetaBrowserToolset20260801Param return param.MarshalObject(r, (*shadow)(&r)) } -func (r *BetaCodeExecutionTool20250825Param) UnmarshalJSON(data []byte) error { +func (r *BetaBrowserToolset20260801Param) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// Code execution tool with REPL state persistence (daemon mode + gVisor -// checkpoint). -// -// The properties Name, Type are required. -type BetaCodeExecutionTool20260120Param struct { - // If true, tool will not be included in initial system prompt. Only loaded when - // returned via tool_reference from tool search. - DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` - // When true, guarantees schema validation on tool names and inputs - Strict param.Opt[bool] `json:"strict,omitzero"` - // Any of "direct", "code_execution_20250825", "code_execution_20260120". - AllowedCallers []string `json:"allowed_callers,omitzero"` - // Create a cache control breakpoint at this content block. - CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` - // Name of the tool. - // - // This is how the tool will be called by the model and in `tool_use` blocks. - // - // This field can be elided, and will marshal its zero value as "code_execution". - Name constant.CodeExecution `json:"name" default:"code_execution"` - // This field can be elided, and will marshal its zero value as - // "code_execution_20260120". - Type constant.CodeExecution20260120 `json:"type" default:"code_execution_20260120"` +// Per-member configuration for `browser_toolset_20260801`: one optional field per +// member tool, keyed by the member name — the same name the member's `tool_use` +// blocks carry. Every member is an accepted key, and a member's defaults apply +// wherever its key is absent. Unknown keys are rejected: the field set is this +// toolset version's complete member set. +type BetaBrowserToolsetConfigsParam struct { + // `close_tab`'s config overrides. + CloseTab BetaBrowserCloseTabConfigParam `json:"close_tab,omitzero"` + // `double_click`'s config overrides. + DoubleClick BetaBrowserDoubleClickConfigParam `json:"double_click,omitzero"` + // `file_upload`'s config overrides. + FileUpload BetaBrowserFileUploadConfigParam `json:"file_upload,omitzero"` + // `find`'s config overrides. + Find BetaBrowserFindConfigParam `json:"find,omitzero"` + // `form_input`'s config overrides. + FormInput BetaBrowserFormInputConfigParam `json:"form_input,omitzero"` + // `get_page_text`'s config overrides. + GetPageText BetaBrowserGetPageTextConfigParam `json:"get_page_text,omitzero"` + // `hold_key`'s config overrides. + HoldKey BetaBrowserHoldKeyConfigParam `json:"hold_key,omitzero"` + // `hover`'s config overrides. + Hover BetaBrowserHoverConfigParam `json:"hover,omitzero"` + // `javascript_exec`'s config overrides. + JavascriptExec BetaBrowserJavascriptExecConfigParam `json:"javascript_exec,omitzero"` + // `key`'s config overrides. + Key BetaBrowserKeyConfigParam `json:"key,omitzero"` + // `left_click`'s config overrides. + LeftClick BetaBrowserLeftClickConfigParam `json:"left_click,omitzero"` + // `left_click_drag`'s config overrides. + LeftClickDrag BetaBrowserLeftClickDragConfigParam `json:"left_click_drag,omitzero"` + // `left_mouse_down`'s config overrides. + LeftMouseDown BetaBrowserLeftMouseDownConfigParam `json:"left_mouse_down,omitzero"` + // `left_mouse_up`'s config overrides. + LeftMouseUp BetaBrowserLeftMouseUpConfigParam `json:"left_mouse_up,omitzero"` + // `list_tabs`'s config overrides. + ListTabs BetaBrowserListTabsConfigParam `json:"list_tabs,omitzero"` + // `middle_click`'s config overrides. + MiddleClick BetaBrowserMiddleClickConfigParam `json:"middle_click,omitzero"` + // `mouse_move`'s config overrides. + MouseMove BetaBrowserMouseMoveConfigParam `json:"mouse_move,omitzero"` + // `navigate`'s config overrides. + Navigate BetaBrowserNavigateConfigParam `json:"navigate,omitzero"` + // `new_tab`'s config overrides. + NewTab BetaBrowserNewTabConfigParam `json:"new_tab,omitzero"` + // `read_console`'s config overrides. + ReadConsole BetaBrowserReadConsoleConfigParam `json:"read_console,omitzero"` + // `read_network`'s config overrides. + ReadNetwork BetaBrowserReadNetworkConfigParam `json:"read_network,omitzero"` + // `read_page`'s config overrides. + ReadPage BetaBrowserReadPageConfigParam `json:"read_page,omitzero"` + // `right_click`'s config overrides. + RightClick BetaBrowserRightClickConfigParam `json:"right_click,omitzero"` + // `screenshot`'s config overrides. + Screenshot BetaBrowserScreenshotConfigParam `json:"screenshot,omitzero"` + // `scroll`'s config overrides. + Scroll BetaBrowserScrollConfigParam `json:"scroll,omitzero"` + // `scroll_to`'s config overrides. + ScrollTo BetaBrowserScrollToConfigParam `json:"scroll_to,omitzero"` + // `switch_tab`'s config overrides. + SwitchTab BetaBrowserSwitchTabConfigParam `json:"switch_tab,omitzero"` + // `triple_click`'s config overrides. + TripleClick BetaBrowserTripleClickConfigParam `json:"triple_click,omitzero"` + // `type`'s config overrides. + Type BetaBrowserTypeConfigParam `json:"type,omitzero"` + // `wait`'s config overrides. + Wait BetaBrowserWaitConfigParam `json:"wait,omitzero"` + // `zoom`'s config overrides. + Zoom BetaBrowserZoomConfigParam `json:"zoom,omitzero"` paramObj } -func (r BetaCodeExecutionTool20260120Param) MarshalJSON() (data []byte, err error) { - type shadow BetaCodeExecutionTool20260120Param +func (r BetaBrowserToolsetConfigsParam) MarshalJSON() (data []byte, err error) { + type shadow BetaBrowserToolsetConfigsParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *BetaCodeExecutionTool20260120Param) UnmarshalJSON(data []byte) error { +func (r *BetaBrowserToolsetConfigsParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type BetaCodeExecutionToolResultBlock struct { - // Code execution result with encrypted stdout for PFC + web_search results. - Content BetaCodeExecutionToolResultBlockContentUnion `json:"content" api:"required"` - ToolUseID string `json:"tool_use_id" api:"required"` - Type constant.CodeExecutionToolResult `json:"type" default:"code_execution_tool_result"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Content respjson.Field - ToolUseID respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +// `triple_click`'s config overrides. +type BetaBrowserTripleClickConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -// Returns the unmodified JSON received from the API -func (r BetaCodeExecutionToolResultBlock) RawJSON() string { return r.JSON.raw } -func (r *BetaCodeExecutionToolResultBlock) UnmarshalJSON(data []byte) error { +func (r BetaBrowserTripleClickConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaBrowserTripleClickConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaBrowserTripleClickConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// BetaCodeExecutionToolResultBlockContentUnion contains all possible properties -// and values from [BetaCodeExecutionToolResultError], -// [BetaCodeExecutionResultBlock], [BetaEncryptedCodeExecutionResultBlock]. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -type BetaCodeExecutionToolResultBlockContentUnion struct { - // This field is from variant [BetaCodeExecutionToolResultError]. - ErrorCode BetaCodeExecutionToolResultErrorCode `json:"error_code"` - Type string `json:"type"` - Content []BetaCodeExecutionOutputBlock `json:"content"` - ReturnCode int64 `json:"return_code"` - Stderr string `json:"stderr"` - // This field is from variant [BetaCodeExecutionResultBlock]. - Stdout string `json:"stdout"` - // This field is from variant [BetaEncryptedCodeExecutionResultBlock]. - EncryptedStdout string `json:"encrypted_stdout"` - JSON struct { - ErrorCode respjson.Field - Type respjson.Field - Content respjson.Field - ReturnCode respjson.Field - Stderr respjson.Field - Stdout respjson.Field - EncryptedStdout respjson.Field - raw string - } `json:"-"` +// `type`'s config overrides. +type BetaBrowserTypeConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -func (u BetaCodeExecutionToolResultBlockContentUnion) AsResponseCodeExecutionToolResultError() (v BetaCodeExecutionToolResultError) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +func (r BetaBrowserTypeConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaBrowserTypeConfigParam + return param.MarshalObject(r, (*shadow)(&r)) } - -func (u BetaCodeExecutionToolResultBlockContentUnion) AsResponseCodeExecutionResultBlock() (v BetaCodeExecutionResultBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +func (r *BetaBrowserTypeConfigParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func (u BetaCodeExecutionToolResultBlockContentUnion) AsResponseEncryptedCodeExecutionResultBlock() (v BetaEncryptedCodeExecutionResultBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +// `wait`'s config overrides. +type BetaBrowserWaitConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -// Returns the unmodified JSON received from the API -func (u BetaCodeExecutionToolResultBlockContentUnion) RawJSON() string { return u.JSON.raw } - -func (r *BetaCodeExecutionToolResultBlockContentUnion) UnmarshalJSON(data []byte) error { +func (r BetaBrowserWaitConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaBrowserWaitConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaBrowserWaitConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The properties Content, ToolUseID, Type are required. -type BetaCodeExecutionToolResultBlockParam struct { - // Code execution result with encrypted stdout for PFC + web_search results. - Content BetaCodeExecutionToolResultBlockParamContentUnion `json:"content,omitzero" api:"required"` - ToolUseID string `json:"tool_use_id" api:"required"` - // Create a cache control breakpoint at this content block. - CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` - // This field can be elided, and will marshal its zero value as - // "code_execution_tool_result". - Type constant.CodeExecutionToolResult `json:"type" default:"code_execution_tool_result"` +// `zoom`'s config overrides. +type BetaBrowserZoomConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` paramObj } -func (r BetaCodeExecutionToolResultBlockParam) MarshalJSON() (data []byte, err error) { - type shadow BetaCodeExecutionToolResultBlockParam +func (r BetaBrowserZoomConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaBrowserZoomConfigParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *BetaCodeExecutionToolResultBlockParam) UnmarshalJSON(data []byte) error { +func (r *BetaBrowserZoomConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -func BetaNewCodeExecutionToolRequestError(errorCode BetaCodeExecutionToolResultErrorCode) BetaCodeExecutionToolResultBlockParamContentUnion { - var variant BetaCodeExecutionToolResultErrorParam - variant.ErrorCode = errorCode - return BetaCodeExecutionToolResultBlockParamContentUnion{OfError: &variant} +func NewBetaCacheControlEphemeralParam() BetaCacheControlEphemeralParam { + return BetaCacheControlEphemeralParam{ + Type: "ephemeral", + } } -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type BetaCodeExecutionToolResultBlockParamContentUnion struct { - OfError *BetaCodeExecutionToolResultErrorParam `json:",omitzero,inline"` - OfResultBlock *BetaCodeExecutionResultBlockParam `json:",omitzero,inline"` - OfRequestEncryptedCodeExecutionResultBlock *BetaEncryptedCodeExecutionResultBlockParam `json:",omitzero,inline"` - paramUnion +// This struct has a constant value, construct it with +// [NewBetaCacheControlEphemeralParam]. +type BetaCacheControlEphemeralParam struct { + // The time-to-live for the cache control breakpoint. + // + // This may be one the following values: + // + // - `5m`: 5 minutes + // - `1h`: 1 hour + // + // Defaults to `5m`. See + // [prompt caching pricing](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) + // for details. + // + // Any of "5m", "1h". + TTL BetaCacheControlEphemeralTTL `json:"ttl,omitzero"` + Type constant.Ephemeral `json:"type" default:"ephemeral"` + paramObj } -func (u BetaCodeExecutionToolResultBlockParamContentUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfError, u.OfResultBlock, u.OfRequestEncryptedCodeExecutionResultBlock) +func (r BetaCacheControlEphemeralParam) MarshalJSON() (data []byte, err error) { + type shadow BetaCacheControlEphemeralParam + return param.MarshalObject(r, (*shadow)(&r)) } -func (u *BetaCodeExecutionToolResultBlockParamContentUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) +func (r *BetaCacheControlEphemeralParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func (u *BetaCodeExecutionToolResultBlockParamContentUnion) asAny() any { - if !param.IsOmitted(u.OfError) { - return u.OfError - } else if !param.IsOmitted(u.OfResultBlock) { - return u.OfResultBlock - } else if !param.IsOmitted(u.OfRequestEncryptedCodeExecutionResultBlock) { - return u.OfRequestEncryptedCodeExecutionResultBlock - } - return nil -} +// The time-to-live for the cache control breakpoint. +// +// This may be one the following values: +// +// - `5m`: 5 minutes +// - `1h`: 1 hour +// +// Defaults to `5m`. See +// [prompt caching pricing](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) +// for details. +type BetaCacheControlEphemeralTTL string -// Returns a pointer to the underlying variant's property, if present. -func (u BetaCodeExecutionToolResultBlockParamContentUnion) GetErrorCode() *string { - if vt := u.OfError; vt != nil { - return (*string)(&vt.ErrorCode) - } - return nil +const ( + BetaCacheControlEphemeralTTLTTL5m BetaCacheControlEphemeralTTL = "5m" + BetaCacheControlEphemeralTTLTTL1h BetaCacheControlEphemeralTTL = "1h" +) + +type BetaCacheCreation struct { + // The number of input tokens used to create the 1 hour cache entry. + Ephemeral1hInputTokens int64 `json:"ephemeral_1h_input_tokens" api:"required"` + // The number of input tokens used to create the 5 minute cache entry. + Ephemeral5mInputTokens int64 `json:"ephemeral_5m_input_tokens" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Ephemeral1hInputTokens respjson.Field + Ephemeral5mInputTokens respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaCodeExecutionToolResultBlockParamContentUnion) GetStdout() *string { - if vt := u.OfResultBlock; vt != nil { - return &vt.Stdout - } - return nil +// Returns the unmodified JSON received from the API +func (r BetaCacheCreation) RawJSON() string { return r.JSON.raw } +func (r *BetaCacheCreation) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaCodeExecutionToolResultBlockParamContentUnion) GetEncryptedStdout() *string { - if vt := u.OfRequestEncryptedCodeExecutionResultBlock; vt != nil { - return &vt.EncryptedStdout - } - return nil +type BetaCacheMissMessagesChanged struct { + // Approximate number of input tokens that would have been read from cache had the + // prefix matched the previous request. + CacheMissedInputTokens int64 `json:"cache_missed_input_tokens" api:"required"` + Type constant.MessagesChanged `json:"type" default:"messages_changed"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + CacheMissedInputTokens respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaCodeExecutionToolResultBlockParamContentUnion) GetType() *string { - if vt := u.OfError; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfResultBlock; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfRequestEncryptedCodeExecutionResultBlock; vt != nil { - return (*string)(&vt.Type) - } - return nil +// Returns the unmodified JSON received from the API +func (r BetaCacheMissMessagesChanged) RawJSON() string { return r.JSON.raw } +func (r *BetaCacheMissMessagesChanged) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaCodeExecutionToolResultBlockParamContentUnion) GetReturnCode() *int64 { - if vt := u.OfResultBlock; vt != nil { - return (*int64)(&vt.ReturnCode) - } else if vt := u.OfRequestEncryptedCodeExecutionResultBlock; vt != nil { - return (*int64)(&vt.ReturnCode) - } - return nil +type BetaCacheMissModelChanged struct { + // Approximate number of input tokens that would have been read from cache had the + // prefix matched the previous request. + CacheMissedInputTokens int64 `json:"cache_missed_input_tokens" api:"required"` + Type constant.ModelChanged `json:"type" default:"model_changed"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + CacheMissedInputTokens respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaCodeExecutionToolResultBlockParamContentUnion) GetStderr() *string { - if vt := u.OfResultBlock; vt != nil { - return (*string)(&vt.Stderr) - } else if vt := u.OfRequestEncryptedCodeExecutionResultBlock; vt != nil { - return (*string)(&vt.Stderr) - } - return nil +// Returns the unmodified JSON received from the API +func (r BetaCacheMissModelChanged) RawJSON() string { return r.JSON.raw } +func (r *BetaCacheMissModelChanged) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns a pointer to the underlying variant's Content property, if present. -func (u BetaCodeExecutionToolResultBlockParamContentUnion) GetContent() []BetaCodeExecutionOutputBlockParam { - if vt := u.OfResultBlock; vt != nil { - return vt.Content - } else if vt := u.OfRequestEncryptedCodeExecutionResultBlock; vt != nil { - return vt.Content - } - return nil -} - -type BetaCodeExecutionToolResultError struct { - // Any of "invalid_tool_input", "unavailable", "too_many_requests", - // "execution_time_exceeded". - ErrorCode BetaCodeExecutionToolResultErrorCode `json:"error_code" api:"required"` - Type constant.CodeExecutionToolResultError `json:"type" default:"code_execution_tool_result_error"` +type BetaCacheMissPreviousMessageNotFound struct { + Type constant.PreviousMessageNotFound `json:"type" default:"previous_message_not_found"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { - ErrorCode respjson.Field Type respjson.Field ExtraFields map[string]respjson.Field raw string @@ -1950,2128 +2070,1822 @@ type BetaCodeExecutionToolResultError struct { } // Returns the unmodified JSON received from the API -func (r BetaCodeExecutionToolResultError) RawJSON() string { return r.JSON.raw } -func (r *BetaCodeExecutionToolResultError) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type BetaCodeExecutionToolResultErrorCode string - -const ( - BetaCodeExecutionToolResultErrorCodeInvalidToolInput BetaCodeExecutionToolResultErrorCode = "invalid_tool_input" - BetaCodeExecutionToolResultErrorCodeUnavailable BetaCodeExecutionToolResultErrorCode = "unavailable" - BetaCodeExecutionToolResultErrorCodeTooManyRequests BetaCodeExecutionToolResultErrorCode = "too_many_requests" - BetaCodeExecutionToolResultErrorCodeExecutionTimeExceeded BetaCodeExecutionToolResultErrorCode = "execution_time_exceeded" -) - -// The properties ErrorCode, Type are required. -type BetaCodeExecutionToolResultErrorParam struct { - // Any of "invalid_tool_input", "unavailable", "too_many_requests", - // "execution_time_exceeded". - ErrorCode BetaCodeExecutionToolResultErrorCode `json:"error_code,omitzero" api:"required"` - // This field can be elided, and will marshal its zero value as - // "code_execution_tool_result_error". - Type constant.CodeExecutionToolResultError `json:"type" default:"code_execution_tool_result_error"` - paramObj -} - -func (r BetaCodeExecutionToolResultErrorParam) MarshalJSON() (data []byte, err error) { - type shadow BetaCodeExecutionToolResultErrorParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaCodeExecutionToolResultErrorParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Automatically compact older context when reaching the configured trigger -// threshold. -// -// The property Type is required. -type BetaCompact20260112EditParam struct { - // Additional instructions for summarization. - Instructions param.Opt[string] `json:"instructions,omitzero"` - // Whether to pause after compaction and return the compaction block to the user. - PauseAfterCompaction param.Opt[bool] `json:"pause_after_compaction,omitzero"` - // When to trigger compaction. Defaults to 150000 input tokens. - Trigger BetaInputTokensTriggerParam `json:"trigger,omitzero"` - // This field can be elided, and will marshal its zero value as "compact_20260112". - Type constant.Compact20260112 `json:"type" default:"compact_20260112"` - paramObj -} - -func (r BetaCompact20260112EditParam) MarshalJSON() (data []byte, err error) { - type shadow BetaCompact20260112EditParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaCompact20260112EditParam) UnmarshalJSON(data []byte) error { +func (r BetaCacheMissPreviousMessageNotFound) RawJSON() string { return r.JSON.raw } +func (r *BetaCacheMissPreviousMessageNotFound) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// A compaction block returned when autocompact is triggered. -// -// When content is None, it indicates the compaction failed to produce a valid -// summary (e.g., malformed output from the model). Clients may round-trip -// compaction blocks with null content; the server treats them as no-ops. -type BetaCompactionBlock struct { - // Summary of compacted content, or null if compaction failed - Content string `json:"content" api:"required"` - // Opaque metadata from prior compaction, to be round-tripped verbatim - EncryptedContent string `json:"encrypted_content" api:"required"` - Type constant.Compaction `json:"type" default:"compaction"` +type BetaCacheMissSystemChanged struct { + // Approximate number of input tokens that would have been read from cache had the + // prefix matched the previous request. + CacheMissedInputTokens int64 `json:"cache_missed_input_tokens" api:"required"` + Type constant.SystemChanged `json:"type" default:"system_changed"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { - Content respjson.Field - EncryptedContent respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string + CacheMissedInputTokens respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string } `json:"-"` } // Returns the unmodified JSON received from the API -func (r BetaCompactionBlock) RawJSON() string { return r.JSON.raw } -func (r *BetaCompactionBlock) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// A compaction block containing summary of previous context. -// -// Users should round-trip these blocks from responses to subsequent requests to -// maintain context across compaction boundaries. -// -// When content is None, the block represents a failed compaction. The server -// treats these as no-ops. Empty string content is not allowed. -// -// The properties Content, Type are required. -type BetaCompactionBlockParam struct { - // Summary of previously compacted content, or null if compaction failed - Content param.Opt[string] `json:"content,omitzero" api:"required"` - // Opaque metadata from prior compaction, to be round-tripped verbatim - EncryptedContent param.Opt[string] `json:"encrypted_content,omitzero"` - // Create a cache control breakpoint at this content block. - CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` - // This field can be elided, and will marshal its zero value as "compaction". - Type constant.Compaction `json:"type" default:"compaction"` - paramObj -} - -func (r BetaCompactionBlockParam) MarshalJSON() (data []byte, err error) { - type shadow BetaCompactionBlockParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaCompactionBlockParam) UnmarshalJSON(data []byte) error { +func (r BetaCacheMissSystemChanged) RawJSON() string { return r.JSON.raw } +func (r *BetaCacheMissSystemChanged) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type BetaCompactionContentBlockDelta struct { - Content string `json:"content" api:"required"` - // Opaque metadata from prior compaction, to be round-tripped verbatim - EncryptedContent string `json:"encrypted_content" api:"required"` - Type constant.CompactionDelta `json:"type" default:"compaction_delta"` +type BetaCacheMissToolsChanged struct { + // Approximate number of input tokens that would have been read from cache had the + // prefix matched the previous request. + CacheMissedInputTokens int64 `json:"cache_missed_input_tokens" api:"required"` + Type constant.ToolsChanged `json:"type" default:"tools_changed"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { - Content respjson.Field - EncryptedContent respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string + CacheMissedInputTokens respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string } `json:"-"` } // Returns the unmodified JSON received from the API -func (r BetaCompactionContentBlockDelta) RawJSON() string { return r.JSON.raw } -func (r *BetaCompactionContentBlockDelta) UnmarshalJSON(data []byte) error { +func (r BetaCacheMissToolsChanged) RawJSON() string { return r.JSON.raw } +func (r *BetaCacheMissToolsChanged) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// Token usage for a compaction iteration. -type BetaCompactionIterationUsage struct { - // Breakdown of cached tokens by TTL - CacheCreation BetaCacheCreation `json:"cache_creation" api:"required"` - // The number of input tokens used to create the cache entry. - CacheCreationInputTokens int64 `json:"cache_creation_input_tokens" api:"required"` - // The number of input tokens read from the cache. - CacheReadInputTokens int64 `json:"cache_read_input_tokens" api:"required"` - // The number of input tokens which were used. - InputTokens int64 `json:"input_tokens" api:"required"` - // The number of output tokens which were used. - OutputTokens int64 `json:"output_tokens" api:"required"` - // Usage for a compaction iteration - Type constant.Compaction `json:"type" default:"compaction"` +type BetaCacheMissUnavailable struct { + Type constant.Unavailable `json:"type" default:"unavailable"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { - CacheCreation respjson.Field - CacheCreationInputTokens respjson.Field - CacheReadInputTokens respjson.Field - InputTokens respjson.Field - OutputTokens respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string } `json:"-"` } // Returns the unmodified JSON received from the API -func (r BetaCompactionIterationUsage) RawJSON() string { return r.JSON.raw } -func (r *BetaCompactionIterationUsage) UnmarshalJSON(data []byte) error { +func (r BetaCacheMissUnavailable) RawJSON() string { return r.JSON.raw } +func (r *BetaCacheMissUnavailable) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// Information about the container used in the request (for the code execution -// tool) -type BetaContainer struct { - // Identifier for the container used in this request - ID string `json:"id" api:"required"` - // The time at which the container will expire. - ExpiresAt time.Time `json:"expires_at" api:"required" format:"date-time"` - // Skills loaded in the container - Skills []BetaSkill `json:"skills" api:"required"` +type BetaCitationCharLocation struct { + CitedText string `json:"cited_text" api:"required"` + DocumentIndex int64 `json:"document_index" api:"required"` + DocumentTitle string `json:"document_title" api:"required"` + EndCharIndex int64 `json:"end_char_index" api:"required"` + FileID string `json:"file_id" api:"required"` + StartCharIndex int64 `json:"start_char_index" api:"required"` + Type constant.CharLocation `json:"type" default:"char_location"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { - ID respjson.Field - ExpiresAt respjson.Field - Skills respjson.Field - ExtraFields map[string]respjson.Field - raw string + CitedText respjson.Field + DocumentIndex respjson.Field + DocumentTitle respjson.Field + EndCharIndex respjson.Field + FileID respjson.Field + StartCharIndex respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string } `json:"-"` } // Returns the unmodified JSON received from the API -func (r BetaContainer) RawJSON() string { return r.JSON.raw } -func (r *BetaContainer) UnmarshalJSON(data []byte) error { +func (r BetaCitationCharLocation) RawJSON() string { return r.JSON.raw } +func (r *BetaCitationCharLocation) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// Container parameters with skills to be loaded. -type BetaContainerParams struct { - // Container id - ID param.Opt[string] `json:"id,omitzero"` - // List of skills to load in the container - Skills []BetaSkillParams `json:"skills,omitzero"` +// The properties CitedText, DocumentIndex, DocumentTitle, EndCharIndex, +// StartCharIndex, Type are required. +type BetaCitationCharLocationParam struct { + DocumentTitle param.Opt[string] `json:"document_title,omitzero" api:"required"` + CitedText string `json:"cited_text" api:"required"` + DocumentIndex int64 `json:"document_index" api:"required"` + EndCharIndex int64 `json:"end_char_index" api:"required"` + StartCharIndex int64 `json:"start_char_index" api:"required"` + // This field can be elided, and will marshal its zero value as "char_location". + Type constant.CharLocation `json:"type" default:"char_location"` paramObj } -func (r BetaContainerParams) MarshalJSON() (data []byte, err error) { - type shadow BetaContainerParams +func (r BetaCitationCharLocationParam) MarshalJSON() (data []byte, err error) { + type shadow BetaCitationCharLocationParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *BetaContainerParams) UnmarshalJSON(data []byte) error { +func (r *BetaCitationCharLocationParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// Response model for a file uploaded to the container. -type BetaContainerUploadBlock struct { - FileID string `json:"file_id" api:"required"` - Type constant.ContainerUpload `json:"type" default:"container_upload"` +type BetaCitationConfig struct { + Enabled bool `json:"enabled" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { - FileID respjson.Field - Type respjson.Field + Enabled respjson.Field ExtraFields map[string]respjson.Field raw string } `json:"-"` } // Returns the unmodified JSON received from the API -func (r BetaContainerUploadBlock) RawJSON() string { return r.JSON.raw } -func (r *BetaContainerUploadBlock) UnmarshalJSON(data []byte) error { +func (r BetaCitationConfig) RawJSON() string { return r.JSON.raw } +func (r *BetaCitationConfig) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// A content block that represents a file to be uploaded to the container Files -// uploaded via this block will be available in the container's input directory. -// -// The properties FileID, Type are required. -type BetaContainerUploadBlockParam struct { - FileID string `json:"file_id" api:"required"` - // Create a cache control breakpoint at this content block. - CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` - // This field can be elided, and will marshal its zero value as "container_upload". - Type constant.ContainerUpload `json:"type" default:"container_upload"` - paramObj +type BetaCitationContentBlockLocation struct { + // The full text of the cited block range, concatenated. + // + // Always equals the contents of `content[start_block_index:end_block_index]` + // joined together. The text block is the minimal citable unit; this field is never + // a substring of a single block. Not counted toward output tokens, and not counted + // toward input tokens when sent back in subsequent turns. + CitedText string `json:"cited_text" api:"required"` + DocumentIndex int64 `json:"document_index" api:"required"` + DocumentTitle string `json:"document_title" api:"required"` + // Exclusive 0-based end index of the cited block range in the source's `content` + // array. + // + // Always greater than `start_block_index`; a single-block citation has + // `end_block_index = start_block_index + 1`. + EndBlockIndex int64 `json:"end_block_index" api:"required"` + FileID string `json:"file_id" api:"required"` + // 0-based index of the first cited block in the source's `content` array. + StartBlockIndex int64 `json:"start_block_index" api:"required"` + Type constant.ContentBlockLocation `json:"type" default:"content_block_location"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + CitedText respjson.Field + DocumentIndex respjson.Field + DocumentTitle respjson.Field + EndBlockIndex respjson.Field + FileID respjson.Field + StartBlockIndex respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` } -func (r BetaContainerUploadBlockParam) MarshalJSON() (data []byte, err error) { - type shadow BetaContainerUploadBlockParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaContainerUploadBlockParam) UnmarshalJSON(data []byte) error { +// Returns the unmodified JSON received from the API +func (r BetaCitationContentBlockLocation) RawJSON() string { return r.JSON.raw } +func (r *BetaCitationContentBlockLocation) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// BetaContentBlockUnion contains all possible properties and values from -// [BetaTextBlock], [BetaThinkingBlock], [BetaRedactedThinkingBlock], -// [BetaToolUseBlock], [BetaServerToolUseBlock], [BetaWebSearchToolResultBlock], -// [BetaWebFetchToolResultBlock], [BetaAdvisorToolResultBlock], -// [BetaCodeExecutionToolResultBlock], [BetaBashCodeExecutionToolResultBlock], -// [BetaTextEditorCodeExecutionToolResultBlock], [BetaToolSearchToolResultBlock], -// [BetaMCPToolUseBlock], [BetaMCPToolResultBlock], [BetaContainerUploadBlock], -// [BetaCompactionBlock]. -// -// Use the [BetaContentBlockUnion.AsAny] method to switch on the variant. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -type BetaContentBlockUnion struct { - // This field is from variant [BetaTextBlock]. - Citations []BetaTextCitationUnion `json:"citations"` - // This field is from variant [BetaTextBlock]. - Text string `json:"text"` - // Any of "text", "thinking", "redacted_thinking", "tool_use", "server_tool_use", - // "web_search_tool_result", "web_fetch_tool_result", "advisor_tool_result", - // "code_execution_tool_result", "bash_code_execution_tool_result", - // "text_editor_code_execution_tool_result", "tool_search_tool_result", - // "mcp_tool_use", "mcp_tool_result", "container_upload", "compaction". - Type string `json:"type"` - // This field is from variant [BetaThinkingBlock]. - Signature string `json:"signature"` - // This field is from variant [BetaThinkingBlock]. - Thinking string `json:"thinking"` - // This field is from variant [BetaRedactedThinkingBlock]. - Data string `json:"data"` - ID string `json:"id"` - // necessary custom code modification - Input json.RawMessage `json:"input"` - Name string `json:"name"` - // This field is a union of [BetaToolUseBlockCallerUnion], - // [BetaServerToolUseBlockCallerUnion], [BetaWebSearchToolResultBlockCallerUnion], - // [BetaWebFetchToolResultBlockCallerUnion] - Caller BetaContentBlockUnionCaller `json:"caller"` - // This field is a union of [BetaWebSearchToolResultBlockContentUnion], - // [BetaWebFetchToolResultBlockContentUnion], - // [BetaAdvisorToolResultBlockContentUnion], - // [BetaCodeExecutionToolResultBlockContentUnion], - // [BetaBashCodeExecutionToolResultBlockContentUnion], - // [BetaTextEditorCodeExecutionToolResultBlockContentUnion], - // [BetaToolSearchToolResultBlockContentUnion], - // [BetaMCPToolResultBlockContentUnion], [string] - Content BetaContentBlockUnionContent `json:"content"` - ToolUseID string `json:"tool_use_id"` - // This field is from variant [BetaMCPToolUseBlock]. - ServerName string `json:"server_name"` - // This field is from variant [BetaMCPToolResultBlock]. - IsError bool `json:"is_error"` - // This field is from variant [BetaContainerUploadBlock]. - FileID string `json:"file_id"` - // This field is from variant [BetaCompactionBlock]. - EncryptedContent string `json:"encrypted_content"` - JSON struct { - Citations respjson.Field - Text respjson.Field - Type respjson.Field - Signature respjson.Field - Thinking respjson.Field - Data respjson.Field - ID respjson.Field - Input respjson.Field - Name respjson.Field - Caller respjson.Field - Content respjson.Field - ToolUseID respjson.Field - ServerName respjson.Field - IsError respjson.Field - FileID respjson.Field - EncryptedContent respjson.Field - raw string - } `json:"-"` +// The properties CitedText, DocumentIndex, DocumentTitle, EndBlockIndex, +// StartBlockIndex, Type are required. +type BetaCitationContentBlockLocationParam struct { + DocumentTitle param.Opt[string] `json:"document_title,omitzero" api:"required"` + // The full text of the cited block range, concatenated. + // + // Always equals the contents of `content[start_block_index:end_block_index]` + // joined together. The text block is the minimal citable unit; this field is never + // a substring of a single block. Not counted toward output tokens, and not counted + // toward input tokens when sent back in subsequent turns. + CitedText string `json:"cited_text" api:"required"` + DocumentIndex int64 `json:"document_index" api:"required"` + // Exclusive 0-based end index of the cited block range in the source's `content` + // array. + // + // Always greater than `start_block_index`; a single-block citation has + // `end_block_index = start_block_index + 1`. + EndBlockIndex int64 `json:"end_block_index" api:"required"` + // 0-based index of the first cited block in the source's `content` array. + StartBlockIndex int64 `json:"start_block_index" api:"required"` + // This field can be elided, and will marshal its zero value as + // "content_block_location". + Type constant.ContentBlockLocation `json:"type" default:"content_block_location"` + paramObj } -// anyBetaContentBlock is implemented by each variant of [BetaContentBlockUnion] to -// add type safety for the return type of [BetaContentBlockUnion.AsAny] -type anyBetaContentBlock interface { - implBetaContentBlockUnion() - toParamUnion() BetaContentBlockParamUnion +func (r BetaCitationContentBlockLocationParam) MarshalJSON() (data []byte, err error) { + type shadow BetaCitationContentBlockLocationParam + return param.MarshalObject(r, (*shadow)(&r)) } - -func (BetaTextBlock) implBetaContentBlockUnion() {} -func (BetaThinkingBlock) implBetaContentBlockUnion() {} -func (BetaRedactedThinkingBlock) implBetaContentBlockUnion() {} -func (BetaToolUseBlock) implBetaContentBlockUnion() {} -func (BetaServerToolUseBlock) implBetaContentBlockUnion() {} -func (BetaWebSearchToolResultBlock) implBetaContentBlockUnion() {} -func (BetaWebFetchToolResultBlock) implBetaContentBlockUnion() {} -func (BetaAdvisorToolResultBlock) implBetaContentBlockUnion() {} -func (BetaCodeExecutionToolResultBlock) implBetaContentBlockUnion() {} -func (BetaBashCodeExecutionToolResultBlock) implBetaContentBlockUnion() {} -func (BetaTextEditorCodeExecutionToolResultBlock) implBetaContentBlockUnion() {} -func (BetaToolSearchToolResultBlock) implBetaContentBlockUnion() {} -func (BetaMCPToolUseBlock) implBetaContentBlockUnion() {} -func (BetaMCPToolResultBlock) implBetaContentBlockUnion() {} -func (BetaContainerUploadBlock) implBetaContentBlockUnion() {} -func (BetaCompactionBlock) implBetaContentBlockUnion() {} - -// Use the following switch statement to find the correct variant -// -// switch variant := BetaContentBlockUnion.AsAny().(type) { -// case anthropic.BetaTextBlock: -// case anthropic.BetaThinkingBlock: -// case anthropic.BetaRedactedThinkingBlock: -// case anthropic.BetaToolUseBlock: -// case anthropic.BetaServerToolUseBlock: -// case anthropic.BetaWebSearchToolResultBlock: -// case anthropic.BetaWebFetchToolResultBlock: -// case anthropic.BetaAdvisorToolResultBlock: -// case anthropic.BetaCodeExecutionToolResultBlock: -// case anthropic.BetaBashCodeExecutionToolResultBlock: -// case anthropic.BetaTextEditorCodeExecutionToolResultBlock: -// case anthropic.BetaToolSearchToolResultBlock: -// case anthropic.BetaMCPToolUseBlock: -// case anthropic.BetaMCPToolResultBlock: -// case anthropic.BetaContainerUploadBlock: -// case anthropic.BetaCompactionBlock: -// default: -// fmt.Errorf("no variant present") -// } -func (u BetaContentBlockUnion) AsAny() anyBetaContentBlock { - switch u.Type { - case "text": - return u.AsText() - case "thinking": - return u.AsThinking() - case "redacted_thinking": - return u.AsRedactedThinking() - case "tool_use": - return u.AsToolUse() - case "server_tool_use": - return u.AsServerToolUse() - case "web_search_tool_result": - return u.AsWebSearchToolResult() - case "web_fetch_tool_result": - return u.AsWebFetchToolResult() - case "advisor_tool_result": - return u.AsAdvisorToolResult() - case "code_execution_tool_result": - return u.AsCodeExecutionToolResult() - case "bash_code_execution_tool_result": - return u.AsBashCodeExecutionToolResult() - case "text_editor_code_execution_tool_result": - return u.AsTextEditorCodeExecutionToolResult() - case "tool_search_tool_result": - return u.AsToolSearchToolResult() - case "mcp_tool_use": - return u.AsMCPToolUse() - case "mcp_tool_result": - return u.AsMCPToolResult() - case "container_upload": - return u.AsContainerUpload() - case "compaction": - return u.AsCompaction() - } - return nil +func (r *BetaCitationContentBlockLocationParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func (u BetaContentBlockUnion) AsText() (v BetaTextBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +type BetaCitationPageLocation struct { + CitedText string `json:"cited_text" api:"required"` + DocumentIndex int64 `json:"document_index" api:"required"` + DocumentTitle string `json:"document_title" api:"required"` + EndPageNumber int64 `json:"end_page_number" api:"required"` + FileID string `json:"file_id" api:"required"` + StartPageNumber int64 `json:"start_page_number" api:"required"` + Type constant.PageLocation `json:"type" default:"page_location"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + CitedText respjson.Field + DocumentIndex respjson.Field + DocumentTitle respjson.Field + EndPageNumber respjson.Field + FileID respjson.Field + StartPageNumber respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` } -func (u BetaContentBlockUnion) AsThinking() (v BetaThinkingBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +// Returns the unmodified JSON received from the API +func (r BetaCitationPageLocation) RawJSON() string { return r.JSON.raw } +func (r *BetaCitationPageLocation) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func (u BetaContentBlockUnion) AsRedactedThinking() (v BetaRedactedThinkingBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +// The properties CitedText, DocumentIndex, DocumentTitle, EndPageNumber, +// StartPageNumber, Type are required. +type BetaCitationPageLocationParam struct { + DocumentTitle param.Opt[string] `json:"document_title,omitzero" api:"required"` + CitedText string `json:"cited_text" api:"required"` + DocumentIndex int64 `json:"document_index" api:"required"` + EndPageNumber int64 `json:"end_page_number" api:"required"` + StartPageNumber int64 `json:"start_page_number" api:"required"` + // This field can be elided, and will marshal its zero value as "page_location". + Type constant.PageLocation `json:"type" default:"page_location"` + paramObj } -func (u BetaContentBlockUnion) AsToolUse() (v BetaToolUseBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +func (r BetaCitationPageLocationParam) MarshalJSON() (data []byte, err error) { + type shadow BetaCitationPageLocationParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaCitationPageLocationParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func (u BetaContentBlockUnion) AsServerToolUse() (v BetaServerToolUseBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +type BetaCitationSearchResultLocation struct { + // The full text of the cited block range, concatenated. + // + // Always equals the contents of `content[start_block_index:end_block_index]` + // joined together. The text block is the minimal citable unit; this field is never + // a substring of a single block. Not counted toward output tokens, and not counted + // toward input tokens when sent back in subsequent turns. + CitedText string `json:"cited_text" api:"required"` + // Exclusive 0-based end index of the cited block range in the source's `content` + // array. + // + // Always greater than `start_block_index`; a single-block citation has + // `end_block_index = start_block_index + 1`. + EndBlockIndex int64 `json:"end_block_index" api:"required"` + // 0-based index of the cited search result among all `search_result` content + // blocks in the request, in the order they appear across messages and tool + // results. + // + // Counted separately from `document_index`; server-side web search results are not + // included in this count. + SearchResultIndex int64 `json:"search_result_index" api:"required"` + Source string `json:"source" api:"required"` + // 0-based index of the first cited block in the source's `content` array. + StartBlockIndex int64 `json:"start_block_index" api:"required"` + Title string `json:"title" api:"required"` + Type constant.SearchResultLocation `json:"type" default:"search_result_location"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + CitedText respjson.Field + EndBlockIndex respjson.Field + SearchResultIndex respjson.Field + Source respjson.Field + StartBlockIndex respjson.Field + Title respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` } -func (u BetaContentBlockUnion) AsWebSearchToolResult() (v BetaWebSearchToolResultBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +// Returns the unmodified JSON received from the API +func (r BetaCitationSearchResultLocation) RawJSON() string { return r.JSON.raw } +func (r *BetaCitationSearchResultLocation) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func (u BetaContentBlockUnion) AsWebFetchToolResult() (v BetaWebFetchToolResultBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +// The properties CitedText, EndBlockIndex, SearchResultIndex, Source, +// StartBlockIndex, Title, Type are required. +type BetaCitationSearchResultLocationParam struct { + Title param.Opt[string] `json:"title,omitzero" api:"required"` + // The full text of the cited block range, concatenated. + // + // Always equals the contents of `content[start_block_index:end_block_index]` + // joined together. The text block is the minimal citable unit; this field is never + // a substring of a single block. Not counted toward output tokens, and not counted + // toward input tokens when sent back in subsequent turns. + CitedText string `json:"cited_text" api:"required"` + // Exclusive 0-based end index of the cited block range in the source's `content` + // array. + // + // Always greater than `start_block_index`; a single-block citation has + // `end_block_index = start_block_index + 1`. + EndBlockIndex int64 `json:"end_block_index" api:"required"` + // 0-based index of the cited search result among all `search_result` content + // blocks in the request, in the order they appear across messages and tool + // results. + // + // Counted separately from `document_index`; server-side web search results are not + // included in this count. + SearchResultIndex int64 `json:"search_result_index" api:"required"` + Source string `json:"source" api:"required"` + // 0-based index of the first cited block in the source's `content` array. + StartBlockIndex int64 `json:"start_block_index" api:"required"` + // This field can be elided, and will marshal its zero value as + // "search_result_location". + Type constant.SearchResultLocation `json:"type" default:"search_result_location"` + paramObj } -func (u BetaContentBlockUnion) AsAdvisorToolResult() (v BetaAdvisorToolResultBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +func (r BetaCitationSearchResultLocationParam) MarshalJSON() (data []byte, err error) { + type shadow BetaCitationSearchResultLocationParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaCitationSearchResultLocationParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func (u BetaContentBlockUnion) AsCodeExecutionToolResult() (v BetaCodeExecutionToolResultBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +// The properties CitedText, EncryptedIndex, Title, Type, URL are required. +type BetaCitationWebSearchResultLocationParam struct { + Title param.Opt[string] `json:"title,omitzero" api:"required"` + CitedText string `json:"cited_text" api:"required"` + EncryptedIndex string `json:"encrypted_index" api:"required"` + URL string `json:"url" api:"required"` + // This field can be elided, and will marshal its zero value as + // "web_search_result_location". + Type constant.WebSearchResultLocation `json:"type" default:"web_search_result_location"` + paramObj } -func (u BetaContentBlockUnion) AsBashCodeExecutionToolResult() (v BetaBashCodeExecutionToolResultBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +func (r BetaCitationWebSearchResultLocationParam) MarshalJSON() (data []byte, err error) { + type shadow BetaCitationWebSearchResultLocationParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaCitationWebSearchResultLocationParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func (u BetaContentBlockUnion) AsTextEditorCodeExecutionToolResult() (v BetaTextEditorCodeExecutionToolResultBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +type BetaCitationsConfigParam struct { + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -func (u BetaContentBlockUnion) AsToolSearchToolResult() (v BetaToolSearchToolResultBlock) { +func (r BetaCitationsConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaCitationsConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaCitationsConfigParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaCitationsDelta struct { + Citation BetaCitationsDeltaCitationUnion `json:"citation" api:"required"` + Type constant.CitationsDelta `json:"type" default:"citations_delta"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Citation respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaCitationsDelta) RawJSON() string { return r.JSON.raw } +func (r *BetaCitationsDelta) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaCitationsDeltaCitationUnion contains all possible properties and values from +// [BetaCitationCharLocation], [BetaCitationPageLocation], +// [BetaCitationContentBlockLocation], [BetaCitationsWebSearchResultLocation], +// [BetaCitationSearchResultLocation]. +// +// Use the [BetaCitationsDeltaCitationUnion.AsAny] method to switch on the variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaCitationsDeltaCitationUnion struct { + CitedText string `json:"cited_text"` + DocumentIndex int64 `json:"document_index"` + DocumentTitle string `json:"document_title"` + // This field is from variant [BetaCitationCharLocation]. + EndCharIndex int64 `json:"end_char_index"` + FileID string `json:"file_id"` + // This field is from variant [BetaCitationCharLocation]. + StartCharIndex int64 `json:"start_char_index"` + // Any of "char_location", "page_location", "content_block_location", + // "web_search_result_location", "search_result_location". + Type string `json:"type"` + // This field is from variant [BetaCitationPageLocation]. + EndPageNumber int64 `json:"end_page_number"` + // This field is from variant [BetaCitationPageLocation]. + StartPageNumber int64 `json:"start_page_number"` + EndBlockIndex int64 `json:"end_block_index"` + StartBlockIndex int64 `json:"start_block_index"` + // This field is from variant [BetaCitationsWebSearchResultLocation]. + EncryptedIndex string `json:"encrypted_index"` + Title string `json:"title"` + // This field is from variant [BetaCitationsWebSearchResultLocation]. + URL string `json:"url"` + // This field is from variant [BetaCitationSearchResultLocation]. + SearchResultIndex int64 `json:"search_result_index"` + // This field is from variant [BetaCitationSearchResultLocation]. + Source string `json:"source"` + JSON struct { + CitedText respjson.Field + DocumentIndex respjson.Field + DocumentTitle respjson.Field + EndCharIndex respjson.Field + FileID respjson.Field + StartCharIndex respjson.Field + Type respjson.Field + EndPageNumber respjson.Field + StartPageNumber respjson.Field + EndBlockIndex respjson.Field + StartBlockIndex respjson.Field + EncryptedIndex respjson.Field + Title respjson.Field + URL respjson.Field + SearchResultIndex respjson.Field + Source respjson.Field + raw string + } `json:"-"` +} + +// anyBetaCitationsDeltaCitation is implemented by each variant of +// [BetaCitationsDeltaCitationUnion] to add type safety for the return type of +// [BetaCitationsDeltaCitationUnion.AsAny] +type anyBetaCitationsDeltaCitation interface { + implBetaCitationsDeltaCitationUnion() +} + +func (BetaCitationCharLocation) implBetaCitationsDeltaCitationUnion() {} +func (BetaCitationPageLocation) implBetaCitationsDeltaCitationUnion() {} +func (BetaCitationContentBlockLocation) implBetaCitationsDeltaCitationUnion() {} +func (BetaCitationsWebSearchResultLocation) implBetaCitationsDeltaCitationUnion() {} +func (BetaCitationSearchResultLocation) implBetaCitationsDeltaCitationUnion() {} + +// Use the following switch statement to find the correct variant +// +// switch variant := BetaCitationsDeltaCitationUnion.AsAny().(type) { +// case anthropic.BetaCitationCharLocation: +// case anthropic.BetaCitationPageLocation: +// case anthropic.BetaCitationContentBlockLocation: +// case anthropic.BetaCitationsWebSearchResultLocation: +// case anthropic.BetaCitationSearchResultLocation: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaCitationsDeltaCitationUnion) AsAny() anyBetaCitationsDeltaCitation { + switch u.Type { + case "char_location": + return u.AsCharLocation() + case "page_location": + return u.AsPageLocation() + case "content_block_location": + return u.AsContentBlockLocation() + case "web_search_result_location": + return u.AsWebSearchResultLocation() + case "search_result_location": + return u.AsSearchResultLocation() + } + return nil +} + +func (u BetaCitationsDeltaCitationUnion) AsCharLocation() (v BetaCitationCharLocation) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return } -func (u BetaContentBlockUnion) AsMCPToolUse() (v BetaMCPToolUseBlock) { +func (u BetaCitationsDeltaCitationUnion) AsPageLocation() (v BetaCitationPageLocation) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return } -func (u BetaContentBlockUnion) AsMCPToolResult() (v BetaMCPToolResultBlock) { +func (u BetaCitationsDeltaCitationUnion) AsContentBlockLocation() (v BetaCitationContentBlockLocation) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return } -func (u BetaContentBlockUnion) AsContainerUpload() (v BetaContainerUploadBlock) { +func (u BetaCitationsDeltaCitationUnion) AsWebSearchResultLocation() (v BetaCitationsWebSearchResultLocation) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return } -func (u BetaContentBlockUnion) AsCompaction() (v BetaCompactionBlock) { +func (u BetaCitationsDeltaCitationUnion) AsSearchResultLocation() (v BetaCitationSearchResultLocation) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return } // Returns the unmodified JSON received from the API -func (u BetaContentBlockUnion) RawJSON() string { return u.JSON.raw } +func (u BetaCitationsDeltaCitationUnion) RawJSON() string { return u.JSON.raw } -func (r *BetaContentBlockUnion) UnmarshalJSON(data []byte) error { +func (r *BetaCitationsDeltaCitationUnion) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// BetaContentBlockUnionCaller is an implicit subunion of [BetaContentBlockUnion]. -// BetaContentBlockUnionCaller provides convenient access to the sub-properties of -// the union. -// -// For type safety it is recommended to directly use a variant of the -// [BetaContentBlockUnion]. -type BetaContentBlockUnionCaller struct { - Type string `json:"type"` - ToolID string `json:"tool_id"` - JSON struct { - Type respjson.Field - ToolID respjson.Field - raw string +type BetaCitationsWebSearchResultLocation struct { + CitedText string `json:"cited_text" api:"required"` + EncryptedIndex string `json:"encrypted_index" api:"required"` + Title string `json:"title" api:"required"` + Type constant.WebSearchResultLocation `json:"type" default:"web_search_result_location"` + URL string `json:"url" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + CitedText respjson.Field + EncryptedIndex respjson.Field + Title respjson.Field + Type respjson.Field + URL respjson.Field + ExtraFields map[string]respjson.Field + raw string } `json:"-"` } -func (r *BetaContentBlockUnionCaller) UnmarshalJSON(data []byte) error { +// Returns the unmodified JSON received from the API +func (r BetaCitationsWebSearchResultLocation) RawJSON() string { return r.JSON.raw } +func (r *BetaCitationsWebSearchResultLocation) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// BetaContentBlockUnionContent is an implicit subunion of [BetaContentBlockUnion]. -// BetaContentBlockUnionContent provides convenient access to the sub-properties of -// the union. -// -// For type safety it is recommended to directly use a variant of the -// [BetaContentBlockUnion]. +// The property Type is required. +type BetaClearThinking20251015EditParam struct { + // Number of most recent assistant turns to keep thinking blocks for. Older turns + // will have their thinking blocks removed. + Keep BetaClearThinking20251015EditKeepUnionParam `json:"keep,omitzero"` + // This field can be elided, and will marshal its zero value as + // "clear_thinking_20251015". + Type constant.ClearThinking20251015 `json:"type" default:"clear_thinking_20251015"` + paramObj +} + +func (r BetaClearThinking20251015EditParam) MarshalJSON() (data []byte, err error) { + type shadow BetaClearThinking20251015EditParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaClearThinking20251015EditParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Only one field can be non-zero. // -// If the underlying value is not a json object, one of the following properties -// will be valid: OfBetaWebSearchResultBlockArray OfString -// OfBetaMCPToolResultBlockContent] -type BetaContentBlockUnionContent struct { - // This field will be present if the value is a [[]BetaWebSearchResultBlock] - // instead of an object. - OfBetaWebSearchResultBlockArray []BetaWebSearchResultBlock `json:",inline"` - // This field will be present if the value is a [string] instead of an object. - OfString string `json:",inline"` - // This field will be present if the value is a [[]BetaTextBlock] instead of an - // object. - OfBetaMCPToolResultBlockContent []BetaTextBlock `json:",inline"` - ErrorCode string `json:"error_code"` - Type string `json:"type"` - // This field is a union of [BetaDocumentBlock], [[]BetaCodeExecutionOutputBlock], - // [[]BetaCodeExecutionOutputBlock], [[]BetaBashCodeExecutionOutputBlock], [string] - Content BetaContentBlockUnionContentContent `json:"content"` - // This field is from variant [BetaWebFetchToolResultBlockContentUnion]. - RetrievedAt string `json:"retrieved_at"` - // This field is from variant [BetaWebFetchToolResultBlockContentUnion]. - URL string `json:"url"` - // This field is from variant [BetaAdvisorToolResultBlockContentUnion]. - Text string `json:"text"` - // This field is from variant [BetaAdvisorToolResultBlockContentUnion]. - EncryptedContent string `json:"encrypted_content"` - ReturnCode int64 `json:"return_code"` - Stderr string `json:"stderr"` - Stdout string `json:"stdout"` - // This field is from variant [BetaCodeExecutionToolResultBlockContentUnion]. - EncryptedStdout string `json:"encrypted_stdout"` - ErrorMessage string `json:"error_message"` - // This field is from variant - // [BetaTextEditorCodeExecutionToolResultBlockContentUnion]. - FileType BetaTextEditorCodeExecutionViewResultBlockFileType `json:"file_type"` - // This field is from variant - // [BetaTextEditorCodeExecutionToolResultBlockContentUnion]. - NumLines int64 `json:"num_lines"` - // This field is from variant - // [BetaTextEditorCodeExecutionToolResultBlockContentUnion]. - StartLine int64 `json:"start_line"` - // This field is from variant - // [BetaTextEditorCodeExecutionToolResultBlockContentUnion]. - TotalLines int64 `json:"total_lines"` - // This field is from variant - // [BetaTextEditorCodeExecutionToolResultBlockContentUnion]. - IsFileUpdate bool `json:"is_file_update"` - // This field is from variant - // [BetaTextEditorCodeExecutionToolResultBlockContentUnion]. - Lines []string `json:"lines"` - // This field is from variant - // [BetaTextEditorCodeExecutionToolResultBlockContentUnion]. - NewLines int64 `json:"new_lines"` - // This field is from variant - // [BetaTextEditorCodeExecutionToolResultBlockContentUnion]. - NewStart int64 `json:"new_start"` - // This field is from variant - // [BetaTextEditorCodeExecutionToolResultBlockContentUnion]. - OldLines int64 `json:"old_lines"` - // This field is from variant - // [BetaTextEditorCodeExecutionToolResultBlockContentUnion]. - OldStart int64 `json:"old_start"` - // This field is from variant [BetaToolSearchToolResultBlockContentUnion]. - ToolReferences []BetaToolReferenceBlock `json:"tool_references"` - JSON struct { - OfBetaWebSearchResultBlockArray respjson.Field - OfString respjson.Field - OfBetaMCPToolResultBlockContent respjson.Field - ErrorCode respjson.Field - Type respjson.Field - Content respjson.Field - RetrievedAt respjson.Field - URL respjson.Field - Text respjson.Field - EncryptedContent respjson.Field - ReturnCode respjson.Field - Stderr respjson.Field - Stdout respjson.Field - EncryptedStdout respjson.Field - ErrorMessage respjson.Field - FileType respjson.Field - NumLines respjson.Field - StartLine respjson.Field - TotalLines respjson.Field - IsFileUpdate respjson.Field - Lines respjson.Field - NewLines respjson.Field - NewStart respjson.Field - OldLines respjson.Field - OldStart respjson.Field - ToolReferences respjson.Field - raw string - } `json:"-"` -} - -func (r *BetaContentBlockUnionContent) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +// Use [param.IsOmitted] to confirm if a field is set. +type BetaClearThinking20251015EditKeepUnionParam struct { + OfThinkingTurns *BetaThinkingTurnsParam `json:",omitzero,inline"` + OfAllThinkingTurns *BetaAllThinkingTurnsParam `json:",omitzero,inline"` + // Construct this variant with constant.ValueOf[constant.All]() + OfAll constant.All `json:",omitzero,inline"` + paramUnion } -// BetaContentBlockUnionContentContent is an implicit subunion of -// [BetaContentBlockUnion]. BetaContentBlockUnionContentContent provides convenient -// access to the sub-properties of the union. -// -// For type safety it is recommended to directly use a variant of the -// [BetaContentBlockUnion]. -// -// If the underlying value is not a json object, one of the following properties -// will be valid: OfContent OfString] -type BetaContentBlockUnionContentContent struct { - // This field will be present if the value is a [[]BetaCodeExecutionOutputBlock] - // instead of an object. - OfContent []BetaCodeExecutionOutputBlock `json:",inline"` - // This field will be present if the value is a [string] instead of an object. - OfString string `json:",inline"` - // This field is from variant [BetaDocumentBlock]. - Citations BetaCitationConfig `json:"citations"` - // This field is from variant [BetaDocumentBlock]. - Source BetaDocumentBlockSourceUnion `json:"source"` - // This field is from variant [BetaDocumentBlock]. - Title string `json:"title"` - // This field is from variant [BetaDocumentBlock]. - Type constant.Document `json:"type"` - JSON struct { - OfContent respjson.Field - OfString respjson.Field - Citations respjson.Field - Source respjson.Field - Title respjson.Field - Type respjson.Field - raw string - } `json:"-"` +func (u BetaClearThinking20251015EditKeepUnionParam) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfThinkingTurns, u.OfAllThinkingTurns, u.OfAll) } - -func (r *BetaContentBlockUnionContentContent) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +func (u *BetaClearThinking20251015EditKeepUnionParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) } -func NewBetaTextBlock(text string) BetaContentBlockParamUnion { - var variant BetaTextBlockParam - variant.Text = text - return BetaContentBlockParamUnion{OfText: &variant} +func (u *BetaClearThinking20251015EditKeepUnionParam) asAny() any { + if !param.IsOmitted(u.OfThinkingTurns) { + return u.OfThinkingTurns + } else if !param.IsOmitted(u.OfAllThinkingTurns) { + return u.OfAllThinkingTurns + } else if !param.IsOmitted(u.OfAll) { + return &u.OfAll + } + return nil } -func NewBetaImageBlock[ - T BetaBase64ImageSourceParam | BetaURLImageSourceParam | BetaFileImageSourceParam, -](source T) BetaContentBlockParamUnion { - var image BetaImageBlockParam - switch v := any(source).(type) { - case BetaBase64ImageSourceParam: - image.Source.OfBase64 = &v - case BetaURLImageSourceParam: - image.Source.OfURL = &v - case BetaFileImageSourceParam: - image.Source.OfFile = &v +// Returns a pointer to the underlying variant's property, if present. +func (u BetaClearThinking20251015EditKeepUnionParam) GetValue() *int64 { + if vt := u.OfThinkingTurns; vt != nil { + return &vt.Value } - return BetaContentBlockParamUnion{OfImage: &image} + return nil } -func NewBetaDocumentBlock[ - T BetaBase64PDFSourceParam | BetaPlainTextSourceParam | BetaContentBlockSourceParam | BetaURLPDFSourceParam | BetaFileDocumentSourceParam, -](source T) BetaContentBlockParamUnion { - var document BetaRequestDocumentBlockParam - switch v := any(source).(type) { - case BetaBase64PDFSourceParam: - document.Source.OfBase64 = &v - case BetaPlainTextSourceParam: - document.Source.OfText = &v - case BetaContentBlockSourceParam: - document.Source.OfContent = &v - case BetaURLPDFSourceParam: - document.Source.OfURL = &v - case BetaFileDocumentSourceParam: - document.Source.OfFile = &v +// Returns a pointer to the underlying variant's property, if present. +func (u BetaClearThinking20251015EditKeepUnionParam) GetType() *string { + if vt := u.OfThinkingTurns; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfAllThinkingTurns; vt != nil { + return (*string)(&vt.Type) } - return BetaContentBlockParamUnion{OfDocument: &document} + return nil } -func NewBetaSearchResultBlock(content []BetaTextBlockParam, source string, title string) BetaContentBlockParamUnion { - var searchResult BetaSearchResultBlockParam - searchResult.Content = content - searchResult.Source = source - searchResult.Title = title - return BetaContentBlockParamUnion{OfSearchResult: &searchResult} +type BetaClearThinking20251015EditResponse struct { + // Number of input tokens cleared by this edit. + ClearedInputTokens int64 `json:"cleared_input_tokens" api:"required"` + // Number of thinking turns that were cleared. + ClearedThinkingTurns int64 `json:"cleared_thinking_turns" api:"required"` + // The type of context management edit applied. + Type constant.ClearThinking20251015 `json:"type" default:"clear_thinking_20251015"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ClearedInputTokens respjson.Field + ClearedThinkingTurns respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` } -func NewBetaThinkingBlock(signature string, thinking string) BetaContentBlockParamUnion { - var variant BetaThinkingBlockParam - variant.Signature = signature - variant.Thinking = thinking - return BetaContentBlockParamUnion{OfThinking: &variant} +// Returns the unmodified JSON received from the API +func (r BetaClearThinking20251015EditResponse) RawJSON() string { return r.JSON.raw } +func (r *BetaClearThinking20251015EditResponse) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func NewBetaRedactedThinkingBlock(data string) BetaContentBlockParamUnion { - var redactedThinking BetaRedactedThinkingBlockParam - redactedThinking.Data = data - return BetaContentBlockParamUnion{OfRedactedThinking: &redactedThinking} +// The property Type is required. +type BetaClearToolUses20250919EditParam struct { + // Whether to clear all tool inputs (bool) or specific tool inputs to clear (list) + ClearToolInputs BetaClearToolUses20250919EditClearToolInputsUnionParam `json:"clear_tool_inputs,omitzero"` + // Tool names whose uses are preserved from clearing + ExcludeTools []string `json:"exclude_tools,omitzero"` + // Minimum number of tokens that must be cleared when triggered. Context will only + // be modified if at least this many tokens can be removed. + ClearAtLeast BetaInputTokensClearAtLeastParam `json:"clear_at_least,omitzero"` + // Number of tool uses to retain in the conversation + Keep BetaToolUsesKeepParam `json:"keep,omitzero"` + // Condition that triggers the context management strategy + Trigger BetaClearToolUses20250919EditTriggerUnionParam `json:"trigger,omitzero"` + // This field can be elided, and will marshal its zero value as + // "clear_tool_uses_20250919". + Type constant.ClearToolUses20250919 `json:"type" default:"clear_tool_uses_20250919"` + paramObj } -func NewBetaToolUseBlock(id string, input any, name string) BetaContentBlockParamUnion { - var toolUse BetaToolUseBlockParam - toolUse.ID = id - toolUse.Input = input - toolUse.Name = name - return BetaContentBlockParamUnion{OfToolUse: &toolUse} +func (r BetaClearToolUses20250919EditParam) MarshalJSON() (data []byte, err error) { + type shadow BetaClearToolUses20250919EditParam + return param.MarshalObject(r, (*shadow)(&r)) } - -func NewBetaToolResultBlock(toolUseID string, content string, isError bool) BetaContentBlockParamUnion { - var toolBlock BetaToolResultBlockParam - toolBlock.ToolUseID = toolUseID - toolBlock.Content = []BetaToolResultBlockParamContentUnion{ - {OfText: &BetaTextBlockParam{Text: content}}, - } - toolBlock.IsError = Bool(isError) - return BetaContentBlockParamUnion{OfToolResult: &toolBlock} +func (r *BetaClearToolUses20250919EditParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func NewBetaServerToolUseBlock(id string, input any, name BetaServerToolUseBlockParamName) BetaContentBlockParamUnion { - var serverToolUse BetaServerToolUseBlockParam - serverToolUse.ID = id - serverToolUse.Input = input - serverToolUse.Name = name - return BetaContentBlockParamUnion{OfServerToolUse: &serverToolUse} -} - -func NewBetaWebSearchToolResultBlock[ - T []BetaWebSearchResultBlockParam | BetaWebSearchToolRequestErrorParam, -](content T, toolUseID string) BetaContentBlockParamUnion { - var webSearchToolResult BetaWebSearchToolResultBlockParam - switch v := any(content).(type) { - case []BetaWebSearchResultBlockParam: - webSearchToolResult.Content.OfResultBlock = v - case BetaWebSearchToolRequestErrorParam: - webSearchToolResult.Content.OfError = &v - } - webSearchToolResult.ToolUseID = toolUseID - return BetaContentBlockParamUnion{OfWebSearchToolResult: &webSearchToolResult} -} - -func NewBetaWebFetchToolResultBlock[ - T BetaWebFetchToolResultErrorBlockParam | BetaWebFetchBlockParam, -](content T, toolUseID string) BetaContentBlockParamUnion { - var webFetchToolResult BetaWebFetchToolResultBlockParam - switch v := any(content).(type) { - case BetaWebFetchToolResultErrorBlockParam: - webFetchToolResult.Content.OfRequestWebFetchToolResultError = &v - case BetaWebFetchBlockParam: - webFetchToolResult.Content.OfRequestWebFetchResultBlock = &v - } - webFetchToolResult.ToolUseID = toolUseID - return BetaContentBlockParamUnion{OfWebFetchToolResult: &webFetchToolResult} -} - -func NewBetaAdvisorToolResultBlock[ - T BetaAdvisorToolResultErrorParam | BetaAdvisorResultBlockParam | BetaAdvisorRedactedResultBlockParam, -](content T, toolUseID string) BetaContentBlockParamUnion { - var advisorToolResult BetaAdvisorToolResultBlockParam - switch v := any(content).(type) { - case BetaAdvisorToolResultErrorParam: - advisorToolResult.Content.OfRequestAdvisorToolResultError = &v - case BetaAdvisorResultBlockParam: - advisorToolResult.Content.OfRequestAdvisorResultBlock = &v - case BetaAdvisorRedactedResultBlockParam: - advisorToolResult.Content.OfRequestAdvisorRedactedResultBlock = &v - } - advisorToolResult.ToolUseID = toolUseID - return BetaContentBlockParamUnion{OfAdvisorToolResult: &advisorToolResult} -} - -func NewBetaCodeExecutionToolResultBlock[ - T BetaCodeExecutionToolResultErrorParam | BetaCodeExecutionResultBlockParam | BetaEncryptedCodeExecutionResultBlockParam, -](content T, toolUseID string) BetaContentBlockParamUnion { - var codeExecutionToolResult BetaCodeExecutionToolResultBlockParam - switch v := any(content).(type) { - case BetaCodeExecutionToolResultErrorParam: - codeExecutionToolResult.Content.OfError = &v - case BetaCodeExecutionResultBlockParam: - codeExecutionToolResult.Content.OfResultBlock = &v - case BetaEncryptedCodeExecutionResultBlockParam: - codeExecutionToolResult.Content.OfRequestEncryptedCodeExecutionResultBlock = &v - } - codeExecutionToolResult.ToolUseID = toolUseID - return BetaContentBlockParamUnion{OfCodeExecutionToolResult: &codeExecutionToolResult} +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaClearToolUses20250919EditClearToolInputsUnionParam struct { + OfBool param.Opt[bool] `json:",omitzero,inline"` + OfStringArray []string `json:",omitzero,inline"` + paramUnion } -func NewBetaBashCodeExecutionToolResultBlock[ - T BetaBashCodeExecutionToolResultErrorParam | BetaBashCodeExecutionResultBlockParam, -](content T, toolUseID string) BetaContentBlockParamUnion { - var bashCodeExecutionToolResult BetaBashCodeExecutionToolResultBlockParam - switch v := any(content).(type) { - case BetaBashCodeExecutionToolResultErrorParam: - bashCodeExecutionToolResult.Content.OfRequestBashCodeExecutionToolResultError = &v - case BetaBashCodeExecutionResultBlockParam: - bashCodeExecutionToolResult.Content.OfRequestBashCodeExecutionResultBlock = &v - } - bashCodeExecutionToolResult.ToolUseID = toolUseID - return BetaContentBlockParamUnion{OfBashCodeExecutionToolResult: &bashCodeExecutionToolResult} +func (u BetaClearToolUses20250919EditClearToolInputsUnionParam) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfBool, u.OfStringArray) } - -func NewBetaTextEditorCodeExecutionToolResultBlock[ - T BetaTextEditorCodeExecutionToolResultErrorParam | BetaTextEditorCodeExecutionViewResultBlockParam | BetaTextEditorCodeExecutionCreateResultBlockParam | BetaTextEditorCodeExecutionStrReplaceResultBlockParam, -](content T, toolUseID string) BetaContentBlockParamUnion { - var textEditorCodeExecutionToolResult BetaTextEditorCodeExecutionToolResultBlockParam - switch v := any(content).(type) { - case BetaTextEditorCodeExecutionToolResultErrorParam: - textEditorCodeExecutionToolResult.Content.OfRequestTextEditorCodeExecutionToolResultError = &v - case BetaTextEditorCodeExecutionViewResultBlockParam: - textEditorCodeExecutionToolResult.Content.OfRequestTextEditorCodeExecutionViewResultBlock = &v - case BetaTextEditorCodeExecutionCreateResultBlockParam: - textEditorCodeExecutionToolResult.Content.OfRequestTextEditorCodeExecutionCreateResultBlock = &v - case BetaTextEditorCodeExecutionStrReplaceResultBlockParam: - textEditorCodeExecutionToolResult.Content.OfRequestTextEditorCodeExecutionStrReplaceResultBlock = &v - } - textEditorCodeExecutionToolResult.ToolUseID = toolUseID - return BetaContentBlockParamUnion{OfTextEditorCodeExecutionToolResult: &textEditorCodeExecutionToolResult} +func (u *BetaClearToolUses20250919EditClearToolInputsUnionParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) } -func NewBetaToolSearchToolResultBlock[ - T BetaToolSearchToolResultErrorParam | BetaToolSearchToolSearchResultBlockParam, -](content T, toolUseID string) BetaContentBlockParamUnion { - var toolSearchToolResult BetaToolSearchToolResultBlockParam - switch v := any(content).(type) { - case BetaToolSearchToolResultErrorParam: - toolSearchToolResult.Content.OfRequestToolSearchToolResultError = &v - case BetaToolSearchToolSearchResultBlockParam: - toolSearchToolResult.Content.OfRequestToolSearchToolSearchResultBlock = &v +func (u *BetaClearToolUses20250919EditClearToolInputsUnionParam) asAny() any { + if !param.IsOmitted(u.OfBool) { + return &u.OfBool.Value + } else if !param.IsOmitted(u.OfStringArray) { + return &u.OfStringArray } - toolSearchToolResult.ToolUseID = toolUseID - return BetaContentBlockParamUnion{OfToolSearchToolResult: &toolSearchToolResult} -} - -func NewBetaMCPToolResultBlock(toolUseID string) BetaContentBlockParamUnion { - var mcpToolResult BetaRequestMCPToolResultBlockParam - mcpToolResult.ToolUseID = toolUseID - return BetaContentBlockParamUnion{OfMCPToolResult: &mcpToolResult} -} - -func NewBetaContainerUploadBlock(fileID string) BetaContentBlockParamUnion { - var containerUpload BetaContainerUploadBlockParam - containerUpload.FileID = fileID - return BetaContentBlockParamUnion{OfContainerUpload: &containerUpload} -} - -func NewBetaCompactionBlock(content string) BetaContentBlockParamUnion { - var compaction BetaCompactionBlockParam - compaction.Content = param.NewOpt(content) - return BetaContentBlockParamUnion{OfCompaction: &compaction} + return nil } // Only one field can be non-zero. // // Use [param.IsOmitted] to confirm if a field is set. -type BetaContentBlockParamUnion struct { - OfText *BetaTextBlockParam `json:",omitzero,inline"` - OfImage *BetaImageBlockParam `json:",omitzero,inline"` - OfDocument *BetaRequestDocumentBlockParam `json:",omitzero,inline"` - OfSearchResult *BetaSearchResultBlockParam `json:",omitzero,inline"` - OfThinking *BetaThinkingBlockParam `json:",omitzero,inline"` - OfRedactedThinking *BetaRedactedThinkingBlockParam `json:",omitzero,inline"` - OfToolUse *BetaToolUseBlockParam `json:",omitzero,inline"` - OfToolResult *BetaToolResultBlockParam `json:",omitzero,inline"` - OfServerToolUse *BetaServerToolUseBlockParam `json:",omitzero,inline"` - OfWebSearchToolResult *BetaWebSearchToolResultBlockParam `json:",omitzero,inline"` - OfWebFetchToolResult *BetaWebFetchToolResultBlockParam `json:",omitzero,inline"` - OfAdvisorToolResult *BetaAdvisorToolResultBlockParam `json:",omitzero,inline"` - OfCodeExecutionToolResult *BetaCodeExecutionToolResultBlockParam `json:",omitzero,inline"` - OfBashCodeExecutionToolResult *BetaBashCodeExecutionToolResultBlockParam `json:",omitzero,inline"` - OfTextEditorCodeExecutionToolResult *BetaTextEditorCodeExecutionToolResultBlockParam `json:",omitzero,inline"` - OfToolSearchToolResult *BetaToolSearchToolResultBlockParam `json:",omitzero,inline"` - OfMCPToolUse *BetaMCPToolUseBlockParam `json:",omitzero,inline"` - OfMCPToolResult *BetaRequestMCPToolResultBlockParam `json:",omitzero,inline"` - OfContainerUpload *BetaContainerUploadBlockParam `json:",omitzero,inline"` - OfCompaction *BetaCompactionBlockParam `json:",omitzero,inline"` +type BetaClearToolUses20250919EditTriggerUnionParam struct { + OfInputTokens *BetaInputTokensTriggerParam `json:",omitzero,inline"` + OfToolUses *BetaToolUsesTriggerParam `json:",omitzero,inline"` paramUnion } -func (u BetaContentBlockParamUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfText, - u.OfImage, - u.OfDocument, - u.OfSearchResult, - u.OfThinking, - u.OfRedactedThinking, - u.OfToolUse, - u.OfToolResult, - u.OfServerToolUse, - u.OfWebSearchToolResult, - u.OfWebFetchToolResult, - u.OfAdvisorToolResult, - u.OfCodeExecutionToolResult, - u.OfBashCodeExecutionToolResult, - u.OfTextEditorCodeExecutionToolResult, - u.OfToolSearchToolResult, - u.OfMCPToolUse, - u.OfMCPToolResult, - u.OfContainerUpload, - u.OfCompaction) +func (u BetaClearToolUses20250919EditTriggerUnionParam) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfInputTokens, u.OfToolUses) } -func (u *BetaContentBlockParamUnion) UnmarshalJSON(data []byte) error { +func (u *BetaClearToolUses20250919EditTriggerUnionParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, u) } -func (u *BetaContentBlockParamUnion) asAny() any { - if !param.IsOmitted(u.OfText) { - return u.OfText - } else if !param.IsOmitted(u.OfImage) { - return u.OfImage - } else if !param.IsOmitted(u.OfDocument) { - return u.OfDocument - } else if !param.IsOmitted(u.OfSearchResult) { - return u.OfSearchResult - } else if !param.IsOmitted(u.OfThinking) { - return u.OfThinking - } else if !param.IsOmitted(u.OfRedactedThinking) { - return u.OfRedactedThinking - } else if !param.IsOmitted(u.OfToolUse) { - return u.OfToolUse - } else if !param.IsOmitted(u.OfToolResult) { - return u.OfToolResult - } else if !param.IsOmitted(u.OfServerToolUse) { - return u.OfServerToolUse - } else if !param.IsOmitted(u.OfWebSearchToolResult) { - return u.OfWebSearchToolResult - } else if !param.IsOmitted(u.OfWebFetchToolResult) { - return u.OfWebFetchToolResult - } else if !param.IsOmitted(u.OfAdvisorToolResult) { - return u.OfAdvisorToolResult - } else if !param.IsOmitted(u.OfCodeExecutionToolResult) { - return u.OfCodeExecutionToolResult - } else if !param.IsOmitted(u.OfBashCodeExecutionToolResult) { - return u.OfBashCodeExecutionToolResult - } else if !param.IsOmitted(u.OfTextEditorCodeExecutionToolResult) { - return u.OfTextEditorCodeExecutionToolResult - } else if !param.IsOmitted(u.OfToolSearchToolResult) { - return u.OfToolSearchToolResult - } else if !param.IsOmitted(u.OfMCPToolUse) { - return u.OfMCPToolUse - } else if !param.IsOmitted(u.OfMCPToolResult) { - return u.OfMCPToolResult - } else if !param.IsOmitted(u.OfContainerUpload) { - return u.OfContainerUpload - } else if !param.IsOmitted(u.OfCompaction) { - return u.OfCompaction - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u BetaContentBlockParamUnion) GetText() *string { - if vt := u.OfText; vt != nil { - return &vt.Text +func (u *BetaClearToolUses20250919EditTriggerUnionParam) asAny() any { + if !param.IsOmitted(u.OfInputTokens) { + return u.OfInputTokens + } else if !param.IsOmitted(u.OfToolUses) { + return u.OfToolUses } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u BetaContentBlockParamUnion) GetContext() *string { - if vt := u.OfDocument; vt != nil && vt.Context.Valid() { - return &vt.Context.Value +func (u BetaClearToolUses20250919EditTriggerUnionParam) GetType() *string { + if vt := u.OfInputTokens; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfToolUses; vt != nil { + return (*string)(&vt.Type) } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u BetaContentBlockParamUnion) GetSignature() *string { - if vt := u.OfThinking; vt != nil { - return &vt.Signature +func (u BetaClearToolUses20250919EditTriggerUnionParam) GetValue() *int64 { + if vt := u.OfInputTokens; vt != nil { + return (*int64)(&vt.Value) + } else if vt := u.OfToolUses; vt != nil { + return (*int64)(&vt.Value) } return nil } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaContentBlockParamUnion) GetThinking() *string { - if vt := u.OfThinking; vt != nil { - return &vt.Thinking - } - return nil +func init() { + apijson.RegisterUnion[BetaClearToolUses20250919EditTriggerUnionParam]( + "type", + apijson.Discriminator[BetaInputTokensTriggerParam]("input_tokens"), + apijson.Discriminator[BetaToolUsesTriggerParam]("tool_uses"), + ) } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaContentBlockParamUnion) GetData() *string { - if vt := u.OfRedactedThinking; vt != nil { - return &vt.Data - } - return nil +type BetaClearToolUses20250919EditResponse struct { + // Number of input tokens cleared by this edit. + ClearedInputTokens int64 `json:"cleared_input_tokens" api:"required"` + // Number of tool uses that were cleared. + ClearedToolUses int64 `json:"cleared_tool_uses" api:"required"` + // The type of context management edit applied. + Type constant.ClearToolUses20250919 `json:"type" default:"clear_tool_uses_20250919"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ClearedInputTokens respjson.Field + ClearedToolUses respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaContentBlockParamUnion) GetServerName() *string { - if vt := u.OfMCPToolUse; vt != nil { - return &vt.ServerName - } - return nil +// Returns the unmodified JSON received from the API +func (r BetaClearToolUses20250919EditResponse) RawJSON() string { return r.JSON.raw } +func (r *BetaClearToolUses20250919EditResponse) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaContentBlockParamUnion) GetFileID() *string { - if vt := u.OfContainerUpload; vt != nil { - return &vt.FileID - } - return nil +type BetaCodeExecutionOutputBlock struct { + FileID string `json:"file_id" api:"required"` + Type constant.CodeExecutionOutput `json:"type" default:"code_execution_output"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + FileID respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaContentBlockParamUnion) GetEncryptedContent() *string { - if vt := u.OfCompaction; vt != nil && vt.EncryptedContent.Valid() { - return &vt.EncryptedContent.Value - } - return nil +// Returns the unmodified JSON received from the API +func (r BetaCodeExecutionOutputBlock) RawJSON() string { return r.JSON.raw } +func (r *BetaCodeExecutionOutputBlock) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaContentBlockParamUnion) GetType() *string { - if vt := u.OfText; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfImage; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfDocument; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfSearchResult; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfThinking; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfRedactedThinking; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfToolUse; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfToolResult; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfServerToolUse; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfWebSearchToolResult; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfWebFetchToolResult; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfAdvisorToolResult; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfCodeExecutionToolResult; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfBashCodeExecutionToolResult; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfTextEditorCodeExecutionToolResult; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfToolSearchToolResult; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfMCPToolUse; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfMCPToolResult; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfContainerUpload; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfCompaction; vt != nil { - return (*string)(&vt.Type) - } - return nil +// The properties FileID, Type are required. +type BetaCodeExecutionOutputBlockParam struct { + FileID string `json:"file_id" api:"required"` + // This field can be elided, and will marshal its zero value as + // "code_execution_output". + Type constant.CodeExecutionOutput `json:"type" default:"code_execution_output"` + paramObj } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaContentBlockParamUnion) GetTitle() *string { - if vt := u.OfDocument; vt != nil && vt.Title.Valid() { - return &vt.Title.Value - } else if vt := u.OfSearchResult; vt != nil { - return (*string)(&vt.Title) - } - return nil +func (r BetaCodeExecutionOutputBlockParam) MarshalJSON() (data []byte, err error) { + type shadow BetaCodeExecutionOutputBlockParam + return param.MarshalObject(r, (*shadow)(&r)) } - -// Returns a pointer to the underlying variant's property, if present. -func (u BetaContentBlockParamUnion) GetID() *string { - if vt := u.OfToolUse; vt != nil { - return (*string)(&vt.ID) - } else if vt := u.OfServerToolUse; vt != nil { - return (*string)(&vt.ID) - } else if vt := u.OfMCPToolUse; vt != nil { - return (*string)(&vt.ID) - } - return nil +func (r *BetaCodeExecutionOutputBlockParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaContentBlockParamUnion) GetName() *string { - if vt := u.OfToolUse; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfServerToolUse; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfMCPToolUse; vt != nil { - return (*string)(&vt.Name) - } - return nil +type BetaCodeExecutionResultBlock struct { + Content []BetaCodeExecutionOutputBlock `json:"content" api:"required"` + ReturnCode int64 `json:"return_code" api:"required"` + Stderr string `json:"stderr" api:"required"` + Stdout string `json:"stdout" api:"required"` + Type constant.CodeExecutionResult `json:"type" default:"code_execution_result"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Content respjson.Field + ReturnCode respjson.Field + Stderr respjson.Field + Stdout respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaContentBlockParamUnion) GetToolUseID() *string { - if vt := u.OfToolResult; vt != nil { - return (*string)(&vt.ToolUseID) - } else if vt := u.OfWebSearchToolResult; vt != nil { - return (*string)(&vt.ToolUseID) - } else if vt := u.OfWebFetchToolResult; vt != nil { - return (*string)(&vt.ToolUseID) - } else if vt := u.OfAdvisorToolResult; vt != nil { - return (*string)(&vt.ToolUseID) - } else if vt := u.OfCodeExecutionToolResult; vt != nil { - return (*string)(&vt.ToolUseID) - } else if vt := u.OfBashCodeExecutionToolResult; vt != nil { - return (*string)(&vt.ToolUseID) - } else if vt := u.OfTextEditorCodeExecutionToolResult; vt != nil { - return (*string)(&vt.ToolUseID) - } else if vt := u.OfToolSearchToolResult; vt != nil { - return (*string)(&vt.ToolUseID) - } else if vt := u.OfMCPToolResult; vt != nil { - return (*string)(&vt.ToolUseID) - } - return nil +// Returns the unmodified JSON received from the API +func (r BetaCodeExecutionResultBlock) RawJSON() string { return r.JSON.raw } +func (r *BetaCodeExecutionResultBlock) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaContentBlockParamUnion) GetIsError() *bool { - if vt := u.OfToolResult; vt != nil && vt.IsError.Valid() { - return &vt.IsError.Value - } else if vt := u.OfMCPToolResult; vt != nil && vt.IsError.Valid() { - return &vt.IsError.Value - } - return nil +// The properties Content, ReturnCode, Stderr, Stdout, Type are required. +type BetaCodeExecutionResultBlockParam struct { + Content []BetaCodeExecutionOutputBlockParam `json:"content,omitzero" api:"required"` + ReturnCode int64 `json:"return_code" api:"required"` + Stderr string `json:"stderr" api:"required"` + Stdout string `json:"stdout" api:"required"` + // This field can be elided, and will marshal its zero value as + // "code_execution_result". + Type constant.CodeExecutionResult `json:"type" default:"code_execution_result"` + paramObj } -// Returns a pointer to the underlying variant's CacheControl property, if present. -func (u BetaContentBlockParamUnion) GetCacheControl() *BetaCacheControlEphemeralParam { - if vt := u.OfText; vt != nil { - return &vt.CacheControl - } else if vt := u.OfImage; vt != nil { - return &vt.CacheControl - } else if vt := u.OfDocument; vt != nil { - return &vt.CacheControl - } else if vt := u.OfSearchResult; vt != nil { - return &vt.CacheControl - } else if vt := u.OfToolUse; vt != nil { - return &vt.CacheControl - } else if vt := u.OfToolResult; vt != nil { - return &vt.CacheControl - } else if vt := u.OfServerToolUse; vt != nil { - return &vt.CacheControl - } else if vt := u.OfWebSearchToolResult; vt != nil { - return &vt.CacheControl - } else if vt := u.OfWebFetchToolResult; vt != nil { - return &vt.CacheControl - } else if vt := u.OfAdvisorToolResult; vt != nil { - return &vt.CacheControl - } else if vt := u.OfCodeExecutionToolResult; vt != nil { - return &vt.CacheControl - } else if vt := u.OfBashCodeExecutionToolResult; vt != nil { - return &vt.CacheControl - } else if vt := u.OfTextEditorCodeExecutionToolResult; vt != nil { - return &vt.CacheControl - } else if vt := u.OfToolSearchToolResult; vt != nil { - return &vt.CacheControl - } else if vt := u.OfMCPToolUse; vt != nil { - return &vt.CacheControl - } else if vt := u.OfMCPToolResult; vt != nil { - return &vt.CacheControl - } else if vt := u.OfContainerUpload; vt != nil { - return &vt.CacheControl - } else if vt := u.OfCompaction; vt != nil { - return &vt.CacheControl - } - return nil +func (r BetaCodeExecutionResultBlockParam) MarshalJSON() (data []byte, err error) { + type shadow BetaCodeExecutionResultBlockParam + return param.MarshalObject(r, (*shadow)(&r)) } - -// Returns a subunion which exports methods to access subproperties -// -// Or use AsAny() to get the underlying value -func (u BetaContentBlockParamUnion) GetCitations() (res betaContentBlockParamUnionCitations) { - if vt := u.OfText; vt != nil { - res.any = &vt.Citations - } else if vt := u.OfDocument; vt != nil { - res.any = &vt.Citations - } else if vt := u.OfSearchResult; vt != nil { - res.any = &vt.Citations - } - return +func (r *BetaCodeExecutionResultBlockParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Can have the runtime types [*[]BetaTextCitationParamUnion], -// [*BetaCitationsConfigParam] -type betaContentBlockParamUnionCitations struct{ any } - -// Use the following switch statement to get the type of the union: -// -// switch u.AsAny().(type) { -// case *[]anthropic.BetaTextCitationParamUnion: -// case *anthropic.BetaCitationsConfigParam: -// default: -// fmt.Errorf("not present") -// } -func (u betaContentBlockParamUnionCitations) AsAny() any { return u.any } +// The properties Name, Type are required. +type BetaCodeExecutionTool20250522Param struct { + // If true, tool will not be included in initial system prompt. Only loaded when + // returned via tool_reference from tool search. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // When true, guarantees schema validation on tool names and inputs + Strict param.Opt[bool] `json:"strict,omitzero"` + // Any of "direct", "code_execution_20250825", "code_execution_20260120", + // "code_execution_20260521". + AllowedCallers []string `json:"allowed_callers,omitzero"` + // Create a cache control breakpoint at this content block. + CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` + // Name of the tool. + // + // This is how the tool will be called by the model and in `tool_use` blocks. + // + // This field can be elided, and will marshal its zero value as "code_execution". + Name constant.CodeExecution `json:"name" default:"code_execution"` + // This field can be elided, and will marshal its zero value as + // "code_execution_20250522". + Type constant.CodeExecution20250522 `json:"type" default:"code_execution_20250522"` + paramObj +} -// Returns a pointer to the underlying variant's property, if present. -func (u betaContentBlockParamUnionCitations) GetEnabled() *bool { - switch vt := u.any.(type) { - case *BetaCitationsConfigParam: - return paramutil.AddrIfPresent(vt.Enabled) - } - return nil +func (r BetaCodeExecutionTool20250522Param) MarshalJSON() (data []byte, err error) { + type shadow BetaCodeExecutionTool20250522Param + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaCodeExecutionTool20250522Param) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns a subunion which exports methods to access subproperties -// -// Or use AsAny() to get the underlying value -func (u BetaContentBlockParamUnion) GetSource() (res betaContentBlockParamUnionSource) { - if vt := u.OfImage; vt != nil { - res.any = vt.Source.asAny() - } else if vt := u.OfDocument; vt != nil { - res.any = vt.Source.asAny() - } else if vt := u.OfSearchResult; vt != nil { - res.any = &vt.Source - } - return +// The properties Name, Type are required. +type BetaCodeExecutionTool20250825Param struct { + // If true, tool will not be included in initial system prompt. Only loaded when + // returned via tool_reference from tool search. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // When true, guarantees schema validation on tool names and inputs + Strict param.Opt[bool] `json:"strict,omitzero"` + // Any of "direct", "code_execution_20250825", "code_execution_20260120", + // "code_execution_20260521". + AllowedCallers []string `json:"allowed_callers,omitzero"` + // Create a cache control breakpoint at this content block. + CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` + // Name of the tool. + // + // This is how the tool will be called by the model and in `tool_use` blocks. + // + // This field can be elided, and will marshal its zero value as "code_execution". + Name constant.CodeExecution `json:"name" default:"code_execution"` + // This field can be elided, and will marshal its zero value as + // "code_execution_20250825". + Type constant.CodeExecution20250825 `json:"type" default:"code_execution_20250825"` + paramObj } -// Can have the runtime types [*BetaBase64ImageSourceParam], -// [*BetaURLImageSourceParam], [*BetaFileImageSourceParam], -// [*BetaBase64PDFSourceParam], [*BetaPlainTextSourceParam], -// [*BetaContentBlockSourceParam], [*BetaURLPDFSourceParam], -// [*BetaFileDocumentSourceParam], [*string] -type betaContentBlockParamUnionSource struct{ any } +func (r BetaCodeExecutionTool20250825Param) MarshalJSON() (data []byte, err error) { + type shadow BetaCodeExecutionTool20250825Param + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaCodeExecutionTool20250825Param) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} -// Use the following switch statement to get the type of the union: +// Code execution tool with REPL state persistence (daemon mode + gVisor +// checkpoint). // -// switch u.AsAny().(type) { -// case *anthropic.BetaBase64ImageSourceParam: -// case *anthropic.BetaURLImageSourceParam: -// case *anthropic.BetaFileImageSourceParam: -// case *anthropic.BetaBase64PDFSourceParam: -// case *anthropic.BetaPlainTextSourceParam: -// case *anthropic.BetaContentBlockSourceParam: -// case *anthropic.BetaURLPDFSourceParam: -// case *anthropic.BetaFileDocumentSourceParam: -// case *string: -// default: -// fmt.Errorf("not present") -// } -func (u betaContentBlockParamUnionSource) AsAny() any { return u.any } - -// Returns a pointer to the underlying variant's property, if present. -func (u betaContentBlockParamUnionSource) GetContent() *BetaContentBlockSourceContentUnionParam { - switch vt := u.any.(type) { - case *BetaRequestDocumentBlockSourceUnionParam: - return vt.GetContent() - } - return nil +// The properties Name, Type are required. +type BetaCodeExecutionTool20260120Param struct { + // If true, tool will not be included in initial system prompt. Only loaded when + // returned via tool_reference from tool search. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // When true, guarantees schema validation on tool names and inputs + Strict param.Opt[bool] `json:"strict,omitzero"` + // Any of "direct", "code_execution_20250825", "code_execution_20260120", + // "code_execution_20260521". + AllowedCallers []string `json:"allowed_callers,omitzero"` + // Create a cache control breakpoint at this content block. + CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` + // Name of the tool. + // + // This is how the tool will be called by the model and in `tool_use` blocks. + // + // This field can be elided, and will marshal its zero value as "code_execution". + Name constant.CodeExecution `json:"name" default:"code_execution"` + // This field can be elided, and will marshal its zero value as + // "code_execution_20260120". + Type constant.CodeExecution20260120 `json:"type" default:"code_execution_20260120"` + paramObj } -// Returns a pointer to the underlying variant's property, if present. -func (u betaContentBlockParamUnionSource) GetData() *string { - switch vt := u.any.(type) { - case *BetaImageBlockParamSourceUnion: - return vt.GetData() - case *BetaRequestDocumentBlockSourceUnionParam: - return vt.GetData() - } - return nil +func (r BetaCodeExecutionTool20260120Param) MarshalJSON() (data []byte, err error) { + type shadow BetaCodeExecutionTool20260120Param + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaCodeExecutionTool20260120Param) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns a pointer to the underlying variant's property, if present. -func (u betaContentBlockParamUnionSource) GetMediaType() *string { - switch vt := u.any.(type) { - case *BetaImageBlockParamSourceUnion: - return vt.GetMediaType() - case *BetaRequestDocumentBlockSourceUnionParam: - return vt.GetMediaType() - } - return nil +// Code execution tool with REPL state persistence. +// +// The properties Name, Type are required. +type BetaCodeExecutionTool20260521Param struct { + // If true, tool will not be included in initial system prompt. Only loaded when + // returned via tool_reference from tool search. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // When true, guarantees schema validation on tool names and inputs + Strict param.Opt[bool] `json:"strict,omitzero"` + // Any of "direct", "code_execution_20250825", "code_execution_20260120", + // "code_execution_20260521". + AllowedCallers []string `json:"allowed_callers,omitzero"` + // Create a cache control breakpoint at this content block. + CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` + // Name of the tool. + // + // This is how the tool will be called by the model and in `tool_use` blocks. + // + // This field can be elided, and will marshal its zero value as "code_execution". + Name constant.CodeExecution `json:"name" default:"code_execution"` + // This field can be elided, and will marshal its zero value as + // "code_execution_20260521". + Type constant.CodeExecution20260521 `json:"type" default:"code_execution_20260521"` + paramObj } -// Returns a pointer to the underlying variant's property, if present. -func (u betaContentBlockParamUnionSource) GetType() *string { - switch vt := u.any.(type) { - case *BetaImageBlockParamSourceUnion: - return vt.GetType() - case *BetaRequestDocumentBlockSourceUnionParam: - return vt.GetType() - } - return nil +func (r BetaCodeExecutionTool20260521Param) MarshalJSON() (data []byte, err error) { + type shadow BetaCodeExecutionTool20260521Param + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaCodeExecutionTool20260521Param) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns a pointer to the underlying variant's property, if present. -func (u betaContentBlockParamUnionSource) GetURL() *string { - switch vt := u.any.(type) { - case *BetaImageBlockParamSourceUnion: - return vt.GetURL() - case *BetaRequestDocumentBlockSourceUnionParam: - return vt.GetURL() - } - return nil +type BetaCodeExecutionToolResultBlock struct { + // Code execution result with encrypted stdout for PFC + web_search results. + Content BetaCodeExecutionToolResultBlockContentUnion `json:"content" api:"required"` + ToolUseID string `json:"tool_use_id" api:"required"` + Type constant.CodeExecutionToolResult `json:"type" default:"code_execution_tool_result"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Content respjson.Field + ToolUseID respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` } -// Returns a pointer to the underlying variant's property, if present. -func (u betaContentBlockParamUnionSource) GetFileID() *string { - switch vt := u.any.(type) { - case *BetaImageBlockParamSourceUnion: - return vt.GetFileID() - case *BetaRequestDocumentBlockSourceUnionParam: - return vt.GetFileID() - } - return nil +// Returns the unmodified JSON received from the API +func (r BetaCodeExecutionToolResultBlock) RawJSON() string { return r.JSON.raw } +func (r *BetaCodeExecutionToolResultBlock) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns a subunion which exports methods to access subproperties +// BetaCodeExecutionToolResultBlockContentUnion contains all possible properties +// and values from [BetaCodeExecutionToolResultError], +// [BetaCodeExecutionResultBlock], [BetaEncryptedCodeExecutionResultBlock]. // -// Or use AsAny() to get the underlying value -func (u BetaContentBlockParamUnion) GetContent() (res betaContentBlockParamUnionContent) { - if vt := u.OfSearchResult; vt != nil { - res.any = &vt.Content - } else if vt := u.OfToolResult; vt != nil { - res.any = &vt.Content - } else if vt := u.OfWebSearchToolResult; vt != nil { - res.any = vt.Content.asAny() - } else if vt := u.OfWebFetchToolResult; vt != nil { - res.any = vt.Content.asAny() - } else if vt := u.OfAdvisorToolResult; vt != nil { - res.any = vt.Content.asAny() - } else if vt := u.OfCodeExecutionToolResult; vt != nil { - res.any = vt.Content.asAny() - } else if vt := u.OfBashCodeExecutionToolResult; vt != nil { - res.any = vt.Content.asAny() - } else if vt := u.OfTextEditorCodeExecutionToolResult; vt != nil { - res.any = vt.Content.asAny() - } else if vt := u.OfToolSearchToolResult; vt != nil { - res.any = vt.Content.asAny() - } else if vt := u.OfMCPToolResult; vt != nil { - res.any = vt.Content.asAny() - } else if vt := u.OfCompaction; vt != nil && vt.Content.Valid() { - res.any = &vt.Content.Value - } - return +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaCodeExecutionToolResultBlockContentUnion struct { + // This field is from variant [BetaCodeExecutionToolResultError]. + ErrorCode BetaCodeExecutionToolResultErrorCode `json:"error_code"` + Type string `json:"type"` + Content []BetaCodeExecutionOutputBlock `json:"content"` + ReturnCode int64 `json:"return_code"` + Stderr string `json:"stderr"` + // This field is from variant [BetaCodeExecutionResultBlock]. + Stdout string `json:"stdout"` + // This field is from variant [BetaEncryptedCodeExecutionResultBlock]. + EncryptedStdout string `json:"encrypted_stdout"` + JSON struct { + ErrorCode respjson.Field + Type respjson.Field + Content respjson.Field + ReturnCode respjson.Field + Stderr respjson.Field + Stdout respjson.Field + EncryptedStdout respjson.Field + raw string + } `json:"-"` } -// Can have the runtime types [_[]BetaTextBlockParam], -// [_[]BetaToolResultBlockParamContentUnion], [*[]BetaWebSearchResultBlockParam], -// [*BetaWebFetchToolResultErrorBlockParam], [*BetaWebFetchBlockParam], -// [*BetaAdvisorToolResultErrorParam], [*BetaAdvisorResultBlockParam], -// [*BetaAdvisorRedactedResultBlockParam], -// [*BetaCodeExecutionToolResultErrorParam], [*BetaCodeExecutionResultBlockParam], -// [*BetaEncryptedCodeExecutionResultBlockParam], -// [*BetaBashCodeExecutionToolResultErrorParam], -// [*BetaBashCodeExecutionResultBlockParam], -// [*BetaTextEditorCodeExecutionToolResultErrorParam], -// [*BetaTextEditorCodeExecutionViewResultBlockParam], -// [*BetaTextEditorCodeExecutionCreateResultBlockParam], -// [*BetaTextEditorCodeExecutionStrReplaceResultBlockParam], -// [*BetaToolSearchToolResultErrorParam], -// [*BetaToolSearchToolSearchResultBlockParam], [*string] -type betaContentBlockParamUnionContent struct{ any } +func (u BetaCodeExecutionToolResultBlockContentUnion) AsResponseCodeExecutionToolResultError() (v BetaCodeExecutionToolResultError) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} -// Use the following switch statement to get the type of the union: -// -// switch u.AsAny().(type) { -// case *[]anthropic.BetaTextBlockParam: -// case *[]anthropic.BetaToolResultBlockParamContentUnion: -// case *[]anthropic.BetaWebSearchResultBlockParam: -// case *anthropic.BetaWebFetchToolResultErrorBlockParam: -// case *anthropic.BetaWebFetchBlockParam: -// case *anthropic.BetaAdvisorToolResultErrorParam: -// case *anthropic.BetaAdvisorResultBlockParam: -// case *anthropic.BetaAdvisorRedactedResultBlockParam: -// case *anthropic.BetaCodeExecutionToolResultErrorParam: -// case *anthropic.BetaCodeExecutionResultBlockParam: -// case *anthropic.BetaEncryptedCodeExecutionResultBlockParam: -// case *anthropic.BetaBashCodeExecutionToolResultErrorParam: -// case *anthropic.BetaBashCodeExecutionResultBlockParam: -// case *anthropic.BetaTextEditorCodeExecutionToolResultErrorParam: -// case *anthropic.BetaTextEditorCodeExecutionViewResultBlockParam: -// case *anthropic.BetaTextEditorCodeExecutionCreateResultBlockParam: -// case *anthropic.BetaTextEditorCodeExecutionStrReplaceResultBlockParam: -// case *anthropic.BetaToolSearchToolResultErrorParam: -// case *anthropic.BetaToolSearchToolSearchResultBlockParam: -// case *string: -// default: -// fmt.Errorf("not present") -// } -func (u betaContentBlockParamUnionContent) AsAny() any { return u.any } +func (u BetaCodeExecutionToolResultBlockContentUnion) AsResponseCodeExecutionResultBlock() (v BetaCodeExecutionResultBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} -// Returns a pointer to the underlying variant's property, if present. -func (u betaContentBlockParamUnionContent) GetURL() *string { - switch vt := u.any.(type) { - case *BetaWebFetchToolResultBlockParamContentUnion: - return vt.GetURL() - } - return nil +func (u BetaCodeExecutionToolResultBlockContentUnion) AsResponseEncryptedCodeExecutionResultBlock() (v BetaEncryptedCodeExecutionResultBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -// Returns a pointer to the underlying variant's property, if present. -func (u betaContentBlockParamUnionContent) GetRetrievedAt() *string { - switch vt := u.any.(type) { - case *BetaWebFetchToolResultBlockParamContentUnion: - return vt.GetRetrievedAt() - } - return nil +// Returns the unmodified JSON received from the API +func (u BetaCodeExecutionToolResultBlockContentUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaCodeExecutionToolResultBlockContentUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns a pointer to the underlying variant's property, if present. -func (u betaContentBlockParamUnionContent) GetText() *string { - switch vt := u.any.(type) { - case *BetaAdvisorToolResultBlockParamContentUnion: - return vt.GetText() - } - return nil +// The properties Content, ToolUseID, Type are required. +type BetaCodeExecutionToolResultBlockParam struct { + // Code execution result with encrypted stdout for PFC + web_search results. + Content BetaCodeExecutionToolResultBlockParamContentUnion `json:"content,omitzero" api:"required"` + ToolUseID string `json:"tool_use_id" api:"required"` + // Create a cache control breakpoint at this content block. + CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` + // This field can be elided, and will marshal its zero value as + // "code_execution_tool_result". + Type constant.CodeExecutionToolResult `json:"type" default:"code_execution_tool_result"` + paramObj } -// Returns a pointer to the underlying variant's property, if present. -func (u betaContentBlockParamUnionContent) GetEncryptedContent() *string { - switch vt := u.any.(type) { - case *BetaAdvisorToolResultBlockParamContentUnion: - return vt.GetEncryptedContent() - } - return nil +func (r BetaCodeExecutionToolResultBlockParam) MarshalJSON() (data []byte, err error) { + type shadow BetaCodeExecutionToolResultBlockParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaCodeExecutionToolResultBlockParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns a pointer to the underlying variant's property, if present. -func (u betaContentBlockParamUnionContent) GetEncryptedStdout() *string { - switch vt := u.any.(type) { - case *BetaCodeExecutionToolResultBlockParamContentUnion: - return vt.GetEncryptedStdout() - } - return nil +func BetaNewCodeExecutionToolRequestError(errorCode BetaCodeExecutionToolResultErrorCode) BetaCodeExecutionToolResultBlockParamContentUnion { + var variant BetaCodeExecutionToolResultErrorParam + variant.ErrorCode = errorCode + return BetaCodeExecutionToolResultBlockParamContentUnion{OfError: &variant} } -// Returns a pointer to the underlying variant's property, if present. -func (u betaContentBlockParamUnionContent) GetErrorMessage() *string { - switch vt := u.any.(type) { - case *BetaTextEditorCodeExecutionToolResultBlockParamContentUnion: - return vt.GetErrorMessage() - } - return nil +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaCodeExecutionToolResultBlockParamContentUnion struct { + OfError *BetaCodeExecutionToolResultErrorParam `json:",omitzero,inline"` + OfResultBlock *BetaCodeExecutionResultBlockParam `json:",omitzero,inline"` + OfRequestEncryptedCodeExecutionResultBlock *BetaEncryptedCodeExecutionResultBlockParam `json:",omitzero,inline"` + paramUnion } -// Returns a pointer to the underlying variant's property, if present. -func (u betaContentBlockParamUnionContent) GetFileType() *string { - switch vt := u.any.(type) { - case *BetaTextEditorCodeExecutionToolResultBlockParamContentUnion: - return vt.GetFileType() - } - return nil +func (u BetaCodeExecutionToolResultBlockParamContentUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfError, u.OfResultBlock, u.OfRequestEncryptedCodeExecutionResultBlock) +} +func (u *BetaCodeExecutionToolResultBlockParamContentUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) } -// Returns a pointer to the underlying variant's property, if present. -func (u betaContentBlockParamUnionContent) GetNumLines() *int64 { - switch vt := u.any.(type) { - case *BetaTextEditorCodeExecutionToolResultBlockParamContentUnion: - return vt.GetNumLines() +func (u *BetaCodeExecutionToolResultBlockParamContentUnion) asAny() any { + if !param.IsOmitted(u.OfError) { + return u.OfError + } else if !param.IsOmitted(u.OfResultBlock) { + return u.OfResultBlock + } else if !param.IsOmitted(u.OfRequestEncryptedCodeExecutionResultBlock) { + return u.OfRequestEncryptedCodeExecutionResultBlock } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u betaContentBlockParamUnionContent) GetStartLine() *int64 { - switch vt := u.any.(type) { - case *BetaTextEditorCodeExecutionToolResultBlockParamContentUnion: - return vt.GetStartLine() +func (u BetaCodeExecutionToolResultBlockParamContentUnion) GetErrorCode() *string { + if vt := u.OfError; vt != nil { + return (*string)(&vt.ErrorCode) } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u betaContentBlockParamUnionContent) GetTotalLines() *int64 { - switch vt := u.any.(type) { - case *BetaTextEditorCodeExecutionToolResultBlockParamContentUnion: - return vt.GetTotalLines() +func (u BetaCodeExecutionToolResultBlockParamContentUnion) GetStdout() *string { + if vt := u.OfResultBlock; vt != nil { + return &vt.Stdout } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u betaContentBlockParamUnionContent) GetIsFileUpdate() *bool { - switch vt := u.any.(type) { - case *BetaTextEditorCodeExecutionToolResultBlockParamContentUnion: - return vt.GetIsFileUpdate() +func (u BetaCodeExecutionToolResultBlockParamContentUnion) GetEncryptedStdout() *string { + if vt := u.OfRequestEncryptedCodeExecutionResultBlock; vt != nil { + return &vt.EncryptedStdout } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u betaContentBlockParamUnionContent) GetLines() []string { - switch vt := u.any.(type) { - case *BetaTextEditorCodeExecutionToolResultBlockParamContentUnion: - return vt.GetLines() +func (u BetaCodeExecutionToolResultBlockParamContentUnion) GetType() *string { + if vt := u.OfError; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfResultBlock; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfRequestEncryptedCodeExecutionResultBlock; vt != nil { + return (*string)(&vt.Type) } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u betaContentBlockParamUnionContent) GetNewLines() *int64 { - switch vt := u.any.(type) { - case *BetaTextEditorCodeExecutionToolResultBlockParamContentUnion: - return vt.GetNewLines() +func (u BetaCodeExecutionToolResultBlockParamContentUnion) GetReturnCode() *int64 { + if vt := u.OfResultBlock; vt != nil { + return (*int64)(&vt.ReturnCode) + } else if vt := u.OfRequestEncryptedCodeExecutionResultBlock; vt != nil { + return (*int64)(&vt.ReturnCode) } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u betaContentBlockParamUnionContent) GetNewStart() *int64 { - switch vt := u.any.(type) { - case *BetaTextEditorCodeExecutionToolResultBlockParamContentUnion: - return vt.GetNewStart() +func (u BetaCodeExecutionToolResultBlockParamContentUnion) GetStderr() *string { + if vt := u.OfResultBlock; vt != nil { + return (*string)(&vt.Stderr) + } else if vt := u.OfRequestEncryptedCodeExecutionResultBlock; vt != nil { + return (*string)(&vt.Stderr) } return nil } -// Returns a pointer to the underlying variant's property, if present. -func (u betaContentBlockParamUnionContent) GetOldLines() *int64 { - switch vt := u.any.(type) { - case *BetaTextEditorCodeExecutionToolResultBlockParamContentUnion: - return vt.GetOldLines() +// Returns a pointer to the underlying variant's Content property, if present. +func (u BetaCodeExecutionToolResultBlockParamContentUnion) GetContent() []BetaCodeExecutionOutputBlockParam { + if vt := u.OfResultBlock; vt != nil { + return vt.Content + } else if vt := u.OfRequestEncryptedCodeExecutionResultBlock; vt != nil { + return vt.Content } return nil } -// Returns a pointer to the underlying variant's property, if present. -func (u betaContentBlockParamUnionContent) GetOldStart() *int64 { - switch vt := u.any.(type) { - case *BetaTextEditorCodeExecutionToolResultBlockParamContentUnion: - return vt.GetOldStart() - } - return nil +type BetaCodeExecutionToolResultError struct { + // Any of "invalid_tool_input", "unavailable", "too_many_requests", + // "execution_time_exceeded". + ErrorCode BetaCodeExecutionToolResultErrorCode `json:"error_code" api:"required"` + Type constant.CodeExecutionToolResultError `json:"type" default:"code_execution_tool_result_error"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ErrorCode respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` } -// Returns a pointer to the underlying variant's property, if present. -func (u betaContentBlockParamUnionContent) GetToolReferences() []BetaToolReferenceBlockParam { - switch vt := u.any.(type) { - case *BetaToolSearchToolResultBlockParamContentUnion: - return vt.GetToolReferences() - } - return nil +// Returns the unmodified JSON received from the API +func (r BetaCodeExecutionToolResultError) RawJSON() string { return r.JSON.raw } +func (r *BetaCodeExecutionToolResultError) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns a pointer to the underlying variant's property, if present. -func (u betaContentBlockParamUnionContent) GetErrorCode() *string { - switch vt := u.any.(type) { - case *BetaWebSearchToolResultBlockParamContentUnion: - if vt.OfError != nil { - return (*string)(&vt.OfError.ErrorCode) - } - case *BetaWebFetchToolResultBlockParamContentUnion: - return vt.GetErrorCode() - case *BetaAdvisorToolResultBlockParamContentUnion: - return vt.GetErrorCode() - case *BetaCodeExecutionToolResultBlockParamContentUnion: - return vt.GetErrorCode() - case *BetaBashCodeExecutionToolResultBlockParamContentUnion: - return vt.GetErrorCode() - case *BetaTextEditorCodeExecutionToolResultBlockParamContentUnion: - return vt.GetErrorCode() - case *BetaToolSearchToolResultBlockParamContentUnion: - return vt.GetErrorCode() - } - return nil -} +type BetaCodeExecutionToolResultErrorCode string -// Returns a pointer to the underlying variant's property, if present. -func (u betaContentBlockParamUnionContent) GetType() *string { - switch vt := u.any.(type) { - case *BetaWebSearchToolResultBlockParamContentUnion: - if vt.OfError != nil { - return (*string)(&vt.OfError.Type) - } - case *BetaWebFetchToolResultBlockParamContentUnion: - return vt.GetType() - case *BetaAdvisorToolResultBlockParamContentUnion: - return vt.GetType() - case *BetaCodeExecutionToolResultBlockParamContentUnion: - return vt.GetType() - case *BetaBashCodeExecutionToolResultBlockParamContentUnion: - return vt.GetType() - case *BetaTextEditorCodeExecutionToolResultBlockParamContentUnion: - return vt.GetType() - case *BetaToolSearchToolResultBlockParamContentUnion: - return vt.GetType() - } - return nil -} +const ( + BetaCodeExecutionToolResultErrorCodeInvalidToolInput BetaCodeExecutionToolResultErrorCode = "invalid_tool_input" + BetaCodeExecutionToolResultErrorCodeUnavailable BetaCodeExecutionToolResultErrorCode = "unavailable" + BetaCodeExecutionToolResultErrorCodeTooManyRequests BetaCodeExecutionToolResultErrorCode = "too_many_requests" + BetaCodeExecutionToolResultErrorCodeExecutionTimeExceeded BetaCodeExecutionToolResultErrorCode = "execution_time_exceeded" +) -// Returns a pointer to the underlying variant's property, if present. -func (u betaContentBlockParamUnionContent) GetReturnCode() *int64 { - switch vt := u.any.(type) { - case *BetaCodeExecutionToolResultBlockParamContentUnion: - return vt.GetReturnCode() - case *BetaBashCodeExecutionToolResultBlockParamContentUnion: - return vt.GetReturnCode() - } - return nil +// The properties ErrorCode, Type are required. +type BetaCodeExecutionToolResultErrorParam struct { + // Any of "invalid_tool_input", "unavailable", "too_many_requests", + // "execution_time_exceeded". + ErrorCode BetaCodeExecutionToolResultErrorCode `json:"error_code,omitzero" api:"required"` + // This field can be elided, and will marshal its zero value as + // "code_execution_tool_result_error". + Type constant.CodeExecutionToolResultError `json:"type" default:"code_execution_tool_result_error"` + paramObj } -// Returns a pointer to the underlying variant's property, if present. -func (u betaContentBlockParamUnionContent) GetStderr() *string { - switch vt := u.any.(type) { - case *BetaCodeExecutionToolResultBlockParamContentUnion: - return vt.GetStderr() - case *BetaBashCodeExecutionToolResultBlockParamContentUnion: - return vt.GetStderr() - } - return nil +func (r BetaCodeExecutionToolResultErrorParam) MarshalJSON() (data []byte, err error) { + type shadow BetaCodeExecutionToolResultErrorParam + return param.MarshalObject(r, (*shadow)(&r)) } - -// Returns a pointer to the underlying variant's property, if present. -func (u betaContentBlockParamUnionContent) GetStdout() *string { - switch vt := u.any.(type) { - case *BetaCodeExecutionToolResultBlockParamContentUnion: - return vt.GetStdout() - case *BetaBashCodeExecutionToolResultBlockParamContentUnion: - return vt.GetStdout() - } - return nil +func (r *BetaCodeExecutionToolResultErrorParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns a subunion which exports methods to access subproperties +// Automatically compact older context when reaching the configured trigger +// threshold. // -// Or use AsAny() to get the underlying value -func (u betaContentBlockParamUnionContent) GetContent() (res betaContentBlockParamUnionContentContent) { - switch vt := u.any.(type) { - case *BetaWebFetchToolResultBlockParamContentUnion: - res.any = vt.GetContent() - case *BetaCodeExecutionToolResultBlockParamContentUnion: - res.any = vt.GetContent() - case *BetaBashCodeExecutionToolResultBlockParamContentUnion: - res.any = vt.GetContent() - case *BetaTextEditorCodeExecutionToolResultBlockParamContentUnion: - res.any = vt.GetContent() - } - return res +// The property Type is required. +type BetaCompact20260112EditParam struct { + // Additional instructions for summarization. + Instructions param.Opt[string] `json:"instructions,omitzero"` + // Whether to pause after compaction and return the compaction block to the user. + PauseAfterCompaction param.Opt[bool] `json:"pause_after_compaction,omitzero"` + // When to trigger compaction. Defaults to 150000 input tokens. + Trigger BetaInputTokensTriggerParam `json:"trigger,omitzero"` + // This field can be elided, and will marshal its zero value as "compact_20260112". + Type constant.Compact20260112 `json:"type" default:"compact_20260112"` + paramObj } -// Can have the runtime types [*BetaRequestDocumentBlockParam], -// [_[]BetaCodeExecutionOutputBlockParam], -// [_[]BetaBashCodeExecutionOutputBlockParam], [*string] -type betaContentBlockParamUnionContentContent struct{ any } +func (r BetaCompact20260112EditParam) MarshalJSON() (data []byte, err error) { + type shadow BetaCompact20260112EditParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaCompact20260112EditParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} -// Use the following switch statement to get the type of the union: +// A compaction block returned when autocompact is triggered. // -// switch u.AsAny().(type) { -// case *anthropic.BetaRequestDocumentBlockParam: -// case *[]anthropic.BetaCodeExecutionOutputBlockParam: -// case *[]anthropic.BetaBashCodeExecutionOutputBlockParam: -// case *string: -// default: -// fmt.Errorf("not present") -// } -func (u betaContentBlockParamUnionContentContent) AsAny() any { return u.any } +// When content is None, it indicates the compaction failed to produce a valid +// summary (e.g., malformed output from the model). Clients may round-trip +// compaction blocks with null content; the server treats them as no-ops. +type BetaCompactionBlock struct { + // Summary of compacted content, or null if compaction failed + Content string `json:"content" api:"required"` + // Opaque metadata from prior compaction, to be round-tripped verbatim + EncryptedContent string `json:"encrypted_content" api:"required"` + Type constant.Compaction `json:"type" default:"compaction"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Content respjson.Field + EncryptedContent respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} -// Returns a pointer to the underlying variant's Input property, if present. -func (u BetaContentBlockParamUnion) GetInput() *any { - if vt := u.OfToolUse; vt != nil { - return &vt.Input - } else if vt := u.OfServerToolUse; vt != nil { - return &vt.Input - } else if vt := u.OfMCPToolUse; vt != nil { - return &vt.Input - } - return nil +// Returns the unmodified JSON received from the API +func (r BetaCompactionBlock) RawJSON() string { return r.JSON.raw } +func (r *BetaCompactionBlock) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns a subunion which exports methods to access subproperties +// A compaction block containing summary of previous context. // -// Or use AsAny() to get the underlying value -func (u BetaContentBlockParamUnion) GetCaller() (res betaContentBlockParamUnionCaller) { - if vt := u.OfToolUse; vt != nil { - res.any = vt.Caller.asAny() - } else if vt := u.OfServerToolUse; vt != nil { - res.any = vt.Caller.asAny() - } else if vt := u.OfWebSearchToolResult; vt != nil { - res.any = vt.Caller.asAny() - } else if vt := u.OfWebFetchToolResult; vt != nil { - res.any = vt.Caller.asAny() - } - return +// Users should round-trip these blocks from responses to subsequent requests to +// maintain context across compaction boundaries. +// +// When content is None, the block represents a failed compaction. The server +// treats these as no-ops. Empty string content is not allowed. +// +// The property Type is required. +type BetaCompactionBlockParam struct { + // Summary of previously compacted content, or null if compaction failed + Content param.Opt[string] `json:"content,omitzero"` + // Opaque metadata from prior compaction, to be round-tripped verbatim + EncryptedContent param.Opt[string] `json:"encrypted_content,omitzero"` + // Create a cache control breakpoint at this content block. + CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` + // This field can be elided, and will marshal its zero value as "compaction". + Type constant.Compaction `json:"type" default:"compaction"` + paramObj } -// Can have the runtime types [*BetaDirectCallerParam], -// [*BetaServerToolCallerParam], [*BetaServerToolCaller20260120Param] -type betaContentBlockParamUnionCaller struct{ any } - -// Use the following switch statement to get the type of the union: -// -// switch u.AsAny().(type) { -// case *anthropic.BetaDirectCallerParam: -// case *anthropic.BetaServerToolCallerParam: -// case *anthropic.BetaServerToolCaller20260120Param: -// default: -// fmt.Errorf("not present") -// } -func (u betaContentBlockParamUnionCaller) AsAny() any { return u.any } +func (r BetaCompactionBlockParam) MarshalJSON() (data []byte, err error) { + type shadow BetaCompactionBlockParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaCompactionBlockParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} -// Returns a pointer to the underlying variant's property, if present. -func (u betaContentBlockParamUnionCaller) GetType() *string { - switch vt := u.any.(type) { - case *BetaToolUseBlockParamCallerUnion: - return vt.GetType() - case *BetaServerToolUseBlockParamCallerUnion: - return vt.GetType() - case *BetaWebSearchToolResultBlockParamCallerUnion: - return vt.GetType() - case *BetaWebFetchToolResultBlockParamCallerUnion: - return vt.GetType() - } - return nil +type BetaCompactionContentBlockDelta struct { + Content string `json:"content" api:"required"` + // Opaque metadata from prior compaction, to be round-tripped verbatim + EncryptedContent string `json:"encrypted_content" api:"required"` + Type constant.CompactionDelta `json:"type" default:"compaction_delta"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Content respjson.Field + EncryptedContent respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` } -// Returns a pointer to the underlying variant's property, if present. -func (u betaContentBlockParamUnionCaller) GetToolID() *string { - switch vt := u.any.(type) { - case *BetaToolUseBlockParamCallerUnion: - return vt.GetToolID() - case *BetaServerToolUseBlockParamCallerUnion: - return vt.GetToolID() - case *BetaWebSearchToolResultBlockParamCallerUnion: - return vt.GetToolID() - case *BetaWebFetchToolResultBlockParamCallerUnion: - return vt.GetToolID() - } - return nil +// Returns the unmodified JSON received from the API +func (r BetaCompactionContentBlockDelta) RawJSON() string { return r.JSON.raw } +func (r *BetaCompactionContentBlockDelta) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func init() { - apijson.RegisterUnion[BetaContentBlockParamUnion]( - "type", - apijson.Discriminator[BetaTextBlockParam]("text"), - apijson.Discriminator[BetaImageBlockParam]("image"), - apijson.Discriminator[BetaRequestDocumentBlockParam]("document"), - apijson.Discriminator[BetaSearchResultBlockParam]("search_result"), - apijson.Discriminator[BetaThinkingBlockParam]("thinking"), - apijson.Discriminator[BetaRedactedThinkingBlockParam]("redacted_thinking"), - apijson.Discriminator[BetaToolUseBlockParam]("tool_use"), - apijson.Discriminator[BetaToolResultBlockParam]("tool_result"), - apijson.Discriminator[BetaServerToolUseBlockParam]("server_tool_use"), - apijson.Discriminator[BetaWebSearchToolResultBlockParam]("web_search_tool_result"), - apijson.Discriminator[BetaWebFetchToolResultBlockParam]("web_fetch_tool_result"), - apijson.Discriminator[BetaAdvisorToolResultBlockParam]("advisor_tool_result"), - apijson.Discriminator[BetaCodeExecutionToolResultBlockParam]("code_execution_tool_result"), - apijson.Discriminator[BetaBashCodeExecutionToolResultBlockParam]("bash_code_execution_tool_result"), - apijson.Discriminator[BetaTextEditorCodeExecutionToolResultBlockParam]("text_editor_code_execution_tool_result"), - apijson.Discriminator[BetaToolSearchToolResultBlockParam]("tool_search_tool_result"), - apijson.Discriminator[BetaMCPToolUseBlockParam]("mcp_tool_use"), - apijson.Discriminator[BetaRequestMCPToolResultBlockParam]("mcp_tool_result"), - apijson.Discriminator[BetaContainerUploadBlockParam]("container_upload"), - apijson.Discriminator[BetaCompactionBlockParam]("compaction"), - ) +// Token usage for a compaction iteration. +type BetaCompactionIterationUsage struct { + // Breakdown of cached tokens by TTL + CacheCreation BetaCacheCreation `json:"cache_creation" api:"required"` + // The number of input tokens used to create the cache entry. + CacheCreationInputTokens int64 `json:"cache_creation_input_tokens" api:"required"` + // The number of input tokens read from the cache. + CacheReadInputTokens int64 `json:"cache_read_input_tokens" api:"required"` + // The number of input tokens which were used. + InputTokens int64 `json:"input_tokens" api:"required"` + // The number of output tokens which were used. + OutputTokens int64 `json:"output_tokens" api:"required"` + // Usage for a compaction iteration + Type constant.Compaction `json:"type" default:"compaction"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + CacheCreation respjson.Field + CacheCreationInputTokens respjson.Field + CacheReadInputTokens respjson.Field + InputTokens respjson.Field + OutputTokens respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` } -// The properties Content, Type are required. -type BetaContentBlockSourceParam struct { - Content BetaContentBlockSourceContentUnionParam `json:"content,omitzero" api:"required"` - // This field can be elided, and will marshal its zero value as "content". - Type constant.Content `json:"type" default:"content"` +// Returns the unmodified JSON received from the API +func (r BetaCompactionIterationUsage) RawJSON() string { return r.JSON.raw } +func (r *BetaCompactionIterationUsage) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// `cursor_position`'s config overrides. +type BetaComputerCursorPositionConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` paramObj } -func (r BetaContentBlockSourceParam) MarshalJSON() (data []byte, err error) { - type shadow BetaContentBlockSourceParam +func (r BetaComputerCursorPositionConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaComputerCursorPositionConfigParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *BetaContentBlockSourceParam) UnmarshalJSON(data []byte) error { +func (r *BetaComputerCursorPositionConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type BetaContentBlockSourceContentUnionParam struct { - OfString param.Opt[string] `json:",omitzero,inline"` - OfBetaContentBlockSourceContent []BetaContentBlockSourceContentUnionParam `json:",omitzero,inline"` - paramUnion +// `double_click`'s config overrides. +type BetaComputerDoubleClickConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -func (u BetaContentBlockSourceContentUnionParam) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfString, u.OfBetaContentBlockSourceContent) +func (r BetaComputerDoubleClickConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaComputerDoubleClickConfigParam + return param.MarshalObject(r, (*shadow)(&r)) } -func (u *BetaContentBlockSourceContentUnionParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) +func (r *BetaComputerDoubleClickConfigParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func (u *BetaContentBlockSourceContentUnionParam) asAny() any { - if !param.IsOmitted(u.OfString) { - return &u.OfString.Value - } else if !param.IsOmitted(u.OfBetaContentBlockSourceContent) { - return &u.OfBetaContentBlockSourceContent - } - return nil +// `hold_key`'s config overrides. +type BetaComputerHoldKeyConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -type BetaContextManagementConfigParam struct { - // List of context management edits to apply - Edits []BetaContextManagementConfigEditUnionParam `json:"edits,omitzero"` +func (r BetaComputerHoldKeyConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaComputerHoldKeyConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaComputerHoldKeyConfigParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// `key`'s config overrides. +type BetaComputerKeyConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` paramObj } -func (r BetaContextManagementConfigParam) MarshalJSON() (data []byte, err error) { - type shadow BetaContextManagementConfigParam +func (r BetaComputerKeyConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaComputerKeyConfigParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *BetaContextManagementConfigParam) UnmarshalJSON(data []byte) error { +func (r *BetaComputerKeyConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type BetaContextManagementConfigEditUnionParam struct { - OfClearToolUses20250919 *BetaClearToolUses20250919EditParam `json:",omitzero,inline"` - OfClearThinking20251015 *BetaClearThinking20251015EditParam `json:",omitzero,inline"` - OfCompact20260112 *BetaCompact20260112EditParam `json:",omitzero,inline"` - paramUnion +// `left_click`'s config overrides. +type BetaComputerLeftClickConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -func (u BetaContextManagementConfigEditUnionParam) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfClearToolUses20250919, u.OfClearThinking20251015, u.OfCompact20260112) +func (r BetaComputerLeftClickConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaComputerLeftClickConfigParam + return param.MarshalObject(r, (*shadow)(&r)) } -func (u *BetaContextManagementConfigEditUnionParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) +func (r *BetaComputerLeftClickConfigParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func (u *BetaContextManagementConfigEditUnionParam) asAny() any { - if !param.IsOmitted(u.OfClearToolUses20250919) { - return u.OfClearToolUses20250919 - } else if !param.IsOmitted(u.OfClearThinking20251015) { - return u.OfClearThinking20251015 - } else if !param.IsOmitted(u.OfCompact20260112) { - return u.OfCompact20260112 - } - return nil +// `left_click_drag`'s config overrides. +type BetaComputerLeftClickDragConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaContextManagementConfigEditUnionParam) GetClearAtLeast() *BetaInputTokensClearAtLeastParam { - if vt := u.OfClearToolUses20250919; vt != nil { - return &vt.ClearAtLeast - } - return nil +func (r BetaComputerLeftClickDragConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaComputerLeftClickDragConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaComputerLeftClickDragConfigParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaContextManagementConfigEditUnionParam) GetClearToolInputs() *BetaClearToolUses20250919EditClearToolInputsUnionParam { - if vt := u.OfClearToolUses20250919; vt != nil { - return &vt.ClearToolInputs - } - return nil +// `left_mouse_down`'s config overrides. +type BetaComputerLeftMouseDownConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaContextManagementConfigEditUnionParam) GetExcludeTools() []string { - if vt := u.OfClearToolUses20250919; vt != nil { - return vt.ExcludeTools - } - return nil +func (r BetaComputerLeftMouseDownConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaComputerLeftMouseDownConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaComputerLeftMouseDownConfigParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaContextManagementConfigEditUnionParam) GetInstructions() *string { - if vt := u.OfCompact20260112; vt != nil && vt.Instructions.Valid() { - return &vt.Instructions.Value - } - return nil +// `left_mouse_up`'s config overrides. +type BetaComputerLeftMouseUpConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaContextManagementConfigEditUnionParam) GetPauseAfterCompaction() *bool { - if vt := u.OfCompact20260112; vt != nil && vt.PauseAfterCompaction.Valid() { - return &vt.PauseAfterCompaction.Value - } - return nil +func (r BetaComputerLeftMouseUpConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaComputerLeftMouseUpConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaComputerLeftMouseUpConfigParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaContextManagementConfigEditUnionParam) GetType() *string { - if vt := u.OfClearToolUses20250919; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfClearThinking20251015; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfCompact20260112; vt != nil { - return (*string)(&vt.Type) - } - return nil +// `middle_click`'s config overrides. +type BetaComputerMiddleClickConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -// Returns a subunion which exports methods to access subproperties -// -// Or use AsAny() to get the underlying value -func (u BetaContextManagementConfigEditUnionParam) GetKeep() (res betaContextManagementConfigEditUnionParamKeep) { - if vt := u.OfClearToolUses20250919; vt != nil { - res.any = &vt.Keep - } else if vt := u.OfClearThinking20251015; vt != nil { - res.any = vt.Keep.asAny() - } - return +func (r BetaComputerMiddleClickConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaComputerMiddleClickConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaComputerMiddleClickConfigParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Can have the runtime types [*BetaToolUsesKeepParam], [*string] -type betaContextManagementConfigEditUnionParamKeep struct{ any } +// `mouse_move`'s config overrides. +type BetaComputerMouseMoveConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj +} -// Use the following switch statement to get the type of the union: -// -// switch u.AsAny().(type) { -// case *anthropic.BetaToolUsesKeepParam: -// case *string: -// default: -// fmt.Errorf("not present") -// } -func (u betaContextManagementConfigEditUnionParamKeep) AsAny() any { return u.any } +func (r BetaComputerMouseMoveConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaComputerMouseMoveConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaComputerMouseMoveConfigParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} -// Returns a pointer to the underlying variant's property, if present. -func (u betaContextManagementConfigEditUnionParamKeep) GetType() *string { - switch vt := u.any.(type) { - case *BetaToolUsesKeepParam: - return (*string)(&vt.Type) - case *BetaClearThinking20251015EditKeepUnionParam: - return vt.GetType() - } - return nil +// `right_click`'s config overrides. +type BetaComputerRightClickConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -// Returns a pointer to the underlying variant's property, if present. -func (u betaContextManagementConfigEditUnionParamKeep) GetValue() *int64 { - switch vt := u.any.(type) { - case *BetaToolUsesKeepParam: - return (*int64)(&vt.Value) - case *BetaClearThinking20251015EditKeepUnionParam: - return vt.GetValue() - } - return nil +func (r BetaComputerRightClickConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaComputerRightClickConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaComputerRightClickConfigParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func init() { - apijson.RegisterUnion[BetaContextManagementConfigEditUnionParam]( - "type", - apijson.Discriminator[BetaClearToolUses20250919EditParam]("clear_tool_uses_20250919"), - apijson.Discriminator[BetaClearThinking20251015EditParam]("clear_thinking_20251015"), - apijson.Discriminator[BetaCompact20260112EditParam]("compact_20260112"), - ) +// `screenshot`'s config overrides. +type BetaComputerScreenshotConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -type BetaContextManagementResponse struct { - // List of context management edits that were applied. - AppliedEdits []BetaContextManagementResponseAppliedEditUnion `json:"applied_edits" api:"required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - AppliedEdits respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +func (r BetaComputerScreenshotConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaComputerScreenshotConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaComputerScreenshotConfigParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns the unmodified JSON received from the API -func (r BetaContextManagementResponse) RawJSON() string { return r.JSON.raw } -func (r *BetaContextManagementResponse) UnmarshalJSON(data []byte) error { +// `scroll`'s config overrides. +type BetaComputerScrollConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj +} + +func (r BetaComputerScrollConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaComputerScrollConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaComputerScrollConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// BetaContextManagementResponseAppliedEditUnion contains all possible properties -// and values from [BetaClearToolUses20250919EditResponse], -// [BetaClearThinking20251015EditResponse]. -// -// Use the [BetaContextManagementResponseAppliedEditUnion.AsAny] method to switch -// on the variant. +// The computer toolset: a single `tools[]` entry (carrying no `name`) that +// declares the computer tool family. The model is served the family's tool with +// any members disabled via `configs` removed from its schema. Every member is +// enabled by default, zoom included. The single-tool options `display_number` and +// `enable_zoom` are not fields of a toolset entry — it carries only `type`, +// `configs`, and `cache_control`; zoom is controlled via `configs.zoom.enabled`. // -// Use the methods beginning with 'As' to cast the union to one of its variants. -type BetaContextManagementResponseAppliedEditUnion struct { - ClearedInputTokens int64 `json:"cleared_input_tokens"` - // This field is from variant [BetaClearToolUses20250919EditResponse]. - ClearedToolUses int64 `json:"cleared_tool_uses"` - // Any of "clear_tool_uses_20250919", "clear_thinking_20251015". - Type string `json:"type"` - // This field is from variant [BetaClearThinking20251015EditResponse]. - ClearedThinkingTurns int64 `json:"cleared_thinking_turns"` - JSON struct { - ClearedInputTokens respjson.Field - ClearedToolUses respjson.Field - Type respjson.Field - ClearedThinkingTurns respjson.Field - raw string - } `json:"-"` +// The property Type is required. +type BetaComputerToolset20260801Param struct { + // Any of "direct", "code_execution_20250825", "code_execution_20260120", + // "code_execution_20260521". + AllowedCallers []string `json:"allowed_callers,omitzero"` + // Create a cache control breakpoint at this content block. + CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` + // Per-member configuration for `computer_toolset_20260801`: one optional field per + // member tool, keyed by the member name — the same name the member's `tool_use` + // blocks carry. Every member is an accepted key, and a member's defaults apply + // wherever its key is absent. Unknown keys are rejected: the field set is this + // toolset version's complete member set. + Configs BetaComputerToolsetConfigsParam `json:"configs,omitzero"` + // This field can be elided, and will marshal its zero value as + // "computer_toolset_20260801". + Type constant.ComputerToolset20260801 `json:"type" default:"computer_toolset_20260801"` + paramObj } -// anyBetaContextManagementResponseAppliedEdit is implemented by each variant of -// [BetaContextManagementResponseAppliedEditUnion] to add type safety for the -// return type of [BetaContextManagementResponseAppliedEditUnion.AsAny] -type anyBetaContextManagementResponseAppliedEdit interface { - implBetaContextManagementResponseAppliedEditUnion() +func (r BetaComputerToolset20260801Param) MarshalJSON() (data []byte, err error) { + type shadow BetaComputerToolset20260801Param + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaComputerToolset20260801Param) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func (BetaClearToolUses20250919EditResponse) implBetaContextManagementResponseAppliedEditUnion() {} -func (BetaClearThinking20251015EditResponse) implBetaContextManagementResponseAppliedEditUnion() {} +// Per-member configuration for `computer_toolset_20260801`: one optional field per +// member tool, keyed by the member name — the same name the member's `tool_use` +// blocks carry. Every member is an accepted key, and a member's defaults apply +// wherever its key is absent. Unknown keys are rejected: the field set is this +// toolset version's complete member set. +type BetaComputerToolsetConfigsParam struct { + // `cursor_position`'s config overrides. + CursorPosition BetaComputerCursorPositionConfigParam `json:"cursor_position,omitzero"` + // `double_click`'s config overrides. + DoubleClick BetaComputerDoubleClickConfigParam `json:"double_click,omitzero"` + // `hold_key`'s config overrides. + HoldKey BetaComputerHoldKeyConfigParam `json:"hold_key,omitzero"` + // `key`'s config overrides. + Key BetaComputerKeyConfigParam `json:"key,omitzero"` + // `left_click`'s config overrides. + LeftClick BetaComputerLeftClickConfigParam `json:"left_click,omitzero"` + // `left_click_drag`'s config overrides. + LeftClickDrag BetaComputerLeftClickDragConfigParam `json:"left_click_drag,omitzero"` + // `left_mouse_down`'s config overrides. + LeftMouseDown BetaComputerLeftMouseDownConfigParam `json:"left_mouse_down,omitzero"` + // `left_mouse_up`'s config overrides. + LeftMouseUp BetaComputerLeftMouseUpConfigParam `json:"left_mouse_up,omitzero"` + // `middle_click`'s config overrides. + MiddleClick BetaComputerMiddleClickConfigParam `json:"middle_click,omitzero"` + // `mouse_move`'s config overrides. + MouseMove BetaComputerMouseMoveConfigParam `json:"mouse_move,omitzero"` + // `right_click`'s config overrides. + RightClick BetaComputerRightClickConfigParam `json:"right_click,omitzero"` + // `screenshot`'s config overrides. + Screenshot BetaComputerScreenshotConfigParam `json:"screenshot,omitzero"` + // `scroll`'s config overrides. + Scroll BetaComputerScrollConfigParam `json:"scroll,omitzero"` + // `triple_click`'s config overrides. + TripleClick BetaComputerTripleClickConfigParam `json:"triple_click,omitzero"` + // `type`'s config overrides. + Type BetaComputerTypeConfigParam `json:"type,omitzero"` + // `wait`'s config overrides. + Wait BetaComputerWaitConfigParam `json:"wait,omitzero"` + // `zoom`'s config overrides. + Zoom BetaComputerZoomConfigParam `json:"zoom,omitzero"` + paramObj +} -// Use the following switch statement to find the correct variant -// -// switch variant := BetaContextManagementResponseAppliedEditUnion.AsAny().(type) { -// case anthropic.BetaClearToolUses20250919EditResponse: -// case anthropic.BetaClearThinking20251015EditResponse: -// default: -// fmt.Errorf("no variant present") -// } -func (u BetaContextManagementResponseAppliedEditUnion) AsAny() anyBetaContextManagementResponseAppliedEdit { - switch u.Type { - case "clear_tool_uses_20250919": - return u.AsClearToolUses20250919() - case "clear_thinking_20251015": - return u.AsClearThinking20251015() - } - return nil +func (r BetaComputerToolsetConfigsParam) MarshalJSON() (data []byte, err error) { + type shadow BetaComputerToolsetConfigsParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaComputerToolsetConfigsParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func (u BetaContextManagementResponseAppliedEditUnion) AsClearToolUses20250919() (v BetaClearToolUses20250919EditResponse) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +// `triple_click`'s config overrides. +type BetaComputerTripleClickConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -func (u BetaContextManagementResponseAppliedEditUnion) AsClearThinking20251015() (v BetaClearThinking20251015EditResponse) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +func (r BetaComputerTripleClickConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaComputerTripleClickConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaComputerTripleClickConfigParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns the unmodified JSON received from the API -func (u BetaContextManagementResponseAppliedEditUnion) RawJSON() string { return u.JSON.raw } +// `type`'s config overrides. +type BetaComputerTypeConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj +} -func (r *BetaContextManagementResponseAppliedEditUnion) UnmarshalJSON(data []byte) error { +func (r BetaComputerTypeConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaComputerTypeConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaComputerTypeConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type BetaCountTokensContextManagementResponse struct { - // The original token count before context management was applied - OriginalInputTokens int64 `json:"original_input_tokens" api:"required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - OriginalInputTokens respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +// `wait`'s config overrides. +type BetaComputerWaitConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -// Returns the unmodified JSON received from the API -func (r BetaCountTokensContextManagementResponse) RawJSON() string { return r.JSON.raw } -func (r *BetaCountTokensContextManagementResponse) UnmarshalJSON(data []byte) error { +func (r BetaComputerWaitConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaComputerWaitConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaComputerWaitConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// Tool invocation directly from the model. -type BetaDirectCaller struct { - Type constant.Direct `json:"type" default:"direct"` +// `zoom`'s config overrides. +type BetaComputerZoomConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj +} + +func (r BetaComputerZoomConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaComputerZoomConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaComputerZoomConfigParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Information about the container used in the request (for the code execution +// tool) +type BetaContainer struct { + // Identifier for the container used in this request + ID string `json:"id" api:"required"` + // The time at which the container will expire. + ExpiresAt time.Time `json:"expires_at" api:"required" format:"date-time"` + // Skills loaded in the container + Skills []BetaSkill `json:"skills" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { - Type respjson.Field + ID respjson.Field + ExpiresAt respjson.Field + Skills respjson.Field ExtraFields map[string]respjson.Field raw string } `json:"-"` } // Returns the unmodified JSON received from the API -func (r BetaDirectCaller) RawJSON() string { return r.JSON.raw } -func (r *BetaDirectCaller) UnmarshalJSON(data []byte) error { +func (r BetaContainer) RawJSON() string { return r.JSON.raw } +func (r *BetaContainer) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// ToParam converts this BetaDirectCaller to a BetaDirectCallerParam. -// -// Warning: the fields of the param type will not be present. ToParam should only -// be used at the last possible moment before sending a request. Test for this with -// BetaDirectCallerParam.Overrides() -func (r BetaDirectCaller) ToParam() BetaDirectCallerParam { - return param.Override[BetaDirectCallerParam](json.RawMessage(r.RawJSON())) -} - -func NewBetaDirectCallerParam() BetaDirectCallerParam { - return BetaDirectCallerParam{ - Type: "direct", - } -} - -// Tool invocation directly from the model. -// -// This struct has a constant value, construct it with [NewBetaDirectCallerParam]. -type BetaDirectCallerParam struct { - Type constant.Direct `json:"type" default:"direct"` +// Container parameters with skills to be loaded. +type BetaContainerParams struct { + // Container id + ID param.Opt[string] `json:"id,omitzero"` + // List of skills to load in the container + Skills []BetaSkillParams `json:"skills,omitzero"` paramObj } -func (r BetaDirectCallerParam) MarshalJSON() (data []byte, err error) { - type shadow BetaDirectCallerParam +func (r BetaContainerParams) MarshalJSON() (data []byte, err error) { + type shadow BetaContainerParams return param.MarshalObject(r, (*shadow)(&r)) } -func (r *BetaDirectCallerParam) UnmarshalJSON(data []byte) error { +func (r *BetaContainerParams) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type BetaDocumentBlock struct { - // Citation configuration for the document - Citations BetaCitationConfig `json:"citations" api:"required"` - Source BetaDocumentBlockSourceUnion `json:"source" api:"required"` - // The title of the document - Title string `json:"title" api:"required"` - Type constant.Document `json:"type" default:"document"` +// Response model for a file uploaded to the container. +type BetaContainerUploadBlock struct { + FileID string `json:"file_id" api:"required"` + Type constant.ContainerUpload `json:"type" default:"container_upload"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { - Citations respjson.Field - Source respjson.Field - Title respjson.Field + FileID respjson.Field Type respjson.Field ExtraFields map[string]respjson.Field raw string @@ -4079,2432 +3893,2187 @@ type BetaDocumentBlock struct { } // Returns the unmodified JSON received from the API -func (r BetaDocumentBlock) RawJSON() string { return r.JSON.raw } -func (r *BetaDocumentBlock) UnmarshalJSON(data []byte) error { +func (r BetaContainerUploadBlock) RawJSON() string { return r.JSON.raw } +func (r *BetaContainerUploadBlock) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// BetaDocumentBlockSourceUnion contains all possible properties and values from -// [BetaBase64PDFSource], [BetaPlainTextSource]. -// -// Use the [BetaDocumentBlockSourceUnion.AsAny] method to switch on the variant. +// A content block that represents a file to be uploaded to the container Files +// uploaded via this block will be available in the container's input directory. // -// Use the methods beginning with 'As' to cast the union to one of its variants. -type BetaDocumentBlockSourceUnion struct { - Data string `json:"data"` - MediaType string `json:"media_type"` - // Any of "base64", "text". - Type string `json:"type"` - JSON struct { - Data respjson.Field - MediaType respjson.Field - Type respjson.Field - raw string - } `json:"-"` +// The properties FileID, Type are required. +type BetaContainerUploadBlockParam struct { + FileID string `json:"file_id" api:"required"` + // Create a cache control breakpoint at this content block. + CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` + // This field can be elided, and will marshal its zero value as "container_upload". + Type constant.ContainerUpload `json:"type" default:"container_upload"` + paramObj } -// anyBetaDocumentBlockSource is implemented by each variant of -// [BetaDocumentBlockSourceUnion] to add type safety for the return type of -// [BetaDocumentBlockSourceUnion.AsAny] -type anyBetaDocumentBlockSource interface { - implBetaDocumentBlockSourceUnion() +func (r BetaContainerUploadBlockParam) MarshalJSON() (data []byte, err error) { + type shadow BetaContainerUploadBlockParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaContainerUploadBlockParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func (BetaBase64PDFSource) implBetaDocumentBlockSourceUnion() {} -func (BetaPlainTextSource) implBetaDocumentBlockSourceUnion() {} +// BetaContentBlockUnion contains all possible properties and values from +// [BetaTextBlock], [BetaThinkingBlock], [BetaRedactedThinkingBlock], +// [BetaToolUseBlock], [BetaServerToolUseBlock], [BetaWebSearchToolResultBlock], +// [BetaWebFetchToolResultBlock], [BetaAdvisorToolResultBlock], +// [BetaCodeExecutionToolResultBlock], [BetaBashCodeExecutionToolResultBlock], +// [BetaTextEditorCodeExecutionToolResultBlock], [BetaToolSearchToolResultBlock], +// [BetaMCPToolUseBlock], [BetaMCPToolResultBlock], [BetaContainerUploadBlock], +// [BetaCompactionBlock], [BetaFallbackBlock]. +// +// Use the [BetaContentBlockUnion.AsAny] method to switch on the variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaContentBlockUnion struct { + // This field is from variant [BetaTextBlock]. + Citations []BetaTextCitationUnion `json:"citations"` + // This field is from variant [BetaTextBlock]. + Text string `json:"text"` + // Any of "text", "thinking", "redacted_thinking", "tool_use", "server_tool_use", + // "web_search_tool_result", "web_fetch_tool_result", "advisor_tool_result", + // "code_execution_tool_result", "bash_code_execution_tool_result", + // "text_editor_code_execution_tool_result", "tool_search_tool_result", + // "mcp_tool_use", "mcp_tool_result", "container_upload", "compaction", "fallback". + Type string `json:"type"` + // This field is from variant [BetaThinkingBlock]. + Signature string `json:"signature"` + // This field is from variant [BetaThinkingBlock]. + Thinking string `json:"thinking"` + // This field is from variant [BetaRedactedThinkingBlock]. + Data string `json:"data"` + ID string `json:"id"` + // necessary custom code modification + Input json.RawMessage `json:"input"` + Name string `json:"name"` + // This field is a union of [BetaToolUseBlockCallerUnion], + // [BetaServerToolUseBlockCallerUnion], [BetaWebSearchToolResultBlockCallerUnion], + // [BetaWebFetchToolResultBlockCallerUnion] + Caller BetaContentBlockUnionCaller `json:"caller"` + // This field is from variant [BetaToolUseBlock]. + ToolsetName string `json:"toolset_name"` + // This field is a union of [BetaWebSearchToolResultBlockContentUnion], + // [BetaWebFetchToolResultBlockContentUnion], + // [BetaAdvisorToolResultBlockContentUnion], + // [BetaCodeExecutionToolResultBlockContentUnion], + // [BetaBashCodeExecutionToolResultBlockContentUnion], + // [BetaTextEditorCodeExecutionToolResultBlockContentUnion], + // [BetaToolSearchToolResultBlockContentUnion], + // [BetaMCPToolResultBlockContentUnion], [string] + Content BetaContentBlockUnionContent `json:"content"` + ToolUseID string `json:"tool_use_id"` + // This field is from variant [BetaMCPToolUseBlock]. + ServerName string `json:"server_name"` + // This field is from variant [BetaMCPToolResultBlock]. + IsError bool `json:"is_error"` + // This field is from variant [BetaContainerUploadBlock]. + FileID string `json:"file_id"` + // This field is from variant [BetaCompactionBlock]. + EncryptedContent string `json:"encrypted_content"` + // This field is from variant [BetaFallbackBlock]. + From BetaFallbackInfo `json:"from"` + // This field is from variant [BetaFallbackBlock]. + To BetaFallbackInfo `json:"to"` + // This field is from variant [BetaFallbackBlock]. + Trigger BetaFallbackRefusalTrigger `json:"trigger"` + JSON struct { + Citations respjson.Field + Text respjson.Field + Type respjson.Field + Signature respjson.Field + Thinking respjson.Field + Data respjson.Field + ID respjson.Field + Input respjson.Field + Name respjson.Field + Caller respjson.Field + ToolsetName respjson.Field + Content respjson.Field + ToolUseID respjson.Field + ServerName respjson.Field + IsError respjson.Field + FileID respjson.Field + EncryptedContent respjson.Field + From respjson.Field + To respjson.Field + Trigger respjson.Field + raw string + } `json:"-"` +} + +// anyBetaContentBlock is implemented by each variant of [BetaContentBlockUnion] to +// add type safety for the return type of [BetaContentBlockUnion.AsAny] +type anyBetaContentBlock interface { + implBetaContentBlockUnion() + toParamUnion() BetaContentBlockParamUnion +} + +func (BetaTextBlock) implBetaContentBlockUnion() {} +func (BetaThinkingBlock) implBetaContentBlockUnion() {} +func (BetaRedactedThinkingBlock) implBetaContentBlockUnion() {} +func (BetaToolUseBlock) implBetaContentBlockUnion() {} +func (BetaServerToolUseBlock) implBetaContentBlockUnion() {} +func (BetaWebSearchToolResultBlock) implBetaContentBlockUnion() {} +func (BetaWebFetchToolResultBlock) implBetaContentBlockUnion() {} +func (BetaAdvisorToolResultBlock) implBetaContentBlockUnion() {} +func (BetaCodeExecutionToolResultBlock) implBetaContentBlockUnion() {} +func (BetaBashCodeExecutionToolResultBlock) implBetaContentBlockUnion() {} +func (BetaTextEditorCodeExecutionToolResultBlock) implBetaContentBlockUnion() {} +func (BetaToolSearchToolResultBlock) implBetaContentBlockUnion() {} +func (BetaMCPToolUseBlock) implBetaContentBlockUnion() {} +func (BetaMCPToolResultBlock) implBetaContentBlockUnion() {} +func (BetaContainerUploadBlock) implBetaContentBlockUnion() {} +func (BetaCompactionBlock) implBetaContentBlockUnion() {} +func (BetaFallbackBlock) implBetaContentBlockUnion() {} // Use the following switch statement to find the correct variant // -// switch variant := BetaDocumentBlockSourceUnion.AsAny().(type) { -// case anthropic.BetaBase64PDFSource: -// case anthropic.BetaPlainTextSource: +// switch variant := BetaContentBlockUnion.AsAny().(type) { +// case anthropic.BetaTextBlock: +// case anthropic.BetaThinkingBlock: +// case anthropic.BetaRedactedThinkingBlock: +// case anthropic.BetaToolUseBlock: +// case anthropic.BetaServerToolUseBlock: +// case anthropic.BetaWebSearchToolResultBlock: +// case anthropic.BetaWebFetchToolResultBlock: +// case anthropic.BetaAdvisorToolResultBlock: +// case anthropic.BetaCodeExecutionToolResultBlock: +// case anthropic.BetaBashCodeExecutionToolResultBlock: +// case anthropic.BetaTextEditorCodeExecutionToolResultBlock: +// case anthropic.BetaToolSearchToolResultBlock: +// case anthropic.BetaMCPToolUseBlock: +// case anthropic.BetaMCPToolResultBlock: +// case anthropic.BetaContainerUploadBlock: +// case anthropic.BetaCompactionBlock: +// case anthropic.BetaFallbackBlock: // default: // fmt.Errorf("no variant present") // } -func (u BetaDocumentBlockSourceUnion) AsAny() anyBetaDocumentBlockSource { +func (u BetaContentBlockUnion) AsAny() anyBetaContentBlock { switch u.Type { - case "base64": - return u.AsBase64() case "text": return u.AsText() + case "thinking": + return u.AsThinking() + case "redacted_thinking": + return u.AsRedactedThinking() + case "tool_use": + return u.AsToolUse() + case "server_tool_use": + return u.AsServerToolUse() + case "web_search_tool_result": + return u.AsWebSearchToolResult() + case "web_fetch_tool_result": + return u.AsWebFetchToolResult() + case "advisor_tool_result": + return u.AsAdvisorToolResult() + case "code_execution_tool_result": + return u.AsCodeExecutionToolResult() + case "bash_code_execution_tool_result": + return u.AsBashCodeExecutionToolResult() + case "text_editor_code_execution_tool_result": + return u.AsTextEditorCodeExecutionToolResult() + case "tool_search_tool_result": + return u.AsToolSearchToolResult() + case "mcp_tool_use": + return u.AsMCPToolUse() + case "mcp_tool_result": + return u.AsMCPToolResult() + case "container_upload": + return u.AsContainerUpload() + case "compaction": + return u.AsCompaction() + case "fallback": + return u.AsFallback() } return nil } -func (u BetaDocumentBlockSourceUnion) AsBase64() (v BetaBase64PDFSource) { +func (u BetaContentBlockUnion) AsText() (v BetaTextBlock) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return } -func (u BetaDocumentBlockSourceUnion) AsText() (v BetaPlainTextSource) { +func (u BetaContentBlockUnion) AsThinking() (v BetaThinkingBlock) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return } -// Returns the unmodified JSON received from the API -func (u BetaDocumentBlockSourceUnion) RawJSON() string { return u.JSON.raw } - -func (r *BetaDocumentBlockSourceUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +func (u BetaContentBlockUnion) AsRedactedThinking() (v BetaRedactedThinkingBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -// Code execution result with encrypted stdout for PFC + web_search results. -type BetaEncryptedCodeExecutionResultBlock struct { - Content []BetaCodeExecutionOutputBlock `json:"content" api:"required"` - EncryptedStdout string `json:"encrypted_stdout" api:"required"` - ReturnCode int64 `json:"return_code" api:"required"` - Stderr string `json:"stderr" api:"required"` - Type constant.EncryptedCodeExecutionResult `json:"type" default:"encrypted_code_execution_result"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Content respjson.Field - EncryptedStdout respjson.Field - ReturnCode respjson.Field - Stderr respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +func (u BetaContentBlockUnion) AsToolUse() (v BetaToolUseBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -// Returns the unmodified JSON received from the API -func (r BetaEncryptedCodeExecutionResultBlock) RawJSON() string { return r.JSON.raw } -func (r *BetaEncryptedCodeExecutionResultBlock) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +func (u BetaContentBlockUnion) AsServerToolUse() (v BetaServerToolUseBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -// Code execution result with encrypted stdout for PFC + web_search results. -// -// The properties Content, EncryptedStdout, ReturnCode, Stderr, Type are required. -type BetaEncryptedCodeExecutionResultBlockParam struct { - Content []BetaCodeExecutionOutputBlockParam `json:"content,omitzero" api:"required"` - EncryptedStdout string `json:"encrypted_stdout" api:"required"` - ReturnCode int64 `json:"return_code" api:"required"` - Stderr string `json:"stderr" api:"required"` - // This field can be elided, and will marshal its zero value as - // "encrypted_code_execution_result". - Type constant.EncryptedCodeExecutionResult `json:"type" default:"encrypted_code_execution_result"` - paramObj +func (u BetaContentBlockUnion) AsWebSearchToolResult() (v BetaWebSearchToolResultBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -func (r BetaEncryptedCodeExecutionResultBlockParam) MarshalJSON() (data []byte, err error) { - type shadow BetaEncryptedCodeExecutionResultBlockParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaEncryptedCodeExecutionResultBlockParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +func (u BetaContentBlockUnion) AsWebFetchToolResult() (v BetaWebFetchToolResultBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -// The properties FileID, Type are required. -type BetaFileDocumentSourceParam struct { - FileID string `json:"file_id" api:"required"` - // This field can be elided, and will marshal its zero value as "file". - Type constant.File `json:"type" default:"file"` - paramObj +func (u BetaContentBlockUnion) AsAdvisorToolResult() (v BetaAdvisorToolResultBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -func (r BetaFileDocumentSourceParam) MarshalJSON() (data []byte, err error) { - type shadow BetaFileDocumentSourceParam - return param.MarshalObject(r, (*shadow)(&r)) +func (u BetaContentBlockUnion) AsCodeExecutionToolResult() (v BetaCodeExecutionToolResultBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -func (r *BetaFileDocumentSourceParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) + +func (u BetaContentBlockUnion) AsBashCodeExecutionToolResult() (v BetaBashCodeExecutionToolResultBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -// The properties FileID, Type are required. -type BetaFileImageSourceParam struct { - FileID string `json:"file_id" api:"required"` - // This field can be elided, and will marshal its zero value as "file". - Type constant.File `json:"type" default:"file"` - paramObj -} - -func (r BetaFileImageSourceParam) MarshalJSON() (data []byte, err error) { - type shadow BetaFileImageSourceParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaFileImageSourceParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The properties Source, Type are required. -type BetaImageBlockParam struct { - Source BetaImageBlockParamSourceUnion `json:"source,omitzero" api:"required"` - // Create a cache control breakpoint at this content block. - CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` - // This field can be elided, and will marshal its zero value as "image". - Type constant.Image `json:"type" default:"image"` - paramObj -} - -func (r BetaImageBlockParam) MarshalJSON() (data []byte, err error) { - type shadow BetaImageBlockParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaImageBlockParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type BetaImageBlockParamSourceUnion struct { - OfBase64 *BetaBase64ImageSourceParam `json:",omitzero,inline"` - OfURL *BetaURLImageSourceParam `json:",omitzero,inline"` - OfFile *BetaFileImageSourceParam `json:",omitzero,inline"` - paramUnion -} - -func (u BetaImageBlockParamSourceUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfBase64, u.OfURL, u.OfFile) -} -func (u *BetaImageBlockParamSourceUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *BetaImageBlockParamSourceUnion) asAny() any { - if !param.IsOmitted(u.OfBase64) { - return u.OfBase64 - } else if !param.IsOmitted(u.OfURL) { - return u.OfURL - } else if !param.IsOmitted(u.OfFile) { - return u.OfFile - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u BetaImageBlockParamSourceUnion) GetData() *string { - if vt := u.OfBase64; vt != nil { - return &vt.Data - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u BetaImageBlockParamSourceUnion) GetMediaType() *string { - if vt := u.OfBase64; vt != nil { - return (*string)(&vt.MediaType) - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u BetaImageBlockParamSourceUnion) GetURL() *string { - if vt := u.OfURL; vt != nil { - return &vt.URL - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u BetaImageBlockParamSourceUnion) GetFileID() *string { - if vt := u.OfFile; vt != nil { - return &vt.FileID - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u BetaImageBlockParamSourceUnion) GetType() *string { - if vt := u.OfBase64; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfURL; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfFile; vt != nil { - return (*string)(&vt.Type) - } - return nil -} - -func init() { - apijson.RegisterUnion[BetaImageBlockParamSourceUnion]( - "type", - apijson.Discriminator[BetaBase64ImageSourceParam]("base64"), - apijson.Discriminator[BetaURLImageSourceParam]("url"), - apijson.Discriminator[BetaFileImageSourceParam]("file"), - ) -} - -type BetaInputJSONDelta struct { - PartialJSON string `json:"partial_json" api:"required"` - Type constant.InputJSONDelta `json:"type" default:"input_json_delta"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - PartialJSON respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r BetaInputJSONDelta) RawJSON() string { return r.JSON.raw } -func (r *BetaInputJSONDelta) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The properties Type, Value are required. -type BetaInputTokensClearAtLeastParam struct { - Value int64 `json:"value" api:"required"` - // This field can be elided, and will marshal its zero value as "input_tokens". - Type constant.InputTokens `json:"type" default:"input_tokens"` - paramObj -} - -func (r BetaInputTokensClearAtLeastParam) MarshalJSON() (data []byte, err error) { - type shadow BetaInputTokensClearAtLeastParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaInputTokensClearAtLeastParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The properties Type, Value are required. -type BetaInputTokensTriggerParam struct { - Value int64 `json:"value" api:"required"` - // This field can be elided, and will marshal its zero value as "input_tokens". - Type constant.InputTokens `json:"type" default:"input_tokens"` - paramObj -} - -func (r BetaInputTokensTriggerParam) MarshalJSON() (data []byte, err error) { - type shadow BetaInputTokensTriggerParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaInputTokensTriggerParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +func (u BetaContentBlockUnion) AsTextEditorCodeExecutionToolResult() (v BetaTextEditorCodeExecutionToolResultBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -type BetaIterationsUsage []BetaIterationsUsageItemUnion - -// BetaIterationsUsageItemUnion contains all possible properties and values from -// [BetaMessageIterationUsage], [BetaCompactionIterationUsage], -// [BetaAdvisorMessageIterationUsage]. -// -// Use the [BetaIterationsUsageItemUnion.AsAny] method to switch on the variant. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -type BetaIterationsUsageItemUnion struct { - // This field is from variant [BetaMessageIterationUsage]. - CacheCreation BetaCacheCreation `json:"cache_creation"` - CacheCreationInputTokens int64 `json:"cache_creation_input_tokens"` - CacheReadInputTokens int64 `json:"cache_read_input_tokens"` - InputTokens int64 `json:"input_tokens"` - OutputTokens int64 `json:"output_tokens"` - // Any of "message", "compaction", "advisor_message". - Type string `json:"type"` - // This field is from variant [BetaAdvisorMessageIterationUsage]. - Model Model `json:"model"` - JSON struct { - CacheCreation respjson.Field - CacheCreationInputTokens respjson.Field - CacheReadInputTokens respjson.Field - InputTokens respjson.Field - OutputTokens respjson.Field - Type respjson.Field - Model respjson.Field - raw string - } `json:"-"` +func (u BetaContentBlockUnion) AsToolSearchToolResult() (v BetaToolSearchToolResultBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -// anyBetaIterationsUsageItem is implemented by each variant of -// [BetaIterationsUsageItemUnion] to add type safety for the return type of -// [BetaIterationsUsageItemUnion.AsAny] -type anyBetaIterationsUsageItem interface { - implBetaIterationsUsageItemUnion() +func (u BetaContentBlockUnion) AsMCPToolUse() (v BetaMCPToolUseBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -func (BetaMessageIterationUsage) implBetaIterationsUsageItemUnion() {} -func (BetaCompactionIterationUsage) implBetaIterationsUsageItemUnion() {} -func (BetaAdvisorMessageIterationUsage) implBetaIterationsUsageItemUnion() {} - -// Use the following switch statement to find the correct variant -// -// switch variant := BetaIterationsUsageItemUnion.AsAny().(type) { -// case anthropic.BetaMessageIterationUsage: -// case anthropic.BetaCompactionIterationUsage: -// case anthropic.BetaAdvisorMessageIterationUsage: -// default: -// fmt.Errorf("no variant present") -// } -func (u BetaIterationsUsageItemUnion) AsAny() anyBetaIterationsUsageItem { - switch u.Type { - case "message": - return u.AsMessage() - case "compaction": - return u.AsCompaction() - case "advisor_message": - return u.AsAdvisorMessage() - } - return nil +func (u BetaContentBlockUnion) AsMCPToolResult() (v BetaMCPToolResultBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -func (u BetaIterationsUsageItemUnion) AsMessage() (v BetaMessageIterationUsage) { +func (u BetaContentBlockUnion) AsContainerUpload() (v BetaContainerUploadBlock) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return } -func (u BetaIterationsUsageItemUnion) AsCompaction() (v BetaCompactionIterationUsage) { +func (u BetaContentBlockUnion) AsCompaction() (v BetaCompactionBlock) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return } -func (u BetaIterationsUsageItemUnion) AsAdvisorMessage() (v BetaAdvisorMessageIterationUsage) { +func (u BetaContentBlockUnion) AsFallback() (v BetaFallbackBlock) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return } // Returns the unmodified JSON received from the API -func (u BetaIterationsUsageItemUnion) RawJSON() string { return u.JSON.raw } +func (u BetaContentBlockUnion) RawJSON() string { return u.JSON.raw } -func (r *BetaIterationsUsageItemUnion) UnmarshalJSON(data []byte) error { +func (r *BetaContentBlockUnion) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The properties Schema, Type are required. -type BetaJSONOutputFormatParam struct { - // The JSON schema of the format - Schema map[string]any `json:"schema,omitzero" api:"required"` - // This field can be elided, and will marshal its zero value as "json_schema". - Type constant.JSONSchema `json:"type" default:"json_schema"` - paramObj +// BetaContentBlockUnionCaller is an implicit subunion of [BetaContentBlockUnion]. +// BetaContentBlockUnionCaller provides convenient access to the sub-properties of +// the union. +// +// For type safety it is recommended to directly use a variant of the +// [BetaContentBlockUnion]. +type BetaContentBlockUnionCaller struct { + Type string `json:"type"` + ToolID string `json:"tool_id"` + JSON struct { + Type respjson.Field + ToolID respjson.Field + raw string + } `json:"-"` } -func (r BetaJSONOutputFormatParam) MarshalJSON() (data []byte, err error) { - type shadow BetaJSONOutputFormatParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaJSONOutputFormatParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Configuration for a specific tool in an MCP toolset. -type BetaMCPToolConfigParam struct { - DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` - Enabled param.Opt[bool] `json:"enabled,omitzero"` - paramObj -} - -func (r BetaMCPToolConfigParam) MarshalJSON() (data []byte, err error) { - type shadow BetaMCPToolConfigParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaMCPToolConfigParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Default configuration for tools in an MCP toolset. -type BetaMCPToolDefaultConfigParam struct { - DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` - Enabled param.Opt[bool] `json:"enabled,omitzero"` - paramObj -} - -func (r BetaMCPToolDefaultConfigParam) MarshalJSON() (data []byte, err error) { - type shadow BetaMCPToolDefaultConfigParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaMCPToolDefaultConfigParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type BetaMCPToolResultBlock struct { - Content BetaMCPToolResultBlockContentUnion `json:"content" api:"required"` - IsError bool `json:"is_error" api:"required"` - ToolUseID string `json:"tool_use_id" api:"required"` - Type constant.MCPToolResult `json:"type" default:"mcp_tool_result"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Content respjson.Field - IsError respjson.Field - ToolUseID respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r BetaMCPToolResultBlock) RawJSON() string { return r.JSON.raw } -func (r *BetaMCPToolResultBlock) UnmarshalJSON(data []byte) error { +func (r *BetaContentBlockUnionCaller) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// BetaMCPToolResultBlockContentUnion contains all possible properties and values -// from [string], [[]BetaTextBlock]. +// BetaContentBlockUnionContent is an implicit subunion of [BetaContentBlockUnion]. +// BetaContentBlockUnionContent provides convenient access to the sub-properties of +// the union. // -// Use the methods beginning with 'As' to cast the union to one of its variants. +// For type safety it is recommended to directly use a variant of the +// [BetaContentBlockUnion]. // // If the underlying value is not a json object, one of the following properties -// will be valid: OfString OfBetaMCPToolResultBlockContent] -type BetaMCPToolResultBlockContentUnion struct { +// will be valid: OfBetaWebSearchResultBlockArray OfString +// OfBetaMCPToolResultBlockContent] +type BetaContentBlockUnionContent struct { + // This field will be present if the value is a [[]BetaWebSearchResultBlock] + // instead of an object. + OfBetaWebSearchResultBlockArray []BetaWebSearchResultBlock `json:",inline"` // This field will be present if the value is a [string] instead of an object. OfString string `json:",inline"` // This field will be present if the value is a [[]BetaTextBlock] instead of an // object. OfBetaMCPToolResultBlockContent []BetaTextBlock `json:",inline"` - JSON struct { + ErrorCode string `json:"error_code"` + Type string `json:"type"` + // This field is a union of [BetaDocumentBlock], [[]BetaCodeExecutionOutputBlock], + // [[]BetaCodeExecutionOutputBlock], [[]BetaBashCodeExecutionOutputBlock], [string] + Content BetaContentBlockUnionContentContent `json:"content"` + // This field is from variant [BetaWebFetchToolResultBlockContentUnion]. + RetrievedAt string `json:"retrieved_at"` + // This field is from variant [BetaWebFetchToolResultBlockContentUnion]. + URL string `json:"url"` + StopReason string `json:"stop_reason"` + // This field is from variant [BetaAdvisorToolResultBlockContentUnion]. + Text string `json:"text"` + // This field is from variant [BetaAdvisorToolResultBlockContentUnion]. + EncryptedContent string `json:"encrypted_content"` + ReturnCode int64 `json:"return_code"` + Stderr string `json:"stderr"` + Stdout string `json:"stdout"` + // This field is from variant [BetaCodeExecutionToolResultBlockContentUnion]. + EncryptedStdout string `json:"encrypted_stdout"` + ErrorMessage string `json:"error_message"` + // This field is from variant + // [BetaTextEditorCodeExecutionToolResultBlockContentUnion]. + FileType BetaTextEditorCodeExecutionViewResultBlockFileType `json:"file_type"` + // This field is from variant + // [BetaTextEditorCodeExecutionToolResultBlockContentUnion]. + NumLines int64 `json:"num_lines"` + // This field is from variant + // [BetaTextEditorCodeExecutionToolResultBlockContentUnion]. + StartLine int64 `json:"start_line"` + // This field is from variant + // [BetaTextEditorCodeExecutionToolResultBlockContentUnion]. + TotalLines int64 `json:"total_lines"` + // This field is from variant + // [BetaTextEditorCodeExecutionToolResultBlockContentUnion]. + IsFileUpdate bool `json:"is_file_update"` + // This field is from variant + // [BetaTextEditorCodeExecutionToolResultBlockContentUnion]. + Lines []string `json:"lines"` + // This field is from variant + // [BetaTextEditorCodeExecutionToolResultBlockContentUnion]. + NewLines int64 `json:"new_lines"` + // This field is from variant + // [BetaTextEditorCodeExecutionToolResultBlockContentUnion]. + NewStart int64 `json:"new_start"` + // This field is from variant + // [BetaTextEditorCodeExecutionToolResultBlockContentUnion]. + OldLines int64 `json:"old_lines"` + // This field is from variant + // [BetaTextEditorCodeExecutionToolResultBlockContentUnion]. + OldStart int64 `json:"old_start"` + // This field is from variant [BetaToolSearchToolResultBlockContentUnion]. + ToolReferences []BetaToolReferenceBlock `json:"tool_references"` + JSON struct { + OfBetaWebSearchResultBlockArray respjson.Field OfString respjson.Field OfBetaMCPToolResultBlockContent respjson.Field + ErrorCode respjson.Field + Type respjson.Field + Content respjson.Field + RetrievedAt respjson.Field + URL respjson.Field + StopReason respjson.Field + Text respjson.Field + EncryptedContent respjson.Field + ReturnCode respjson.Field + Stderr respjson.Field + Stdout respjson.Field + EncryptedStdout respjson.Field + ErrorMessage respjson.Field + FileType respjson.Field + NumLines respjson.Field + StartLine respjson.Field + TotalLines respjson.Field + IsFileUpdate respjson.Field + Lines respjson.Field + NewLines respjson.Field + NewStart respjson.Field + OldLines respjson.Field + OldStart respjson.Field + ToolReferences respjson.Field raw string } `json:"-"` } -func (u BetaMCPToolResultBlockContentUnion) AsString() (v string) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u BetaMCPToolResultBlockContentUnion) AsBetaMCPToolResultBlockContent() (v []BetaTextBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -// Returns the unmodified JSON received from the API -func (u BetaMCPToolResultBlockContentUnion) RawJSON() string { return u.JSON.raw } - -func (r *BetaMCPToolResultBlockContentUnion) UnmarshalJSON(data []byte) error { +func (r *BetaContentBlockUnionContent) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type BetaMCPToolUseBlock struct { - ID string `json:"id" api:"required"` - Input any `json:"input" api:"required"` - // The name of the MCP tool - Name string `json:"name" api:"required"` - // The name of the MCP server - ServerName string `json:"server_name" api:"required"` - Type constant.MCPToolUse `json:"type" default:"mcp_tool_use"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. +// BetaContentBlockUnionContentContent is an implicit subunion of +// [BetaContentBlockUnion]. BetaContentBlockUnionContentContent provides convenient +// access to the sub-properties of the union. +// +// For type safety it is recommended to directly use a variant of the +// [BetaContentBlockUnion]. +// +// If the underlying value is not a json object, one of the following properties +// will be valid: OfContent OfString] +type BetaContentBlockUnionContentContent struct { + // This field will be present if the value is a [[]BetaCodeExecutionOutputBlock] + // instead of an object. + OfContent []BetaCodeExecutionOutputBlock `json:",inline"` + // This field will be present if the value is a [string] instead of an object. + OfString string `json:",inline"` + // This field is from variant [BetaDocumentBlock]. + Citations BetaCitationConfig `json:"citations"` + // This field is from variant [BetaDocumentBlock]. + Source BetaDocumentBlockSourceUnion `json:"source"` + // This field is from variant [BetaDocumentBlock]. + Title string `json:"title"` + // This field is from variant [BetaDocumentBlock]. + Type constant.Document `json:"type"` JSON struct { - ID respjson.Field - Input respjson.Field - Name respjson.Field - ServerName respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string + OfContent respjson.Field + OfString respjson.Field + Citations respjson.Field + Source respjson.Field + Title respjson.Field + Type respjson.Field + raw string } `json:"-"` } -// Returns the unmodified JSON received from the API -func (r BetaMCPToolUseBlock) RawJSON() string { return r.JSON.raw } -func (r *BetaMCPToolUseBlock) UnmarshalJSON(data []byte) error { +func (r *BetaContentBlockUnionContentContent) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The properties ID, Input, Name, ServerName, Type are required. -type BetaMCPToolUseBlockParam struct { - ID string `json:"id" api:"required"` - Input any `json:"input,omitzero" api:"required"` - Name string `json:"name" api:"required"` - // The name of the MCP server - ServerName string `json:"server_name" api:"required"` - // Create a cache control breakpoint at this content block. - CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` - // This field can be elided, and will marshal its zero value as "mcp_tool_use". - Type constant.MCPToolUse `json:"type" default:"mcp_tool_use"` - paramObj +func NewBetaTextBlock(text string) BetaContentBlockParamUnion { + var variant BetaTextBlockParam + variant.Text = text + return BetaContentBlockParamUnion{OfText: &variant} } -func (r BetaMCPToolUseBlockParam) MarshalJSON() (data []byte, err error) { - type shadow BetaMCPToolUseBlockParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaMCPToolUseBlockParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +func NewBetaImageBlock[ + T BetaBase64ImageSourceParam | BetaURLImageSourceParam | BetaFileImageSourceParam, +](source T) BetaContentBlockParamUnion { + var image BetaImageBlockParam + switch v := any(source).(type) { + case BetaBase64ImageSourceParam: + image.Source.OfBase64 = &v + case BetaURLImageSourceParam: + image.Source.OfURL = &v + case BetaFileImageSourceParam: + image.Source.OfFile = &v + } + return BetaContentBlockParamUnion{OfImage: &image} } -// Configuration for a group of tools from an MCP server. -// -// Allows configuring enabled status and defer_loading for all tools from an MCP -// server, with optional per-tool overrides. -// -// The properties MCPServerName, Type are required. -type BetaMCPToolsetParam struct { - // Name of the MCP server to configure tools for - MCPServerName string `json:"mcp_server_name" api:"required"` - // Configuration overrides for specific tools, keyed by tool name - Configs map[string]BetaMCPToolConfigParam `json:"configs,omitzero"` - // Create a cache control breakpoint at this content block. - CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` - // Default configuration applied to all tools from this server - DefaultConfig BetaMCPToolDefaultConfigParam `json:"default_config,omitzero"` - // This field can be elided, and will marshal its zero value as "mcp_toolset". - Type constant.MCPToolset `json:"type" default:"mcp_toolset"` - paramObj +func NewBetaDocumentBlock[ + T BetaBase64PDFSourceParam | BetaPlainTextSourceParam | BetaContentBlockSourceParam | BetaURLPDFSourceParam | BetaFileDocumentSourceParam, +](source T) BetaContentBlockParamUnion { + var document BetaRequestDocumentBlockParam + switch v := any(source).(type) { + case BetaBase64PDFSourceParam: + document.Source.OfBase64 = &v + case BetaPlainTextSourceParam: + document.Source.OfText = &v + case BetaContentBlockSourceParam: + document.Source.OfContent = &v + case BetaURLPDFSourceParam: + document.Source.OfURL = &v + case BetaFileDocumentSourceParam: + document.Source.OfFile = &v + } + return BetaContentBlockParamUnion{OfDocument: &document} } -func (r BetaMCPToolsetParam) MarshalJSON() (data []byte, err error) { - type shadow BetaMCPToolsetParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaMCPToolsetParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +func NewBetaSearchResultBlock(content []BetaTextBlockParam, source string, title string) BetaContentBlockParamUnion { + var searchResult BetaSearchResultBlockParam + searchResult.Content = content + searchResult.Source = source + searchResult.Title = title + return BetaContentBlockParamUnion{OfSearchResult: &searchResult} } -// The properties Name, Type are required. -type BetaMemoryTool20250818Param struct { - // If true, tool will not be included in initial system prompt. Only loaded when - // returned via tool_reference from tool search. - DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` - // When true, guarantees schema validation on tool names and inputs - Strict param.Opt[bool] `json:"strict,omitzero"` - // Any of "direct", "code_execution_20250825", "code_execution_20260120". - AllowedCallers []string `json:"allowed_callers,omitzero"` - // Create a cache control breakpoint at this content block. - CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` - InputExamples []map[string]any `json:"input_examples,omitzero"` - // Name of the tool. - // - // This is how the tool will be called by the model and in `tool_use` blocks. - // - // This field can be elided, and will marshal its zero value as "memory". - Name constant.Memory `json:"name" default:"memory"` - // This field can be elided, and will marshal its zero value as "memory_20250818". - Type constant.Memory20250818 `json:"type" default:"memory_20250818"` - paramObj +func NewBetaThinkingBlock(signature string, thinking string) BetaContentBlockParamUnion { + var variant BetaThinkingBlockParam + variant.Signature = signature + variant.Thinking = thinking + return BetaContentBlockParamUnion{OfThinking: &variant} } -func (r BetaMemoryTool20250818Param) MarshalJSON() (data []byte, err error) { - type shadow BetaMemoryTool20250818Param - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaMemoryTool20250818Param) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +func NewBetaRedactedThinkingBlock(data string) BetaContentBlockParamUnion { + var redactedThinking BetaRedactedThinkingBlockParam + redactedThinking.Data = data + return BetaContentBlockParamUnion{OfRedactedThinking: &redactedThinking} } -// BetaMemoryTool20250818CommandUnion contains all possible properties and values -// from [BetaMemoryTool20250818ViewCommand], [BetaMemoryTool20250818CreateCommand], -// [BetaMemoryTool20250818StrReplaceCommand], -// [BetaMemoryTool20250818InsertCommand], [BetaMemoryTool20250818DeleteCommand], -// [BetaMemoryTool20250818RenameCommand]. -// -// Use the [BetaMemoryTool20250818CommandUnion.AsAny] method to switch on the -// variant. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -type BetaMemoryTool20250818CommandUnion struct { - // Any of "view", "create", "str_replace", "insert", "delete", "rename". - Command string `json:"command"` - Path string `json:"path"` - // This field is from variant [BetaMemoryTool20250818ViewCommand]. - ViewRange []int64 `json:"view_range"` - // This field is from variant [BetaMemoryTool20250818CreateCommand]. - FileText string `json:"file_text"` - // This field is from variant [BetaMemoryTool20250818StrReplaceCommand]. - NewStr string `json:"new_str"` - // This field is from variant [BetaMemoryTool20250818StrReplaceCommand]. - OldStr string `json:"old_str"` - // This field is from variant [BetaMemoryTool20250818InsertCommand]. - InsertLine int64 `json:"insert_line"` - // This field is from variant [BetaMemoryTool20250818InsertCommand]. - InsertText string `json:"insert_text"` - // This field is from variant [BetaMemoryTool20250818RenameCommand]. - NewPath string `json:"new_path"` - // This field is from variant [BetaMemoryTool20250818RenameCommand]. - OldPath string `json:"old_path"` - JSON struct { - Command respjson.Field - Path respjson.Field - ViewRange respjson.Field - FileText respjson.Field - NewStr respjson.Field - OldStr respjson.Field - InsertLine respjson.Field - InsertText respjson.Field - NewPath respjson.Field - OldPath respjson.Field - raw string - } `json:"-"` +func NewBetaToolUseBlock(id string, input any, name string) BetaContentBlockParamUnion { + var toolUse BetaToolUseBlockParam + toolUse.ID = id + toolUse.Input = input + toolUse.Name = name + return BetaContentBlockParamUnion{OfToolUse: &toolUse} } -// anyBetaMemoryTool20250818Command is implemented by each variant of -// [BetaMemoryTool20250818CommandUnion] to add type safety for the return type of -// [BetaMemoryTool20250818CommandUnion.AsAny] -type anyBetaMemoryTool20250818Command interface { - implBetaMemoryTool20250818CommandUnion() +func NewBetaToolResultBlock(toolUseID string, content string, isError bool) BetaContentBlockParamUnion { + var toolBlock BetaToolResultBlockParam + toolBlock.ToolUseID = toolUseID + toolBlock.Content = []BetaToolResultBlockParamContentUnion{ + {OfText: &BetaTextBlockParam{Text: content}}, + } + toolBlock.IsError = Bool(isError) + return BetaContentBlockParamUnion{OfToolResult: &toolBlock} } -func (BetaMemoryTool20250818ViewCommand) implBetaMemoryTool20250818CommandUnion() {} -func (BetaMemoryTool20250818CreateCommand) implBetaMemoryTool20250818CommandUnion() {} -func (BetaMemoryTool20250818StrReplaceCommand) implBetaMemoryTool20250818CommandUnion() {} -func (BetaMemoryTool20250818InsertCommand) implBetaMemoryTool20250818CommandUnion() {} -func (BetaMemoryTool20250818DeleteCommand) implBetaMemoryTool20250818CommandUnion() {} -func (BetaMemoryTool20250818RenameCommand) implBetaMemoryTool20250818CommandUnion() {} - -// Use the following switch statement to find the correct variant -// -// switch variant := BetaMemoryTool20250818CommandUnion.AsAny().(type) { -// case anthropic.BetaMemoryTool20250818ViewCommand: -// case anthropic.BetaMemoryTool20250818CreateCommand: -// case anthropic.BetaMemoryTool20250818StrReplaceCommand: -// case anthropic.BetaMemoryTool20250818InsertCommand: -// case anthropic.BetaMemoryTool20250818DeleteCommand: -// case anthropic.BetaMemoryTool20250818RenameCommand: -// default: -// fmt.Errorf("no variant present") -// } -func (u BetaMemoryTool20250818CommandUnion) AsAny() anyBetaMemoryTool20250818Command { - switch u.Command { - case "view": - return u.AsView() - case "create": - return u.AsCreate() - case "str_replace": - return u.AsStrReplace() - case "insert": - return u.AsInsert() - case "delete": - return u.AsDelete() - case "rename": - return u.AsRename() - } - return nil +func NewBetaServerToolUseBlock(id string, input any, name BetaServerToolUseBlockParamName) BetaContentBlockParamUnion { + var serverToolUse BetaServerToolUseBlockParam + serverToolUse.ID = id + serverToolUse.Input = input + serverToolUse.Name = name + return BetaContentBlockParamUnion{OfServerToolUse: &serverToolUse} } -func (u BetaMemoryTool20250818CommandUnion) AsView() (v BetaMemoryTool20250818ViewCommand) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +func NewBetaWebSearchToolResultBlock[ + T []BetaWebSearchResultBlockParam | BetaWebSearchToolRequestErrorParam, +](content T, toolUseID string) BetaContentBlockParamUnion { + var webSearchToolResult BetaWebSearchToolResultBlockParam + switch v := any(content).(type) { + case []BetaWebSearchResultBlockParam: + webSearchToolResult.Content.OfResultBlock = v + case BetaWebSearchToolRequestErrorParam: + webSearchToolResult.Content.OfError = &v + } + webSearchToolResult.ToolUseID = toolUseID + return BetaContentBlockParamUnion{OfWebSearchToolResult: &webSearchToolResult} } -func (u BetaMemoryTool20250818CommandUnion) AsCreate() (v BetaMemoryTool20250818CreateCommand) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +func NewBetaWebFetchToolResultBlock[ + T BetaWebFetchToolResultErrorBlockParam | BetaWebFetchBlockParam, +](content T, toolUseID string) BetaContentBlockParamUnion { + var webFetchToolResult BetaWebFetchToolResultBlockParam + switch v := any(content).(type) { + case BetaWebFetchToolResultErrorBlockParam: + webFetchToolResult.Content.OfRequestWebFetchToolResultError = &v + case BetaWebFetchBlockParam: + webFetchToolResult.Content.OfRequestWebFetchResultBlock = &v + } + webFetchToolResult.ToolUseID = toolUseID + return BetaContentBlockParamUnion{OfWebFetchToolResult: &webFetchToolResult} } -func (u BetaMemoryTool20250818CommandUnion) AsStrReplace() (v BetaMemoryTool20250818StrReplaceCommand) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +func NewBetaAdvisorToolResultBlock[ + T BetaAdvisorToolResultErrorParam | BetaAdvisorResultBlockParam | BetaAdvisorRedactedResultBlockParam, +](content T, toolUseID string) BetaContentBlockParamUnion { + var advisorToolResult BetaAdvisorToolResultBlockParam + switch v := any(content).(type) { + case BetaAdvisorToolResultErrorParam: + advisorToolResult.Content.OfRequestAdvisorToolResultError = &v + case BetaAdvisorResultBlockParam: + advisorToolResult.Content.OfRequestAdvisorResultBlock = &v + case BetaAdvisorRedactedResultBlockParam: + advisorToolResult.Content.OfRequestAdvisorRedactedResultBlock = &v + } + advisorToolResult.ToolUseID = toolUseID + return BetaContentBlockParamUnion{OfAdvisorToolResult: &advisorToolResult} } -func (u BetaMemoryTool20250818CommandUnion) AsInsert() (v BetaMemoryTool20250818InsertCommand) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +func NewBetaCodeExecutionToolResultBlock[ + T BetaCodeExecutionToolResultErrorParam | BetaCodeExecutionResultBlockParam | BetaEncryptedCodeExecutionResultBlockParam, +](content T, toolUseID string) BetaContentBlockParamUnion { + var codeExecutionToolResult BetaCodeExecutionToolResultBlockParam + switch v := any(content).(type) { + case BetaCodeExecutionToolResultErrorParam: + codeExecutionToolResult.Content.OfError = &v + case BetaCodeExecutionResultBlockParam: + codeExecutionToolResult.Content.OfResultBlock = &v + case BetaEncryptedCodeExecutionResultBlockParam: + codeExecutionToolResult.Content.OfRequestEncryptedCodeExecutionResultBlock = &v + } + codeExecutionToolResult.ToolUseID = toolUseID + return BetaContentBlockParamUnion{OfCodeExecutionToolResult: &codeExecutionToolResult} } -func (u BetaMemoryTool20250818CommandUnion) AsDelete() (v BetaMemoryTool20250818DeleteCommand) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +func NewBetaBashCodeExecutionToolResultBlock[ + T BetaBashCodeExecutionToolResultErrorParam | BetaBashCodeExecutionResultBlockParam, +](content T, toolUseID string) BetaContentBlockParamUnion { + var bashCodeExecutionToolResult BetaBashCodeExecutionToolResultBlockParam + switch v := any(content).(type) { + case BetaBashCodeExecutionToolResultErrorParam: + bashCodeExecutionToolResult.Content.OfRequestBashCodeExecutionToolResultError = &v + case BetaBashCodeExecutionResultBlockParam: + bashCodeExecutionToolResult.Content.OfRequestBashCodeExecutionResultBlock = &v + } + bashCodeExecutionToolResult.ToolUseID = toolUseID + return BetaContentBlockParamUnion{OfBashCodeExecutionToolResult: &bashCodeExecutionToolResult} } -func (u BetaMemoryTool20250818CommandUnion) AsRename() (v BetaMemoryTool20250818RenameCommand) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +func NewBetaTextEditorCodeExecutionToolResultBlock[ + T BetaTextEditorCodeExecutionToolResultErrorParam | BetaTextEditorCodeExecutionViewResultBlockParam | BetaTextEditorCodeExecutionCreateResultBlockParam | BetaTextEditorCodeExecutionStrReplaceResultBlockParam, +](content T, toolUseID string) BetaContentBlockParamUnion { + var textEditorCodeExecutionToolResult BetaTextEditorCodeExecutionToolResultBlockParam + switch v := any(content).(type) { + case BetaTextEditorCodeExecutionToolResultErrorParam: + textEditorCodeExecutionToolResult.Content.OfRequestTextEditorCodeExecutionToolResultError = &v + case BetaTextEditorCodeExecutionViewResultBlockParam: + textEditorCodeExecutionToolResult.Content.OfRequestTextEditorCodeExecutionViewResultBlock = &v + case BetaTextEditorCodeExecutionCreateResultBlockParam: + textEditorCodeExecutionToolResult.Content.OfRequestTextEditorCodeExecutionCreateResultBlock = &v + case BetaTextEditorCodeExecutionStrReplaceResultBlockParam: + textEditorCodeExecutionToolResult.Content.OfRequestTextEditorCodeExecutionStrReplaceResultBlock = &v + } + textEditorCodeExecutionToolResult.ToolUseID = toolUseID + return BetaContentBlockParamUnion{OfTextEditorCodeExecutionToolResult: &textEditorCodeExecutionToolResult} } -// Returns the unmodified JSON received from the API -func (u BetaMemoryTool20250818CommandUnion) RawJSON() string { return u.JSON.raw } +func NewBetaToolSearchToolResultBlock[ + T BetaToolSearchToolResultErrorParam | BetaToolSearchToolSearchResultBlockParam, +](content T, toolUseID string) BetaContentBlockParamUnion { + var toolSearchToolResult BetaToolSearchToolResultBlockParam + switch v := any(content).(type) { + case BetaToolSearchToolResultErrorParam: + toolSearchToolResult.Content.OfRequestToolSearchToolResultError = &v + case BetaToolSearchToolSearchResultBlockParam: + toolSearchToolResult.Content.OfRequestToolSearchToolSearchResultBlock = &v + } + toolSearchToolResult.ToolUseID = toolUseID + return BetaContentBlockParamUnion{OfToolSearchToolResult: &toolSearchToolResult} +} -func (r *BetaMemoryTool20250818CommandUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +func NewBetaMCPToolResultBlock(toolUseID string) BetaContentBlockParamUnion { + var mcpToolResult BetaRequestMCPToolResultBlockParam + mcpToolResult.ToolUseID = toolUseID + return BetaContentBlockParamUnion{OfMCPToolResult: &mcpToolResult} } -type BetaMemoryTool20250818CreateCommand struct { - // Command type identifier - Command constant.Create `json:"command" default:"create"` - // Content to write to the file - FileText string `json:"file_text" api:"required"` - // Path where the file should be created - Path string `json:"path" api:"required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Command respjson.Field - FileText respjson.Field - Path respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +func NewBetaContainerUploadBlock(fileID string) BetaContentBlockParamUnion { + var containerUpload BetaContainerUploadBlockParam + containerUpload.FileID = fileID + return BetaContentBlockParamUnion{OfContainerUpload: &containerUpload} } -// Returns the unmodified JSON received from the API -func (r BetaMemoryTool20250818CreateCommand) RawJSON() string { return r.JSON.raw } -func (r *BetaMemoryTool20250818CreateCommand) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +func NewBetaToolAdditionBlock[ + T BetaToolChangeToolReferenceParam | BetaToolChangeMCPToolReferenceParam | BetaToolChangeMCPToolsetReferenceParam, +](tool T) BetaContentBlockParamUnion { + var toolAddition BetaRequestToolAdditionBlockParam + switch v := any(tool).(type) { + case BetaToolChangeToolReferenceParam: + toolAddition.Tool.OfToolReference = &v + case BetaToolChangeMCPToolReferenceParam: + toolAddition.Tool.OfMCPToolReference = &v + case BetaToolChangeMCPToolsetReferenceParam: + toolAddition.Tool.OfMCPToolsetReference = &v + } + return BetaContentBlockParamUnion{OfToolAddition: &toolAddition} } -type BetaMemoryTool20250818DeleteCommand struct { - // Command type identifier - Command constant.Delete `json:"command" default:"delete"` - // Path to the file or directory to delete - Path string `json:"path" api:"required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Command respjson.Field - Path respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +func NewBetaToolRemovalBlock[ + T BetaToolChangeToolReferenceParam | BetaToolChangeMCPToolReferenceParam | BetaToolChangeMCPToolsetReferenceParam, +](tool T) BetaContentBlockParamUnion { + var toolRemoval BetaRequestToolRemovalBlockParam + switch v := any(tool).(type) { + case BetaToolChangeToolReferenceParam: + toolRemoval.Tool.OfToolReference = &v + case BetaToolChangeMCPToolReferenceParam: + toolRemoval.Tool.OfMCPToolReference = &v + case BetaToolChangeMCPToolsetReferenceParam: + toolRemoval.Tool.OfMCPToolsetReference = &v + } + return BetaContentBlockParamUnion{OfToolRemoval: &toolRemoval} } -// Returns the unmodified JSON received from the API -func (r BetaMemoryTool20250818DeleteCommand) RawJSON() string { return r.JSON.raw } -func (r *BetaMemoryTool20250818DeleteCommand) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +func NewBetaFallbackBlock(from BetaFallbackInfoParam, to BetaFallbackInfoParam) BetaContentBlockParamUnion { + var fallback BetaFallbackBlockParam + fallback.From = from + fallback.To = to + return BetaContentBlockParamUnion{OfFallback: &fallback} } -type BetaMemoryTool20250818InsertCommand struct { - // Command type identifier - Command constant.Insert `json:"command" default:"insert"` - // Line number where text should be inserted - InsertLine int64 `json:"insert_line" api:"required"` - // Text to insert at the specified line - InsertText string `json:"insert_text" api:"required"` - // Path to the file where text should be inserted - Path string `json:"path" api:"required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Command respjson.Field - InsertLine respjson.Field - InsertText respjson.Field - Path respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaContentBlockParamUnion struct { + OfText *BetaTextBlockParam `json:",omitzero,inline"` + OfImage *BetaImageBlockParam `json:",omitzero,inline"` + OfDocument *BetaRequestDocumentBlockParam `json:",omitzero,inline"` + OfSearchResult *BetaSearchResultBlockParam `json:",omitzero,inline"` + OfThinking *BetaThinkingBlockParam `json:",omitzero,inline"` + OfRedactedThinking *BetaRedactedThinkingBlockParam `json:",omitzero,inline"` + OfToolUse *BetaToolUseBlockParam `json:",omitzero,inline"` + OfToolResult *BetaToolResultBlockParam `json:",omitzero,inline"` + OfServerToolUse *BetaServerToolUseBlockParam `json:",omitzero,inline"` + OfWebSearchToolResult *BetaWebSearchToolResultBlockParam `json:",omitzero,inline"` + OfWebFetchToolResult *BetaWebFetchToolResultBlockParam `json:",omitzero,inline"` + OfAdvisorToolResult *BetaAdvisorToolResultBlockParam `json:",omitzero,inline"` + OfCodeExecutionToolResult *BetaCodeExecutionToolResultBlockParam `json:",omitzero,inline"` + OfBashCodeExecutionToolResult *BetaBashCodeExecutionToolResultBlockParam `json:",omitzero,inline"` + OfTextEditorCodeExecutionToolResult *BetaTextEditorCodeExecutionToolResultBlockParam `json:",omitzero,inline"` + OfToolSearchToolResult *BetaToolSearchToolResultBlockParam `json:",omitzero,inline"` + OfMCPToolUse *BetaMCPToolUseBlockParam `json:",omitzero,inline"` + OfMCPToolResult *BetaRequestMCPToolResultBlockParam `json:",omitzero,inline"` + OfContainerUpload *BetaContainerUploadBlockParam `json:",omitzero,inline"` + OfCompaction *BetaCompactionBlockParam `json:",omitzero,inline"` + OfToolAddition *BetaRequestToolAdditionBlockParam `json:",omitzero,inline"` + OfToolRemoval *BetaRequestToolRemovalBlockParam `json:",omitzero,inline"` + OfFallback *BetaFallbackBlockParam `json:",omitzero,inline"` + paramUnion } -// Returns the unmodified JSON received from the API -func (r BetaMemoryTool20250818InsertCommand) RawJSON() string { return r.JSON.raw } -func (r *BetaMemoryTool20250818InsertCommand) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +func (u BetaContentBlockParamUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfText, + u.OfImage, + u.OfDocument, + u.OfSearchResult, + u.OfThinking, + u.OfRedactedThinking, + u.OfToolUse, + u.OfToolResult, + u.OfServerToolUse, + u.OfWebSearchToolResult, + u.OfWebFetchToolResult, + u.OfAdvisorToolResult, + u.OfCodeExecutionToolResult, + u.OfBashCodeExecutionToolResult, + u.OfTextEditorCodeExecutionToolResult, + u.OfToolSearchToolResult, + u.OfMCPToolUse, + u.OfMCPToolResult, + u.OfContainerUpload, + u.OfCompaction, + u.OfToolAddition, + u.OfToolRemoval, + u.OfFallback) +} +func (u *BetaContentBlockParamUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) } -type BetaMemoryTool20250818RenameCommand struct { - // Command type identifier - Command constant.Rename `json:"command" default:"rename"` - // New path for the file or directory - NewPath string `json:"new_path" api:"required"` - // Current path of the file or directory - OldPath string `json:"old_path" api:"required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Command respjson.Field - NewPath respjson.Field - OldPath respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +func (u *BetaContentBlockParamUnion) asAny() any { + if !param.IsOmitted(u.OfText) { + return u.OfText + } else if !param.IsOmitted(u.OfImage) { + return u.OfImage + } else if !param.IsOmitted(u.OfDocument) { + return u.OfDocument + } else if !param.IsOmitted(u.OfSearchResult) { + return u.OfSearchResult + } else if !param.IsOmitted(u.OfThinking) { + return u.OfThinking + } else if !param.IsOmitted(u.OfRedactedThinking) { + return u.OfRedactedThinking + } else if !param.IsOmitted(u.OfToolUse) { + return u.OfToolUse + } else if !param.IsOmitted(u.OfToolResult) { + return u.OfToolResult + } else if !param.IsOmitted(u.OfServerToolUse) { + return u.OfServerToolUse + } else if !param.IsOmitted(u.OfWebSearchToolResult) { + return u.OfWebSearchToolResult + } else if !param.IsOmitted(u.OfWebFetchToolResult) { + return u.OfWebFetchToolResult + } else if !param.IsOmitted(u.OfAdvisorToolResult) { + return u.OfAdvisorToolResult + } else if !param.IsOmitted(u.OfCodeExecutionToolResult) { + return u.OfCodeExecutionToolResult + } else if !param.IsOmitted(u.OfBashCodeExecutionToolResult) { + return u.OfBashCodeExecutionToolResult + } else if !param.IsOmitted(u.OfTextEditorCodeExecutionToolResult) { + return u.OfTextEditorCodeExecutionToolResult + } else if !param.IsOmitted(u.OfToolSearchToolResult) { + return u.OfToolSearchToolResult + } else if !param.IsOmitted(u.OfMCPToolUse) { + return u.OfMCPToolUse + } else if !param.IsOmitted(u.OfMCPToolResult) { + return u.OfMCPToolResult + } else if !param.IsOmitted(u.OfContainerUpload) { + return u.OfContainerUpload + } else if !param.IsOmitted(u.OfCompaction) { + return u.OfCompaction + } else if !param.IsOmitted(u.OfToolAddition) { + return u.OfToolAddition + } else if !param.IsOmitted(u.OfToolRemoval) { + return u.OfToolRemoval + } else if !param.IsOmitted(u.OfFallback) { + return u.OfFallback + } + return nil } -// Returns the unmodified JSON received from the API -func (r BetaMemoryTool20250818RenameCommand) RawJSON() string { return r.JSON.raw } -func (r *BetaMemoryTool20250818RenameCommand) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +// Returns a pointer to the underlying variant's property, if present. +func (u BetaContentBlockParamUnion) GetText() *string { + if vt := u.OfText; vt != nil { + return &vt.Text + } + return nil } -type BetaMemoryTool20250818StrReplaceCommand struct { - // Command type identifier - Command constant.StrReplace `json:"command" default:"str_replace"` - // Text to replace with - NewStr string `json:"new_str" api:"required"` - // Text to search for and replace - OldStr string `json:"old_str" api:"required"` - // Path to the file where text should be replaced - Path string `json:"path" api:"required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Command respjson.Field - NewStr respjson.Field - OldStr respjson.Field - Path respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +// Returns a pointer to the underlying variant's property, if present. +func (u BetaContentBlockParamUnion) GetTransformations() *BetaImageTransformationsParam { + if vt := u.OfImage; vt != nil { + return &vt.Transformations + } + return nil } -// Returns the unmodified JSON received from the API -func (r BetaMemoryTool20250818StrReplaceCommand) RawJSON() string { return r.JSON.raw } -func (r *BetaMemoryTool20250818StrReplaceCommand) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +// Returns a pointer to the underlying variant's property, if present. +func (u BetaContentBlockParamUnion) GetContext() *string { + if vt := u.OfDocument; vt != nil && vt.Context.Valid() { + return &vt.Context.Value + } + return nil } -type BetaMemoryTool20250818ViewCommand struct { - // Command type identifier - Command constant.View `json:"command" default:"view"` - // Path to directory or file to view - Path string `json:"path" api:"required"` - // Optional line range for viewing specific lines - ViewRange []int64 `json:"view_range"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Command respjson.Field - Path respjson.Field - ViewRange respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r BetaMemoryTool20250818ViewCommand) RawJSON() string { return r.JSON.raw } -func (r *BetaMemoryTool20250818ViewCommand) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +// Returns a pointer to the underlying variant's property, if present. +func (u BetaContentBlockParamUnion) GetSignature() *string { + if vt := u.OfThinking; vt != nil { + return &vt.Signature + } + return nil } -type BetaMessage struct { - // Unique object identifier. - // - // The format and length of IDs may change over time. - ID string `json:"id" api:"required"` - // Information about the container used in the request (for the code execution - // tool) - Container BetaContainer `json:"container" api:"required"` - // Content generated by the model. - // - // This is an array of content blocks, each of which has a `type` that determines - // its shape. - // - // Example: - // - // ```json - // [{ "type": "text", "text": "Hi, I'm Claude." }] - // ``` - // - // If the request input `messages` ended with an `assistant` turn, then the - // response `content` will continue directly from that last turn. You can use this - // to constrain the model's output. - // - // For example, if the input `messages` were: - // - // ```json - // [ - // - // { - // "role": "user", - // "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun" - // }, - // { "role": "assistant", "content": "The best answer is (" } - // - // ] - // ``` - // - // Then the response `content` might be: - // - // ```json - // [{ "type": "text", "text": "B)" }] - // ``` - Content []BetaContentBlockUnion `json:"content" api:"required"` - // Context management response. - // - // Information about context management strategies applied during the request. - ContextManagement BetaContextManagementResponse `json:"context_management" api:"required"` - // The model that will complete your prompt.\n\nSee - // [models](https://docs.anthropic.com/en/docs/models-overview) for additional - // details and options. - Model Model `json:"model" api:"required"` - // Conversational role of the generated message. - // - // This will always be `"assistant"`. - Role constant.Assistant `json:"role" default:"assistant"` - // Structured information about a refusal. - StopDetails BetaRefusalStopDetails `json:"stop_details" api:"required"` - // The reason that we stopped. - // - // This may be one the following values: - // - // - `"end_turn"`: the model reached a natural stopping point - // - `"max_tokens"`: we exceeded the requested `max_tokens` or the model's maximum - // - `"stop_sequence"`: one of your provided custom `stop_sequences` was generated - // - `"tool_use"`: the model invoked one or more tools - // - `"pause_turn"`: we paused a long-running turn. You may provide the response - // back as-is in a subsequent request to let the model continue. - // - `"refusal"`: when streaming classifiers intervene to handle potential policy - // violations - // - // In non-streaming mode this value is always non-null. In streaming mode, it is - // null in the `message_start` event and non-null otherwise. - // - // Any of "end_turn", "max_tokens", "stop_sequence", "tool_use", "pause_turn", - // "compaction", "refusal", "model_context_window_exceeded". - StopReason BetaStopReason `json:"stop_reason" api:"required"` - // Which custom stop sequence was generated, if any. - // - // This value will be a non-null string if one of your custom stop sequences was - // generated. - StopSequence string `json:"stop_sequence" api:"required"` - // Object type. - // - // For Messages, this is always `"message"`. - Type constant.Message `json:"type" default:"message"` - // Billing and rate-limit usage. - // - // Anthropic's API bills and rate-limits by token counts, as tokens represent the - // underlying cost to our systems. - // - // Under the hood, the API transforms requests into a format suitable for the - // model. The model's output then goes through a parsing stage before becoming an - // API response. As a result, the token counts in `usage` will not match one-to-one - // with the exact visible content of an API request or response. - // - // For example, `output_tokens` will be non-zero, even for an empty string response - // from Claude. - // - // Total input tokens in a request is the summation of `input_tokens`, - // `cache_creation_input_tokens`, and `cache_read_input_tokens`. - Usage BetaUsage `json:"usage" api:"required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ID respjson.Field - Container respjson.Field - Content respjson.Field - ContextManagement respjson.Field - Model respjson.Field - Role respjson.Field - StopDetails respjson.Field - StopReason respjson.Field - StopSequence respjson.Field - Type respjson.Field - Usage respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +// Returns a pointer to the underlying variant's property, if present. +func (u BetaContentBlockParamUnion) GetThinking() *string { + if vt := u.OfThinking; vt != nil { + return &vt.Thinking + } + return nil } -// Returns the unmodified JSON received from the API -func (r BetaMessage) RawJSON() string { return r.JSON.raw } -func (r *BetaMessage) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +// Returns a pointer to the underlying variant's property, if present. +func (u BetaContentBlockParamUnion) GetData() *string { + if vt := u.OfRedactedThinking; vt != nil { + return &vt.Data + } + return nil } - -type BetaMessageDeltaUsage struct { - // The cumulative number of input tokens used to create the cache entry. - CacheCreationInputTokens int64 `json:"cache_creation_input_tokens" api:"required"` - // The cumulative number of input tokens read from the cache. - CacheReadInputTokens int64 `json:"cache_read_input_tokens" api:"required"` - // The cumulative number of input tokens which were used. - InputTokens int64 `json:"input_tokens" api:"required"` - // Per-iteration token usage breakdown. - // - // Each entry represents one sampling iteration, with its own input/output token - // counts and cache statistics. This allows you to: - // - // - Determine which iterations exceeded long context thresholds (>=200k tokens) - // - Calculate the true context window size from the last iteration - // - Understand token accumulation across server-side tool use loops - Iterations BetaIterationsUsage `json:"iterations" api:"required"` - // The cumulative number of output tokens which were used. - OutputTokens int64 `json:"output_tokens" api:"required"` - // The number of server tool requests. - ServerToolUse BetaServerToolUsage `json:"server_tool_use" api:"required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - CacheCreationInputTokens respjson.Field - CacheReadInputTokens respjson.Field - InputTokens respjson.Field - Iterations respjson.Field - OutputTokens respjson.Field - ServerToolUse respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +// Returns a pointer to the underlying variant's property, if present. +func (u BetaContentBlockParamUnion) GetServerName() *string { + if vt := u.OfMCPToolUse; vt != nil { + return &vt.ServerName + } + return nil } -// Returns the unmodified JSON received from the API -func (r BetaMessageDeltaUsage) RawJSON() string { return r.JSON.raw } -func (r *BetaMessageDeltaUsage) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +// Returns a pointer to the underlying variant's property, if present. +func (u BetaContentBlockParamUnion) GetFileID() *string { + if vt := u.OfContainerUpload; vt != nil { + return &vt.FileID + } + return nil } -// Token usage for a sampling iteration. -type BetaMessageIterationUsage struct { - // Breakdown of cached tokens by TTL - CacheCreation BetaCacheCreation `json:"cache_creation" api:"required"` - // The number of input tokens used to create the cache entry. - CacheCreationInputTokens int64 `json:"cache_creation_input_tokens" api:"required"` - // The number of input tokens read from the cache. - CacheReadInputTokens int64 `json:"cache_read_input_tokens" api:"required"` - // The number of input tokens which were used. - InputTokens int64 `json:"input_tokens" api:"required"` - // The number of output tokens which were used. - OutputTokens int64 `json:"output_tokens" api:"required"` - // Usage for a sampling iteration - Type constant.Message `json:"type" default:"message"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - CacheCreation respjson.Field - CacheCreationInputTokens respjson.Field - CacheReadInputTokens respjson.Field - InputTokens respjson.Field - OutputTokens respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +// Returns a pointer to the underlying variant's property, if present. +func (u BetaContentBlockParamUnion) GetEncryptedContent() *string { + if vt := u.OfCompaction; vt != nil && vt.EncryptedContent.Valid() { + return &vt.EncryptedContent.Value + } + return nil } -// Returns the unmodified JSON received from the API -func (r BetaMessageIterationUsage) RawJSON() string { return r.JSON.raw } -func (r *BetaMessageIterationUsage) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +// Returns a pointer to the underlying variant's property, if present. +func (u BetaContentBlockParamUnion) GetFrom() *BetaFallbackInfoParam { + if vt := u.OfFallback; vt != nil { + return &vt.From + } + return nil } -// The properties Content, Role are required. -type BetaMessageParam struct { - Content []BetaContentBlockParamUnion `json:"content,omitzero" api:"required"` - // Any of "user", "assistant". - Role BetaMessageParamRole `json:"role,omitzero" api:"required"` - paramObj +// Returns a pointer to the underlying variant's property, if present. +func (u BetaContentBlockParamUnion) GetTo() *BetaFallbackInfoParam { + if vt := u.OfFallback; vt != nil { + return &vt.To + } + return nil } -func NewBetaUserMessage(blocks ...BetaContentBlockParamUnion) BetaMessageParam { - return BetaMessageParam{ - Role: BetaMessageParamRoleUser, - Content: blocks, +// Returns a pointer to the underlying variant's property, if present. +func (u BetaContentBlockParamUnion) GetTrigger() *any { + if vt := u.OfFallback; vt != nil { + return &vt.Trigger } + return nil } -func (r BetaMessageParam) MarshalJSON() (data []byte, err error) { - type shadow BetaMessageParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaMessageParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type BetaMessageParamRole string - -const ( - BetaMessageParamRoleUser BetaMessageParamRole = "user" - BetaMessageParamRoleAssistant BetaMessageParamRole = "assistant" -) - -type BetaMessageTokensCount struct { - // Information about context management applied to the message. - ContextManagement BetaCountTokensContextManagementResponse `json:"context_management" api:"required"` - // The total number of tokens across the provided list of messages, system prompt, - // and tools. - InputTokens int64 `json:"input_tokens" api:"required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ContextManagement respjson.Field - InputTokens respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +// Returns a pointer to the underlying variant's property, if present. +func (u BetaContentBlockParamUnion) GetType() *string { + if vt := u.OfText; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfImage; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfDocument; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfSearchResult; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfThinking; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfRedactedThinking; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfToolUse; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfToolResult; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfServerToolUse; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfWebSearchToolResult; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfWebFetchToolResult; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfAdvisorToolResult; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfCodeExecutionToolResult; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfBashCodeExecutionToolResult; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfTextEditorCodeExecutionToolResult; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfToolSearchToolResult; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfMCPToolUse; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfMCPToolResult; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfContainerUpload; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfCompaction; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfToolAddition; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfToolRemoval; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfFallback; vt != nil { + return (*string)(&vt.Type) + } + return nil } -// Returns the unmodified JSON received from the API -func (r BetaMessageTokensCount) RawJSON() string { return r.JSON.raw } -func (r *BetaMessageTokensCount) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +// Returns a pointer to the underlying variant's property, if present. +func (u BetaContentBlockParamUnion) GetTitle() *string { + if vt := u.OfDocument; vt != nil && vt.Title.Valid() { + return &vt.Title.Value + } else if vt := u.OfSearchResult; vt != nil { + return (*string)(&vt.Title) + } + return nil } -type BetaMetadataParam struct { - // An external identifier for the user who is associated with the request. - // - // This should be a uuid, hash value, or other opaque identifier. Anthropic may use - // this id to help detect abuse. Do not include any identifying information such as - // name, email address, or phone number. - UserID param.Opt[string] `json:"user_id,omitzero"` - paramObj +// Returns a pointer to the underlying variant's property, if present. +func (u BetaContentBlockParamUnion) GetID() *string { + if vt := u.OfToolUse; vt != nil { + return (*string)(&vt.ID) + } else if vt := u.OfServerToolUse; vt != nil { + return (*string)(&vt.ID) + } else if vt := u.OfMCPToolUse; vt != nil { + return (*string)(&vt.ID) + } + return nil } -func (r BetaMetadataParam) MarshalJSON() (data []byte, err error) { - type shadow BetaMetadataParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaMetadataParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +// Returns a pointer to the underlying variant's property, if present. +func (u BetaContentBlockParamUnion) GetName() *string { + if vt := u.OfToolUse; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfServerToolUse; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfMCPToolUse; vt != nil { + return (*string)(&vt.Name) + } + return nil } -type BetaOutputConfigParam struct { - // All possible effort levels. - // - // Any of "low", "medium", "high", "xhigh", "max". - Effort BetaOutputConfigEffort `json:"effort,omitzero"` - // A schema to specify Claude's output format in responses. See - // [structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs) - Format BetaJSONOutputFormatParam `json:"format,omitzero"` - // User-configurable total token budget across contexts. - TaskBudget BetaTokenTaskBudgetParam `json:"task_budget,omitzero"` - paramObj +// Returns a pointer to the underlying variant's property, if present. +func (u BetaContentBlockParamUnion) GetToolsetName() *string { + if vt := u.OfToolUse; vt != nil && vt.ToolsetName.Valid() { + return &vt.ToolsetName.Value + } else if vt := u.OfToolResult; vt != nil && vt.ToolsetName.Valid() { + return &vt.ToolsetName.Value + } + return nil } -func (r BetaOutputConfigParam) MarshalJSON() (data []byte, err error) { - type shadow BetaOutputConfigParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaOutputConfigParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +// Returns a pointer to the underlying variant's property, if present. +func (u BetaContentBlockParamUnion) GetToolUseID() *string { + if vt := u.OfToolResult; vt != nil { + return (*string)(&vt.ToolUseID) + } else if vt := u.OfWebSearchToolResult; vt != nil { + return (*string)(&vt.ToolUseID) + } else if vt := u.OfWebFetchToolResult; vt != nil { + return (*string)(&vt.ToolUseID) + } else if vt := u.OfAdvisorToolResult; vt != nil { + return (*string)(&vt.ToolUseID) + } else if vt := u.OfCodeExecutionToolResult; vt != nil { + return (*string)(&vt.ToolUseID) + } else if vt := u.OfBashCodeExecutionToolResult; vt != nil { + return (*string)(&vt.ToolUseID) + } else if vt := u.OfTextEditorCodeExecutionToolResult; vt != nil { + return (*string)(&vt.ToolUseID) + } else if vt := u.OfToolSearchToolResult; vt != nil { + return (*string)(&vt.ToolUseID) + } else if vt := u.OfMCPToolResult; vt != nil { + return (*string)(&vt.ToolUseID) + } + return nil } -// All possible effort levels. -type BetaOutputConfigEffort string - -const ( - BetaOutputConfigEffortLow BetaOutputConfigEffort = "low" - BetaOutputConfigEffortMedium BetaOutputConfigEffort = "medium" - BetaOutputConfigEffortHigh BetaOutputConfigEffort = "high" - BetaOutputConfigEffortXhigh BetaOutputConfigEffort = "xhigh" - BetaOutputConfigEffortMax BetaOutputConfigEffort = "max" -) - -type BetaPlainTextSource struct { - Data string `json:"data" api:"required"` - MediaType constant.TextPlain `json:"media_type" default:"text/plain"` - Type constant.Text `json:"type" default:"text"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Data respjson.Field - MediaType respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +// Returns a pointer to the underlying variant's property, if present. +func (u BetaContentBlockParamUnion) GetIsError() *bool { + if vt := u.OfToolResult; vt != nil && vt.IsError.Valid() { + return &vt.IsError.Value + } else if vt := u.OfMCPToolResult; vt != nil && vt.IsError.Valid() { + return &vt.IsError.Value + } + return nil } -// Returns the unmodified JSON received from the API -func (r BetaPlainTextSource) RawJSON() string { return r.JSON.raw } -func (r *BetaPlainTextSource) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +// Returns a pointer to the underlying variant's CacheControl property, if present. +func (u BetaContentBlockParamUnion) GetCacheControl() *BetaCacheControlEphemeralParam { + if vt := u.OfText; vt != nil { + return &vt.CacheControl + } else if vt := u.OfImage; vt != nil { + return &vt.CacheControl + } else if vt := u.OfDocument; vt != nil { + return &vt.CacheControl + } else if vt := u.OfSearchResult; vt != nil { + return &vt.CacheControl + } else if vt := u.OfToolUse; vt != nil { + return &vt.CacheControl + } else if vt := u.OfToolResult; vt != nil { + return &vt.CacheControl + } else if vt := u.OfServerToolUse; vt != nil { + return &vt.CacheControl + } else if vt := u.OfWebSearchToolResult; vt != nil { + return &vt.CacheControl + } else if vt := u.OfWebFetchToolResult; vt != nil { + return &vt.CacheControl + } else if vt := u.OfAdvisorToolResult; vt != nil { + return &vt.CacheControl + } else if vt := u.OfCodeExecutionToolResult; vt != nil { + return &vt.CacheControl + } else if vt := u.OfBashCodeExecutionToolResult; vt != nil { + return &vt.CacheControl + } else if vt := u.OfTextEditorCodeExecutionToolResult; vt != nil { + return &vt.CacheControl + } else if vt := u.OfToolSearchToolResult; vt != nil { + return &vt.CacheControl + } else if vt := u.OfMCPToolUse; vt != nil { + return &vt.CacheControl + } else if vt := u.OfMCPToolResult; vt != nil { + return &vt.CacheControl + } else if vt := u.OfContainerUpload; vt != nil { + return &vt.CacheControl + } else if vt := u.OfCompaction; vt != nil { + return &vt.CacheControl + } else if vt := u.OfToolAddition; vt != nil { + return &vt.CacheControl + } else if vt := u.OfToolRemoval; vt != nil { + return &vt.CacheControl + } + return nil } -// ToParam converts this BetaPlainTextSource to a BetaPlainTextSourceParam. +// Returns a subunion which exports methods to access subproperties // -// Warning: the fields of the param type will not be present. ToParam should only -// be used at the last possible moment before sending a request. Test for this with -// BetaPlainTextSourceParam.Overrides() -func (r BetaPlainTextSource) ToParam() BetaPlainTextSourceParam { - return param.Override[BetaPlainTextSourceParam](json.RawMessage(r.RawJSON())) +// Or use AsAny() to get the underlying value +func (u BetaContentBlockParamUnion) GetCitations() (res betaContentBlockParamUnionCitations) { + if vt := u.OfText; vt != nil { + res.any = &vt.Citations + } else if vt := u.OfDocument; vt != nil { + res.any = &vt.Citations + } else if vt := u.OfSearchResult; vt != nil { + res.any = &vt.Citations + } + return } -// The properties Data, MediaType, Type are required. -type BetaPlainTextSourceParam struct { - Data string `json:"data" api:"required"` - // This field can be elided, and will marshal its zero value as "text/plain". - MediaType constant.TextPlain `json:"media_type" default:"text/plain"` - // This field can be elided, and will marshal its zero value as "text". - Type constant.Text `json:"type" default:"text"` - paramObj -} - -func (r BetaPlainTextSourceParam) MarshalJSON() (data []byte, err error) { - type shadow BetaPlainTextSourceParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaPlainTextSourceParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} +// Can have the runtime types [*[]BetaTextCitationParamUnion], +// [*BetaCitationsConfigParam] +type betaContentBlockParamUnionCitations struct{ any } -// BetaRawContentBlockDeltaUnion contains all possible properties and values from -// [BetaTextDelta], [BetaInputJSONDelta], [BetaCitationsDelta], -// [BetaThinkingDelta], [BetaSignatureDelta], [BetaCompactionContentBlockDelta]. -// -// Use the [BetaRawContentBlockDeltaUnion.AsAny] method to switch on the variant. +// Use the following switch statement to get the type of the union: // -// Use the methods beginning with 'As' to cast the union to one of its variants. -type BetaRawContentBlockDeltaUnion struct { - // This field is from variant [BetaTextDelta]. - Text string `json:"text"` - // Any of "text_delta", "input_json_delta", "citations_delta", "thinking_delta", - // "signature_delta", "compaction_delta". - Type string `json:"type"` - // This field is from variant [BetaInputJSONDelta]. - PartialJSON string `json:"partial_json"` - // This field is from variant [BetaCitationsDelta]. - Citation BetaCitationsDeltaCitationUnion `json:"citation"` - // This field is from variant [BetaThinkingDelta]. - Thinking string `json:"thinking"` - // This field is from variant [BetaSignatureDelta]. - Signature string `json:"signature"` - // This field is from variant [BetaCompactionContentBlockDelta]. - Content string `json:"content"` - // This field is from variant [BetaCompactionContentBlockDelta]. - EncryptedContent string `json:"encrypted_content"` - JSON struct { - Text respjson.Field - Type respjson.Field - PartialJSON respjson.Field - Citation respjson.Field - Thinking respjson.Field - Signature respjson.Field - Content respjson.Field - EncryptedContent respjson.Field - raw string - } `json:"-"` +// switch u.AsAny().(type) { +// case *[]anthropic.BetaTextCitationParamUnion: +// case *anthropic.BetaCitationsConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u betaContentBlockParamUnionCitations) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u betaContentBlockParamUnionCitations) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BetaCitationsConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + } + return nil } -// anyBetaRawContentBlockDelta is implemented by each variant of -// [BetaRawContentBlockDeltaUnion] to add type safety for the return type of -// [BetaRawContentBlockDeltaUnion.AsAny] -type anyBetaRawContentBlockDelta interface { - implBetaRawContentBlockDeltaUnion() +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u BetaContentBlockParamUnion) GetSource() (res betaContentBlockParamUnionSource) { + if vt := u.OfImage; vt != nil { + res.any = vt.Source.asAny() + } else if vt := u.OfDocument; vt != nil { + res.any = vt.Source.asAny() + } else if vt := u.OfSearchResult; vt != nil { + res.any = &vt.Source + } + return } -func (BetaTextDelta) implBetaRawContentBlockDeltaUnion() {} -func (BetaInputJSONDelta) implBetaRawContentBlockDeltaUnion() {} -func (BetaCitationsDelta) implBetaRawContentBlockDeltaUnion() {} -func (BetaThinkingDelta) implBetaRawContentBlockDeltaUnion() {} -func (BetaSignatureDelta) implBetaRawContentBlockDeltaUnion() {} -func (BetaCompactionContentBlockDelta) implBetaRawContentBlockDeltaUnion() {} +// Can have the runtime types [*BetaBase64ImageSourceParam], +// [*BetaURLImageSourceParam], [*BetaFileImageSourceParam], +// [*BetaBase64PDFSourceParam], [*BetaPlainTextSourceParam], +// [*BetaContentBlockSourceParam], [*BetaURLPDFSourceParam], +// [*BetaFileDocumentSourceParam], [*string] +type betaContentBlockParamUnionSource struct{ any } -// Use the following switch statement to find the correct variant +// Use the following switch statement to get the type of the union: // -// switch variant := BetaRawContentBlockDeltaUnion.AsAny().(type) { -// case anthropic.BetaTextDelta: -// case anthropic.BetaInputJSONDelta: -// case anthropic.BetaCitationsDelta: -// case anthropic.BetaThinkingDelta: -// case anthropic.BetaSignatureDelta: -// case anthropic.BetaCompactionContentBlockDelta: +// switch u.AsAny().(type) { +// case *anthropic.BetaBase64ImageSourceParam: +// case *anthropic.BetaURLImageSourceParam: +// case *anthropic.BetaFileImageSourceParam: +// case *anthropic.BetaBase64PDFSourceParam: +// case *anthropic.BetaPlainTextSourceParam: +// case *anthropic.BetaContentBlockSourceParam: +// case *anthropic.BetaURLPDFSourceParam: +// case *anthropic.BetaFileDocumentSourceParam: +// case *string: // default: -// fmt.Errorf("no variant present") +// fmt.Errorf("not present") // } -func (u BetaRawContentBlockDeltaUnion) AsAny() anyBetaRawContentBlockDelta { - switch u.Type { - case "text_delta": - return u.AsTextDelta() - case "input_json_delta": - return u.AsInputJSONDelta() - case "citations_delta": - return u.AsCitationsDelta() - case "thinking_delta": - return u.AsThinkingDelta() - case "signature_delta": - return u.AsSignatureDelta() - case "compaction_delta": - return u.AsCompactionDelta() +func (u betaContentBlockParamUnionSource) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u betaContentBlockParamUnionSource) GetContent() *BetaContentBlockSourceContentUnionParam { + switch vt := u.any.(type) { + case *BetaRequestDocumentBlockSourceUnionParam: + return vt.GetContent() } return nil } -func (u BetaRawContentBlockDeltaUnion) AsTextDelta() (v BetaTextDelta) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +// Returns a pointer to the underlying variant's property, if present. +func (u betaContentBlockParamUnionSource) GetData() *string { + switch vt := u.any.(type) { + case *BetaImageBlockParamSourceUnion: + return vt.GetData() + case *BetaRequestDocumentBlockSourceUnionParam: + return vt.GetData() + } + return nil } -func (u BetaRawContentBlockDeltaUnion) AsInputJSONDelta() (v BetaInputJSONDelta) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +// Returns a pointer to the underlying variant's property, if present. +func (u betaContentBlockParamUnionSource) GetMediaType() *string { + switch vt := u.any.(type) { + case *BetaImageBlockParamSourceUnion: + return vt.GetMediaType() + case *BetaRequestDocumentBlockSourceUnionParam: + return vt.GetMediaType() + } + return nil } -func (u BetaRawContentBlockDeltaUnion) AsCitationsDelta() (v BetaCitationsDelta) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +// Returns a pointer to the underlying variant's property, if present. +func (u betaContentBlockParamUnionSource) GetType() *string { + switch vt := u.any.(type) { + case *BetaImageBlockParamSourceUnion: + return vt.GetType() + case *BetaRequestDocumentBlockSourceUnionParam: + return vt.GetType() + } + return nil } -func (u BetaRawContentBlockDeltaUnion) AsThinkingDelta() (v BetaThinkingDelta) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +// Returns a pointer to the underlying variant's property, if present. +func (u betaContentBlockParamUnionSource) GetURL() *string { + switch vt := u.any.(type) { + case *BetaImageBlockParamSourceUnion: + return vt.GetURL() + case *BetaRequestDocumentBlockSourceUnionParam: + return vt.GetURL() + } + return nil } -func (u BetaRawContentBlockDeltaUnion) AsSignatureDelta() (v BetaSignatureDelta) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +// Returns a pointer to the underlying variant's property, if present. +func (u betaContentBlockParamUnionSource) GetFileID() *string { + switch vt := u.any.(type) { + case *BetaImageBlockParamSourceUnion: + return vt.GetFileID() + case *BetaRequestDocumentBlockSourceUnionParam: + return vt.GetFileID() + } + return nil } -func (u BetaRawContentBlockDeltaUnion) AsCompactionDelta() (v BetaCompactionContentBlockDelta) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u BetaContentBlockParamUnion) GetContent() (res betaContentBlockParamUnionContent) { + if vt := u.OfSearchResult; vt != nil { + res.any = &vt.Content + } else if vt := u.OfToolResult; vt != nil { + res.any = &vt.Content + } else if vt := u.OfWebSearchToolResult; vt != nil { + res.any = vt.Content.asAny() + } else if vt := u.OfWebFetchToolResult; vt != nil { + res.any = vt.Content.asAny() + } else if vt := u.OfAdvisorToolResult; vt != nil { + res.any = vt.Content.asAny() + } else if vt := u.OfCodeExecutionToolResult; vt != nil { + res.any = vt.Content.asAny() + } else if vt := u.OfBashCodeExecutionToolResult; vt != nil { + res.any = vt.Content.asAny() + } else if vt := u.OfTextEditorCodeExecutionToolResult; vt != nil { + res.any = vt.Content.asAny() + } else if vt := u.OfToolSearchToolResult; vt != nil { + res.any = vt.Content.asAny() + } else if vt := u.OfMCPToolResult; vt != nil { + res.any = vt.Content.asAny() + } else if vt := u.OfCompaction; vt != nil && vt.Content.Valid() { + res.any = &vt.Content.Value + } return } -// Returns the unmodified JSON received from the API -func (u BetaRawContentBlockDeltaUnion) RawJSON() string { return u.JSON.raw } - -func (r *BetaRawContentBlockDeltaUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} +// Can have the runtime types [_[]BetaTextBlockParam], +// [_[]BetaToolResultBlockParamContentUnion], [*[]BetaWebSearchResultBlockParam], +// [*BetaWebFetchToolResultErrorBlockParam], [*BetaWebFetchBlockParam], +// [*BetaAdvisorToolResultErrorParam], [*BetaAdvisorResultBlockParam], +// [*BetaAdvisorRedactedResultBlockParam], +// [*BetaCodeExecutionToolResultErrorParam], [*BetaCodeExecutionResultBlockParam], +// [*BetaEncryptedCodeExecutionResultBlockParam], +// [*BetaBashCodeExecutionToolResultErrorParam], +// [*BetaBashCodeExecutionResultBlockParam], +// [*BetaTextEditorCodeExecutionToolResultErrorParam], +// [*BetaTextEditorCodeExecutionViewResultBlockParam], +// [*BetaTextEditorCodeExecutionCreateResultBlockParam], +// [*BetaTextEditorCodeExecutionStrReplaceResultBlockParam], +// [*BetaToolSearchToolResultErrorParam], +// [*BetaToolSearchToolSearchResultBlockParam], [*string] +type betaContentBlockParamUnionContent struct{ any } -type BetaRawContentBlockDeltaEvent struct { - Delta BetaRawContentBlockDeltaUnion `json:"delta" api:"required"` - Index int64 `json:"index" api:"required"` - Type constant.ContentBlockDelta `json:"type" default:"content_block_delta"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Delta respjson.Field - Index respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r BetaRawContentBlockDeltaEvent) RawJSON() string { return r.JSON.raw } -func (r *BetaRawContentBlockDeltaEvent) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *[]anthropic.BetaTextBlockParam: +// case *[]anthropic.BetaToolResultBlockParamContentUnion: +// case *[]anthropic.BetaWebSearchResultBlockParam: +// case *anthropic.BetaWebFetchToolResultErrorBlockParam: +// case *anthropic.BetaWebFetchBlockParam: +// case *anthropic.BetaAdvisorToolResultErrorParam: +// case *anthropic.BetaAdvisorResultBlockParam: +// case *anthropic.BetaAdvisorRedactedResultBlockParam: +// case *anthropic.BetaCodeExecutionToolResultErrorParam: +// case *anthropic.BetaCodeExecutionResultBlockParam: +// case *anthropic.BetaEncryptedCodeExecutionResultBlockParam: +// case *anthropic.BetaBashCodeExecutionToolResultErrorParam: +// case *anthropic.BetaBashCodeExecutionResultBlockParam: +// case *anthropic.BetaTextEditorCodeExecutionToolResultErrorParam: +// case *anthropic.BetaTextEditorCodeExecutionViewResultBlockParam: +// case *anthropic.BetaTextEditorCodeExecutionCreateResultBlockParam: +// case *anthropic.BetaTextEditorCodeExecutionStrReplaceResultBlockParam: +// case *anthropic.BetaToolSearchToolResultErrorParam: +// case *anthropic.BetaToolSearchToolSearchResultBlockParam: +// case *string: +// default: +// fmt.Errorf("not present") +// } +func (u betaContentBlockParamUnionContent) AsAny() any { return u.any } -type BetaRawContentBlockStartEvent struct { - // Response model for a file uploaded to the container. - ContentBlock BetaRawContentBlockStartEventContentBlockUnion `json:"content_block" api:"required"` - Index int64 `json:"index" api:"required"` - Type constant.ContentBlockStart `json:"type" default:"content_block_start"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ContentBlock respjson.Field - Index respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +// Returns a pointer to the underlying variant's property, if present. +func (u betaContentBlockParamUnionContent) GetURL() *string { + switch vt := u.any.(type) { + case *BetaWebFetchToolResultBlockParamContentUnion: + return vt.GetURL() + } + return nil } -// Returns the unmodified JSON received from the API -func (r BetaRawContentBlockStartEvent) RawJSON() string { return r.JSON.raw } -func (r *BetaRawContentBlockStartEvent) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +// Returns a pointer to the underlying variant's property, if present. +func (u betaContentBlockParamUnionContent) GetRetrievedAt() *string { + switch vt := u.any.(type) { + case *BetaWebFetchToolResultBlockParamContentUnion: + return vt.GetRetrievedAt() + } + return nil } -// BetaRawContentBlockStartEventContentBlockUnion contains all possible properties -// and values from [BetaTextBlock], [BetaThinkingBlock], -// [BetaRedactedThinkingBlock], [BetaToolUseBlock], [BetaServerToolUseBlock], -// [BetaWebSearchToolResultBlock], [BetaWebFetchToolResultBlock], -// [BetaAdvisorToolResultBlock], [BetaCodeExecutionToolResultBlock], -// [BetaBashCodeExecutionToolResultBlock], -// [BetaTextEditorCodeExecutionToolResultBlock], [BetaToolSearchToolResultBlock], -// [BetaMCPToolUseBlock], [BetaMCPToolResultBlock], [BetaContainerUploadBlock], -// [BetaCompactionBlock]. -// -// Use the [BetaRawContentBlockStartEventContentBlockUnion.AsAny] method to switch -// on the variant. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -type BetaRawContentBlockStartEventContentBlockUnion struct { - // This field is from variant [BetaTextBlock]. - Citations []BetaTextCitationUnion `json:"citations"` - // This field is from variant [BetaTextBlock]. - Text string `json:"text"` - // Any of "text", "thinking", "redacted_thinking", "tool_use", "server_tool_use", - // "web_search_tool_result", "web_fetch_tool_result", "advisor_tool_result", - // "code_execution_tool_result", "bash_code_execution_tool_result", - // "text_editor_code_execution_tool_result", "tool_search_tool_result", - // "mcp_tool_use", "mcp_tool_result", "container_upload", "compaction". - Type string `json:"type"` - // This field is from variant [BetaThinkingBlock]. - Signature string `json:"signature"` - // This field is from variant [BetaThinkingBlock]. - Thinking string `json:"thinking"` - // This field is from variant [BetaRedactedThinkingBlock]. - Data string `json:"data"` - ID string `json:"id"` - Input any `json:"input"` - Name string `json:"name"` - // This field is a union of [BetaToolUseBlockCallerUnion], - // [BetaServerToolUseBlockCallerUnion], [BetaWebSearchToolResultBlockCallerUnion], - // [BetaWebFetchToolResultBlockCallerUnion] - Caller BetaRawContentBlockStartEventContentBlockUnionCaller `json:"caller"` - // This field is a union of [BetaWebSearchToolResultBlockContentUnion], - // [BetaWebFetchToolResultBlockContentUnion], - // [BetaAdvisorToolResultBlockContentUnion], - // [BetaCodeExecutionToolResultBlockContentUnion], - // [BetaBashCodeExecutionToolResultBlockContentUnion], - // [BetaTextEditorCodeExecutionToolResultBlockContentUnion], - // [BetaToolSearchToolResultBlockContentUnion], - // [BetaMCPToolResultBlockContentUnion], [string] - Content BetaRawContentBlockStartEventContentBlockUnionContent `json:"content"` - ToolUseID string `json:"tool_use_id"` - // This field is from variant [BetaMCPToolUseBlock]. - ServerName string `json:"server_name"` - // This field is from variant [BetaMCPToolResultBlock]. - IsError bool `json:"is_error"` - // This field is from variant [BetaContainerUploadBlock]. - FileID string `json:"file_id"` - // This field is from variant [BetaCompactionBlock]. - EncryptedContent string `json:"encrypted_content"` - JSON struct { - Citations respjson.Field - Text respjson.Field - Type respjson.Field - Signature respjson.Field - Thinking respjson.Field - Data respjson.Field - ID respjson.Field - Input respjson.Field - Name respjson.Field - Caller respjson.Field - Content respjson.Field - ToolUseID respjson.Field - ServerName respjson.Field - IsError respjson.Field - FileID respjson.Field - EncryptedContent respjson.Field - raw string - } `json:"-"` +// Returns a pointer to the underlying variant's property, if present. +func (u betaContentBlockParamUnionContent) GetText() *string { + switch vt := u.any.(type) { + case *BetaAdvisorToolResultBlockParamContentUnion: + return vt.GetText() + } + return nil } -// anyBetaRawContentBlockStartEventContentBlock is implemented by each variant of -// [BetaRawContentBlockStartEventContentBlockUnion] to add type safety for the -// return type of [BetaRawContentBlockStartEventContentBlockUnion.AsAny] -type anyBetaRawContentBlockStartEventContentBlock interface { - implBetaRawContentBlockStartEventContentBlockUnion() +// Returns a pointer to the underlying variant's property, if present. +func (u betaContentBlockParamUnionContent) GetEncryptedContent() *string { + switch vt := u.any.(type) { + case *BetaAdvisorToolResultBlockParamContentUnion: + return vt.GetEncryptedContent() + } + return nil } -func (BetaTextBlock) implBetaRawContentBlockStartEventContentBlockUnion() {} -func (BetaThinkingBlock) implBetaRawContentBlockStartEventContentBlockUnion() {} -func (BetaRedactedThinkingBlock) implBetaRawContentBlockStartEventContentBlockUnion() {} -func (BetaToolUseBlock) implBetaRawContentBlockStartEventContentBlockUnion() {} -func (BetaServerToolUseBlock) implBetaRawContentBlockStartEventContentBlockUnion() {} -func (BetaWebSearchToolResultBlock) implBetaRawContentBlockStartEventContentBlockUnion() {} -func (BetaWebFetchToolResultBlock) implBetaRawContentBlockStartEventContentBlockUnion() {} -func (BetaAdvisorToolResultBlock) implBetaRawContentBlockStartEventContentBlockUnion() {} -func (BetaCodeExecutionToolResultBlock) implBetaRawContentBlockStartEventContentBlockUnion() {} -func (BetaBashCodeExecutionToolResultBlock) implBetaRawContentBlockStartEventContentBlockUnion() {} -func (BetaTextEditorCodeExecutionToolResultBlock) implBetaRawContentBlockStartEventContentBlockUnion() { +// Returns a pointer to the underlying variant's property, if present. +func (u betaContentBlockParamUnionContent) GetEncryptedStdout() *string { + switch vt := u.any.(type) { + case *BetaCodeExecutionToolResultBlockParamContentUnion: + return vt.GetEncryptedStdout() + } + return nil } -func (BetaToolSearchToolResultBlock) implBetaRawContentBlockStartEventContentBlockUnion() {} -func (BetaMCPToolUseBlock) implBetaRawContentBlockStartEventContentBlockUnion() {} -func (BetaMCPToolResultBlock) implBetaRawContentBlockStartEventContentBlockUnion() {} -func (BetaContainerUploadBlock) implBetaRawContentBlockStartEventContentBlockUnion() {} -func (BetaCompactionBlock) implBetaRawContentBlockStartEventContentBlockUnion() {} -// Use the following switch statement to find the correct variant -// -// switch variant := BetaRawContentBlockStartEventContentBlockUnion.AsAny().(type) { -// case anthropic.BetaTextBlock: -// case anthropic.BetaThinkingBlock: -// case anthropic.BetaRedactedThinkingBlock: -// case anthropic.BetaToolUseBlock: -// case anthropic.BetaServerToolUseBlock: -// case anthropic.BetaWebSearchToolResultBlock: -// case anthropic.BetaWebFetchToolResultBlock: -// case anthropic.BetaAdvisorToolResultBlock: -// case anthropic.BetaCodeExecutionToolResultBlock: -// case anthropic.BetaBashCodeExecutionToolResultBlock: -// case anthropic.BetaTextEditorCodeExecutionToolResultBlock: -// case anthropic.BetaToolSearchToolResultBlock: -// case anthropic.BetaMCPToolUseBlock: -// case anthropic.BetaMCPToolResultBlock: -// case anthropic.BetaContainerUploadBlock: -// case anthropic.BetaCompactionBlock: -// default: -// fmt.Errorf("no variant present") -// } -func (u BetaRawContentBlockStartEventContentBlockUnion) AsAny() anyBetaRawContentBlockStartEventContentBlock { - switch u.Type { - case "text": - return u.AsText() - case "thinking": - return u.AsThinking() - case "redacted_thinking": - return u.AsRedactedThinking() - case "tool_use": - return u.AsToolUse() - case "server_tool_use": - return u.AsServerToolUse() - case "web_search_tool_result": - return u.AsWebSearchToolResult() - case "web_fetch_tool_result": - return u.AsWebFetchToolResult() - case "advisor_tool_result": - return u.AsAdvisorToolResult() - case "code_execution_tool_result": - return u.AsCodeExecutionToolResult() - case "bash_code_execution_tool_result": - return u.AsBashCodeExecutionToolResult() - case "text_editor_code_execution_tool_result": - return u.AsTextEditorCodeExecutionToolResult() - case "tool_search_tool_result": - return u.AsToolSearchToolResult() - case "mcp_tool_use": - return u.AsMCPToolUse() - case "mcp_tool_result": - return u.AsMCPToolResult() - case "container_upload": - return u.AsContainerUpload() - case "compaction": - return u.AsCompaction() +// Returns a pointer to the underlying variant's property, if present. +func (u betaContentBlockParamUnionContent) GetFileType() *string { + switch vt := u.any.(type) { + case *BetaTextEditorCodeExecutionToolResultBlockParamContentUnion: + return vt.GetFileType() } return nil } -func (u BetaRawContentBlockStartEventContentBlockUnion) AsText() (v BetaTextBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +// Returns a pointer to the underlying variant's property, if present. +func (u betaContentBlockParamUnionContent) GetNumLines() *int64 { + switch vt := u.any.(type) { + case *BetaTextEditorCodeExecutionToolResultBlockParamContentUnion: + return vt.GetNumLines() + } + return nil } -func (u BetaRawContentBlockStartEventContentBlockUnion) AsThinking() (v BetaThinkingBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +// Returns a pointer to the underlying variant's property, if present. +func (u betaContentBlockParamUnionContent) GetStartLine() *int64 { + switch vt := u.any.(type) { + case *BetaTextEditorCodeExecutionToolResultBlockParamContentUnion: + return vt.GetStartLine() + } + return nil } -func (u BetaRawContentBlockStartEventContentBlockUnion) AsRedactedThinking() (v BetaRedactedThinkingBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +// Returns a pointer to the underlying variant's property, if present. +func (u betaContentBlockParamUnionContent) GetTotalLines() *int64 { + switch vt := u.any.(type) { + case *BetaTextEditorCodeExecutionToolResultBlockParamContentUnion: + return vt.GetTotalLines() + } + return nil } -func (u BetaRawContentBlockStartEventContentBlockUnion) AsToolUse() (v BetaToolUseBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +// Returns a pointer to the underlying variant's property, if present. +func (u betaContentBlockParamUnionContent) GetIsFileUpdate() *bool { + switch vt := u.any.(type) { + case *BetaTextEditorCodeExecutionToolResultBlockParamContentUnion: + return vt.GetIsFileUpdate() + } + return nil } -func (u BetaRawContentBlockStartEventContentBlockUnion) AsServerToolUse() (v BetaServerToolUseBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +// Returns a pointer to the underlying variant's property, if present. +func (u betaContentBlockParamUnionContent) GetLines() []string { + switch vt := u.any.(type) { + case *BetaTextEditorCodeExecutionToolResultBlockParamContentUnion: + return vt.GetLines() + } + return nil } -func (u BetaRawContentBlockStartEventContentBlockUnion) AsWebSearchToolResult() (v BetaWebSearchToolResultBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +// Returns a pointer to the underlying variant's property, if present. +func (u betaContentBlockParamUnionContent) GetNewLines() *int64 { + switch vt := u.any.(type) { + case *BetaTextEditorCodeExecutionToolResultBlockParamContentUnion: + return vt.GetNewLines() + } + return nil } -func (u BetaRawContentBlockStartEventContentBlockUnion) AsWebFetchToolResult() (v BetaWebFetchToolResultBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +// Returns a pointer to the underlying variant's property, if present. +func (u betaContentBlockParamUnionContent) GetNewStart() *int64 { + switch vt := u.any.(type) { + case *BetaTextEditorCodeExecutionToolResultBlockParamContentUnion: + return vt.GetNewStart() + } + return nil } -func (u BetaRawContentBlockStartEventContentBlockUnion) AsAdvisorToolResult() (v BetaAdvisorToolResultBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +// Returns a pointer to the underlying variant's property, if present. +func (u betaContentBlockParamUnionContent) GetOldLines() *int64 { + switch vt := u.any.(type) { + case *BetaTextEditorCodeExecutionToolResultBlockParamContentUnion: + return vt.GetOldLines() + } + return nil } -func (u BetaRawContentBlockStartEventContentBlockUnion) AsCodeExecutionToolResult() (v BetaCodeExecutionToolResultBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +// Returns a pointer to the underlying variant's property, if present. +func (u betaContentBlockParamUnionContent) GetOldStart() *int64 { + switch vt := u.any.(type) { + case *BetaTextEditorCodeExecutionToolResultBlockParamContentUnion: + return vt.GetOldStart() + } + return nil } -func (u BetaRawContentBlockStartEventContentBlockUnion) AsBashCodeExecutionToolResult() (v BetaBashCodeExecutionToolResultBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +// Returns a pointer to the underlying variant's property, if present. +func (u betaContentBlockParamUnionContent) GetToolReferences() []BetaToolReferenceBlockParam { + switch vt := u.any.(type) { + case *BetaToolSearchToolResultBlockParamContentUnion: + return vt.GetToolReferences() + } + return nil } -func (u BetaRawContentBlockStartEventContentBlockUnion) AsTextEditorCodeExecutionToolResult() (v BetaTextEditorCodeExecutionToolResultBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +// Returns a pointer to the underlying variant's property, if present. +func (u betaContentBlockParamUnionContent) GetErrorCode() *string { + switch vt := u.any.(type) { + case *BetaWebSearchToolResultBlockParamContentUnion: + if vt.OfError != nil { + return (*string)(&vt.OfError.ErrorCode) + } + case *BetaWebFetchToolResultBlockParamContentUnion: + return vt.GetErrorCode() + case *BetaAdvisorToolResultBlockParamContentUnion: + return vt.GetErrorCode() + case *BetaCodeExecutionToolResultBlockParamContentUnion: + return vt.GetErrorCode() + case *BetaBashCodeExecutionToolResultBlockParamContentUnion: + return vt.GetErrorCode() + case *BetaTextEditorCodeExecutionToolResultBlockParamContentUnion: + return vt.GetErrorCode() + case *BetaToolSearchToolResultBlockParamContentUnion: + return vt.GetErrorCode() + } + return nil } -func (u BetaRawContentBlockStartEventContentBlockUnion) AsToolSearchToolResult() (v BetaToolSearchToolResultBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +// Returns a pointer to the underlying variant's property, if present. +func (u betaContentBlockParamUnionContent) GetType() *string { + switch vt := u.any.(type) { + case *BetaWebSearchToolResultBlockParamContentUnion: + if vt.OfError != nil { + return (*string)(&vt.OfError.Type) + } + case *BetaWebFetchToolResultBlockParamContentUnion: + return vt.GetType() + case *BetaAdvisorToolResultBlockParamContentUnion: + return vt.GetType() + case *BetaCodeExecutionToolResultBlockParamContentUnion: + return vt.GetType() + case *BetaBashCodeExecutionToolResultBlockParamContentUnion: + return vt.GetType() + case *BetaTextEditorCodeExecutionToolResultBlockParamContentUnion: + return vt.GetType() + case *BetaToolSearchToolResultBlockParamContentUnion: + return vt.GetType() + } + return nil } -func (u BetaRawContentBlockStartEventContentBlockUnion) AsMCPToolUse() (v BetaMCPToolUseBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +// Returns a pointer to the underlying variant's property, if present. +func (u betaContentBlockParamUnionContent) GetStopReason() *string { + switch vt := u.any.(type) { + case *BetaAdvisorToolResultBlockParamContentUnion: + return vt.GetStopReason() + } + return nil } -func (u BetaRawContentBlockStartEventContentBlockUnion) AsMCPToolResult() (v BetaMCPToolResultBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +// Returns a pointer to the underlying variant's property, if present. +func (u betaContentBlockParamUnionContent) GetReturnCode() *int64 { + switch vt := u.any.(type) { + case *BetaCodeExecutionToolResultBlockParamContentUnion: + return vt.GetReturnCode() + case *BetaBashCodeExecutionToolResultBlockParamContentUnion: + return vt.GetReturnCode() + } + return nil } -func (u BetaRawContentBlockStartEventContentBlockUnion) AsContainerUpload() (v BetaContainerUploadBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +// Returns a pointer to the underlying variant's property, if present. +func (u betaContentBlockParamUnionContent) GetStderr() *string { + switch vt := u.any.(type) { + case *BetaCodeExecutionToolResultBlockParamContentUnion: + return vt.GetStderr() + case *BetaBashCodeExecutionToolResultBlockParamContentUnion: + return vt.GetStderr() + } + return nil } -func (u BetaRawContentBlockStartEventContentBlockUnion) AsCompaction() (v BetaCompactionBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +// Returns a pointer to the underlying variant's property, if present. +func (u betaContentBlockParamUnionContent) GetStdout() *string { + switch vt := u.any.(type) { + case *BetaCodeExecutionToolResultBlockParamContentUnion: + return vt.GetStdout() + case *BetaBashCodeExecutionToolResultBlockParamContentUnion: + return vt.GetStdout() + } + return nil } -// Returns the unmodified JSON received from the API -func (u BetaRawContentBlockStartEventContentBlockUnion) RawJSON() string { return u.JSON.raw } - -func (r *BetaRawContentBlockStartEventContentBlockUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +// Returns a pointer to the underlying variant's property, if present. +func (u betaContentBlockParamUnionContent) GetErrorMessage() *string { + switch vt := u.any.(type) { + case *BetaTextEditorCodeExecutionToolResultBlockParamContentUnion: + return vt.GetErrorMessage() + case *BetaToolSearchToolResultBlockParamContentUnion: + return vt.GetErrorMessage() + } + return nil } -// BetaRawContentBlockStartEventContentBlockUnionCaller is an implicit subunion of -// [BetaRawContentBlockStartEventContentBlockUnion]. -// BetaRawContentBlockStartEventContentBlockUnionCaller provides convenient access -// to the sub-properties of the union. +// Returns a subunion which exports methods to access subproperties // -// For type safety it is recommended to directly use a variant of the -// [BetaRawContentBlockStartEventContentBlockUnion]. -type BetaRawContentBlockStartEventContentBlockUnionCaller struct { - Type string `json:"type"` - ToolID string `json:"tool_id"` - JSON struct { - Type respjson.Field - ToolID respjson.Field - raw string - } `json:"-"` +// Or use AsAny() to get the underlying value +func (u betaContentBlockParamUnionContent) GetContent() (res betaContentBlockParamUnionContentContent) { + switch vt := u.any.(type) { + case *BetaWebFetchToolResultBlockParamContentUnion: + res.any = vt.GetContent() + case *BetaCodeExecutionToolResultBlockParamContentUnion: + res.any = vt.GetContent() + case *BetaBashCodeExecutionToolResultBlockParamContentUnion: + res.any = vt.GetContent() + case *BetaTextEditorCodeExecutionToolResultBlockParamContentUnion: + res.any = vt.GetContent() + } + return res } -func (r *BetaRawContentBlockStartEventContentBlockUnionCaller) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} +// Can have the runtime types [*BetaRequestDocumentBlockParam], +// [_[]BetaCodeExecutionOutputBlockParam], +// [_[]BetaBashCodeExecutionOutputBlockParam], [*string] +type betaContentBlockParamUnionContentContent struct{ any } -// BetaRawContentBlockStartEventContentBlockUnionContent is an implicit subunion of -// [BetaRawContentBlockStartEventContentBlockUnion]. -// BetaRawContentBlockStartEventContentBlockUnionContent provides convenient access -// to the sub-properties of the union. -// -// For type safety it is recommended to directly use a variant of the -// [BetaRawContentBlockStartEventContentBlockUnion]. +// Use the following switch statement to get the type of the union: // -// If the underlying value is not a json object, one of the following properties -// will be valid: OfBetaWebSearchResultBlockArray OfString -// OfBetaMCPToolResultBlockContent] -type BetaRawContentBlockStartEventContentBlockUnionContent struct { - // This field will be present if the value is a [[]BetaWebSearchResultBlock] - // instead of an object. - OfBetaWebSearchResultBlockArray []BetaWebSearchResultBlock `json:",inline"` - // This field will be present if the value is a [string] instead of an object. - OfString string `json:",inline"` - // This field will be present if the value is a [[]BetaTextBlock] instead of an - // object. - OfBetaMCPToolResultBlockContent []BetaTextBlock `json:",inline"` - ErrorCode string `json:"error_code"` - Type string `json:"type"` - // This field is a union of [BetaDocumentBlock], [[]BetaCodeExecutionOutputBlock], - // [[]BetaCodeExecutionOutputBlock], [[]BetaBashCodeExecutionOutputBlock], [string] - Content BetaRawContentBlockStartEventContentBlockUnionContentContent `json:"content"` - // This field is from variant [BetaWebFetchToolResultBlockContentUnion]. - RetrievedAt string `json:"retrieved_at"` - // This field is from variant [BetaWebFetchToolResultBlockContentUnion]. - URL string `json:"url"` - // This field is from variant [BetaAdvisorToolResultBlockContentUnion]. - Text string `json:"text"` - // This field is from variant [BetaAdvisorToolResultBlockContentUnion]. - EncryptedContent string `json:"encrypted_content"` - ReturnCode int64 `json:"return_code"` - Stderr string `json:"stderr"` - Stdout string `json:"stdout"` - // This field is from variant [BetaCodeExecutionToolResultBlockContentUnion]. - EncryptedStdout string `json:"encrypted_stdout"` - ErrorMessage string `json:"error_message"` - // This field is from variant - // [BetaTextEditorCodeExecutionToolResultBlockContentUnion]. - FileType BetaTextEditorCodeExecutionViewResultBlockFileType `json:"file_type"` - // This field is from variant - // [BetaTextEditorCodeExecutionToolResultBlockContentUnion]. - NumLines int64 `json:"num_lines"` - // This field is from variant - // [BetaTextEditorCodeExecutionToolResultBlockContentUnion]. - StartLine int64 `json:"start_line"` - // This field is from variant - // [BetaTextEditorCodeExecutionToolResultBlockContentUnion]. - TotalLines int64 `json:"total_lines"` - // This field is from variant - // [BetaTextEditorCodeExecutionToolResultBlockContentUnion]. - IsFileUpdate bool `json:"is_file_update"` - // This field is from variant - // [BetaTextEditorCodeExecutionToolResultBlockContentUnion]. - Lines []string `json:"lines"` - // This field is from variant - // [BetaTextEditorCodeExecutionToolResultBlockContentUnion]. - NewLines int64 `json:"new_lines"` - // This field is from variant - // [BetaTextEditorCodeExecutionToolResultBlockContentUnion]. - NewStart int64 `json:"new_start"` - // This field is from variant - // [BetaTextEditorCodeExecutionToolResultBlockContentUnion]. - OldLines int64 `json:"old_lines"` - // This field is from variant - // [BetaTextEditorCodeExecutionToolResultBlockContentUnion]. - OldStart int64 `json:"old_start"` - // This field is from variant [BetaToolSearchToolResultBlockContentUnion]. - ToolReferences []BetaToolReferenceBlock `json:"tool_references"` - JSON struct { - OfBetaWebSearchResultBlockArray respjson.Field - OfString respjson.Field - OfBetaMCPToolResultBlockContent respjson.Field - ErrorCode respjson.Field - Type respjson.Field - Content respjson.Field - RetrievedAt respjson.Field - URL respjson.Field - Text respjson.Field - EncryptedContent respjson.Field - ReturnCode respjson.Field - Stderr respjson.Field - Stdout respjson.Field - EncryptedStdout respjson.Field - ErrorMessage respjson.Field - FileType respjson.Field - NumLines respjson.Field - StartLine respjson.Field - TotalLines respjson.Field - IsFileUpdate respjson.Field - Lines respjson.Field - NewLines respjson.Field - NewStart respjson.Field - OldLines respjson.Field - OldStart respjson.Field - ToolReferences respjson.Field - raw string - } `json:"-"` -} +// switch u.AsAny().(type) { +// case *anthropic.BetaRequestDocumentBlockParam: +// case *[]anthropic.BetaCodeExecutionOutputBlockParam: +// case *[]anthropic.BetaBashCodeExecutionOutputBlockParam: +// case *string: +// default: +// fmt.Errorf("not present") +// } +func (u betaContentBlockParamUnionContentContent) AsAny() any { return u.any } -func (r *BetaRawContentBlockStartEventContentBlockUnionContent) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +// Returns a pointer to the underlying variant's Input property, if present. +func (u BetaContentBlockParamUnion) GetInput() *any { + if vt := u.OfToolUse; vt != nil { + return &vt.Input + } else if vt := u.OfServerToolUse; vt != nil { + return &vt.Input + } else if vt := u.OfMCPToolUse; vt != nil { + return &vt.Input + } + return nil } -// BetaRawContentBlockStartEventContentBlockUnionContentContent is an implicit -// subunion of [BetaRawContentBlockStartEventContentBlockUnion]. -// BetaRawContentBlockStartEventContentBlockUnionContentContent provides convenient -// access to the sub-properties of the union. -// -// For type safety it is recommended to directly use a variant of the -// [BetaRawContentBlockStartEventContentBlockUnion]. +// Returns a subunion which exports methods to access subproperties // -// If the underlying value is not a json object, one of the following properties -// will be valid: OfContent OfString] -type BetaRawContentBlockStartEventContentBlockUnionContentContent struct { - // This field will be present if the value is a [[]BetaCodeExecutionOutputBlock] - // instead of an object. - OfContent []BetaCodeExecutionOutputBlock `json:",inline"` - // This field will be present if the value is a [string] instead of an object. - OfString string `json:",inline"` - // This field is from variant [BetaDocumentBlock]. - Citations BetaCitationConfig `json:"citations"` - // This field is from variant [BetaDocumentBlock]. - Source BetaDocumentBlockSourceUnion `json:"source"` - // This field is from variant [BetaDocumentBlock]. - Title string `json:"title"` - // This field is from variant [BetaDocumentBlock]. - Type constant.Document `json:"type"` - JSON struct { - OfContent respjson.Field - OfString respjson.Field - Citations respjson.Field - Source respjson.Field - Title respjson.Field - Type respjson.Field - raw string - } `json:"-"` +// Or use AsAny() to get the underlying value +func (u BetaContentBlockParamUnion) GetCaller() (res betaContentBlockParamUnionCaller) { + if vt := u.OfToolUse; vt != nil { + res.any = vt.Caller.asAny() + } else if vt := u.OfServerToolUse; vt != nil { + res.any = vt.Caller.asAny() + } else if vt := u.OfWebSearchToolResult; vt != nil { + res.any = vt.Caller.asAny() + } else if vt := u.OfWebFetchToolResult; vt != nil { + res.any = vt.Caller.asAny() + } + return } -func (r *BetaRawContentBlockStartEventContentBlockUnionContentContent) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +// Can have the runtime types [*BetaDirectCallerParam], +// [*BetaServerToolCallerParam], [*BetaServerToolCaller20260120Param] +type betaContentBlockParamUnionCaller struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BetaDirectCallerParam: +// case *anthropic.BetaServerToolCallerParam: +// case *anthropic.BetaServerToolCaller20260120Param: +// default: +// fmt.Errorf("not present") +// } +func (u betaContentBlockParamUnionCaller) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u betaContentBlockParamUnionCaller) GetType() *string { + switch vt := u.any.(type) { + case *BetaToolUseBlockParamCallerUnion: + return vt.GetType() + case *BetaServerToolUseBlockParamCallerUnion: + return vt.GetType() + case *BetaWebSearchToolResultBlockParamCallerUnion: + return vt.GetType() + case *BetaWebFetchToolResultBlockParamCallerUnion: + return vt.GetType() + } + return nil } -type BetaRawContentBlockStopEvent struct { - Index int64 `json:"index" api:"required"` - Type constant.ContentBlockStop `json:"type" default:"content_block_stop"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Index respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +// Returns a pointer to the underlying variant's property, if present. +func (u betaContentBlockParamUnionCaller) GetToolID() *string { + switch vt := u.any.(type) { + case *BetaToolUseBlockParamCallerUnion: + return vt.GetToolID() + case *BetaServerToolUseBlockParamCallerUnion: + return vt.GetToolID() + case *BetaWebSearchToolResultBlockParamCallerUnion: + return vt.GetToolID() + case *BetaWebFetchToolResultBlockParamCallerUnion: + return vt.GetToolID() + } + return nil } -// Returns the unmodified JSON received from the API -func (r BetaRawContentBlockStopEvent) RawJSON() string { return r.JSON.raw } -func (r *BetaRawContentBlockStopEvent) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u BetaContentBlockParamUnion) GetTool() (res betaContentBlockParamUnionTool) { + if vt := u.OfToolAddition; vt != nil { + res.any = vt.Tool.asAny() + } else if vt := u.OfToolRemoval; vt != nil { + res.any = vt.Tool.asAny() + } + return } -type BetaRawMessageDeltaEvent struct { - // Information about context management strategies applied during the request - ContextManagement BetaContextManagementResponse `json:"context_management" api:"required"` - Delta BetaRawMessageDeltaEventDelta `json:"delta" api:"required"` - Type constant.MessageDelta `json:"type" default:"message_delta"` - // Billing and rate-limit usage. - // - // Anthropic's API bills and rate-limits by token counts, as tokens represent the - // underlying cost to our systems. - // - // Under the hood, the API transforms requests into a format suitable for the - // model. The model's output then goes through a parsing stage before becoming an - // API response. As a result, the token counts in `usage` will not match one-to-one - // with the exact visible content of an API request or response. - // - // For example, `output_tokens` will be non-zero, even for an empty string response - // from Claude. - // - // Total input tokens in a request is the summation of `input_tokens`, - // `cache_creation_input_tokens`, and `cache_read_input_tokens`. - Usage BetaMessageDeltaUsage `json:"usage" api:"required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ContextManagement respjson.Field - Delta respjson.Field - Type respjson.Field - Usage respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +// Can have the runtime types [*BetaToolChangeToolReferenceParam], +// [*BetaToolChangeMCPToolReferenceParam], +// [*BetaToolChangeMCPToolsetReferenceParam] +type betaContentBlockParamUnionTool struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BetaToolChangeToolReferenceParam: +// case *anthropic.BetaToolChangeMCPToolReferenceParam: +// case *anthropic.BetaToolChangeMCPToolsetReferenceParam: +// default: +// fmt.Errorf("not present") +// } +func (u betaContentBlockParamUnionTool) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u betaContentBlockParamUnionTool) GetName() *string { + switch vt := u.any.(type) { + case *BetaRequestToolAdditionBlockToolUnionParam: + return vt.GetName() + case *BetaRequestToolRemovalBlockToolUnionParam: + return vt.GetName() + } + return nil } -// Returns the unmodified JSON received from the API -func (r BetaRawMessageDeltaEvent) RawJSON() string { return r.JSON.raw } -func (r *BetaRawMessageDeltaEvent) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +// Returns a pointer to the underlying variant's property, if present. +func (u betaContentBlockParamUnionTool) GetType() *string { + switch vt := u.any.(type) { + case *BetaRequestToolAdditionBlockToolUnionParam: + return vt.GetType() + case *BetaRequestToolRemovalBlockToolUnionParam: + return vt.GetType() + } + return nil } -type BetaRawMessageDeltaEventDelta struct { - // Information about the container used in the request (for the code execution - // tool) - Container BetaContainer `json:"container" api:"required"` - // Structured information about a refusal. - StopDetails BetaRefusalStopDetails `json:"stop_details" api:"required"` - // Any of "end_turn", "max_tokens", "stop_sequence", "tool_use", "pause_turn", - // "compaction", "refusal", "model_context_window_exceeded". - StopReason BetaStopReason `json:"stop_reason" api:"required"` - StopSequence string `json:"stop_sequence" api:"required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Container respjson.Field - StopDetails respjson.Field - StopReason respjson.Field - StopSequence respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r BetaRawMessageDeltaEventDelta) RawJSON() string { return r.JSON.raw } -func (r *BetaRawMessageDeltaEventDelta) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +// Returns a pointer to the underlying variant's property, if present. +func (u betaContentBlockParamUnionTool) GetServerName() *string { + switch vt := u.any.(type) { + case *BetaRequestToolAdditionBlockToolUnionParam: + return vt.GetServerName() + case *BetaRequestToolRemovalBlockToolUnionParam: + return vt.GetServerName() + } + return nil } -type BetaRawMessageStartEvent struct { - Message BetaMessage `json:"message" api:"required"` - Type constant.MessageStart `json:"type" default:"message_start"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Message respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +func init() { + apijson.RegisterUnion[BetaContentBlockParamUnion]( + "type", + apijson.Discriminator[BetaTextBlockParam]("text"), + apijson.Discriminator[BetaImageBlockParam]("image"), + apijson.Discriminator[BetaRequestDocumentBlockParam]("document"), + apijson.Discriminator[BetaSearchResultBlockParam]("search_result"), + apijson.Discriminator[BetaThinkingBlockParam]("thinking"), + apijson.Discriminator[BetaRedactedThinkingBlockParam]("redacted_thinking"), + apijson.Discriminator[BetaToolUseBlockParam]("tool_use"), + apijson.Discriminator[BetaToolResultBlockParam]("tool_result"), + apijson.Discriminator[BetaServerToolUseBlockParam]("server_tool_use"), + apijson.Discriminator[BetaWebSearchToolResultBlockParam]("web_search_tool_result"), + apijson.Discriminator[BetaWebFetchToolResultBlockParam]("web_fetch_tool_result"), + apijson.Discriminator[BetaAdvisorToolResultBlockParam]("advisor_tool_result"), + apijson.Discriminator[BetaCodeExecutionToolResultBlockParam]("code_execution_tool_result"), + apijson.Discriminator[BetaBashCodeExecutionToolResultBlockParam]("bash_code_execution_tool_result"), + apijson.Discriminator[BetaTextEditorCodeExecutionToolResultBlockParam]("text_editor_code_execution_tool_result"), + apijson.Discriminator[BetaToolSearchToolResultBlockParam]("tool_search_tool_result"), + apijson.Discriminator[BetaMCPToolUseBlockParam]("mcp_tool_use"), + apijson.Discriminator[BetaRequestMCPToolResultBlockParam]("mcp_tool_result"), + apijson.Discriminator[BetaContainerUploadBlockParam]("container_upload"), + apijson.Discriminator[BetaCompactionBlockParam]("compaction"), + apijson.Discriminator[BetaRequestToolAdditionBlockParam]("tool_addition"), + apijson.Discriminator[BetaRequestToolRemovalBlockParam]("tool_removal"), + apijson.Discriminator[BetaFallbackBlockParam]("fallback"), + ) } -// Returns the unmodified JSON received from the API -func (r BetaRawMessageStartEvent) RawJSON() string { return r.JSON.raw } -func (r *BetaRawMessageStartEvent) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +// The properties Content, Type are required. +type BetaContentBlockSourceParam struct { + Content BetaContentBlockSourceContentUnionParam `json:"content,omitzero" api:"required"` + // This field can be elided, and will marshal its zero value as "content". + Type constant.Content `json:"type" default:"content"` + paramObj } -type BetaRawMessageStopEvent struct { - Type constant.MessageStop `json:"type" default:"message_stop"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +func (r BetaContentBlockSourceParam) MarshalJSON() (data []byte, err error) { + type shadow BetaContentBlockSourceParam + return param.MarshalObject(r, (*shadow)(&r)) } - -// Returns the unmodified JSON received from the API -func (r BetaRawMessageStopEvent) RawJSON() string { return r.JSON.raw } -func (r *BetaRawMessageStopEvent) UnmarshalJSON(data []byte) error { +func (r *BetaContentBlockSourceParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// BetaRawMessageStreamEventUnion contains all possible properties and values from -// [BetaRawMessageStartEvent], [BetaRawMessageDeltaEvent], -// [BetaRawMessageStopEvent], [BetaRawContentBlockStartEvent], -// [BetaRawContentBlockDeltaEvent], [BetaRawContentBlockStopEvent]. -// -// Use the [BetaRawMessageStreamEventUnion.AsAny] method to switch on the variant. +// Only one field can be non-zero. // -// Use the methods beginning with 'As' to cast the union to one of its variants. -type BetaRawMessageStreamEventUnion struct { - // This field is from variant [BetaRawMessageStartEvent]. - Message BetaMessage `json:"message"` - // Any of "message_start", "message_delta", "message_stop", "content_block_start", - // "content_block_delta", "content_block_stop". - Type string `json:"type"` - // This field is from variant [BetaRawMessageDeltaEvent]. - ContextManagement BetaContextManagementResponse `json:"context_management"` - // This field is a union of [BetaRawMessageDeltaEventDelta], - // [BetaRawContentBlockDeltaUnion] - Delta BetaRawMessageStreamEventUnionDelta `json:"delta"` - // This field is from variant [BetaRawMessageDeltaEvent]. - Usage BetaMessageDeltaUsage `json:"usage"` - // This field is from variant [BetaRawContentBlockStartEvent]. - ContentBlock BetaRawContentBlockStartEventContentBlockUnion `json:"content_block"` - Index int64 `json:"index"` - JSON struct { - Message respjson.Field - Type respjson.Field - ContextManagement respjson.Field - Delta respjson.Field - Usage respjson.Field - ContentBlock respjson.Field - Index respjson.Field - raw string - } `json:"-"` +// Use [param.IsOmitted] to confirm if a field is set. +type BetaContentBlockSourceContentUnionParam struct { + OfString param.Opt[string] `json:",omitzero,inline"` + OfBetaContentBlockSourceContent []BetaContentBlockSourceContentUnionParam `json:",omitzero,inline"` + paramUnion } -// anyBetaRawMessageStreamEvent is implemented by each variant of -// [BetaRawMessageStreamEventUnion] to add type safety for the return type of -// [BetaRawMessageStreamEventUnion.AsAny] -type anyBetaRawMessageStreamEvent interface { - implBetaRawMessageStreamEventUnion() +func (u BetaContentBlockSourceContentUnionParam) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfString, u.OfBetaContentBlockSourceContent) +} +func (u *BetaContentBlockSourceContentUnionParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) } -func (BetaRawMessageStartEvent) implBetaRawMessageStreamEventUnion() {} -func (BetaRawMessageDeltaEvent) implBetaRawMessageStreamEventUnion() {} -func (BetaRawMessageStopEvent) implBetaRawMessageStreamEventUnion() {} -func (BetaRawContentBlockStartEvent) implBetaRawMessageStreamEventUnion() {} -func (BetaRawContentBlockDeltaEvent) implBetaRawMessageStreamEventUnion() {} -func (BetaRawContentBlockStopEvent) implBetaRawMessageStreamEventUnion() {} - -// Use the following switch statement to find the correct variant -// -// switch variant := BetaRawMessageStreamEventUnion.AsAny().(type) { -// case anthropic.BetaRawMessageStartEvent: -// case anthropic.BetaRawMessageDeltaEvent: -// case anthropic.BetaRawMessageStopEvent: -// case anthropic.BetaRawContentBlockStartEvent: -// case anthropic.BetaRawContentBlockDeltaEvent: -// case anthropic.BetaRawContentBlockStopEvent: -// default: -// fmt.Errorf("no variant present") -// } -func (u BetaRawMessageStreamEventUnion) AsAny() anyBetaRawMessageStreamEvent { - switch u.Type { - case "message_start": - return u.AsMessageStart() - case "message_delta": - return u.AsMessageDelta() - case "message_stop": - return u.AsMessageStop() - case "content_block_start": - return u.AsContentBlockStart() - case "content_block_delta": - return u.AsContentBlockDelta() - case "content_block_stop": - return u.AsContentBlockStop() +func (u *BetaContentBlockSourceContentUnionParam) asAny() any { + if !param.IsOmitted(u.OfString) { + return &u.OfString.Value + } else if !param.IsOmitted(u.OfBetaContentBlockSourceContent) { + return &u.OfBetaContentBlockSourceContent } return nil } -func (u BetaRawMessageStreamEventUnion) AsMessageStart() (v BetaRawMessageStartEvent) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +type BetaContextManagementConfigParam struct { + // List of context management edits to apply + Edits []BetaContextManagementConfigEditUnionParam `json:"edits,omitzero"` + paramObj } -func (u BetaRawMessageStreamEventUnion) AsMessageDelta() (v BetaRawMessageDeltaEvent) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +func (r BetaContextManagementConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaContextManagementConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaContextManagementConfigParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func (u BetaRawMessageStreamEventUnion) AsMessageStop() (v BetaRawMessageStopEvent) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaContextManagementConfigEditUnionParam struct { + OfClearToolUses20250919 *BetaClearToolUses20250919EditParam `json:",omitzero,inline"` + OfClearThinking20251015 *BetaClearThinking20251015EditParam `json:",omitzero,inline"` + OfCompact20260112 *BetaCompact20260112EditParam `json:",omitzero,inline"` + paramUnion } -func (u BetaRawMessageStreamEventUnion) AsContentBlockStart() (v BetaRawContentBlockStartEvent) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +func (u BetaContextManagementConfigEditUnionParam) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfClearToolUses20250919, u.OfClearThinking20251015, u.OfCompact20260112) +} +func (u *BetaContextManagementConfigEditUnionParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) } -func (u BetaRawMessageStreamEventUnion) AsContentBlockDelta() (v BetaRawContentBlockDeltaEvent) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +func (u *BetaContextManagementConfigEditUnionParam) asAny() any { + if !param.IsOmitted(u.OfClearToolUses20250919) { + return u.OfClearToolUses20250919 + } else if !param.IsOmitted(u.OfClearThinking20251015) { + return u.OfClearThinking20251015 + } else if !param.IsOmitted(u.OfCompact20260112) { + return u.OfCompact20260112 + } + return nil } -func (u BetaRawMessageStreamEventUnion) AsContentBlockStop() (v BetaRawContentBlockStopEvent) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +// Returns a pointer to the underlying variant's property, if present. +func (u BetaContextManagementConfigEditUnionParam) GetClearAtLeast() *BetaInputTokensClearAtLeastParam { + if vt := u.OfClearToolUses20250919; vt != nil { + return &vt.ClearAtLeast + } + return nil } -// Returns the unmodified JSON received from the API -func (u BetaRawMessageStreamEventUnion) RawJSON() string { return u.JSON.raw } +// Returns a pointer to the underlying variant's property, if present. +func (u BetaContextManagementConfigEditUnionParam) GetClearToolInputs() *BetaClearToolUses20250919EditClearToolInputsUnionParam { + if vt := u.OfClearToolUses20250919; vt != nil { + return &vt.ClearToolInputs + } + return nil +} -func (r *BetaRawMessageStreamEventUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// BetaRawMessageStreamEventUnionDelta is an implicit subunion of -// [BetaRawMessageStreamEventUnion]. BetaRawMessageStreamEventUnionDelta provides -// convenient access to the sub-properties of the union. -// -// For type safety it is recommended to directly use a variant of the -// [BetaRawMessageStreamEventUnion]. -type BetaRawMessageStreamEventUnionDelta struct { - // This field is from variant [BetaRawMessageDeltaEventDelta]. - Container BetaContainer `json:"container"` - // This field is from variant [BetaRawMessageDeltaEventDelta]. - StopDetails BetaRefusalStopDetails `json:"stop_details"` - // This field is from variant [BetaRawMessageDeltaEventDelta]. - StopReason BetaStopReason `json:"stop_reason"` - // This field is from variant [BetaRawMessageDeltaEventDelta]. - StopSequence string `json:"stop_sequence"` - // This field is from variant [BetaRawContentBlockDeltaUnion]. - Text string `json:"text"` - Type string `json:"type"` - // This field is from variant [BetaRawContentBlockDeltaUnion]. - PartialJSON string `json:"partial_json"` - // This field is from variant [BetaRawContentBlockDeltaUnion]. - Citation BetaCitationsDeltaCitationUnion `json:"citation"` - // This field is from variant [BetaRawContentBlockDeltaUnion]. - Thinking string `json:"thinking"` - // This field is from variant [BetaRawContentBlockDeltaUnion]. - Signature string `json:"signature"` - // This field is from variant [BetaRawContentBlockDeltaUnion]. - Content string `json:"content"` - // This field is from variant [BetaRawContentBlockDeltaUnion]. - EncryptedContent string `json:"encrypted_content"` - JSON struct { - Container respjson.Field - StopDetails respjson.Field - StopReason respjson.Field - StopSequence respjson.Field - Text respjson.Field - Type respjson.Field - PartialJSON respjson.Field - Citation respjson.Field - Thinking respjson.Field - Signature respjson.Field - Content respjson.Field - EncryptedContent respjson.Field - raw string - } `json:"-"` -} - -func (r *BetaRawMessageStreamEventUnionDelta) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type BetaRedactedThinkingBlock struct { - Data string `json:"data" api:"required"` - Type constant.RedactedThinking `json:"type" default:"redacted_thinking"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Data respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r BetaRedactedThinkingBlock) RawJSON() string { return r.JSON.raw } -func (r *BetaRedactedThinkingBlock) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The properties Data, Type are required. -type BetaRedactedThinkingBlockParam struct { - Data string `json:"data" api:"required"` - // This field can be elided, and will marshal its zero value as - // "redacted_thinking". - Type constant.RedactedThinking `json:"type" default:"redacted_thinking"` - paramObj -} - -func (r BetaRedactedThinkingBlockParam) MarshalJSON() (data []byte, err error) { - type shadow BetaRedactedThinkingBlockParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaRedactedThinkingBlockParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Structured information about a refusal. -type BetaRefusalStopDetails struct { - // The policy category that triggered the refusal. - // - // `null` when the refusal doesn't map to a named category. - // - // Any of "cyber", "bio". - Category BetaRefusalStopDetailsCategory `json:"category" api:"required"` - // Human-readable explanation of the refusal. - // - // This text is not guaranteed to be stable. `null` when no explanation is - // available for the category. - Explanation string `json:"explanation" api:"required"` - Type constant.Refusal `json:"type" default:"refusal"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Category respjson.Field - Explanation respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r BetaRefusalStopDetails) RawJSON() string { return r.JSON.raw } -func (r *BetaRefusalStopDetails) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The policy category that triggered the refusal. -// -// `null` when the refusal doesn't map to a named category. -type BetaRefusalStopDetailsCategory string - -const ( - BetaRefusalStopDetailsCategoryCyber BetaRefusalStopDetailsCategory = "cyber" - BetaRefusalStopDetailsCategoryBio BetaRefusalStopDetailsCategory = "bio" -) - -// The properties Source, Type are required. -type BetaRequestDocumentBlockParam struct { - Source BetaRequestDocumentBlockSourceUnionParam `json:"source,omitzero" api:"required"` - Context param.Opt[string] `json:"context,omitzero"` - Title param.Opt[string] `json:"title,omitzero"` - // Create a cache control breakpoint at this content block. - CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` - Citations BetaCitationsConfigParam `json:"citations,omitzero"` - // This field can be elided, and will marshal its zero value as "document". - Type constant.Document `json:"type" default:"document"` - paramObj -} - -func (r BetaRequestDocumentBlockParam) MarshalJSON() (data []byte, err error) { - type shadow BetaRequestDocumentBlockParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaRequestDocumentBlockParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type BetaRequestDocumentBlockSourceUnionParam struct { - OfBase64 *BetaBase64PDFSourceParam `json:",omitzero,inline"` - OfText *BetaPlainTextSourceParam `json:",omitzero,inline"` - OfContent *BetaContentBlockSourceParam `json:",omitzero,inline"` - OfURL *BetaURLPDFSourceParam `json:",omitzero,inline"` - OfFile *BetaFileDocumentSourceParam `json:",omitzero,inline"` - paramUnion -} - -func (u BetaRequestDocumentBlockSourceUnionParam) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfBase64, - u.OfText, - u.OfContent, - u.OfURL, - u.OfFile) -} -func (u *BetaRequestDocumentBlockSourceUnionParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *BetaRequestDocumentBlockSourceUnionParam) asAny() any { - if !param.IsOmitted(u.OfBase64) { - return u.OfBase64 - } else if !param.IsOmitted(u.OfText) { - return u.OfText - } else if !param.IsOmitted(u.OfContent) { - return u.OfContent - } else if !param.IsOmitted(u.OfURL) { - return u.OfURL - } else if !param.IsOmitted(u.OfFile) { - return u.OfFile - } - return nil +// Returns a pointer to the underlying variant's property, if present. +func (u BetaContextManagementConfigEditUnionParam) GetExcludeTools() []string { + if vt := u.OfClearToolUses20250919; vt != nil { + return vt.ExcludeTools + } + return nil } // Returns a pointer to the underlying variant's property, if present. -func (u BetaRequestDocumentBlockSourceUnionParam) GetContent() *BetaContentBlockSourceContentUnionParam { - if vt := u.OfContent; vt != nil { - return &vt.Content +func (u BetaContextManagementConfigEditUnionParam) GetInstructions() *string { + if vt := u.OfCompact20260112; vt != nil && vt.Instructions.Valid() { + return &vt.Instructions.Value } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u BetaRequestDocumentBlockSourceUnionParam) GetURL() *string { - if vt := u.OfURL; vt != nil { - return &vt.URL +func (u BetaContextManagementConfigEditUnionParam) GetPauseAfterCompaction() *bool { + if vt := u.OfCompact20260112; vt != nil && vt.PauseAfterCompaction.Valid() { + return &vt.PauseAfterCompaction.Value } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u BetaRequestDocumentBlockSourceUnionParam) GetFileID() *string { - if vt := u.OfFile; vt != nil { - return &vt.FileID +func (u BetaContextManagementConfigEditUnionParam) GetType() *string { + if vt := u.OfClearToolUses20250919; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfClearThinking20251015; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfCompact20260112; vt != nil { + return (*string)(&vt.Type) } return nil } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaRequestDocumentBlockSourceUnionParam) GetData() *string { - if vt := u.OfBase64; vt != nil { - return (*string)(&vt.Data) - } else if vt := u.OfText; vt != nil { - return (*string)(&vt.Data) +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u BetaContextManagementConfigEditUnionParam) GetKeep() (res betaContextManagementConfigEditUnionParamKeep) { + if vt := u.OfClearToolUses20250919; vt != nil { + res.any = &vt.Keep + } else if vt := u.OfClearThinking20251015; vt != nil { + res.any = vt.Keep.asAny() } - return nil + return } +// Can have the runtime types [*BetaToolUsesKeepParam], [*string] +type betaContextManagementConfigEditUnionParamKeep struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BetaToolUsesKeepParam: +// case *string: +// default: +// fmt.Errorf("not present") +// } +func (u betaContextManagementConfigEditUnionParamKeep) AsAny() any { return u.any } + // Returns a pointer to the underlying variant's property, if present. -func (u BetaRequestDocumentBlockSourceUnionParam) GetMediaType() *string { - if vt := u.OfBase64; vt != nil { - return (*string)(&vt.MediaType) - } else if vt := u.OfText; vt != nil { - return (*string)(&vt.MediaType) +func (u betaContextManagementConfigEditUnionParamKeep) GetType() *string { + switch vt := u.any.(type) { + case *BetaToolUsesKeepParam: + return (*string)(&vt.Type) + case *BetaClearThinking20251015EditKeepUnionParam: + return vt.GetType() } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u BetaRequestDocumentBlockSourceUnionParam) GetType() *string { - if vt := u.OfBase64; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfText; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfContent; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfURL; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfFile; vt != nil { - return (*string)(&vt.Type) +func (u betaContextManagementConfigEditUnionParamKeep) GetValue() *int64 { + switch vt := u.any.(type) { + case *BetaToolUsesKeepParam: + return (*int64)(&vt.Value) + case *BetaClearThinking20251015EditKeepUnionParam: + return vt.GetValue() } return nil } func init() { - apijson.RegisterUnion[BetaRequestDocumentBlockSourceUnionParam]( + apijson.RegisterUnion[BetaContextManagementConfigEditUnionParam]( "type", - apijson.Discriminator[BetaBase64PDFSourceParam]("base64"), - apijson.Discriminator[BetaPlainTextSourceParam]("text"), - apijson.Discriminator[BetaContentBlockSourceParam]("content"), - apijson.Discriminator[BetaURLPDFSourceParam]("url"), - apijson.Discriminator[BetaFileDocumentSourceParam]("file"), + apijson.Discriminator[BetaClearToolUses20250919EditParam]("clear_tool_uses_20250919"), + apijson.Discriminator[BetaClearThinking20251015EditParam]("clear_thinking_20251015"), + apijson.Discriminator[BetaCompact20260112EditParam]("compact_20260112"), ) } -type BetaRequestMCPServerToolConfigurationParam struct { - Enabled param.Opt[bool] `json:"enabled,omitzero"` - AllowedTools []string `json:"allowed_tools,omitzero"` - paramObj +type BetaContextManagementResponse struct { + // List of context management edits that were applied. + AppliedEdits []BetaContextManagementResponseAppliedEditUnion `json:"applied_edits" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + AppliedEdits respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` } -func (r BetaRequestMCPServerToolConfigurationParam) MarshalJSON() (data []byte, err error) { - type shadow BetaRequestMCPServerToolConfigurationParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaRequestMCPServerToolConfigurationParam) UnmarshalJSON(data []byte) error { +// Returns the unmodified JSON received from the API +func (r BetaContextManagementResponse) RawJSON() string { return r.JSON.raw } +func (r *BetaContextManagementResponse) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The properties Name, Type, URL are required. -type BetaRequestMCPServerURLDefinitionParam struct { - Name string `json:"name" api:"required"` - URL string `json:"url" api:"required"` - AuthorizationToken param.Opt[string] `json:"authorization_token,omitzero"` - ToolConfiguration BetaRequestMCPServerToolConfigurationParam `json:"tool_configuration,omitzero"` - // This field can be elided, and will marshal its zero value as "url". - Type constant.URL `json:"type" default:"url"` - paramObj +// BetaContextManagementResponseAppliedEditUnion contains all possible properties +// and values from [BetaClearToolUses20250919EditResponse], +// [BetaClearThinking20251015EditResponse]. +// +// Use the [BetaContextManagementResponseAppliedEditUnion.AsAny] method to switch +// on the variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaContextManagementResponseAppliedEditUnion struct { + ClearedInputTokens int64 `json:"cleared_input_tokens"` + // This field is from variant [BetaClearToolUses20250919EditResponse]. + ClearedToolUses int64 `json:"cleared_tool_uses"` + // Any of "clear_tool_uses_20250919", "clear_thinking_20251015". + Type string `json:"type"` + // This field is from variant [BetaClearThinking20251015EditResponse]. + ClearedThinkingTurns int64 `json:"cleared_thinking_turns"` + JSON struct { + ClearedInputTokens respjson.Field + ClearedToolUses respjson.Field + Type respjson.Field + ClearedThinkingTurns respjson.Field + raw string + } `json:"-"` } -func (r BetaRequestMCPServerURLDefinitionParam) MarshalJSON() (data []byte, err error) { - type shadow BetaRequestMCPServerURLDefinitionParam - return param.MarshalObject(r, (*shadow)(&r)) +// anyBetaContextManagementResponseAppliedEdit is implemented by each variant of +// [BetaContextManagementResponseAppliedEditUnion] to add type safety for the +// return type of [BetaContextManagementResponseAppliedEditUnion.AsAny] +type anyBetaContextManagementResponseAppliedEdit interface { + implBetaContextManagementResponseAppliedEditUnion() } -func (r *BetaRequestMCPServerURLDefinitionParam) UnmarshalJSON(data []byte) error { + +func (BetaClearToolUses20250919EditResponse) implBetaContextManagementResponseAppliedEditUnion() {} +func (BetaClearThinking20251015EditResponse) implBetaContextManagementResponseAppliedEditUnion() {} + +// Use the following switch statement to find the correct variant +// +// switch variant := BetaContextManagementResponseAppliedEditUnion.AsAny().(type) { +// case anthropic.BetaClearToolUses20250919EditResponse: +// case anthropic.BetaClearThinking20251015EditResponse: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaContextManagementResponseAppliedEditUnion) AsAny() anyBetaContextManagementResponseAppliedEdit { + switch u.Type { + case "clear_tool_uses_20250919": + return u.AsClearToolUses20250919() + case "clear_thinking_20251015": + return u.AsClearThinking20251015() + } + return nil +} + +func (u BetaContextManagementResponseAppliedEditUnion) AsClearToolUses20250919() (v BetaClearToolUses20250919EditResponse) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaContextManagementResponseAppliedEditUnion) AsClearThinking20251015() (v BetaClearThinking20251015EditResponse) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u BetaContextManagementResponseAppliedEditUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaContextManagementResponseAppliedEditUnion) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The properties ToolUseID, Type are required. -type BetaRequestMCPToolResultBlockParam struct { - ToolUseID string `json:"tool_use_id" api:"required"` - IsError param.Opt[bool] `json:"is_error,omitzero"` - // Create a cache control breakpoint at this content block. - CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` - Content BetaRequestMCPToolResultBlockParamContentUnion `json:"content,omitzero"` - // This field can be elided, and will marshal its zero value as "mcp_tool_result". - Type constant.MCPToolResult `json:"type" default:"mcp_tool_result"` - paramObj +type BetaCountTokensContextManagementResponse struct { + // The original token count before context management was applied + OriginalInputTokens int64 `json:"original_input_tokens" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + OriginalInputTokens respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` } -func (r BetaRequestMCPToolResultBlockParam) MarshalJSON() (data []byte, err error) { - type shadow BetaRequestMCPToolResultBlockParam - return param.MarshalObject(r, (*shadow)(&r)) +// Returns the unmodified JSON received from the API +func (r BetaCountTokensContextManagementResponse) RawJSON() string { return r.JSON.raw } +func (r *BetaCountTokensContextManagementResponse) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func (r *BetaRequestMCPToolResultBlockParam) UnmarshalJSON(data []byte) error { + +// Response envelope for request-level diagnostics. Present (possibly null) +// whenever the caller supplied `diagnostics` on the request. +type BetaDiagnostics struct { + // Explains why the prompt cache could not fully reuse the prefix from the request + // identified by `diagnostics.previous_message_id`. `null` means diagnosis is still + // pending — the response was serialized before the background comparison + // completed. + CacheMissReason BetaDiagnosticsCacheMissReasonUnion `json:"cache_miss_reason" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + CacheMissReason respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaDiagnostics) RawJSON() string { return r.JSON.raw } +func (r *BetaDiagnostics) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// Only one field can be non-zero. +// BetaDiagnosticsCacheMissReasonUnion contains all possible properties and values +// from [BetaCacheMissModelChanged], [BetaCacheMissSystemChanged], +// [BetaCacheMissToolsChanged], [BetaCacheMissMessagesChanged], +// [BetaCacheMissPreviousMessageNotFound], [BetaCacheMissUnavailable]. // -// Use [param.IsOmitted] to confirm if a field is set. -type BetaRequestMCPToolResultBlockParamContentUnion struct { - OfString param.Opt[string] `json:",omitzero,inline"` - OfBetaMCPToolResultBlockContent []BetaTextBlockParam `json:",omitzero,inline"` - paramUnion +// Use the [BetaDiagnosticsCacheMissReasonUnion.AsAny] method to switch on the +// variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaDiagnosticsCacheMissReasonUnion struct { + CacheMissedInputTokens int64 `json:"cache_missed_input_tokens"` + // Any of "model_changed", "system_changed", "tools_changed", "messages_changed", + // "previous_message_not_found", "unavailable". + Type string `json:"type"` + JSON struct { + CacheMissedInputTokens respjson.Field + Type respjson.Field + raw string + } `json:"-"` } -func (u BetaRequestMCPToolResultBlockParamContentUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfString, u.OfBetaMCPToolResultBlockContent) -} -func (u *BetaRequestMCPToolResultBlockParamContentUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) +// anyBetaDiagnosticsCacheMissReason is implemented by each variant of +// [BetaDiagnosticsCacheMissReasonUnion] to add type safety for the return type of +// [BetaDiagnosticsCacheMissReasonUnion.AsAny] +type anyBetaDiagnosticsCacheMissReason interface { + implBetaDiagnosticsCacheMissReasonUnion() } -func (u *BetaRequestMCPToolResultBlockParamContentUnion) asAny() any { - if !param.IsOmitted(u.OfString) { - return &u.OfString.Value - } else if !param.IsOmitted(u.OfBetaMCPToolResultBlockContent) { - return &u.OfBetaMCPToolResultBlockContent +func (BetaCacheMissModelChanged) implBetaDiagnosticsCacheMissReasonUnion() {} +func (BetaCacheMissSystemChanged) implBetaDiagnosticsCacheMissReasonUnion() {} +func (BetaCacheMissToolsChanged) implBetaDiagnosticsCacheMissReasonUnion() {} +func (BetaCacheMissMessagesChanged) implBetaDiagnosticsCacheMissReasonUnion() {} +func (BetaCacheMissPreviousMessageNotFound) implBetaDiagnosticsCacheMissReasonUnion() {} +func (BetaCacheMissUnavailable) implBetaDiagnosticsCacheMissReasonUnion() {} + +// Use the following switch statement to find the correct variant +// +// switch variant := BetaDiagnosticsCacheMissReasonUnion.AsAny().(type) { +// case anthropic.BetaCacheMissModelChanged: +// case anthropic.BetaCacheMissSystemChanged: +// case anthropic.BetaCacheMissToolsChanged: +// case anthropic.BetaCacheMissMessagesChanged: +// case anthropic.BetaCacheMissPreviousMessageNotFound: +// case anthropic.BetaCacheMissUnavailable: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaDiagnosticsCacheMissReasonUnion) AsAny() anyBetaDiagnosticsCacheMissReason { + switch u.Type { + case "model_changed": + return u.AsModelChanged() + case "system_changed": + return u.AsSystemChanged() + case "tools_changed": + return u.AsToolsChanged() + case "messages_changed": + return u.AsMessagesChanged() + case "previous_message_not_found": + return u.AsPreviousMessageNotFound() + case "unavailable": + return u.AsUnavailable() } return nil } -// The properties Content, Source, Title, Type are required. -type BetaSearchResultBlockParam struct { - Content []BetaTextBlockParam `json:"content,omitzero" api:"required"` - Source string `json:"source" api:"required"` - Title string `json:"title" api:"required"` - // Create a cache control breakpoint at this content block. - CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` - Citations BetaCitationsConfigParam `json:"citations,omitzero"` - // This field can be elided, and will marshal its zero value as "search_result". - Type constant.SearchResult `json:"type" default:"search_result"` - paramObj +func (u BetaDiagnosticsCacheMissReasonUnion) AsModelChanged() (v BetaCacheMissModelChanged) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -func (r BetaSearchResultBlockParam) MarshalJSON() (data []byte, err error) { - type shadow BetaSearchResultBlockParam - return param.MarshalObject(r, (*shadow)(&r)) +func (u BetaDiagnosticsCacheMissReasonUnion) AsSystemChanged() (v BetaCacheMissSystemChanged) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -func (r *BetaSearchResultBlockParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) + +func (u BetaDiagnosticsCacheMissReasonUnion) AsToolsChanged() (v BetaCacheMissToolsChanged) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -// Tool invocation generated by a server-side tool. -type BetaServerToolCaller struct { - ToolID string `json:"tool_id" api:"required"` - Type constant.CodeExecution20250825 `json:"type" default:"code_execution_20250825"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ToolID respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +func (u BetaDiagnosticsCacheMissReasonUnion) AsMessagesChanged() (v BetaCacheMissMessagesChanged) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -// Returns the unmodified JSON received from the API -func (r BetaServerToolCaller) RawJSON() string { return r.JSON.raw } -func (r *BetaServerToolCaller) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +func (u BetaDiagnosticsCacheMissReasonUnion) AsPreviousMessageNotFound() (v BetaCacheMissPreviousMessageNotFound) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -// ToParam converts this BetaServerToolCaller to a BetaServerToolCallerParam. -// -// Warning: the fields of the param type will not be present. ToParam should only -// be used at the last possible moment before sending a request. Test for this with -// BetaServerToolCallerParam.Overrides() -func (r BetaServerToolCaller) ToParam() BetaServerToolCallerParam { - return param.Override[BetaServerToolCallerParam](json.RawMessage(r.RawJSON())) +func (u BetaDiagnosticsCacheMissReasonUnion) AsUnavailable() (v BetaCacheMissUnavailable) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -// Tool invocation generated by a server-side tool. -// -// The properties ToolID, Type are required. -type BetaServerToolCallerParam struct { - ToolID string `json:"tool_id" api:"required"` - // This field can be elided, and will marshal its zero value as - // "code_execution_20250825". - Type constant.CodeExecution20250825 `json:"type" default:"code_execution_20250825"` +// Returns the unmodified JSON received from the API +func (u BetaDiagnosticsCacheMissReasonUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaDiagnosticsCacheMissReasonUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Request-level diagnostics. Currently carries the previous response id for +// prompt-cache divergence reporting. +type BetaDiagnosticsParam struct { + // The `id` (`msg_...`) from this client's previous /v1/messages response. The + // server compares that request's prompt fingerprint against this one and returns + // `diagnostics.cache_miss_reason` when the prompt-cache prefix could not be + // reused. Pass `null` on the first turn to opt in without a prior message to + // compare. + PreviousMessageID param.Opt[string] `json:"previous_message_id,omitzero"` paramObj } -func (r BetaServerToolCallerParam) MarshalJSON() (data []byte, err error) { - type shadow BetaServerToolCallerParam +func (r BetaDiagnosticsParam) MarshalJSON() (data []byte, err error) { + type shadow BetaDiagnosticsParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *BetaServerToolCallerParam) UnmarshalJSON(data []byte) error { +func (r *BetaDiagnosticsParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type BetaServerToolCaller20260120 struct { - ToolID string `json:"tool_id" api:"required"` - Type constant.CodeExecution20260120 `json:"type" default:"code_execution_20260120"` +// Tool invocation directly from the model. +type BetaDirectCaller struct { + Type constant.Direct `json:"type" default:"direct"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { - ToolID respjson.Field Type respjson.Field ExtraFields map[string]respjson.Field raw string @@ -6512,741 +6081,672 @@ type BetaServerToolCaller20260120 struct { } // Returns the unmodified JSON received from the API -func (r BetaServerToolCaller20260120) RawJSON() string { return r.JSON.raw } -func (r *BetaServerToolCaller20260120) UnmarshalJSON(data []byte) error { +func (r BetaDirectCaller) RawJSON() string { return r.JSON.raw } +func (r *BetaDirectCaller) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// ToParam converts this BetaServerToolCaller20260120 to a -// BetaServerToolCaller20260120Param. +// ToParam converts this BetaDirectCaller to a BetaDirectCallerParam. // // Warning: the fields of the param type will not be present. ToParam should only // be used at the last possible moment before sending a request. Test for this with -// BetaServerToolCaller20260120Param.Overrides() -func (r BetaServerToolCaller20260120) ToParam() BetaServerToolCaller20260120Param { - return param.Override[BetaServerToolCaller20260120Param](json.RawMessage(r.RawJSON())) +// BetaDirectCallerParam.Overrides() +func (r BetaDirectCaller) ToParam() BetaDirectCallerParam { + return param.Override[BetaDirectCallerParam](json.RawMessage(r.RawJSON())) } -// The properties ToolID, Type are required. -type BetaServerToolCaller20260120Param struct { - ToolID string `json:"tool_id" api:"required"` - // This field can be elided, and will marshal its zero value as - // "code_execution_20260120". - Type constant.CodeExecution20260120 `json:"type" default:"code_execution_20260120"` - paramObj +func NewBetaDirectCallerParam() BetaDirectCallerParam { + return BetaDirectCallerParam{ + Type: "direct", + } } -func (r BetaServerToolCaller20260120Param) MarshalJSON() (data []byte, err error) { - type shadow BetaServerToolCaller20260120Param - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaServerToolCaller20260120Param) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +// Tool invocation directly from the model. +// +// This struct has a constant value, construct it with [NewBetaDirectCallerParam]. +type BetaDirectCallerParam struct { + Type constant.Direct `json:"type" default:"direct"` + paramObj } -type BetaServerToolUsage struct { - // The number of web fetch tool requests. - WebFetchRequests int64 `json:"web_fetch_requests" api:"required"` - // The number of web search tool requests. - WebSearchRequests int64 `json:"web_search_requests" api:"required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - WebFetchRequests respjson.Field - WebSearchRequests respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +func (r BetaDirectCallerParam) MarshalJSON() (data []byte, err error) { + type shadow BetaDirectCallerParam + return param.MarshalObject(r, (*shadow)(&r)) } - -// Returns the unmodified JSON received from the API -func (r BetaServerToolUsage) RawJSON() string { return r.JSON.raw } -func (r *BetaServerToolUsage) UnmarshalJSON(data []byte) error { +func (r *BetaDirectCallerParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type BetaServerToolUseBlock struct { - ID string `json:"id" api:"required"` - Input any `json:"input" api:"required"` - // Any of "advisor", "web_search", "web_fetch", "code_execution", - // "bash_code_execution", "text_editor_code_execution", "tool_search_tool_regex", - // "tool_search_tool_bm25". - Name BetaServerToolUseBlockName `json:"name" api:"required"` - Type constant.ServerToolUse `json:"type" default:"server_tool_use"` - // Tool invocation directly from the model. - Caller BetaServerToolUseBlockCallerUnion `json:"caller"` +type BetaDocumentBlock struct { + // Citation configuration for the document + Citations BetaCitationConfig `json:"citations" api:"required"` + Source BetaDocumentBlockSourceUnion `json:"source" api:"required"` + // The title of the document + Title string `json:"title" api:"required"` + Type constant.Document `json:"type" default:"document"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { - ID respjson.Field - Input respjson.Field - Name respjson.Field + Citations respjson.Field + Source respjson.Field + Title respjson.Field Type respjson.Field - Caller respjson.Field ExtraFields map[string]respjson.Field raw string } `json:"-"` } // Returns the unmodified JSON received from the API -func (r BetaServerToolUseBlock) RawJSON() string { return r.JSON.raw } -func (r *BetaServerToolUseBlock) UnmarshalJSON(data []byte) error { +func (r BetaDocumentBlock) RawJSON() string { return r.JSON.raw } +func (r *BetaDocumentBlock) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type BetaServerToolUseBlockName string - -const ( - BetaServerToolUseBlockNameAdvisor BetaServerToolUseBlockName = "advisor" - BetaServerToolUseBlockNameWebSearch BetaServerToolUseBlockName = "web_search" - BetaServerToolUseBlockNameWebFetch BetaServerToolUseBlockName = "web_fetch" - BetaServerToolUseBlockNameCodeExecution BetaServerToolUseBlockName = "code_execution" - BetaServerToolUseBlockNameBashCodeExecution BetaServerToolUseBlockName = "bash_code_execution" - BetaServerToolUseBlockNameTextEditorCodeExecution BetaServerToolUseBlockName = "text_editor_code_execution" - BetaServerToolUseBlockNameToolSearchToolRegex BetaServerToolUseBlockName = "tool_search_tool_regex" - BetaServerToolUseBlockNameToolSearchToolBm25 BetaServerToolUseBlockName = "tool_search_tool_bm25" -) - -// BetaServerToolUseBlockCallerUnion contains all possible properties and values -// from [BetaDirectCaller], [BetaServerToolCaller], [BetaServerToolCaller20260120]. +// BetaDocumentBlockSourceUnion contains all possible properties and values from +// [BetaBase64PDFSource], [BetaPlainTextSource]. // -// Use the [BetaServerToolUseBlockCallerUnion.AsAny] method to switch on the -// variant. +// Use the [BetaDocumentBlockSourceUnion.AsAny] method to switch on the variant. // // Use the methods beginning with 'As' to cast the union to one of its variants. -type BetaServerToolUseBlockCallerUnion struct { - // Any of "direct", "code_execution_20250825", "code_execution_20260120". - Type string `json:"type"` - ToolID string `json:"tool_id"` - JSON struct { - Type respjson.Field - ToolID respjson.Field - raw string +type BetaDocumentBlockSourceUnion struct { + Data string `json:"data"` + MediaType string `json:"media_type"` + // Any of "base64", "text". + Type string `json:"type"` + JSON struct { + Data respjson.Field + MediaType respjson.Field + Type respjson.Field + raw string } `json:"-"` } -// anyBetaServerToolUseBlockCaller is implemented by each variant of -// [BetaServerToolUseBlockCallerUnion] to add type safety for the return type of -// [BetaServerToolUseBlockCallerUnion.AsAny] -type anyBetaServerToolUseBlockCaller interface { - implBetaServerToolUseBlockCallerUnion() +// anyBetaDocumentBlockSource is implemented by each variant of +// [BetaDocumentBlockSourceUnion] to add type safety for the return type of +// [BetaDocumentBlockSourceUnion.AsAny] +type anyBetaDocumentBlockSource interface { + implBetaDocumentBlockSourceUnion() } -func (BetaDirectCaller) implBetaServerToolUseBlockCallerUnion() {} -func (BetaServerToolCaller) implBetaServerToolUseBlockCallerUnion() {} -func (BetaServerToolCaller20260120) implBetaServerToolUseBlockCallerUnion() {} +func (BetaBase64PDFSource) implBetaDocumentBlockSourceUnion() {} +func (BetaPlainTextSource) implBetaDocumentBlockSourceUnion() {} // Use the following switch statement to find the correct variant // -// switch variant := BetaServerToolUseBlockCallerUnion.AsAny().(type) { -// case anthropic.BetaDirectCaller: -// case anthropic.BetaServerToolCaller: -// case anthropic.BetaServerToolCaller20260120: +// switch variant := BetaDocumentBlockSourceUnion.AsAny().(type) { +// case anthropic.BetaBase64PDFSource: +// case anthropic.BetaPlainTextSource: // default: // fmt.Errorf("no variant present") // } -func (u BetaServerToolUseBlockCallerUnion) AsAny() anyBetaServerToolUseBlockCaller { +func (u BetaDocumentBlockSourceUnion) AsAny() anyBetaDocumentBlockSource { switch u.Type { - case "direct": - return u.AsDirect() - case "code_execution_20250825": - return u.AsCodeExecution20250825() - case "code_execution_20260120": - return u.AsCodeExecution20260120() + case "base64": + return u.AsBase64() + case "text": + return u.AsText() } return nil } -func (u BetaServerToolUseBlockCallerUnion) AsDirect() (v BetaDirectCaller) { +func (u BetaDocumentBlockSourceUnion) AsBase64() (v BetaBase64PDFSource) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return } -func (u BetaServerToolUseBlockCallerUnion) AsCodeExecution20250825() (v BetaServerToolCaller) { +func (u BetaDocumentBlockSourceUnion) AsText() (v BetaPlainTextSource) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return } -func (u BetaServerToolUseBlockCallerUnion) AsCodeExecution20260120() (v BetaServerToolCaller20260120) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +// Returns the unmodified JSON received from the API +func (u BetaDocumentBlockSourceUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaDocumentBlockSourceUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns the unmodified JSON received from the API -func (u BetaServerToolUseBlockCallerUnion) RawJSON() string { return u.JSON.raw } +// Code execution result with encrypted stdout for PFC + web_search results. +type BetaEncryptedCodeExecutionResultBlock struct { + Content []BetaCodeExecutionOutputBlock `json:"content" api:"required"` + EncryptedStdout string `json:"encrypted_stdout" api:"required"` + ReturnCode int64 `json:"return_code" api:"required"` + Stderr string `json:"stderr" api:"required"` + Type constant.EncryptedCodeExecutionResult `json:"type" default:"encrypted_code_execution_result"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Content respjson.Field + EncryptedStdout respjson.Field + ReturnCode respjson.Field + Stderr respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} -func (r *BetaServerToolUseBlockCallerUnion) UnmarshalJSON(data []byte) error { +// Returns the unmodified JSON received from the API +func (r BetaEncryptedCodeExecutionResultBlock) RawJSON() string { return r.JSON.raw } +func (r *BetaEncryptedCodeExecutionResultBlock) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The properties ID, Input, Name, Type are required. -type BetaServerToolUseBlockParam struct { - ID string `json:"id" api:"required"` - Input any `json:"input,omitzero" api:"required"` - // Any of "advisor", "web_search", "web_fetch", "code_execution", - // "bash_code_execution", "text_editor_code_execution", "tool_search_tool_regex", - // "tool_search_tool_bm25". - Name BetaServerToolUseBlockParamName `json:"name,omitzero" api:"required"` - // Create a cache control breakpoint at this content block. - CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` - // Tool invocation directly from the model. - Caller BetaServerToolUseBlockParamCallerUnion `json:"caller,omitzero"` - // This field can be elided, and will marshal its zero value as "server_tool_use". - Type constant.ServerToolUse `json:"type" default:"server_tool_use"` +// Code execution result with encrypted stdout for PFC + web_search results. +// +// The properties Content, EncryptedStdout, ReturnCode, Stderr, Type are required. +type BetaEncryptedCodeExecutionResultBlockParam struct { + Content []BetaCodeExecutionOutputBlockParam `json:"content,omitzero" api:"required"` + EncryptedStdout string `json:"encrypted_stdout" api:"required"` + ReturnCode int64 `json:"return_code" api:"required"` + Stderr string `json:"stderr" api:"required"` + // This field can be elided, and will marshal its zero value as + // "encrypted_code_execution_result". + Type constant.EncryptedCodeExecutionResult `json:"type" default:"encrypted_code_execution_result"` paramObj } -func (r BetaServerToolUseBlockParam) MarshalJSON() (data []byte, err error) { - type shadow BetaServerToolUseBlockParam +func (r BetaEncryptedCodeExecutionResultBlockParam) MarshalJSON() (data []byte, err error) { + type shadow BetaEncryptedCodeExecutionResultBlockParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *BetaServerToolUseBlockParam) UnmarshalJSON(data []byte) error { +func (r *BetaEncryptedCodeExecutionResultBlockParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type BetaServerToolUseBlockParamName string - -const ( - BetaServerToolUseBlockParamNameAdvisor BetaServerToolUseBlockParamName = "advisor" - BetaServerToolUseBlockParamNameWebSearch BetaServerToolUseBlockParamName = "web_search" - BetaServerToolUseBlockParamNameWebFetch BetaServerToolUseBlockParamName = "web_fetch" - BetaServerToolUseBlockParamNameCodeExecution BetaServerToolUseBlockParamName = "code_execution" - BetaServerToolUseBlockParamNameBashCodeExecution BetaServerToolUseBlockParamName = "bash_code_execution" - BetaServerToolUseBlockParamNameTextEditorCodeExecution BetaServerToolUseBlockParamName = "text_editor_code_execution" - BetaServerToolUseBlockParamNameToolSearchToolRegex BetaServerToolUseBlockParamName = "tool_search_tool_regex" - BetaServerToolUseBlockParamNameToolSearchToolBm25 BetaServerToolUseBlockParamName = "tool_search_tool_bm25" -) - -// Only one field can be non-zero. +// Marks the point in `content` where one model's output gives way to the next. // -// Use [param.IsOmitted] to confirm if a field is set. -type BetaServerToolUseBlockParamCallerUnion struct { - OfDirect *BetaDirectCallerParam `json:",omitzero,inline"` - OfCodeExecution20250825 *BetaServerToolCallerParam `json:",omitzero,inline"` - OfCodeExecution20260120 *BetaServerToolCaller20260120Param `json:",omitzero,inline"` - paramUnion +// One block appears per hop where a preceding model actually ran this turn and +// declined. A turn where no preceding model ran and declined has no such boundary +// and carries no block — the signal for whether a fallback model served the +// response is the presence of a `fallback_message` entry in `usage.iterations`, +// not this block. +// +// The block is treated like a server-tool content block for streaming: it arrives +// via the standard `content_block_start` / `content_block_stop` pair and carries +// no deltas. +type BetaFallbackBlock struct { + // The model whose output ends at this point — the model that declined at this hop. + // When the declining hop is the requested model, its `model` echoes the top-level + // `model` string the caller sent (alias or canonical); when the declining hop is a + // fallback model, its `model` is that model's canonical id. + From BetaFallbackInfo `json:"from" api:"required"` + // The fallback model producing the content that follows this block. Its `model` is + // always the canonical id. + To BetaFallbackInfo `json:"to" api:"required"` + // What caused the `from` model to hand over at this hop. + Trigger BetaFallbackRefusalTrigger `json:"trigger" api:"required"` + Type constant.Fallback `json:"type" default:"fallback"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + From respjson.Field + To respjson.Field + Trigger respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` } -func (u BetaServerToolUseBlockParamCallerUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfDirect, u.OfCodeExecution20250825, u.OfCodeExecution20260120) +// Returns the unmodified JSON received from the API +func (r BetaFallbackBlock) RawJSON() string { return r.JSON.raw } +func (r *BetaFallbackBlock) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func (u *BetaServerToolUseBlockParamCallerUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) + +// A `fallback` block echoed back from a prior response. +// +// Accepted in `messages[].content` and not rendered into the prompt; not validated +// against the request's `fallbacks` chain or top-level `model`. +// +// Echo the assistant turn back verbatim, including this block in its original +// position. The block marks the boundary between content produced before and after +// a fallback hop, and the server relies on that boundary to validate the turn: +// when thinking runs flank the boundary, omitting the block merges them into one +// span the server cannot validate (the request is rejected), and moving it into +// the middle of a single run is likewise rejected; between non-thinking blocks the +// block's placement has no validation effect. +// +// The properties From, To, Type are required. +type BetaFallbackBlockParam struct { + // Identifies one hop of a fallback transition. + From BetaFallbackInfoParam `json:"from,omitzero" api:"required"` + // Identifies one hop of a fallback transition. + To BetaFallbackInfoParam `json:"to,omitzero" api:"required"` + // The response block's `trigger`, echoed verbatim. Accepted and ignored by the + // server; any object or `null` is allowed. + Trigger any `json:"trigger,omitzero"` + // This field can be elided, and will marshal its zero value as "fallback". + Type constant.Fallback `json:"type" default:"fallback"` + paramObj } -func (u *BetaServerToolUseBlockParamCallerUnion) asAny() any { - if !param.IsOmitted(u.OfDirect) { - return u.OfDirect - } else if !param.IsOmitted(u.OfCodeExecution20250825) { - return u.OfCodeExecution20250825 - } else if !param.IsOmitted(u.OfCodeExecution20260120) { - return u.OfCodeExecution20260120 - } - return nil +func (r BetaFallbackBlockParam) MarshalJSON() (data []byte, err error) { + type shadow BetaFallbackBlockParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaFallbackBlockParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaServerToolUseBlockParamCallerUnion) GetType() *string { - if vt := u.OfDirect; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfCodeExecution20250825; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfCodeExecution20260120; vt != nil { - return (*string)(&vt.Type) - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u BetaServerToolUseBlockParamCallerUnion) GetToolID() *string { - if vt := u.OfCodeExecution20250825; vt != nil { - return (*string)(&vt.ToolID) - } else if vt := u.OfCodeExecution20260120; vt != nil { - return (*string)(&vt.ToolID) - } - return nil -} - -func init() { - apijson.RegisterUnion[BetaServerToolUseBlockParamCallerUnion]( - "type", - apijson.Discriminator[BetaDirectCallerParam]("direct"), - apijson.Discriminator[BetaServerToolCallerParam]("code_execution_20250825"), - apijson.Discriminator[BetaServerToolCaller20260120Param]("code_execution_20260120"), - ) -} - -type BetaSignatureDelta struct { - Signature string `json:"signature" api:"required"` - Type constant.SignatureDelta `json:"type" default:"signature_delta"` +// No reprice was applied; `reason` says why. +type BetaFallbackCreditNotApplied struct { + // Why the reprice was not applied. + // + // A closed enum; additions to the redemption-check vocabulary arrive as deliberate + // schema updates. + // + // Any of "body_mismatch", "continuation_excluded", "continuation_only", "expired", + // "invalid_target_model", "not_enabled", "reprice_unavailable", + // "temporarily_unavailable", "variant_fields_present", "wrong_organization", + // "wrong_platform", "wrong_workspace". + Reason BetaFallbackCreditNotAppliedReason `json:"reason" api:"required"` + Type constant.NotApplied `json:"type" default:"not_applied"` + // Request fields to remove before retrying, so the retry can redeem this token. + // + // Present exactly when `reason` is `variant_fields_present` — never null, never an + // empty array; absent otherwise. Fields are named only from your own request, and + // only after the sealed variant hash matched. A served best-effort retry has + // already been billed at normal price; nothing redeems retroactively, but a + // corrected re-send inside the token's five-minute window can still redeem. + RemoveToRedeem []string `json:"remove_to_redeem" api:"nullable"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { - Signature respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string + Reason respjson.Field + Type respjson.Field + RemoveToRedeem respjson.Field + ExtraFields map[string]respjson.Field + raw string } `json:"-"` } // Returns the unmodified JSON received from the API -func (r BetaSignatureDelta) RawJSON() string { return r.JSON.raw } -func (r *BetaSignatureDelta) UnmarshalJSON(data []byte) error { +func (r BetaFallbackCreditNotApplied) RawJSON() string { return r.JSON.raw } +func (r *BetaFallbackCreditNotApplied) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// A skill that was loaded in a container (response model). -type BetaSkill struct { - // Skill ID - SkillID string `json:"skill_id" api:"required"` - // Type of skill - either 'anthropic' (built-in) or 'custom' (user-defined) - // - // Any of "anthropic", "custom". - Type BetaSkillType `json:"type" api:"required"` - // Skill version or 'latest' for most recent version - Version string `json:"version" api:"required"` +// Why the reprice was not applied. +// +// A closed enum; additions to the redemption-check vocabulary arrive as deliberate +// schema updates. +type BetaFallbackCreditNotAppliedReason string + +const ( + BetaFallbackCreditNotAppliedReasonBodyMismatch BetaFallbackCreditNotAppliedReason = "body_mismatch" + BetaFallbackCreditNotAppliedReasonContinuationExcluded BetaFallbackCreditNotAppliedReason = "continuation_excluded" + BetaFallbackCreditNotAppliedReasonContinuationOnly BetaFallbackCreditNotAppliedReason = "continuation_only" + BetaFallbackCreditNotAppliedReasonExpired BetaFallbackCreditNotAppliedReason = "expired" + BetaFallbackCreditNotAppliedReasonInvalidTargetModel BetaFallbackCreditNotAppliedReason = "invalid_target_model" + BetaFallbackCreditNotAppliedReasonNotEnabled BetaFallbackCreditNotAppliedReason = "not_enabled" + BetaFallbackCreditNotAppliedReasonRepriceUnavailable BetaFallbackCreditNotAppliedReason = "reprice_unavailable" + BetaFallbackCreditNotAppliedReasonTemporarilyUnavailable BetaFallbackCreditNotAppliedReason = "temporarily_unavailable" + BetaFallbackCreditNotAppliedReasonVariantFieldsPresent BetaFallbackCreditNotAppliedReason = "variant_fields_present" + BetaFallbackCreditNotAppliedReasonWrongOrganization BetaFallbackCreditNotAppliedReason = "wrong_organization" + BetaFallbackCreditNotAppliedReasonWrongPlatform BetaFallbackCreditNotAppliedReason = "wrong_platform" + BetaFallbackCreditNotAppliedReasonWrongWorkspace BetaFallbackCreditNotAppliedReason = "wrong_workspace" +) + +// The reprice was applied: the retry is billed as if the conversation had been on +// the retry model all along. +type BetaFallbackCreditRedeemed struct { + Type constant.Redeemed `json:"type" default:"redeemed"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { - SkillID respjson.Field Type respjson.Field - Version respjson.Field ExtraFields map[string]respjson.Field raw string } `json:"-"` } // Returns the unmodified JSON received from the API -func (r BetaSkill) RawJSON() string { return r.JSON.raw } -func (r *BetaSkill) UnmarshalJSON(data []byte) error { +func (r BetaFallbackCreditRedeemed) RawJSON() string { return r.JSON.raw } +func (r *BetaFallbackCreditRedeemed) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// Type of skill - either 'anthropic' (built-in) or 'custom' (user-defined) -type BetaSkillType string - -const ( - BetaSkillTypeAnthropic BetaSkillType = "anthropic" - BetaSkillTypeCustom BetaSkillType = "custom" -) - -// Specification for a skill to be loaded in a container (request model). +// Object form of `fallback_credit_token`: the token plus a redemption mode. // -// The properties SkillID, Type are required. -type BetaSkillParams struct { - // Skill ID - SkillID string `json:"skill_id" api:"required"` - // Type of skill - either 'anthropic' (built-in) or 'custom' (user-defined) +// Requires `anthropic-beta: fallback-credit-2026-07-01`; without that header the +// field accepts the bare string only. The bare string and the mode-less object are +// equivalent (both select `strict`), so wrapping an existing token changes nothing +// by itself. +// +// The property Token is required. +type BetaFallbackCreditTokenParam struct { + // The opaque `fallback_credit_token` from a prior refusal's `stop_details` — the + // same string the bare-string form carries. + Token string `json:"token" api:"required"` + // How a failing token affects the retry. `strict` (the default, and the + // bare-string behavior): a failing redemption is a 400 and the retry is not + // served. `best_effort`: the retry is served either way — a token-layer failure no + // longer rejects the request; the retry proceeds at normal price and the outcome + // is reported on the response's `usage.fallback_credit`. Two failures stay hard in + // both modes: a malformed token, and combining `fallback_credit_token` with + // `fallbacks`. // - // Any of "anthropic", "custom". - Type BetaSkillParamsType `json:"type,omitzero" api:"required"` - // Skill version or 'latest' for most recent version - Version param.Opt[string] `json:"version,omitzero"` + // Any of "strict", "best_effort". + Mode BetaFallbackCreditTokenParamMode `json:"mode,omitzero"` paramObj } -func (r BetaSkillParams) MarshalJSON() (data []byte, err error) { - type shadow BetaSkillParams +func (r BetaFallbackCreditTokenParam) MarshalJSON() (data []byte, err error) { + type shadow BetaFallbackCreditTokenParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *BetaSkillParams) UnmarshalJSON(data []byte) error { +func (r *BetaFallbackCreditTokenParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// Type of skill - either 'anthropic' (built-in) or 'custom' (user-defined) -type BetaSkillParamsType string - -const ( - BetaSkillParamsTypeAnthropic BetaSkillParamsType = "anthropic" - BetaSkillParamsTypeCustom BetaSkillParamsType = "custom" -) - -type BetaStopReason string +// How a failing token affects the retry. `strict` (the default, and the +// bare-string behavior): a failing redemption is a 400 and the retry is not +// served. `best_effort`: the retry is served either way — a token-layer failure no +// longer rejects the request; the retry proceeds at normal price and the outcome +// is reported on the response's `usage.fallback_credit`. Two failures stay hard in +// both modes: a malformed token, and combining `fallback_credit_token` with +// `fallbacks`. +type BetaFallbackCreditTokenParamMode string const ( - BetaStopReasonEndTurn BetaStopReason = "end_turn" - BetaStopReasonMaxTokens BetaStopReason = "max_tokens" - BetaStopReasonStopSequence BetaStopReason = "stop_sequence" - BetaStopReasonToolUse BetaStopReason = "tool_use" - BetaStopReasonPauseTurn BetaStopReason = "pause_turn" - BetaStopReasonCompaction BetaStopReason = "compaction" - BetaStopReasonRefusal BetaStopReason = "refusal" - BetaStopReasonModelContextWindowExceeded BetaStopReason = "model_context_window_exceeded" + BetaFallbackCreditTokenParamModeStrict BetaFallbackCreditTokenParamMode = "strict" + BetaFallbackCreditTokenParamModeBestEffort BetaFallbackCreditTokenParamMode = "best_effort" ) -type BetaTextBlock struct { - // Citations supporting the text block. +// Outcome of the `fallback_credit_token` presented on this request. +type BetaFallbackCreditUsage struct { + // Whether the fallback-credit reprice was applied to this response's billing. // - // The type of citation returned will depend on the type of document being cited. - // Citing a PDF results in `page_location`, plain text results in `char_location`, - // and content document results in `content_block_location`. - Citations []BetaTextCitationUnion `json:"citations" api:"required"` - Text string `json:"text" api:"required"` - Type constant.Text `json:"type" default:"text"` + // A union discriminated on `type`. `redeemed`: the retry is billed as if the + // conversation had been on the retry model all along — including when the + // resulting shift is zero because there was nothing to move. `not_applied`: no + // reprice was applied; the arm's `reason` says why. + Status BetaFallbackCreditUsageStatusUnion `json:"status" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { - Citations respjson.Field - Text respjson.Field - Type respjson.Field + Status respjson.Field ExtraFields map[string]respjson.Field raw string } `json:"-"` } // Returns the unmodified JSON received from the API -func (r BetaTextBlock) RawJSON() string { return r.JSON.raw } -func (r *BetaTextBlock) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The properties Text, Type are required. -type BetaTextBlockParam struct { - Text string `json:"text" api:"required"` - Citations []BetaTextCitationParamUnion `json:"citations,omitzero"` - // Create a cache control breakpoint at this content block. - CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` - // This field can be elided, and will marshal its zero value as "text". - Type constant.Text `json:"type" default:"text"` - paramObj -} - -func (r BetaTextBlockParam) MarshalJSON() (data []byte, err error) { - type shadow BetaTextBlockParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaTextBlockParam) UnmarshalJSON(data []byte) error { +func (r BetaFallbackCreditUsage) RawJSON() string { return r.JSON.raw } +func (r *BetaFallbackCreditUsage) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// BetaTextCitationUnion contains all possible properties and values from -// [BetaCitationCharLocation], [BetaCitationPageLocation], -// [BetaCitationContentBlockLocation], [BetaCitationsWebSearchResultLocation], -// [BetaCitationSearchResultLocation]. +// BetaFallbackCreditUsageStatusUnion contains all possible properties and values +// from [BetaFallbackCreditRedeemed], [BetaFallbackCreditNotApplied]. // -// Use the [BetaTextCitationUnion.AsAny] method to switch on the variant. +// Use the [BetaFallbackCreditUsageStatusUnion.AsAny] method to switch on the +// variant. // // Use the methods beginning with 'As' to cast the union to one of its variants. -type BetaTextCitationUnion struct { - CitedText string `json:"cited_text"` - DocumentIndex int64 `json:"document_index"` - DocumentTitle string `json:"document_title"` - // This field is from variant [BetaCitationCharLocation]. - EndCharIndex int64 `json:"end_char_index"` - FileID string `json:"file_id"` - // This field is from variant [BetaCitationCharLocation]. - StartCharIndex int64 `json:"start_char_index"` - // Any of "char_location", "page_location", "content_block_location", - // "web_search_result_location", "search_result_location". +type BetaFallbackCreditUsageStatusUnion struct { + // Any of "redeemed", "not_applied". Type string `json:"type"` - // This field is from variant [BetaCitationPageLocation]. - EndPageNumber int64 `json:"end_page_number"` - // This field is from variant [BetaCitationPageLocation]. - StartPageNumber int64 `json:"start_page_number"` - EndBlockIndex int64 `json:"end_block_index"` - StartBlockIndex int64 `json:"start_block_index"` - // This field is from variant [BetaCitationsWebSearchResultLocation]. - EncryptedIndex string `json:"encrypted_index"` - Title string `json:"title"` - // This field is from variant [BetaCitationsWebSearchResultLocation]. - URL string `json:"url"` - // This field is from variant [BetaCitationSearchResultLocation]. - SearchResultIndex int64 `json:"search_result_index"` - // This field is from variant [BetaCitationSearchResultLocation]. - Source string `json:"source"` - JSON struct { - CitedText respjson.Field - DocumentIndex respjson.Field - DocumentTitle respjson.Field - EndCharIndex respjson.Field - FileID respjson.Field - StartCharIndex respjson.Field - Type respjson.Field - EndPageNumber respjson.Field - StartPageNumber respjson.Field - EndBlockIndex respjson.Field - StartBlockIndex respjson.Field - EncryptedIndex respjson.Field - Title respjson.Field - URL respjson.Field - SearchResultIndex respjson.Field - Source respjson.Field - raw string + // This field is from variant [BetaFallbackCreditNotApplied]. + Reason BetaFallbackCreditNotAppliedReason `json:"reason"` + // This field is from variant [BetaFallbackCreditNotApplied]. + RemoveToRedeem []string `json:"remove_to_redeem"` + JSON struct { + Type respjson.Field + Reason respjson.Field + RemoveToRedeem respjson.Field + raw string } `json:"-"` } -// anyBetaTextCitation is implemented by each variant of [BetaTextCitationUnion] to -// add type safety for the return type of [BetaTextCitationUnion.AsAny] -type anyBetaTextCitation interface { - implBetaTextCitationUnion() - toParamUnion() BetaTextCitationParamUnion +// anyBetaFallbackCreditUsageStatus is implemented by each variant of +// [BetaFallbackCreditUsageStatusUnion] to add type safety for the return type of +// [BetaFallbackCreditUsageStatusUnion.AsAny] +type anyBetaFallbackCreditUsageStatus interface { + implBetaFallbackCreditUsageStatusUnion() } -func (BetaCitationCharLocation) implBetaTextCitationUnion() {} -func (BetaCitationPageLocation) implBetaTextCitationUnion() {} -func (BetaCitationContentBlockLocation) implBetaTextCitationUnion() {} -func (BetaCitationsWebSearchResultLocation) implBetaTextCitationUnion() {} -func (BetaCitationSearchResultLocation) implBetaTextCitationUnion() {} +func (BetaFallbackCreditRedeemed) implBetaFallbackCreditUsageStatusUnion() {} +func (BetaFallbackCreditNotApplied) implBetaFallbackCreditUsageStatusUnion() {} // Use the following switch statement to find the correct variant // -// switch variant := BetaTextCitationUnion.AsAny().(type) { -// case anthropic.BetaCitationCharLocation: -// case anthropic.BetaCitationPageLocation: -// case anthropic.BetaCitationContentBlockLocation: -// case anthropic.BetaCitationsWebSearchResultLocation: -// case anthropic.BetaCitationSearchResultLocation: +// switch variant := BetaFallbackCreditUsageStatusUnion.AsAny().(type) { +// case anthropic.BetaFallbackCreditRedeemed: +// case anthropic.BetaFallbackCreditNotApplied: // default: // fmt.Errorf("no variant present") // } -func (u BetaTextCitationUnion) AsAny() anyBetaTextCitation { +func (u BetaFallbackCreditUsageStatusUnion) AsAny() anyBetaFallbackCreditUsageStatus { switch u.Type { - case "char_location": - return u.AsCharLocation() - case "page_location": - return u.AsPageLocation() - case "content_block_location": - return u.AsContentBlockLocation() - case "web_search_result_location": - return u.AsWebSearchResultLocation() - case "search_result_location": - return u.AsSearchResultLocation() + case "redeemed": + return u.AsRedeemed() + case "not_applied": + return u.AsNotApplied() } return nil } -func (u BetaTextCitationUnion) AsCharLocation() (v BetaCitationCharLocation) { +func (u BetaFallbackCreditUsageStatusUnion) AsRedeemed() (v BetaFallbackCreditRedeemed) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return } -func (u BetaTextCitationUnion) AsPageLocation() (v BetaCitationPageLocation) { +func (u BetaFallbackCreditUsageStatusUnion) AsNotApplied() (v BetaFallbackCreditNotApplied) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return } -func (u BetaTextCitationUnion) AsContentBlockLocation() (v BetaCitationContentBlockLocation) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} +// Returns the unmodified JSON received from the API +func (u BetaFallbackCreditUsageStatusUnion) RawJSON() string { return u.JSON.raw } -func (u BetaTextCitationUnion) AsWebSearchResultLocation() (v BetaCitationsWebSearchResultLocation) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +func (r *BetaFallbackCreditUsageStatusUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func (u BetaTextCitationUnion) AsSearchResultLocation() (v BetaCitationSearchResultLocation) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +// Identifies one hop of a fallback transition. +type BetaFallbackInfo struct { + // The model that will complete your prompt. + // + // See [models](https://docs.anthropic.com/en/docs/models-overview) for additional + // details and options. + Model Model `json:"model" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Model respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` } // Returns the unmodified JSON received from the API -func (u BetaTextCitationUnion) RawJSON() string { return u.JSON.raw } - -func (r *BetaTextCitationUnion) UnmarshalJSON(data []byte) error { +func (r BetaFallbackInfo) RawJSON() string { return r.JSON.raw } +func (r *BetaFallbackInfo) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// Only one field can be non-zero. +// Identifies one hop of a fallback transition. // -// Use [param.IsOmitted] to confirm if a field is set. -type BetaTextCitationParamUnion struct { - OfCharLocation *BetaCitationCharLocationParam `json:",omitzero,inline"` - OfPageLocation *BetaCitationPageLocationParam `json:",omitzero,inline"` - OfContentBlockLocation *BetaCitationContentBlockLocationParam `json:",omitzero,inline"` - OfWebSearchResultLocation *BetaCitationWebSearchResultLocationParam `json:",omitzero,inline"` - OfSearchResultLocation *BetaCitationSearchResultLocationParam `json:",omitzero,inline"` - paramUnion +// The property Model is required. +type BetaFallbackInfoParam struct { + // The model that will complete your prompt. + // + // See [models](https://docs.anthropic.com/en/docs/models-overview) for additional + // details and options. + Model Model `json:"model,omitzero" api:"required"` + paramObj } -func (u BetaTextCitationParamUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfCharLocation, - u.OfPageLocation, - u.OfContentBlockLocation, - u.OfWebSearchResultLocation, - u.OfSearchResultLocation) +func (r BetaFallbackInfoParam) MarshalJSON() (data []byte, err error) { + type shadow BetaFallbackInfoParam + return param.MarshalObject(r, (*shadow)(&r)) } -func (u *BetaTextCitationParamUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) +func (r *BetaFallbackInfoParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func (u *BetaTextCitationParamUnion) asAny() any { - if !param.IsOmitted(u.OfCharLocation) { - return u.OfCharLocation - } else if !param.IsOmitted(u.OfPageLocation) { - return u.OfPageLocation - } else if !param.IsOmitted(u.OfContentBlockLocation) { - return u.OfContentBlockLocation - } else if !param.IsOmitted(u.OfWebSearchResultLocation) { - return u.OfWebSearchResultLocation - } else if !param.IsOmitted(u.OfSearchResultLocation) { - return u.OfSearchResultLocation - } - return nil +// Token usage for the fallback-model attempt of a server-side fallback request. +// +// Produced in place of a `message` entry for whichever hop served the response. A +// declined hop produces the existing `message` entry. Whether a fallback model +// served the response is signalled by the presence of this entry in +// `usage.iterations`. +type BetaFallbackMessageIterationUsage struct { + // Breakdown of cached tokens by TTL + CacheCreation BetaCacheCreation `json:"cache_creation" api:"required"` + // The number of input tokens used to create the cache entry. + CacheCreationInputTokens int64 `json:"cache_creation_input_tokens" api:"required"` + // The number of input tokens read from the cache. + CacheReadInputTokens int64 `json:"cache_read_input_tokens" api:"required"` + // The number of input tokens which were used. + InputTokens int64 `json:"input_tokens" api:"required"` + // The model that will complete your prompt. + // + // See [models](https://docs.anthropic.com/en/docs/models-overview) for additional + // details and options. + Model Model `json:"model" api:"required"` + // The number of output tokens which were used. + OutputTokens int64 `json:"output_tokens" api:"required"` + // Usage for the fallback-model attempt that served the response + Type constant.FallbackMessage `json:"type" default:"fallback_message"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + CacheCreation respjson.Field + CacheCreationInputTokens respjson.Field + CacheReadInputTokens respjson.Field + InputTokens respjson.Field + Model respjson.Field + OutputTokens respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaTextCitationParamUnion) GetEndCharIndex() *int64 { - if vt := u.OfCharLocation; vt != nil { - return &vt.EndCharIndex - } - return nil +// Returns the unmodified JSON received from the API +func (r BetaFallbackMessageIterationUsage) RawJSON() string { return r.JSON.raw } +func (r *BetaFallbackMessageIterationUsage) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaTextCitationParamUnion) GetStartCharIndex() *int64 { - if vt := u.OfCharLocation; vt != nil { - return &vt.StartCharIndex - } - return nil +// One entry in the `fallbacks` chain on a `/v1/messages` request. +// +// `model` is required. The override fields (`max_tokens`, `thinking`, +// `output_config`, and `speed`) set the corresponding parameter for this attempt +// only and are validated as if the request were made to `model`. Any other key is +// rejected at parse time. +// +// The property Model is required. +type BetaFallbackParam struct { + // The model that will complete your prompt. + // + // See [models](https://docs.anthropic.com/en/docs/models-overview) for additional + // details and options. + Model Model `json:"model,omitzero" api:"required"` + MaxTokens param.Opt[int64] `json:"max_tokens,omitzero"` + // Inference speed mode. `fast` provides significantly faster output token + // generation at premium pricing. Not all models support `fast`; invalid + // combinations are rejected at create time. + // + // Any of "standard", "fast". + Speed BetaFallbackParamSpeed `json:"speed,omitzero"` + Thinking BetaFallbackParamThinkingUnion `json:"thinking,omitzero"` + OutputConfig BetaOutputConfigParam `json:"output_config,omitzero"` + ExtraFields map[string]any `json:"-"` + paramObj } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaTextCitationParamUnion) GetEndPageNumber() *int64 { - if vt := u.OfPageLocation; vt != nil { - return &vt.EndPageNumber - } - return nil +func (r BetaFallbackParam) MarshalJSON() (data []byte, err error) { + type shadow BetaFallbackParam + return param.MarshalWithExtras(r, (*shadow)(&r), r.ExtraFields) } - -// Returns a pointer to the underlying variant's property, if present. -func (u BetaTextCitationParamUnion) GetStartPageNumber() *int64 { - if vt := u.OfPageLocation; vt != nil { - return &vt.StartPageNumber - } - return nil +func (r *BetaFallbackParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaTextCitationParamUnion) GetEncryptedIndex() *string { - if vt := u.OfWebSearchResultLocation; vt != nil { - return &vt.EncryptedIndex - } - return nil -} +// Inference speed mode. `fast` provides significantly faster output token +// generation at premium pricing. Not all models support `fast`; invalid +// combinations are rejected at create time. +type BetaFallbackParamSpeed string -// Returns a pointer to the underlying variant's property, if present. -func (u BetaTextCitationParamUnion) GetURL() *string { - if vt := u.OfWebSearchResultLocation; vt != nil { - return &vt.URL - } - return nil -} +const ( + BetaFallbackParamSpeedStandard BetaFallbackParamSpeed = "standard" + BetaFallbackParamSpeedFast BetaFallbackParamSpeed = "fast" +) -// Returns a pointer to the underlying variant's property, if present. -func (u BetaTextCitationParamUnion) GetSearchResultIndex() *int64 { - if vt := u.OfSearchResultLocation; vt != nil { - return &vt.SearchResultIndex - } - return nil +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaFallbackParamThinkingUnion struct { + OfEnabled *BetaThinkingConfigEnabledParam `json:",omitzero,inline"` + OfDisabled *BetaThinkingConfigDisabledParam `json:",omitzero,inline"` + OfAdaptive *BetaThinkingConfigAdaptiveParam `json:",omitzero,inline"` + paramUnion } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaTextCitationParamUnion) GetSource() *string { - if vt := u.OfSearchResultLocation; vt != nil { - return &vt.Source - } - return nil +func (u BetaFallbackParamThinkingUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfEnabled, u.OfDisabled, u.OfAdaptive) } - -// Returns a pointer to the underlying variant's property, if present. -func (u BetaTextCitationParamUnion) GetCitedText() *string { - if vt := u.OfCharLocation; vt != nil { - return (*string)(&vt.CitedText) - } else if vt := u.OfPageLocation; vt != nil { - return (*string)(&vt.CitedText) - } else if vt := u.OfContentBlockLocation; vt != nil { - return (*string)(&vt.CitedText) - } else if vt := u.OfWebSearchResultLocation; vt != nil { - return (*string)(&vt.CitedText) - } else if vt := u.OfSearchResultLocation; vt != nil { - return (*string)(&vt.CitedText) - } - return nil +func (u *BetaFallbackParamThinkingUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaTextCitationParamUnion) GetDocumentIndex() *int64 { - if vt := u.OfCharLocation; vt != nil { - return (*int64)(&vt.DocumentIndex) - } else if vt := u.OfPageLocation; vt != nil { - return (*int64)(&vt.DocumentIndex) - } else if vt := u.OfContentBlockLocation; vt != nil { - return (*int64)(&vt.DocumentIndex) +func (u *BetaFallbackParamThinkingUnion) asAny() any { + if !param.IsOmitted(u.OfEnabled) { + return u.OfEnabled + } else if !param.IsOmitted(u.OfDisabled) { + return u.OfDisabled + } else if !param.IsOmitted(u.OfAdaptive) { + return u.OfAdaptive } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u BetaTextCitationParamUnion) GetDocumentTitle() *string { - if vt := u.OfCharLocation; vt != nil && vt.DocumentTitle.Valid() { - return &vt.DocumentTitle.Value - } else if vt := u.OfPageLocation; vt != nil && vt.DocumentTitle.Valid() { - return &vt.DocumentTitle.Value - } else if vt := u.OfContentBlockLocation; vt != nil && vt.DocumentTitle.Valid() { - return &vt.DocumentTitle.Value +func (u BetaFallbackParamThinkingUnion) GetBudgetTokens() *int64 { + if vt := u.OfEnabled; vt != nil { + return &vt.BudgetTokens } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u BetaTextCitationParamUnion) GetType() *string { - if vt := u.OfCharLocation; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfPageLocation; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfContentBlockLocation; vt != nil { +func (u BetaFallbackParamThinkingUnion) GetType() *string { + if vt := u.OfEnabled; vt != nil { return (*string)(&vt.Type) - } else if vt := u.OfWebSearchResultLocation; vt != nil { + } else if vt := u.OfDisabled; vt != nil { return (*string)(&vt.Type) - } else if vt := u.OfSearchResultLocation; vt != nil { + } else if vt := u.OfAdaptive; vt != nil { return (*string)(&vt.Type) } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u BetaTextCitationParamUnion) GetEndBlockIndex() *int64 { - if vt := u.OfContentBlockLocation; vt != nil { - return (*int64)(&vt.EndBlockIndex) - } else if vt := u.OfSearchResultLocation; vt != nil { - return (*int64)(&vt.EndBlockIndex) - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u BetaTextCitationParamUnion) GetStartBlockIndex() *int64 { - if vt := u.OfContentBlockLocation; vt != nil { - return (*int64)(&vt.StartBlockIndex) - } else if vt := u.OfSearchResultLocation; vt != nil { - return (*int64)(&vt.StartBlockIndex) - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u BetaTextCitationParamUnion) GetTitle() *string { - if vt := u.OfWebSearchResultLocation; vt != nil && vt.Title.Valid() { - return &vt.Title.Value - } else if vt := u.OfSearchResultLocation; vt != nil && vt.Title.Valid() { - return &vt.Title.Value +func (u BetaFallbackParamThinkingUnion) GetDisplay() *string { + if vt := u.OfEnabled; vt != nil { + return (*string)(&vt.Display) + } else if vt := u.OfAdaptive; vt != nil { + return (*string)(&vt.Display) } return nil } func init() { - apijson.RegisterUnion[BetaTextCitationParamUnion]( + apijson.RegisterUnion[BetaFallbackParamThinkingUnion]( "type", - apijson.Discriminator[BetaCitationCharLocationParam]("char_location"), - apijson.Discriminator[BetaCitationPageLocationParam]("page_location"), - apijson.Discriminator[BetaCitationContentBlockLocationParam]("content_block_location"), - apijson.Discriminator[BetaCitationWebSearchResultLocationParam]("web_search_result_location"), - apijson.Discriminator[BetaCitationSearchResultLocationParam]("search_result_location"), + apijson.Discriminator[BetaThinkingConfigEnabledParam]("enabled"), + apijson.Discriminator[BetaThinkingConfigDisabledParam]("disabled"), + apijson.Discriminator[BetaThinkingConfigAdaptiveParam]("adaptive"), ) } -type BetaTextDelta struct { - Text string `json:"text" api:"required"` - Type constant.TextDelta `json:"type" default:"text_delta"` +// The `from` model declined for policy reasons. +type BetaFallbackRefusalTrigger struct { + // The policy category that triggered a refusal. + // + // Any of "cyber", "bio", "frontier_llm", "reasoning_extraction", "general_harms". + Category BetaFallbackRefusalTriggerCategory `json:"category" api:"required"` + Type constant.Refusal `json:"type" default:"refusal"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { - Text respjson.Field + Category respjson.Field Type respjson.Field ExtraFields map[string]respjson.Field raw string @@ -7254,703 +6754,529 @@ type BetaTextDelta struct { } // Returns the unmodified JSON received from the API -func (r BetaTextDelta) RawJSON() string { return r.JSON.raw } -func (r *BetaTextDelta) UnmarshalJSON(data []byte) error { +func (r BetaFallbackRefusalTrigger) RawJSON() string { return r.JSON.raw } +func (r *BetaFallbackRefusalTrigger) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type BetaTextEditorCodeExecutionCreateResultBlock struct { - IsFileUpdate bool `json:"is_file_update" api:"required"` - Type constant.TextEditorCodeExecutionCreateResult `json:"type" default:"text_editor_code_execution_create_result"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - IsFileUpdate respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} +// The policy category that triggered a refusal. +type BetaFallbackRefusalTriggerCategory string -// Returns the unmodified JSON received from the API -func (r BetaTextEditorCodeExecutionCreateResultBlock) RawJSON() string { return r.JSON.raw } -func (r *BetaTextEditorCodeExecutionCreateResultBlock) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +const ( + BetaFallbackRefusalTriggerCategoryCyber BetaFallbackRefusalTriggerCategory = "cyber" + BetaFallbackRefusalTriggerCategoryBio BetaFallbackRefusalTriggerCategory = "bio" + BetaFallbackRefusalTriggerCategoryFrontierLLM BetaFallbackRefusalTriggerCategory = "frontier_llm" + BetaFallbackRefusalTriggerCategoryReasoningExtraction BetaFallbackRefusalTriggerCategory = "reasoning_extraction" + BetaFallbackRefusalTriggerCategoryGeneralHarms BetaFallbackRefusalTriggerCategory = "general_harms" +) + +func BetaFallbacksParamOfDefault() BetaFallbacksParamUnion { + return BetaFallbacksParamUnion{OfDefault: constant.ValueOf[constant.Default]()} } -// The properties IsFileUpdate, Type are required. -type BetaTextEditorCodeExecutionCreateResultBlockParam struct { - IsFileUpdate bool `json:"is_file_update" api:"required"` - // This field can be elided, and will marshal its zero value as - // "text_editor_code_execution_create_result". - Type constant.TextEditorCodeExecutionCreateResult `json:"type" default:"text_editor_code_execution_create_result"` - paramObj +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaFallbacksParamUnion struct { + OfBetaFallbackArray []BetaFallbackParam `json:",omitzero,inline"` + // Construct this variant with constant.ValueOf[constant.Default]() + OfDefault constant.Default `json:",omitzero,inline"` + paramUnion } -func (r BetaTextEditorCodeExecutionCreateResultBlockParam) MarshalJSON() (data []byte, err error) { - type shadow BetaTextEditorCodeExecutionCreateResultBlockParam - return param.MarshalObject(r, (*shadow)(&r)) +func (u BetaFallbacksParamUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfBetaFallbackArray, u.OfDefault) } -func (r *BetaTextEditorCodeExecutionCreateResultBlockParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +func (u *BetaFallbacksParamUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) } -type BetaTextEditorCodeExecutionStrReplaceResultBlock struct { - Lines []string `json:"lines" api:"required"` - NewLines int64 `json:"new_lines" api:"required"` - NewStart int64 `json:"new_start" api:"required"` - OldLines int64 `json:"old_lines" api:"required"` - OldStart int64 `json:"old_start" api:"required"` - Type constant.TextEditorCodeExecutionStrReplaceResult `json:"type" default:"text_editor_code_execution_str_replace_result"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Lines respjson.Field - NewLines respjson.Field - NewStart respjson.Field - OldLines respjson.Field - OldStart respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r BetaTextEditorCodeExecutionStrReplaceResultBlock) RawJSON() string { return r.JSON.raw } -func (r *BetaTextEditorCodeExecutionStrReplaceResultBlock) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +func (u *BetaFallbacksParamUnion) asAny() any { + if !param.IsOmitted(u.OfBetaFallbackArray) { + return &u.OfBetaFallbackArray + } else if !param.IsOmitted(u.OfDefault) { + return &u.OfDefault + } + return nil } -// The property Type is required. -type BetaTextEditorCodeExecutionStrReplaceResultBlockParam struct { - NewLines param.Opt[int64] `json:"new_lines,omitzero"` - NewStart param.Opt[int64] `json:"new_start,omitzero"` - OldLines param.Opt[int64] `json:"old_lines,omitzero"` - OldStart param.Opt[int64] `json:"old_start,omitzero"` - Lines []string `json:"lines,omitzero"` - // This field can be elided, and will marshal its zero value as - // "text_editor_code_execution_str_replace_result". - Type constant.TextEditorCodeExecutionStrReplaceResult `json:"type" default:"text_editor_code_execution_str_replace_result"` +// The properties FileID, Type are required. +type BetaFileDocumentSourceParam struct { + FileID string `json:"file_id" api:"required"` + // This field can be elided, and will marshal its zero value as "file". + Type constant.File `json:"type" default:"file"` paramObj } -func (r BetaTextEditorCodeExecutionStrReplaceResultBlockParam) MarshalJSON() (data []byte, err error) { - type shadow BetaTextEditorCodeExecutionStrReplaceResultBlockParam +func (r BetaFileDocumentSourceParam) MarshalJSON() (data []byte, err error) { + type shadow BetaFileDocumentSourceParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *BetaTextEditorCodeExecutionStrReplaceResultBlockParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type BetaTextEditorCodeExecutionToolResultBlock struct { - Content BetaTextEditorCodeExecutionToolResultBlockContentUnion `json:"content" api:"required"` - ToolUseID string `json:"tool_use_id" api:"required"` - Type constant.TextEditorCodeExecutionToolResult `json:"type" default:"text_editor_code_execution_tool_result"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Content respjson.Field - ToolUseID respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r BetaTextEditorCodeExecutionToolResultBlock) RawJSON() string { return r.JSON.raw } -func (r *BetaTextEditorCodeExecutionToolResultBlock) UnmarshalJSON(data []byte) error { +func (r *BetaFileDocumentSourceParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// BetaTextEditorCodeExecutionToolResultBlockContentUnion contains all possible -// properties and values from [BetaTextEditorCodeExecutionToolResultError], -// [BetaTextEditorCodeExecutionViewResultBlock], -// [BetaTextEditorCodeExecutionCreateResultBlock], -// [BetaTextEditorCodeExecutionStrReplaceResultBlock]. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -type BetaTextEditorCodeExecutionToolResultBlockContentUnion struct { - // This field is from variant [BetaTextEditorCodeExecutionToolResultError]. - ErrorCode BetaTextEditorCodeExecutionToolResultErrorErrorCode `json:"error_code"` - // This field is from variant [BetaTextEditorCodeExecutionToolResultError]. - ErrorMessage string `json:"error_message"` - Type string `json:"type"` - // This field is from variant [BetaTextEditorCodeExecutionViewResultBlock]. - Content string `json:"content"` - // This field is from variant [BetaTextEditorCodeExecutionViewResultBlock]. - FileType BetaTextEditorCodeExecutionViewResultBlockFileType `json:"file_type"` - // This field is from variant [BetaTextEditorCodeExecutionViewResultBlock]. - NumLines int64 `json:"num_lines"` - // This field is from variant [BetaTextEditorCodeExecutionViewResultBlock]. - StartLine int64 `json:"start_line"` - // This field is from variant [BetaTextEditorCodeExecutionViewResultBlock]. - TotalLines int64 `json:"total_lines"` - // This field is from variant [BetaTextEditorCodeExecutionCreateResultBlock]. - IsFileUpdate bool `json:"is_file_update"` - // This field is from variant [BetaTextEditorCodeExecutionStrReplaceResultBlock]. - Lines []string `json:"lines"` - // This field is from variant [BetaTextEditorCodeExecutionStrReplaceResultBlock]. - NewLines int64 `json:"new_lines"` - // This field is from variant [BetaTextEditorCodeExecutionStrReplaceResultBlock]. - NewStart int64 `json:"new_start"` - // This field is from variant [BetaTextEditorCodeExecutionStrReplaceResultBlock]. - OldLines int64 `json:"old_lines"` - // This field is from variant [BetaTextEditorCodeExecutionStrReplaceResultBlock]. - OldStart int64 `json:"old_start"` - JSON struct { - ErrorCode respjson.Field - ErrorMessage respjson.Field - Type respjson.Field - Content respjson.Field - FileType respjson.Field - NumLines respjson.Field - StartLine respjson.Field - TotalLines respjson.Field - IsFileUpdate respjson.Field - Lines respjson.Field - NewLines respjson.Field - NewStart respjson.Field - OldLines respjson.Field - OldStart respjson.Field - raw string - } `json:"-"` -} - -func (u BetaTextEditorCodeExecutionToolResultBlockContentUnion) AsResponseTextEditorCodeExecutionToolResultError() (v BetaTextEditorCodeExecutionToolResultError) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u BetaTextEditorCodeExecutionToolResultBlockContentUnion) AsResponseTextEditorCodeExecutionViewResultBlock() (v BetaTextEditorCodeExecutionViewResultBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u BetaTextEditorCodeExecutionToolResultBlockContentUnion) AsResponseTextEditorCodeExecutionCreateResultBlock() (v BetaTextEditorCodeExecutionCreateResultBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +// The properties FileID, Type are required. +type BetaFileImageSourceParam struct { + FileID string `json:"file_id" api:"required"` + // This field can be elided, and will marshal its zero value as "file". + Type constant.File `json:"type" default:"file"` + paramObj } -func (u BetaTextEditorCodeExecutionToolResultBlockContentUnion) AsResponseTextEditorCodeExecutionStrReplaceResultBlock() (v BetaTextEditorCodeExecutionStrReplaceResultBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +func (r BetaFileImageSourceParam) MarshalJSON() (data []byte, err error) { + type shadow BetaFileImageSourceParam + return param.MarshalObject(r, (*shadow)(&r)) } - -// Returns the unmodified JSON received from the API -func (u BetaTextEditorCodeExecutionToolResultBlockContentUnion) RawJSON() string { return u.JSON.raw } - -func (r *BetaTextEditorCodeExecutionToolResultBlockContentUnion) UnmarshalJSON(data []byte) error { +func (r *BetaFileImageSourceParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The properties Content, ToolUseID, Type are required. -type BetaTextEditorCodeExecutionToolResultBlockParam struct { - Content BetaTextEditorCodeExecutionToolResultBlockParamContentUnion `json:"content,omitzero" api:"required"` - ToolUseID string `json:"tool_use_id" api:"required"` +// The properties Source, Type are required. +type BetaImageBlockParam struct { + Source BetaImageBlockParamSourceUnion `json:"source,omitzero" api:"required"` // Create a cache control breakpoint at this content block. CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` - // This field can be elided, and will marshal its zero value as - // "text_editor_code_execution_tool_result". - Type constant.TextEditorCodeExecutionToolResult `json:"type" default:"text_editor_code_execution_tool_result"` + // Configures the transformations the server applies to this image before the model + // observes it. Each key names a condition the server transforms images for; its + // value selects the transformation applied. Omitted keys keep their default + // behavior, and an empty object is equivalent to omitting the field. + Transformations BetaImageTransformationsParam `json:"transformations,omitzero"` + // This field can be elided, and will marshal its zero value as "image". + Type constant.Image `json:"type" default:"image"` paramObj } -func (r BetaTextEditorCodeExecutionToolResultBlockParam) MarshalJSON() (data []byte, err error) { - type shadow BetaTextEditorCodeExecutionToolResultBlockParam +func (r BetaImageBlockParam) MarshalJSON() (data []byte, err error) { + type shadow BetaImageBlockParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *BetaTextEditorCodeExecutionToolResultBlockParam) UnmarshalJSON(data []byte) error { +func (r *BetaImageBlockParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } // Only one field can be non-zero. // // Use [param.IsOmitted] to confirm if a field is set. -type BetaTextEditorCodeExecutionToolResultBlockParamContentUnion struct { - OfRequestTextEditorCodeExecutionToolResultError *BetaTextEditorCodeExecutionToolResultErrorParam `json:",omitzero,inline"` - OfRequestTextEditorCodeExecutionViewResultBlock *BetaTextEditorCodeExecutionViewResultBlockParam `json:",omitzero,inline"` - OfRequestTextEditorCodeExecutionCreateResultBlock *BetaTextEditorCodeExecutionCreateResultBlockParam `json:",omitzero,inline"` - OfRequestTextEditorCodeExecutionStrReplaceResultBlock *BetaTextEditorCodeExecutionStrReplaceResultBlockParam `json:",omitzero,inline"` +type BetaImageBlockParamSourceUnion struct { + OfBase64 *BetaBase64ImageSourceParam `json:",omitzero,inline"` + OfURL *BetaURLImageSourceParam `json:",omitzero,inline"` + OfFile *BetaFileImageSourceParam `json:",omitzero,inline"` paramUnion } -func (u BetaTextEditorCodeExecutionToolResultBlockParamContentUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfRequestTextEditorCodeExecutionToolResultError, u.OfRequestTextEditorCodeExecutionViewResultBlock, u.OfRequestTextEditorCodeExecutionCreateResultBlock, u.OfRequestTextEditorCodeExecutionStrReplaceResultBlock) +func (u BetaImageBlockParamSourceUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfBase64, u.OfURL, u.OfFile) } -func (u *BetaTextEditorCodeExecutionToolResultBlockParamContentUnion) UnmarshalJSON(data []byte) error { +func (u *BetaImageBlockParamSourceUnion) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, u) } -func (u *BetaTextEditorCodeExecutionToolResultBlockParamContentUnion) asAny() any { - if !param.IsOmitted(u.OfRequestTextEditorCodeExecutionToolResultError) { - return u.OfRequestTextEditorCodeExecutionToolResultError - } else if !param.IsOmitted(u.OfRequestTextEditorCodeExecutionViewResultBlock) { - return u.OfRequestTextEditorCodeExecutionViewResultBlock - } else if !param.IsOmitted(u.OfRequestTextEditorCodeExecutionCreateResultBlock) { - return u.OfRequestTextEditorCodeExecutionCreateResultBlock - } else if !param.IsOmitted(u.OfRequestTextEditorCodeExecutionStrReplaceResultBlock) { - return u.OfRequestTextEditorCodeExecutionStrReplaceResultBlock +func (u *BetaImageBlockParamSourceUnion) asAny() any { + if !param.IsOmitted(u.OfBase64) { + return u.OfBase64 + } else if !param.IsOmitted(u.OfURL) { + return u.OfURL + } else if !param.IsOmitted(u.OfFile) { + return u.OfFile } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u BetaTextEditorCodeExecutionToolResultBlockParamContentUnion) GetErrorCode() *string { - if vt := u.OfRequestTextEditorCodeExecutionToolResultError; vt != nil { - return (*string)(&vt.ErrorCode) +func (u BetaImageBlockParamSourceUnion) GetData() *string { + if vt := u.OfBase64; vt != nil { + return &vt.Data } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u BetaTextEditorCodeExecutionToolResultBlockParamContentUnion) GetErrorMessage() *string { - if vt := u.OfRequestTextEditorCodeExecutionToolResultError; vt != nil && vt.ErrorMessage.Valid() { - return &vt.ErrorMessage.Value +func (u BetaImageBlockParamSourceUnion) GetMediaType() *string { + if vt := u.OfBase64; vt != nil { + return (*string)(&vt.MediaType) } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u BetaTextEditorCodeExecutionToolResultBlockParamContentUnion) GetContent() *string { - if vt := u.OfRequestTextEditorCodeExecutionViewResultBlock; vt != nil { - return &vt.Content +func (u BetaImageBlockParamSourceUnion) GetURL() *string { + if vt := u.OfURL; vt != nil { + return &vt.URL } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u BetaTextEditorCodeExecutionToolResultBlockParamContentUnion) GetFileType() *string { - if vt := u.OfRequestTextEditorCodeExecutionViewResultBlock; vt != nil { - return (*string)(&vt.FileType) +func (u BetaImageBlockParamSourceUnion) GetFileID() *string { + if vt := u.OfFile; vt != nil { + return &vt.FileID } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u BetaTextEditorCodeExecutionToolResultBlockParamContentUnion) GetNumLines() *int64 { - if vt := u.OfRequestTextEditorCodeExecutionViewResultBlock; vt != nil && vt.NumLines.Valid() { - return &vt.NumLines.Value +func (u BetaImageBlockParamSourceUnion) GetType() *string { + if vt := u.OfBase64; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfURL; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfFile; vt != nil { + return (*string)(&vt.Type) } return nil } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaTextEditorCodeExecutionToolResultBlockParamContentUnion) GetStartLine() *int64 { - if vt := u.OfRequestTextEditorCodeExecutionViewResultBlock; vt != nil && vt.StartLine.Valid() { - return &vt.StartLine.Value - } - return nil +func init() { + apijson.RegisterUnion[BetaImageBlockParamSourceUnion]( + "type", + apijson.Discriminator[BetaBase64ImageSourceParam]("base64"), + apijson.Discriminator[BetaURLImageSourceParam]("url"), + apijson.Discriminator[BetaFileImageSourceParam]("file"), + ) } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaTextEditorCodeExecutionToolResultBlockParamContentUnion) GetTotalLines() *int64 { - if vt := u.OfRequestTextEditorCodeExecutionViewResultBlock; vt != nil && vt.TotalLines.Valid() { - return &vt.TotalLines.Value - } - return nil +// Configures the transformations the server applies to this image before the model +// observes it. Each key names a condition the server transforms images for; its +// value selects the transformation applied. Omitted keys keep their default +// behavior, and an empty object is equivalent to omitting the field. +type BetaImageTransformationsParam struct { + // What the server does when this image exceeds the model's maximum image size. + // `"downsize"` (the default) scales the image down to fit, which changes the + // dimensions the model observes without telling you. `"error"` instead rejects the + // request with a 400 error naming the image's dimensions and the largest + // dimensions that fit, so you can scale the image deliberately — your image is + // never silently scaled down. + // + // Any of "downsize", "error". + OversizedImage BetaImageTransformationsParamOversizedImage `json:"oversized_image,omitzero"` + paramObj } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaTextEditorCodeExecutionToolResultBlockParamContentUnion) GetIsFileUpdate() *bool { - if vt := u.OfRequestTextEditorCodeExecutionCreateResultBlock; vt != nil { - return &vt.IsFileUpdate - } - return nil +func (r BetaImageTransformationsParam) MarshalJSON() (data []byte, err error) { + type shadow BetaImageTransformationsParam + return param.MarshalObject(r, (*shadow)(&r)) } - -// Returns a pointer to the underlying variant's property, if present. -func (u BetaTextEditorCodeExecutionToolResultBlockParamContentUnion) GetLines() []string { - if vt := u.OfRequestTextEditorCodeExecutionStrReplaceResultBlock; vt != nil { - return vt.Lines - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u BetaTextEditorCodeExecutionToolResultBlockParamContentUnion) GetNewLines() *int64 { - if vt := u.OfRequestTextEditorCodeExecutionStrReplaceResultBlock; vt != nil && vt.NewLines.Valid() { - return &vt.NewLines.Value - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u BetaTextEditorCodeExecutionToolResultBlockParamContentUnion) GetNewStart() *int64 { - if vt := u.OfRequestTextEditorCodeExecutionStrReplaceResultBlock; vt != nil && vt.NewStart.Valid() { - return &vt.NewStart.Value - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u BetaTextEditorCodeExecutionToolResultBlockParamContentUnion) GetOldLines() *int64 { - if vt := u.OfRequestTextEditorCodeExecutionStrReplaceResultBlock; vt != nil && vt.OldLines.Valid() { - return &vt.OldLines.Value - } - return nil +func (r *BetaImageTransformationsParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaTextEditorCodeExecutionToolResultBlockParamContentUnion) GetOldStart() *int64 { - if vt := u.OfRequestTextEditorCodeExecutionStrReplaceResultBlock; vt != nil && vt.OldStart.Valid() { - return &vt.OldStart.Value - } - return nil -} +// What the server does when this image exceeds the model's maximum image size. +// `"downsize"` (the default) scales the image down to fit, which changes the +// dimensions the model observes without telling you. `"error"` instead rejects the +// request with a 400 error naming the image's dimensions and the largest +// dimensions that fit, so you can scale the image deliberately — your image is +// never silently scaled down. +type BetaImageTransformationsParamOversizedImage string -// Returns a pointer to the underlying variant's property, if present. -func (u BetaTextEditorCodeExecutionToolResultBlockParamContentUnion) GetType() *string { - if vt := u.OfRequestTextEditorCodeExecutionToolResultError; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfRequestTextEditorCodeExecutionViewResultBlock; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfRequestTextEditorCodeExecutionCreateResultBlock; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfRequestTextEditorCodeExecutionStrReplaceResultBlock; vt != nil { - return (*string)(&vt.Type) - } - return nil -} +const ( + BetaImageTransformationsParamOversizedImageDownsize BetaImageTransformationsParamOversizedImage = "downsize" + BetaImageTransformationsParamOversizedImageError BetaImageTransformationsParamOversizedImage = "error" +) -type BetaTextEditorCodeExecutionToolResultError struct { - // Any of "invalid_tool_input", "unavailable", "too_many_requests", - // "execution_time_exceeded", "file_not_found". - ErrorCode BetaTextEditorCodeExecutionToolResultErrorErrorCode `json:"error_code" api:"required"` - ErrorMessage string `json:"error_message" api:"required"` - Type constant.TextEditorCodeExecutionToolResultError `json:"type" default:"text_editor_code_execution_tool_result_error"` +type BetaInputJSONDelta struct { + PartialJSON string `json:"partial_json" api:"required"` + Type constant.InputJSONDelta `json:"type" default:"input_json_delta"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { - ErrorCode respjson.Field - ErrorMessage respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string + PartialJSON respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string } `json:"-"` } // Returns the unmodified JSON received from the API -func (r BetaTextEditorCodeExecutionToolResultError) RawJSON() string { return r.JSON.raw } -func (r *BetaTextEditorCodeExecutionToolResultError) UnmarshalJSON(data []byte) error { +func (r BetaInputJSONDelta) RawJSON() string { return r.JSON.raw } +func (r *BetaInputJSONDelta) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type BetaTextEditorCodeExecutionToolResultErrorErrorCode string +// The properties Type, Value are required. +type BetaInputTokensClearAtLeastParam struct { + Value int64 `json:"value" api:"required"` + // This field can be elided, and will marshal its zero value as "input_tokens". + Type constant.InputTokens `json:"type" default:"input_tokens"` + paramObj +} -const ( - BetaTextEditorCodeExecutionToolResultErrorErrorCodeInvalidToolInput BetaTextEditorCodeExecutionToolResultErrorErrorCode = "invalid_tool_input" - BetaTextEditorCodeExecutionToolResultErrorErrorCodeUnavailable BetaTextEditorCodeExecutionToolResultErrorErrorCode = "unavailable" - BetaTextEditorCodeExecutionToolResultErrorErrorCodeTooManyRequests BetaTextEditorCodeExecutionToolResultErrorErrorCode = "too_many_requests" - BetaTextEditorCodeExecutionToolResultErrorErrorCodeExecutionTimeExceeded BetaTextEditorCodeExecutionToolResultErrorErrorCode = "execution_time_exceeded" - BetaTextEditorCodeExecutionToolResultErrorErrorCodeFileNotFound BetaTextEditorCodeExecutionToolResultErrorErrorCode = "file_not_found" -) +func (r BetaInputTokensClearAtLeastParam) MarshalJSON() (data []byte, err error) { + type shadow BetaInputTokensClearAtLeastParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaInputTokensClearAtLeastParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} -// The properties ErrorCode, Type are required. -type BetaTextEditorCodeExecutionToolResultErrorParam struct { - // Any of "invalid_tool_input", "unavailable", "too_many_requests", - // "execution_time_exceeded", "file_not_found". - ErrorCode BetaTextEditorCodeExecutionToolResultErrorParamErrorCode `json:"error_code,omitzero" api:"required"` - ErrorMessage param.Opt[string] `json:"error_message,omitzero"` - // This field can be elided, and will marshal its zero value as - // "text_editor_code_execution_tool_result_error". - Type constant.TextEditorCodeExecutionToolResultError `json:"type" default:"text_editor_code_execution_tool_result_error"` +// The properties Type, Value are required. +type BetaInputTokensTriggerParam struct { + Value int64 `json:"value" api:"required"` + // This field can be elided, and will marshal its zero value as "input_tokens". + Type constant.InputTokens `json:"type" default:"input_tokens"` paramObj } -func (r BetaTextEditorCodeExecutionToolResultErrorParam) MarshalJSON() (data []byte, err error) { - type shadow BetaTextEditorCodeExecutionToolResultErrorParam +func (r BetaInputTokensTriggerParam) MarshalJSON() (data []byte, err error) { + type shadow BetaInputTokensTriggerParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *BetaTextEditorCodeExecutionToolResultErrorParam) UnmarshalJSON(data []byte) error { +func (r *BetaInputTokensTriggerParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type BetaTextEditorCodeExecutionToolResultErrorParamErrorCode string - -const ( - BetaTextEditorCodeExecutionToolResultErrorParamErrorCodeInvalidToolInput BetaTextEditorCodeExecutionToolResultErrorParamErrorCode = "invalid_tool_input" - BetaTextEditorCodeExecutionToolResultErrorParamErrorCodeUnavailable BetaTextEditorCodeExecutionToolResultErrorParamErrorCode = "unavailable" - BetaTextEditorCodeExecutionToolResultErrorParamErrorCodeTooManyRequests BetaTextEditorCodeExecutionToolResultErrorParamErrorCode = "too_many_requests" - BetaTextEditorCodeExecutionToolResultErrorParamErrorCodeExecutionTimeExceeded BetaTextEditorCodeExecutionToolResultErrorParamErrorCode = "execution_time_exceeded" - BetaTextEditorCodeExecutionToolResultErrorParamErrorCodeFileNotFound BetaTextEditorCodeExecutionToolResultErrorParamErrorCode = "file_not_found" -) +type BetaIterationsUsage []BetaIterationsUsageItemUnion -type BetaTextEditorCodeExecutionViewResultBlock struct { - Content string `json:"content" api:"required"` - // Any of "text", "image", "pdf". - FileType BetaTextEditorCodeExecutionViewResultBlockFileType `json:"file_type" api:"required"` - NumLines int64 `json:"num_lines" api:"required"` - StartLine int64 `json:"start_line" api:"required"` - TotalLines int64 `json:"total_lines" api:"required"` - Type constant.TextEditorCodeExecutionViewResult `json:"type" default:"text_editor_code_execution_view_result"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. +// BetaIterationsUsageItemUnion contains all possible properties and values from +// [BetaMessageIterationUsage], [BetaCompactionIterationUsage], +// [BetaAdvisorMessageIterationUsage], [BetaFallbackMessageIterationUsage]. +// +// Use the [BetaIterationsUsageItemUnion.AsAny] method to switch on the variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaIterationsUsageItemUnion struct { + // This field is from variant [BetaMessageIterationUsage]. + CacheCreation BetaCacheCreation `json:"cache_creation"` + CacheCreationInputTokens int64 `json:"cache_creation_input_tokens"` + CacheReadInputTokens int64 `json:"cache_read_input_tokens"` + InputTokens int64 `json:"input_tokens"` + // This field is from variant [BetaMessageIterationUsage]. + Model Model `json:"model"` + OutputTokens int64 `json:"output_tokens"` + // Any of "message", "compaction", "advisor_message", "fallback_message". + Type string `json:"type"` JSON struct { - Content respjson.Field - FileType respjson.Field - NumLines respjson.Field - StartLine respjson.Field - TotalLines respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string + CacheCreation respjson.Field + CacheCreationInputTokens respjson.Field + CacheReadInputTokens respjson.Field + InputTokens respjson.Field + Model respjson.Field + OutputTokens respjson.Field + Type respjson.Field + raw string } `json:"-"` } -// Returns the unmodified JSON received from the API -func (r BetaTextEditorCodeExecutionViewResultBlock) RawJSON() string { return r.JSON.raw } -func (r *BetaTextEditorCodeExecutionViewResultBlock) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +// anyBetaIterationsUsageItem is implemented by each variant of +// [BetaIterationsUsageItemUnion] to add type safety for the return type of +// [BetaIterationsUsageItemUnion.AsAny] +type anyBetaIterationsUsageItem interface { + implBetaIterationsUsageItemUnion() } -type BetaTextEditorCodeExecutionViewResultBlockFileType string - -const ( - BetaTextEditorCodeExecutionViewResultBlockFileTypeText BetaTextEditorCodeExecutionViewResultBlockFileType = "text" - BetaTextEditorCodeExecutionViewResultBlockFileTypeImage BetaTextEditorCodeExecutionViewResultBlockFileType = "image" - BetaTextEditorCodeExecutionViewResultBlockFileTypePDF BetaTextEditorCodeExecutionViewResultBlockFileType = "pdf" -) +func (BetaMessageIterationUsage) implBetaIterationsUsageItemUnion() {} +func (BetaCompactionIterationUsage) implBetaIterationsUsageItemUnion() {} +func (BetaAdvisorMessageIterationUsage) implBetaIterationsUsageItemUnion() {} +func (BetaFallbackMessageIterationUsage) implBetaIterationsUsageItemUnion() {} -// The properties Content, FileType, Type are required. -type BetaTextEditorCodeExecutionViewResultBlockParam struct { - Content string `json:"content" api:"required"` - // Any of "text", "image", "pdf". - FileType BetaTextEditorCodeExecutionViewResultBlockParamFileType `json:"file_type,omitzero" api:"required"` - NumLines param.Opt[int64] `json:"num_lines,omitzero"` - StartLine param.Opt[int64] `json:"start_line,omitzero"` - TotalLines param.Opt[int64] `json:"total_lines,omitzero"` - // This field can be elided, and will marshal its zero value as - // "text_editor_code_execution_view_result". - Type constant.TextEditorCodeExecutionViewResult `json:"type" default:"text_editor_code_execution_view_result"` - paramObj +// Use the following switch statement to find the correct variant +// +// switch variant := BetaIterationsUsageItemUnion.AsAny().(type) { +// case anthropic.BetaMessageIterationUsage: +// case anthropic.BetaCompactionIterationUsage: +// case anthropic.BetaAdvisorMessageIterationUsage: +// case anthropic.BetaFallbackMessageIterationUsage: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaIterationsUsageItemUnion) AsAny() anyBetaIterationsUsageItem { + switch u.Type { + case "message": + return u.AsMessage() + case "compaction": + return u.AsCompaction() + case "advisor_message": + return u.AsAdvisorMessage() + case "fallback_message": + return u.AsFallbackMessage() + } + return nil } -func (r BetaTextEditorCodeExecutionViewResultBlockParam) MarshalJSON() (data []byte, err error) { - type shadow BetaTextEditorCodeExecutionViewResultBlockParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaTextEditorCodeExecutionViewResultBlockParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +func (u BetaIterationsUsageItemUnion) AsMessage() (v BetaMessageIterationUsage) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -type BetaTextEditorCodeExecutionViewResultBlockParamFileType string +func (u BetaIterationsUsageItemUnion) AsCompaction() (v BetaCompactionIterationUsage) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} -const ( - BetaTextEditorCodeExecutionViewResultBlockParamFileTypeText BetaTextEditorCodeExecutionViewResultBlockParamFileType = "text" - BetaTextEditorCodeExecutionViewResultBlockParamFileTypeImage BetaTextEditorCodeExecutionViewResultBlockParamFileType = "image" - BetaTextEditorCodeExecutionViewResultBlockParamFileTypePDF BetaTextEditorCodeExecutionViewResultBlockParamFileType = "pdf" -) +func (u BetaIterationsUsageItemUnion) AsAdvisorMessage() (v BetaAdvisorMessageIterationUsage) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} -type BetaThinkingBlock struct { - Signature string `json:"signature" api:"required"` - Thinking string `json:"thinking" api:"required"` - Type constant.Thinking `json:"type" default:"thinking"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Signature respjson.Field - Thinking respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +func (u BetaIterationsUsageItemUnion) AsFallbackMessage() (v BetaFallbackMessageIterationUsage) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } // Returns the unmodified JSON received from the API -func (r BetaThinkingBlock) RawJSON() string { return r.JSON.raw } -func (r *BetaThinkingBlock) UnmarshalJSON(data []byte) error { +func (u BetaIterationsUsageItemUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaIterationsUsageItemUnion) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The properties Signature, Thinking, Type are required. -type BetaThinkingBlockParam struct { - Signature string `json:"signature" api:"required"` - Thinking string `json:"thinking" api:"required"` - // This field can be elided, and will marshal its zero value as "thinking". - Type constant.Thinking `json:"type" default:"thinking"` +// BetaJSONOutputFormatParam configures JSON structured output for a message request. +// The preferred usage is to pass a pointer to a Go struct as Schema. The SDK will +// auto-generate the JSON schema on the wire and auto-parse the response back into +// the struct after the request completes: +// +// var result MyStruct +// msg, _ := client.Beta.Messages.New(ctx, anthropic.BetaMessageNewParams{ +// OutputFormat: anthropic.BetaJSONOutputFormatParam{Schema: &result}, +// ... +// }) +// +// For streaming, call ParseOutput after accumulating the message: +// +// msg.ParseOutput(&result) +// +// The properties Schema, Type are required. +type BetaJSONOutputFormatParam struct { + // The JSON schema of the format. + // + // This can be a map[string]any, json.RawMessage, or a pointer to a Go struct. + // When a struct pointer is provided, the SDK automatically generates the JSON + // schema on the wire and can auto-parse the response back into the struct. + // A struct pointer is preferred over map[string]any because it provides + // auto-parsing and type safety. If you already have a JSON schema as bytes, + // use json.RawMessage to avoid unnecessary marshaling overhead. + // + // Set the schema on either BetaMessageNewParams.OutputFormat or + // BetaMessageNewParams.OutputConfig.Format, not both. If both carry a struct + // pointer, OutputFormat wins for auto-parse. + Schema any `json:"schema,omitzero" api:"required"` + // This field can be elided, and will marshal its zero value as "json_schema". + Type constant.JSONSchema `json:"type" default:"json_schema"` paramObj } -func (r BetaThinkingBlockParam) MarshalJSON() (data []byte, err error) { - type shadow BetaThinkingBlockParam +func (r BetaJSONOutputFormatParam) MarshalJSON() (data []byte, err error) { + // Convert struct pointers and maps to json.RawMessage so the wire + // payload contains a JSON schema, not the struct's field values. + // Value receiver keeps the caller's Schema intact for auto-parse. + if r.Schema != nil { + raw, e := schemaToRaw(r.Schema) + if e != nil { + return nil, e + } + if raw != nil { + r.Schema = raw + } + } + type shadow BetaJSONOutputFormatParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *BetaThinkingBlockParam) UnmarshalJSON(data []byte) error { +func (r *BetaJSONOutputFormatParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The property Type is required. -type BetaThinkingConfigAdaptiveParam struct { - // Controls how thinking content appears in the response. When set to `summarized`, - // thinking is returned normally. When set to `omitted`, thinking content is - // redacted but a signature is returned for multi-turn continuity. Defaults to - // `summarized`. - // - // Any of "summarized", "omitted". - Display BetaThinkingConfigAdaptiveDisplay `json:"display,omitzero"` - // This field can be elided, and will marshal its zero value as "adaptive". - Type constant.Adaptive `json:"type" default:"adaptive"` +// Configuration for a specific tool in an MCP toolset. +type BetaMCPToolConfigParam struct { + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + Enabled param.Opt[bool] `json:"enabled,omitzero"` paramObj } -func (r BetaThinkingConfigAdaptiveParam) MarshalJSON() (data []byte, err error) { - type shadow BetaThinkingConfigAdaptiveParam +func (r BetaMCPToolConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaMCPToolConfigParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *BetaThinkingConfigAdaptiveParam) UnmarshalJSON(data []byte) error { +func (r *BetaMCPToolConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// Controls how thinking content appears in the response. When set to `summarized`, -// thinking is returned normally. When set to `omitted`, thinking content is -// redacted but a signature is returned for multi-turn continuity. Defaults to -// `summarized`. -type BetaThinkingConfigAdaptiveDisplay string - -const ( - BetaThinkingConfigAdaptiveDisplaySummarized BetaThinkingConfigAdaptiveDisplay = "summarized" - BetaThinkingConfigAdaptiveDisplayOmitted BetaThinkingConfigAdaptiveDisplay = "omitted" -) - -func NewBetaThinkingConfigDisabledParam() BetaThinkingConfigDisabledParam { - return BetaThinkingConfigDisabledParam{ - Type: "disabled", - } -} - -// This struct has a constant value, construct it with -// [NewBetaThinkingConfigDisabledParam]. -type BetaThinkingConfigDisabledParam struct { - Type constant.Disabled `json:"type" default:"disabled"` +// Default configuration for tools in an MCP toolset. +type BetaMCPToolDefaultConfigParam struct { + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + Enabled param.Opt[bool] `json:"enabled,omitzero"` paramObj } -func (r BetaThinkingConfigDisabledParam) MarshalJSON() (data []byte, err error) { - type shadow BetaThinkingConfigDisabledParam +func (r BetaMCPToolDefaultConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaMCPToolDefaultConfigParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *BetaThinkingConfigDisabledParam) UnmarshalJSON(data []byte) error { +func (r *BetaMCPToolDefaultConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The properties BudgetTokens, Type are required. -type BetaThinkingConfigEnabledParam struct { - // Determines how many tokens Claude can use for its internal reasoning process. - // Larger budgets can enable more thorough analysis for complex problems, improving - // response quality. - // - // Must be ≥1024 and less than `max_tokens`. - // - // See - // [extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking) - // for details. - BudgetTokens int64 `json:"budget_tokens" api:"required"` - // Controls how thinking content appears in the response. When set to `summarized`, - // thinking is returned normally. When set to `omitted`, thinking content is - // redacted but a signature is returned for multi-turn continuity. Defaults to - // `summarized`. - // - // Any of "summarized", "omitted". - Display BetaThinkingConfigEnabledDisplay `json:"display,omitzero"` - // This field can be elided, and will marshal its zero value as "enabled". - Type constant.Enabled `json:"type" default:"enabled"` - paramObj +type BetaMCPToolResultBlock struct { + Content BetaMCPToolResultBlockContentUnion `json:"content" api:"required"` + IsError bool `json:"is_error" api:"required"` + ToolUseID string `json:"tool_use_id" api:"required"` + Type constant.MCPToolResult `json:"type" default:"mcp_tool_result"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Content respjson.Field + IsError respjson.Field + ToolUseID respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` } -func (r BetaThinkingConfigEnabledParam) MarshalJSON() (data []byte, err error) { - type shadow BetaThinkingConfigEnabledParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaThinkingConfigEnabledParam) UnmarshalJSON(data []byte) error { +// Returns the unmodified JSON received from the API +func (r BetaMCPToolResultBlock) RawJSON() string { return r.JSON.raw } +func (r *BetaMCPToolResultBlock) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// Controls how thinking content appears in the response. When set to `summarized`, -// thinking is returned normally. When set to `omitted`, thinking content is -// redacted but a signature is returned for multi-turn continuity. Defaults to -// `summarized`. -type BetaThinkingConfigEnabledDisplay string - -const ( - BetaThinkingConfigEnabledDisplaySummarized BetaThinkingConfigEnabledDisplay = "summarized" - BetaThinkingConfigEnabledDisplayOmitted BetaThinkingConfigEnabledDisplay = "omitted" -) - -func BetaThinkingConfigParamOfEnabled(budgetTokens int64) BetaThinkingConfigParamUnion { - var enabled BetaThinkingConfigEnabledParam - enabled.BudgetTokens = budgetTokens - return BetaThinkingConfigParamUnion{OfEnabled: &enabled} -} - -// Only one field can be non-zero. +// BetaMCPToolResultBlockContentUnion contains all possible properties and values +// from [string], [[]BetaTextBlock]. // -// Use [param.IsOmitted] to confirm if a field is set. -type BetaThinkingConfigParamUnion struct { - OfEnabled *BetaThinkingConfigEnabledParam `json:",omitzero,inline"` - OfDisabled *BetaThinkingConfigDisabledParam `json:",omitzero,inline"` - OfAdaptive *BetaThinkingConfigAdaptiveParam `json:",omitzero,inline"` - paramUnion -} - -func (u BetaThinkingConfigParamUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfEnabled, u.OfDisabled, u.OfAdaptive) -} -func (u *BetaThinkingConfigParamUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *BetaThinkingConfigParamUnion) asAny() any { - if !param.IsOmitted(u.OfEnabled) { - return u.OfEnabled - } else if !param.IsOmitted(u.OfDisabled) { - return u.OfDisabled - } else if !param.IsOmitted(u.OfAdaptive) { - return u.OfAdaptive - } - return nil +// Use the methods beginning with 'As' to cast the union to one of its variants. +// +// If the underlying value is not a json object, one of the following properties +// will be valid: OfString OfBetaMCPToolResultBlockContent] +type BetaMCPToolResultBlockContentUnion struct { + // This field will be present if the value is a [string] instead of an object. + OfString string `json:",inline"` + // This field will be present if the value is a [[]BetaTextBlock] instead of an + // object. + OfBetaMCPToolResultBlockContent []BetaTextBlock `json:",inline"` + JSON struct { + OfString respjson.Field + OfBetaMCPToolResultBlockContent respjson.Field + raw string + } `json:"-"` } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaThinkingConfigParamUnion) GetBudgetTokens() *int64 { - if vt := u.OfEnabled; vt != nil { - return &vt.BudgetTokens - } - return nil +func (u BetaMCPToolResultBlockContentUnion) AsString() (v string) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaThinkingConfigParamUnion) GetType() *string { - if vt := u.OfEnabled; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfDisabled; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfAdaptive; vt != nil { - return (*string)(&vt.Type) - } - return nil +func (u BetaMCPToolResultBlockContentUnion) AsBetaMCPToolResultBlockContent() (v []BetaTextBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaThinkingConfigParamUnion) GetDisplay() *string { - if vt := u.OfEnabled; vt != nil { - return (*string)(&vt.Display) - } else if vt := u.OfAdaptive; vt != nil { - return (*string)(&vt.Display) - } - return nil -} +// Returns the unmodified JSON received from the API +func (u BetaMCPToolResultBlockContentUnion) RawJSON() string { return u.JSON.raw } -func init() { - apijson.RegisterUnion[BetaThinkingConfigParamUnion]( - "type", - apijson.Discriminator[BetaThinkingConfigEnabledParam]("enabled"), - apijson.Discriminator[BetaThinkingConfigDisabledParam]("disabled"), - apijson.Discriminator[BetaThinkingConfigAdaptiveParam]("adaptive"), - ) +func (r *BetaMCPToolResultBlockContentUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -type BetaThinkingDelta struct { - Thinking string `json:"thinking" api:"required"` - Type constant.ThinkingDelta `json:"type" default:"thinking_delta"` +type BetaMCPToolUseBlock struct { + ID string `json:"id" api:"required"` + Input any `json:"input" api:"required"` + // The name of the MCP tool + Name string `json:"name" api:"required"` + // The name of the MCP server + ServerName string `json:"server_name" api:"required"` + Type constant.MCPToolUse `json:"type" default:"mcp_tool_use"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { - Thinking respjson.Field + ID respjson.Field + Input respjson.Field + Name respjson.Field + ServerName respjson.Field Type respjson.Field ExtraFields map[string]respjson.Field raw string @@ -7958,2570 +7284,2400 @@ type BetaThinkingDelta struct { } // Returns the unmodified JSON received from the API -func (r BetaThinkingDelta) RawJSON() string { return r.JSON.raw } -func (r *BetaThinkingDelta) UnmarshalJSON(data []byte) error { +func (r BetaMCPToolUseBlock) RawJSON() string { return r.JSON.raw } +func (r *BetaMCPToolUseBlock) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The properties Type, Value are required. -type BetaThinkingTurnsParam struct { - Value int64 `json:"value" api:"required"` - // This field can be elided, and will marshal its zero value as "thinking_turns". - Type constant.ThinkingTurns `json:"type" default:"thinking_turns"` +// The properties ID, Input, Name, ServerName, Type are required. +type BetaMCPToolUseBlockParam struct { + ID string `json:"id" api:"required"` + Input any `json:"input,omitzero" api:"required"` + Name string `json:"name" api:"required"` + // The name of the MCP server + ServerName string `json:"server_name" api:"required"` + // Create a cache control breakpoint at this content block. + CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` + // This field can be elided, and will marshal its zero value as "mcp_tool_use". + Type constant.MCPToolUse `json:"type" default:"mcp_tool_use"` paramObj } -func (r BetaThinkingTurnsParam) MarshalJSON() (data []byte, err error) { - type shadow BetaThinkingTurnsParam +func (r BetaMCPToolUseBlockParam) MarshalJSON() (data []byte, err error) { + type shadow BetaMCPToolUseBlockParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *BetaThinkingTurnsParam) UnmarshalJSON(data []byte) error { +func (r *BetaMCPToolUseBlockParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// User-configurable total token budget across contexts. +// Configuration for a group of tools from an MCP server. // -// The properties Total, Type are required. -type BetaTokenTaskBudgetParam struct { - // Total token budget across all contexts in the session. - Total int64 `json:"total" api:"required"` - // Remaining tokens in the budget. Use this to track usage across contexts when - // implementing compaction client-side. Defaults to total if not provided. - Remaining param.Opt[int64] `json:"remaining,omitzero"` - // The budget type. Currently only 'tokens' is supported. - // - // This field can be elided, and will marshal its zero value as "tokens". - Type constant.Tokens `json:"type" default:"tokens"` +// Allows configuring enabled status and defer_loading for all tools from an MCP +// server, with optional per-tool overrides. +// +// The properties MCPServerName, Type are required. +type BetaMCPToolsetParam struct { + // Name of the MCP server to configure tools for + MCPServerName string `json:"mcp_server_name" api:"required"` + // Configuration overrides for specific tools, keyed by tool name + Configs map[string]BetaMCPToolConfigParam `json:"configs,omitzero"` + // Create a cache control breakpoint at this content block. + CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` + // Default configuration applied to all tools from this server + DefaultConfig BetaMCPToolDefaultConfigParam `json:"default_config,omitzero"` + // This field can be elided, and will marshal its zero value as "mcp_toolset". + Type constant.MCPToolset `json:"type" default:"mcp_toolset"` paramObj } -func (r BetaTokenTaskBudgetParam) MarshalJSON() (data []byte, err error) { - type shadow BetaTokenTaskBudgetParam +func (r BetaMCPToolsetParam) MarshalJSON() (data []byte, err error) { + type shadow BetaMCPToolsetParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *BetaTokenTaskBudgetParam) UnmarshalJSON(data []byte) error { +func (r *BetaMCPToolsetParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The properties InputSchema, Name are required. -type BetaToolParam struct { - // [JSON schema](https://json-schema.org/draft/2020-12) for this tool's input. - // - // This defines the shape of the `input` that your tool accepts and that the model - // will produce. - InputSchema BetaToolInputSchemaParam `json:"input_schema,omitzero" api:"required"` - // Name of the tool. - // - // This is how the tool will be called by the model and in `tool_use` blocks. - Name string `json:"name" api:"required"` - // Enable eager input streaming for this tool. When true, tool input parameters - // will be streamed incrementally as they are generated, and types will be inferred - // on-the-fly rather than buffering the full JSON output. When false, streaming is - // disabled for this tool even if the fine-grained-tool-streaming beta is active. - // When null (default), uses the default behavior based on beta headers. - EagerInputStreaming param.Opt[bool] `json:"eager_input_streaming,omitzero"` +// The properties Name, Type are required. +type BetaMemoryTool20250818Param struct { // If true, tool will not be included in initial system prompt. Only loaded when // returned via tool_reference from tool search. DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` - // Description of what this tool does. - // - // Tool descriptions should be as detailed as possible. The more information that - // the model has about what the tool is and how to use it, the better it will - // perform. You can use natural language descriptions to reinforce important - // aspects of the tool input JSON schema. - Description param.Opt[string] `json:"description,omitzero"` // When true, guarantees schema validation on tool names and inputs Strict param.Opt[bool] `json:"strict,omitzero"` - // Any of "custom". - Type BetaToolType `json:"type,omitzero"` - // Any of "direct", "code_execution_20250825", "code_execution_20260120". + // Any of "direct", "code_execution_20250825", "code_execution_20260120", + // "code_execution_20260521". AllowedCallers []string `json:"allowed_callers,omitzero"` // Create a cache control breakpoint at this content block. CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` InputExamples []map[string]any `json:"input_examples,omitzero"` + // Name of the tool. + // + // This is how the tool will be called by the model and in `tool_use` blocks. + // + // This field can be elided, and will marshal its zero value as "memory". + Name constant.Memory `json:"name" default:"memory"` + // This field can be elided, and will marshal its zero value as "memory_20250818". + Type constant.Memory20250818 `json:"type" default:"memory_20250818"` paramObj } -func (r BetaToolParam) MarshalJSON() (data []byte, err error) { - type shadow BetaToolParam +func (r BetaMemoryTool20250818Param) MarshalJSON() (data []byte, err error) { + type shadow BetaMemoryTool20250818Param return param.MarshalObject(r, (*shadow)(&r)) } -func (r *BetaToolParam) UnmarshalJSON(data []byte) error { +func (r *BetaMemoryTool20250818Param) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// [JSON schema](https://json-schema.org/draft/2020-12) for this tool's input. +// BetaMemoryTool20250818CommandUnion contains all possible properties and values +// from [BetaMemoryTool20250818ViewCommand], [BetaMemoryTool20250818CreateCommand], +// [BetaMemoryTool20250818StrReplaceCommand], +// [BetaMemoryTool20250818InsertCommand], [BetaMemoryTool20250818DeleteCommand], +// [BetaMemoryTool20250818RenameCommand]. // -// This defines the shape of the `input` that your tool accepts and that the model -// will produce. +// Use the [BetaMemoryTool20250818CommandUnion.AsAny] method to switch on the +// variant. // -// The property Type is required. -type BetaToolInputSchemaParam struct { - Properties any `json:"properties,omitzero"` - Required []string `json:"required,omitzero"` - // This field can be elided, and will marshal its zero value as "object". - Type constant.Object `json:"type" default:"object"` - ExtraFields map[string]any `json:"-"` - paramObj +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaMemoryTool20250818CommandUnion struct { + // Any of "view", "create", "str_replace", "insert", "delete", "rename". + Command string `json:"command"` + Path string `json:"path"` + // This field is from variant [BetaMemoryTool20250818ViewCommand]. + ViewRange []int64 `json:"view_range"` + // This field is from variant [BetaMemoryTool20250818CreateCommand]. + FileText string `json:"file_text"` + // This field is from variant [BetaMemoryTool20250818StrReplaceCommand]. + NewStr string `json:"new_str"` + // This field is from variant [BetaMemoryTool20250818StrReplaceCommand]. + OldStr string `json:"old_str"` + // This field is from variant [BetaMemoryTool20250818InsertCommand]. + InsertLine int64 `json:"insert_line"` + // This field is from variant [BetaMemoryTool20250818InsertCommand]. + InsertText string `json:"insert_text"` + // This field is from variant [BetaMemoryTool20250818RenameCommand]. + NewPath string `json:"new_path"` + // This field is from variant [BetaMemoryTool20250818RenameCommand]. + OldPath string `json:"old_path"` + JSON struct { + Command respjson.Field + Path respjson.Field + ViewRange respjson.Field + FileText respjson.Field + NewStr respjson.Field + OldStr respjson.Field + InsertLine respjson.Field + InsertText respjson.Field + NewPath respjson.Field + OldPath respjson.Field + raw string + } `json:"-"` } -func (r BetaToolInputSchemaParam) MarshalJSON() (data []byte, err error) { - type shadow BetaToolInputSchemaParam - return param.MarshalWithExtras(r, (*shadow)(&r), r.ExtraFields) -} -func (r *BetaToolInputSchemaParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +// anyBetaMemoryTool20250818Command is implemented by each variant of +// [BetaMemoryTool20250818CommandUnion] to add type safety for the return type of +// [BetaMemoryTool20250818CommandUnion.AsAny] +type anyBetaMemoryTool20250818Command interface { + implBetaMemoryTool20250818CommandUnion() } -type BetaToolType string - -const ( - BetaToolTypeCustom BetaToolType = "custom" -) +func (BetaMemoryTool20250818ViewCommand) implBetaMemoryTool20250818CommandUnion() {} +func (BetaMemoryTool20250818CreateCommand) implBetaMemoryTool20250818CommandUnion() {} +func (BetaMemoryTool20250818StrReplaceCommand) implBetaMemoryTool20250818CommandUnion() {} +func (BetaMemoryTool20250818InsertCommand) implBetaMemoryTool20250818CommandUnion() {} +func (BetaMemoryTool20250818DeleteCommand) implBetaMemoryTool20250818CommandUnion() {} +func (BetaMemoryTool20250818RenameCommand) implBetaMemoryTool20250818CommandUnion() {} -// The properties Name, Type are required. -type BetaToolBash20241022Param struct { - // If true, tool will not be included in initial system prompt. Only loaded when - // returned via tool_reference from tool search. - DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` - // When true, guarantees schema validation on tool names and inputs - Strict param.Opt[bool] `json:"strict,omitzero"` - // Any of "direct", "code_execution_20250825", "code_execution_20260120". - AllowedCallers []string `json:"allowed_callers,omitzero"` - // Create a cache control breakpoint at this content block. - CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` - InputExamples []map[string]any `json:"input_examples,omitzero"` - // Name of the tool. - // - // This is how the tool will be called by the model and in `tool_use` blocks. - // - // This field can be elided, and will marshal its zero value as "bash". - Name constant.Bash `json:"name" default:"bash"` - // This field can be elided, and will marshal its zero value as "bash_20241022". - Type constant.Bash20241022 `json:"type" default:"bash_20241022"` - paramObj +// Use the following switch statement to find the correct variant +// +// switch variant := BetaMemoryTool20250818CommandUnion.AsAny().(type) { +// case anthropic.BetaMemoryTool20250818ViewCommand: +// case anthropic.BetaMemoryTool20250818CreateCommand: +// case anthropic.BetaMemoryTool20250818StrReplaceCommand: +// case anthropic.BetaMemoryTool20250818InsertCommand: +// case anthropic.BetaMemoryTool20250818DeleteCommand: +// case anthropic.BetaMemoryTool20250818RenameCommand: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaMemoryTool20250818CommandUnion) AsAny() anyBetaMemoryTool20250818Command { + switch u.Command { + case "view": + return u.AsView() + case "create": + return u.AsCreate() + case "str_replace": + return u.AsStrReplace() + case "insert": + return u.AsInsert() + case "delete": + return u.AsDelete() + case "rename": + return u.AsRename() + } + return nil } -func (r BetaToolBash20241022Param) MarshalJSON() (data []byte, err error) { - type shadow BetaToolBash20241022Param - return param.MarshalObject(r, (*shadow)(&r)) +func (u BetaMemoryTool20250818CommandUnion) AsView() (v BetaMemoryTool20250818ViewCommand) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -func (r *BetaToolBash20241022Param) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) + +func (u BetaMemoryTool20250818CommandUnion) AsCreate() (v BetaMemoryTool20250818CreateCommand) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -// The properties Name, Type are required. -type BetaToolBash20250124Param struct { - // If true, tool will not be included in initial system prompt. Only loaded when - // returned via tool_reference from tool search. - DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` - // When true, guarantees schema validation on tool names and inputs - Strict param.Opt[bool] `json:"strict,omitzero"` - // Any of "direct", "code_execution_20250825", "code_execution_20260120". - AllowedCallers []string `json:"allowed_callers,omitzero"` - // Create a cache control breakpoint at this content block. - CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` - InputExamples []map[string]any `json:"input_examples,omitzero"` - // Name of the tool. - // - // This is how the tool will be called by the model and in `tool_use` blocks. - // - // This field can be elided, and will marshal its zero value as "bash". - Name constant.Bash `json:"name" default:"bash"` - // This field can be elided, and will marshal its zero value as "bash_20250124". - Type constant.Bash20250124 `json:"type" default:"bash_20250124"` - paramObj +func (u BetaMemoryTool20250818CommandUnion) AsStrReplace() (v BetaMemoryTool20250818StrReplaceCommand) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -func (r BetaToolBash20250124Param) MarshalJSON() (data []byte, err error) { - type shadow BetaToolBash20250124Param - return param.MarshalObject(r, (*shadow)(&r)) +func (u BetaMemoryTool20250818CommandUnion) AsInsert() (v BetaMemoryTool20250818InsertCommand) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -func (r *BetaToolBash20250124Param) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) + +func (u BetaMemoryTool20250818CommandUnion) AsDelete() (v BetaMemoryTool20250818DeleteCommand) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -func BetaToolChoiceParamOfTool(name string) BetaToolChoiceUnionParam { - var tool BetaToolChoiceToolParam - tool.Name = name - return BetaToolChoiceUnionParam{OfTool: &tool} +func (u BetaMemoryTool20250818CommandUnion) AsRename() (v BetaMemoryTool20250818RenameCommand) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type BetaToolChoiceUnionParam struct { - OfAuto *BetaToolChoiceAutoParam `json:",omitzero,inline"` - OfAny *BetaToolChoiceAnyParam `json:",omitzero,inline"` - OfTool *BetaToolChoiceToolParam `json:",omitzero,inline"` - OfNone *BetaToolChoiceNoneParam `json:",omitzero,inline"` - paramUnion -} - -func (u BetaToolChoiceUnionParam) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfAuto, u.OfAny, u.OfTool, u.OfNone) -} -func (u *BetaToolChoiceUnionParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} +// Returns the unmodified JSON received from the API +func (u BetaMemoryTool20250818CommandUnion) RawJSON() string { return u.JSON.raw } -func (u *BetaToolChoiceUnionParam) asAny() any { - if !param.IsOmitted(u.OfAuto) { - return u.OfAuto - } else if !param.IsOmitted(u.OfAny) { - return u.OfAny - } else if !param.IsOmitted(u.OfTool) { - return u.OfTool - } else if !param.IsOmitted(u.OfNone) { - return u.OfNone - } - return nil +func (r *BetaMemoryTool20250818CommandUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaToolChoiceUnionParam) GetName() *string { - if vt := u.OfTool; vt != nil { - return &vt.Name - } - return nil +type BetaMemoryTool20250818CreateCommand struct { + // Command type identifier + Command constant.Create `json:"command" default:"create"` + // Content to write to the file + FileText string `json:"file_text" api:"required"` + // Path where the file should be created + Path string `json:"path" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Command respjson.Field + FileText respjson.Field + Path respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaToolChoiceUnionParam) GetType() *string { - if vt := u.OfAuto; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfAny; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfTool; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfNone; vt != nil { - return (*string)(&vt.Type) - } - return nil +// Returns the unmodified JSON received from the API +func (r BetaMemoryTool20250818CreateCommand) RawJSON() string { return r.JSON.raw } +func (r *BetaMemoryTool20250818CreateCommand) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaToolChoiceUnionParam) GetDisableParallelToolUse() *bool { - if vt := u.OfAuto; vt != nil && vt.DisableParallelToolUse.Valid() { - return &vt.DisableParallelToolUse.Value - } else if vt := u.OfAny; vt != nil && vt.DisableParallelToolUse.Valid() { - return &vt.DisableParallelToolUse.Value - } else if vt := u.OfTool; vt != nil && vt.DisableParallelToolUse.Valid() { - return &vt.DisableParallelToolUse.Value - } - return nil +type BetaMemoryTool20250818DeleteCommand struct { + // Command type identifier + Command constant.Delete `json:"command" default:"delete"` + // Path to the file or directory to delete + Path string `json:"path" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Command respjson.Field + Path respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` } -func init() { - apijson.RegisterUnion[BetaToolChoiceUnionParam]( - "type", - apijson.Discriminator[BetaToolChoiceAutoParam]("auto"), - apijson.Discriminator[BetaToolChoiceAnyParam]("any"), - apijson.Discriminator[BetaToolChoiceToolParam]("tool"), - apijson.Discriminator[BetaToolChoiceNoneParam]("none"), - ) +// Returns the unmodified JSON received from the API +func (r BetaMemoryTool20250818DeleteCommand) RawJSON() string { return r.JSON.raw } +func (r *BetaMemoryTool20250818DeleteCommand) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// The model will use any available tools. -// -// The property Type is required. -type BetaToolChoiceAnyParam struct { - // Whether to disable parallel tool use. - // - // Defaults to `false`. If set to `true`, the model will output exactly one tool - // use. - DisableParallelToolUse param.Opt[bool] `json:"disable_parallel_tool_use,omitzero"` - // This field can be elided, and will marshal its zero value as "any". - Type constant.Any `json:"type" default:"any"` - paramObj +type BetaMemoryTool20250818InsertCommand struct { + // Command type identifier + Command constant.Insert `json:"command" default:"insert"` + // Line number where text should be inserted + InsertLine int64 `json:"insert_line" api:"required"` + // Text to insert at the specified line + InsertText string `json:"insert_text" api:"required"` + // Path to the file where text should be inserted + Path string `json:"path" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Command respjson.Field + InsertLine respjson.Field + InsertText respjson.Field + Path respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` } -func (r BetaToolChoiceAnyParam) MarshalJSON() (data []byte, err error) { - type shadow BetaToolChoiceAnyParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaToolChoiceAnyParam) UnmarshalJSON(data []byte) error { +// Returns the unmodified JSON received from the API +func (r BetaMemoryTool20250818InsertCommand) RawJSON() string { return r.JSON.raw } +func (r *BetaMemoryTool20250818InsertCommand) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The model will automatically decide whether to use tools. -// -// The property Type is required. -type BetaToolChoiceAutoParam struct { - // Whether to disable parallel tool use. - // - // Defaults to `false`. If set to `true`, the model will output at most one tool - // use. - DisableParallelToolUse param.Opt[bool] `json:"disable_parallel_tool_use,omitzero"` - // This field can be elided, and will marshal its zero value as "auto". - Type constant.Auto `json:"type" default:"auto"` - paramObj +type BetaMemoryTool20250818RenameCommand struct { + // Command type identifier + Command constant.Rename `json:"command" default:"rename"` + // New path for the file or directory + NewPath string `json:"new_path" api:"required"` + // Current path of the file or directory + OldPath string `json:"old_path" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Command respjson.Field + NewPath respjson.Field + OldPath respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` } -func (r BetaToolChoiceAutoParam) MarshalJSON() (data []byte, err error) { - type shadow BetaToolChoiceAutoParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaToolChoiceAutoParam) UnmarshalJSON(data []byte) error { +// Returns the unmodified JSON received from the API +func (r BetaMemoryTool20250818RenameCommand) RawJSON() string { return r.JSON.raw } +func (r *BetaMemoryTool20250818RenameCommand) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -func NewBetaToolChoiceNoneParam() BetaToolChoiceNoneParam { - return BetaToolChoiceNoneParam{ - Type: "none", - } -} - -// The model will not be allowed to use tools. -// -// This struct has a constant value, construct it with -// [NewBetaToolChoiceNoneParam]. -type BetaToolChoiceNoneParam struct { - Type constant.None `json:"type" default:"none"` - paramObj +type BetaMemoryTool20250818StrReplaceCommand struct { + // Command type identifier + Command constant.StrReplace `json:"command" default:"str_replace"` + // Text to replace with + NewStr string `json:"new_str" api:"required"` + // Text to search for and replace + OldStr string `json:"old_str" api:"required"` + // Path to the file where text should be replaced + Path string `json:"path" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Command respjson.Field + NewStr respjson.Field + OldStr respjson.Field + Path respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` } -func (r BetaToolChoiceNoneParam) MarshalJSON() (data []byte, err error) { - type shadow BetaToolChoiceNoneParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaToolChoiceNoneParam) UnmarshalJSON(data []byte) error { +// Returns the unmodified JSON received from the API +func (r BetaMemoryTool20250818StrReplaceCommand) RawJSON() string { return r.JSON.raw } +func (r *BetaMemoryTool20250818StrReplaceCommand) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The model will use the specified tool with `tool_choice.name`. -// -// The properties Name, Type are required. -type BetaToolChoiceToolParam struct { - // The name of the tool to use. - Name string `json:"name" api:"required"` - // Whether to disable parallel tool use. - // - // Defaults to `false`. If set to `true`, the model will output exactly one tool - // use. - DisableParallelToolUse param.Opt[bool] `json:"disable_parallel_tool_use,omitzero"` - // This field can be elided, and will marshal its zero value as "tool". - Type constant.Tool `json:"type" default:"tool"` - paramObj +type BetaMemoryTool20250818ViewCommand struct { + // Command type identifier + Command constant.View `json:"command" default:"view"` + // Path to directory or file to view + Path string `json:"path" api:"required"` + // Optional line range for viewing specific lines + ViewRange []int64 `json:"view_range"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Command respjson.Field + Path respjson.Field + ViewRange respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` } -func (r BetaToolChoiceToolParam) MarshalJSON() (data []byte, err error) { - type shadow BetaToolChoiceToolParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaToolChoiceToolParam) UnmarshalJSON(data []byte) error { +// Returns the unmodified JSON received from the API +func (r BetaMemoryTool20250818ViewCommand) RawJSON() string { return r.JSON.raw } +func (r *BetaMemoryTool20250818ViewCommand) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The properties DisplayHeightPx, DisplayWidthPx, Name, Type are required. -type BetaToolComputerUse20241022Param struct { - // The height of the display in pixels. - DisplayHeightPx int64 `json:"display_height_px" api:"required"` - // The width of the display in pixels. - DisplayWidthPx int64 `json:"display_width_px" api:"required"` - // The X11 display number (e.g. 0, 1) for the display. - DisplayNumber param.Opt[int64] `json:"display_number,omitzero"` - // If true, tool will not be included in initial system prompt. Only loaded when - // returned via tool_reference from tool search. - DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` - // When true, guarantees schema validation on tool names and inputs - Strict param.Opt[bool] `json:"strict,omitzero"` - // Any of "direct", "code_execution_20250825", "code_execution_20260120". - AllowedCallers []string `json:"allowed_callers,omitzero"` - // Create a cache control breakpoint at this content block. - CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` - InputExamples []map[string]any `json:"input_examples,omitzero"` - // Name of the tool. +type BetaMessage struct { + // Unique object identifier. // - // This is how the tool will be called by the model and in `tool_use` blocks. + // The format and length of IDs may change over time. + ID string `json:"id" api:"required"` + // Information about the container used in the request (for the code execution + // tool) + Container BetaContainer `json:"container" api:"required"` + // Content generated by the model. // - // This field can be elided, and will marshal its zero value as "computer". - Name constant.Computer `json:"name" default:"computer"` - // This field can be elided, and will marshal its zero value as - // "computer_20241022". - Type constant.Computer20241022 `json:"type" default:"computer_20241022"` - paramObj -} - -func (r BetaToolComputerUse20241022Param) MarshalJSON() (data []byte, err error) { - type shadow BetaToolComputerUse20241022Param - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaToolComputerUse20241022Param) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The properties DisplayHeightPx, DisplayWidthPx, Name, Type are required. -type BetaToolComputerUse20250124Param struct { - // The height of the display in pixels. - DisplayHeightPx int64 `json:"display_height_px" api:"required"` - // The width of the display in pixels. - DisplayWidthPx int64 `json:"display_width_px" api:"required"` - // The X11 display number (e.g. 0, 1) for the display. - DisplayNumber param.Opt[int64] `json:"display_number,omitzero"` - // If true, tool will not be included in initial system prompt. Only loaded when - // returned via tool_reference from tool search. - DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` - // When true, guarantees schema validation on tool names and inputs - Strict param.Opt[bool] `json:"strict,omitzero"` - // Any of "direct", "code_execution_20250825", "code_execution_20260120". - AllowedCallers []string `json:"allowed_callers,omitzero"` - // Create a cache control breakpoint at this content block. - CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` - InputExamples []map[string]any `json:"input_examples,omitzero"` - // Name of the tool. + // This is an array of content blocks, each of which has a `type` that determines + // its shape. // - // This is how the tool will be called by the model and in `tool_use` blocks. + // Example: // - // This field can be elided, and will marshal its zero value as "computer". - Name constant.Computer `json:"name" default:"computer"` - // This field can be elided, and will marshal its zero value as - // "computer_20250124". - Type constant.Computer20250124 `json:"type" default:"computer_20250124"` - paramObj -} - -func (r BetaToolComputerUse20250124Param) MarshalJSON() (data []byte, err error) { - type shadow BetaToolComputerUse20250124Param - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaToolComputerUse20250124Param) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The properties DisplayHeightPx, DisplayWidthPx, Name, Type are required. -type BetaToolComputerUse20251124Param struct { - // The height of the display in pixels. - DisplayHeightPx int64 `json:"display_height_px" api:"required"` - // The width of the display in pixels. - DisplayWidthPx int64 `json:"display_width_px" api:"required"` - // The X11 display number (e.g. 0, 1) for the display. - DisplayNumber param.Opt[int64] `json:"display_number,omitzero"` - // If true, tool will not be included in initial system prompt. Only loaded when - // returned via tool_reference from tool search. - DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` - // Whether to enable an action to take a zoomed-in screenshot of the screen. - EnableZoom param.Opt[bool] `json:"enable_zoom,omitzero"` - // When true, guarantees schema validation on tool names and inputs - Strict param.Opt[bool] `json:"strict,omitzero"` - // Any of "direct", "code_execution_20250825", "code_execution_20260120". - AllowedCallers []string `json:"allowed_callers,omitzero"` - // Create a cache control breakpoint at this content block. - CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` - InputExamples []map[string]any `json:"input_examples,omitzero"` - // Name of the tool. + // ```json + // [{ "type": "text", "text": "Hi, I'm Claude." }] + // ``` // - // This is how the tool will be called by the model and in `tool_use` blocks. + // If the request input `messages` ended with an `assistant` turn, then the + // response `content` will continue directly from that last turn. You can use this + // to constrain the model's output. // - // This field can be elided, and will marshal its zero value as "computer". - Name constant.Computer `json:"name" default:"computer"` - // This field can be elided, and will marshal its zero value as - // "computer_20251124". - Type constant.Computer20251124 `json:"type" default:"computer_20251124"` - paramObj + // For example, if the input `messages` were: + // + // ```json + // [ + // + // { + // "role": "user", + // "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun" + // }, + // { "role": "assistant", "content": "The best answer is (" } + // + // ] + // ``` + // + // Then the response `content` might be: + // + // ```json + // [{ "type": "text", "text": "B)" }] + // ``` + Content []BetaContentBlockUnion `json:"content" api:"required"` + // Context management response. + // + // Information about context management strategies applied during the request. + ContextManagement BetaContextManagementResponse `json:"context_management" api:"required"` + // Response envelope for request-level diagnostics. Present (possibly null) + // whenever the caller supplied `diagnostics` on the request. + Diagnostics BetaDiagnostics `json:"diagnostics" api:"required"` + // The model that will complete your prompt. + // + // See [models](https://docs.anthropic.com/en/docs/models-overview) for additional + // details and options. + Model Model `json:"model" api:"required"` + // Conversational role of the generated message. + // + // This will always be `"assistant"`. + Role constant.Assistant `json:"role" default:"assistant"` + // Structured information about a refusal. + StopDetails BetaRefusalStopDetails `json:"stop_details" api:"required"` + // The reason that we stopped. + // + // This may be one the following values: + // + // - `"end_turn"`: the model reached a natural stopping point + // - `"max_tokens"`: we exceeded the requested `max_tokens` or the model's maximum + // - `"stop_sequence"`: one of your provided custom `stop_sequences` was generated + // - `"tool_use"`: the model invoked one or more tools + // - `"pause_turn"`: we paused a long-running turn. You may provide the response + // back as-is in a subsequent request to let the model continue. + // - `"refusal"`: when streaming classifiers intervene to handle potential policy + // violations + // - `"model_context_window_exceeded"`: we exceeded the model's context window + // + // In non-streaming mode this value is always non-null. In streaming mode, it is + // null in the `message_start` event and non-null otherwise. + // + // Any of "end_turn", "max_tokens", "stop_sequence", "tool_use", "pause_turn", + // "compaction", "refusal", "model_context_window_exceeded". + StopReason BetaStopReason `json:"stop_reason" api:"required"` + // Which custom stop sequence was generated, if any. + // + // This value will be a non-null string if one of your custom stop sequences was + // generated. + StopSequence string `json:"stop_sequence" api:"required"` + // Object type. + // + // For Messages, this is always `"message"`. + Type constant.Message `json:"type" default:"message"` + // Billing and rate-limit usage. + // + // Anthropic's API bills and rate-limits by token counts, as tokens represent the + // underlying cost to our systems. + // + // Under the hood, the API transforms requests into a format suitable for the + // model. The model's output then goes through a parsing stage before becoming an + // API response. As a result, the token counts in `usage` will not match one-to-one + // with the exact visible content of an API request or response. + // + // For example, `output_tokens` will be non-zero, even for an empty string response + // from Claude. + // + // Total input tokens in a request is the summation of `input_tokens`, + // `cache_creation_input_tokens`, and `cache_read_input_tokens`. + Usage BetaUsage `json:"usage" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + Container respjson.Field + Content respjson.Field + ContextManagement respjson.Field + Diagnostics respjson.Field + Model respjson.Field + Role respjson.Field + StopDetails respjson.Field + StopReason respjson.Field + StopSequence respjson.Field + Type respjson.Field + Usage respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` } -func (r BetaToolComputerUse20251124Param) MarshalJSON() (data []byte, err error) { - type shadow BetaToolComputerUse20251124Param - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaToolComputerUse20251124Param) UnmarshalJSON(data []byte) error { +// Returns the unmodified JSON received from the API +func (r BetaMessage) RawJSON() string { return r.JSON.raw } +func (r *BetaMessage) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type BetaToolReferenceBlock struct { - ToolName string `json:"tool_name" api:"required"` - Type constant.ToolReference `json:"type" default:"tool_reference"` +type BetaMessageDeltaUsage struct { + // The cumulative number of input tokens used to create the cache entry. + CacheCreationInputTokens int64 `json:"cache_creation_input_tokens" api:"required"` + // The cumulative number of input tokens read from the cache. + CacheReadInputTokens int64 `json:"cache_read_input_tokens" api:"required"` + // Outcome of the `fallback_credit_token` presented on this request. + FallbackCredit BetaFallbackCreditUsage `json:"fallback_credit" api:"required"` + // The cumulative number of input tokens which were used. + InputTokens int64 `json:"input_tokens" api:"required"` + // Per-iteration token usage breakdown. + // + // Each entry represents one sampling iteration, with its own input/output token + // counts and cache statistics, discriminated by `type`. For `message` entries + // (model sampling iterations, such as the turns of a server-side tool use loop), + // this allows you to: + // + // - Determine which iterations exceeded long context thresholds (>=200k tokens) + // - Calculate the context window size from the last `message` entry + // - Understand token accumulation across server-side tool use loops + // + // A `compaction` entry reports the token usage of the compaction operation itself + // — the server-side request that summarizes the context being closed — NOT the + // size of the context that was compacted away, and its token counts can be much + // smaller than that closed context (for example, a compaction that closes a + // ~200k-token context can report only a few thousand tokens). Do not derive the + // context window size from a `compaction` entry, even when it is the last entry. A + // `compaction` entry's tokens are not included in the top-level `usage` fields. + // When an input-token trigger is in effect (the default — 150,000 tokens unless + // configured otherwise), each `compaction` entry closes a context that had reached + // at least that threshold, though the context can exceed it by the final + // iteration's output and tool results. + Iterations BetaIterationsUsage `json:"iterations" api:"required"` + // The cumulative number of output tokens which were used. + OutputTokens int64 `json:"output_tokens" api:"required"` + // Breakdown of output tokens by category. + // + // `output_tokens` remains the inclusive, authoritative total used for billing. + // This object provides a read-only decomposition for observability — for example, + // how many of the billed output tokens were spent on internal reasoning that may + // have been summarized before being returned to you. + OutputTokensDetails BetaOutputTokensDetails `json:"output_tokens_details" api:"required"` + // The number of server tool requests. + ServerToolUse BetaServerToolUsage `json:"server_tool_use" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { - ToolName respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string + CacheCreationInputTokens respjson.Field + CacheReadInputTokens respjson.Field + FallbackCredit respjson.Field + InputTokens respjson.Field + Iterations respjson.Field + OutputTokens respjson.Field + OutputTokensDetails respjson.Field + ServerToolUse respjson.Field + ExtraFields map[string]respjson.Field + raw string } `json:"-"` } // Returns the unmodified JSON received from the API -func (r BetaToolReferenceBlock) RawJSON() string { return r.JSON.raw } -func (r *BetaToolReferenceBlock) UnmarshalJSON(data []byte) error { +func (r BetaMessageDeltaUsage) RawJSON() string { return r.JSON.raw } +func (r *BetaMessageDeltaUsage) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// Tool reference block that can be included in tool_result content. -// -// The properties ToolName, Type are required. -type BetaToolReferenceBlockParam struct { - ToolName string `json:"tool_name" api:"required"` - // Create a cache control breakpoint at this content block. - CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` - // This field can be elided, and will marshal its zero value as "tool_reference". - Type constant.ToolReference `json:"type" default:"tool_reference"` - paramObj +// Token usage for a sampling iteration. +type BetaMessageIterationUsage struct { + // Breakdown of cached tokens by TTL + CacheCreation BetaCacheCreation `json:"cache_creation" api:"required"` + // The number of input tokens used to create the cache entry. + CacheCreationInputTokens int64 `json:"cache_creation_input_tokens" api:"required"` + // The number of input tokens read from the cache. + CacheReadInputTokens int64 `json:"cache_read_input_tokens" api:"required"` + // The number of input tokens which were used. + InputTokens int64 `json:"input_tokens" api:"required"` + // The model that will complete your prompt. + // + // See [models](https://docs.anthropic.com/en/docs/models-overview) for additional + // details and options. + Model Model `json:"model" api:"required"` + // The number of output tokens which were used. + OutputTokens int64 `json:"output_tokens" api:"required"` + // Usage for a sampling iteration + Type constant.Message `json:"type" default:"message"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + CacheCreation respjson.Field + CacheCreationInputTokens respjson.Field + CacheReadInputTokens respjson.Field + InputTokens respjson.Field + Model respjson.Field + OutputTokens respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` } -func (r BetaToolReferenceBlockParam) MarshalJSON() (data []byte, err error) { - type shadow BetaToolReferenceBlockParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaToolReferenceBlockParam) UnmarshalJSON(data []byte) error { +// Returns the unmodified JSON received from the API +func (r BetaMessageIterationUsage) RawJSON() string { return r.JSON.raw } +func (r *BetaMessageIterationUsage) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The properties ToolUseID, Type are required. -type BetaToolResultBlockParam struct { - ToolUseID string `json:"tool_use_id" api:"required"` - IsError param.Opt[bool] `json:"is_error,omitzero"` - // Create a cache control breakpoint at this content block. - CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` - Content []BetaToolResultBlockParamContentUnion `json:"content,omitzero"` - // This field can be elided, and will marshal its zero value as "tool_result". - Type constant.ToolResult `json:"type" default:"tool_result"` +// The properties Content, Role are required. +type BetaMessageParam struct { + Content []BetaContentBlockParamUnion `json:"content,omitzero" api:"required"` + // Any of "user", "assistant", "system". + Role BetaMessageParamRole `json:"role,omitzero" api:"required"` paramObj } -func (r BetaToolResultBlockParam) MarshalJSON() (data []byte, err error) { - type shadow BetaToolResultBlockParam +func NewBetaUserMessage(blocks ...BetaContentBlockParamUnion) BetaMessageParam { + return BetaMessageParam{ + Role: BetaMessageParamRoleUser, + Content: blocks, + } +} + +func (r BetaMessageParam) MarshalJSON() (data []byte, err error) { + type shadow BetaMessageParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *BetaToolResultBlockParam) UnmarshalJSON(data []byte) error { +func (r *BetaMessageParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -func NewBetaToolResultTextBlockParam(toolUseID string, text string, isError bool) BetaToolResultBlockParam { - var p BetaToolResultBlockParam - p.ToolUseID = toolUseID - p.IsError = param.Opt[bool]{Value: isError} - p.Content = []BetaToolResultBlockParamContentUnion{ - {OfText: &BetaTextBlockParam{Text: text}}, - } - return p +type BetaMessageParamRole string + +const ( + BetaMessageParamRoleUser BetaMessageParamRole = "user" + BetaMessageParamRoleAssistant BetaMessageParamRole = "assistant" + BetaMessageParamRoleSystem BetaMessageParamRole = "system" +) + +type BetaMessageTokensCount struct { + // Information about context management applied to the message. + ContextManagement BetaCountTokensContextManagementResponse `json:"context_management" api:"required"` + // The total number of tokens across the provided list of messages, system prompt, + // and tools. + InputTokens int64 `json:"input_tokens" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ContextManagement respjson.Field + InputTokens respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` } -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type BetaToolResultBlockParamContentUnion struct { - OfText *BetaTextBlockParam `json:",omitzero,inline"` - OfImage *BetaImageBlockParam `json:",omitzero,inline"` - OfSearchResult *BetaSearchResultBlockParam `json:",omitzero,inline"` - OfDocument *BetaRequestDocumentBlockParam `json:",omitzero,inline"` - OfToolReference *BetaToolReferenceBlockParam `json:",omitzero,inline"` - paramUnion +// Returns the unmodified JSON received from the API +func (r BetaMessageTokensCount) RawJSON() string { return r.JSON.raw } +func (r *BetaMessageTokensCount) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func (u BetaToolResultBlockParamContentUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfText, - u.OfImage, - u.OfSearchResult, - u.OfDocument, - u.OfToolReference) +type BetaMetadataParam struct { + // An external identifier for the user who is associated with the request. + // + // This should be a uuid, hash value, or other opaque identifier. Anthropic may use + // this id to help detect abuse. Do not include any identifying information such as + // name, email address, or phone number. + UserID param.Opt[string] `json:"user_id,omitzero"` + paramObj } -func (u *BetaToolResultBlockParamContentUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) + +func (r BetaMetadataParam) MarshalJSON() (data []byte, err error) { + type shadow BetaMetadataParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaMetadataParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func (u *BetaToolResultBlockParamContentUnion) asAny() any { - if !param.IsOmitted(u.OfText) { - return u.OfText - } else if !param.IsOmitted(u.OfImage) { - return u.OfImage - } else if !param.IsOmitted(u.OfSearchResult) { - return u.OfSearchResult - } else if !param.IsOmitted(u.OfDocument) { - return u.OfDocument - } else if !param.IsOmitted(u.OfToolReference) { - return u.OfToolReference - } - return nil +type BetaOutputConfigParam struct { + // All possible effort levels. + // + // Any of "low", "medium", "high", "xhigh", "max". + Effort BetaOutputConfigEffort `json:"effort,omitzero"` + // A schema to specify Claude's output format in responses. See + // [structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs) + Format BetaJSONOutputFormatParam `json:"format,omitzero"` + // User-configurable total token budget across contexts. + TaskBudget BetaTokenTaskBudgetParam `json:"task_budget,omitzero"` + paramObj } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaToolResultBlockParamContentUnion) GetText() *string { - if vt := u.OfText; vt != nil { - return &vt.Text - } - return nil +func (r BetaOutputConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaOutputConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaOutputConfigParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaToolResultBlockParamContentUnion) GetContent() []BetaTextBlockParam { - if vt := u.OfSearchResult; vt != nil { - return vt.Content - } - return nil +// All possible effort levels. +type BetaOutputConfigEffort string + +const ( + BetaOutputConfigEffortLow BetaOutputConfigEffort = "low" + BetaOutputConfigEffortMedium BetaOutputConfigEffort = "medium" + BetaOutputConfigEffortHigh BetaOutputConfigEffort = "high" + BetaOutputConfigEffortXhigh BetaOutputConfigEffort = "xhigh" + BetaOutputConfigEffortMax BetaOutputConfigEffort = "max" +) + +type BetaOutputTokensDetails struct { + // Number of output tokens the model generated as internal reasoning, including the + // thinking-block delimiter tokens. + // + // Reflects the raw reasoning the model produced, not the (possibly shorter) + // summarized thinking text returned in the response body. Computed by + // re-tokenizing the raw reasoning text, so it may differ from the model's exact + // generation count by a small number of tokens. Always ≤ `output_tokens`; + // `output_tokens - thinking_tokens` approximates the non-reasoning output. + ThinkingTokens int64 `json:"thinking_tokens" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ThinkingTokens respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaToolResultBlockParamContentUnion) GetContext() *string { - if vt := u.OfDocument; vt != nil && vt.Context.Valid() { - return &vt.Context.Value - } - return nil +// Returns the unmodified JSON received from the API +func (r BetaOutputTokensDetails) RawJSON() string { return r.JSON.raw } +func (r *BetaOutputTokensDetails) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaToolResultBlockParamContentUnion) GetToolName() *string { - if vt := u.OfToolReference; vt != nil { - return &vt.ToolName - } - return nil +type BetaPlainTextSource struct { + Data string `json:"data" api:"required"` + MediaType constant.TextPlain `json:"media_type" default:"text/plain"` + Type constant.Text `json:"type" default:"text"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Data respjson.Field + MediaType respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaToolResultBlockParamContentUnion) GetType() *string { - if vt := u.OfText; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfImage; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfSearchResult; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfDocument; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfToolReference; vt != nil { - return (*string)(&vt.Type) - } - return nil +// Returns the unmodified JSON received from the API +func (r BetaPlainTextSource) RawJSON() string { return r.JSON.raw } +func (r *BetaPlainTextSource) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaToolResultBlockParamContentUnion) GetTitle() *string { - if vt := u.OfSearchResult; vt != nil { - return (*string)(&vt.Title) - } else if vt := u.OfDocument; vt != nil && vt.Title.Valid() { - return &vt.Title.Value - } - return nil +// ToParam converts this BetaPlainTextSource to a BetaPlainTextSourceParam. +// +// Warning: the fields of the param type will not be present. ToParam should only +// be used at the last possible moment before sending a request. Test for this with +// BetaPlainTextSourceParam.Overrides() +func (r BetaPlainTextSource) ToParam() BetaPlainTextSourceParam { + return param.Override[BetaPlainTextSourceParam](json.RawMessage(r.RawJSON())) } -// Returns a pointer to the underlying variant's CacheControl property, if present. -func (u BetaToolResultBlockParamContentUnion) GetCacheControl() *BetaCacheControlEphemeralParam { - if vt := u.OfText; vt != nil { - return &vt.CacheControl - } else if vt := u.OfImage; vt != nil { - return &vt.CacheControl - } else if vt := u.OfSearchResult; vt != nil { - return &vt.CacheControl - } else if vt := u.OfDocument; vt != nil { - return &vt.CacheControl - } else if vt := u.OfToolReference; vt != nil { - return &vt.CacheControl - } - return nil +// The properties Data, MediaType, Type are required. +type BetaPlainTextSourceParam struct { + Data string `json:"data" api:"required"` + // This field can be elided, and will marshal its zero value as "text/plain". + MediaType constant.TextPlain `json:"media_type" default:"text/plain"` + // This field can be elided, and will marshal its zero value as "text". + Type constant.Text `json:"type" default:"text"` + paramObj } -// Returns a subunion which exports methods to access subproperties +func (r BetaPlainTextSourceParam) MarshalJSON() (data []byte, err error) { + type shadow BetaPlainTextSourceParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaPlainTextSourceParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaRawContentBlockDeltaUnion contains all possible properties and values from +// [BetaTextDelta], [BetaInputJSONDelta], [BetaCitationsDelta], +// [BetaThinkingDelta], [BetaSignatureDelta], [BetaCompactionContentBlockDelta]. // -// Or use AsAny() to get the underlying value -func (u BetaToolResultBlockParamContentUnion) GetCitations() (res betaToolResultBlockParamContentUnionCitations) { - if vt := u.OfText; vt != nil { - res.any = &vt.Citations - } else if vt := u.OfSearchResult; vt != nil { - res.any = &vt.Citations - } else if vt := u.OfDocument; vt != nil { - res.any = &vt.Citations - } - return +// Use the [BetaRawContentBlockDeltaUnion.AsAny] method to switch on the variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaRawContentBlockDeltaUnion struct { + // This field is from variant [BetaTextDelta]. + Text string `json:"text"` + // Any of "text_delta", "input_json_delta", "citations_delta", "thinking_delta", + // "signature_delta", "compaction_delta". + Type string `json:"type"` + // This field is from variant [BetaInputJSONDelta]. + PartialJSON string `json:"partial_json"` + // This field is from variant [BetaCitationsDelta]. + Citation BetaCitationsDeltaCitationUnion `json:"citation"` + // This field is from variant [BetaThinkingDelta]. + EstimatedTokens int64 `json:"estimated_tokens"` + // This field is from variant [BetaThinkingDelta]. + Thinking string `json:"thinking"` + // This field is from variant [BetaSignatureDelta]. + Signature string `json:"signature"` + // This field is from variant [BetaCompactionContentBlockDelta]. + Content string `json:"content"` + // This field is from variant [BetaCompactionContentBlockDelta]. + EncryptedContent string `json:"encrypted_content"` + JSON struct { + Text respjson.Field + Type respjson.Field + PartialJSON respjson.Field + Citation respjson.Field + EstimatedTokens respjson.Field + Thinking respjson.Field + Signature respjson.Field + Content respjson.Field + EncryptedContent respjson.Field + raw string + } `json:"-"` } -// Can have the runtime types [*[]BetaTextCitationParamUnion], -// [*BetaCitationsConfigParam] -type betaToolResultBlockParamContentUnionCitations struct{ any } +// anyBetaRawContentBlockDelta is implemented by each variant of +// [BetaRawContentBlockDeltaUnion] to add type safety for the return type of +// [BetaRawContentBlockDeltaUnion.AsAny] +type anyBetaRawContentBlockDelta interface { + implBetaRawContentBlockDeltaUnion() +} -// Use the following switch statement to get the type of the union: +func (BetaTextDelta) implBetaRawContentBlockDeltaUnion() {} +func (BetaInputJSONDelta) implBetaRawContentBlockDeltaUnion() {} +func (BetaCitationsDelta) implBetaRawContentBlockDeltaUnion() {} +func (BetaThinkingDelta) implBetaRawContentBlockDeltaUnion() {} +func (BetaSignatureDelta) implBetaRawContentBlockDeltaUnion() {} +func (BetaCompactionContentBlockDelta) implBetaRawContentBlockDeltaUnion() {} + +// Use the following switch statement to find the correct variant // -// switch u.AsAny().(type) { -// case *[]anthropic.BetaTextCitationParamUnion: -// case *anthropic.BetaCitationsConfigParam: +// switch variant := BetaRawContentBlockDeltaUnion.AsAny().(type) { +// case anthropic.BetaTextDelta: +// case anthropic.BetaInputJSONDelta: +// case anthropic.BetaCitationsDelta: +// case anthropic.BetaThinkingDelta: +// case anthropic.BetaSignatureDelta: +// case anthropic.BetaCompactionContentBlockDelta: // default: -// fmt.Errorf("not present") +// fmt.Errorf("no variant present") // } -func (u betaToolResultBlockParamContentUnionCitations) AsAny() any { return u.any } - -// Returns a pointer to the underlying variant's property, if present. -func (u betaToolResultBlockParamContentUnionCitations) GetEnabled() *bool { - switch vt := u.any.(type) { - case *BetaCitationsConfigParam: - return paramutil.AddrIfPresent(vt.Enabled) +func (u BetaRawContentBlockDeltaUnion) AsAny() anyBetaRawContentBlockDelta { + switch u.Type { + case "text_delta": + return u.AsTextDelta() + case "input_json_delta": + return u.AsInputJSONDelta() + case "citations_delta": + return u.AsCitationsDelta() + case "thinking_delta": + return u.AsThinkingDelta() + case "signature_delta": + return u.AsSignatureDelta() + case "compaction_delta": + return u.AsCompactionDelta() } return nil } -// Returns a subunion which exports methods to access subproperties -// -// Or use AsAny() to get the underlying value -func (u BetaToolResultBlockParamContentUnion) GetSource() (res betaToolResultBlockParamContentUnionSource) { - if vt := u.OfImage; vt != nil { - res.any = vt.Source.asAny() - } else if vt := u.OfSearchResult; vt != nil { - res.any = &vt.Source - } else if vt := u.OfDocument; vt != nil { - res.any = vt.Source.asAny() - } +func (u BetaRawContentBlockDeltaUnion) AsTextDelta() (v BetaTextDelta) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return } -// Can have the runtime types [*BetaBase64ImageSourceParam], -// [*BetaURLImageSourceParam], [*BetaFileImageSourceParam], [*string], -// [*BetaBase64PDFSourceParam], [*BetaPlainTextSourceParam], -// [*BetaContentBlockSourceParam], [*BetaURLPDFSourceParam], -// [*BetaFileDocumentSourceParam] -type betaToolResultBlockParamContentUnionSource struct{ any } - -// Use the following switch statement to get the type of the union: -// -// switch u.AsAny().(type) { -// case *anthropic.BetaBase64ImageSourceParam: -// case *anthropic.BetaURLImageSourceParam: -// case *anthropic.BetaFileImageSourceParam: -// case *string: -// case *anthropic.BetaBase64PDFSourceParam: -// case *anthropic.BetaPlainTextSourceParam: -// case *anthropic.BetaContentBlockSourceParam: -// case *anthropic.BetaURLPDFSourceParam: -// case *anthropic.BetaFileDocumentSourceParam: -// default: -// fmt.Errorf("not present") -// } -func (u betaToolResultBlockParamContentUnionSource) AsAny() any { return u.any } - -// Returns a pointer to the underlying variant's property, if present. -func (u betaToolResultBlockParamContentUnionSource) GetContent() *BetaContentBlockSourceContentUnionParam { - switch vt := u.any.(type) { - case *BetaRequestDocumentBlockSourceUnionParam: - return vt.GetContent() - } - return nil +func (u BetaRawContentBlockDeltaUnion) AsInputJSONDelta() (v BetaInputJSONDelta) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -// Returns a pointer to the underlying variant's property, if present. -func (u betaToolResultBlockParamContentUnionSource) GetData() *string { - switch vt := u.any.(type) { - case *BetaImageBlockParamSourceUnion: - return vt.GetData() - case *BetaRequestDocumentBlockSourceUnionParam: - return vt.GetData() - } - return nil +func (u BetaRawContentBlockDeltaUnion) AsCitationsDelta() (v BetaCitationsDelta) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -// Returns a pointer to the underlying variant's property, if present. -func (u betaToolResultBlockParamContentUnionSource) GetMediaType() *string { - switch vt := u.any.(type) { - case *BetaImageBlockParamSourceUnion: - return vt.GetMediaType() - case *BetaRequestDocumentBlockSourceUnionParam: - return vt.GetMediaType() - } - return nil +func (u BetaRawContentBlockDeltaUnion) AsThinkingDelta() (v BetaThinkingDelta) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -// Returns a pointer to the underlying variant's property, if present. -func (u betaToolResultBlockParamContentUnionSource) GetType() *string { - switch vt := u.any.(type) { - case *BetaImageBlockParamSourceUnion: - return vt.GetType() - case *BetaRequestDocumentBlockSourceUnionParam: - return vt.GetType() - } - return nil +func (u BetaRawContentBlockDeltaUnion) AsSignatureDelta() (v BetaSignatureDelta) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -// Returns a pointer to the underlying variant's property, if present. -func (u betaToolResultBlockParamContentUnionSource) GetURL() *string { - switch vt := u.any.(type) { - case *BetaImageBlockParamSourceUnion: - return vt.GetURL() - case *BetaRequestDocumentBlockSourceUnionParam: - return vt.GetURL() - } - return nil +func (u BetaRawContentBlockDeltaUnion) AsCompactionDelta() (v BetaCompactionContentBlockDelta) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -// Returns a pointer to the underlying variant's property, if present. -func (u betaToolResultBlockParamContentUnionSource) GetFileID() *string { - switch vt := u.any.(type) { - case *BetaImageBlockParamSourceUnion: - return vt.GetFileID() - case *BetaRequestDocumentBlockSourceUnionParam: - return vt.GetFileID() - } - return nil +// Returns the unmodified JSON received from the API +func (u BetaRawContentBlockDeltaUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaRawContentBlockDeltaUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func init() { - apijson.RegisterUnion[BetaToolResultBlockParamContentUnion]( - "type", - apijson.Discriminator[BetaTextBlockParam]("text"), - apijson.Discriminator[BetaImageBlockParam]("image"), - apijson.Discriminator[BetaSearchResultBlockParam]("search_result"), - apijson.Discriminator[BetaRequestDocumentBlockParam]("document"), - apijson.Discriminator[BetaToolReferenceBlockParam]("tool_reference"), - ) +type BetaRawContentBlockDeltaEvent struct { + Delta BetaRawContentBlockDeltaUnion `json:"delta" api:"required"` + Index int64 `json:"index" api:"required"` + Type constant.ContentBlockDelta `json:"type" default:"content_block_delta"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Delta respjson.Field + Index respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` } -// The properties Name, Type are required. -type BetaToolSearchToolBm25_20251119Param struct { - // Any of "tool_search_tool_bm25_20251119", "tool_search_tool_bm25". - Type BetaToolSearchToolBm25_20251119Type `json:"type,omitzero" api:"required"` - // If true, tool will not be included in initial system prompt. Only loaded when - // returned via tool_reference from tool search. - DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` - // When true, guarantees schema validation on tool names and inputs - Strict param.Opt[bool] `json:"strict,omitzero"` - // Any of "direct", "code_execution_20250825", "code_execution_20260120". - AllowedCallers []string `json:"allowed_callers,omitzero"` - // Create a cache control breakpoint at this content block. - CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` - InputExamples []map[string]any `json:"input_examples,omitzero"` - // Name of the tool. - // - // This is how the tool will be called by the model and in `tool_use` blocks. - // - // This field can be elided, and will marshal its zero value as - // "tool_search_tool_bm25". - Name constant.ToolSearchToolBm25 `json:"name" default:"tool_search_tool_bm25"` - paramObj -} - -func (r BetaToolSearchToolBm25_20251119Param) MarshalJSON() (data []byte, err error) { - type shadow BetaToolSearchToolBm25_20251119Param - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaToolSearchToolBm25_20251119Param) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type BetaToolSearchToolBm25_20251119Type string - -const ( - BetaToolSearchToolBm25_20251119TypeToolSearchToolBm25_20251119 BetaToolSearchToolBm25_20251119Type = "tool_search_tool_bm25_20251119" - BetaToolSearchToolBm25_20251119TypeToolSearchToolBm25 BetaToolSearchToolBm25_20251119Type = "tool_search_tool_bm25" -) - -// The properties Name, Type are required. -type BetaToolSearchToolRegex20251119Param struct { - // Any of "tool_search_tool_regex_20251119", "tool_search_tool_regex". - Type BetaToolSearchToolRegex20251119Type `json:"type,omitzero" api:"required"` - // If true, tool will not be included in initial system prompt. Only loaded when - // returned via tool_reference from tool search. - DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` - // When true, guarantees schema validation on tool names and inputs - Strict param.Opt[bool] `json:"strict,omitzero"` - // Any of "direct", "code_execution_20250825", "code_execution_20260120". - AllowedCallers []string `json:"allowed_callers,omitzero"` - // Create a cache control breakpoint at this content block. - CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` - // Name of the tool. - // - // This is how the tool will be called by the model and in `tool_use` blocks. - // - // This field can be elided, and will marshal its zero value as - // "tool_search_tool_regex". - Name constant.ToolSearchToolRegex `json:"name" default:"tool_search_tool_regex"` - paramObj -} - -func (r BetaToolSearchToolRegex20251119Param) MarshalJSON() (data []byte, err error) { - type shadow BetaToolSearchToolRegex20251119Param - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaToolSearchToolRegex20251119Param) UnmarshalJSON(data []byte) error { +// Returns the unmodified JSON received from the API +func (r BetaRawContentBlockDeltaEvent) RawJSON() string { return r.JSON.raw } +func (r *BetaRawContentBlockDeltaEvent) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type BetaToolSearchToolRegex20251119Type string - -const ( - BetaToolSearchToolRegex20251119TypeToolSearchToolRegex20251119 BetaToolSearchToolRegex20251119Type = "tool_search_tool_regex_20251119" - BetaToolSearchToolRegex20251119TypeToolSearchToolRegex BetaToolSearchToolRegex20251119Type = "tool_search_tool_regex" -) - -type BetaToolSearchToolResultBlock struct { - Content BetaToolSearchToolResultBlockContentUnion `json:"content" api:"required"` - ToolUseID string `json:"tool_use_id" api:"required"` - Type constant.ToolSearchToolResult `json:"type" default:"tool_search_tool_result"` +type BetaRawContentBlockStartEvent struct { + // Response model for a file uploaded to the container. + ContentBlock BetaRawContentBlockStartEventContentBlockUnion `json:"content_block" api:"required"` + Index int64 `json:"index" api:"required"` + Type constant.ContentBlockStart `json:"type" default:"content_block_start"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { - Content respjson.Field - ToolUseID respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string + ContentBlock respjson.Field + Index respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string } `json:"-"` } // Returns the unmodified JSON received from the API -func (r BetaToolSearchToolResultBlock) RawJSON() string { return r.JSON.raw } -func (r *BetaToolSearchToolResultBlock) UnmarshalJSON(data []byte) error { +func (r BetaRawContentBlockStartEvent) RawJSON() string { return r.JSON.raw } +func (r *BetaRawContentBlockStartEvent) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// BetaToolSearchToolResultBlockContentUnion contains all possible properties and -// values from [BetaToolSearchToolResultError], -// [BetaToolSearchToolSearchResultBlock]. +// BetaRawContentBlockStartEventContentBlockUnion contains all possible properties +// and values from [BetaTextBlock], [BetaThinkingBlock], +// [BetaRedactedThinkingBlock], [BetaToolUseBlock], [BetaServerToolUseBlock], +// [BetaWebSearchToolResultBlock], [BetaWebFetchToolResultBlock], +// [BetaAdvisorToolResultBlock], [BetaCodeExecutionToolResultBlock], +// [BetaBashCodeExecutionToolResultBlock], +// [BetaTextEditorCodeExecutionToolResultBlock], [BetaToolSearchToolResultBlock], +// [BetaMCPToolUseBlock], [BetaMCPToolResultBlock], [BetaContainerUploadBlock], +// [BetaCompactionBlock], [BetaFallbackBlock]. +// +// Use the [BetaRawContentBlockStartEventContentBlockUnion.AsAny] method to switch +// on the variant. // // Use the methods beginning with 'As' to cast the union to one of its variants. -type BetaToolSearchToolResultBlockContentUnion struct { - // This field is from variant [BetaToolSearchToolResultError]. - ErrorCode BetaToolSearchToolResultErrorErrorCode `json:"error_code"` - // This field is from variant [BetaToolSearchToolResultError]. - ErrorMessage string `json:"error_message"` - Type string `json:"type"` - // This field is from variant [BetaToolSearchToolSearchResultBlock]. - ToolReferences []BetaToolReferenceBlock `json:"tool_references"` - JSON struct { - ErrorCode respjson.Field - ErrorMessage respjson.Field - Type respjson.Field - ToolReferences respjson.Field - raw string +type BetaRawContentBlockStartEventContentBlockUnion struct { + // This field is from variant [BetaTextBlock]. + Citations []BetaTextCitationUnion `json:"citations"` + // This field is from variant [BetaTextBlock]. + Text string `json:"text"` + // Any of "text", "thinking", "redacted_thinking", "tool_use", "server_tool_use", + // "web_search_tool_result", "web_fetch_tool_result", "advisor_tool_result", + // "code_execution_tool_result", "bash_code_execution_tool_result", + // "text_editor_code_execution_tool_result", "tool_search_tool_result", + // "mcp_tool_use", "mcp_tool_result", "container_upload", "compaction", "fallback". + Type string `json:"type"` + // This field is from variant [BetaThinkingBlock]. + Signature string `json:"signature"` + // This field is from variant [BetaThinkingBlock]. + Thinking string `json:"thinking"` + // This field is from variant [BetaRedactedThinkingBlock]. + Data string `json:"data"` + ID string `json:"id"` + Input any `json:"input"` + Name string `json:"name"` + // This field is a union of [BetaToolUseBlockCallerUnion], + // [BetaServerToolUseBlockCallerUnion], [BetaWebSearchToolResultBlockCallerUnion], + // [BetaWebFetchToolResultBlockCallerUnion] + Caller BetaRawContentBlockStartEventContentBlockUnionCaller `json:"caller"` + // This field is from variant [BetaToolUseBlock]. + ToolsetName string `json:"toolset_name"` + // This field is a union of [BetaWebSearchToolResultBlockContentUnion], + // [BetaWebFetchToolResultBlockContentUnion], + // [BetaAdvisorToolResultBlockContentUnion], + // [BetaCodeExecutionToolResultBlockContentUnion], + // [BetaBashCodeExecutionToolResultBlockContentUnion], + // [BetaTextEditorCodeExecutionToolResultBlockContentUnion], + // [BetaToolSearchToolResultBlockContentUnion], + // [BetaMCPToolResultBlockContentUnion], [string] + Content BetaRawContentBlockStartEventContentBlockUnionContent `json:"content"` + ToolUseID string `json:"tool_use_id"` + // This field is from variant [BetaMCPToolUseBlock]. + ServerName string `json:"server_name"` + // This field is from variant [BetaMCPToolResultBlock]. + IsError bool `json:"is_error"` + // This field is from variant [BetaContainerUploadBlock]. + FileID string `json:"file_id"` + // This field is from variant [BetaCompactionBlock]. + EncryptedContent string `json:"encrypted_content"` + // This field is from variant [BetaFallbackBlock]. + From BetaFallbackInfo `json:"from"` + // This field is from variant [BetaFallbackBlock]. + To BetaFallbackInfo `json:"to"` + // This field is from variant [BetaFallbackBlock]. + Trigger BetaFallbackRefusalTrigger `json:"trigger"` + JSON struct { + Citations respjson.Field + Text respjson.Field + Type respjson.Field + Signature respjson.Field + Thinking respjson.Field + Data respjson.Field + ID respjson.Field + Input respjson.Field + Name respjson.Field + Caller respjson.Field + ToolsetName respjson.Field + Content respjson.Field + ToolUseID respjson.Field + ServerName respjson.Field + IsError respjson.Field + FileID respjson.Field + EncryptedContent respjson.Field + From respjson.Field + To respjson.Field + Trigger respjson.Field + raw string } `json:"-"` } -func (u BetaToolSearchToolResultBlockContentUnion) AsResponseToolSearchToolResultError() (v BetaToolSearchToolResultError) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u BetaToolSearchToolResultBlockContentUnion) AsResponseToolSearchToolSearchResultBlock() (v BetaToolSearchToolSearchResultBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -// Returns the unmodified JSON received from the API -func (u BetaToolSearchToolResultBlockContentUnion) RawJSON() string { return u.JSON.raw } - -func (r *BetaToolSearchToolResultBlockContentUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The properties Content, ToolUseID, Type are required. -type BetaToolSearchToolResultBlockParam struct { - Content BetaToolSearchToolResultBlockParamContentUnion `json:"content,omitzero" api:"required"` - ToolUseID string `json:"tool_use_id" api:"required"` - // Create a cache control breakpoint at this content block. - CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` - // This field can be elided, and will marshal its zero value as - // "tool_search_tool_result". - Type constant.ToolSearchToolResult `json:"type" default:"tool_search_tool_result"` - paramObj +// anyBetaRawContentBlockStartEventContentBlock is implemented by each variant of +// [BetaRawContentBlockStartEventContentBlockUnion] to add type safety for the +// return type of [BetaRawContentBlockStartEventContentBlockUnion.AsAny] +type anyBetaRawContentBlockStartEventContentBlock interface { + implBetaRawContentBlockStartEventContentBlockUnion() } -func (r BetaToolSearchToolResultBlockParam) MarshalJSON() (data []byte, err error) { - type shadow BetaToolSearchToolResultBlockParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaToolSearchToolResultBlockParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +func (BetaTextBlock) implBetaRawContentBlockStartEventContentBlockUnion() {} +func (BetaThinkingBlock) implBetaRawContentBlockStartEventContentBlockUnion() {} +func (BetaRedactedThinkingBlock) implBetaRawContentBlockStartEventContentBlockUnion() {} +func (BetaToolUseBlock) implBetaRawContentBlockStartEventContentBlockUnion() {} +func (BetaServerToolUseBlock) implBetaRawContentBlockStartEventContentBlockUnion() {} +func (BetaWebSearchToolResultBlock) implBetaRawContentBlockStartEventContentBlockUnion() {} +func (BetaWebFetchToolResultBlock) implBetaRawContentBlockStartEventContentBlockUnion() {} +func (BetaAdvisorToolResultBlock) implBetaRawContentBlockStartEventContentBlockUnion() {} +func (BetaCodeExecutionToolResultBlock) implBetaRawContentBlockStartEventContentBlockUnion() {} +func (BetaBashCodeExecutionToolResultBlock) implBetaRawContentBlockStartEventContentBlockUnion() {} +func (BetaTextEditorCodeExecutionToolResultBlock) implBetaRawContentBlockStartEventContentBlockUnion() { } +func (BetaToolSearchToolResultBlock) implBetaRawContentBlockStartEventContentBlockUnion() {} +func (BetaMCPToolUseBlock) implBetaRawContentBlockStartEventContentBlockUnion() {} +func (BetaMCPToolResultBlock) implBetaRawContentBlockStartEventContentBlockUnion() {} +func (BetaContainerUploadBlock) implBetaRawContentBlockStartEventContentBlockUnion() {} +func (BetaCompactionBlock) implBetaRawContentBlockStartEventContentBlockUnion() {} +func (BetaFallbackBlock) implBetaRawContentBlockStartEventContentBlockUnion() {} -// Only one field can be non-zero. +// Use the following switch statement to find the correct variant // -// Use [param.IsOmitted] to confirm if a field is set. -type BetaToolSearchToolResultBlockParamContentUnion struct { - OfRequestToolSearchToolResultError *BetaToolSearchToolResultErrorParam `json:",omitzero,inline"` - OfRequestToolSearchToolSearchResultBlock *BetaToolSearchToolSearchResultBlockParam `json:",omitzero,inline"` - paramUnion -} - -func (u BetaToolSearchToolResultBlockParamContentUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfRequestToolSearchToolResultError, u.OfRequestToolSearchToolSearchResultBlock) -} -func (u *BetaToolSearchToolResultBlockParamContentUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *BetaToolSearchToolResultBlockParamContentUnion) asAny() any { - if !param.IsOmitted(u.OfRequestToolSearchToolResultError) { - return u.OfRequestToolSearchToolResultError - } else if !param.IsOmitted(u.OfRequestToolSearchToolSearchResultBlock) { - return u.OfRequestToolSearchToolSearchResultBlock +// switch variant := BetaRawContentBlockStartEventContentBlockUnion.AsAny().(type) { +// case anthropic.BetaTextBlock: +// case anthropic.BetaThinkingBlock: +// case anthropic.BetaRedactedThinkingBlock: +// case anthropic.BetaToolUseBlock: +// case anthropic.BetaServerToolUseBlock: +// case anthropic.BetaWebSearchToolResultBlock: +// case anthropic.BetaWebFetchToolResultBlock: +// case anthropic.BetaAdvisorToolResultBlock: +// case anthropic.BetaCodeExecutionToolResultBlock: +// case anthropic.BetaBashCodeExecutionToolResultBlock: +// case anthropic.BetaTextEditorCodeExecutionToolResultBlock: +// case anthropic.BetaToolSearchToolResultBlock: +// case anthropic.BetaMCPToolUseBlock: +// case anthropic.BetaMCPToolResultBlock: +// case anthropic.BetaContainerUploadBlock: +// case anthropic.BetaCompactionBlock: +// case anthropic.BetaFallbackBlock: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaRawContentBlockStartEventContentBlockUnion) AsAny() anyBetaRawContentBlockStartEventContentBlock { + switch u.Type { + case "text": + return u.AsText() + case "thinking": + return u.AsThinking() + case "redacted_thinking": + return u.AsRedactedThinking() + case "tool_use": + return u.AsToolUse() + case "server_tool_use": + return u.AsServerToolUse() + case "web_search_tool_result": + return u.AsWebSearchToolResult() + case "web_fetch_tool_result": + return u.AsWebFetchToolResult() + case "advisor_tool_result": + return u.AsAdvisorToolResult() + case "code_execution_tool_result": + return u.AsCodeExecutionToolResult() + case "bash_code_execution_tool_result": + return u.AsBashCodeExecutionToolResult() + case "text_editor_code_execution_tool_result": + return u.AsTextEditorCodeExecutionToolResult() + case "tool_search_tool_result": + return u.AsToolSearchToolResult() + case "mcp_tool_use": + return u.AsMCPToolUse() + case "mcp_tool_result": + return u.AsMCPToolResult() + case "container_upload": + return u.AsContainerUpload() + case "compaction": + return u.AsCompaction() + case "fallback": + return u.AsFallback() } return nil } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaToolSearchToolResultBlockParamContentUnion) GetErrorCode() *string { - if vt := u.OfRequestToolSearchToolResultError; vt != nil { - return (*string)(&vt.ErrorCode) - } - return nil +func (u BetaRawContentBlockStartEventContentBlockUnion) AsText() (v BetaTextBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaToolSearchToolResultBlockParamContentUnion) GetToolReferences() []BetaToolReferenceBlockParam { - if vt := u.OfRequestToolSearchToolSearchResultBlock; vt != nil { - return vt.ToolReferences - } - return nil +func (u BetaRawContentBlockStartEventContentBlockUnion) AsThinking() (v BetaThinkingBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaToolSearchToolResultBlockParamContentUnion) GetType() *string { - if vt := u.OfRequestToolSearchToolResultError; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfRequestToolSearchToolSearchResultBlock; vt != nil { - return (*string)(&vt.Type) - } - return nil +func (u BetaRawContentBlockStartEventContentBlockUnion) AsRedactedThinking() (v BetaRedactedThinkingBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -type BetaToolSearchToolResultError struct { - // Any of "invalid_tool_input", "unavailable", "too_many_requests", - // "execution_time_exceeded". - ErrorCode BetaToolSearchToolResultErrorErrorCode `json:"error_code" api:"required"` - ErrorMessage string `json:"error_message" api:"required"` - Type constant.ToolSearchToolResultError `json:"type" default:"tool_search_tool_result_error"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ErrorCode respjson.Field - ErrorMessage respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +func (u BetaRawContentBlockStartEventContentBlockUnion) AsToolUse() (v BetaToolUseBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -// Returns the unmodified JSON received from the API -func (r BetaToolSearchToolResultError) RawJSON() string { return r.JSON.raw } -func (r *BetaToolSearchToolResultError) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +func (u BetaRawContentBlockStartEventContentBlockUnion) AsServerToolUse() (v BetaServerToolUseBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -type BetaToolSearchToolResultErrorErrorCode string +func (u BetaRawContentBlockStartEventContentBlockUnion) AsWebSearchToolResult() (v BetaWebSearchToolResultBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} -const ( - BetaToolSearchToolResultErrorErrorCodeInvalidToolInput BetaToolSearchToolResultErrorErrorCode = "invalid_tool_input" - BetaToolSearchToolResultErrorErrorCodeUnavailable BetaToolSearchToolResultErrorErrorCode = "unavailable" - BetaToolSearchToolResultErrorErrorCodeTooManyRequests BetaToolSearchToolResultErrorErrorCode = "too_many_requests" - BetaToolSearchToolResultErrorErrorCodeExecutionTimeExceeded BetaToolSearchToolResultErrorErrorCode = "execution_time_exceeded" -) +func (u BetaRawContentBlockStartEventContentBlockUnion) AsWebFetchToolResult() (v BetaWebFetchToolResultBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} -// The properties ErrorCode, Type are required. -type BetaToolSearchToolResultErrorParam struct { - // Any of "invalid_tool_input", "unavailable", "too_many_requests", - // "execution_time_exceeded". - ErrorCode BetaToolSearchToolResultErrorParamErrorCode `json:"error_code,omitzero" api:"required"` - // This field can be elided, and will marshal its zero value as - // "tool_search_tool_result_error". - Type constant.ToolSearchToolResultError `json:"type" default:"tool_search_tool_result_error"` - paramObj +func (u BetaRawContentBlockStartEventContentBlockUnion) AsAdvisorToolResult() (v BetaAdvisorToolResultBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -func (r BetaToolSearchToolResultErrorParam) MarshalJSON() (data []byte, err error) { - type shadow BetaToolSearchToolResultErrorParam - return param.MarshalObject(r, (*shadow)(&r)) +func (u BetaRawContentBlockStartEventContentBlockUnion) AsCodeExecutionToolResult() (v BetaCodeExecutionToolResultBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -func (r *BetaToolSearchToolResultErrorParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) + +func (u BetaRawContentBlockStartEventContentBlockUnion) AsBashCodeExecutionToolResult() (v BetaBashCodeExecutionToolResultBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -type BetaToolSearchToolResultErrorParamErrorCode string +func (u BetaRawContentBlockStartEventContentBlockUnion) AsTextEditorCodeExecutionToolResult() (v BetaTextEditorCodeExecutionToolResultBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} -const ( - BetaToolSearchToolResultErrorParamErrorCodeInvalidToolInput BetaToolSearchToolResultErrorParamErrorCode = "invalid_tool_input" - BetaToolSearchToolResultErrorParamErrorCodeUnavailable BetaToolSearchToolResultErrorParamErrorCode = "unavailable" - BetaToolSearchToolResultErrorParamErrorCodeTooManyRequests BetaToolSearchToolResultErrorParamErrorCode = "too_many_requests" - BetaToolSearchToolResultErrorParamErrorCodeExecutionTimeExceeded BetaToolSearchToolResultErrorParamErrorCode = "execution_time_exceeded" -) +func (u BetaRawContentBlockStartEventContentBlockUnion) AsToolSearchToolResult() (v BetaToolSearchToolResultBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} -type BetaToolSearchToolSearchResultBlock struct { - ToolReferences []BetaToolReferenceBlock `json:"tool_references" api:"required"` - Type constant.ToolSearchToolSearchResult `json:"type" default:"tool_search_tool_search_result"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ToolReferences respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +func (u BetaRawContentBlockStartEventContentBlockUnion) AsMCPToolUse() (v BetaMCPToolUseBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -// Returns the unmodified JSON received from the API -func (r BetaToolSearchToolSearchResultBlock) RawJSON() string { return r.JSON.raw } -func (r *BetaToolSearchToolSearchResultBlock) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +func (u BetaRawContentBlockStartEventContentBlockUnion) AsMCPToolResult() (v BetaMCPToolResultBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -// The properties ToolReferences, Type are required. -type BetaToolSearchToolSearchResultBlockParam struct { - ToolReferences []BetaToolReferenceBlockParam `json:"tool_references,omitzero" api:"required"` - // This field can be elided, and will marshal its zero value as - // "tool_search_tool_search_result". - Type constant.ToolSearchToolSearchResult `json:"type" default:"tool_search_tool_search_result"` - paramObj +func (u BetaRawContentBlockStartEventContentBlockUnion) AsContainerUpload() (v BetaContainerUploadBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -func (r BetaToolSearchToolSearchResultBlockParam) MarshalJSON() (data []byte, err error) { - type shadow BetaToolSearchToolSearchResultBlockParam - return param.MarshalObject(r, (*shadow)(&r)) +func (u BetaRawContentBlockStartEventContentBlockUnion) AsCompaction() (v BetaCompactionBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -func (r *BetaToolSearchToolSearchResultBlockParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) + +func (u BetaRawContentBlockStartEventContentBlockUnion) AsFallback() (v BetaFallbackBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -// The properties Name, Type are required. -type BetaToolTextEditor20241022Param struct { - // If true, tool will not be included in initial system prompt. Only loaded when - // returned via tool_reference from tool search. - DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` - // When true, guarantees schema validation on tool names and inputs - Strict param.Opt[bool] `json:"strict,omitzero"` - // Any of "direct", "code_execution_20250825", "code_execution_20260120". - AllowedCallers []string `json:"allowed_callers,omitzero"` - // Create a cache control breakpoint at this content block. - CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` - InputExamples []map[string]any `json:"input_examples,omitzero"` - // Name of the tool. - // - // This is how the tool will be called by the model and in `tool_use` blocks. - // - // This field can be elided, and will marshal its zero value as - // "str_replace_editor". - Name constant.StrReplaceEditor `json:"name" default:"str_replace_editor"` - // This field can be elided, and will marshal its zero value as - // "text_editor_20241022". - Type constant.TextEditor20241022 `json:"type" default:"text_editor_20241022"` - paramObj +// Returns the unmodified JSON received from the API +func (u BetaRawContentBlockStartEventContentBlockUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaRawContentBlockStartEventContentBlockUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func (r BetaToolTextEditor20241022Param) MarshalJSON() (data []byte, err error) { - type shadow BetaToolTextEditor20241022Param - return param.MarshalObject(r, (*shadow)(&r)) +// BetaRawContentBlockStartEventContentBlockUnionCaller is an implicit subunion of +// [BetaRawContentBlockStartEventContentBlockUnion]. +// BetaRawContentBlockStartEventContentBlockUnionCaller provides convenient access +// to the sub-properties of the union. +// +// For type safety it is recommended to directly use a variant of the +// [BetaRawContentBlockStartEventContentBlockUnion]. +type BetaRawContentBlockStartEventContentBlockUnionCaller struct { + Type string `json:"type"` + ToolID string `json:"tool_id"` + JSON struct { + Type respjson.Field + ToolID respjson.Field + raw string + } `json:"-"` } -func (r *BetaToolTextEditor20241022Param) UnmarshalJSON(data []byte) error { + +func (r *BetaRawContentBlockStartEventContentBlockUnionCaller) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The properties Name, Type are required. -type BetaToolTextEditor20250124Param struct { - // If true, tool will not be included in initial system prompt. Only loaded when - // returned via tool_reference from tool search. - DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` - // When true, guarantees schema validation on tool names and inputs - Strict param.Opt[bool] `json:"strict,omitzero"` - // Any of "direct", "code_execution_20250825", "code_execution_20260120". - AllowedCallers []string `json:"allowed_callers,omitzero"` - // Create a cache control breakpoint at this content block. - CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` - InputExamples []map[string]any `json:"input_examples,omitzero"` - // Name of the tool. - // - // This is how the tool will be called by the model and in `tool_use` blocks. - // - // This field can be elided, and will marshal its zero value as - // "str_replace_editor". - Name constant.StrReplaceEditor `json:"name" default:"str_replace_editor"` - // This field can be elided, and will marshal its zero value as - // "text_editor_20250124". - Type constant.TextEditor20250124 `json:"type" default:"text_editor_20250124"` - paramObj +// BetaRawContentBlockStartEventContentBlockUnionContent is an implicit subunion of +// [BetaRawContentBlockStartEventContentBlockUnion]. +// BetaRawContentBlockStartEventContentBlockUnionContent provides convenient access +// to the sub-properties of the union. +// +// For type safety it is recommended to directly use a variant of the +// [BetaRawContentBlockStartEventContentBlockUnion]. +// +// If the underlying value is not a json object, one of the following properties +// will be valid: OfBetaWebSearchResultBlockArray OfString +// OfBetaMCPToolResultBlockContent] +type BetaRawContentBlockStartEventContentBlockUnionContent struct { + // This field will be present if the value is a [[]BetaWebSearchResultBlock] + // instead of an object. + OfBetaWebSearchResultBlockArray []BetaWebSearchResultBlock `json:",inline"` + // This field will be present if the value is a [string] instead of an object. + OfString string `json:",inline"` + // This field will be present if the value is a [[]BetaTextBlock] instead of an + // object. + OfBetaMCPToolResultBlockContent []BetaTextBlock `json:",inline"` + ErrorCode string `json:"error_code"` + Type string `json:"type"` + // This field is a union of [BetaDocumentBlock], [[]BetaCodeExecutionOutputBlock], + // [[]BetaCodeExecutionOutputBlock], [[]BetaBashCodeExecutionOutputBlock], [string] + Content BetaRawContentBlockStartEventContentBlockUnionContentContent `json:"content"` + // This field is from variant [BetaWebFetchToolResultBlockContentUnion]. + RetrievedAt string `json:"retrieved_at"` + // This field is from variant [BetaWebFetchToolResultBlockContentUnion]. + URL string `json:"url"` + StopReason string `json:"stop_reason"` + // This field is from variant [BetaAdvisorToolResultBlockContentUnion]. + Text string `json:"text"` + // This field is from variant [BetaAdvisorToolResultBlockContentUnion]. + EncryptedContent string `json:"encrypted_content"` + ReturnCode int64 `json:"return_code"` + Stderr string `json:"stderr"` + Stdout string `json:"stdout"` + // This field is from variant [BetaCodeExecutionToolResultBlockContentUnion]. + EncryptedStdout string `json:"encrypted_stdout"` + ErrorMessage string `json:"error_message"` + // This field is from variant + // [BetaTextEditorCodeExecutionToolResultBlockContentUnion]. + FileType BetaTextEditorCodeExecutionViewResultBlockFileType `json:"file_type"` + // This field is from variant + // [BetaTextEditorCodeExecutionToolResultBlockContentUnion]. + NumLines int64 `json:"num_lines"` + // This field is from variant + // [BetaTextEditorCodeExecutionToolResultBlockContentUnion]. + StartLine int64 `json:"start_line"` + // This field is from variant + // [BetaTextEditorCodeExecutionToolResultBlockContentUnion]. + TotalLines int64 `json:"total_lines"` + // This field is from variant + // [BetaTextEditorCodeExecutionToolResultBlockContentUnion]. + IsFileUpdate bool `json:"is_file_update"` + // This field is from variant + // [BetaTextEditorCodeExecutionToolResultBlockContentUnion]. + Lines []string `json:"lines"` + // This field is from variant + // [BetaTextEditorCodeExecutionToolResultBlockContentUnion]. + NewLines int64 `json:"new_lines"` + // This field is from variant + // [BetaTextEditorCodeExecutionToolResultBlockContentUnion]. + NewStart int64 `json:"new_start"` + // This field is from variant + // [BetaTextEditorCodeExecutionToolResultBlockContentUnion]. + OldLines int64 `json:"old_lines"` + // This field is from variant + // [BetaTextEditorCodeExecutionToolResultBlockContentUnion]. + OldStart int64 `json:"old_start"` + // This field is from variant [BetaToolSearchToolResultBlockContentUnion]. + ToolReferences []BetaToolReferenceBlock `json:"tool_references"` + JSON struct { + OfBetaWebSearchResultBlockArray respjson.Field + OfString respjson.Field + OfBetaMCPToolResultBlockContent respjson.Field + ErrorCode respjson.Field + Type respjson.Field + Content respjson.Field + RetrievedAt respjson.Field + URL respjson.Field + StopReason respjson.Field + Text respjson.Field + EncryptedContent respjson.Field + ReturnCode respjson.Field + Stderr respjson.Field + Stdout respjson.Field + EncryptedStdout respjson.Field + ErrorMessage respjson.Field + FileType respjson.Field + NumLines respjson.Field + StartLine respjson.Field + TotalLines respjson.Field + IsFileUpdate respjson.Field + Lines respjson.Field + NewLines respjson.Field + NewStart respjson.Field + OldLines respjson.Field + OldStart respjson.Field + ToolReferences respjson.Field + raw string + } `json:"-"` } -func (r BetaToolTextEditor20250124Param) MarshalJSON() (data []byte, err error) { - type shadow BetaToolTextEditor20250124Param - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaToolTextEditor20250124Param) UnmarshalJSON(data []byte) error { +func (r *BetaRawContentBlockStartEventContentBlockUnionContent) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The properties Name, Type are required. -type BetaToolTextEditor20250429Param struct { - // If true, tool will not be included in initial system prompt. Only loaded when - // returned via tool_reference from tool search. - DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` - // When true, guarantees schema validation on tool names and inputs - Strict param.Opt[bool] `json:"strict,omitzero"` - // Any of "direct", "code_execution_20250825", "code_execution_20260120". - AllowedCallers []string `json:"allowed_callers,omitzero"` - // Create a cache control breakpoint at this content block. - CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` - InputExamples []map[string]any `json:"input_examples,omitzero"` - // Name of the tool. - // - // This is how the tool will be called by the model and in `tool_use` blocks. - // - // This field can be elided, and will marshal its zero value as - // "str_replace_based_edit_tool". - Name constant.StrReplaceBasedEditTool `json:"name" default:"str_replace_based_edit_tool"` - // This field can be elided, and will marshal its zero value as - // "text_editor_20250429". - Type constant.TextEditor20250429 `json:"type" default:"text_editor_20250429"` - paramObj +// BetaRawContentBlockStartEventContentBlockUnionContentContent is an implicit +// subunion of [BetaRawContentBlockStartEventContentBlockUnion]. +// BetaRawContentBlockStartEventContentBlockUnionContentContent provides convenient +// access to the sub-properties of the union. +// +// For type safety it is recommended to directly use a variant of the +// [BetaRawContentBlockStartEventContentBlockUnion]. +// +// If the underlying value is not a json object, one of the following properties +// will be valid: OfContent OfString] +type BetaRawContentBlockStartEventContentBlockUnionContentContent struct { + // This field will be present if the value is a [[]BetaCodeExecutionOutputBlock] + // instead of an object. + OfContent []BetaCodeExecutionOutputBlock `json:",inline"` + // This field will be present if the value is a [string] instead of an object. + OfString string `json:",inline"` + // This field is from variant [BetaDocumentBlock]. + Citations BetaCitationConfig `json:"citations"` + // This field is from variant [BetaDocumentBlock]. + Source BetaDocumentBlockSourceUnion `json:"source"` + // This field is from variant [BetaDocumentBlock]. + Title string `json:"title"` + // This field is from variant [BetaDocumentBlock]. + Type constant.Document `json:"type"` + JSON struct { + OfContent respjson.Field + OfString respjson.Field + Citations respjson.Field + Source respjson.Field + Title respjson.Field + Type respjson.Field + raw string + } `json:"-"` } -func (r BetaToolTextEditor20250429Param) MarshalJSON() (data []byte, err error) { - type shadow BetaToolTextEditor20250429Param - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaToolTextEditor20250429Param) UnmarshalJSON(data []byte) error { +func (r *BetaRawContentBlockStartEventContentBlockUnionContentContent) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The properties Name, Type are required. -type BetaToolTextEditor20250728Param struct { - // Maximum number of characters to display when viewing a file. If not specified, - // defaults to displaying the full file. - MaxCharacters param.Opt[int64] `json:"max_characters,omitzero"` - // If true, tool will not be included in initial system prompt. Only loaded when - // returned via tool_reference from tool search. - DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` - // When true, guarantees schema validation on tool names and inputs - Strict param.Opt[bool] `json:"strict,omitzero"` - // Any of "direct", "code_execution_20250825", "code_execution_20260120". - AllowedCallers []string `json:"allowed_callers,omitzero"` - // Create a cache control breakpoint at this content block. - CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` - InputExamples []map[string]any `json:"input_examples,omitzero"` - // Name of the tool. - // - // This is how the tool will be called by the model and in `tool_use` blocks. - // - // This field can be elided, and will marshal its zero value as - // "str_replace_based_edit_tool". - Name constant.StrReplaceBasedEditTool `json:"name" default:"str_replace_based_edit_tool"` - // This field can be elided, and will marshal its zero value as - // "text_editor_20250728". - Type constant.TextEditor20250728 `json:"type" default:"text_editor_20250728"` - paramObj +type BetaRawContentBlockStopEvent struct { + Index int64 `json:"index" api:"required"` + Type constant.ContentBlockStop `json:"type" default:"content_block_stop"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Index respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` } -func (r BetaToolTextEditor20250728Param) MarshalJSON() (data []byte, err error) { - type shadow BetaToolTextEditor20250728Param - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaToolTextEditor20250728Param) UnmarshalJSON(data []byte) error { +// Returns the unmodified JSON received from the API +func (r BetaRawContentBlockStopEvent) RawJSON() string { return r.JSON.raw } +func (r *BetaRawContentBlockStopEvent) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -func BetaToolUnionParamOfTool(inputSchema BetaToolInputSchemaParam, name string) BetaToolUnionParam { - var variant BetaToolParam - variant.InputSchema = inputSchema - variant.Name = name - return BetaToolUnionParam{OfTool: &variant} -} - -func BetaToolUnionParamOfComputerUseTool20241022(displayHeightPx int64, displayWidthPx int64) BetaToolUnionParam { - var variant BetaToolComputerUse20241022Param - variant.DisplayHeightPx = displayHeightPx - variant.DisplayWidthPx = displayWidthPx - return BetaToolUnionParam{OfComputerUseTool20241022: &variant} -} - -func BetaToolUnionParamOfComputerUseTool20250124(displayHeightPx int64, displayWidthPx int64) BetaToolUnionParam { - var variant BetaToolComputerUse20250124Param - variant.DisplayHeightPx = displayHeightPx - variant.DisplayWidthPx = displayWidthPx - return BetaToolUnionParam{OfComputerUseTool20250124: &variant} -} - -func BetaToolUnionParamOfComputerUseTool20251124(displayHeightPx int64, displayWidthPx int64) BetaToolUnionParam { - var variant BetaToolComputerUse20251124Param - variant.DisplayHeightPx = displayHeightPx - variant.DisplayWidthPx = displayWidthPx - return BetaToolUnionParam{OfComputerUseTool20251124: &variant} +type BetaRawMessageDeltaEvent struct { + // Information about context management strategies applied during the request + ContextManagement BetaContextManagementResponse `json:"context_management" api:"required"` + Delta BetaRawMessageDeltaEventDelta `json:"delta" api:"required"` + Type constant.MessageDelta `json:"type" default:"message_delta"` + // Billing and rate-limit usage. + // + // Anthropic's API bills and rate-limits by token counts, as tokens represent the + // underlying cost to our systems. + // + // Under the hood, the API transforms requests into a format suitable for the + // model. The model's output then goes through a parsing stage before becoming an + // API response. As a result, the token counts in `usage` will not match one-to-one + // with the exact visible content of an API request or response. + // + // For example, `output_tokens` will be non-zero, even for an empty string response + // from Claude. + // + // Total input tokens in a request is the summation of `input_tokens`, + // `cache_creation_input_tokens`, and `cache_read_input_tokens`. + Usage BetaMessageDeltaUsage `json:"usage" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ContextManagement respjson.Field + Delta respjson.Field + Type respjson.Field + Usage respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` } -func BetaToolUnionParamOfAdvisorTool20260301(model Model) BetaToolUnionParam { - var variant BetaAdvisorTool20260301Param - variant.Model = model - return BetaToolUnionParam{OfAdvisorTool20260301: &variant} +// Returns the unmodified JSON received from the API +func (r BetaRawMessageDeltaEvent) RawJSON() string { return r.JSON.raw } +func (r *BetaRawMessageDeltaEvent) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func BetaToolUnionParamOfToolSearchToolBm25_20251119(type_ BetaToolSearchToolBm25_20251119Type) BetaToolUnionParam { - var variant BetaToolSearchToolBm25_20251119Param - variant.Type = type_ - return BetaToolUnionParam{OfToolSearchToolBm25_20251119: &variant} +type BetaRawMessageDeltaEventDelta struct { + // Information about the container used in the request (for the code execution + // tool) + Container BetaContainer `json:"container" api:"required"` + // Structured information about a refusal. + StopDetails BetaRefusalStopDetails `json:"stop_details" api:"required"` + // Any of "end_turn", "max_tokens", "stop_sequence", "tool_use", "pause_turn", + // "compaction", "refusal", "model_context_window_exceeded". + StopReason BetaStopReason `json:"stop_reason" api:"required"` + StopSequence string `json:"stop_sequence" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Container respjson.Field + StopDetails respjson.Field + StopReason respjson.Field + StopSequence respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` } -func BetaToolUnionParamOfToolSearchToolRegex20251119(type_ BetaToolSearchToolRegex20251119Type) BetaToolUnionParam { - var variant BetaToolSearchToolRegex20251119Param - variant.Type = type_ - return BetaToolUnionParam{OfToolSearchToolRegex20251119: &variant} +// Returns the unmodified JSON received from the API +func (r BetaRawMessageDeltaEventDelta) RawJSON() string { return r.JSON.raw } +func (r *BetaRawMessageDeltaEventDelta) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func BetaToolUnionParamOfMCPToolset(mcpServerName string) BetaToolUnionParam { - var variant BetaMCPToolsetParam - variant.MCPServerName = mcpServerName - return BetaToolUnionParam{OfMCPToolset: &variant} +type BetaRawMessageStartEvent struct { + Message BetaMessage `json:"message" api:"required"` + Type constant.MessageStart `json:"type" default:"message_start"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Message respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` } -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type BetaToolUnionParam struct { - OfTool *BetaToolParam `json:",omitzero,inline"` - OfBashTool20241022 *BetaToolBash20241022Param `json:",omitzero,inline"` - OfBashTool20250124 *BetaToolBash20250124Param `json:",omitzero,inline"` - OfCodeExecutionTool20250522 *BetaCodeExecutionTool20250522Param `json:",omitzero,inline"` - OfCodeExecutionTool20250825 *BetaCodeExecutionTool20250825Param `json:",omitzero,inline"` - OfCodeExecutionTool20260120 *BetaCodeExecutionTool20260120Param `json:",omitzero,inline"` - OfComputerUseTool20241022 *BetaToolComputerUse20241022Param `json:",omitzero,inline"` - OfMemoryTool20250818 *BetaMemoryTool20250818Param `json:",omitzero,inline"` - OfComputerUseTool20250124 *BetaToolComputerUse20250124Param `json:",omitzero,inline"` - OfTextEditor20241022 *BetaToolTextEditor20241022Param `json:",omitzero,inline"` - OfComputerUseTool20251124 *BetaToolComputerUse20251124Param `json:",omitzero,inline"` - OfTextEditor20250124 *BetaToolTextEditor20250124Param `json:",omitzero,inline"` - OfTextEditor20250429 *BetaToolTextEditor20250429Param `json:",omitzero,inline"` - OfTextEditor20250728 *BetaToolTextEditor20250728Param `json:",omitzero,inline"` - OfWebSearchTool20250305 *BetaWebSearchTool20250305Param `json:",omitzero,inline"` - OfWebFetchTool20250910 *BetaWebFetchTool20250910Param `json:",omitzero,inline"` - OfWebSearchTool20260209 *BetaWebSearchTool20260209Param `json:",omitzero,inline"` - OfWebFetchTool20260209 *BetaWebFetchTool20260209Param `json:",omitzero,inline"` - OfWebFetchTool20260309 *BetaWebFetchTool20260309Param `json:",omitzero,inline"` - OfAdvisorTool20260301 *BetaAdvisorTool20260301Param `json:",omitzero,inline"` - OfToolSearchToolBm25_20251119 *BetaToolSearchToolBm25_20251119Param `json:",omitzero,inline"` - OfToolSearchToolRegex20251119 *BetaToolSearchToolRegex20251119Param `json:",omitzero,inline"` - OfMCPToolset *BetaMCPToolsetParam `json:",omitzero,inline"` - paramUnion +// Returns the unmodified JSON received from the API +func (r BetaRawMessageStartEvent) RawJSON() string { return r.JSON.raw } +func (r *BetaRawMessageStartEvent) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func (u BetaToolUnionParam) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfTool, - u.OfBashTool20241022, - u.OfBashTool20250124, - u.OfCodeExecutionTool20250522, - u.OfCodeExecutionTool20250825, - u.OfCodeExecutionTool20260120, - u.OfComputerUseTool20241022, - u.OfMemoryTool20250818, - u.OfComputerUseTool20250124, - u.OfTextEditor20241022, - u.OfComputerUseTool20251124, - u.OfTextEditor20250124, - u.OfTextEditor20250429, - u.OfTextEditor20250728, - u.OfWebSearchTool20250305, - u.OfWebFetchTool20250910, - u.OfWebSearchTool20260209, - u.OfWebFetchTool20260209, - u.OfWebFetchTool20260309, - u.OfAdvisorTool20260301, - u.OfToolSearchToolBm25_20251119, - u.OfToolSearchToolRegex20251119, - u.OfMCPToolset) -} -func (u *BetaToolUnionParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) +type BetaRawMessageStopEvent struct { + Type constant.MessageStop `json:"type" default:"message_stop"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` } -func (u *BetaToolUnionParam) asAny() any { - if !param.IsOmitted(u.OfTool) { - return u.OfTool - } else if !param.IsOmitted(u.OfBashTool20241022) { - return u.OfBashTool20241022 - } else if !param.IsOmitted(u.OfBashTool20250124) { - return u.OfBashTool20250124 - } else if !param.IsOmitted(u.OfCodeExecutionTool20250522) { - return u.OfCodeExecutionTool20250522 - } else if !param.IsOmitted(u.OfCodeExecutionTool20250825) { - return u.OfCodeExecutionTool20250825 - } else if !param.IsOmitted(u.OfCodeExecutionTool20260120) { - return u.OfCodeExecutionTool20260120 - } else if !param.IsOmitted(u.OfComputerUseTool20241022) { - return u.OfComputerUseTool20241022 - } else if !param.IsOmitted(u.OfMemoryTool20250818) { - return u.OfMemoryTool20250818 - } else if !param.IsOmitted(u.OfComputerUseTool20250124) { - return u.OfComputerUseTool20250124 - } else if !param.IsOmitted(u.OfTextEditor20241022) { - return u.OfTextEditor20241022 - } else if !param.IsOmitted(u.OfComputerUseTool20251124) { - return u.OfComputerUseTool20251124 - } else if !param.IsOmitted(u.OfTextEditor20250124) { - return u.OfTextEditor20250124 - } else if !param.IsOmitted(u.OfTextEditor20250429) { - return u.OfTextEditor20250429 - } else if !param.IsOmitted(u.OfTextEditor20250728) { - return u.OfTextEditor20250728 - } else if !param.IsOmitted(u.OfWebSearchTool20250305) { - return u.OfWebSearchTool20250305 - } else if !param.IsOmitted(u.OfWebFetchTool20250910) { - return u.OfWebFetchTool20250910 - } else if !param.IsOmitted(u.OfWebSearchTool20260209) { - return u.OfWebSearchTool20260209 - } else if !param.IsOmitted(u.OfWebFetchTool20260209) { - return u.OfWebFetchTool20260209 - } else if !param.IsOmitted(u.OfWebFetchTool20260309) { - return u.OfWebFetchTool20260309 - } else if !param.IsOmitted(u.OfAdvisorTool20260301) { - return u.OfAdvisorTool20260301 - } else if !param.IsOmitted(u.OfToolSearchToolBm25_20251119) { - return u.OfToolSearchToolBm25_20251119 - } else if !param.IsOmitted(u.OfToolSearchToolRegex20251119) { - return u.OfToolSearchToolRegex20251119 - } else if !param.IsOmitted(u.OfMCPToolset) { - return u.OfMCPToolset - } - return nil +// Returns the unmodified JSON received from the API +func (r BetaRawMessageStopEvent) RawJSON() string { return r.JSON.raw } +func (r *BetaRawMessageStopEvent) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaToolUnionParam) GetInputSchema() *BetaToolInputSchemaParam { - if vt := u.OfTool; vt != nil { - return &vt.InputSchema - } - return nil +// BetaRawMessageStreamEventUnion contains all possible properties and values from +// [BetaRawMessageStartEvent], [BetaRawMessageDeltaEvent], +// [BetaRawMessageStopEvent], [BetaRawContentBlockStartEvent], +// [BetaRawContentBlockDeltaEvent], [BetaRawContentBlockStopEvent]. +// +// Use the [BetaRawMessageStreamEventUnion.AsAny] method to switch on the variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaRawMessageStreamEventUnion struct { + // This field is from variant [BetaRawMessageStartEvent]. + Message BetaMessage `json:"message"` + // Any of "message_start", "message_delta", "message_stop", "content_block_start", + // "content_block_delta", "content_block_stop". + Type string `json:"type"` + // This field is from variant [BetaRawMessageDeltaEvent]. + ContextManagement BetaContextManagementResponse `json:"context_management"` + // This field is a union of [BetaRawMessageDeltaEventDelta], + // [BetaRawContentBlockDeltaUnion] + Delta BetaRawMessageStreamEventUnionDelta `json:"delta"` + // This field is from variant [BetaRawMessageDeltaEvent]. + Usage BetaMessageDeltaUsage `json:"usage"` + // This field is from variant [BetaRawContentBlockStartEvent]. + ContentBlock BetaRawContentBlockStartEventContentBlockUnion `json:"content_block"` + Index int64 `json:"index"` + JSON struct { + Message respjson.Field + Type respjson.Field + ContextManagement respjson.Field + Delta respjson.Field + Usage respjson.Field + ContentBlock respjson.Field + Index respjson.Field + raw string + } `json:"-"` } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaToolUnionParam) GetDescription() *string { - if vt := u.OfTool; vt != nil && vt.Description.Valid() { - return &vt.Description.Value - } - return nil +// anyBetaRawMessageStreamEvent is implemented by each variant of +// [BetaRawMessageStreamEventUnion] to add type safety for the return type of +// [BetaRawMessageStreamEventUnion.AsAny] +type anyBetaRawMessageStreamEvent interface { + implBetaRawMessageStreamEventUnion() } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaToolUnionParam) GetEagerInputStreaming() *bool { - if vt := u.OfTool; vt != nil && vt.EagerInputStreaming.Valid() { - return &vt.EagerInputStreaming.Value - } - return nil -} +func (BetaRawMessageStartEvent) implBetaRawMessageStreamEventUnion() {} +func (BetaRawMessageDeltaEvent) implBetaRawMessageStreamEventUnion() {} +func (BetaRawMessageStopEvent) implBetaRawMessageStreamEventUnion() {} +func (BetaRawContentBlockStartEvent) implBetaRawMessageStreamEventUnion() {} +func (BetaRawContentBlockDeltaEvent) implBetaRawMessageStreamEventUnion() {} +func (BetaRawContentBlockStopEvent) implBetaRawMessageStreamEventUnion() {} -// Returns a pointer to the underlying variant's property, if present. -func (u BetaToolUnionParam) GetEnableZoom() *bool { - if vt := u.OfComputerUseTool20251124; vt != nil && vt.EnableZoom.Valid() { - return &vt.EnableZoom.Value +// Use the following switch statement to find the correct variant +// +// switch variant := BetaRawMessageStreamEventUnion.AsAny().(type) { +// case anthropic.BetaRawMessageStartEvent: +// case anthropic.BetaRawMessageDeltaEvent: +// case anthropic.BetaRawMessageStopEvent: +// case anthropic.BetaRawContentBlockStartEvent: +// case anthropic.BetaRawContentBlockDeltaEvent: +// case anthropic.BetaRawContentBlockStopEvent: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaRawMessageStreamEventUnion) AsAny() anyBetaRawMessageStreamEvent { + switch u.Type { + case "message_start": + return u.AsMessageStart() + case "message_delta": + return u.AsMessageDelta() + case "message_stop": + return u.AsMessageStop() + case "content_block_start": + return u.AsContentBlockStart() + case "content_block_delta": + return u.AsContentBlockDelta() + case "content_block_stop": + return u.AsContentBlockStop() } return nil } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaToolUnionParam) GetMaxCharacters() *int64 { - if vt := u.OfTextEditor20250728; vt != nil && vt.MaxCharacters.Valid() { - return &vt.MaxCharacters.Value - } - return nil +func (u BetaRawMessageStreamEventUnion) AsMessageStart() (v BetaRawMessageStartEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaToolUnionParam) GetUseCache() *bool { - if vt := u.OfWebFetchTool20260309; vt != nil && vt.UseCache.Valid() { - return &vt.UseCache.Value - } - return nil +func (u BetaRawMessageStreamEventUnion) AsMessageDelta() (v BetaRawMessageDeltaEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaToolUnionParam) GetModel() *Model { - if vt := u.OfAdvisorTool20260301; vt != nil { - return &vt.Model - } - return nil +func (u BetaRawMessageStreamEventUnion) AsMessageStop() (v BetaRawMessageStopEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaToolUnionParam) GetCaching() *BetaCacheControlEphemeralParam { - if vt := u.OfAdvisorTool20260301; vt != nil { - return &vt.Caching - } - return nil +func (u BetaRawMessageStreamEventUnion) AsContentBlockStart() (v BetaRawContentBlockStartEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaToolUnionParam) GetMCPServerName() *string { - if vt := u.OfMCPToolset; vt != nil { - return &vt.MCPServerName - } - return nil +func (u BetaRawMessageStreamEventUnion) AsContentBlockDelta() (v BetaRawContentBlockDeltaEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaToolUnionParam) GetConfigs() map[string]BetaMCPToolConfigParam { - if vt := u.OfMCPToolset; vt != nil { - return vt.Configs - } - return nil +func (u BetaRawMessageStreamEventUnion) AsContentBlockStop() (v BetaRawContentBlockStopEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaToolUnionParam) GetDefaultConfig() *BetaMCPToolDefaultConfigParam { - if vt := u.OfMCPToolset; vt != nil { - return &vt.DefaultConfig - } - return nil +// Returns the unmodified JSON received from the API +func (u BetaRawMessageStreamEventUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaRawMessageStreamEventUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaToolUnionParam) GetName() *string { - if vt := u.OfTool; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfBashTool20241022; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfBashTool20250124; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfCodeExecutionTool20250522; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfCodeExecutionTool20250825; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfCodeExecutionTool20260120; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfComputerUseTool20241022; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfMemoryTool20250818; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfComputerUseTool20250124; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfTextEditor20241022; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfComputerUseTool20251124; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfTextEditor20250124; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfTextEditor20250429; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfTextEditor20250728; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfWebSearchTool20250305; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfWebFetchTool20250910; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfWebSearchTool20260209; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfWebFetchTool20260209; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfWebFetchTool20260309; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfAdvisorTool20260301; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfToolSearchToolRegex20251119; vt != nil { - return (*string)(&vt.Name) - } - return nil +// BetaRawMessageStreamEventUnionDelta is an implicit subunion of +// [BetaRawMessageStreamEventUnion]. BetaRawMessageStreamEventUnionDelta provides +// convenient access to the sub-properties of the union. +// +// For type safety it is recommended to directly use a variant of the +// [BetaRawMessageStreamEventUnion]. +type BetaRawMessageStreamEventUnionDelta struct { + // This field is from variant [BetaRawMessageDeltaEventDelta]. + Container BetaContainer `json:"container"` + // This field is from variant [BetaRawMessageDeltaEventDelta]. + StopDetails BetaRefusalStopDetails `json:"stop_details"` + // This field is from variant [BetaRawMessageDeltaEventDelta]. + StopReason BetaStopReason `json:"stop_reason"` + // This field is from variant [BetaRawMessageDeltaEventDelta]. + StopSequence string `json:"stop_sequence"` + // This field is from variant [BetaRawContentBlockDeltaUnion]. + Text string `json:"text"` + Type string `json:"type"` + // This field is from variant [BetaRawContentBlockDeltaUnion]. + PartialJSON string `json:"partial_json"` + // This field is from variant [BetaRawContentBlockDeltaUnion]. + Citation BetaCitationsDeltaCitationUnion `json:"citation"` + // This field is from variant [BetaRawContentBlockDeltaUnion]. + EstimatedTokens int64 `json:"estimated_tokens"` + // This field is from variant [BetaRawContentBlockDeltaUnion]. + Thinking string `json:"thinking"` + // This field is from variant [BetaRawContentBlockDeltaUnion]. + Signature string `json:"signature"` + // This field is from variant [BetaRawContentBlockDeltaUnion]. + Content string `json:"content"` + // This field is from variant [BetaRawContentBlockDeltaUnion]. + EncryptedContent string `json:"encrypted_content"` + JSON struct { + Container respjson.Field + StopDetails respjson.Field + StopReason respjson.Field + StopSequence respjson.Field + Text respjson.Field + Type respjson.Field + PartialJSON respjson.Field + Citation respjson.Field + EstimatedTokens respjson.Field + Thinking respjson.Field + Signature respjson.Field + Content respjson.Field + EncryptedContent respjson.Field + raw string + } `json:"-"` } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaToolUnionParam) GetDeferLoading() *bool { - if vt := u.OfTool; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfBashTool20241022; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfBashTool20250124; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfCodeExecutionTool20250522; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfCodeExecutionTool20250825; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfCodeExecutionTool20260120; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfComputerUseTool20241022; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfMemoryTool20250818; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfComputerUseTool20250124; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfTextEditor20241022; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfComputerUseTool20251124; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfTextEditor20250124; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfTextEditor20250429; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfTextEditor20250728; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfWebSearchTool20250305; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfWebFetchTool20250910; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfWebSearchTool20260209; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfWebFetchTool20260209; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfWebFetchTool20260309; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfAdvisorTool20260301; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfToolSearchToolRegex20251119; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } - return nil +func (r *BetaRawMessageStreamEventUnionDelta) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaToolUnionParam) GetStrict() *bool { - if vt := u.OfTool; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfBashTool20241022; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfBashTool20250124; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfCodeExecutionTool20250522; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfCodeExecutionTool20250825; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfCodeExecutionTool20260120; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfComputerUseTool20241022; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfMemoryTool20250818; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfComputerUseTool20250124; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfTextEditor20241022; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfComputerUseTool20251124; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfTextEditor20250124; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfTextEditor20250429; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfTextEditor20250728; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfWebSearchTool20250305; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfWebFetchTool20250910; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfWebSearchTool20260209; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfWebFetchTool20260209; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfWebFetchTool20260309; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfAdvisorTool20260301; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfToolSearchToolRegex20251119; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value +type BetaRedactedThinkingBlock struct { + // The contents of this redacted thinking block, returned when portions of the + // model's thinking were safety-redacted. This field is opaque and encrypted, with + // no readable content. + // + // Pass `redacted_thinking` blocks back to the API unchanged when continuing a + // multi-turn conversation. + // + // See + // [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking#redacted-thinking-blocks) + // for details. + Data string `json:"data" api:"required"` + Type constant.RedactedThinking `json:"type" default:"redacted_thinking"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Data respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaRedactedThinkingBlock) RawJSON() string { return r.JSON.raw } +func (r *BetaRedactedThinkingBlock) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The properties Data, Type are required. +type BetaRedactedThinkingBlockParam struct { + // The `data` value of this redacted thinking block, exactly as returned by the API + // in a previous response. Opaque and encrypted; pass it back unchanged. + Data string `json:"data" api:"required"` + // This field can be elided, and will marshal its zero value as + // "redacted_thinking". + Type constant.RedactedThinking `json:"type" default:"redacted_thinking"` + paramObj +} + +func (r BetaRedactedThinkingBlockParam) MarshalJSON() (data []byte, err error) { + type shadow BetaRedactedThinkingBlockParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaRedactedThinkingBlockParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Structured information about a refusal. +type BetaRefusalStopDetails struct { + // The policy category that triggered a refusal. + // + // Any of "cyber", "bio", "frontier_llm", "reasoning_extraction", "general_harms". + Category BetaRefusalStopDetailsCategory `json:"category" api:"required"` + // Human-readable explanation of the refusal. + // + // This text is not guaranteed to be stable. `null` when no explanation is + // available for the category. + Explanation string `json:"explanation" api:"required"` + // Opaque code that refunds the cache-miss cost when retrying this refused request + // on the fallback model. Pass it as `fallback_credit_token` on the retry request. + // Expires 5 minutes after the refusal. + // + // The retry is sent either with the same request body (`system`, `messages`, + // `tools`, and other render-shaping fields), or with the same body plus one + // appended `assistant` message whose content is the partial text (with any + // trailing whitespace stripped from the final text block) and paired server-tool + // blocks from this refusal — which also authorizes that appended turn as an + // assistant-prefill continuation on models that otherwise disallow prefill. A + // token minted mid-server-tool-loop whose partial content was continuable may only + // be redeemed the second way — if a same-body retry is rejected with a 400 saying + // the token must be redeemed by continuing the partial response, retry the second + // way instead. Either way: same workspace, same platform; a mismatch is a 400. + // Resending a token for an already-warm prefix is permitted but yields no + // additional credit. + // + // `null` when the refused model isn't eligible for a fallback credit. + FallbackCreditToken string `json:"fallback_credit_token" api:"required"` + // Whether the accompanying `fallback_credit_token` may be redeemed with the + // appended-assistant retry form. Only set when `fallback_credit_token` is present. + // + // `true`: retry by resending the same request body plus one appended `assistant` + // message whose content is this response's `content` with any trailing whitespace + // stripped from the final text block and unpaired `tool_use` blocks omitted (the + // same appended-turn shape described on `fallback_credit_token`), with the token + // attached. `false`: retry by resending the original request body unchanged, with + // the token attached — the appended-assistant form is not available for this + // refusal (no continuable partial content, or the request uses `output_format` or + // a `tool_choice` that forces tool use). One exception: when the request used + // `output_format` or a forced `tool_choice` and the refusal arrived after server + // tools (including MCP connector tools) had already executed, the token may not be + // redeemable by either retry form; if the exact-body retry is then rejected with a + // 400 saying the token must be redeemed by continuing the partial response, + // discard the token and retry without it. + // + // Advisory: if an appended-assistant retry is rejected with a 400 despite `true`, + // fall back to resending the original request body with the token. + FallbackHasPrefillClaim bool `json:"fallback_has_prefill_claim" api:"required"` + // The server's suggested retry target for this refusal. Populated when a fallback + // attempt could not be made (the fallback model's rate limit was exhausted, or it + // was overloaded); names the fallback model the caller can retry directly. Null + // otherwise. + RecommendedModel string `json:"recommended_model" api:"required"` + Type constant.Refusal `json:"type" default:"refusal"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Category respjson.Field + Explanation respjson.Field + FallbackCreditToken respjson.Field + FallbackHasPrefillClaim respjson.Field + RecommendedModel respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaRefusalStopDetails) RawJSON() string { return r.JSON.raw } +func (r *BetaRefusalStopDetails) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The policy category that triggered a refusal. +type BetaRefusalStopDetailsCategory string + +const ( + BetaRefusalStopDetailsCategoryCyber BetaRefusalStopDetailsCategory = "cyber" + BetaRefusalStopDetailsCategoryBio BetaRefusalStopDetailsCategory = "bio" + BetaRefusalStopDetailsCategoryFrontierLLM BetaRefusalStopDetailsCategory = "frontier_llm" + BetaRefusalStopDetailsCategoryReasoningExtraction BetaRefusalStopDetailsCategory = "reasoning_extraction" + BetaRefusalStopDetailsCategoryGeneralHarms BetaRefusalStopDetailsCategory = "general_harms" +) + +// The properties Source, Type are required. +type BetaRequestDocumentBlockParam struct { + Source BetaRequestDocumentBlockSourceUnionParam `json:"source,omitzero" api:"required"` + Context param.Opt[string] `json:"context,omitzero"` + Title param.Opt[string] `json:"title,omitzero"` + // Create a cache control breakpoint at this content block. + CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` + Citations BetaCitationsConfigParam `json:"citations,omitzero"` + // This field can be elided, and will marshal its zero value as "document". + Type constant.Document `json:"type" default:"document"` + paramObj +} + +func (r BetaRequestDocumentBlockParam) MarshalJSON() (data []byte, err error) { + type shadow BetaRequestDocumentBlockParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaRequestDocumentBlockParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaRequestDocumentBlockSourceUnionParam struct { + OfBase64 *BetaBase64PDFSourceParam `json:",omitzero,inline"` + OfText *BetaPlainTextSourceParam `json:",omitzero,inline"` + OfContent *BetaContentBlockSourceParam `json:",omitzero,inline"` + OfURL *BetaURLPDFSourceParam `json:",omitzero,inline"` + OfFile *BetaFileDocumentSourceParam `json:",omitzero,inline"` + paramUnion +} + +func (u BetaRequestDocumentBlockSourceUnionParam) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfBase64, + u.OfText, + u.OfContent, + u.OfURL, + u.OfFile) +} +func (u *BetaRequestDocumentBlockSourceUnionParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *BetaRequestDocumentBlockSourceUnionParam) asAny() any { + if !param.IsOmitted(u.OfBase64) { + return u.OfBase64 + } else if !param.IsOmitted(u.OfText) { + return u.OfText + } else if !param.IsOmitted(u.OfContent) { + return u.OfContent + } else if !param.IsOmitted(u.OfURL) { + return u.OfURL + } else if !param.IsOmitted(u.OfFile) { + return u.OfFile } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u BetaToolUnionParam) GetType() *string { - if vt := u.OfTool; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfBashTool20241022; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfBashTool20250124; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfCodeExecutionTool20250522; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfCodeExecutionTool20250825; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfCodeExecutionTool20260120; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfComputerUseTool20241022; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfMemoryTool20250818; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfComputerUseTool20250124; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfTextEditor20241022; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfComputerUseTool20251124; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfTextEditor20250124; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfTextEditor20250429; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfTextEditor20250728; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfWebSearchTool20250305; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfWebFetchTool20250910; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfWebSearchTool20260209; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfWebFetchTool20260209; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfWebFetchTool20260309; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfAdvisorTool20260301; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfToolSearchToolRegex20251119; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfMCPToolset; vt != nil { - return (*string)(&vt.Type) +func (u BetaRequestDocumentBlockSourceUnionParam) GetContent() *BetaContentBlockSourceContentUnionParam { + if vt := u.OfContent; vt != nil { + return &vt.Content } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u BetaToolUnionParam) GetDisplayHeightPx() *int64 { - if vt := u.OfComputerUseTool20241022; vt != nil { - return (*int64)(&vt.DisplayHeightPx) - } else if vt := u.OfComputerUseTool20250124; vt != nil { - return (*int64)(&vt.DisplayHeightPx) - } else if vt := u.OfComputerUseTool20251124; vt != nil { - return (*int64)(&vt.DisplayHeightPx) +func (u BetaRequestDocumentBlockSourceUnionParam) GetURL() *string { + if vt := u.OfURL; vt != nil { + return &vt.URL } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u BetaToolUnionParam) GetDisplayWidthPx() *int64 { - if vt := u.OfComputerUseTool20241022; vt != nil { - return (*int64)(&vt.DisplayWidthPx) - } else if vt := u.OfComputerUseTool20250124; vt != nil { - return (*int64)(&vt.DisplayWidthPx) - } else if vt := u.OfComputerUseTool20251124; vt != nil { - return (*int64)(&vt.DisplayWidthPx) +func (u BetaRequestDocumentBlockSourceUnionParam) GetFileID() *string { + if vt := u.OfFile; vt != nil { + return &vt.FileID } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u BetaToolUnionParam) GetDisplayNumber() *int64 { - if vt := u.OfComputerUseTool20241022; vt != nil && vt.DisplayNumber.Valid() { - return &vt.DisplayNumber.Value - } else if vt := u.OfComputerUseTool20250124; vt != nil && vt.DisplayNumber.Valid() { - return &vt.DisplayNumber.Value - } else if vt := u.OfComputerUseTool20251124; vt != nil && vt.DisplayNumber.Valid() { - return &vt.DisplayNumber.Value +func (u BetaRequestDocumentBlockSourceUnionParam) GetData() *string { + if vt := u.OfBase64; vt != nil { + return (*string)(&vt.Data) + } else if vt := u.OfText; vt != nil { + return (*string)(&vt.Data) } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u BetaToolUnionParam) GetMaxUses() *int64 { - if vt := u.OfWebSearchTool20250305; vt != nil && vt.MaxUses.Valid() { - return &vt.MaxUses.Value - } else if vt := u.OfWebFetchTool20250910; vt != nil && vt.MaxUses.Valid() { - return &vt.MaxUses.Value - } else if vt := u.OfWebSearchTool20260209; vt != nil && vt.MaxUses.Valid() { - return &vt.MaxUses.Value - } else if vt := u.OfWebFetchTool20260209; vt != nil && vt.MaxUses.Valid() { - return &vt.MaxUses.Value - } else if vt := u.OfWebFetchTool20260309; vt != nil && vt.MaxUses.Valid() { - return &vt.MaxUses.Value - } else if vt := u.OfAdvisorTool20260301; vt != nil && vt.MaxUses.Valid() { - return &vt.MaxUses.Value +func (u BetaRequestDocumentBlockSourceUnionParam) GetMediaType() *string { + if vt := u.OfBase64; vt != nil { + return (*string)(&vt.MediaType) + } else if vt := u.OfText; vt != nil { + return (*string)(&vt.MediaType) } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u BetaToolUnionParam) GetMaxContentTokens() *int64 { - if vt := u.OfWebFetchTool20250910; vt != nil && vt.MaxContentTokens.Valid() { - return &vt.MaxContentTokens.Value - } else if vt := u.OfWebFetchTool20260209; vt != nil && vt.MaxContentTokens.Valid() { - return &vt.MaxContentTokens.Value - } else if vt := u.OfWebFetchTool20260309; vt != nil && vt.MaxContentTokens.Valid() { - return &vt.MaxContentTokens.Value +func (u BetaRequestDocumentBlockSourceUnionParam) GetType() *string { + if vt := u.OfBase64; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfText; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfContent; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfURL; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfFile; vt != nil { + return (*string)(&vt.Type) } return nil } -// Returns a pointer to the underlying variant's AllowedCallers property, if -// present. -func (u BetaToolUnionParam) GetAllowedCallers() []string { - if vt := u.OfTool; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfBashTool20241022; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfBashTool20250124; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfCodeExecutionTool20250522; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfCodeExecutionTool20250825; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfCodeExecutionTool20260120; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfComputerUseTool20241022; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfMemoryTool20250818; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfComputerUseTool20250124; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfTextEditor20241022; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfComputerUseTool20251124; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfTextEditor20250124; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfTextEditor20250429; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfTextEditor20250728; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfWebSearchTool20250305; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfWebFetchTool20250910; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfWebSearchTool20260209; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfWebFetchTool20260209; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfWebFetchTool20260309; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfAdvisorTool20260301; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfToolSearchToolRegex20251119; vt != nil { - return vt.AllowedCallers - } - return nil +func init() { + apijson.RegisterUnion[BetaRequestDocumentBlockSourceUnionParam]( + "type", + apijson.Discriminator[BetaBase64PDFSourceParam]("base64"), + apijson.Discriminator[BetaPlainTextSourceParam]("text"), + apijson.Discriminator[BetaContentBlockSourceParam]("content"), + apijson.Discriminator[BetaURLPDFSourceParam]("url"), + apijson.Discriminator[BetaFileDocumentSourceParam]("file"), + ) } -// Returns a pointer to the underlying variant's CacheControl property, if present. -func (u BetaToolUnionParam) GetCacheControl() *BetaCacheControlEphemeralParam { - if vt := u.OfTool; vt != nil { - return &vt.CacheControl - } else if vt := u.OfBashTool20241022; vt != nil { - return &vt.CacheControl - } else if vt := u.OfBashTool20250124; vt != nil { - return &vt.CacheControl - } else if vt := u.OfCodeExecutionTool20250522; vt != nil { - return &vt.CacheControl - } else if vt := u.OfCodeExecutionTool20250825; vt != nil { - return &vt.CacheControl - } else if vt := u.OfCodeExecutionTool20260120; vt != nil { - return &vt.CacheControl - } else if vt := u.OfComputerUseTool20241022; vt != nil { - return &vt.CacheControl - } else if vt := u.OfMemoryTool20250818; vt != nil { - return &vt.CacheControl - } else if vt := u.OfComputerUseTool20250124; vt != nil { - return &vt.CacheControl - } else if vt := u.OfTextEditor20241022; vt != nil { - return &vt.CacheControl - } else if vt := u.OfComputerUseTool20251124; vt != nil { - return &vt.CacheControl - } else if vt := u.OfTextEditor20250124; vt != nil { - return &vt.CacheControl - } else if vt := u.OfTextEditor20250429; vt != nil { - return &vt.CacheControl - } else if vt := u.OfTextEditor20250728; vt != nil { - return &vt.CacheControl - } else if vt := u.OfWebSearchTool20250305; vt != nil { - return &vt.CacheControl - } else if vt := u.OfWebFetchTool20250910; vt != nil { - return &vt.CacheControl - } else if vt := u.OfWebSearchTool20260209; vt != nil { - return &vt.CacheControl - } else if vt := u.OfWebFetchTool20260209; vt != nil { - return &vt.CacheControl - } else if vt := u.OfWebFetchTool20260309; vt != nil { - return &vt.CacheControl - } else if vt := u.OfAdvisorTool20260301; vt != nil { - return &vt.CacheControl - } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil { - return &vt.CacheControl - } else if vt := u.OfToolSearchToolRegex20251119; vt != nil { - return &vt.CacheControl - } else if vt := u.OfMCPToolset; vt != nil { - return &vt.CacheControl - } - return nil +type BetaRequestMCPServerToolConfigurationParam struct { + Enabled param.Opt[bool] `json:"enabled,omitzero"` + AllowedTools []string `json:"allowed_tools,omitzero"` + paramObj } -// Returns a pointer to the underlying variant's InputExamples property, if -// present. -func (u BetaToolUnionParam) GetInputExamples() []map[string]any { - if vt := u.OfTool; vt != nil { - return vt.InputExamples - } else if vt := u.OfBashTool20241022; vt != nil { - return vt.InputExamples - } else if vt := u.OfBashTool20250124; vt != nil { - return vt.InputExamples - } else if vt := u.OfComputerUseTool20241022; vt != nil { - return vt.InputExamples - } else if vt := u.OfMemoryTool20250818; vt != nil { - return vt.InputExamples - } else if vt := u.OfComputerUseTool20250124; vt != nil { - return vt.InputExamples - } else if vt := u.OfTextEditor20241022; vt != nil { - return vt.InputExamples - } else if vt := u.OfComputerUseTool20251124; vt != nil { - return vt.InputExamples - } else if vt := u.OfTextEditor20250124; vt != nil { - return vt.InputExamples - } else if vt := u.OfTextEditor20250429; vt != nil { - return vt.InputExamples - } else if vt := u.OfTextEditor20250728; vt != nil { - return vt.InputExamples - } - return nil +func (r BetaRequestMCPServerToolConfigurationParam) MarshalJSON() (data []byte, err error) { + type shadow BetaRequestMCPServerToolConfigurationParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaRequestMCPServerToolConfigurationParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns a pointer to the underlying variant's AllowedDomains property, if -// present. -func (u BetaToolUnionParam) GetAllowedDomains() []string { - if vt := u.OfWebSearchTool20250305; vt != nil { - return vt.AllowedDomains - } else if vt := u.OfWebFetchTool20250910; vt != nil { - return vt.AllowedDomains - } else if vt := u.OfWebSearchTool20260209; vt != nil { - return vt.AllowedDomains - } else if vt := u.OfWebFetchTool20260209; vt != nil { - return vt.AllowedDomains - } else if vt := u.OfWebFetchTool20260309; vt != nil { - return vt.AllowedDomains - } - return nil +// The properties Name, Type, URL are required. +type BetaRequestMCPServerURLDefinitionParam struct { + Name string `json:"name" api:"required"` + URL string `json:"url" api:"required"` + AuthorizationToken param.Opt[string] `json:"authorization_token,omitzero"` + ToolConfiguration BetaRequestMCPServerToolConfigurationParam `json:"tool_configuration,omitzero"` + // This field can be elided, and will marshal its zero value as "url". + Type constant.URL `json:"type" default:"url"` + paramObj } -// Returns a pointer to the underlying variant's BlockedDomains property, if -// present. -func (u BetaToolUnionParam) GetBlockedDomains() []string { - if vt := u.OfWebSearchTool20250305; vt != nil { - return vt.BlockedDomains - } else if vt := u.OfWebFetchTool20250910; vt != nil { - return vt.BlockedDomains - } else if vt := u.OfWebSearchTool20260209; vt != nil { - return vt.BlockedDomains - } else if vt := u.OfWebFetchTool20260209; vt != nil { - return vt.BlockedDomains - } else if vt := u.OfWebFetchTool20260309; vt != nil { - return vt.BlockedDomains - } - return nil +func (r BetaRequestMCPServerURLDefinitionParam) MarshalJSON() (data []byte, err error) { + type shadow BetaRequestMCPServerURLDefinitionParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaRequestMCPServerURLDefinitionParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns a pointer to the underlying variant's UserLocation property, if present. -func (u BetaToolUnionParam) GetUserLocation() *BetaUserLocationParam { - if vt := u.OfWebSearchTool20250305; vt != nil { - return &vt.UserLocation - } else if vt := u.OfWebSearchTool20260209; vt != nil { - return &vt.UserLocation - } - return nil +// The properties ToolUseID, Type are required. +type BetaRequestMCPToolResultBlockParam struct { + ToolUseID string `json:"tool_use_id" api:"required"` + IsError param.Opt[bool] `json:"is_error,omitzero"` + // Create a cache control breakpoint at this content block. + CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` + Content BetaRequestMCPToolResultBlockParamContentUnion `json:"content,omitzero"` + // This field can be elided, and will marshal its zero value as "mcp_tool_result". + Type constant.MCPToolResult `json:"type" default:"mcp_tool_result"` + paramObj } -// Returns a pointer to the underlying variant's Citations property, if present. -func (u BetaToolUnionParam) GetCitations() *BetaCitationsConfigParam { - if vt := u.OfWebFetchTool20250910; vt != nil { - return &vt.Citations - } else if vt := u.OfWebFetchTool20260209; vt != nil { - return &vt.Citations - } else if vt := u.OfWebFetchTool20260309; vt != nil { - return &vt.Citations - } - return nil +func (r BetaRequestMCPToolResultBlockParam) MarshalJSON() (data []byte, err error) { + type shadow BetaRequestMCPToolResultBlockParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaRequestMCPToolResultBlockParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -type BetaToolUseBlock struct { - ID string `json:"id" api:"required"` - Input any `json:"input" api:"required"` - Name string `json:"name" api:"required"` - Type constant.ToolUse `json:"type" default:"tool_use"` - // Tool invocation directly from the model. - Caller BetaToolUseBlockCallerUnion `json:"caller"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ID respjson.Field - Input respjson.Field - Name respjson.Field - Type respjson.Field - Caller respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaRequestMCPToolResultBlockParamContentUnion struct { + OfString param.Opt[string] `json:",omitzero,inline"` + OfBetaMCPToolResultBlockContent []BetaTextBlockParam `json:",omitzero,inline"` + paramUnion } -// Returns the unmodified JSON received from the API -func (r BetaToolUseBlock) RawJSON() string { return r.JSON.raw } -func (r *BetaToolUseBlock) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +func (u BetaRequestMCPToolResultBlockParamContentUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfString, u.OfBetaMCPToolResultBlockContent) +} +func (u *BetaRequestMCPToolResultBlockParamContentUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) } -// BetaToolUseBlockCallerUnion contains all possible properties and values from -// [BetaDirectCaller], [BetaServerToolCaller], [BetaServerToolCaller20260120]. +func (u *BetaRequestMCPToolResultBlockParamContentUnion) asAny() any { + if !param.IsOmitted(u.OfString) { + return &u.OfString.Value + } else if !param.IsOmitted(u.OfBetaMCPToolResultBlockContent) { + return &u.OfBetaMCPToolResultBlockContent + } + return nil +} + +// Mid-conversation directive to surface a declared tool. // -// Use the [BetaToolUseBlockCallerUnion.AsAny] method to switch on the variant. +// `tool` references a tool (or MCP toolset) by name from the request's `tools`; it +// is offered to the model from this point in the conversation onward. // -// Use the methods beginning with 'As' to cast the union to one of its variants. -type BetaToolUseBlockCallerUnion struct { - // Any of "direct", "code_execution_20250825", "code_execution_20260120". - Type string `json:"type"` - ToolID string `json:"tool_id"` - JSON struct { - Type respjson.Field - ToolID respjson.Field - raw string - } `json:"-"` +// The properties Tool, Type are required. +type BetaRequestToolAdditionBlockParam struct { + // Reference to a single tool the caller declared directly in `tools[]`. Does not + // accept the composed `{server}_{name}` form the server assigns to MCP-resolved + // tools — use `mcp_tool_reference` or `mcp_toolset_reference` for those. + Tool BetaRequestToolAdditionBlockToolUnionParam `json:"tool,omitzero" api:"required"` + // Create a cache control breakpoint at this content block. + CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` + // This field can be elided, and will marshal its zero value as "tool_addition". + Type constant.ToolAddition `json:"type" default:"tool_addition"` + paramObj } -// anyBetaToolUseBlockCaller is implemented by each variant of -// [BetaToolUseBlockCallerUnion] to add type safety for the return type of -// [BetaToolUseBlockCallerUnion.AsAny] -type anyBetaToolUseBlockCaller interface { - implBetaToolUseBlockCallerUnion() +func (r BetaRequestToolAdditionBlockParam) MarshalJSON() (data []byte, err error) { + type shadow BetaRequestToolAdditionBlockParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaRequestToolAdditionBlockParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func (BetaDirectCaller) implBetaToolUseBlockCallerUnion() {} -func (BetaServerToolCaller) implBetaToolUseBlockCallerUnion() {} -func (BetaServerToolCaller20260120) implBetaToolUseBlockCallerUnion() {} - -// Use the following switch statement to find the correct variant +// Only one field can be non-zero. // -// switch variant := BetaToolUseBlockCallerUnion.AsAny().(type) { -// case anthropic.BetaDirectCaller: -// case anthropic.BetaServerToolCaller: -// case anthropic.BetaServerToolCaller20260120: -// default: -// fmt.Errorf("no variant present") -// } -func (u BetaToolUseBlockCallerUnion) AsAny() anyBetaToolUseBlockCaller { - switch u.Type { - case "direct": - return u.AsDirect() - case "code_execution_20250825": - return u.AsCodeExecution20250825() - case "code_execution_20260120": - return u.AsCodeExecution20260120() +// Use [param.IsOmitted] to confirm if a field is set. +type BetaRequestToolAdditionBlockToolUnionParam struct { + OfToolReference *BetaToolChangeToolReferenceParam `json:",omitzero,inline"` + OfMCPToolReference *BetaToolChangeMCPToolReferenceParam `json:",omitzero,inline"` + OfMCPToolsetReference *BetaToolChangeMCPToolsetReferenceParam `json:",omitzero,inline"` + paramUnion +} + +func (u BetaRequestToolAdditionBlockToolUnionParam) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfToolReference, u.OfMCPToolReference, u.OfMCPToolsetReference) +} +func (u *BetaRequestToolAdditionBlockToolUnionParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *BetaRequestToolAdditionBlockToolUnionParam) asAny() any { + if !param.IsOmitted(u.OfToolReference) { + return u.OfToolReference + } else if !param.IsOmitted(u.OfMCPToolReference) { + return u.OfMCPToolReference + } else if !param.IsOmitted(u.OfMCPToolsetReference) { + return u.OfMCPToolsetReference } return nil } -func (u BetaToolUseBlockCallerUnion) AsDirect() (v BetaDirectCaller) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +// Returns a pointer to the underlying variant's property, if present. +func (u BetaRequestToolAdditionBlockToolUnionParam) GetName() *string { + if vt := u.OfToolReference; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfMCPToolReference; vt != nil { + return (*string)(&vt.Name) + } + return nil } -func (u BetaToolUseBlockCallerUnion) AsCodeExecution20250825() (v BetaServerToolCaller) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +// Returns a pointer to the underlying variant's property, if present. +func (u BetaRequestToolAdditionBlockToolUnionParam) GetType() *string { + if vt := u.OfToolReference; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfMCPToolReference; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfMCPToolsetReference; vt != nil { + return (*string)(&vt.Type) + } + return nil } -func (u BetaToolUseBlockCallerUnion) AsCodeExecution20260120() (v BetaServerToolCaller20260120) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +// Returns a pointer to the underlying variant's property, if present. +func (u BetaRequestToolAdditionBlockToolUnionParam) GetServerName() *string { + if vt := u.OfMCPToolReference; vt != nil { + return (*string)(&vt.ServerName) + } else if vt := u.OfMCPToolsetReference; vt != nil { + return (*string)(&vt.ServerName) + } + return nil } -// Returns the unmodified JSON received from the API -func (u BetaToolUseBlockCallerUnion) RawJSON() string { return u.JSON.raw } - -func (r *BetaToolUseBlockCallerUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +func init() { + apijson.RegisterUnion[BetaRequestToolAdditionBlockToolUnionParam]( + "type", + apijson.Discriminator[BetaToolChangeToolReferenceParam]("tool_reference"), + apijson.Discriminator[BetaToolChangeMCPToolReferenceParam]("mcp_tool_reference"), + apijson.Discriminator[BetaToolChangeMCPToolsetReferenceParam]("mcp_toolset_reference"), + ) } -// The properties ID, Input, Name, Type are required. -type BetaToolUseBlockParam struct { - ID string `json:"id" api:"required"` - Input any `json:"input,omitzero" api:"required"` - Name string `json:"name" api:"required"` +// Mid-conversation directive to withdraw a tool. +// +// `tool` references a tool (or MCP toolset) by name from the request's `tools`; it +// is no longer offered to the model from this point in the conversation onward. +// +// The properties Tool, Type are required. +type BetaRequestToolRemovalBlockParam struct { + // Reference to a single tool the caller declared directly in `tools[]`. Does not + // accept the composed `{server}_{name}` form the server assigns to MCP-resolved + // tools — use `mcp_tool_reference` or `mcp_toolset_reference` for those. + Tool BetaRequestToolRemovalBlockToolUnionParam `json:"tool,omitzero" api:"required"` // Create a cache control breakpoint at this content block. CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` - // Tool invocation directly from the model. - Caller BetaToolUseBlockParamCallerUnion `json:"caller,omitzero"` - // This field can be elided, and will marshal its zero value as "tool_use". - Type constant.ToolUse `json:"type" default:"tool_use"` + // This field can be elided, and will marshal its zero value as "tool_removal". + Type constant.ToolRemoval `json:"type" default:"tool_removal"` paramObj } -func (r BetaToolUseBlockParam) MarshalJSON() (data []byte, err error) { - type shadow BetaToolUseBlockParam +func (r BetaRequestToolRemovalBlockParam) MarshalJSON() (data []byte, err error) { + type shadow BetaRequestToolRemovalBlockParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *BetaToolUseBlockParam) UnmarshalJSON(data []byte) error { +func (r *BetaRequestToolRemovalBlockParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } // Only one field can be non-zero. // // Use [param.IsOmitted] to confirm if a field is set. -type BetaToolUseBlockParamCallerUnion struct { - OfDirect *BetaDirectCallerParam `json:",omitzero,inline"` - OfCodeExecution20250825 *BetaServerToolCallerParam `json:",omitzero,inline"` - OfCodeExecution20260120 *BetaServerToolCaller20260120Param `json:",omitzero,inline"` +type BetaRequestToolRemovalBlockToolUnionParam struct { + OfToolReference *BetaToolChangeToolReferenceParam `json:",omitzero,inline"` + OfMCPToolReference *BetaToolChangeMCPToolReferenceParam `json:",omitzero,inline"` + OfMCPToolsetReference *BetaToolChangeMCPToolsetReferenceParam `json:",omitzero,inline"` paramUnion } -func (u BetaToolUseBlockParamCallerUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfDirect, u.OfCodeExecution20250825, u.OfCodeExecution20260120) +func (u BetaRequestToolRemovalBlockToolUnionParam) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfToolReference, u.OfMCPToolReference, u.OfMCPToolsetReference) } -func (u *BetaToolUseBlockParamCallerUnion) UnmarshalJSON(data []byte) error { +func (u *BetaRequestToolRemovalBlockToolUnionParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, u) } -func (u *BetaToolUseBlockParamCallerUnion) asAny() any { - if !param.IsOmitted(u.OfDirect) { - return u.OfDirect - } else if !param.IsOmitted(u.OfCodeExecution20250825) { - return u.OfCodeExecution20250825 - } else if !param.IsOmitted(u.OfCodeExecution20260120) { - return u.OfCodeExecution20260120 +func (u *BetaRequestToolRemovalBlockToolUnionParam) asAny() any { + if !param.IsOmitted(u.OfToolReference) { + return u.OfToolReference + } else if !param.IsOmitted(u.OfMCPToolReference) { + return u.OfMCPToolReference + } else if !param.IsOmitted(u.OfMCPToolsetReference) { + return u.OfMCPToolsetReference } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u BetaToolUseBlockParamCallerUnion) GetType() *string { - if vt := u.OfDirect; vt != nil { +func (u BetaRequestToolRemovalBlockToolUnionParam) GetName() *string { + if vt := u.OfToolReference; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfMCPToolReference; vt != nil { + return (*string)(&vt.Name) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaRequestToolRemovalBlockToolUnionParam) GetType() *string { + if vt := u.OfToolReference; vt != nil { return (*string)(&vt.Type) - } else if vt := u.OfCodeExecution20250825; vt != nil { + } else if vt := u.OfMCPToolReference; vt != nil { return (*string)(&vt.Type) - } else if vt := u.OfCodeExecution20260120; vt != nil { + } else if vt := u.OfMCPToolsetReference; vt != nil { return (*string)(&vt.Type) } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u BetaToolUseBlockParamCallerUnion) GetToolID() *string { - if vt := u.OfCodeExecution20250825; vt != nil { - return (*string)(&vt.ToolID) - } else if vt := u.OfCodeExecution20260120; vt != nil { - return (*string)(&vt.ToolID) +func (u BetaRequestToolRemovalBlockToolUnionParam) GetServerName() *string { + if vt := u.OfMCPToolReference; vt != nil { + return (*string)(&vt.ServerName) + } else if vt := u.OfMCPToolsetReference; vt != nil { + return (*string)(&vt.ServerName) } return nil } func init() { - apijson.RegisterUnion[BetaToolUseBlockParamCallerUnion]( + apijson.RegisterUnion[BetaRequestToolRemovalBlockToolUnionParam]( "type", - apijson.Discriminator[BetaDirectCallerParam]("direct"), - apijson.Discriminator[BetaServerToolCallerParam]("code_execution_20250825"), - apijson.Discriminator[BetaServerToolCaller20260120Param]("code_execution_20260120"), + apijson.Discriminator[BetaToolChangeToolReferenceParam]("tool_reference"), + apijson.Discriminator[BetaToolChangeMCPToolReferenceParam]("mcp_tool_reference"), + apijson.Discriminator[BetaToolChangeMCPToolsetReferenceParam]("mcp_toolset_reference"), ) } -// The properties Type, Value are required. -type BetaToolUsesKeepParam struct { - Value int64 `json:"value" api:"required"` - // This field can be elided, and will marshal its zero value as "tool_uses". - Type constant.ToolUses `json:"type" default:"tool_uses"` +// The properties Content, Source, Title, Type are required. +type BetaSearchResultBlockParam struct { + Content []BetaTextBlockParam `json:"content,omitzero" api:"required"` + Source string `json:"source" api:"required"` + Title string `json:"title" api:"required"` + // Create a cache control breakpoint at this content block. + CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` + Citations BetaCitationsConfigParam `json:"citations,omitzero"` + // This field can be elided, and will marshal its zero value as "search_result". + Type constant.SearchResult `json:"type" default:"search_result"` paramObj } -func (r BetaToolUsesKeepParam) MarshalJSON() (data []byte, err error) { - type shadow BetaToolUsesKeepParam +func (r BetaSearchResultBlockParam) MarshalJSON() (data []byte, err error) { + type shadow BetaSearchResultBlockParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *BetaToolUsesKeepParam) UnmarshalJSON(data []byte) error { +func (r *BetaSearchResultBlockParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The properties Type, Value are required. -type BetaToolUsesTriggerParam struct { - Value int64 `json:"value" api:"required"` - // This field can be elided, and will marshal its zero value as "tool_uses". - Type constant.ToolUses `json:"type" default:"tool_uses"` - paramObj +// Tool invocation generated by a server-side tool. +type BetaServerToolCaller struct { + ToolID string `json:"tool_id" api:"required"` + Type constant.CodeExecution20250825 `json:"type" default:"code_execution_20250825"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ToolID respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` } -func (r BetaToolUsesTriggerParam) MarshalJSON() (data []byte, err error) { - type shadow BetaToolUsesTriggerParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaToolUsesTriggerParam) UnmarshalJSON(data []byte) error { +// Returns the unmodified JSON received from the API +func (r BetaServerToolCaller) RawJSON() string { return r.JSON.raw } +func (r *BetaServerToolCaller) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The properties Type, URL are required. -type BetaURLImageSourceParam struct { - URL string `json:"url" api:"required"` - // This field can be elided, and will marshal its zero value as "url". - Type constant.URL `json:"type" default:"url"` +// ToParam converts this BetaServerToolCaller to a BetaServerToolCallerParam. +// +// Warning: the fields of the param type will not be present. ToParam should only +// be used at the last possible moment before sending a request. Test for this with +// BetaServerToolCallerParam.Overrides() +func (r BetaServerToolCaller) ToParam() BetaServerToolCallerParam { + return param.Override[BetaServerToolCallerParam](json.RawMessage(r.RawJSON())) +} + +// Tool invocation generated by a server-side tool. +// +// The properties ToolID, Type are required. +type BetaServerToolCallerParam struct { + ToolID string `json:"tool_id" api:"required"` + // This field can be elided, and will marshal its zero value as + // "code_execution_20250825". + Type constant.CodeExecution20250825 `json:"type" default:"code_execution_20250825"` paramObj } -func (r BetaURLImageSourceParam) MarshalJSON() (data []byte, err error) { - type shadow BetaURLImageSourceParam +func (r BetaServerToolCallerParam) MarshalJSON() (data []byte, err error) { + type shadow BetaServerToolCallerParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *BetaURLImageSourceParam) UnmarshalJSON(data []byte) error { +func (r *BetaServerToolCallerParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The properties Type, URL are required. -type BetaURLPDFSourceParam struct { - URL string `json:"url" api:"required"` - // This field can be elided, and will marshal its zero value as "url". - Type constant.URL `json:"type" default:"url"` - paramObj -} - -func (r BetaURLPDFSourceParam) MarshalJSON() (data []byte, err error) { - type shadow BetaURLPDFSourceParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaURLPDFSourceParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type BetaUsage struct { - // Breakdown of cached tokens by TTL - CacheCreation BetaCacheCreation `json:"cache_creation" api:"required"` - // The number of input tokens used to create the cache entry. - CacheCreationInputTokens int64 `json:"cache_creation_input_tokens" api:"required"` - // The number of input tokens read from the cache. - CacheReadInputTokens int64 `json:"cache_read_input_tokens" api:"required"` - // The geographic region where inference was performed for this request. - InferenceGeo string `json:"inference_geo" api:"required"` - // The number of input tokens which were used. - InputTokens int64 `json:"input_tokens" api:"required"` - // Per-iteration token usage breakdown. - // - // Each entry represents one sampling iteration, with its own input/output token - // counts and cache statistics. This allows you to: - // - // - Determine which iterations exceeded long context thresholds (>=200k tokens) - // - Calculate the true context window size from the last iteration - // - Understand token accumulation across server-side tool use loops - Iterations BetaIterationsUsage `json:"iterations" api:"required"` - // The number of output tokens which were used. - OutputTokens int64 `json:"output_tokens" api:"required"` - // The number of server tool requests. - ServerToolUse BetaServerToolUsage `json:"server_tool_use" api:"required"` - // If the request used the priority, standard, or batch tier. - // - // Any of "standard", "priority", "batch". - ServiceTier BetaUsageServiceTier `json:"service_tier" api:"required"` - // The inference speed mode used for this request. - // - // Any of "standard", "fast". - Speed BetaUsageSpeed `json:"speed" api:"required"` +type BetaServerToolCaller20260120 struct { + ToolID string `json:"tool_id" api:"required"` + Type constant.CodeExecution20260120 `json:"type" default:"code_execution_20260120"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { - CacheCreation respjson.Field - CacheCreationInputTokens respjson.Field - CacheReadInputTokens respjson.Field - InferenceGeo respjson.Field - InputTokens respjson.Field - Iterations respjson.Field - OutputTokens respjson.Field - ServerToolUse respjson.Field - ServiceTier respjson.Field - Speed respjson.Field - ExtraFields map[string]respjson.Field - raw string + ToolID respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string } `json:"-"` } // Returns the unmodified JSON received from the API -func (r BetaUsage) RawJSON() string { return r.JSON.raw } -func (r *BetaUsage) UnmarshalJSON(data []byte) error { +func (r BetaServerToolCaller20260120) RawJSON() string { return r.JSON.raw } +func (r *BetaServerToolCaller20260120) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// If the request used the priority, standard, or batch tier. -type BetaUsageServiceTier string - -const ( - BetaUsageServiceTierStandard BetaUsageServiceTier = "standard" - BetaUsageServiceTierPriority BetaUsageServiceTier = "priority" - BetaUsageServiceTierBatch BetaUsageServiceTier = "batch" -) - -// The inference speed mode used for this request. -type BetaUsageSpeed string - -const ( - BetaUsageSpeedStandard BetaUsageSpeed = "standard" - BetaUsageSpeedFast BetaUsageSpeed = "fast" -) +// ToParam converts this BetaServerToolCaller20260120 to a +// BetaServerToolCaller20260120Param. +// +// Warning: the fields of the param type will not be present. ToParam should only +// be used at the last possible moment before sending a request. Test for this with +// BetaServerToolCaller20260120Param.Overrides() +func (r BetaServerToolCaller20260120) ToParam() BetaServerToolCaller20260120Param { + return param.Override[BetaServerToolCaller20260120Param](json.RawMessage(r.RawJSON())) +} -// The property Type is required. -type BetaUserLocationParam struct { - // The city of the user. - City param.Opt[string] `json:"city,omitzero"` - // The two letter - // [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the - // user. - Country param.Opt[string] `json:"country,omitzero"` - // The region of the user. - Region param.Opt[string] `json:"region,omitzero"` - // The [IANA timezone](https://nodatime.org/TimeZones) of the user. - Timezone param.Opt[string] `json:"timezone,omitzero"` - // This field can be elided, and will marshal its zero value as "approximate". - Type constant.Approximate `json:"type" default:"approximate"` +// The properties ToolID, Type are required. +type BetaServerToolCaller20260120Param struct { + ToolID string `json:"tool_id" api:"required"` + // This field can be elided, and will marshal its zero value as + // "code_execution_20260120". + Type constant.CodeExecution20260120 `json:"type" default:"code_execution_20260120"` paramObj } -func (r BetaUserLocationParam) MarshalJSON() (data []byte, err error) { - type shadow BetaUserLocationParam +func (r BetaServerToolCaller20260120Param) MarshalJSON() (data []byte, err error) { + type shadow BetaServerToolCaller20260120Param return param.MarshalObject(r, (*shadow)(&r)) } -func (r *BetaUserLocationParam) UnmarshalJSON(data []byte) error { +func (r *BetaServerToolCaller20260120Param) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type BetaWebFetchBlock struct { - Content BetaDocumentBlock `json:"content" api:"required"` - // ISO 8601 timestamp when the content was retrieved - RetrievedAt string `json:"retrieved_at" api:"required"` - Type constant.WebFetchResult `json:"type" default:"web_fetch_result"` - // Fetched content URL - URL string `json:"url" api:"required"` +type BetaServerToolUsage struct { + // The number of web fetch tool requests. + WebFetchRequests int64 `json:"web_fetch_requests" api:"required"` + // The number of web search tool requests. + WebSearchRequests int64 `json:"web_search_requests" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { - Content respjson.Field - RetrievedAt respjson.Field - Type respjson.Field - URL respjson.Field - ExtraFields map[string]respjson.Field - raw string + WebFetchRequests respjson.Field + WebSearchRequests respjson.Field + ExtraFields map[string]respjson.Field + raw string } `json:"-"` } // Returns the unmodified JSON received from the API -func (r BetaWebFetchBlock) RawJSON() string { return r.JSON.raw } -func (r *BetaWebFetchBlock) UnmarshalJSON(data []byte) error { +func (r BetaServerToolUsage) RawJSON() string { return r.JSON.raw } +func (r *BetaServerToolUsage) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The properties Content, Type, URL are required. -type BetaWebFetchBlockParam struct { - Content BetaRequestDocumentBlockParam `json:"content,omitzero" api:"required"` - // Fetched content URL - URL string `json:"url" api:"required"` - // ISO 8601 timestamp when the content was retrieved - RetrievedAt param.Opt[string] `json:"retrieved_at,omitzero"` - // This field can be elided, and will marshal its zero value as "web_fetch_result". - Type constant.WebFetchResult `json:"type" default:"web_fetch_result"` - paramObj +type BetaServerToolUseBlock struct { + ID string `json:"id" api:"required"` + Input any `json:"input" api:"required"` + // Any of "advisor", "web_search", "web_fetch", "code_execution", + // "bash_code_execution", "text_editor_code_execution", "tool_search_tool_regex", + // "tool_search_tool_bm25". + Name BetaServerToolUseBlockName `json:"name" api:"required"` + Type constant.ServerToolUse `json:"type" default:"server_tool_use"` + // Tool invocation directly from the model. + Caller BetaServerToolUseBlockCallerUnion `json:"caller"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + Input respjson.Field + Name respjson.Field + Type respjson.Field + Caller respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` } -func (r BetaWebFetchBlockParam) MarshalJSON() (data []byte, err error) { - type shadow BetaWebFetchBlockParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaWebFetchBlockParam) UnmarshalJSON(data []byte) error { +// Returns the unmodified JSON received from the API +func (r BetaServerToolUseBlock) RawJSON() string { return r.JSON.raw } +func (r *BetaServerToolUseBlock) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The properties Name, Type are required. -type BetaWebFetchTool20250910Param struct { - // Maximum number of tokens used by including web page text content in the context. - // The limit is approximate and does not apply to binary content such as PDFs. - MaxContentTokens param.Opt[int64] `json:"max_content_tokens,omitzero"` - // Maximum number of times the tool can be used in the API request. - MaxUses param.Opt[int64] `json:"max_uses,omitzero"` - // If true, tool will not be included in initial system prompt. Only loaded when - // returned via tool_reference from tool search. - DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` - // When true, guarantees schema validation on tool names and inputs - Strict param.Opt[bool] `json:"strict,omitzero"` - // List of domains to allow fetching from - AllowedDomains []string `json:"allowed_domains,omitzero"` - // List of domains to block fetching from - BlockedDomains []string `json:"blocked_domains,omitzero"` +type BetaServerToolUseBlockName string + +const ( + BetaServerToolUseBlockNameAdvisor BetaServerToolUseBlockName = "advisor" + BetaServerToolUseBlockNameWebSearch BetaServerToolUseBlockName = "web_search" + BetaServerToolUseBlockNameWebFetch BetaServerToolUseBlockName = "web_fetch" + BetaServerToolUseBlockNameCodeExecution BetaServerToolUseBlockName = "code_execution" + BetaServerToolUseBlockNameBashCodeExecution BetaServerToolUseBlockName = "bash_code_execution" + BetaServerToolUseBlockNameTextEditorCodeExecution BetaServerToolUseBlockName = "text_editor_code_execution" + BetaServerToolUseBlockNameToolSearchToolRegex BetaServerToolUseBlockName = "tool_search_tool_regex" + BetaServerToolUseBlockNameToolSearchToolBm25 BetaServerToolUseBlockName = "tool_search_tool_bm25" +) + +// BetaServerToolUseBlockCallerUnion contains all possible properties and values +// from [BetaDirectCaller], [BetaServerToolCaller], [BetaServerToolCaller20260120]. +// +// Use the [BetaServerToolUseBlockCallerUnion.AsAny] method to switch on the +// variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaServerToolUseBlockCallerUnion struct { // Any of "direct", "code_execution_20250825", "code_execution_20260120". - AllowedCallers []string `json:"allowed_callers,omitzero"` - // Create a cache control breakpoint at this content block. - CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` - // Citations configuration for fetched documents. Citations are disabled by - // default. - Citations BetaCitationsConfigParam `json:"citations,omitzero"` - // Name of the tool. - // - // This is how the tool will be called by the model and in `tool_use` blocks. - // - // This field can be elided, and will marshal its zero value as "web_fetch". - Name constant.WebFetch `json:"name" default:"web_fetch"` - // This field can be elided, and will marshal its zero value as - // "web_fetch_20250910". - Type constant.WebFetch20250910 `json:"type" default:"web_fetch_20250910"` - paramObj + Type string `json:"type"` + ToolID string `json:"tool_id"` + JSON struct { + Type respjson.Field + ToolID respjson.Field + raw string + } `json:"-"` } -func (r BetaWebFetchTool20250910Param) MarshalJSON() (data []byte, err error) { - type shadow BetaWebFetchTool20250910Param - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaWebFetchTool20250910Param) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +// anyBetaServerToolUseBlockCaller is implemented by each variant of +// [BetaServerToolUseBlockCallerUnion] to add type safety for the return type of +// [BetaServerToolUseBlockCallerUnion.AsAny] +type anyBetaServerToolUseBlockCaller interface { + implBetaServerToolUseBlockCallerUnion() } -// The properties Name, Type are required. -type BetaWebFetchTool20260209Param struct { - // Maximum number of tokens used by including web page text content in the context. - // The limit is approximate and does not apply to binary content such as PDFs. - MaxContentTokens param.Opt[int64] `json:"max_content_tokens,omitzero"` - // Maximum number of times the tool can be used in the API request. - MaxUses param.Opt[int64] `json:"max_uses,omitzero"` - // If true, tool will not be included in initial system prompt. Only loaded when - // returned via tool_reference from tool search. - DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` - // When true, guarantees schema validation on tool names and inputs - Strict param.Opt[bool] `json:"strict,omitzero"` - // List of domains to allow fetching from - AllowedDomains []string `json:"allowed_domains,omitzero"` - // List of domains to block fetching from - BlockedDomains []string `json:"blocked_domains,omitzero"` - // Any of "direct", "code_execution_20250825", "code_execution_20260120". - AllowedCallers []string `json:"allowed_callers,omitzero"` - // Create a cache control breakpoint at this content block. - CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` - // Citations configuration for fetched documents. Citations are disabled by - // default. - Citations BetaCitationsConfigParam `json:"citations,omitzero"` - // Name of the tool. - // - // This is how the tool will be called by the model and in `tool_use` blocks. - // - // This field can be elided, and will marshal its zero value as "web_fetch". - Name constant.WebFetch `json:"name" default:"web_fetch"` - // This field can be elided, and will marshal its zero value as - // "web_fetch_20260209". - Type constant.WebFetch20260209 `json:"type" default:"web_fetch_20260209"` - paramObj -} - -func (r BetaWebFetchTool20260209Param) MarshalJSON() (data []byte, err error) { - type shadow BetaWebFetchTool20260209Param - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaWebFetchTool20260209Param) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Web fetch tool with use_cache parameter for bypassing cached content. -// -// The properties Name, Type are required. -type BetaWebFetchTool20260309Param struct { - // Maximum number of tokens used by including web page text content in the context. - // The limit is approximate and does not apply to binary content such as PDFs. - MaxContentTokens param.Opt[int64] `json:"max_content_tokens,omitzero"` - // Maximum number of times the tool can be used in the API request. - MaxUses param.Opt[int64] `json:"max_uses,omitzero"` - // If true, tool will not be included in initial system prompt. Only loaded when - // returned via tool_reference from tool search. - DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` - // When true, guarantees schema validation on tool names and inputs - Strict param.Opt[bool] `json:"strict,omitzero"` - // Whether to use cached content. Set to false to bypass the cache and fetch fresh - // content. Only set to false when the user explicitly requests fresh content or - // when fetching rapidly-changing sources. - UseCache param.Opt[bool] `json:"use_cache,omitzero"` - // List of domains to allow fetching from - AllowedDomains []string `json:"allowed_domains,omitzero"` - // List of domains to block fetching from - BlockedDomains []string `json:"blocked_domains,omitzero"` - // Any of "direct", "code_execution_20250825", "code_execution_20260120". - AllowedCallers []string `json:"allowed_callers,omitzero"` - // Create a cache control breakpoint at this content block. - CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` - // Citations configuration for fetched documents. Citations are disabled by - // default. - Citations BetaCitationsConfigParam `json:"citations,omitzero"` - // Name of the tool. - // - // This is how the tool will be called by the model and in `tool_use` blocks. - // - // This field can be elided, and will marshal its zero value as "web_fetch". - Name constant.WebFetch `json:"name" default:"web_fetch"` - // This field can be elided, and will marshal its zero value as - // "web_fetch_20260309". - Type constant.WebFetch20260309 `json:"type" default:"web_fetch_20260309"` - paramObj -} - -func (r BetaWebFetchTool20260309Param) MarshalJSON() (data []byte, err error) { - type shadow BetaWebFetchTool20260309Param - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaWebFetchTool20260309Param) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type BetaWebFetchToolResultBlock struct { - Content BetaWebFetchToolResultBlockContentUnion `json:"content" api:"required"` - ToolUseID string `json:"tool_use_id" api:"required"` - Type constant.WebFetchToolResult `json:"type" default:"web_fetch_tool_result"` - // Tool invocation directly from the model. - Caller BetaWebFetchToolResultBlockCallerUnion `json:"caller"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Content respjson.Field - ToolUseID respjson.Field - Type respjson.Field - Caller respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r BetaWebFetchToolResultBlock) RawJSON() string { return r.JSON.raw } -func (r *BetaWebFetchToolResultBlock) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// BetaWebFetchToolResultBlockContentUnion contains all possible properties and -// values from [BetaWebFetchToolResultErrorBlock], [BetaWebFetchBlock]. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -type BetaWebFetchToolResultBlockContentUnion struct { - // This field is from variant [BetaWebFetchToolResultErrorBlock]. - ErrorCode BetaWebFetchToolResultErrorCode `json:"error_code"` - Type string `json:"type"` - // This field is from variant [BetaWebFetchBlock]. - Content BetaDocumentBlock `json:"content"` - // This field is from variant [BetaWebFetchBlock]. - RetrievedAt string `json:"retrieved_at"` - // This field is from variant [BetaWebFetchBlock]. - URL string `json:"url"` - JSON struct { - ErrorCode respjson.Field - Type respjson.Field - Content respjson.Field - RetrievedAt respjson.Field - URL respjson.Field - raw string - } `json:"-"` -} - -func (u BetaWebFetchToolResultBlockContentUnion) AsResponseWebFetchToolResultError() (v BetaWebFetchToolResultErrorBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u BetaWebFetchToolResultBlockContentUnion) AsResponseWebFetchResultBlock() (v BetaWebFetchBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -// Returns the unmodified JSON received from the API -func (u BetaWebFetchToolResultBlockContentUnion) RawJSON() string { return u.JSON.raw } - -func (r *BetaWebFetchToolResultBlockContentUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// BetaWebFetchToolResultBlockCallerUnion contains all possible properties and -// values from [BetaDirectCaller], [BetaServerToolCaller], -// [BetaServerToolCaller20260120]. -// -// Use the [BetaWebFetchToolResultBlockCallerUnion.AsAny] method to switch on the -// variant. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -type BetaWebFetchToolResultBlockCallerUnion struct { - // Any of "direct", "code_execution_20250825", "code_execution_20260120". - Type string `json:"type"` - ToolID string `json:"tool_id"` - JSON struct { - Type respjson.Field - ToolID respjson.Field - raw string - } `json:"-"` -} - -// anyBetaWebFetchToolResultBlockCaller is implemented by each variant of -// [BetaWebFetchToolResultBlockCallerUnion] to add type safety for the return type -// of [BetaWebFetchToolResultBlockCallerUnion.AsAny] -type anyBetaWebFetchToolResultBlockCaller interface { - implBetaWebFetchToolResultBlockCallerUnion() -} - -func (BetaDirectCaller) implBetaWebFetchToolResultBlockCallerUnion() {} -func (BetaServerToolCaller) implBetaWebFetchToolResultBlockCallerUnion() {} -func (BetaServerToolCaller20260120) implBetaWebFetchToolResultBlockCallerUnion() {} +func (BetaDirectCaller) implBetaServerToolUseBlockCallerUnion() {} +func (BetaServerToolCaller) implBetaServerToolUseBlockCallerUnion() {} +func (BetaServerToolCaller20260120) implBetaServerToolUseBlockCallerUnion() {} // Use the following switch statement to find the correct variant // -// switch variant := BetaWebFetchToolResultBlockCallerUnion.AsAny().(type) { +// switch variant := BetaServerToolUseBlockCallerUnion.AsAny().(type) { // case anthropic.BetaDirectCaller: // case anthropic.BetaServerToolCaller: // case anthropic.BetaServerToolCaller20260120: // default: // fmt.Errorf("no variant present") // } -func (u BetaWebFetchToolResultBlockCallerUnion) AsAny() anyBetaWebFetchToolResultBlockCaller { +func (u BetaServerToolUseBlockCallerUnion) AsAny() anyBetaServerToolUseBlockCaller { switch u.Type { case "direct": return u.AsDirect() @@ -10533,147 +9689,96 @@ func (u BetaWebFetchToolResultBlockCallerUnion) AsAny() anyBetaWebFetchToolResul return nil } -func (u BetaWebFetchToolResultBlockCallerUnion) AsDirect() (v BetaDirectCaller) { +func (u BetaServerToolUseBlockCallerUnion) AsDirect() (v BetaDirectCaller) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return } -func (u BetaWebFetchToolResultBlockCallerUnion) AsCodeExecution20250825() (v BetaServerToolCaller) { +func (u BetaServerToolUseBlockCallerUnion) AsCodeExecution20250825() (v BetaServerToolCaller) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return } -func (u BetaWebFetchToolResultBlockCallerUnion) AsCodeExecution20260120() (v BetaServerToolCaller20260120) { +func (u BetaServerToolUseBlockCallerUnion) AsCodeExecution20260120() (v BetaServerToolCaller20260120) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return } // Returns the unmodified JSON received from the API -func (u BetaWebFetchToolResultBlockCallerUnion) RawJSON() string { return u.JSON.raw } +func (u BetaServerToolUseBlockCallerUnion) RawJSON() string { return u.JSON.raw } -func (r *BetaWebFetchToolResultBlockCallerUnion) UnmarshalJSON(data []byte) error { +func (r *BetaServerToolUseBlockCallerUnion) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The properties Content, ToolUseID, Type are required. -type BetaWebFetchToolResultBlockParam struct { - Content BetaWebFetchToolResultBlockParamContentUnion `json:"content,omitzero" api:"required"` - ToolUseID string `json:"tool_use_id" api:"required"` +// The properties ID, Input, Name, Type are required. +type BetaServerToolUseBlockParam struct { + ID string `json:"id" api:"required"` + Input any `json:"input,omitzero" api:"required"` + // Any of "advisor", "web_search", "web_fetch", "code_execution", + // "bash_code_execution", "text_editor_code_execution", "tool_search_tool_regex", + // "tool_search_tool_bm25". + Name BetaServerToolUseBlockParamName `json:"name,omitzero" api:"required"` // Create a cache control breakpoint at this content block. CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` // Tool invocation directly from the model. - Caller BetaWebFetchToolResultBlockParamCallerUnion `json:"caller,omitzero"` - // This field can be elided, and will marshal its zero value as - // "web_fetch_tool_result". - Type constant.WebFetchToolResult `json:"type" default:"web_fetch_tool_result"` + Caller BetaServerToolUseBlockParamCallerUnion `json:"caller,omitzero"` + // This field can be elided, and will marshal its zero value as "server_tool_use". + Type constant.ServerToolUse `json:"type" default:"server_tool_use"` paramObj } -func (r BetaWebFetchToolResultBlockParam) MarshalJSON() (data []byte, err error) { - type shadow BetaWebFetchToolResultBlockParam +func (r BetaServerToolUseBlockParam) MarshalJSON() (data []byte, err error) { + type shadow BetaServerToolUseBlockParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *BetaWebFetchToolResultBlockParam) UnmarshalJSON(data []byte) error { +func (r *BetaServerToolUseBlockParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } +type BetaServerToolUseBlockParamName string + +const ( + BetaServerToolUseBlockParamNameAdvisor BetaServerToolUseBlockParamName = "advisor" + BetaServerToolUseBlockParamNameWebSearch BetaServerToolUseBlockParamName = "web_search" + BetaServerToolUseBlockParamNameWebFetch BetaServerToolUseBlockParamName = "web_fetch" + BetaServerToolUseBlockParamNameCodeExecution BetaServerToolUseBlockParamName = "code_execution" + BetaServerToolUseBlockParamNameBashCodeExecution BetaServerToolUseBlockParamName = "bash_code_execution" + BetaServerToolUseBlockParamNameTextEditorCodeExecution BetaServerToolUseBlockParamName = "text_editor_code_execution" + BetaServerToolUseBlockParamNameToolSearchToolRegex BetaServerToolUseBlockParamName = "tool_search_tool_regex" + BetaServerToolUseBlockParamNameToolSearchToolBm25 BetaServerToolUseBlockParamName = "tool_search_tool_bm25" +) + // Only one field can be non-zero. // // Use [param.IsOmitted] to confirm if a field is set. -type BetaWebFetchToolResultBlockParamContentUnion struct { - OfRequestWebFetchToolResultError *BetaWebFetchToolResultErrorBlockParam `json:",omitzero,inline"` - OfRequestWebFetchResultBlock *BetaWebFetchBlockParam `json:",omitzero,inline"` +type BetaServerToolUseBlockParamCallerUnion struct { + OfDirect *BetaDirectCallerParam `json:",omitzero,inline"` + OfCodeExecution20250825 *BetaServerToolCallerParam `json:",omitzero,inline"` + OfCodeExecution20260120 *BetaServerToolCaller20260120Param `json:",omitzero,inline"` paramUnion } -func (u BetaWebFetchToolResultBlockParamContentUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfRequestWebFetchToolResultError, u.OfRequestWebFetchResultBlock) +func (u BetaServerToolUseBlockParamCallerUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfDirect, u.OfCodeExecution20250825, u.OfCodeExecution20260120) } -func (u *BetaWebFetchToolResultBlockParamContentUnion) UnmarshalJSON(data []byte) error { +func (u *BetaServerToolUseBlockParamCallerUnion) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, u) } -func (u *BetaWebFetchToolResultBlockParamContentUnion) asAny() any { - if !param.IsOmitted(u.OfRequestWebFetchToolResultError) { - return u.OfRequestWebFetchToolResultError - } else if !param.IsOmitted(u.OfRequestWebFetchResultBlock) { - return u.OfRequestWebFetchResultBlock +func (u *BetaServerToolUseBlockParamCallerUnion) asAny() any { + if !param.IsOmitted(u.OfDirect) { + return u.OfDirect + } else if !param.IsOmitted(u.OfCodeExecution20250825) { + return u.OfCodeExecution20250825 + } else if !param.IsOmitted(u.OfCodeExecution20260120) { + return u.OfCodeExecution20260120 } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u BetaWebFetchToolResultBlockParamContentUnion) GetErrorCode() *string { - if vt := u.OfRequestWebFetchToolResultError; vt != nil { - return (*string)(&vt.ErrorCode) - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u BetaWebFetchToolResultBlockParamContentUnion) GetContent() *BetaRequestDocumentBlockParam { - if vt := u.OfRequestWebFetchResultBlock; vt != nil { - return &vt.Content - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u BetaWebFetchToolResultBlockParamContentUnion) GetURL() *string { - if vt := u.OfRequestWebFetchResultBlock; vt != nil { - return &vt.URL - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u BetaWebFetchToolResultBlockParamContentUnion) GetRetrievedAt() *string { - if vt := u.OfRequestWebFetchResultBlock; vt != nil && vt.RetrievedAt.Valid() { - return &vt.RetrievedAt.Value - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u BetaWebFetchToolResultBlockParamContentUnion) GetType() *string { - if vt := u.OfRequestWebFetchToolResultError; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfRequestWebFetchResultBlock; vt != nil { - return (*string)(&vt.Type) - } - return nil -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type BetaWebFetchToolResultBlockParamCallerUnion struct { - OfDirect *BetaDirectCallerParam `json:",omitzero,inline"` - OfCodeExecution20250825 *BetaServerToolCallerParam `json:",omitzero,inline"` - OfCodeExecution20260120 *BetaServerToolCaller20260120Param `json:",omitzero,inline"` - paramUnion -} - -func (u BetaWebFetchToolResultBlockParamCallerUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfDirect, u.OfCodeExecution20250825, u.OfCodeExecution20260120) -} -func (u *BetaWebFetchToolResultBlockParamCallerUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *BetaWebFetchToolResultBlockParamCallerUnion) asAny() any { - if !param.IsOmitted(u.OfDirect) { - return u.OfDirect - } else if !param.IsOmitted(u.OfCodeExecution20250825) { - return u.OfCodeExecution20250825 - } else if !param.IsOmitted(u.OfCodeExecution20260120) { - return u.OfCodeExecution20260120 - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u BetaWebFetchToolResultBlockParamCallerUnion) GetType() *string { +func (u BetaServerToolUseBlockParamCallerUnion) GetType() *string { if vt := u.OfDirect; vt != nil { return (*string)(&vt.Type) } else if vt := u.OfCodeExecution20250825; vt != nil { @@ -10685,7 +9790,7 @@ func (u BetaWebFetchToolResultBlockParamCallerUnion) GetType() *string { } // Returns a pointer to the underlying variant's property, if present. -func (u BetaWebFetchToolResultBlockParamCallerUnion) GetToolID() *string { +func (u BetaServerToolUseBlockParamCallerUnion) GetToolID() *string { if vt := u.OfCodeExecution20250825; vt != nil { return (*string)(&vt.ToolID) } else if vt := u.OfCodeExecution20260120; vt != nil { @@ -10695,7 +9800,7 @@ func (u BetaWebFetchToolResultBlockParamCallerUnion) GetToolID() *string { } func init() { - apijson.RegisterUnion[BetaWebFetchToolResultBlockParamCallerUnion]( + apijson.RegisterUnion[BetaServerToolUseBlockParamCallerUnion]( "type", apijson.Discriminator[BetaDirectCallerParam]("direct"), apijson.Discriminator[BetaServerToolCallerParam]("code_execution_20250825"), @@ -10703,15 +9808,15 @@ func init() { ) } -type BetaWebFetchToolResultErrorBlock struct { - // Any of "invalid_tool_input", "url_too_long", "url_not_allowed", - // "url_not_accessible", "unsupported_content_type", "too_many_requests", - // "max_uses_exceeded", "unavailable". - ErrorCode BetaWebFetchToolResultErrorCode `json:"error_code" api:"required"` - Type constant.WebFetchToolResultError `json:"type" default:"web_fetch_tool_result_error"` +type BetaSignatureDelta struct { + // The `signature` for this thinking block: an opaque value used to verify that the + // block was generated by Claude when it is passed back to the API. Delivered in a + // `signature_delta` event just before the block's `content_block_stop` event. + Signature string `json:"signature" api:"required"` + Type constant.SignatureDelta `json:"type" default:"signature_delta"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { - ErrorCode respjson.Field + Signature respjson.Field Type respjson.Field ExtraFields map[string]respjson.Field raw string @@ -10719,447 +9824,466 @@ type BetaWebFetchToolResultErrorBlock struct { } // Returns the unmodified JSON received from the API -func (r BetaWebFetchToolResultErrorBlock) RawJSON() string { return r.JSON.raw } -func (r *BetaWebFetchToolResultErrorBlock) UnmarshalJSON(data []byte) error { +func (r BetaSignatureDelta) RawJSON() string { return r.JSON.raw } +func (r *BetaSignatureDelta) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The properties ErrorCode, Type are required. -type BetaWebFetchToolResultErrorBlockParam struct { - // Any of "invalid_tool_input", "url_too_long", "url_not_allowed", - // "url_not_accessible", "unsupported_content_type", "too_many_requests", - // "max_uses_exceeded", "unavailable". - ErrorCode BetaWebFetchToolResultErrorCode `json:"error_code,omitzero" api:"required"` - // This field can be elided, and will marshal its zero value as - // "web_fetch_tool_result_error". - Type constant.WebFetchToolResultError `json:"type" default:"web_fetch_tool_result_error"` +// A skill that was loaded in a container (response model). +type BetaSkill struct { + // Skill ID + SkillID string `json:"skill_id" api:"required"` + // Type of skill - either 'anthropic' (built-in) or 'custom' (user-defined) + // + // Any of "anthropic", "custom". + Type BetaSkillType `json:"type" api:"required"` + // The resolved version: a skill version ID for custom skills. + Version string `json:"version" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + SkillID respjson.Field + Type respjson.Field + Version respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaSkill) RawJSON() string { return r.JSON.raw } +func (r *BetaSkill) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Type of skill - either 'anthropic' (built-in) or 'custom' (user-defined) +type BetaSkillType string + +const ( + BetaSkillTypeAnthropic BetaSkillType = "anthropic" + BetaSkillTypeCustom BetaSkillType = "custom" +) + +// Specification for a skill to be loaded in a container (request model). +// +// The properties SkillID, Type are required. +type BetaSkillParams struct { + // Skill ID + SkillID string `json:"skill_id" api:"required"` + // Type of skill - either 'anthropic' (built-in) or 'custom' (user-defined) + // + // Any of "anthropic", "custom". + Type BetaSkillParamsType `json:"type,omitzero" api:"required"` + // Skill version or 'latest' for most recent version + Version param.Opt[string] `json:"version,omitzero"` paramObj } -func (r BetaWebFetchToolResultErrorBlockParam) MarshalJSON() (data []byte, err error) { - type shadow BetaWebFetchToolResultErrorBlockParam +func (r BetaSkillParams) MarshalJSON() (data []byte, err error) { + type shadow BetaSkillParams return param.MarshalObject(r, (*shadow)(&r)) } -func (r *BetaWebFetchToolResultErrorBlockParam) UnmarshalJSON(data []byte) error { +func (r *BetaSkillParams) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type BetaWebFetchToolResultErrorCode string +// Type of skill - either 'anthropic' (built-in) or 'custom' (user-defined) +type BetaSkillParamsType string const ( - BetaWebFetchToolResultErrorCodeInvalidToolInput BetaWebFetchToolResultErrorCode = "invalid_tool_input" - BetaWebFetchToolResultErrorCodeURLTooLong BetaWebFetchToolResultErrorCode = "url_too_long" - BetaWebFetchToolResultErrorCodeURLNotAllowed BetaWebFetchToolResultErrorCode = "url_not_allowed" - BetaWebFetchToolResultErrorCodeURLNotAccessible BetaWebFetchToolResultErrorCode = "url_not_accessible" - BetaWebFetchToolResultErrorCodeUnsupportedContentType BetaWebFetchToolResultErrorCode = "unsupported_content_type" - BetaWebFetchToolResultErrorCodeTooManyRequests BetaWebFetchToolResultErrorCode = "too_many_requests" - BetaWebFetchToolResultErrorCodeMaxUsesExceeded BetaWebFetchToolResultErrorCode = "max_uses_exceeded" - BetaWebFetchToolResultErrorCodeUnavailable BetaWebFetchToolResultErrorCode = "unavailable" + BetaSkillParamsTypeAnthropic BetaSkillParamsType = "anthropic" + BetaSkillParamsTypeCustom BetaSkillParamsType = "custom" ) -type BetaWebSearchResultBlock struct { - EncryptedContent string `json:"encrypted_content" api:"required"` - PageAge string `json:"page_age" api:"required"` - Title string `json:"title" api:"required"` - Type constant.WebSearchResult `json:"type" default:"web_search_result"` - URL string `json:"url" api:"required"` +type BetaStopReason string + +const ( + BetaStopReasonEndTurn BetaStopReason = "end_turn" + BetaStopReasonMaxTokens BetaStopReason = "max_tokens" + BetaStopReasonStopSequence BetaStopReason = "stop_sequence" + BetaStopReasonToolUse BetaStopReason = "tool_use" + BetaStopReasonPauseTurn BetaStopReason = "pause_turn" + BetaStopReasonCompaction BetaStopReason = "compaction" + BetaStopReasonRefusal BetaStopReason = "refusal" + BetaStopReasonModelContextWindowExceeded BetaStopReason = "model_context_window_exceeded" +) + +type BetaTextBlock struct { + // Citations supporting the text block. + // + // The type of citation returned will depend on the type of document being cited. + // Citing a PDF results in `page_location`, plain text results in `char_location`, + // and content document results in `content_block_location`. + Citations []BetaTextCitationUnion `json:"citations" api:"required"` + Text string `json:"text" api:"required"` + Type constant.Text `json:"type" default:"text"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { - EncryptedContent respjson.Field - PageAge respjson.Field - Title respjson.Field - Type respjson.Field - URL respjson.Field - ExtraFields map[string]respjson.Field - raw string + Citations respjson.Field + Text respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string } `json:"-"` } // Returns the unmodified JSON received from the API -func (r BetaWebSearchResultBlock) RawJSON() string { return r.JSON.raw } -func (r *BetaWebSearchResultBlock) UnmarshalJSON(data []byte) error { +func (r BetaTextBlock) RawJSON() string { return r.JSON.raw } +func (r *BetaTextBlock) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The properties EncryptedContent, Title, Type, URL are required. -type BetaWebSearchResultBlockParam struct { - EncryptedContent string `json:"encrypted_content" api:"required"` - Title string `json:"title" api:"required"` - URL string `json:"url" api:"required"` - PageAge param.Opt[string] `json:"page_age,omitzero"` - // This field can be elided, and will marshal its zero value as - // "web_search_result". - Type constant.WebSearchResult `json:"type" default:"web_search_result"` +// The properties Text, Type are required. +type BetaTextBlockParam struct { + Text string `json:"text" api:"required"` + Citations []BetaTextCitationParamUnion `json:"citations,omitzero"` + // Create a cache control breakpoint at this content block. + CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` + // This field can be elided, and will marshal its zero value as "text". + Type constant.Text `json:"type" default:"text"` paramObj } -func (r BetaWebSearchResultBlockParam) MarshalJSON() (data []byte, err error) { - type shadow BetaWebSearchResultBlockParam +func (r BetaTextBlockParam) MarshalJSON() (data []byte, err error) { + type shadow BetaTextBlockParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *BetaWebSearchResultBlockParam) UnmarshalJSON(data []byte) error { +func (r *BetaTextBlockParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The properties Name, Type are required. -type BetaWebSearchTool20250305Param struct { - // Maximum number of times the tool can be used in the API request. - MaxUses param.Opt[int64] `json:"max_uses,omitzero"` - // If true, tool will not be included in initial system prompt. Only loaded when - // returned via tool_reference from tool search. - DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` - // When true, guarantees schema validation on tool names and inputs - Strict param.Opt[bool] `json:"strict,omitzero"` - // If provided, only these domains will be included in results. Cannot be used - // alongside `blocked_domains`. - AllowedDomains []string `json:"allowed_domains,omitzero"` - // If provided, these domains will never appear in results. Cannot be used - // alongside `allowed_domains`. - BlockedDomains []string `json:"blocked_domains,omitzero"` - // Any of "direct", "code_execution_20250825", "code_execution_20260120". - AllowedCallers []string `json:"allowed_callers,omitzero"` - // Create a cache control breakpoint at this content block. - CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` - // Parameters for the user's location. Used to provide more relevant search - // results. - UserLocation BetaUserLocationParam `json:"user_location,omitzero"` - // Name of the tool. - // - // This is how the tool will be called by the model and in `tool_use` blocks. - // - // This field can be elided, and will marshal its zero value as "web_search". - Name constant.WebSearch `json:"name" default:"web_search"` - // This field can be elided, and will marshal its zero value as - // "web_search_20250305". - Type constant.WebSearch20250305 `json:"type" default:"web_search_20250305"` - paramObj -} - -func (r BetaWebSearchTool20250305Param) MarshalJSON() (data []byte, err error) { - type shadow BetaWebSearchTool20250305Param - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaWebSearchTool20250305Param) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The properties Name, Type are required. -type BetaWebSearchTool20260209Param struct { - // Maximum number of times the tool can be used in the API request. - MaxUses param.Opt[int64] `json:"max_uses,omitzero"` - // If true, tool will not be included in initial system prompt. Only loaded when - // returned via tool_reference from tool search. - DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` - // When true, guarantees schema validation on tool names and inputs - Strict param.Opt[bool] `json:"strict,omitzero"` - // If provided, only these domains will be included in results. Cannot be used - // alongside `blocked_domains`. - AllowedDomains []string `json:"allowed_domains,omitzero"` - // If provided, these domains will never appear in results. Cannot be used - // alongside `allowed_domains`. - BlockedDomains []string `json:"blocked_domains,omitzero"` - // Any of "direct", "code_execution_20250825", "code_execution_20260120". - AllowedCallers []string `json:"allowed_callers,omitzero"` - // Create a cache control breakpoint at this content block. - CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` - // Parameters for the user's location. Used to provide more relevant search - // results. - UserLocation BetaUserLocationParam `json:"user_location,omitzero"` - // Name of the tool. - // - // This is how the tool will be called by the model and in `tool_use` blocks. - // - // This field can be elided, and will marshal its zero value as "web_search". - Name constant.WebSearch `json:"name" default:"web_search"` - // This field can be elided, and will marshal its zero value as - // "web_search_20260209". - Type constant.WebSearch20260209 `json:"type" default:"web_search_20260209"` - paramObj -} - -func (r BetaWebSearchTool20260209Param) MarshalJSON() (data []byte, err error) { - type shadow BetaWebSearchTool20260209Param - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaWebSearchTool20260209Param) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The properties ErrorCode, Type are required. -type BetaWebSearchToolRequestErrorParam struct { - // Any of "invalid_tool_input", "unavailable", "max_uses_exceeded", - // "too_many_requests", "query_too_long", "request_too_large". - ErrorCode BetaWebSearchToolResultErrorCode `json:"error_code,omitzero" api:"required"` - // This field can be elided, and will marshal its zero value as - // "web_search_tool_result_error". - Type constant.WebSearchToolResultError `json:"type" default:"web_search_tool_result_error"` - paramObj -} - -func (r BetaWebSearchToolRequestErrorParam) MarshalJSON() (data []byte, err error) { - type shadow BetaWebSearchToolRequestErrorParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaWebSearchToolRequestErrorParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type BetaWebSearchToolResultBlock struct { - Content BetaWebSearchToolResultBlockContentUnion `json:"content" api:"required"` - ToolUseID string `json:"tool_use_id" api:"required"` - Type constant.WebSearchToolResult `json:"type" default:"web_search_tool_result"` - // Tool invocation directly from the model. - Caller BetaWebSearchToolResultBlockCallerUnion `json:"caller"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Content respjson.Field - ToolUseID respjson.Field - Type respjson.Field - Caller respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r BetaWebSearchToolResultBlock) RawJSON() string { return r.JSON.raw } -func (r *BetaWebSearchToolResultBlock) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// BetaWebSearchToolResultBlockCallerUnion contains all possible properties and -// values from [BetaDirectCaller], [BetaServerToolCaller], -// [BetaServerToolCaller20260120]. +// BetaTextCitationUnion contains all possible properties and values from +// [BetaCitationCharLocation], [BetaCitationPageLocation], +// [BetaCitationContentBlockLocation], [BetaCitationsWebSearchResultLocation], +// [BetaCitationSearchResultLocation]. // -// Use the [BetaWebSearchToolResultBlockCallerUnion.AsAny] method to switch on the -// variant. +// Use the [BetaTextCitationUnion.AsAny] method to switch on the variant. // // Use the methods beginning with 'As' to cast the union to one of its variants. -type BetaWebSearchToolResultBlockCallerUnion struct { - // Any of "direct", "code_execution_20250825", "code_execution_20260120". - Type string `json:"type"` - ToolID string `json:"tool_id"` +type BetaTextCitationUnion struct { + CitedText string `json:"cited_text"` + DocumentIndex int64 `json:"document_index"` + DocumentTitle string `json:"document_title"` + // This field is from variant [BetaCitationCharLocation]. + EndCharIndex int64 `json:"end_char_index"` + FileID string `json:"file_id"` + // This field is from variant [BetaCitationCharLocation]. + StartCharIndex int64 `json:"start_char_index"` + // Any of "char_location", "page_location", "content_block_location", + // "web_search_result_location", "search_result_location". + Type string `json:"type"` + // This field is from variant [BetaCitationPageLocation]. + EndPageNumber int64 `json:"end_page_number"` + // This field is from variant [BetaCitationPageLocation]. + StartPageNumber int64 `json:"start_page_number"` + EndBlockIndex int64 `json:"end_block_index"` + StartBlockIndex int64 `json:"start_block_index"` + // This field is from variant [BetaCitationsWebSearchResultLocation]. + EncryptedIndex string `json:"encrypted_index"` + Title string `json:"title"` + // This field is from variant [BetaCitationsWebSearchResultLocation]. + URL string `json:"url"` + // This field is from variant [BetaCitationSearchResultLocation]. + SearchResultIndex int64 `json:"search_result_index"` + // This field is from variant [BetaCitationSearchResultLocation]. + Source string `json:"source"` JSON struct { - Type respjson.Field - ToolID respjson.Field - raw string + CitedText respjson.Field + DocumentIndex respjson.Field + DocumentTitle respjson.Field + EndCharIndex respjson.Field + FileID respjson.Field + StartCharIndex respjson.Field + Type respjson.Field + EndPageNumber respjson.Field + StartPageNumber respjson.Field + EndBlockIndex respjson.Field + StartBlockIndex respjson.Field + EncryptedIndex respjson.Field + Title respjson.Field + URL respjson.Field + SearchResultIndex respjson.Field + Source respjson.Field + raw string } `json:"-"` } -// anyBetaWebSearchToolResultBlockCaller is implemented by each variant of -// [BetaWebSearchToolResultBlockCallerUnion] to add type safety for the return type -// of [BetaWebSearchToolResultBlockCallerUnion.AsAny] -type anyBetaWebSearchToolResultBlockCaller interface { - implBetaWebSearchToolResultBlockCallerUnion() +// anyBetaTextCitation is implemented by each variant of [BetaTextCitationUnion] to +// add type safety for the return type of [BetaTextCitationUnion.AsAny] +type anyBetaTextCitation interface { + implBetaTextCitationUnion() + toParamUnion() BetaTextCitationParamUnion } -func (BetaDirectCaller) implBetaWebSearchToolResultBlockCallerUnion() {} -func (BetaServerToolCaller) implBetaWebSearchToolResultBlockCallerUnion() {} -func (BetaServerToolCaller20260120) implBetaWebSearchToolResultBlockCallerUnion() {} +func (BetaCitationCharLocation) implBetaTextCitationUnion() {} +func (BetaCitationPageLocation) implBetaTextCitationUnion() {} +func (BetaCitationContentBlockLocation) implBetaTextCitationUnion() {} +func (BetaCitationsWebSearchResultLocation) implBetaTextCitationUnion() {} +func (BetaCitationSearchResultLocation) implBetaTextCitationUnion() {} // Use the following switch statement to find the correct variant // -// switch variant := BetaWebSearchToolResultBlockCallerUnion.AsAny().(type) { -// case anthropic.BetaDirectCaller: -// case anthropic.BetaServerToolCaller: -// case anthropic.BetaServerToolCaller20260120: +// switch variant := BetaTextCitationUnion.AsAny().(type) { +// case anthropic.BetaCitationCharLocation: +// case anthropic.BetaCitationPageLocation: +// case anthropic.BetaCitationContentBlockLocation: +// case anthropic.BetaCitationsWebSearchResultLocation: +// case anthropic.BetaCitationSearchResultLocation: // default: // fmt.Errorf("no variant present") // } -func (u BetaWebSearchToolResultBlockCallerUnion) AsAny() anyBetaWebSearchToolResultBlockCaller { +func (u BetaTextCitationUnion) AsAny() anyBetaTextCitation { switch u.Type { - case "direct": - return u.AsDirect() - case "code_execution_20250825": - return u.AsCodeExecution20250825() - case "code_execution_20260120": - return u.AsCodeExecution20260120() + case "char_location": + return u.AsCharLocation() + case "page_location": + return u.AsPageLocation() + case "content_block_location": + return u.AsContentBlockLocation() + case "web_search_result_location": + return u.AsWebSearchResultLocation() + case "search_result_location": + return u.AsSearchResultLocation() } return nil } -func (u BetaWebSearchToolResultBlockCallerUnion) AsDirect() (v BetaDirectCaller) { +func (u BetaTextCitationUnion) AsCharLocation() (v BetaCitationCharLocation) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return } -func (u BetaWebSearchToolResultBlockCallerUnion) AsCodeExecution20250825() (v BetaServerToolCaller) { +func (u BetaTextCitationUnion) AsPageLocation() (v BetaCitationPageLocation) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return } -func (u BetaWebSearchToolResultBlockCallerUnion) AsCodeExecution20260120() (v BetaServerToolCaller20260120) { +func (u BetaTextCitationUnion) AsContentBlockLocation() (v BetaCitationContentBlockLocation) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return } -// Returns the unmodified JSON received from the API -func (u BetaWebSearchToolResultBlockCallerUnion) RawJSON() string { return u.JSON.raw } - -func (r *BetaWebSearchToolResultBlockCallerUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// BetaWebSearchToolResultBlockContentUnion contains all possible properties and -// values from [BetaWebSearchToolResultError], [[]BetaWebSearchResultBlock]. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -// -// If the underlying value is not a json object, one of the following properties -// will be valid: OfBetaWebSearchResultBlockArray] -type BetaWebSearchToolResultBlockContentUnion struct { - // This field will be present if the value is a [[]BetaWebSearchResultBlock] - // instead of an object. - OfBetaWebSearchResultBlockArray []BetaWebSearchResultBlock `json:",inline"` - // This field is from variant [BetaWebSearchToolResultError]. - ErrorCode BetaWebSearchToolResultErrorCode `json:"error_code"` - // This field is from variant [BetaWebSearchToolResultError]. - Type constant.WebSearchToolResultError `json:"type"` - JSON struct { - OfBetaWebSearchResultBlockArray respjson.Field - ErrorCode respjson.Field - Type respjson.Field - raw string - } `json:"-"` -} - -func (u BetaWebSearchToolResultBlockContentUnion) AsResponseWebSearchToolResultError() (v BetaWebSearchToolResultError) { +func (u BetaTextCitationUnion) AsWebSearchResultLocation() (v BetaCitationsWebSearchResultLocation) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return } -func (u BetaWebSearchToolResultBlockContentUnion) AsBetaWebSearchResultBlockArray() (v []BetaWebSearchResultBlock) { +func (u BetaTextCitationUnion) AsSearchResultLocation() (v BetaCitationSearchResultLocation) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return } // Returns the unmodified JSON received from the API -func (u BetaWebSearchToolResultBlockContentUnion) RawJSON() string { return u.JSON.raw } +func (u BetaTextCitationUnion) RawJSON() string { return u.JSON.raw } -func (r *BetaWebSearchToolResultBlockContentUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The properties Content, ToolUseID, Type are required. -type BetaWebSearchToolResultBlockParam struct { - Content BetaWebSearchToolResultBlockParamContentUnion `json:"content,omitzero" api:"required"` - ToolUseID string `json:"tool_use_id" api:"required"` - // Create a cache control breakpoint at this content block. - CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` - // Tool invocation directly from the model. - Caller BetaWebSearchToolResultBlockParamCallerUnion `json:"caller,omitzero"` - // This field can be elided, and will marshal its zero value as - // "web_search_tool_result". - Type constant.WebSearchToolResult `json:"type" default:"web_search_tool_result"` - paramObj -} - -func (r BetaWebSearchToolResultBlockParam) MarshalJSON() (data []byte, err error) { - type shadow BetaWebSearchToolResultBlockParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaWebSearchToolResultBlockParam) UnmarshalJSON(data []byte) error { +func (r *BetaTextCitationUnion) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } // Only one field can be non-zero. // // Use [param.IsOmitted] to confirm if a field is set. -type BetaWebSearchToolResultBlockParamCallerUnion struct { - OfDirect *BetaDirectCallerParam `json:",omitzero,inline"` - OfCodeExecution20250825 *BetaServerToolCallerParam `json:",omitzero,inline"` - OfCodeExecution20260120 *BetaServerToolCaller20260120Param `json:",omitzero,inline"` +type BetaTextCitationParamUnion struct { + OfCharLocation *BetaCitationCharLocationParam `json:",omitzero,inline"` + OfPageLocation *BetaCitationPageLocationParam `json:",omitzero,inline"` + OfContentBlockLocation *BetaCitationContentBlockLocationParam `json:",omitzero,inline"` + OfWebSearchResultLocation *BetaCitationWebSearchResultLocationParam `json:",omitzero,inline"` + OfSearchResultLocation *BetaCitationSearchResultLocationParam `json:",omitzero,inline"` paramUnion } -func (u BetaWebSearchToolResultBlockParamCallerUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfDirect, u.OfCodeExecution20250825, u.OfCodeExecution20260120) +func (u BetaTextCitationParamUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfCharLocation, + u.OfPageLocation, + u.OfContentBlockLocation, + u.OfWebSearchResultLocation, + u.OfSearchResultLocation) } -func (u *BetaWebSearchToolResultBlockParamCallerUnion) UnmarshalJSON(data []byte) error { +func (u *BetaTextCitationParamUnion) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, u) } -func (u *BetaWebSearchToolResultBlockParamCallerUnion) asAny() any { - if !param.IsOmitted(u.OfDirect) { - return u.OfDirect - } else if !param.IsOmitted(u.OfCodeExecution20250825) { - return u.OfCodeExecution20250825 - } else if !param.IsOmitted(u.OfCodeExecution20260120) { - return u.OfCodeExecution20260120 +func (u *BetaTextCitationParamUnion) asAny() any { + if !param.IsOmitted(u.OfCharLocation) { + return u.OfCharLocation + } else if !param.IsOmitted(u.OfPageLocation) { + return u.OfPageLocation + } else if !param.IsOmitted(u.OfContentBlockLocation) { + return u.OfContentBlockLocation + } else if !param.IsOmitted(u.OfWebSearchResultLocation) { + return u.OfWebSearchResultLocation + } else if !param.IsOmitted(u.OfSearchResultLocation) { + return u.OfSearchResultLocation } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u BetaWebSearchToolResultBlockParamCallerUnion) GetType() *string { - if vt := u.OfDirect; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfCodeExecution20250825; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfCodeExecution20260120; vt != nil { - return (*string)(&vt.Type) +func (u BetaTextCitationParamUnion) GetEndCharIndex() *int64 { + if vt := u.OfCharLocation; vt != nil { + return &vt.EndCharIndex } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u BetaWebSearchToolResultBlockParamCallerUnion) GetToolID() *string { - if vt := u.OfCodeExecution20250825; vt != nil { - return (*string)(&vt.ToolID) - } else if vt := u.OfCodeExecution20260120; vt != nil { - return (*string)(&vt.ToolID) +func (u BetaTextCitationParamUnion) GetStartCharIndex() *int64 { + if vt := u.OfCharLocation; vt != nil { + return &vt.StartCharIndex } return nil } -func init() { - apijson.RegisterUnion[BetaWebSearchToolResultBlockParamCallerUnion]( - "type", - apijson.Discriminator[BetaDirectCallerParam]("direct"), - apijson.Discriminator[BetaServerToolCallerParam]("code_execution_20250825"), - apijson.Discriminator[BetaServerToolCaller20260120Param]("code_execution_20260120"), - ) +// Returns a pointer to the underlying variant's property, if present. +func (u BetaTextCitationParamUnion) GetEndPageNumber() *int64 { + if vt := u.OfPageLocation; vt != nil { + return &vt.EndPageNumber + } + return nil } -func BetaNewWebSearchToolRequestError(errorCode BetaWebSearchToolResultErrorCode) BetaWebSearchToolResultBlockParamContentUnion { - var variant BetaWebSearchToolRequestErrorParam - variant.ErrorCode = errorCode - return BetaWebSearchToolResultBlockParamContentUnion{OfError: &variant} +// Returns a pointer to the underlying variant's property, if present. +func (u BetaTextCitationParamUnion) GetStartPageNumber() *int64 { + if vt := u.OfPageLocation; vt != nil { + return &vt.StartPageNumber + } + return nil } -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type BetaWebSearchToolResultBlockParamContentUnion struct { - OfResultBlock []BetaWebSearchResultBlockParam `json:",omitzero,inline"` - OfError *BetaWebSearchToolRequestErrorParam `json:",omitzero,inline"` - paramUnion +// Returns a pointer to the underlying variant's property, if present. +func (u BetaTextCitationParamUnion) GetEncryptedIndex() *string { + if vt := u.OfWebSearchResultLocation; vt != nil { + return &vt.EncryptedIndex + } + return nil } -func (u BetaWebSearchToolResultBlockParamContentUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfResultBlock, u.OfError) +// Returns a pointer to the underlying variant's property, if present. +func (u BetaTextCitationParamUnion) GetURL() *string { + if vt := u.OfWebSearchResultLocation; vt != nil { + return &vt.URL + } + return nil } -func (u *BetaWebSearchToolResultBlockParamContentUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaTextCitationParamUnion) GetSearchResultIndex() *int64 { + if vt := u.OfSearchResultLocation; vt != nil { + return &vt.SearchResultIndex + } + return nil } -func (u *BetaWebSearchToolResultBlockParamContentUnion) asAny() any { - if !param.IsOmitted(u.OfResultBlock) { - return &u.OfResultBlock - } else if !param.IsOmitted(u.OfError) { - return u.OfError +// Returns a pointer to the underlying variant's property, if present. +func (u BetaTextCitationParamUnion) GetSource() *string { + if vt := u.OfSearchResultLocation; vt != nil { + return &vt.Source } return nil } -type BetaWebSearchToolResultError struct { - // Any of "invalid_tool_input", "unavailable", "max_uses_exceeded", - // "too_many_requests", "query_too_long", "request_too_large". - ErrorCode BetaWebSearchToolResultErrorCode `json:"error_code" api:"required"` - Type constant.WebSearchToolResultError `json:"type" default:"web_search_tool_result_error"` +// Returns a pointer to the underlying variant's property, if present. +func (u BetaTextCitationParamUnion) GetCitedText() *string { + if vt := u.OfCharLocation; vt != nil { + return (*string)(&vt.CitedText) + } else if vt := u.OfPageLocation; vt != nil { + return (*string)(&vt.CitedText) + } else if vt := u.OfContentBlockLocation; vt != nil { + return (*string)(&vt.CitedText) + } else if vt := u.OfWebSearchResultLocation; vt != nil { + return (*string)(&vt.CitedText) + } else if vt := u.OfSearchResultLocation; vt != nil { + return (*string)(&vt.CitedText) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaTextCitationParamUnion) GetDocumentIndex() *int64 { + if vt := u.OfCharLocation; vt != nil { + return (*int64)(&vt.DocumentIndex) + } else if vt := u.OfPageLocation; vt != nil { + return (*int64)(&vt.DocumentIndex) + } else if vt := u.OfContentBlockLocation; vt != nil { + return (*int64)(&vt.DocumentIndex) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaTextCitationParamUnion) GetDocumentTitle() *string { + if vt := u.OfCharLocation; vt != nil && vt.DocumentTitle.Valid() { + return &vt.DocumentTitle.Value + } else if vt := u.OfPageLocation; vt != nil && vt.DocumentTitle.Valid() { + return &vt.DocumentTitle.Value + } else if vt := u.OfContentBlockLocation; vt != nil && vt.DocumentTitle.Valid() { + return &vt.DocumentTitle.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaTextCitationParamUnion) GetType() *string { + if vt := u.OfCharLocation; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfPageLocation; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfContentBlockLocation; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfWebSearchResultLocation; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfSearchResultLocation; vt != nil { + return (*string)(&vt.Type) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaTextCitationParamUnion) GetEndBlockIndex() *int64 { + if vt := u.OfContentBlockLocation; vt != nil { + return (*int64)(&vt.EndBlockIndex) + } else if vt := u.OfSearchResultLocation; vt != nil { + return (*int64)(&vt.EndBlockIndex) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaTextCitationParamUnion) GetStartBlockIndex() *int64 { + if vt := u.OfContentBlockLocation; vt != nil { + return (*int64)(&vt.StartBlockIndex) + } else if vt := u.OfSearchResultLocation; vt != nil { + return (*int64)(&vt.StartBlockIndex) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaTextCitationParamUnion) GetTitle() *string { + if vt := u.OfWebSearchResultLocation; vt != nil && vt.Title.Valid() { + return &vt.Title.Value + } else if vt := u.OfSearchResultLocation; vt != nil && vt.Title.Valid() { + return &vt.Title.Value + } + return nil +} + +func init() { + apijson.RegisterUnion[BetaTextCitationParamUnion]( + "type", + apijson.Discriminator[BetaCitationCharLocationParam]("char_location"), + apijson.Discriminator[BetaCitationPageLocationParam]("page_location"), + apijson.Discriminator[BetaCitationContentBlockLocationParam]("content_block_location"), + apijson.Discriminator[BetaCitationWebSearchResultLocationParam]("web_search_result_location"), + apijson.Discriminator[BetaCitationSearchResultLocationParam]("search_result_location"), + ) +} + +type BetaTextDelta struct { + Text string `json:"text" api:"required"` + Type constant.TextDelta `json:"type" default:"text_delta"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { - ErrorCode respjson.Field + Text respjson.Field Type respjson.Field ExtraFields map[string]respjson.Field raw string @@ -11167,1183 +10291,7589 @@ type BetaWebSearchToolResultError struct { } // Returns the unmodified JSON received from the API -func (r BetaWebSearchToolResultError) RawJSON() string { return r.JSON.raw } -func (r *BetaWebSearchToolResultError) UnmarshalJSON(data []byte) error { +func (r BetaTextDelta) RawJSON() string { return r.JSON.raw } +func (r *BetaTextDelta) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type BetaWebSearchToolResultErrorCode string +type BetaTextEditorCodeExecutionCreateResultBlock struct { + IsFileUpdate bool `json:"is_file_update" api:"required"` + Type constant.TextEditorCodeExecutionCreateResult `json:"type" default:"text_editor_code_execution_create_result"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + IsFileUpdate respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} -const ( - BetaWebSearchToolResultErrorCodeInvalidToolInput BetaWebSearchToolResultErrorCode = "invalid_tool_input" - BetaWebSearchToolResultErrorCodeUnavailable BetaWebSearchToolResultErrorCode = "unavailable" - BetaWebSearchToolResultErrorCodeMaxUsesExceeded BetaWebSearchToolResultErrorCode = "max_uses_exceeded" - BetaWebSearchToolResultErrorCodeTooManyRequests BetaWebSearchToolResultErrorCode = "too_many_requests" - BetaWebSearchToolResultErrorCodeQueryTooLong BetaWebSearchToolResultErrorCode = "query_too_long" - BetaWebSearchToolResultErrorCodeRequestTooLarge BetaWebSearchToolResultErrorCode = "request_too_large" -) +// Returns the unmodified JSON received from the API +func (r BetaTextEditorCodeExecutionCreateResultBlock) RawJSON() string { return r.JSON.raw } +func (r *BetaTextEditorCodeExecutionCreateResultBlock) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} -type BetaMessageNewParams struct { - // The maximum number of tokens to generate before stopping. - // - // Note that our models may stop _before_ reaching this maximum. This parameter - // only specifies the absolute maximum number of tokens to generate. - // - // Different models have different maximum values for this parameter. See - // [models](https://docs.claude.com/en/docs/models-overview) for details. - MaxTokens int64 `json:"max_tokens" api:"required"` - // Input messages. - // - // Our models are trained to operate on alternating `user` and `assistant` - // conversational turns. When creating a new `Message`, you specify the prior - // conversational turns with the `messages` parameter, and the model then generates - // the next `Message` in the conversation. Consecutive `user` or `assistant` turns - // in your request will be combined into a single turn. - // - // Each input message must be an object with a `role` and `content`. You can - // specify a single `user`-role message, or you can include multiple `user` and - // `assistant` messages. - // - // If the final message uses the `assistant` role, the response content will - // continue immediately from the content in that message. This can be used to - // constrain part of the model's response. - // - // Example with a single `user` message: - // - // ```json - // [{ "role": "user", "content": "Hello, Claude" }] - // ``` - // - // Example with multiple conversational turns: - // - // ```json - // [ - // - // { "role": "user", "content": "Hello there." }, - // { "role": "assistant", "content": "Hi, I'm Claude. How can I help you?" }, - // { "role": "user", "content": "Can you explain LLMs in plain English?" } - // - // ] - // ``` - // - // Example with a partially-filled response from Claude: - // - // ```json - // [ - // - // { - // "role": "user", - // "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun" - // }, - // { "role": "assistant", "content": "The best answer is (" } - // - // ] - // ``` - // - // Each input message `content` may be either a single `string` or an array of - // content blocks, where each block has a specific `type`. Using a `string` for - // `content` is shorthand for an array of one content block of type `"text"`. The - // following input messages are equivalent: - // - // ```json - // { "role": "user", "content": "Hello, Claude" } - // ``` - // - // ```json - // { "role": "user", "content": [{ "type": "text", "text": "Hello, Claude" }] } - // ``` - // - // See [input examples](https://docs.claude.com/en/api/messages-examples). - // - // Note that if you want to include a - // [system prompt](https://docs.claude.com/en/docs/system-prompts), you can use the - // top-level `system` parameter — there is no `"system"` role for input messages in - // the Messages API. - // - // There is a limit of 100,000 messages in a single request. - Messages []BetaMessageParam `json:"messages,omitzero" api:"required"` - // The model that will complete your prompt.\n\nSee - // [models](https://docs.anthropic.com/en/docs/models-overview) for additional - // details and options. - Model Model `json:"model,omitzero" api:"required"` - // Specifies the geographic region for inference processing. If not specified, the - // workspace's `default_inference_geo` is used. - InferenceGeo param.Opt[string] `json:"inference_geo,omitzero"` - // The user profile ID to attribute this request to. Use when acting on behalf of a - // party other than your organization. - UserProfileID param.Opt[string] `json:"user_profile_id,omitzero"` - // Amount of randomness injected into the response. - // - // Defaults to `1.0`. Ranges from `0.0` to `1.0`. Use `temperature` closer to `0.0` - // for analytical / multiple choice, and closer to `1.0` for creative and - // generative tasks. - // - // Note that even with `temperature` of `0.0`, the results will not be fully - // deterministic. - Temperature param.Opt[float64] `json:"temperature,omitzero"` - // Only sample from the top K options for each subsequent token. - // - // Used to remove "long tail" low probability responses. - // [Learn more technical details here](https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277). - // - // Recommended for advanced use cases only. You usually only need to use - // `temperature`. - TopK param.Opt[int64] `json:"top_k,omitzero"` - // Use nucleus sampling. - // - // In nucleus sampling, we compute the cumulative distribution over all the options - // for each subsequent token in decreasing probability order and cut it off once it - // reaches a particular probability specified by `top_p`. You should either alter - // `temperature` or `top_p`, but not both. - // - // Recommended for advanced use cases only. You usually only need to use - // `temperature`. - TopP param.Opt[float64] `json:"top_p,omitzero"` - // Container identifier for reuse across requests. - Container BetaMessageNewParamsContainerUnion `json:"container,omitzero"` - // The inference speed mode for this request. `"fast"` enables high - // output-tokens-per-second inference. - // - // Any of "standard", "fast". - Speed BetaMessageNewParamsSpeed `json:"speed,omitzero"` - // Top-level cache control automatically applies a cache_control marker to the last - // cacheable block in the request. - CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` - // Context management configuration. - // - // This allows you to control how Claude manages context across multiple requests, - // such as whether to clear function results or not. - ContextManagement BetaContextManagementConfigParam `json:"context_management,omitzero"` - // MCP servers to be utilized in this request - MCPServers []BetaRequestMCPServerURLDefinitionParam `json:"mcp_servers,omitzero"` - // An object describing metadata about the request. - Metadata BetaMetadataParam `json:"metadata,omitzero"` - // Configuration options for the model's output, such as the output format. - OutputConfig BetaOutputConfigParam `json:"output_config,omitzero"` - // Deprecated: Use `output_config.format` instead. See - // [structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs) - // - // A schema to specify Claude's output format in responses. This parameter will be - // removed in a future release. - OutputFormat BetaJSONOutputFormatParam `json:"output_format,omitzero"` - // Determines whether to use priority capacity (if available) or standard capacity - // for this request. - // - // Anthropic offers different levels of service for your API requests. See - // [service-tiers](https://docs.claude.com/en/api/service-tiers) for details. - // - // Any of "auto", "standard_only". - ServiceTier BetaMessageNewParamsServiceTier `json:"service_tier,omitzero"` - // Custom text sequences that will cause the model to stop generating. - // - // Our models will normally stop when they have naturally completed their turn, - // which will result in a response `stop_reason` of `"end_turn"`. - // - // If you want the model to stop generating when it encounters custom strings of - // text, you can use the `stop_sequences` parameter. If the model encounters one of - // the custom sequences, the response `stop_reason` value will be `"stop_sequence"` - // and the response `stop_sequence` value will contain the matched stop sequence. - StopSequences []string `json:"stop_sequences,omitzero"` - // System prompt. - // - // A system prompt is a way of providing context and instructions to Claude, such - // as specifying a particular goal or role. See our - // [guide to system prompts](https://docs.claude.com/en/docs/system-prompts). - System []BetaTextBlockParam `json:"system,omitzero"` - // Configuration for enabling Claude's extended thinking. - // - // When enabled, responses include `thinking` content blocks showing Claude's - // thinking process before the final answer. Requires a minimum budget of 1,024 - // tokens and counts towards your `max_tokens` limit. - // - // See - // [extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking) - // for details. - Thinking BetaThinkingConfigParamUnion `json:"thinking,omitzero"` - // How the model should use the provided tools. The model can use a specific tool, - // any available tool, decide by itself, or not use tools at all. - ToolChoice BetaToolChoiceUnionParam `json:"tool_choice,omitzero"` - // Definitions of tools that the model may use. - // - // If you include `tools` in your API request, the model may return `tool_use` - // content blocks that represent the model's use of those tools. You can then run - // those tools using the tool input generated by the model and then optionally - // return results back to the model using `tool_result` content blocks. - // - // There are two types of tools: **client tools** and **server tools**. The - // behavior described below applies to client tools. For - // [server tools](https://docs.claude.com/en/docs/agents-and-tools/tool-use/overview#server-tools), - // see their individual documentation as each has its own behavior (e.g., the - // [web search tool](https://docs.claude.com/en/docs/agents-and-tools/tool-use/web-search-tool)). - // - // Each tool definition includes: - // - // - `name`: Name of the tool. - // - `description`: Optional, but strongly-recommended description of the tool. - // - `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the - // tool `input` shape that the model will produce in `tool_use` output content - // blocks. - // - // For example, if you defined `tools` as: - // - // ```json - // [ - // - // { - // "name": "get_stock_price", - // "description": "Get the current stock price for a given ticker symbol.", - // "input_schema": { - // "type": "object", - // "properties": { - // "ticker": { - // "type": "string", - // "description": "The stock ticker symbol, e.g. AAPL for Apple Inc." - // } - // }, - // "required": ["ticker"] - // } - // } - // - // ] - // ``` - // - // And then asked the model "What's the S&P 500 at today?", the model might produce - // `tool_use` content blocks in the response like this: - // - // ```json - // [ - // - // { - // "type": "tool_use", - // "id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV", - // "name": "get_stock_price", - // "input": { "ticker": "^GSPC" } - // } - // - // ] - // ``` - // - // You might then run your `get_stock_price` tool with `{"ticker": "^GSPC"}` as an - // input, and return the following back to the model in a subsequent `user` - // message: - // - // ```json - // [ - // - // { - // "type": "tool_result", - // "tool_use_id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV", - // "content": "259.75 USD" - // } - // - // ] - // ``` - // - // Tools can be used for workflows that include running client-side tools and - // functions, or more generally whenever you want the model to produce a particular - // JSON structure of output. - // - // See our [guide](https://docs.claude.com/en/docs/tool-use) for more details. - Tools []BetaToolUnionParam `json:"tools,omitzero"` - // Optional header to specify the beta version(s) you want to use. - Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` +// The properties IsFileUpdate, Type are required. +type BetaTextEditorCodeExecutionCreateResultBlockParam struct { + IsFileUpdate bool `json:"is_file_update" api:"required"` + // This field can be elided, and will marshal its zero value as + // "text_editor_code_execution_create_result". + Type constant.TextEditorCodeExecutionCreateResult `json:"type" default:"text_editor_code_execution_create_result"` paramObj } -func (r BetaMessageNewParams) MarshalJSON() (data []byte, err error) { - type shadow BetaMessageNewParams - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaMessageNewParams) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +func (r BetaTextEditorCodeExecutionCreateResultBlockParam) MarshalJSON() (data []byte, err error) { + type shadow BetaTextEditorCodeExecutionCreateResultBlockParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaTextEditorCodeExecutionCreateResultBlockParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaTextEditorCodeExecutionStrReplaceResultBlock struct { + Lines []string `json:"lines" api:"required"` + NewLines int64 `json:"new_lines" api:"required"` + NewStart int64 `json:"new_start" api:"required"` + OldLines int64 `json:"old_lines" api:"required"` + OldStart int64 `json:"old_start" api:"required"` + Type constant.TextEditorCodeExecutionStrReplaceResult `json:"type" default:"text_editor_code_execution_str_replace_result"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Lines respjson.Field + NewLines respjson.Field + NewStart respjson.Field + OldLines respjson.Field + OldStart respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaTextEditorCodeExecutionStrReplaceResultBlock) RawJSON() string { return r.JSON.raw } +func (r *BetaTextEditorCodeExecutionStrReplaceResultBlock) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The property Type is required. +type BetaTextEditorCodeExecutionStrReplaceResultBlockParam struct { + NewLines param.Opt[int64] `json:"new_lines,omitzero"` + NewStart param.Opt[int64] `json:"new_start,omitzero"` + OldLines param.Opt[int64] `json:"old_lines,omitzero"` + OldStart param.Opt[int64] `json:"old_start,omitzero"` + Lines []string `json:"lines,omitzero"` + // This field can be elided, and will marshal its zero value as + // "text_editor_code_execution_str_replace_result". + Type constant.TextEditorCodeExecutionStrReplaceResult `json:"type" default:"text_editor_code_execution_str_replace_result"` + paramObj +} + +func (r BetaTextEditorCodeExecutionStrReplaceResultBlockParam) MarshalJSON() (data []byte, err error) { + type shadow BetaTextEditorCodeExecutionStrReplaceResultBlockParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaTextEditorCodeExecutionStrReplaceResultBlockParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaTextEditorCodeExecutionToolResultBlock struct { + Content BetaTextEditorCodeExecutionToolResultBlockContentUnion `json:"content" api:"required"` + ToolUseID string `json:"tool_use_id" api:"required"` + Type constant.TextEditorCodeExecutionToolResult `json:"type" default:"text_editor_code_execution_tool_result"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Content respjson.Field + ToolUseID respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaTextEditorCodeExecutionToolResultBlock) RawJSON() string { return r.JSON.raw } +func (r *BetaTextEditorCodeExecutionToolResultBlock) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaTextEditorCodeExecutionToolResultBlockContentUnion contains all possible +// properties and values from [BetaTextEditorCodeExecutionToolResultError], +// [BetaTextEditorCodeExecutionViewResultBlock], +// [BetaTextEditorCodeExecutionCreateResultBlock], +// [BetaTextEditorCodeExecutionStrReplaceResultBlock]. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaTextEditorCodeExecutionToolResultBlockContentUnion struct { + // This field is from variant [BetaTextEditorCodeExecutionToolResultError]. + ErrorCode BetaTextEditorCodeExecutionToolResultErrorErrorCode `json:"error_code"` + // This field is from variant [BetaTextEditorCodeExecutionToolResultError]. + ErrorMessage string `json:"error_message"` + Type string `json:"type"` + // This field is from variant [BetaTextEditorCodeExecutionViewResultBlock]. + Content string `json:"content"` + // This field is from variant [BetaTextEditorCodeExecutionViewResultBlock]. + FileType BetaTextEditorCodeExecutionViewResultBlockFileType `json:"file_type"` + // This field is from variant [BetaTextEditorCodeExecutionViewResultBlock]. + NumLines int64 `json:"num_lines"` + // This field is from variant [BetaTextEditorCodeExecutionViewResultBlock]. + StartLine int64 `json:"start_line"` + // This field is from variant [BetaTextEditorCodeExecutionViewResultBlock]. + TotalLines int64 `json:"total_lines"` + // This field is from variant [BetaTextEditorCodeExecutionCreateResultBlock]. + IsFileUpdate bool `json:"is_file_update"` + // This field is from variant [BetaTextEditorCodeExecutionStrReplaceResultBlock]. + Lines []string `json:"lines"` + // This field is from variant [BetaTextEditorCodeExecutionStrReplaceResultBlock]. + NewLines int64 `json:"new_lines"` + // This field is from variant [BetaTextEditorCodeExecutionStrReplaceResultBlock]. + NewStart int64 `json:"new_start"` + // This field is from variant [BetaTextEditorCodeExecutionStrReplaceResultBlock]. + OldLines int64 `json:"old_lines"` + // This field is from variant [BetaTextEditorCodeExecutionStrReplaceResultBlock]. + OldStart int64 `json:"old_start"` + JSON struct { + ErrorCode respjson.Field + ErrorMessage respjson.Field + Type respjson.Field + Content respjson.Field + FileType respjson.Field + NumLines respjson.Field + StartLine respjson.Field + TotalLines respjson.Field + IsFileUpdate respjson.Field + Lines respjson.Field + NewLines respjson.Field + NewStart respjson.Field + OldLines respjson.Field + OldStart respjson.Field + raw string + } `json:"-"` +} + +func (u BetaTextEditorCodeExecutionToolResultBlockContentUnion) AsResponseTextEditorCodeExecutionToolResultError() (v BetaTextEditorCodeExecutionToolResultError) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaTextEditorCodeExecutionToolResultBlockContentUnion) AsResponseTextEditorCodeExecutionViewResultBlock() (v BetaTextEditorCodeExecutionViewResultBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaTextEditorCodeExecutionToolResultBlockContentUnion) AsResponseTextEditorCodeExecutionCreateResultBlock() (v BetaTextEditorCodeExecutionCreateResultBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaTextEditorCodeExecutionToolResultBlockContentUnion) AsResponseTextEditorCodeExecutionStrReplaceResultBlock() (v BetaTextEditorCodeExecutionStrReplaceResultBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u BetaTextEditorCodeExecutionToolResultBlockContentUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaTextEditorCodeExecutionToolResultBlockContentUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The properties Content, ToolUseID, Type are required. +type BetaTextEditorCodeExecutionToolResultBlockParam struct { + Content BetaTextEditorCodeExecutionToolResultBlockParamContentUnion `json:"content,omitzero" api:"required"` + ToolUseID string `json:"tool_use_id" api:"required"` + // Create a cache control breakpoint at this content block. + CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` + // This field can be elided, and will marshal its zero value as + // "text_editor_code_execution_tool_result". + Type constant.TextEditorCodeExecutionToolResult `json:"type" default:"text_editor_code_execution_tool_result"` + paramObj +} + +func (r BetaTextEditorCodeExecutionToolResultBlockParam) MarshalJSON() (data []byte, err error) { + type shadow BetaTextEditorCodeExecutionToolResultBlockParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaTextEditorCodeExecutionToolResultBlockParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaTextEditorCodeExecutionToolResultBlockParamContentUnion struct { + OfRequestTextEditorCodeExecutionToolResultError *BetaTextEditorCodeExecutionToolResultErrorParam `json:",omitzero,inline"` + OfRequestTextEditorCodeExecutionViewResultBlock *BetaTextEditorCodeExecutionViewResultBlockParam `json:",omitzero,inline"` + OfRequestTextEditorCodeExecutionCreateResultBlock *BetaTextEditorCodeExecutionCreateResultBlockParam `json:",omitzero,inline"` + OfRequestTextEditorCodeExecutionStrReplaceResultBlock *BetaTextEditorCodeExecutionStrReplaceResultBlockParam `json:",omitzero,inline"` + paramUnion +} + +func (u BetaTextEditorCodeExecutionToolResultBlockParamContentUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfRequestTextEditorCodeExecutionToolResultError, u.OfRequestTextEditorCodeExecutionViewResultBlock, u.OfRequestTextEditorCodeExecutionCreateResultBlock, u.OfRequestTextEditorCodeExecutionStrReplaceResultBlock) +} +func (u *BetaTextEditorCodeExecutionToolResultBlockParamContentUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *BetaTextEditorCodeExecutionToolResultBlockParamContentUnion) asAny() any { + if !param.IsOmitted(u.OfRequestTextEditorCodeExecutionToolResultError) { + return u.OfRequestTextEditorCodeExecutionToolResultError + } else if !param.IsOmitted(u.OfRequestTextEditorCodeExecutionViewResultBlock) { + return u.OfRequestTextEditorCodeExecutionViewResultBlock + } else if !param.IsOmitted(u.OfRequestTextEditorCodeExecutionCreateResultBlock) { + return u.OfRequestTextEditorCodeExecutionCreateResultBlock + } else if !param.IsOmitted(u.OfRequestTextEditorCodeExecutionStrReplaceResultBlock) { + return u.OfRequestTextEditorCodeExecutionStrReplaceResultBlock + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaTextEditorCodeExecutionToolResultBlockParamContentUnion) GetErrorCode() *string { + if vt := u.OfRequestTextEditorCodeExecutionToolResultError; vt != nil { + return (*string)(&vt.ErrorCode) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaTextEditorCodeExecutionToolResultBlockParamContentUnion) GetErrorMessage() *string { + if vt := u.OfRequestTextEditorCodeExecutionToolResultError; vt != nil && vt.ErrorMessage.Valid() { + return &vt.ErrorMessage.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaTextEditorCodeExecutionToolResultBlockParamContentUnion) GetContent() *string { + if vt := u.OfRequestTextEditorCodeExecutionViewResultBlock; vt != nil { + return &vt.Content + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaTextEditorCodeExecutionToolResultBlockParamContentUnion) GetFileType() *string { + if vt := u.OfRequestTextEditorCodeExecutionViewResultBlock; vt != nil { + return (*string)(&vt.FileType) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaTextEditorCodeExecutionToolResultBlockParamContentUnion) GetNumLines() *int64 { + if vt := u.OfRequestTextEditorCodeExecutionViewResultBlock; vt != nil && vt.NumLines.Valid() { + return &vt.NumLines.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaTextEditorCodeExecutionToolResultBlockParamContentUnion) GetStartLine() *int64 { + if vt := u.OfRequestTextEditorCodeExecutionViewResultBlock; vt != nil && vt.StartLine.Valid() { + return &vt.StartLine.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaTextEditorCodeExecutionToolResultBlockParamContentUnion) GetTotalLines() *int64 { + if vt := u.OfRequestTextEditorCodeExecutionViewResultBlock; vt != nil && vt.TotalLines.Valid() { + return &vt.TotalLines.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaTextEditorCodeExecutionToolResultBlockParamContentUnion) GetIsFileUpdate() *bool { + if vt := u.OfRequestTextEditorCodeExecutionCreateResultBlock; vt != nil { + return &vt.IsFileUpdate + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaTextEditorCodeExecutionToolResultBlockParamContentUnion) GetLines() []string { + if vt := u.OfRequestTextEditorCodeExecutionStrReplaceResultBlock; vt != nil { + return vt.Lines + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaTextEditorCodeExecutionToolResultBlockParamContentUnion) GetNewLines() *int64 { + if vt := u.OfRequestTextEditorCodeExecutionStrReplaceResultBlock; vt != nil && vt.NewLines.Valid() { + return &vt.NewLines.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaTextEditorCodeExecutionToolResultBlockParamContentUnion) GetNewStart() *int64 { + if vt := u.OfRequestTextEditorCodeExecutionStrReplaceResultBlock; vt != nil && vt.NewStart.Valid() { + return &vt.NewStart.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaTextEditorCodeExecutionToolResultBlockParamContentUnion) GetOldLines() *int64 { + if vt := u.OfRequestTextEditorCodeExecutionStrReplaceResultBlock; vt != nil && vt.OldLines.Valid() { + return &vt.OldLines.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaTextEditorCodeExecutionToolResultBlockParamContentUnion) GetOldStart() *int64 { + if vt := u.OfRequestTextEditorCodeExecutionStrReplaceResultBlock; vt != nil && vt.OldStart.Valid() { + return &vt.OldStart.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaTextEditorCodeExecutionToolResultBlockParamContentUnion) GetType() *string { + if vt := u.OfRequestTextEditorCodeExecutionToolResultError; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfRequestTextEditorCodeExecutionViewResultBlock; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfRequestTextEditorCodeExecutionCreateResultBlock; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfRequestTextEditorCodeExecutionStrReplaceResultBlock; vt != nil { + return (*string)(&vt.Type) + } + return nil +} + +type BetaTextEditorCodeExecutionToolResultError struct { + // Any of "invalid_tool_input", "unavailable", "too_many_requests", + // "execution_time_exceeded", "file_not_found". + ErrorCode BetaTextEditorCodeExecutionToolResultErrorErrorCode `json:"error_code" api:"required"` + ErrorMessage string `json:"error_message" api:"required"` + Type constant.TextEditorCodeExecutionToolResultError `json:"type" default:"text_editor_code_execution_tool_result_error"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ErrorCode respjson.Field + ErrorMessage respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaTextEditorCodeExecutionToolResultError) RawJSON() string { return r.JSON.raw } +func (r *BetaTextEditorCodeExecutionToolResultError) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaTextEditorCodeExecutionToolResultErrorErrorCode string + +const ( + BetaTextEditorCodeExecutionToolResultErrorErrorCodeInvalidToolInput BetaTextEditorCodeExecutionToolResultErrorErrorCode = "invalid_tool_input" + BetaTextEditorCodeExecutionToolResultErrorErrorCodeUnavailable BetaTextEditorCodeExecutionToolResultErrorErrorCode = "unavailable" + BetaTextEditorCodeExecutionToolResultErrorErrorCodeTooManyRequests BetaTextEditorCodeExecutionToolResultErrorErrorCode = "too_many_requests" + BetaTextEditorCodeExecutionToolResultErrorErrorCodeExecutionTimeExceeded BetaTextEditorCodeExecutionToolResultErrorErrorCode = "execution_time_exceeded" + BetaTextEditorCodeExecutionToolResultErrorErrorCodeFileNotFound BetaTextEditorCodeExecutionToolResultErrorErrorCode = "file_not_found" +) + +// The properties ErrorCode, Type are required. +type BetaTextEditorCodeExecutionToolResultErrorParam struct { + // Any of "invalid_tool_input", "unavailable", "too_many_requests", + // "execution_time_exceeded", "file_not_found". + ErrorCode BetaTextEditorCodeExecutionToolResultErrorParamErrorCode `json:"error_code,omitzero" api:"required"` + ErrorMessage param.Opt[string] `json:"error_message,omitzero"` + // This field can be elided, and will marshal its zero value as + // "text_editor_code_execution_tool_result_error". + Type constant.TextEditorCodeExecutionToolResultError `json:"type" default:"text_editor_code_execution_tool_result_error"` + paramObj +} + +func (r BetaTextEditorCodeExecutionToolResultErrorParam) MarshalJSON() (data []byte, err error) { + type shadow BetaTextEditorCodeExecutionToolResultErrorParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaTextEditorCodeExecutionToolResultErrorParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaTextEditorCodeExecutionToolResultErrorParamErrorCode string + +const ( + BetaTextEditorCodeExecutionToolResultErrorParamErrorCodeInvalidToolInput BetaTextEditorCodeExecutionToolResultErrorParamErrorCode = "invalid_tool_input" + BetaTextEditorCodeExecutionToolResultErrorParamErrorCodeUnavailable BetaTextEditorCodeExecutionToolResultErrorParamErrorCode = "unavailable" + BetaTextEditorCodeExecutionToolResultErrorParamErrorCodeTooManyRequests BetaTextEditorCodeExecutionToolResultErrorParamErrorCode = "too_many_requests" + BetaTextEditorCodeExecutionToolResultErrorParamErrorCodeExecutionTimeExceeded BetaTextEditorCodeExecutionToolResultErrorParamErrorCode = "execution_time_exceeded" + BetaTextEditorCodeExecutionToolResultErrorParamErrorCodeFileNotFound BetaTextEditorCodeExecutionToolResultErrorParamErrorCode = "file_not_found" +) + +type BetaTextEditorCodeExecutionViewResultBlock struct { + Content string `json:"content" api:"required"` + // Any of "text", "image", "pdf". + FileType BetaTextEditorCodeExecutionViewResultBlockFileType `json:"file_type" api:"required"` + NumLines int64 `json:"num_lines" api:"required"` + StartLine int64 `json:"start_line" api:"required"` + TotalLines int64 `json:"total_lines" api:"required"` + Type constant.TextEditorCodeExecutionViewResult `json:"type" default:"text_editor_code_execution_view_result"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Content respjson.Field + FileType respjson.Field + NumLines respjson.Field + StartLine respjson.Field + TotalLines respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaTextEditorCodeExecutionViewResultBlock) RawJSON() string { return r.JSON.raw } +func (r *BetaTextEditorCodeExecutionViewResultBlock) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaTextEditorCodeExecutionViewResultBlockFileType string + +const ( + BetaTextEditorCodeExecutionViewResultBlockFileTypeText BetaTextEditorCodeExecutionViewResultBlockFileType = "text" + BetaTextEditorCodeExecutionViewResultBlockFileTypeImage BetaTextEditorCodeExecutionViewResultBlockFileType = "image" + BetaTextEditorCodeExecutionViewResultBlockFileTypePDF BetaTextEditorCodeExecutionViewResultBlockFileType = "pdf" +) + +// The properties Content, FileType, Type are required. +type BetaTextEditorCodeExecutionViewResultBlockParam struct { + Content string `json:"content" api:"required"` + // Any of "text", "image", "pdf". + FileType BetaTextEditorCodeExecutionViewResultBlockParamFileType `json:"file_type,omitzero" api:"required"` + NumLines param.Opt[int64] `json:"num_lines,omitzero"` + StartLine param.Opt[int64] `json:"start_line,omitzero"` + TotalLines param.Opt[int64] `json:"total_lines,omitzero"` + // This field can be elided, and will marshal its zero value as + // "text_editor_code_execution_view_result". + Type constant.TextEditorCodeExecutionViewResult `json:"type" default:"text_editor_code_execution_view_result"` + paramObj +} + +func (r BetaTextEditorCodeExecutionViewResultBlockParam) MarshalJSON() (data []byte, err error) { + type shadow BetaTextEditorCodeExecutionViewResultBlockParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaTextEditorCodeExecutionViewResultBlockParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaTextEditorCodeExecutionViewResultBlockParamFileType string + +const ( + BetaTextEditorCodeExecutionViewResultBlockParamFileTypeText BetaTextEditorCodeExecutionViewResultBlockParamFileType = "text" + BetaTextEditorCodeExecutionViewResultBlockParamFileTypeImage BetaTextEditorCodeExecutionViewResultBlockParamFileType = "image" + BetaTextEditorCodeExecutionViewResultBlockParamFileTypePDF BetaTextEditorCodeExecutionViewResultBlockParamFileType = "pdf" +) + +type BetaThinkingBlock struct { + // A value used to verify that this thinking block was generated by Claude when it + // is passed back to the API. + // + // This is an opaque field and should not be interpreted or parsed. When passing + // thinking blocks back to the API (required when using tools with extended + // thinking), pass them back exactly as received, with this field intact. + // + // See + // [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking) + // for details. + Signature string `json:"signature" api:"required"` + // The text of Claude's thinking process for this block. + Thinking string `json:"thinking" api:"required"` + Type constant.Thinking `json:"type" default:"thinking"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Signature respjson.Field + Thinking respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaThinkingBlock) RawJSON() string { return r.JSON.raw } +func (r *BetaThinkingBlock) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The properties Signature, Thinking, Type are required. +type BetaThinkingBlockParam struct { + // The `signature` value of this thinking block, exactly as returned by the API in + // a previous response. Used to verify that the block was generated by Claude. + // + // Thinking blocks must be passed back unmodified and in their original order; a + // modified block results in a 400 `invalid_request_error`. + Signature string `json:"signature" api:"required"` + // The `thinking` text of this block as returned by the API. + Thinking string `json:"thinking" api:"required"` + // This field can be elided, and will marshal its zero value as "thinking". + Type constant.Thinking `json:"type" default:"thinking"` + paramObj +} + +func (r BetaThinkingBlockParam) MarshalJSON() (data []byte, err error) { + type shadow BetaThinkingBlockParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaThinkingBlockParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The property Type is required. +type BetaThinkingConfigAdaptiveParam struct { + // Controls how thinking content appears in the response. When set to `summarized`, + // thinking is returned normally. When set to `omitted`, thinking content is + // redacted but a signature is returned for multi-turn continuity. Defaults to + // `summarized`. + // + // Any of "summarized", "omitted", "updates". + Display BetaThinkingConfigAdaptiveDisplay `json:"display,omitzero"` + // This field can be elided, and will marshal its zero value as "adaptive". + Type constant.Adaptive `json:"type" default:"adaptive"` + paramObj +} + +func (r BetaThinkingConfigAdaptiveParam) MarshalJSON() (data []byte, err error) { + type shadow BetaThinkingConfigAdaptiveParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaThinkingConfigAdaptiveParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Controls how thinking content appears in the response. When set to `summarized`, +// thinking is returned normally. When set to `omitted`, thinking content is +// redacted but a signature is returned for multi-turn continuity. Defaults to +// `summarized`. +type BetaThinkingConfigAdaptiveDisplay string + +const ( + BetaThinkingConfigAdaptiveDisplaySummarized BetaThinkingConfigAdaptiveDisplay = "summarized" + BetaThinkingConfigAdaptiveDisplayOmitted BetaThinkingConfigAdaptiveDisplay = "omitted" + BetaThinkingConfigAdaptiveDisplayUpdates BetaThinkingConfigAdaptiveDisplay = "updates" +) + +func NewBetaThinkingConfigDisabledParam() BetaThinkingConfigDisabledParam { + return BetaThinkingConfigDisabledParam{ + Type: "disabled", + } +} + +// This struct has a constant value, construct it with +// [NewBetaThinkingConfigDisabledParam]. +type BetaThinkingConfigDisabledParam struct { + Type constant.Disabled `json:"type" default:"disabled"` + paramObj +} + +func (r BetaThinkingConfigDisabledParam) MarshalJSON() (data []byte, err error) { + type shadow BetaThinkingConfigDisabledParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaThinkingConfigDisabledParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The properties BudgetTokens, Type are required. +type BetaThinkingConfigEnabledParam struct { + // Determines how many tokens Claude can use for its internal reasoning process. + // Larger budgets can enable more thorough analysis for complex problems, improving + // response quality. + // + // Must be ≥1024 and less than `max_tokens`. + // + // See + // [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking) + // for details. + BudgetTokens int64 `json:"budget_tokens" api:"required"` + // Controls how thinking content appears in the response. When set to `summarized`, + // thinking is returned normally. When set to `omitted`, thinking content is + // redacted but a signature is returned for multi-turn continuity. Defaults to + // `summarized`. + // + // Any of "summarized", "omitted", "updates". + Display BetaThinkingConfigEnabledDisplay `json:"display,omitzero"` + // This field can be elided, and will marshal its zero value as "enabled". + Type constant.Enabled `json:"type" default:"enabled"` + paramObj +} + +func (r BetaThinkingConfigEnabledParam) MarshalJSON() (data []byte, err error) { + type shadow BetaThinkingConfigEnabledParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaThinkingConfigEnabledParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Controls how thinking content appears in the response. When set to `summarized`, +// thinking is returned normally. When set to `omitted`, thinking content is +// redacted but a signature is returned for multi-turn continuity. Defaults to +// `summarized`. +type BetaThinkingConfigEnabledDisplay string + +const ( + BetaThinkingConfigEnabledDisplaySummarized BetaThinkingConfigEnabledDisplay = "summarized" + BetaThinkingConfigEnabledDisplayOmitted BetaThinkingConfigEnabledDisplay = "omitted" + BetaThinkingConfigEnabledDisplayUpdates BetaThinkingConfigEnabledDisplay = "updates" +) + +func BetaThinkingConfigParamOfEnabled(budgetTokens int64) BetaThinkingConfigParamUnion { + var enabled BetaThinkingConfigEnabledParam + enabled.BudgetTokens = budgetTokens + return BetaThinkingConfigParamUnion{OfEnabled: &enabled} +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaThinkingConfigParamUnion struct { + OfEnabled *BetaThinkingConfigEnabledParam `json:",omitzero,inline"` + OfDisabled *BetaThinkingConfigDisabledParam `json:",omitzero,inline"` + OfAdaptive *BetaThinkingConfigAdaptiveParam `json:",omitzero,inline"` + paramUnion +} + +func (u BetaThinkingConfigParamUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfEnabled, u.OfDisabled, u.OfAdaptive) +} +func (u *BetaThinkingConfigParamUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *BetaThinkingConfigParamUnion) asAny() any { + if !param.IsOmitted(u.OfEnabled) { + return u.OfEnabled + } else if !param.IsOmitted(u.OfDisabled) { + return u.OfDisabled + } else if !param.IsOmitted(u.OfAdaptive) { + return u.OfAdaptive + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaThinkingConfigParamUnion) GetBudgetTokens() *int64 { + if vt := u.OfEnabled; vt != nil { + return &vt.BudgetTokens + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaThinkingConfigParamUnion) GetType() *string { + if vt := u.OfEnabled; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfDisabled; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfAdaptive; vt != nil { + return (*string)(&vt.Type) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaThinkingConfigParamUnion) GetDisplay() *string { + if vt := u.OfEnabled; vt != nil { + return (*string)(&vt.Display) + } else if vt := u.OfAdaptive; vt != nil { + return (*string)(&vt.Display) + } + return nil +} + +func init() { + apijson.RegisterUnion[BetaThinkingConfigParamUnion]( + "type", + apijson.Discriminator[BetaThinkingConfigEnabledParam]("enabled"), + apijson.Discriminator[BetaThinkingConfigDisabledParam]("disabled"), + apijson.Discriminator[BetaThinkingConfigAdaptiveParam]("adaptive"), + ) +} + +type BetaThinkingDelta struct { + // Per-frame increment of a coarse, running estimate of the tokens this thinking + // block has produced so far. Present whenever the + // `thinking-token-count-2026-05-13` beta is set; `null` unless `thinking.display` + // resolves to `"omitted"` and a count is due this frame. Sum the increments across + // `thinking_delta` frames on this block for a progress indicator. Each increment + // is a non-negative multiple of a fixed quantum and the cadence is rate-limited, + // so this is a deliberately lossy display hint, not a billable count; + // `usage.output_tokens` remains authoritative. + EstimatedTokens int64 `json:"estimated_tokens" api:"required"` + // The incremental `thinking` text for this content block. Concatenate the + // `thinking` values of successive `thinking_delta` events to assemble the block's + // full `thinking` value. + Thinking string `json:"thinking" api:"required"` + Type constant.ThinkingDelta `json:"type" default:"thinking_delta"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + EstimatedTokens respjson.Field + Thinking respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaThinkingDelta) RawJSON() string { return r.JSON.raw } +func (r *BetaThinkingDelta) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The properties Type, Value are required. +type BetaThinkingTurnsParam struct { + Value int64 `json:"value" api:"required"` + // This field can be elided, and will marshal its zero value as "thinking_turns". + Type constant.ThinkingTurns `json:"type" default:"thinking_turns"` + paramObj +} + +func (r BetaThinkingTurnsParam) MarshalJSON() (data []byte, err error) { + type shadow BetaThinkingTurnsParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaThinkingTurnsParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// User-configurable total token budget across contexts. +// +// The properties Total, Type are required. +type BetaTokenTaskBudgetParam struct { + // Total token budget across all contexts in the session. + Total int64 `json:"total" api:"required"` + // Remaining tokens in the budget. Use this to track usage across contexts when + // implementing compaction client-side. Defaults to total if not provided. + Remaining param.Opt[int64] `json:"remaining,omitzero"` + // The budget type. Currently only 'tokens' is supported. + // + // This field can be elided, and will marshal its zero value as "tokens". + Type constant.Tokens `json:"type" default:"tokens"` + paramObj +} + +func (r BetaTokenTaskBudgetParam) MarshalJSON() (data []byte, err error) { + type shadow BetaTokenTaskBudgetParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaTokenTaskBudgetParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The properties InputSchema, Name are required. +type BetaToolParam struct { + // [JSON schema](https://json-schema.org/draft/2020-12) for this tool's input. + // + // This defines the shape of the `input` that your tool accepts and that the model + // will produce. + InputSchema BetaToolInputSchemaParam `json:"input_schema,omitzero" api:"required"` + // Name of the tool. + // + // This is how the tool will be called by the model and in `tool_use` blocks. + Name string `json:"name" api:"required"` + // Enable eager input streaming for this tool. When true, tool input parameters + // will be streamed incrementally as they are generated, and types will be inferred + // on-the-fly rather than buffering the full JSON output. When false, streaming is + // disabled for this tool even if the fine-grained-tool-streaming beta is active. + // When null (default), uses the default behavior based on beta headers. + EagerInputStreaming param.Opt[bool] `json:"eager_input_streaming,omitzero"` + // If true, tool will not be included in initial system prompt. Only loaded when + // returned via tool_reference from tool search. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Description of what this tool does. + // + // Tool descriptions should be as detailed as possible. The more information that + // the model has about what the tool is and how to use it, the better it will + // perform. You can use natural language descriptions to reinforce important + // aspects of the tool input JSON schema. + Description param.Opt[string] `json:"description,omitzero"` + // When true, guarantees schema validation on tool names and inputs + Strict param.Opt[bool] `json:"strict,omitzero"` + // Any of "custom". + Type BetaToolType `json:"type,omitzero"` + // Any of "direct", "code_execution_20250825", "code_execution_20260120", + // "code_execution_20260521". + AllowedCallers []string `json:"allowed_callers,omitzero"` + // Create a cache control breakpoint at this content block. + CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` + InputExamples []map[string]any `json:"input_examples,omitzero"` + paramObj +} + +func (r BetaToolParam) MarshalJSON() (data []byte, err error) { + type shadow BetaToolParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaToolParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// [JSON schema](https://json-schema.org/draft/2020-12) for this tool's input. +// +// This defines the shape of the `input` that your tool accepts and that the model +// will produce. +// +// The property Type is required. +type BetaToolInputSchemaParam struct { + Properties any `json:"properties,omitzero"` + Required []string `json:"required,omitzero"` + // This field can be elided, and will marshal its zero value as "object". + Type constant.Object `json:"type" default:"object"` + ExtraFields map[string]any `json:"-"` + paramObj +} + +func (r BetaToolInputSchemaParam) MarshalJSON() (data []byte, err error) { + type shadow BetaToolInputSchemaParam + return param.MarshalWithExtras(r, (*shadow)(&r), r.ExtraFields) +} +func (r *BetaToolInputSchemaParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaToolType string + +const ( + BetaToolTypeCustom BetaToolType = "custom" +) + +// The properties Name, Type are required. +type BetaToolBash20241022Param struct { + // If true, tool will not be included in initial system prompt. Only loaded when + // returned via tool_reference from tool search. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // When true, guarantees schema validation on tool names and inputs + Strict param.Opt[bool] `json:"strict,omitzero"` + // Any of "direct", "code_execution_20250825", "code_execution_20260120", + // "code_execution_20260521". + AllowedCallers []string `json:"allowed_callers,omitzero"` + // Create a cache control breakpoint at this content block. + CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` + InputExamples []map[string]any `json:"input_examples,omitzero"` + // Name of the tool. + // + // This is how the tool will be called by the model and in `tool_use` blocks. + // + // This field can be elided, and will marshal its zero value as "bash". + Name constant.Bash `json:"name" default:"bash"` + // This field can be elided, and will marshal its zero value as "bash_20241022". + Type constant.Bash20241022 `json:"type" default:"bash_20241022"` + paramObj +} + +func (r BetaToolBash20241022Param) MarshalJSON() (data []byte, err error) { + type shadow BetaToolBash20241022Param + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaToolBash20241022Param) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The properties Name, Type are required. +type BetaToolBash20250124Param struct { + // If true, tool will not be included in initial system prompt. Only loaded when + // returned via tool_reference from tool search. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // When true, guarantees schema validation on tool names and inputs + Strict param.Opt[bool] `json:"strict,omitzero"` + // Any of "direct", "code_execution_20250825", "code_execution_20260120", + // "code_execution_20260521". + AllowedCallers []string `json:"allowed_callers,omitzero"` + // Create a cache control breakpoint at this content block. + CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` + InputExamples []map[string]any `json:"input_examples,omitzero"` + // Name of the tool. + // + // This is how the tool will be called by the model and in `tool_use` blocks. + // + // This field can be elided, and will marshal its zero value as "bash". + Name constant.Bash `json:"name" default:"bash"` + // This field can be elided, and will marshal its zero value as "bash_20250124". + Type constant.Bash20250124 `json:"type" default:"bash_20250124"` + paramObj +} + +func (r BetaToolBash20250124Param) MarshalJSON() (data []byte, err error) { + type shadow BetaToolBash20250124Param + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaToolBash20250124Param) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Reference to a single MCP tool by its server and remote name — the same +// `server_name`/`name` pair `mcp_tool_use` carries. +// +// The properties Name, ServerName, Type are required. +type BetaToolChangeMCPToolReferenceParam struct { + Name string `json:"name" api:"required"` + ServerName string `json:"server_name" api:"required"` + // This field can be elided, and will marshal its zero value as + // "mcp_tool_reference". + Type constant.MCPToolReference `json:"type" default:"mcp_tool_reference"` + paramObj +} + +func (r BetaToolChangeMCPToolReferenceParam) MarshalJSON() (data []byte, err error) { + type shadow BetaToolChangeMCPToolReferenceParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaToolChangeMCPToolReferenceParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Reference to every tool in the named MCP server's toolset. +// +// The properties ServerName, Type are required. +type BetaToolChangeMCPToolsetReferenceParam struct { + ServerName string `json:"server_name" api:"required"` + // This field can be elided, and will marshal its zero value as + // "mcp_toolset_reference". + Type constant.MCPToolsetReference `json:"type" default:"mcp_toolset_reference"` + paramObj +} + +func (r BetaToolChangeMCPToolsetReferenceParam) MarshalJSON() (data []byte, err error) { + type shadow BetaToolChangeMCPToolsetReferenceParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaToolChangeMCPToolsetReferenceParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Reference to a single tool the caller declared directly in `tools[]`. Does not +// accept the composed `{server}_{name}` form the server assigns to MCP-resolved +// tools — use `mcp_tool_reference` or `mcp_toolset_reference` for those. +// +// The properties Name, Type are required. +type BetaToolChangeToolReferenceParam struct { + Name string `json:"name" api:"required"` + // This field can be elided, and will marshal its zero value as "tool_reference". + Type constant.ToolReference `json:"type" default:"tool_reference"` + paramObj +} + +func (r BetaToolChangeToolReferenceParam) MarshalJSON() (data []byte, err error) { + type shadow BetaToolChangeToolReferenceParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaToolChangeToolReferenceParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +func BetaToolChoiceParamOfTool(name string) BetaToolChoiceUnionParam { + var tool BetaToolChoiceToolParam + tool.Name = name + return BetaToolChoiceUnionParam{OfTool: &tool} +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaToolChoiceUnionParam struct { + OfAuto *BetaToolChoiceAutoParam `json:",omitzero,inline"` + OfAny *BetaToolChoiceAnyParam `json:",omitzero,inline"` + OfTool *BetaToolChoiceToolParam `json:",omitzero,inline"` + OfNone *BetaToolChoiceNoneParam `json:",omitzero,inline"` + paramUnion +} + +func (u BetaToolChoiceUnionParam) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfAuto, u.OfAny, u.OfTool, u.OfNone) +} +func (u *BetaToolChoiceUnionParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *BetaToolChoiceUnionParam) asAny() any { + if !param.IsOmitted(u.OfAuto) { + return u.OfAuto + } else if !param.IsOmitted(u.OfAny) { + return u.OfAny + } else if !param.IsOmitted(u.OfTool) { + return u.OfTool + } else if !param.IsOmitted(u.OfNone) { + return u.OfNone + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaToolChoiceUnionParam) GetName() *string { + if vt := u.OfTool; vt != nil { + return &vt.Name + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaToolChoiceUnionParam) GetType() *string { + if vt := u.OfAuto; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfAny; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfTool; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfNone; vt != nil { + return (*string)(&vt.Type) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaToolChoiceUnionParam) GetDisableParallelToolUse() *bool { + if vt := u.OfAuto; vt != nil && vt.DisableParallelToolUse.Valid() { + return &vt.DisableParallelToolUse.Value + } else if vt := u.OfAny; vt != nil && vt.DisableParallelToolUse.Valid() { + return &vt.DisableParallelToolUse.Value + } else if vt := u.OfTool; vt != nil && vt.DisableParallelToolUse.Valid() { + return &vt.DisableParallelToolUse.Value + } + return nil +} + +func init() { + apijson.RegisterUnion[BetaToolChoiceUnionParam]( + "type", + apijson.Discriminator[BetaToolChoiceAutoParam]("auto"), + apijson.Discriminator[BetaToolChoiceAnyParam]("any"), + apijson.Discriminator[BetaToolChoiceToolParam]("tool"), + apijson.Discriminator[BetaToolChoiceNoneParam]("none"), + ) +} + +// The model will use any available tools. +// +// The property Type is required. +type BetaToolChoiceAnyParam struct { + // Whether to disable parallel tool use. + // + // Defaults to `false`. If set to `true`, the model will output exactly one tool + // use. + DisableParallelToolUse param.Opt[bool] `json:"disable_parallel_tool_use,omitzero"` + // This field can be elided, and will marshal its zero value as "any". + Type constant.Any `json:"type" default:"any"` + paramObj +} + +func (r BetaToolChoiceAnyParam) MarshalJSON() (data []byte, err error) { + type shadow BetaToolChoiceAnyParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaToolChoiceAnyParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The model will automatically decide whether to use tools. +// +// The property Type is required. +type BetaToolChoiceAutoParam struct { + // Whether to disable parallel tool use. + // + // Defaults to `false`. If set to `true`, the model will output at most one tool + // use. + DisableParallelToolUse param.Opt[bool] `json:"disable_parallel_tool_use,omitzero"` + // This field can be elided, and will marshal its zero value as "auto". + Type constant.Auto `json:"type" default:"auto"` + paramObj +} + +func (r BetaToolChoiceAutoParam) MarshalJSON() (data []byte, err error) { + type shadow BetaToolChoiceAutoParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaToolChoiceAutoParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +func NewBetaToolChoiceNoneParam() BetaToolChoiceNoneParam { + return BetaToolChoiceNoneParam{ + Type: "none", + } +} + +// The model will not be allowed to use tools. +// +// This struct has a constant value, construct it with +// [NewBetaToolChoiceNoneParam]. +type BetaToolChoiceNoneParam struct { + Type constant.None `json:"type" default:"none"` + paramObj +} + +func (r BetaToolChoiceNoneParam) MarshalJSON() (data []byte, err error) { + type shadow BetaToolChoiceNoneParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaToolChoiceNoneParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The model will use the specified tool with `tool_choice.name`. +// +// The properties Name, Type are required. +type BetaToolChoiceToolParam struct { + // The name of the tool to use. + Name string `json:"name" api:"required"` + // Whether to disable parallel tool use. + // + // Defaults to `false`. If set to `true`, the model will output exactly one tool + // use. + DisableParallelToolUse param.Opt[bool] `json:"disable_parallel_tool_use,omitzero"` + // This field can be elided, and will marshal its zero value as "tool". + Type constant.Tool `json:"type" default:"tool"` + paramObj +} + +func (r BetaToolChoiceToolParam) MarshalJSON() (data []byte, err error) { + type shadow BetaToolChoiceToolParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaToolChoiceToolParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The properties DisplayHeightPx, DisplayWidthPx, Name, Type are required. +type BetaToolComputerUse20241022Param struct { + // The height of the display in pixels. + DisplayHeightPx int64 `json:"display_height_px" api:"required"` + // The width of the display in pixels. + DisplayWidthPx int64 `json:"display_width_px" api:"required"` + // The X11 display number (e.g. 0, 1) for the display. + DisplayNumber param.Opt[int64] `json:"display_number,omitzero"` + // If true, tool will not be included in initial system prompt. Only loaded when + // returned via tool_reference from tool search. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // When true, guarantees schema validation on tool names and inputs + Strict param.Opt[bool] `json:"strict,omitzero"` + // Any of "direct", "code_execution_20250825", "code_execution_20260120", + // "code_execution_20260521". + AllowedCallers []string `json:"allowed_callers,omitzero"` + // Create a cache control breakpoint at this content block. + CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` + InputExamples []map[string]any `json:"input_examples,omitzero"` + // Name of the tool. + // + // This is how the tool will be called by the model and in `tool_use` blocks. + // + // This field can be elided, and will marshal its zero value as "computer". + Name constant.Computer `json:"name" default:"computer"` + // This field can be elided, and will marshal its zero value as + // "computer_20241022". + Type constant.Computer20241022 `json:"type" default:"computer_20241022"` + paramObj +} + +func (r BetaToolComputerUse20241022Param) MarshalJSON() (data []byte, err error) { + type shadow BetaToolComputerUse20241022Param + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaToolComputerUse20241022Param) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The properties DisplayHeightPx, DisplayWidthPx, Name, Type are required. +type BetaToolComputerUse20250124Param struct { + // The height of the display in pixels. + DisplayHeightPx int64 `json:"display_height_px" api:"required"` + // The width of the display in pixels. + DisplayWidthPx int64 `json:"display_width_px" api:"required"` + // The X11 display number (e.g. 0, 1) for the display. + DisplayNumber param.Opt[int64] `json:"display_number,omitzero"` + // If true, tool will not be included in initial system prompt. Only loaded when + // returned via tool_reference from tool search. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // When true, guarantees schema validation on tool names and inputs + Strict param.Opt[bool] `json:"strict,omitzero"` + // Any of "direct", "code_execution_20250825", "code_execution_20260120", + // "code_execution_20260521". + AllowedCallers []string `json:"allowed_callers,omitzero"` + // Create a cache control breakpoint at this content block. + CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` + InputExamples []map[string]any `json:"input_examples,omitzero"` + // Name of the tool. + // + // This is how the tool will be called by the model and in `tool_use` blocks. + // + // This field can be elided, and will marshal its zero value as "computer". + Name constant.Computer `json:"name" default:"computer"` + // This field can be elided, and will marshal its zero value as + // "computer_20250124". + Type constant.Computer20250124 `json:"type" default:"computer_20250124"` + paramObj +} + +func (r BetaToolComputerUse20250124Param) MarshalJSON() (data []byte, err error) { + type shadow BetaToolComputerUse20250124Param + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaToolComputerUse20250124Param) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The properties DisplayHeightPx, DisplayWidthPx, Name, Type are required. +type BetaToolComputerUse20251124Param struct { + // The height of the display in pixels. + DisplayHeightPx int64 `json:"display_height_px" api:"required"` + // The width of the display in pixels. + DisplayWidthPx int64 `json:"display_width_px" api:"required"` + // The X11 display number (e.g. 0, 1) for the display. + DisplayNumber param.Opt[int64] `json:"display_number,omitzero"` + // If true, tool will not be included in initial system prompt. Only loaded when + // returned via tool_reference from tool search. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether to enable an action to take a zoomed-in screenshot of the screen. + EnableZoom param.Opt[bool] `json:"enable_zoom,omitzero"` + // When true, guarantees schema validation on tool names and inputs + Strict param.Opt[bool] `json:"strict,omitzero"` + // Any of "direct", "code_execution_20250825", "code_execution_20260120", + // "code_execution_20260521". + AllowedCallers []string `json:"allowed_callers,omitzero"` + // Create a cache control breakpoint at this content block. + CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` + InputExamples []map[string]any `json:"input_examples,omitzero"` + // Name of the tool. + // + // This is how the tool will be called by the model and in `tool_use` blocks. + // + // This field can be elided, and will marshal its zero value as "computer". + Name constant.Computer `json:"name" default:"computer"` + // This field can be elided, and will marshal its zero value as + // "computer_20251124". + Type constant.Computer20251124 `json:"type" default:"computer_20251124"` + paramObj +} + +func (r BetaToolComputerUse20251124Param) MarshalJSON() (data []byte, err error) { + type shadow BetaToolComputerUse20251124Param + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaToolComputerUse20251124Param) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaToolReferenceBlock struct { + ToolName string `json:"tool_name" api:"required"` + Type constant.ToolReference `json:"type" default:"tool_reference"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ToolName respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaToolReferenceBlock) RawJSON() string { return r.JSON.raw } +func (r *BetaToolReferenceBlock) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Tool reference block that can be included in tool_result content. +// +// The properties ToolName, Type are required. +type BetaToolReferenceBlockParam struct { + ToolName string `json:"tool_name" api:"required"` + // Create a cache control breakpoint at this content block. + CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` + // This field can be elided, and will marshal its zero value as "tool_reference". + Type constant.ToolReference `json:"type" default:"tool_reference"` + paramObj +} + +func (r BetaToolReferenceBlockParam) MarshalJSON() (data []byte, err error) { + type shadow BetaToolReferenceBlockParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaToolReferenceBlockParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The properties ToolUseID, Type are required. +type BetaToolResultBlockParam struct { + ToolUseID string `json:"tool_use_id" api:"required"` + // For a toolset member tool_result, the toolset family of the paired tool_use. + ToolsetName param.Opt[string] `json:"toolset_name,omitzero"` + IsError param.Opt[bool] `json:"is_error,omitzero"` + // Create a cache control breakpoint at this content block. + CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` + Content []BetaToolResultBlockParamContentUnion `json:"content,omitzero"` + // This field can be elided, and will marshal its zero value as "tool_result". + Type constant.ToolResult `json:"type" default:"tool_result"` + paramObj +} + +func (r BetaToolResultBlockParam) MarshalJSON() (data []byte, err error) { + type shadow BetaToolResultBlockParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaToolResultBlockParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +func NewBetaToolResultTextBlockParam(toolUseID string, text string, isError bool) BetaToolResultBlockParam { + var p BetaToolResultBlockParam + p.ToolUseID = toolUseID + p.IsError = param.Opt[bool]{Value: isError} + p.Content = []BetaToolResultBlockParamContentUnion{ + {OfText: &BetaTextBlockParam{Text: text}}, + } + return p +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaToolResultBlockParamContentUnion struct { + OfText *BetaTextBlockParam `json:",omitzero,inline"` + OfImage *BetaImageBlockParam `json:",omitzero,inline"` + OfSearchResult *BetaSearchResultBlockParam `json:",omitzero,inline"` + OfDocument *BetaRequestDocumentBlockParam `json:",omitzero,inline"` + OfToolReference *BetaToolReferenceBlockParam `json:",omitzero,inline"` + OfBrowserState *BetaBrowserStateBlockParam `json:",omitzero,inline"` + paramUnion +} + +func (u BetaToolResultBlockParamContentUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfText, + u.OfImage, + u.OfSearchResult, + u.OfDocument, + u.OfToolReference, + u.OfBrowserState) +} +func (u *BetaToolResultBlockParamContentUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *BetaToolResultBlockParamContentUnion) asAny() any { + if !param.IsOmitted(u.OfText) { + return u.OfText + } else if !param.IsOmitted(u.OfImage) { + return u.OfImage + } else if !param.IsOmitted(u.OfSearchResult) { + return u.OfSearchResult + } else if !param.IsOmitted(u.OfDocument) { + return u.OfDocument + } else if !param.IsOmitted(u.OfToolReference) { + return u.OfToolReference + } else if !param.IsOmitted(u.OfBrowserState) { + return u.OfBrowserState + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaToolResultBlockParamContentUnion) GetText() *string { + if vt := u.OfText; vt != nil { + return &vt.Text + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaToolResultBlockParamContentUnion) GetTransformations() *BetaImageTransformationsParam { + if vt := u.OfImage; vt != nil { + return &vt.Transformations + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaToolResultBlockParamContentUnion) GetContent() []BetaTextBlockParam { + if vt := u.OfSearchResult; vt != nil { + return vt.Content + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaToolResultBlockParamContentUnion) GetContext() *string { + if vt := u.OfDocument; vt != nil && vt.Context.Valid() { + return &vt.Context.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaToolResultBlockParamContentUnion) GetToolName() *string { + if vt := u.OfToolReference; vt != nil { + return &vt.ToolName + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaToolResultBlockParamContentUnion) GetTabs() []BetaBrowserStateTabEntryParam { + if vt := u.OfBrowserState; vt != nil { + return vt.Tabs + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaToolResultBlockParamContentUnion) GetStateChanges() []BetaBrowserStateChangeUnionParam { + if vt := u.OfBrowserState; vt != nil { + return vt.StateChanges + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaToolResultBlockParamContentUnion) GetType() *string { + if vt := u.OfText; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfImage; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfSearchResult; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfDocument; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfToolReference; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfBrowserState; vt != nil { + return (*string)(&vt.Type) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaToolResultBlockParamContentUnion) GetTitle() *string { + if vt := u.OfSearchResult; vt != nil { + return (*string)(&vt.Title) + } else if vt := u.OfDocument; vt != nil && vt.Title.Valid() { + return &vt.Title.Value + } + return nil +} + +// Returns a pointer to the underlying variant's CacheControl property, if present. +func (u BetaToolResultBlockParamContentUnion) GetCacheControl() *BetaCacheControlEphemeralParam { + if vt := u.OfText; vt != nil { + return &vt.CacheControl + } else if vt := u.OfImage; vt != nil { + return &vt.CacheControl + } else if vt := u.OfSearchResult; vt != nil { + return &vt.CacheControl + } else if vt := u.OfDocument; vt != nil { + return &vt.CacheControl + } else if vt := u.OfToolReference; vt != nil { + return &vt.CacheControl + } else if vt := u.OfBrowserState; vt != nil { + return &vt.CacheControl + } + return nil +} + +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u BetaToolResultBlockParamContentUnion) GetCitations() (res betaToolResultBlockParamContentUnionCitations) { + if vt := u.OfText; vt != nil { + res.any = &vt.Citations + } else if vt := u.OfSearchResult; vt != nil { + res.any = &vt.Citations + } else if vt := u.OfDocument; vt != nil { + res.any = &vt.Citations + } + return +} + +// Can have the runtime types [*[]BetaTextCitationParamUnion], +// [*BetaCitationsConfigParam] +type betaToolResultBlockParamContentUnionCitations struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *[]anthropic.BetaTextCitationParamUnion: +// case *anthropic.BetaCitationsConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u betaToolResultBlockParamContentUnionCitations) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolResultBlockParamContentUnionCitations) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BetaCitationsConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + } + return nil +} + +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u BetaToolResultBlockParamContentUnion) GetSource() (res betaToolResultBlockParamContentUnionSource) { + if vt := u.OfImage; vt != nil { + res.any = vt.Source.asAny() + } else if vt := u.OfSearchResult; vt != nil { + res.any = &vt.Source + } else if vt := u.OfDocument; vt != nil { + res.any = vt.Source.asAny() + } + return +} + +// Can have the runtime types [*BetaBase64ImageSourceParam], +// [*BetaURLImageSourceParam], [*BetaFileImageSourceParam], [*string], +// [*BetaBase64PDFSourceParam], [*BetaPlainTextSourceParam], +// [*BetaContentBlockSourceParam], [*BetaURLPDFSourceParam], +// [*BetaFileDocumentSourceParam] +type betaToolResultBlockParamContentUnionSource struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BetaBase64ImageSourceParam: +// case *anthropic.BetaURLImageSourceParam: +// case *anthropic.BetaFileImageSourceParam: +// case *string: +// case *anthropic.BetaBase64PDFSourceParam: +// case *anthropic.BetaPlainTextSourceParam: +// case *anthropic.BetaContentBlockSourceParam: +// case *anthropic.BetaURLPDFSourceParam: +// case *anthropic.BetaFileDocumentSourceParam: +// default: +// fmt.Errorf("not present") +// } +func (u betaToolResultBlockParamContentUnionSource) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolResultBlockParamContentUnionSource) GetContent() *BetaContentBlockSourceContentUnionParam { + switch vt := u.any.(type) { + case *BetaRequestDocumentBlockSourceUnionParam: + return vt.GetContent() + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolResultBlockParamContentUnionSource) GetData() *string { + switch vt := u.any.(type) { + case *BetaImageBlockParamSourceUnion: + return vt.GetData() + case *BetaRequestDocumentBlockSourceUnionParam: + return vt.GetData() + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolResultBlockParamContentUnionSource) GetMediaType() *string { + switch vt := u.any.(type) { + case *BetaImageBlockParamSourceUnion: + return vt.GetMediaType() + case *BetaRequestDocumentBlockSourceUnionParam: + return vt.GetMediaType() + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolResultBlockParamContentUnionSource) GetType() *string { + switch vt := u.any.(type) { + case *BetaImageBlockParamSourceUnion: + return vt.GetType() + case *BetaRequestDocumentBlockSourceUnionParam: + return vt.GetType() + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolResultBlockParamContentUnionSource) GetURL() *string { + switch vt := u.any.(type) { + case *BetaImageBlockParamSourceUnion: + return vt.GetURL() + case *BetaRequestDocumentBlockSourceUnionParam: + return vt.GetURL() + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolResultBlockParamContentUnionSource) GetFileID() *string { + switch vt := u.any.(type) { + case *BetaImageBlockParamSourceUnion: + return vt.GetFileID() + case *BetaRequestDocumentBlockSourceUnionParam: + return vt.GetFileID() + } + return nil +} + +func init() { + apijson.RegisterUnion[BetaToolResultBlockParamContentUnion]( + "type", + apijson.Discriminator[BetaTextBlockParam]("text"), + apijson.Discriminator[BetaImageBlockParam]("image"), + apijson.Discriminator[BetaSearchResultBlockParam]("search_result"), + apijson.Discriminator[BetaRequestDocumentBlockParam]("document"), + apijson.Discriminator[BetaToolReferenceBlockParam]("tool_reference"), + apijson.Discriminator[BetaBrowserStateBlockParam]("browser_state"), + ) +} + +// The properties Name, Type are required. +type BetaToolSearchToolBm25_20251119Param struct { + // Any of "tool_search_tool_bm25_20251119", "tool_search_tool_bm25". + Type BetaToolSearchToolBm25_20251119Type `json:"type,omitzero" api:"required"` + // If true, tool will not be included in initial system prompt. Only loaded when + // returned via tool_reference from tool search. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // When true, guarantees schema validation on tool names and inputs + Strict param.Opt[bool] `json:"strict,omitzero"` + // Any of "direct", "code_execution_20250825", "code_execution_20260120", + // "code_execution_20260521". + AllowedCallers []string `json:"allowed_callers,omitzero"` + // Create a cache control breakpoint at this content block. + CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` + InputExamples []map[string]any `json:"input_examples,omitzero"` + // Name of the tool. + // + // This is how the tool will be called by the model and in `tool_use` blocks. + // + // This field can be elided, and will marshal its zero value as + // "tool_search_tool_bm25". + Name constant.ToolSearchToolBm25 `json:"name" default:"tool_search_tool_bm25"` + paramObj +} + +func (r BetaToolSearchToolBm25_20251119Param) MarshalJSON() (data []byte, err error) { + type shadow BetaToolSearchToolBm25_20251119Param + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaToolSearchToolBm25_20251119Param) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaToolSearchToolBm25_20251119Type string + +const ( + BetaToolSearchToolBm25_20251119TypeToolSearchToolBm25_20251119 BetaToolSearchToolBm25_20251119Type = "tool_search_tool_bm25_20251119" + BetaToolSearchToolBm25_20251119TypeToolSearchToolBm25 BetaToolSearchToolBm25_20251119Type = "tool_search_tool_bm25" +) + +// The properties Name, Type are required. +type BetaToolSearchToolRegex20251119Param struct { + // Any of "tool_search_tool_regex_20251119", "tool_search_tool_regex". + Type BetaToolSearchToolRegex20251119Type `json:"type,omitzero" api:"required"` + // If true, tool will not be included in initial system prompt. Only loaded when + // returned via tool_reference from tool search. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // When true, guarantees schema validation on tool names and inputs + Strict param.Opt[bool] `json:"strict,omitzero"` + // Any of "direct", "code_execution_20250825", "code_execution_20260120", + // "code_execution_20260521". + AllowedCallers []string `json:"allowed_callers,omitzero"` + // Create a cache control breakpoint at this content block. + CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` + // Name of the tool. + // + // This is how the tool will be called by the model and in `tool_use` blocks. + // + // This field can be elided, and will marshal its zero value as + // "tool_search_tool_regex". + Name constant.ToolSearchToolRegex `json:"name" default:"tool_search_tool_regex"` + paramObj +} + +func (r BetaToolSearchToolRegex20251119Param) MarshalJSON() (data []byte, err error) { + type shadow BetaToolSearchToolRegex20251119Param + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaToolSearchToolRegex20251119Param) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaToolSearchToolRegex20251119Type string + +const ( + BetaToolSearchToolRegex20251119TypeToolSearchToolRegex20251119 BetaToolSearchToolRegex20251119Type = "tool_search_tool_regex_20251119" + BetaToolSearchToolRegex20251119TypeToolSearchToolRegex BetaToolSearchToolRegex20251119Type = "tool_search_tool_regex" +) + +type BetaToolSearchToolResultBlock struct { + Content BetaToolSearchToolResultBlockContentUnion `json:"content" api:"required"` + ToolUseID string `json:"tool_use_id" api:"required"` + Type constant.ToolSearchToolResult `json:"type" default:"tool_search_tool_result"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Content respjson.Field + ToolUseID respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaToolSearchToolResultBlock) RawJSON() string { return r.JSON.raw } +func (r *BetaToolSearchToolResultBlock) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaToolSearchToolResultBlockContentUnion contains all possible properties and +// values from [BetaToolSearchToolResultError], +// [BetaToolSearchToolSearchResultBlock]. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaToolSearchToolResultBlockContentUnion struct { + // This field is from variant [BetaToolSearchToolResultError]. + ErrorCode BetaToolSearchToolResultErrorErrorCode `json:"error_code"` + // This field is from variant [BetaToolSearchToolResultError]. + ErrorMessage string `json:"error_message"` + Type string `json:"type"` + // This field is from variant [BetaToolSearchToolSearchResultBlock]. + ToolReferences []BetaToolReferenceBlock `json:"tool_references"` + JSON struct { + ErrorCode respjson.Field + ErrorMessage respjson.Field + Type respjson.Field + ToolReferences respjson.Field + raw string + } `json:"-"` +} + +func (u BetaToolSearchToolResultBlockContentUnion) AsResponseToolSearchToolResultError() (v BetaToolSearchToolResultError) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaToolSearchToolResultBlockContentUnion) AsResponseToolSearchToolSearchResultBlock() (v BetaToolSearchToolSearchResultBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u BetaToolSearchToolResultBlockContentUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaToolSearchToolResultBlockContentUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The properties Content, ToolUseID, Type are required. +type BetaToolSearchToolResultBlockParam struct { + Content BetaToolSearchToolResultBlockParamContentUnion `json:"content,omitzero" api:"required"` + ToolUseID string `json:"tool_use_id" api:"required"` + // Create a cache control breakpoint at this content block. + CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` + // This field can be elided, and will marshal its zero value as + // "tool_search_tool_result". + Type constant.ToolSearchToolResult `json:"type" default:"tool_search_tool_result"` + paramObj +} + +func (r BetaToolSearchToolResultBlockParam) MarshalJSON() (data []byte, err error) { + type shadow BetaToolSearchToolResultBlockParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaToolSearchToolResultBlockParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaToolSearchToolResultBlockParamContentUnion struct { + OfRequestToolSearchToolResultError *BetaToolSearchToolResultErrorParam `json:",omitzero,inline"` + OfRequestToolSearchToolSearchResultBlock *BetaToolSearchToolSearchResultBlockParam `json:",omitzero,inline"` + paramUnion +} + +func (u BetaToolSearchToolResultBlockParamContentUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfRequestToolSearchToolResultError, u.OfRequestToolSearchToolSearchResultBlock) +} +func (u *BetaToolSearchToolResultBlockParamContentUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *BetaToolSearchToolResultBlockParamContentUnion) asAny() any { + if !param.IsOmitted(u.OfRequestToolSearchToolResultError) { + return u.OfRequestToolSearchToolResultError + } else if !param.IsOmitted(u.OfRequestToolSearchToolSearchResultBlock) { + return u.OfRequestToolSearchToolSearchResultBlock + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaToolSearchToolResultBlockParamContentUnion) GetErrorCode() *string { + if vt := u.OfRequestToolSearchToolResultError; vt != nil { + return (*string)(&vt.ErrorCode) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaToolSearchToolResultBlockParamContentUnion) GetErrorMessage() *string { + if vt := u.OfRequestToolSearchToolResultError; vt != nil && vt.ErrorMessage.Valid() { + return &vt.ErrorMessage.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaToolSearchToolResultBlockParamContentUnion) GetToolReferences() []BetaToolReferenceBlockParam { + if vt := u.OfRequestToolSearchToolSearchResultBlock; vt != nil { + return vt.ToolReferences + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaToolSearchToolResultBlockParamContentUnion) GetType() *string { + if vt := u.OfRequestToolSearchToolResultError; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfRequestToolSearchToolSearchResultBlock; vt != nil { + return (*string)(&vt.Type) + } + return nil +} + +type BetaToolSearchToolResultError struct { + // Any of "invalid_tool_input", "unavailable", "too_many_requests", + // "execution_time_exceeded". + ErrorCode BetaToolSearchToolResultErrorErrorCode `json:"error_code" api:"required"` + ErrorMessage string `json:"error_message" api:"required"` + Type constant.ToolSearchToolResultError `json:"type" default:"tool_search_tool_result_error"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ErrorCode respjson.Field + ErrorMessage respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaToolSearchToolResultError) RawJSON() string { return r.JSON.raw } +func (r *BetaToolSearchToolResultError) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaToolSearchToolResultErrorErrorCode string + +const ( + BetaToolSearchToolResultErrorErrorCodeInvalidToolInput BetaToolSearchToolResultErrorErrorCode = "invalid_tool_input" + BetaToolSearchToolResultErrorErrorCodeUnavailable BetaToolSearchToolResultErrorErrorCode = "unavailable" + BetaToolSearchToolResultErrorErrorCodeTooManyRequests BetaToolSearchToolResultErrorErrorCode = "too_many_requests" + BetaToolSearchToolResultErrorErrorCodeExecutionTimeExceeded BetaToolSearchToolResultErrorErrorCode = "execution_time_exceeded" +) + +// The properties ErrorCode, Type are required. +type BetaToolSearchToolResultErrorParam struct { + // Any of "invalid_tool_input", "unavailable", "too_many_requests", + // "execution_time_exceeded". + ErrorCode BetaToolSearchToolResultErrorParamErrorCode `json:"error_code,omitzero" api:"required"` + ErrorMessage param.Opt[string] `json:"error_message,omitzero"` + // This field can be elided, and will marshal its zero value as + // "tool_search_tool_result_error". + Type constant.ToolSearchToolResultError `json:"type" default:"tool_search_tool_result_error"` + paramObj +} + +func (r BetaToolSearchToolResultErrorParam) MarshalJSON() (data []byte, err error) { + type shadow BetaToolSearchToolResultErrorParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaToolSearchToolResultErrorParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaToolSearchToolResultErrorParamErrorCode string + +const ( + BetaToolSearchToolResultErrorParamErrorCodeInvalidToolInput BetaToolSearchToolResultErrorParamErrorCode = "invalid_tool_input" + BetaToolSearchToolResultErrorParamErrorCodeUnavailable BetaToolSearchToolResultErrorParamErrorCode = "unavailable" + BetaToolSearchToolResultErrorParamErrorCodeTooManyRequests BetaToolSearchToolResultErrorParamErrorCode = "too_many_requests" + BetaToolSearchToolResultErrorParamErrorCodeExecutionTimeExceeded BetaToolSearchToolResultErrorParamErrorCode = "execution_time_exceeded" +) + +type BetaToolSearchToolSearchResultBlock struct { + ToolReferences []BetaToolReferenceBlock `json:"tool_references" api:"required"` + Type constant.ToolSearchToolSearchResult `json:"type" default:"tool_search_tool_search_result"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ToolReferences respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaToolSearchToolSearchResultBlock) RawJSON() string { return r.JSON.raw } +func (r *BetaToolSearchToolSearchResultBlock) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The properties ToolReferences, Type are required. +type BetaToolSearchToolSearchResultBlockParam struct { + ToolReferences []BetaToolReferenceBlockParam `json:"tool_references,omitzero" api:"required"` + // This field can be elided, and will marshal its zero value as + // "tool_search_tool_search_result". + Type constant.ToolSearchToolSearchResult `json:"type" default:"tool_search_tool_search_result"` + paramObj +} + +func (r BetaToolSearchToolSearchResultBlockParam) MarshalJSON() (data []byte, err error) { + type shadow BetaToolSearchToolSearchResultBlockParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaToolSearchToolSearchResultBlockParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The properties Name, Type are required. +type BetaToolTextEditor20241022Param struct { + // If true, tool will not be included in initial system prompt. Only loaded when + // returned via tool_reference from tool search. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // When true, guarantees schema validation on tool names and inputs + Strict param.Opt[bool] `json:"strict,omitzero"` + // Any of "direct", "code_execution_20250825", "code_execution_20260120", + // "code_execution_20260521". + AllowedCallers []string `json:"allowed_callers,omitzero"` + // Create a cache control breakpoint at this content block. + CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` + InputExamples []map[string]any `json:"input_examples,omitzero"` + // Name of the tool. + // + // This is how the tool will be called by the model and in `tool_use` blocks. + // + // This field can be elided, and will marshal its zero value as + // "str_replace_editor". + Name constant.StrReplaceEditor `json:"name" default:"str_replace_editor"` + // This field can be elided, and will marshal its zero value as + // "text_editor_20241022". + Type constant.TextEditor20241022 `json:"type" default:"text_editor_20241022"` + paramObj +} + +func (r BetaToolTextEditor20241022Param) MarshalJSON() (data []byte, err error) { + type shadow BetaToolTextEditor20241022Param + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaToolTextEditor20241022Param) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The properties Name, Type are required. +type BetaToolTextEditor20250124Param struct { + // If true, tool will not be included in initial system prompt. Only loaded when + // returned via tool_reference from tool search. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // When true, guarantees schema validation on tool names and inputs + Strict param.Opt[bool] `json:"strict,omitzero"` + // Any of "direct", "code_execution_20250825", "code_execution_20260120", + // "code_execution_20260521". + AllowedCallers []string `json:"allowed_callers,omitzero"` + // Create a cache control breakpoint at this content block. + CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` + InputExamples []map[string]any `json:"input_examples,omitzero"` + // Name of the tool. + // + // This is how the tool will be called by the model and in `tool_use` blocks. + // + // This field can be elided, and will marshal its zero value as + // "str_replace_editor". + Name constant.StrReplaceEditor `json:"name" default:"str_replace_editor"` + // This field can be elided, and will marshal its zero value as + // "text_editor_20250124". + Type constant.TextEditor20250124 `json:"type" default:"text_editor_20250124"` + paramObj +} + +func (r BetaToolTextEditor20250124Param) MarshalJSON() (data []byte, err error) { + type shadow BetaToolTextEditor20250124Param + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaToolTextEditor20250124Param) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The properties Name, Type are required. +type BetaToolTextEditor20250429Param struct { + // If true, tool will not be included in initial system prompt. Only loaded when + // returned via tool_reference from tool search. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // When true, guarantees schema validation on tool names and inputs + Strict param.Opt[bool] `json:"strict,omitzero"` + // Any of "direct", "code_execution_20250825", "code_execution_20260120", + // "code_execution_20260521". + AllowedCallers []string `json:"allowed_callers,omitzero"` + // Create a cache control breakpoint at this content block. + CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` + InputExamples []map[string]any `json:"input_examples,omitzero"` + // Name of the tool. + // + // This is how the tool will be called by the model and in `tool_use` blocks. + // + // This field can be elided, and will marshal its zero value as + // "str_replace_based_edit_tool". + Name constant.StrReplaceBasedEditTool `json:"name" default:"str_replace_based_edit_tool"` + // This field can be elided, and will marshal its zero value as + // "text_editor_20250429". + Type constant.TextEditor20250429 `json:"type" default:"text_editor_20250429"` + paramObj +} + +func (r BetaToolTextEditor20250429Param) MarshalJSON() (data []byte, err error) { + type shadow BetaToolTextEditor20250429Param + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaToolTextEditor20250429Param) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The properties Name, Type are required. +type BetaToolTextEditor20250728Param struct { + // Maximum number of characters to display when viewing a file. If not specified, + // defaults to displaying the full file. + MaxCharacters param.Opt[int64] `json:"max_characters,omitzero"` + // If true, tool will not be included in initial system prompt. Only loaded when + // returned via tool_reference from tool search. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // When true, guarantees schema validation on tool names and inputs + Strict param.Opt[bool] `json:"strict,omitzero"` + // Any of "direct", "code_execution_20250825", "code_execution_20260120", + // "code_execution_20260521". + AllowedCallers []string `json:"allowed_callers,omitzero"` + // Create a cache control breakpoint at this content block. + CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` + InputExamples []map[string]any `json:"input_examples,omitzero"` + // Name of the tool. + // + // This is how the tool will be called by the model and in `tool_use` blocks. + // + // This field can be elided, and will marshal its zero value as + // "str_replace_based_edit_tool". + Name constant.StrReplaceBasedEditTool `json:"name" default:"str_replace_based_edit_tool"` + // This field can be elided, and will marshal its zero value as + // "text_editor_20250728". + Type constant.TextEditor20250728 `json:"type" default:"text_editor_20250728"` + paramObj +} + +func (r BetaToolTextEditor20250728Param) MarshalJSON() (data []byte, err error) { + type shadow BetaToolTextEditor20250728Param + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaToolTextEditor20250728Param) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +func BetaToolUnionParamOfTool(inputSchema BetaToolInputSchemaParam, name string) BetaToolUnionParam { + var variant BetaToolParam + variant.InputSchema = inputSchema + variant.Name = name + return BetaToolUnionParam{OfTool: &variant} +} + +func BetaToolUnionParamOfComputerUseTool20241022(displayHeightPx int64, displayWidthPx int64) BetaToolUnionParam { + var variant BetaToolComputerUse20241022Param + variant.DisplayHeightPx = displayHeightPx + variant.DisplayWidthPx = displayWidthPx + return BetaToolUnionParam{OfComputerUseTool20241022: &variant} +} + +func BetaToolUnionParamOfComputerUseTool20250124(displayHeightPx int64, displayWidthPx int64) BetaToolUnionParam { + var variant BetaToolComputerUse20250124Param + variant.DisplayHeightPx = displayHeightPx + variant.DisplayWidthPx = displayWidthPx + return BetaToolUnionParam{OfComputerUseTool20250124: &variant} +} + +func BetaToolUnionParamOfComputerUseTool20251124(displayHeightPx int64, displayWidthPx int64) BetaToolUnionParam { + var variant BetaToolComputerUse20251124Param + variant.DisplayHeightPx = displayHeightPx + variant.DisplayWidthPx = displayWidthPx + return BetaToolUnionParam{OfComputerUseTool20251124: &variant} +} + +func BetaToolUnionParamOfAdvisorTool20260301(model Model) BetaToolUnionParam { + var variant BetaAdvisorTool20260301Param + variant.Model = model + return BetaToolUnionParam{OfAdvisorTool20260301: &variant} +} + +func BetaToolUnionParamOfToolSearchToolBm25_20251119(type_ BetaToolSearchToolBm25_20251119Type) BetaToolUnionParam { + var variant BetaToolSearchToolBm25_20251119Param + variant.Type = type_ + return BetaToolUnionParam{OfToolSearchToolBm25_20251119: &variant} +} + +func BetaToolUnionParamOfToolSearchToolRegex20251119(type_ BetaToolSearchToolRegex20251119Type) BetaToolUnionParam { + var variant BetaToolSearchToolRegex20251119Param + variant.Type = type_ + return BetaToolUnionParam{OfToolSearchToolRegex20251119: &variant} +} + +func BetaToolUnionParamOfMCPToolset(mcpServerName string) BetaToolUnionParam { + var variant BetaMCPToolsetParam + variant.MCPServerName = mcpServerName + return BetaToolUnionParam{OfMCPToolset: &variant} +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaToolUnionParam struct { + OfTool *BetaToolParam `json:",omitzero,inline"` + OfBashTool20241022 *BetaToolBash20241022Param `json:",omitzero,inline"` + OfBashTool20250124 *BetaToolBash20250124Param `json:",omitzero,inline"` + OfCodeExecutionTool20250522 *BetaCodeExecutionTool20250522Param `json:",omitzero,inline"` + OfCodeExecutionTool20250825 *BetaCodeExecutionTool20250825Param `json:",omitzero,inline"` + OfCodeExecutionTool20260120 *BetaCodeExecutionTool20260120Param `json:",omitzero,inline"` + OfCodeExecutionTool20260521 *BetaCodeExecutionTool20260521Param `json:",omitzero,inline"` + OfBrowserToolset20260801 *BetaBrowserToolset20260801Param `json:",omitzero,inline"` + OfComputerUseTool20241022 *BetaToolComputerUse20241022Param `json:",omitzero,inline"` + OfMemoryTool20250818 *BetaMemoryTool20250818Param `json:",omitzero,inline"` + OfComputerUseTool20250124 *BetaToolComputerUse20250124Param `json:",omitzero,inline"` + OfTextEditor20241022 *BetaToolTextEditor20241022Param `json:",omitzero,inline"` + OfComputerUseTool20251124 *BetaToolComputerUse20251124Param `json:",omitzero,inline"` + OfComputerToolset20260801 *BetaComputerToolset20260801Param `json:",omitzero,inline"` + OfTextEditor20250124 *BetaToolTextEditor20250124Param `json:",omitzero,inline"` + OfTextEditor20250429 *BetaToolTextEditor20250429Param `json:",omitzero,inline"` + OfTextEditor20250728 *BetaToolTextEditor20250728Param `json:",omitzero,inline"` + OfWebSearchTool20250305 *BetaWebSearchTool20250305Param `json:",omitzero,inline"` + OfWebFetchTool20250910 *BetaWebFetchTool20250910Param `json:",omitzero,inline"` + OfWebSearchTool20260209 *BetaWebSearchTool20260209Param `json:",omitzero,inline"` + OfWebFetchTool20260209 *BetaWebFetchTool20260209Param `json:",omitzero,inline"` + OfWebFetchTool20260309 *BetaWebFetchTool20260309Param `json:",omitzero,inline"` + OfWebSearchTool20260318 *BetaWebSearchTool20260318Param `json:",omitzero,inline"` + OfWebFetchTool20260318 *BetaWebFetchTool20260318Param `json:",omitzero,inline"` + OfAdvisorTool20260301 *BetaAdvisorTool20260301Param `json:",omitzero,inline"` + OfToolSearchToolBm25_20251119 *BetaToolSearchToolBm25_20251119Param `json:",omitzero,inline"` + OfToolSearchToolRegex20251119 *BetaToolSearchToolRegex20251119Param `json:",omitzero,inline"` + OfMCPToolset *BetaMCPToolsetParam `json:",omitzero,inline"` + paramUnion +} + +func (u BetaToolUnionParam) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfTool, + u.OfBashTool20241022, + u.OfBashTool20250124, + u.OfCodeExecutionTool20250522, + u.OfCodeExecutionTool20250825, + u.OfCodeExecutionTool20260120, + u.OfCodeExecutionTool20260521, + u.OfBrowserToolset20260801, + u.OfComputerUseTool20241022, + u.OfMemoryTool20250818, + u.OfComputerUseTool20250124, + u.OfTextEditor20241022, + u.OfComputerUseTool20251124, + u.OfComputerToolset20260801, + u.OfTextEditor20250124, + u.OfTextEditor20250429, + u.OfTextEditor20250728, + u.OfWebSearchTool20250305, + u.OfWebFetchTool20250910, + u.OfWebSearchTool20260209, + u.OfWebFetchTool20260209, + u.OfWebFetchTool20260309, + u.OfWebSearchTool20260318, + u.OfWebFetchTool20260318, + u.OfAdvisorTool20260301, + u.OfToolSearchToolBm25_20251119, + u.OfToolSearchToolRegex20251119, + u.OfMCPToolset) +} +func (u *BetaToolUnionParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *BetaToolUnionParam) asAny() any { + if !param.IsOmitted(u.OfTool) { + return u.OfTool + } else if !param.IsOmitted(u.OfBashTool20241022) { + return u.OfBashTool20241022 + } else if !param.IsOmitted(u.OfBashTool20250124) { + return u.OfBashTool20250124 + } else if !param.IsOmitted(u.OfCodeExecutionTool20250522) { + return u.OfCodeExecutionTool20250522 + } else if !param.IsOmitted(u.OfCodeExecutionTool20250825) { + return u.OfCodeExecutionTool20250825 + } else if !param.IsOmitted(u.OfCodeExecutionTool20260120) { + return u.OfCodeExecutionTool20260120 + } else if !param.IsOmitted(u.OfCodeExecutionTool20260521) { + return u.OfCodeExecutionTool20260521 + } else if !param.IsOmitted(u.OfBrowserToolset20260801) { + return u.OfBrowserToolset20260801 + } else if !param.IsOmitted(u.OfComputerUseTool20241022) { + return u.OfComputerUseTool20241022 + } else if !param.IsOmitted(u.OfMemoryTool20250818) { + return u.OfMemoryTool20250818 + } else if !param.IsOmitted(u.OfComputerUseTool20250124) { + return u.OfComputerUseTool20250124 + } else if !param.IsOmitted(u.OfTextEditor20241022) { + return u.OfTextEditor20241022 + } else if !param.IsOmitted(u.OfComputerUseTool20251124) { + return u.OfComputerUseTool20251124 + } else if !param.IsOmitted(u.OfComputerToolset20260801) { + return u.OfComputerToolset20260801 + } else if !param.IsOmitted(u.OfTextEditor20250124) { + return u.OfTextEditor20250124 + } else if !param.IsOmitted(u.OfTextEditor20250429) { + return u.OfTextEditor20250429 + } else if !param.IsOmitted(u.OfTextEditor20250728) { + return u.OfTextEditor20250728 + } else if !param.IsOmitted(u.OfWebSearchTool20250305) { + return u.OfWebSearchTool20250305 + } else if !param.IsOmitted(u.OfWebFetchTool20250910) { + return u.OfWebFetchTool20250910 + } else if !param.IsOmitted(u.OfWebSearchTool20260209) { + return u.OfWebSearchTool20260209 + } else if !param.IsOmitted(u.OfWebFetchTool20260209) { + return u.OfWebFetchTool20260209 + } else if !param.IsOmitted(u.OfWebFetchTool20260309) { + return u.OfWebFetchTool20260309 + } else if !param.IsOmitted(u.OfWebSearchTool20260318) { + return u.OfWebSearchTool20260318 + } else if !param.IsOmitted(u.OfWebFetchTool20260318) { + return u.OfWebFetchTool20260318 + } else if !param.IsOmitted(u.OfAdvisorTool20260301) { + return u.OfAdvisorTool20260301 + } else if !param.IsOmitted(u.OfToolSearchToolBm25_20251119) { + return u.OfToolSearchToolBm25_20251119 + } else if !param.IsOmitted(u.OfToolSearchToolRegex20251119) { + return u.OfToolSearchToolRegex20251119 + } else if !param.IsOmitted(u.OfMCPToolset) { + return u.OfMCPToolset + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaToolUnionParam) GetInputSchema() *BetaToolInputSchemaParam { + if vt := u.OfTool; vt != nil { + return &vt.InputSchema + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaToolUnionParam) GetDescription() *string { + if vt := u.OfTool; vt != nil && vt.Description.Valid() { + return &vt.Description.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaToolUnionParam) GetEagerInputStreaming() *bool { + if vt := u.OfTool; vt != nil && vt.EagerInputStreaming.Valid() { + return &vt.EagerInputStreaming.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaToolUnionParam) GetEnableZoom() *bool { + if vt := u.OfComputerUseTool20251124; vt != nil && vt.EnableZoom.Valid() { + return &vt.EnableZoom.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaToolUnionParam) GetMaxCharacters() *int64 { + if vt := u.OfTextEditor20250728; vt != nil && vt.MaxCharacters.Valid() { + return &vt.MaxCharacters.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaToolUnionParam) GetModel() *Model { + if vt := u.OfAdvisorTool20260301; vt != nil { + return &vt.Model + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaToolUnionParam) GetCaching() *BetaCacheControlEphemeralParam { + if vt := u.OfAdvisorTool20260301; vt != nil { + return &vt.Caching + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaToolUnionParam) GetMaxTokens() *int64 { + if vt := u.OfAdvisorTool20260301; vt != nil && vt.MaxTokens.Valid() { + return &vt.MaxTokens.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaToolUnionParam) GetMCPServerName() *string { + if vt := u.OfMCPToolset; vt != nil { + return &vt.MCPServerName + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaToolUnionParam) GetDefaultConfig() *BetaMCPToolDefaultConfigParam { + if vt := u.OfMCPToolset; vt != nil { + return &vt.DefaultConfig + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaToolUnionParam) GetName() *string { + if vt := u.OfTool; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfBashTool20241022; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfBashTool20250124; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfCodeExecutionTool20250522; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfCodeExecutionTool20250825; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfCodeExecutionTool20260120; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfCodeExecutionTool20260521; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfComputerUseTool20241022; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfMemoryTool20250818; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfComputerUseTool20250124; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfTextEditor20241022; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfComputerUseTool20251124; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfTextEditor20250124; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfTextEditor20250429; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfTextEditor20250728; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfWebSearchTool20250305; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfWebFetchTool20250910; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfWebSearchTool20260209; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfWebFetchTool20260209; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfWebFetchTool20260309; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfWebSearchTool20260318; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfWebFetchTool20260318; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfAdvisorTool20260301; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfToolSearchToolRegex20251119; vt != nil { + return (*string)(&vt.Name) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaToolUnionParam) GetDeferLoading() *bool { + if vt := u.OfTool; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfBashTool20241022; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfBashTool20250124; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfCodeExecutionTool20250522; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfCodeExecutionTool20250825; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfCodeExecutionTool20260120; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfCodeExecutionTool20260521; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfComputerUseTool20241022; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfMemoryTool20250818; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfComputerUseTool20250124; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfTextEditor20241022; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfComputerUseTool20251124; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfTextEditor20250124; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfTextEditor20250429; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfTextEditor20250728; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfWebSearchTool20250305; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfWebFetchTool20250910; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfWebSearchTool20260209; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfWebFetchTool20260209; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfWebFetchTool20260309; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfWebSearchTool20260318; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfWebFetchTool20260318; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfAdvisorTool20260301; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfToolSearchToolRegex20251119; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaToolUnionParam) GetStrict() *bool { + if vt := u.OfTool; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfBashTool20241022; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfBashTool20250124; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfCodeExecutionTool20250522; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfCodeExecutionTool20250825; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfCodeExecutionTool20260120; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfCodeExecutionTool20260521; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfComputerUseTool20241022; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfMemoryTool20250818; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfComputerUseTool20250124; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfTextEditor20241022; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfComputerUseTool20251124; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfTextEditor20250124; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfTextEditor20250429; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfTextEditor20250728; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfWebSearchTool20250305; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfWebFetchTool20250910; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfWebSearchTool20260209; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfWebFetchTool20260209; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfWebFetchTool20260309; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfWebSearchTool20260318; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfWebFetchTool20260318; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfAdvisorTool20260301; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfToolSearchToolRegex20251119; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaToolUnionParam) GetType() *string { + if vt := u.OfTool; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfBashTool20241022; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfBashTool20250124; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfCodeExecutionTool20250522; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfCodeExecutionTool20250825; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfCodeExecutionTool20260120; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfCodeExecutionTool20260521; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfBrowserToolset20260801; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfComputerUseTool20241022; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfMemoryTool20250818; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfComputerUseTool20250124; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfTextEditor20241022; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfComputerUseTool20251124; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfComputerToolset20260801; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfTextEditor20250124; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfTextEditor20250429; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfTextEditor20250728; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfWebSearchTool20250305; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfWebFetchTool20250910; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfWebSearchTool20260209; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfWebFetchTool20260209; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfWebFetchTool20260309; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfWebSearchTool20260318; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfWebFetchTool20260318; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfAdvisorTool20260301; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfToolSearchToolRegex20251119; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfMCPToolset; vt != nil { + return (*string)(&vt.Type) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaToolUnionParam) GetDisplayHeightPx() *int64 { + if vt := u.OfComputerUseTool20241022; vt != nil { + return (*int64)(&vt.DisplayHeightPx) + } else if vt := u.OfComputerUseTool20250124; vt != nil { + return (*int64)(&vt.DisplayHeightPx) + } else if vt := u.OfComputerUseTool20251124; vt != nil { + return (*int64)(&vt.DisplayHeightPx) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaToolUnionParam) GetDisplayWidthPx() *int64 { + if vt := u.OfComputerUseTool20241022; vt != nil { + return (*int64)(&vt.DisplayWidthPx) + } else if vt := u.OfComputerUseTool20250124; vt != nil { + return (*int64)(&vt.DisplayWidthPx) + } else if vt := u.OfComputerUseTool20251124; vt != nil { + return (*int64)(&vt.DisplayWidthPx) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaToolUnionParam) GetDisplayNumber() *int64 { + if vt := u.OfComputerUseTool20241022; vt != nil && vt.DisplayNumber.Valid() { + return &vt.DisplayNumber.Value + } else if vt := u.OfComputerUseTool20250124; vt != nil && vt.DisplayNumber.Valid() { + return &vt.DisplayNumber.Value + } else if vt := u.OfComputerUseTool20251124; vt != nil && vt.DisplayNumber.Valid() { + return &vt.DisplayNumber.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaToolUnionParam) GetMaxUses() *int64 { + if vt := u.OfWebSearchTool20250305; vt != nil && vt.MaxUses.Valid() { + return &vt.MaxUses.Value + } else if vt := u.OfWebFetchTool20250910; vt != nil && vt.MaxUses.Valid() { + return &vt.MaxUses.Value + } else if vt := u.OfWebSearchTool20260209; vt != nil && vt.MaxUses.Valid() { + return &vt.MaxUses.Value + } else if vt := u.OfWebFetchTool20260209; vt != nil && vt.MaxUses.Valid() { + return &vt.MaxUses.Value + } else if vt := u.OfWebFetchTool20260309; vt != nil && vt.MaxUses.Valid() { + return &vt.MaxUses.Value + } else if vt := u.OfWebSearchTool20260318; vt != nil && vt.MaxUses.Valid() { + return &vt.MaxUses.Value + } else if vt := u.OfWebFetchTool20260318; vt != nil && vt.MaxUses.Valid() { + return &vt.MaxUses.Value + } else if vt := u.OfAdvisorTool20260301; vt != nil && vt.MaxUses.Valid() { + return &vt.MaxUses.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaToolUnionParam) GetMaxContentTokens() *int64 { + if vt := u.OfWebFetchTool20250910; vt != nil && vt.MaxContentTokens.Valid() { + return &vt.MaxContentTokens.Value + } else if vt := u.OfWebFetchTool20260209; vt != nil && vt.MaxContentTokens.Valid() { + return &vt.MaxContentTokens.Value + } else if vt := u.OfWebFetchTool20260309; vt != nil && vt.MaxContentTokens.Valid() { + return &vt.MaxContentTokens.Value + } else if vt := u.OfWebFetchTool20260318; vt != nil && vt.MaxContentTokens.Valid() { + return &vt.MaxContentTokens.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaToolUnionParam) GetUseCache() *bool { + if vt := u.OfWebFetchTool20260309; vt != nil && vt.UseCache.Valid() { + return &vt.UseCache.Value + } else if vt := u.OfWebFetchTool20260318; vt != nil && vt.UseCache.Valid() { + return &vt.UseCache.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaToolUnionParam) GetResponseInclusion() *string { + if vt := u.OfWebSearchTool20260318; vt != nil { + return (*string)(&vt.ResponseInclusion) + } else if vt := u.OfWebFetchTool20260318; vt != nil { + return (*string)(&vt.ResponseInclusion) + } + return nil +} + +// Returns a pointer to the underlying variant's AllowedCallers property, if +// present. +func (u BetaToolUnionParam) GetAllowedCallers() []string { + if vt := u.OfTool; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfBashTool20241022; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfBashTool20250124; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfCodeExecutionTool20250522; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfCodeExecutionTool20250825; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfCodeExecutionTool20260120; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfCodeExecutionTool20260521; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfBrowserToolset20260801; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfComputerUseTool20241022; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfMemoryTool20250818; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfComputerUseTool20250124; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfTextEditor20241022; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfComputerUseTool20251124; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfComputerToolset20260801; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfTextEditor20250124; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfTextEditor20250429; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfTextEditor20250728; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfWebSearchTool20250305; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfWebFetchTool20250910; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfWebSearchTool20260209; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfWebFetchTool20260209; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfWebFetchTool20260309; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfWebSearchTool20260318; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfWebFetchTool20260318; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfAdvisorTool20260301; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfToolSearchToolRegex20251119; vt != nil { + return vt.AllowedCallers + } + return nil +} + +// Returns a pointer to the underlying variant's CacheControl property, if present. +func (u BetaToolUnionParam) GetCacheControl() *BetaCacheControlEphemeralParam { + if vt := u.OfTool; vt != nil { + return &vt.CacheControl + } else if vt := u.OfBashTool20241022; vt != nil { + return &vt.CacheControl + } else if vt := u.OfBashTool20250124; vt != nil { + return &vt.CacheControl + } else if vt := u.OfCodeExecutionTool20250522; vt != nil { + return &vt.CacheControl + } else if vt := u.OfCodeExecutionTool20250825; vt != nil { + return &vt.CacheControl + } else if vt := u.OfCodeExecutionTool20260120; vt != nil { + return &vt.CacheControl + } else if vt := u.OfCodeExecutionTool20260521; vt != nil { + return &vt.CacheControl + } else if vt := u.OfBrowserToolset20260801; vt != nil { + return &vt.CacheControl + } else if vt := u.OfComputerUseTool20241022; vt != nil { + return &vt.CacheControl + } else if vt := u.OfMemoryTool20250818; vt != nil { + return &vt.CacheControl + } else if vt := u.OfComputerUseTool20250124; vt != nil { + return &vt.CacheControl + } else if vt := u.OfTextEditor20241022; vt != nil { + return &vt.CacheControl + } else if vt := u.OfComputerUseTool20251124; vt != nil { + return &vt.CacheControl + } else if vt := u.OfComputerToolset20260801; vt != nil { + return &vt.CacheControl + } else if vt := u.OfTextEditor20250124; vt != nil { + return &vt.CacheControl + } else if vt := u.OfTextEditor20250429; vt != nil { + return &vt.CacheControl + } else if vt := u.OfTextEditor20250728; vt != nil { + return &vt.CacheControl + } else if vt := u.OfWebSearchTool20250305; vt != nil { + return &vt.CacheControl + } else if vt := u.OfWebFetchTool20250910; vt != nil { + return &vt.CacheControl + } else if vt := u.OfWebSearchTool20260209; vt != nil { + return &vt.CacheControl + } else if vt := u.OfWebFetchTool20260209; vt != nil { + return &vt.CacheControl + } else if vt := u.OfWebFetchTool20260309; vt != nil { + return &vt.CacheControl + } else if vt := u.OfWebSearchTool20260318; vt != nil { + return &vt.CacheControl + } else if vt := u.OfWebFetchTool20260318; vt != nil { + return &vt.CacheControl + } else if vt := u.OfAdvisorTool20260301; vt != nil { + return &vt.CacheControl + } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil { + return &vt.CacheControl + } else if vt := u.OfToolSearchToolRegex20251119; vt != nil { + return &vt.CacheControl + } else if vt := u.OfMCPToolset; vt != nil { + return &vt.CacheControl + } + return nil +} + +// Returns a pointer to the underlying variant's InputExamples property, if +// present. +func (u BetaToolUnionParam) GetInputExamples() []map[string]any { + if vt := u.OfTool; vt != nil { + return vt.InputExamples + } else if vt := u.OfBashTool20241022; vt != nil { + return vt.InputExamples + } else if vt := u.OfBashTool20250124; vt != nil { + return vt.InputExamples + } else if vt := u.OfComputerUseTool20241022; vt != nil { + return vt.InputExamples + } else if vt := u.OfMemoryTool20250818; vt != nil { + return vt.InputExamples + } else if vt := u.OfComputerUseTool20250124; vt != nil { + return vt.InputExamples + } else if vt := u.OfTextEditor20241022; vt != nil { + return vt.InputExamples + } else if vt := u.OfComputerUseTool20251124; vt != nil { + return vt.InputExamples + } else if vt := u.OfTextEditor20250124; vt != nil { + return vt.InputExamples + } else if vt := u.OfTextEditor20250429; vt != nil { + return vt.InputExamples + } else if vt := u.OfTextEditor20250728; vt != nil { + return vt.InputExamples + } + return nil +} + +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u BetaToolUnionParam) GetConfigs() (res betaToolUnionParamConfigs) { + if vt := u.OfBrowserToolset20260801; vt != nil { + res.any = &vt.Configs + } else if vt := u.OfComputerToolset20260801; vt != nil { + res.any = &vt.Configs + } else if vt := u.OfMCPToolset; vt != nil { + res.any = &vt.Configs + } + return +} + +// Can have the runtime types [*BetaBrowserToolsetConfigsParam], +// [*BetaComputerToolsetConfigsParam], [\*map[string]BetaMCPToolConfigParam] +type betaToolUnionParamConfigs struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BetaBrowserToolsetConfigsParam: +// case *anthropic.BetaComputerToolsetConfigsParam: +// case *map[string]anthropic.BetaMCPToolConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u betaToolUnionParamConfigs) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolUnionParamConfigs) GetCloseTab() *BetaBrowserCloseTabConfigParam { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + return &vt.CloseTab + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolUnionParamConfigs) GetFileUpload() *BetaBrowserFileUploadConfigParam { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + return &vt.FileUpload + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolUnionParamConfigs) GetFind() *BetaBrowserFindConfigParam { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + return &vt.Find + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolUnionParamConfigs) GetFormInput() *BetaBrowserFormInputConfigParam { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + return &vt.FormInput + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolUnionParamConfigs) GetGetPageText() *BetaBrowserGetPageTextConfigParam { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + return &vt.GetPageText + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolUnionParamConfigs) GetHover() *BetaBrowserHoverConfigParam { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + return &vt.Hover + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolUnionParamConfigs) GetJavascriptExec() *BetaBrowserJavascriptExecConfigParam { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + return &vt.JavascriptExec + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolUnionParamConfigs) GetListTabs() *BetaBrowserListTabsConfigParam { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + return &vt.ListTabs + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolUnionParamConfigs) GetNavigate() *BetaBrowserNavigateConfigParam { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + return &vt.Navigate + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolUnionParamConfigs) GetNewTab() *BetaBrowserNewTabConfigParam { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + return &vt.NewTab + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolUnionParamConfigs) GetReadConsole() *BetaBrowserReadConsoleConfigParam { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + return &vt.ReadConsole + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolUnionParamConfigs) GetReadNetwork() *BetaBrowserReadNetworkConfigParam { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + return &vt.ReadNetwork + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolUnionParamConfigs) GetReadPage() *BetaBrowserReadPageConfigParam { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + return &vt.ReadPage + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolUnionParamConfigs) GetScrollTo() *BetaBrowserScrollToConfigParam { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + return &vt.ScrollTo + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolUnionParamConfigs) GetSwitchTab() *BetaBrowserSwitchTabConfigParam { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + return &vt.SwitchTab + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolUnionParamConfigs) GetCursorPosition() *BetaComputerCursorPositionConfigParam { + switch vt := u.any.(type) { + case *BetaComputerToolsetConfigsParam: + return &vt.CursorPosition + } + return nil +} + +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u betaToolUnionParamConfigs) GetDoubleClick() (res betaToolUnionParamConfigsDoubleClick) { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + res.any = &vt.DoubleClick + case *BetaComputerToolsetConfigsParam: + res.any = &vt.DoubleClick + } + return res +} + +// Can have the runtime types [*BetaBrowserDoubleClickConfigParam], +// [*BetaComputerDoubleClickConfigParam] +type betaToolUnionParamConfigsDoubleClick struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BetaBrowserDoubleClickConfigParam: +// case *anthropic.BetaComputerDoubleClickConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u betaToolUnionParamConfigsDoubleClick) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolUnionParamConfigsDoubleClick) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BetaBrowserDoubleClickConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *BetaComputerDoubleClickConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolUnionParamConfigsDoubleClick) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BetaBrowserDoubleClickConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *BetaComputerDoubleClickConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + } + return nil +} + +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u betaToolUnionParamConfigs) GetHoldKey() (res betaToolUnionParamConfigsHoldKey) { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + res.any = &vt.HoldKey + case *BetaComputerToolsetConfigsParam: + res.any = &vt.HoldKey + } + return res +} + +// Can have the runtime types [*BetaBrowserHoldKeyConfigParam], +// [*BetaComputerHoldKeyConfigParam] +type betaToolUnionParamConfigsHoldKey struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BetaBrowserHoldKeyConfigParam: +// case *anthropic.BetaComputerHoldKeyConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u betaToolUnionParamConfigsHoldKey) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolUnionParamConfigsHoldKey) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BetaBrowserHoldKeyConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *BetaComputerHoldKeyConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolUnionParamConfigsHoldKey) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BetaBrowserHoldKeyConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *BetaComputerHoldKeyConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + } + return nil +} + +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u betaToolUnionParamConfigs) GetKey() (res betaToolUnionParamConfigsKey) { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + res.any = &vt.Key + case *BetaComputerToolsetConfigsParam: + res.any = &vt.Key + } + return res +} + +// Can have the runtime types [*BetaBrowserKeyConfigParam], +// [*BetaComputerKeyConfigParam] +type betaToolUnionParamConfigsKey struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BetaBrowserKeyConfigParam: +// case *anthropic.BetaComputerKeyConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u betaToolUnionParamConfigsKey) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolUnionParamConfigsKey) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BetaBrowserKeyConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *BetaComputerKeyConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolUnionParamConfigsKey) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BetaBrowserKeyConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *BetaComputerKeyConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + } + return nil +} + +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u betaToolUnionParamConfigs) GetLeftClick() (res betaToolUnionParamConfigsLeftClick) { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + res.any = &vt.LeftClick + case *BetaComputerToolsetConfigsParam: + res.any = &vt.LeftClick + } + return res +} + +// Can have the runtime types [*BetaBrowserLeftClickConfigParam], +// [*BetaComputerLeftClickConfigParam] +type betaToolUnionParamConfigsLeftClick struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BetaBrowserLeftClickConfigParam: +// case *anthropic.BetaComputerLeftClickConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u betaToolUnionParamConfigsLeftClick) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolUnionParamConfigsLeftClick) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BetaBrowserLeftClickConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *BetaComputerLeftClickConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolUnionParamConfigsLeftClick) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BetaBrowserLeftClickConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *BetaComputerLeftClickConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + } + return nil +} + +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u betaToolUnionParamConfigs) GetLeftClickDrag() (res betaToolUnionParamConfigsLeftClickDrag) { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + res.any = &vt.LeftClickDrag + case *BetaComputerToolsetConfigsParam: + res.any = &vt.LeftClickDrag + } + return res +} + +// Can have the runtime types [*BetaBrowserLeftClickDragConfigParam], +// [*BetaComputerLeftClickDragConfigParam] +type betaToolUnionParamConfigsLeftClickDrag struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BetaBrowserLeftClickDragConfigParam: +// case *anthropic.BetaComputerLeftClickDragConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u betaToolUnionParamConfigsLeftClickDrag) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolUnionParamConfigsLeftClickDrag) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BetaBrowserLeftClickDragConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *BetaComputerLeftClickDragConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolUnionParamConfigsLeftClickDrag) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BetaBrowserLeftClickDragConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *BetaComputerLeftClickDragConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + } + return nil +} + +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u betaToolUnionParamConfigs) GetLeftMouseDown() (res betaToolUnionParamConfigsLeftMouseDown) { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + res.any = &vt.LeftMouseDown + case *BetaComputerToolsetConfigsParam: + res.any = &vt.LeftMouseDown + } + return res +} + +// Can have the runtime types [*BetaBrowserLeftMouseDownConfigParam], +// [*BetaComputerLeftMouseDownConfigParam] +type betaToolUnionParamConfigsLeftMouseDown struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BetaBrowserLeftMouseDownConfigParam: +// case *anthropic.BetaComputerLeftMouseDownConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u betaToolUnionParamConfigsLeftMouseDown) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolUnionParamConfigsLeftMouseDown) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BetaBrowserLeftMouseDownConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *BetaComputerLeftMouseDownConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolUnionParamConfigsLeftMouseDown) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BetaBrowserLeftMouseDownConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *BetaComputerLeftMouseDownConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + } + return nil +} + +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u betaToolUnionParamConfigs) GetLeftMouseUp() (res betaToolUnionParamConfigsLeftMouseUp) { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + res.any = &vt.LeftMouseUp + case *BetaComputerToolsetConfigsParam: + res.any = &vt.LeftMouseUp + } + return res +} + +// Can have the runtime types [*BetaBrowserLeftMouseUpConfigParam], +// [*BetaComputerLeftMouseUpConfigParam] +type betaToolUnionParamConfigsLeftMouseUp struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BetaBrowserLeftMouseUpConfigParam: +// case *anthropic.BetaComputerLeftMouseUpConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u betaToolUnionParamConfigsLeftMouseUp) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolUnionParamConfigsLeftMouseUp) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BetaBrowserLeftMouseUpConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *BetaComputerLeftMouseUpConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolUnionParamConfigsLeftMouseUp) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BetaBrowserLeftMouseUpConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *BetaComputerLeftMouseUpConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + } + return nil +} + +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u betaToolUnionParamConfigs) GetMiddleClick() (res betaToolUnionParamConfigsMiddleClick) { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + res.any = &vt.MiddleClick + case *BetaComputerToolsetConfigsParam: + res.any = &vt.MiddleClick + } + return res +} + +// Can have the runtime types [*BetaBrowserMiddleClickConfigParam], +// [*BetaComputerMiddleClickConfigParam] +type betaToolUnionParamConfigsMiddleClick struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BetaBrowserMiddleClickConfigParam: +// case *anthropic.BetaComputerMiddleClickConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u betaToolUnionParamConfigsMiddleClick) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolUnionParamConfigsMiddleClick) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BetaBrowserMiddleClickConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *BetaComputerMiddleClickConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolUnionParamConfigsMiddleClick) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BetaBrowserMiddleClickConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *BetaComputerMiddleClickConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + } + return nil +} + +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u betaToolUnionParamConfigs) GetMouseMove() (res betaToolUnionParamConfigsMouseMove) { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + res.any = &vt.MouseMove + case *BetaComputerToolsetConfigsParam: + res.any = &vt.MouseMove + } + return res +} + +// Can have the runtime types [*BetaBrowserMouseMoveConfigParam], +// [*BetaComputerMouseMoveConfigParam] +type betaToolUnionParamConfigsMouseMove struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BetaBrowserMouseMoveConfigParam: +// case *anthropic.BetaComputerMouseMoveConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u betaToolUnionParamConfigsMouseMove) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolUnionParamConfigsMouseMove) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BetaBrowserMouseMoveConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *BetaComputerMouseMoveConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolUnionParamConfigsMouseMove) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BetaBrowserMouseMoveConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *BetaComputerMouseMoveConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + } + return nil +} + +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u betaToolUnionParamConfigs) GetRightClick() (res betaToolUnionParamConfigsRightClick) { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + res.any = &vt.RightClick + case *BetaComputerToolsetConfigsParam: + res.any = &vt.RightClick + } + return res +} + +// Can have the runtime types [*BetaBrowserRightClickConfigParam], +// [*BetaComputerRightClickConfigParam] +type betaToolUnionParamConfigsRightClick struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BetaBrowserRightClickConfigParam: +// case *anthropic.BetaComputerRightClickConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u betaToolUnionParamConfigsRightClick) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolUnionParamConfigsRightClick) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BetaBrowserRightClickConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *BetaComputerRightClickConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolUnionParamConfigsRightClick) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BetaBrowserRightClickConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *BetaComputerRightClickConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + } + return nil +} + +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u betaToolUnionParamConfigs) GetScreenshot() (res betaToolUnionParamConfigsScreenshot) { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + res.any = &vt.Screenshot + case *BetaComputerToolsetConfigsParam: + res.any = &vt.Screenshot + } + return res +} + +// Can have the runtime types [*BetaBrowserScreenshotConfigParam], +// [*BetaComputerScreenshotConfigParam] +type betaToolUnionParamConfigsScreenshot struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BetaBrowserScreenshotConfigParam: +// case *anthropic.BetaComputerScreenshotConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u betaToolUnionParamConfigsScreenshot) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolUnionParamConfigsScreenshot) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BetaBrowserScreenshotConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *BetaComputerScreenshotConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolUnionParamConfigsScreenshot) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BetaBrowserScreenshotConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *BetaComputerScreenshotConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + } + return nil +} + +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u betaToolUnionParamConfigs) GetScroll() (res betaToolUnionParamConfigsScroll) { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + res.any = &vt.Scroll + case *BetaComputerToolsetConfigsParam: + res.any = &vt.Scroll + } + return res +} + +// Can have the runtime types [*BetaBrowserScrollConfigParam], +// [*BetaComputerScrollConfigParam] +type betaToolUnionParamConfigsScroll struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BetaBrowserScrollConfigParam: +// case *anthropic.BetaComputerScrollConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u betaToolUnionParamConfigsScroll) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolUnionParamConfigsScroll) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BetaBrowserScrollConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *BetaComputerScrollConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolUnionParamConfigsScroll) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BetaBrowserScrollConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *BetaComputerScrollConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + } + return nil +} + +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u betaToolUnionParamConfigs) GetTripleClick() (res betaToolUnionParamConfigsTripleClick) { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + res.any = &vt.TripleClick + case *BetaComputerToolsetConfigsParam: + res.any = &vt.TripleClick + } + return res +} + +// Can have the runtime types [*BetaBrowserTripleClickConfigParam], +// [*BetaComputerTripleClickConfigParam] +type betaToolUnionParamConfigsTripleClick struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BetaBrowserTripleClickConfigParam: +// case *anthropic.BetaComputerTripleClickConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u betaToolUnionParamConfigsTripleClick) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolUnionParamConfigsTripleClick) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BetaBrowserTripleClickConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *BetaComputerTripleClickConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolUnionParamConfigsTripleClick) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BetaBrowserTripleClickConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *BetaComputerTripleClickConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + } + return nil +} + +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u betaToolUnionParamConfigs) GetType() (res betaToolUnionParamConfigsType) { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + res.any = &vt.Type + case *BetaComputerToolsetConfigsParam: + res.any = &vt.Type + } + return res +} + +// Can have the runtime types [*BetaBrowserTypeConfigParam], +// [*BetaComputerTypeConfigParam] +type betaToolUnionParamConfigsType struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BetaBrowserTypeConfigParam: +// case *anthropic.BetaComputerTypeConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u betaToolUnionParamConfigsType) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolUnionParamConfigsType) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BetaBrowserTypeConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *BetaComputerTypeConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolUnionParamConfigsType) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BetaBrowserTypeConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *BetaComputerTypeConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + } + return nil +} + +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u betaToolUnionParamConfigs) GetWait() (res betaToolUnionParamConfigsWait) { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + res.any = &vt.Wait + case *BetaComputerToolsetConfigsParam: + res.any = &vt.Wait + } + return res +} + +// Can have the runtime types [*BetaBrowserWaitConfigParam], +// [*BetaComputerWaitConfigParam] +type betaToolUnionParamConfigsWait struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BetaBrowserWaitConfigParam: +// case *anthropic.BetaComputerWaitConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u betaToolUnionParamConfigsWait) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolUnionParamConfigsWait) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BetaBrowserWaitConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *BetaComputerWaitConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolUnionParamConfigsWait) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BetaBrowserWaitConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *BetaComputerWaitConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + } + return nil +} + +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u betaToolUnionParamConfigs) GetZoom() (res betaToolUnionParamConfigsZoom) { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + res.any = &vt.Zoom + case *BetaComputerToolsetConfigsParam: + res.any = &vt.Zoom + } + return res +} + +// Can have the runtime types [*BetaBrowserZoomConfigParam], +// [*BetaComputerZoomConfigParam] +type betaToolUnionParamConfigsZoom struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BetaBrowserZoomConfigParam: +// case *anthropic.BetaComputerZoomConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u betaToolUnionParamConfigsZoom) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolUnionParamConfigsZoom) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BetaBrowserZoomConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *BetaComputerZoomConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaToolUnionParamConfigsZoom) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BetaBrowserZoomConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *BetaComputerZoomConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + } + return nil +} + +// Returns a pointer to the underlying variant's AllowedDomains property, if +// present. +func (u BetaToolUnionParam) GetAllowedDomains() []string { + if vt := u.OfWebSearchTool20250305; vt != nil { + return vt.AllowedDomains + } else if vt := u.OfWebFetchTool20250910; vt != nil { + return vt.AllowedDomains + } else if vt := u.OfWebSearchTool20260209; vt != nil { + return vt.AllowedDomains + } else if vt := u.OfWebFetchTool20260209; vt != nil { + return vt.AllowedDomains + } else if vt := u.OfWebFetchTool20260309; vt != nil { + return vt.AllowedDomains + } else if vt := u.OfWebSearchTool20260318; vt != nil { + return vt.AllowedDomains + } else if vt := u.OfWebFetchTool20260318; vt != nil { + return vt.AllowedDomains + } + return nil +} + +// Returns a pointer to the underlying variant's BlockedDomains property, if +// present. +func (u BetaToolUnionParam) GetBlockedDomains() []string { + if vt := u.OfWebSearchTool20250305; vt != nil { + return vt.BlockedDomains + } else if vt := u.OfWebFetchTool20250910; vt != nil { + return vt.BlockedDomains + } else if vt := u.OfWebSearchTool20260209; vt != nil { + return vt.BlockedDomains + } else if vt := u.OfWebFetchTool20260209; vt != nil { + return vt.BlockedDomains + } else if vt := u.OfWebFetchTool20260309; vt != nil { + return vt.BlockedDomains + } else if vt := u.OfWebSearchTool20260318; vt != nil { + return vt.BlockedDomains + } else if vt := u.OfWebFetchTool20260318; vt != nil { + return vt.BlockedDomains + } + return nil +} + +// Returns a pointer to the underlying variant's UserLocation property, if present. +func (u BetaToolUnionParam) GetUserLocation() *BetaUserLocationParam { + if vt := u.OfWebSearchTool20250305; vt != nil { + return &vt.UserLocation + } else if vt := u.OfWebSearchTool20260209; vt != nil { + return &vt.UserLocation + } else if vt := u.OfWebSearchTool20260318; vt != nil { + return &vt.UserLocation + } + return nil +} + +// Returns a pointer to the underlying variant's Citations property, if present. +func (u BetaToolUnionParam) GetCitations() *BetaCitationsConfigParam { + if vt := u.OfWebFetchTool20250910; vt != nil { + return &vt.Citations + } else if vt := u.OfWebFetchTool20260209; vt != nil { + return &vt.Citations + } else if vt := u.OfWebFetchTool20260309; vt != nil { + return &vt.Citations + } else if vt := u.OfWebFetchTool20260318; vt != nil { + return &vt.Citations + } + return nil +} + +type BetaToolUseBlock struct { + ID string `json:"id" api:"required"` + Input any `json:"input" api:"required"` + Name string `json:"name" api:"required"` + Type constant.ToolUse `json:"type" default:"tool_use"` + // Tool invocation directly from the model. + Caller BetaToolUseBlockCallerUnion `json:"caller"` + // For a toolset member tool_use, the toolset family. + ToolsetName string `json:"toolset_name" api:"nullable"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + Input respjson.Field + Name respjson.Field + Type respjson.Field + Caller respjson.Field + ToolsetName respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaToolUseBlock) RawJSON() string { return r.JSON.raw } +func (r *BetaToolUseBlock) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaToolUseBlockCallerUnion contains all possible properties and values from +// [BetaDirectCaller], [BetaServerToolCaller], [BetaServerToolCaller20260120]. +// +// Use the [BetaToolUseBlockCallerUnion.AsAny] method to switch on the variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaToolUseBlockCallerUnion struct { + // Any of "direct", "code_execution_20250825", "code_execution_20260120". + Type string `json:"type"` + ToolID string `json:"tool_id"` + JSON struct { + Type respjson.Field + ToolID respjson.Field + raw string + } `json:"-"` +} + +// anyBetaToolUseBlockCaller is implemented by each variant of +// [BetaToolUseBlockCallerUnion] to add type safety for the return type of +// [BetaToolUseBlockCallerUnion.AsAny] +type anyBetaToolUseBlockCaller interface { + implBetaToolUseBlockCallerUnion() +} + +func (BetaDirectCaller) implBetaToolUseBlockCallerUnion() {} +func (BetaServerToolCaller) implBetaToolUseBlockCallerUnion() {} +func (BetaServerToolCaller20260120) implBetaToolUseBlockCallerUnion() {} + +// Use the following switch statement to find the correct variant +// +// switch variant := BetaToolUseBlockCallerUnion.AsAny().(type) { +// case anthropic.BetaDirectCaller: +// case anthropic.BetaServerToolCaller: +// case anthropic.BetaServerToolCaller20260120: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaToolUseBlockCallerUnion) AsAny() anyBetaToolUseBlockCaller { + switch u.Type { + case "direct": + return u.AsDirect() + case "code_execution_20250825": + return u.AsCodeExecution20250825() + case "code_execution_20260120": + return u.AsCodeExecution20260120() + } + return nil +} + +func (u BetaToolUseBlockCallerUnion) AsDirect() (v BetaDirectCaller) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaToolUseBlockCallerUnion) AsCodeExecution20250825() (v BetaServerToolCaller) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaToolUseBlockCallerUnion) AsCodeExecution20260120() (v BetaServerToolCaller20260120) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u BetaToolUseBlockCallerUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaToolUseBlockCallerUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The properties ID, Input, Name, Type are required. +type BetaToolUseBlockParam struct { + ID string `json:"id" api:"required"` + Input any `json:"input,omitzero" api:"required"` + Name string `json:"name" api:"required"` + // For a toolset member tool_use, the toolset family this member belongs to. + ToolsetName param.Opt[string] `json:"toolset_name,omitzero"` + // Create a cache control breakpoint at this content block. + CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` + // Tool invocation directly from the model. + Caller BetaToolUseBlockParamCallerUnion `json:"caller,omitzero"` + // This field can be elided, and will marshal its zero value as "tool_use". + Type constant.ToolUse `json:"type" default:"tool_use"` + paramObj +} + +func (r BetaToolUseBlockParam) MarshalJSON() (data []byte, err error) { + type shadow BetaToolUseBlockParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaToolUseBlockParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaToolUseBlockParamCallerUnion struct { + OfDirect *BetaDirectCallerParam `json:",omitzero,inline"` + OfCodeExecution20250825 *BetaServerToolCallerParam `json:",omitzero,inline"` + OfCodeExecution20260120 *BetaServerToolCaller20260120Param `json:",omitzero,inline"` + paramUnion +} + +func (u BetaToolUseBlockParamCallerUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfDirect, u.OfCodeExecution20250825, u.OfCodeExecution20260120) +} +func (u *BetaToolUseBlockParamCallerUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *BetaToolUseBlockParamCallerUnion) asAny() any { + if !param.IsOmitted(u.OfDirect) { + return u.OfDirect + } else if !param.IsOmitted(u.OfCodeExecution20250825) { + return u.OfCodeExecution20250825 + } else if !param.IsOmitted(u.OfCodeExecution20260120) { + return u.OfCodeExecution20260120 + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaToolUseBlockParamCallerUnion) GetType() *string { + if vt := u.OfDirect; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfCodeExecution20250825; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfCodeExecution20260120; vt != nil { + return (*string)(&vt.Type) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaToolUseBlockParamCallerUnion) GetToolID() *string { + if vt := u.OfCodeExecution20250825; vt != nil { + return (*string)(&vt.ToolID) + } else if vt := u.OfCodeExecution20260120; vt != nil { + return (*string)(&vt.ToolID) + } + return nil +} + +func init() { + apijson.RegisterUnion[BetaToolUseBlockParamCallerUnion]( + "type", + apijson.Discriminator[BetaDirectCallerParam]("direct"), + apijson.Discriminator[BetaServerToolCallerParam]("code_execution_20250825"), + apijson.Discriminator[BetaServerToolCaller20260120Param]("code_execution_20260120"), + ) +} + +// The properties Type, Value are required. +type BetaToolUsesKeepParam struct { + Value int64 `json:"value" api:"required"` + // This field can be elided, and will marshal its zero value as "tool_uses". + Type constant.ToolUses `json:"type" default:"tool_uses"` + paramObj +} + +func (r BetaToolUsesKeepParam) MarshalJSON() (data []byte, err error) { + type shadow BetaToolUsesKeepParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaToolUsesKeepParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The properties Type, Value are required. +type BetaToolUsesTriggerParam struct { + Value int64 `json:"value" api:"required"` + // This field can be elided, and will marshal its zero value as "tool_uses". + Type constant.ToolUses `json:"type" default:"tool_uses"` + paramObj +} + +func (r BetaToolUsesTriggerParam) MarshalJSON() (data []byte, err error) { + type shadow BetaToolUsesTriggerParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaToolUsesTriggerParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The properties Type, URL are required. +type BetaURLImageSourceParam struct { + URL string `json:"url" api:"required"` + // This field can be elided, and will marshal its zero value as "url". + Type constant.URL `json:"type" default:"url"` + paramObj +} + +func (r BetaURLImageSourceParam) MarshalJSON() (data []byte, err error) { + type shadow BetaURLImageSourceParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaURLImageSourceParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The properties Type, URL are required. +type BetaURLPDFSourceParam struct { + URL string `json:"url" api:"required"` + // This field can be elided, and will marshal its zero value as "url". + Type constant.URL `json:"type" default:"url"` + paramObj +} + +func (r BetaURLPDFSourceParam) MarshalJSON() (data []byte, err error) { + type shadow BetaURLPDFSourceParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaURLPDFSourceParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaUsage struct { + // Breakdown of cached tokens by TTL + CacheCreation BetaCacheCreation `json:"cache_creation" api:"required"` + // The number of input tokens used to create the cache entry. + CacheCreationInputTokens int64 `json:"cache_creation_input_tokens" api:"required"` + // The number of input tokens read from the cache. + CacheReadInputTokens int64 `json:"cache_read_input_tokens" api:"required"` + // Outcome of the `fallback_credit_token` presented on this request. + FallbackCredit BetaFallbackCreditUsage `json:"fallback_credit" api:"required"` + // The geographic region where inference was performed for this request. + InferenceGeo string `json:"inference_geo" api:"required"` + // The number of input tokens which were used. + InputTokens int64 `json:"input_tokens" api:"required"` + // Per-iteration token usage breakdown. + // + // Each entry represents one sampling iteration, with its own input/output token + // counts and cache statistics, discriminated by `type`. For `message` entries + // (model sampling iterations, such as the turns of a server-side tool use loop), + // this allows you to: + // + // - Determine which iterations exceeded long context thresholds (>=200k tokens) + // - Calculate the context window size from the last `message` entry + // - Understand token accumulation across server-side tool use loops + // + // A `compaction` entry reports the token usage of the compaction operation itself + // — the server-side request that summarizes the context being closed — NOT the + // size of the context that was compacted away, and its token counts can be much + // smaller than that closed context (for example, a compaction that closes a + // ~200k-token context can report only a few thousand tokens). Do not derive the + // context window size from a `compaction` entry, even when it is the last entry. A + // `compaction` entry's tokens are not included in the top-level `usage` fields. + // When an input-token trigger is in effect (the default — 150,000 tokens unless + // configured otherwise), each `compaction` entry closes a context that had reached + // at least that threshold, though the context can exceed it by the final + // iteration's output and tool results. + Iterations BetaIterationsUsage `json:"iterations" api:"required"` + // The number of output tokens which were used. + OutputTokens int64 `json:"output_tokens" api:"required"` + // Breakdown of output tokens by category. + // + // `output_tokens` remains the inclusive, authoritative total used for billing. + // This object provides a read-only decomposition for observability — for example, + // how many of the billed output tokens were spent on internal reasoning that may + // have been summarized before being returned to you. + OutputTokensDetails BetaOutputTokensDetails `json:"output_tokens_details" api:"required"` + // The number of server tool requests. + ServerToolUse BetaServerToolUsage `json:"server_tool_use" api:"required"` + // If the request used the priority, standard, or batch tier. + // + // Any of "standard", "priority", "batch". + ServiceTier BetaUsageServiceTier `json:"service_tier" api:"required"` + // Inference speed mode. `fast` provides significantly faster output token + // generation at premium pricing. Not all models support `fast`; invalid + // combinations are rejected at create time. + // + // Any of "standard", "fast". + Speed BetaUsageSpeed `json:"speed" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + CacheCreation respjson.Field + CacheCreationInputTokens respjson.Field + CacheReadInputTokens respjson.Field + FallbackCredit respjson.Field + InferenceGeo respjson.Field + InputTokens respjson.Field + Iterations respjson.Field + OutputTokens respjson.Field + OutputTokensDetails respjson.Field + ServerToolUse respjson.Field + ServiceTier respjson.Field + Speed respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaUsage) RawJSON() string { return r.JSON.raw } +func (r *BetaUsage) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// If the request used the priority, standard, or batch tier. +type BetaUsageServiceTier string + +const ( + BetaUsageServiceTierStandard BetaUsageServiceTier = "standard" + BetaUsageServiceTierPriority BetaUsageServiceTier = "priority" + BetaUsageServiceTierBatch BetaUsageServiceTier = "batch" +) + +// Inference speed mode. `fast` provides significantly faster output token +// generation at premium pricing. Not all models support `fast`; invalid +// combinations are rejected at create time. +type BetaUsageSpeed string + +const ( + BetaUsageSpeedStandard BetaUsageSpeed = "standard" + BetaUsageSpeedFast BetaUsageSpeed = "fast" +) + +// The property Type is required. +type BetaUserLocationParam struct { + // The city of the user. + City param.Opt[string] `json:"city,omitzero"` + // The two letter + // [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the + // user. + Country param.Opt[string] `json:"country,omitzero"` + // The region of the user. + Region param.Opt[string] `json:"region,omitzero"` + // The [IANA timezone](https://nodatime.org/TimeZones) of the user. + Timezone param.Opt[string] `json:"timezone,omitzero"` + // This field can be elided, and will marshal its zero value as "approximate". + Type constant.Approximate `json:"type" default:"approximate"` + paramObj +} + +func (r BetaUserLocationParam) MarshalJSON() (data []byte, err error) { + type shadow BetaUserLocationParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaUserLocationParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaWebFetchBlock struct { + Content BetaDocumentBlock `json:"content" api:"required"` + // ISO 8601 timestamp when the content was retrieved + RetrievedAt string `json:"retrieved_at" api:"required"` + Type constant.WebFetchResult `json:"type" default:"web_fetch_result"` + // Fetched content URL + URL string `json:"url" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Content respjson.Field + RetrievedAt respjson.Field + Type respjson.Field + URL respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaWebFetchBlock) RawJSON() string { return r.JSON.raw } +func (r *BetaWebFetchBlock) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The properties Content, Type, URL are required. +type BetaWebFetchBlockParam struct { + Content BetaRequestDocumentBlockParam `json:"content,omitzero" api:"required"` + // Fetched content URL + URL string `json:"url" api:"required"` + // ISO 8601 timestamp when the content was retrieved + RetrievedAt param.Opt[string] `json:"retrieved_at,omitzero"` + // This field can be elided, and will marshal its zero value as "web_fetch_result". + Type constant.WebFetchResult `json:"type" default:"web_fetch_result"` + paramObj +} + +func (r BetaWebFetchBlockParam) MarshalJSON() (data []byte, err error) { + type shadow BetaWebFetchBlockParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaWebFetchBlockParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The properties Name, Type are required. +type BetaWebFetchTool20250910Param struct { + // Maximum number of tokens used by including web page text content in the context. + // The limit is approximate and does not apply to binary content such as PDFs. + MaxContentTokens param.Opt[int64] `json:"max_content_tokens,omitzero"` + // Maximum number of times the tool can be used in the API request. + MaxUses param.Opt[int64] `json:"max_uses,omitzero"` + // If true, tool will not be included in initial system prompt. Only loaded when + // returned via tool_reference from tool search. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // When true, guarantees schema validation on tool names and inputs + Strict param.Opt[bool] `json:"strict,omitzero"` + // List of domains to allow fetching from + AllowedDomains []string `json:"allowed_domains,omitzero"` + // List of domains to block fetching from + BlockedDomains []string `json:"blocked_domains,omitzero"` + // Any of "direct", "code_execution_20250825", "code_execution_20260120", + // "code_execution_20260521". + AllowedCallers []string `json:"allowed_callers,omitzero"` + // Create a cache control breakpoint at this content block. + CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` + // Citations configuration for fetched documents. Citations are disabled by + // default. + Citations BetaCitationsConfigParam `json:"citations,omitzero"` + // Name of the tool. + // + // This is how the tool will be called by the model and in `tool_use` blocks. + // + // This field can be elided, and will marshal its zero value as "web_fetch". + Name constant.WebFetch `json:"name" default:"web_fetch"` + // This field can be elided, and will marshal its zero value as + // "web_fetch_20250910". + Type constant.WebFetch20250910 `json:"type" default:"web_fetch_20250910"` + paramObj +} + +func (r BetaWebFetchTool20250910Param) MarshalJSON() (data []byte, err error) { + type shadow BetaWebFetchTool20250910Param + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaWebFetchTool20250910Param) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The properties Name, Type are required. +type BetaWebFetchTool20260209Param struct { + // Maximum number of tokens used by including web page text content in the context. + // The limit is approximate and does not apply to binary content such as PDFs. + MaxContentTokens param.Opt[int64] `json:"max_content_tokens,omitzero"` + // Maximum number of times the tool can be used in the API request. + MaxUses param.Opt[int64] `json:"max_uses,omitzero"` + // If true, tool will not be included in initial system prompt. Only loaded when + // returned via tool_reference from tool search. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // When true, guarantees schema validation on tool names and inputs + Strict param.Opt[bool] `json:"strict,omitzero"` + // List of domains to allow fetching from + AllowedDomains []string `json:"allowed_domains,omitzero"` + // List of domains to block fetching from + BlockedDomains []string `json:"blocked_domains,omitzero"` + // Any of "direct", "code_execution_20250825", "code_execution_20260120", + // "code_execution_20260521". + AllowedCallers []string `json:"allowed_callers,omitzero"` + // Create a cache control breakpoint at this content block. + CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` + // Citations configuration for fetched documents. Citations are disabled by + // default. + Citations BetaCitationsConfigParam `json:"citations,omitzero"` + // Name of the tool. + // + // This is how the tool will be called by the model and in `tool_use` blocks. + // + // This field can be elided, and will marshal its zero value as "web_fetch". + Name constant.WebFetch `json:"name" default:"web_fetch"` + // This field can be elided, and will marshal its zero value as + // "web_fetch_20260209". + Type constant.WebFetch20260209 `json:"type" default:"web_fetch_20260209"` + paramObj +} + +func (r BetaWebFetchTool20260209Param) MarshalJSON() (data []byte, err error) { + type shadow BetaWebFetchTool20260209Param + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaWebFetchTool20260209Param) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Web fetch tool with use_cache parameter for bypassing cached content. +// +// The properties Name, Type are required. +type BetaWebFetchTool20260309Param struct { + // Maximum number of tokens used by including web page text content in the context. + // The limit is approximate and does not apply to binary content such as PDFs. + MaxContentTokens param.Opt[int64] `json:"max_content_tokens,omitzero"` + // Maximum number of times the tool can be used in the API request. + MaxUses param.Opt[int64] `json:"max_uses,omitzero"` + // If true, tool will not be included in initial system prompt. Only loaded when + // returned via tool_reference from tool search. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // When true, guarantees schema validation on tool names and inputs + Strict param.Opt[bool] `json:"strict,omitzero"` + // Whether to use cached content. Set to false to bypass the cache and fetch fresh + // content. Only set to false when the user explicitly requests fresh content or + // when fetching rapidly-changing sources. + UseCache param.Opt[bool] `json:"use_cache,omitzero"` + // List of domains to allow fetching from + AllowedDomains []string `json:"allowed_domains,omitzero"` + // List of domains to block fetching from + BlockedDomains []string `json:"blocked_domains,omitzero"` + // Any of "direct", "code_execution_20250825", "code_execution_20260120", + // "code_execution_20260521". + AllowedCallers []string `json:"allowed_callers,omitzero"` + // Create a cache control breakpoint at this content block. + CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` + // Citations configuration for fetched documents. Citations are disabled by + // default. + Citations BetaCitationsConfigParam `json:"citations,omitzero"` + // Name of the tool. + // + // This is how the tool will be called by the model and in `tool_use` blocks. + // + // This field can be elided, and will marshal its zero value as "web_fetch". + Name constant.WebFetch `json:"name" default:"web_fetch"` + // This field can be elided, and will marshal its zero value as + // "web_fetch_20260309". + Type constant.WebFetch20260309 `json:"type" default:"web_fetch_20260309"` + paramObj +} + +func (r BetaWebFetchTool20260309Param) MarshalJSON() (data []byte, err error) { + type shadow BetaWebFetchTool20260309Param + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaWebFetchTool20260309Param) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The properties Name, Type are required. +type BetaWebFetchTool20260318Param struct { + // Maximum number of tokens used by including web page text content in the context. + // The limit is approximate and does not apply to binary content such as PDFs. + MaxContentTokens param.Opt[int64] `json:"max_content_tokens,omitzero"` + // Maximum number of times the tool can be used in the API request. + MaxUses param.Opt[int64] `json:"max_uses,omitzero"` + // If true, tool will not be included in initial system prompt. Only loaded when + // returned via tool_reference from tool search. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // When true, guarantees schema validation on tool names and inputs + Strict param.Opt[bool] `json:"strict,omitzero"` + // Whether to use cached content. Set to false to bypass the cache and fetch fresh + // content. Only set to false when the user explicitly requests fresh content or + // when fetching rapidly-changing sources. + UseCache param.Opt[bool] `json:"use_cache,omitzero"` + // List of domains to allow fetching from + AllowedDomains []string `json:"allowed_domains,omitzero"` + // List of domains to block fetching from + BlockedDomains []string `json:"blocked_domains,omitzero"` + // Any of "direct", "code_execution_20250825", "code_execution_20260120", + // "code_execution_20260521". + AllowedCallers []string `json:"allowed_callers,omitzero"` + // Create a cache control breakpoint at this content block. + CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` + // Citations configuration for fetched documents. Citations are disabled by + // default. + Citations BetaCitationsConfigParam `json:"citations,omitzero"` + // How this tool's result blocks appear in the API response when the result was + // consumed by a completed code_execution call in the same turn. 'full' returns the + // complete content (default). 'excluded' drops the nested server_tool_use and + // result block pair entirely. Results from direct calls, or from code_execution + // calls that paused before completing, are always returned in full so they can be + // sent back on the next turn. + // + // Any of "full", "excluded". + ResponseInclusion BetaWebFetchTool20260318ResponseInclusion `json:"response_inclusion,omitzero"` + // Name of the tool. + // + // This is how the tool will be called by the model and in `tool_use` blocks. + // + // This field can be elided, and will marshal its zero value as "web_fetch". + Name constant.WebFetch `json:"name" default:"web_fetch"` + // This field can be elided, and will marshal its zero value as + // "web_fetch_20260318". + Type constant.WebFetch20260318 `json:"type" default:"web_fetch_20260318"` + paramObj +} + +func (r BetaWebFetchTool20260318Param) MarshalJSON() (data []byte, err error) { + type shadow BetaWebFetchTool20260318Param + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaWebFetchTool20260318Param) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// How this tool's result blocks appear in the API response when the result was +// consumed by a completed code_execution call in the same turn. 'full' returns the +// complete content (default). 'excluded' drops the nested server_tool_use and +// result block pair entirely. Results from direct calls, or from code_execution +// calls that paused before completing, are always returned in full so they can be +// sent back on the next turn. +type BetaWebFetchTool20260318ResponseInclusion string + +const ( + BetaWebFetchTool20260318ResponseInclusionFull BetaWebFetchTool20260318ResponseInclusion = "full" + BetaWebFetchTool20260318ResponseInclusionExcluded BetaWebFetchTool20260318ResponseInclusion = "excluded" +) + +type BetaWebFetchToolResultBlock struct { + Content BetaWebFetchToolResultBlockContentUnion `json:"content" api:"required"` + ToolUseID string `json:"tool_use_id" api:"required"` + Type constant.WebFetchToolResult `json:"type" default:"web_fetch_tool_result"` + // Tool invocation directly from the model. + Caller BetaWebFetchToolResultBlockCallerUnion `json:"caller"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Content respjson.Field + ToolUseID respjson.Field + Type respjson.Field + Caller respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaWebFetchToolResultBlock) RawJSON() string { return r.JSON.raw } +func (r *BetaWebFetchToolResultBlock) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaWebFetchToolResultBlockContentUnion contains all possible properties and +// values from [BetaWebFetchToolResultErrorBlock], [BetaWebFetchBlock]. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaWebFetchToolResultBlockContentUnion struct { + // This field is from variant [BetaWebFetchToolResultErrorBlock]. + ErrorCode BetaWebFetchToolResultErrorCode `json:"error_code"` + Type string `json:"type"` + // This field is from variant [BetaWebFetchBlock]. + Content BetaDocumentBlock `json:"content"` + // This field is from variant [BetaWebFetchBlock]. + RetrievedAt string `json:"retrieved_at"` + // This field is from variant [BetaWebFetchBlock]. + URL string `json:"url"` + JSON struct { + ErrorCode respjson.Field + Type respjson.Field + Content respjson.Field + RetrievedAt respjson.Field + URL respjson.Field + raw string + } `json:"-"` +} + +func (u BetaWebFetchToolResultBlockContentUnion) AsResponseWebFetchToolResultError() (v BetaWebFetchToolResultErrorBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaWebFetchToolResultBlockContentUnion) AsResponseWebFetchResultBlock() (v BetaWebFetchBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u BetaWebFetchToolResultBlockContentUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaWebFetchToolResultBlockContentUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaWebFetchToolResultBlockCallerUnion contains all possible properties and +// values from [BetaDirectCaller], [BetaServerToolCaller], +// [BetaServerToolCaller20260120]. +// +// Use the [BetaWebFetchToolResultBlockCallerUnion.AsAny] method to switch on the +// variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaWebFetchToolResultBlockCallerUnion struct { + // Any of "direct", "code_execution_20250825", "code_execution_20260120". + Type string `json:"type"` + ToolID string `json:"tool_id"` + JSON struct { + Type respjson.Field + ToolID respjson.Field + raw string + } `json:"-"` +} + +// anyBetaWebFetchToolResultBlockCaller is implemented by each variant of +// [BetaWebFetchToolResultBlockCallerUnion] to add type safety for the return type +// of [BetaWebFetchToolResultBlockCallerUnion.AsAny] +type anyBetaWebFetchToolResultBlockCaller interface { + implBetaWebFetchToolResultBlockCallerUnion() +} + +func (BetaDirectCaller) implBetaWebFetchToolResultBlockCallerUnion() {} +func (BetaServerToolCaller) implBetaWebFetchToolResultBlockCallerUnion() {} +func (BetaServerToolCaller20260120) implBetaWebFetchToolResultBlockCallerUnion() {} + +// Use the following switch statement to find the correct variant +// +// switch variant := BetaWebFetchToolResultBlockCallerUnion.AsAny().(type) { +// case anthropic.BetaDirectCaller: +// case anthropic.BetaServerToolCaller: +// case anthropic.BetaServerToolCaller20260120: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaWebFetchToolResultBlockCallerUnion) AsAny() anyBetaWebFetchToolResultBlockCaller { + switch u.Type { + case "direct": + return u.AsDirect() + case "code_execution_20250825": + return u.AsCodeExecution20250825() + case "code_execution_20260120": + return u.AsCodeExecution20260120() + } + return nil +} + +func (u BetaWebFetchToolResultBlockCallerUnion) AsDirect() (v BetaDirectCaller) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaWebFetchToolResultBlockCallerUnion) AsCodeExecution20250825() (v BetaServerToolCaller) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaWebFetchToolResultBlockCallerUnion) AsCodeExecution20260120() (v BetaServerToolCaller20260120) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u BetaWebFetchToolResultBlockCallerUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaWebFetchToolResultBlockCallerUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The properties Content, ToolUseID, Type are required. +type BetaWebFetchToolResultBlockParam struct { + Content BetaWebFetchToolResultBlockParamContentUnion `json:"content,omitzero" api:"required"` + ToolUseID string `json:"tool_use_id" api:"required"` + // Create a cache control breakpoint at this content block. + CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` + // Tool invocation directly from the model. + Caller BetaWebFetchToolResultBlockParamCallerUnion `json:"caller,omitzero"` + // This field can be elided, and will marshal its zero value as + // "web_fetch_tool_result". + Type constant.WebFetchToolResult `json:"type" default:"web_fetch_tool_result"` + paramObj +} + +func (r BetaWebFetchToolResultBlockParam) MarshalJSON() (data []byte, err error) { + type shadow BetaWebFetchToolResultBlockParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaWebFetchToolResultBlockParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaWebFetchToolResultBlockParamContentUnion struct { + OfRequestWebFetchToolResultError *BetaWebFetchToolResultErrorBlockParam `json:",omitzero,inline"` + OfRequestWebFetchResultBlock *BetaWebFetchBlockParam `json:",omitzero,inline"` + paramUnion +} + +func (u BetaWebFetchToolResultBlockParamContentUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfRequestWebFetchToolResultError, u.OfRequestWebFetchResultBlock) +} +func (u *BetaWebFetchToolResultBlockParamContentUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *BetaWebFetchToolResultBlockParamContentUnion) asAny() any { + if !param.IsOmitted(u.OfRequestWebFetchToolResultError) { + return u.OfRequestWebFetchToolResultError + } else if !param.IsOmitted(u.OfRequestWebFetchResultBlock) { + return u.OfRequestWebFetchResultBlock + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaWebFetchToolResultBlockParamContentUnion) GetErrorCode() *string { + if vt := u.OfRequestWebFetchToolResultError; vt != nil { + return (*string)(&vt.ErrorCode) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaWebFetchToolResultBlockParamContentUnion) GetContent() *BetaRequestDocumentBlockParam { + if vt := u.OfRequestWebFetchResultBlock; vt != nil { + return &vt.Content + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaWebFetchToolResultBlockParamContentUnion) GetURL() *string { + if vt := u.OfRequestWebFetchResultBlock; vt != nil { + return &vt.URL + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaWebFetchToolResultBlockParamContentUnion) GetRetrievedAt() *string { + if vt := u.OfRequestWebFetchResultBlock; vt != nil && vt.RetrievedAt.Valid() { + return &vt.RetrievedAt.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaWebFetchToolResultBlockParamContentUnion) GetType() *string { + if vt := u.OfRequestWebFetchToolResultError; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfRequestWebFetchResultBlock; vt != nil { + return (*string)(&vt.Type) + } + return nil +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaWebFetchToolResultBlockParamCallerUnion struct { + OfDirect *BetaDirectCallerParam `json:",omitzero,inline"` + OfCodeExecution20250825 *BetaServerToolCallerParam `json:",omitzero,inline"` + OfCodeExecution20260120 *BetaServerToolCaller20260120Param `json:",omitzero,inline"` + paramUnion +} + +func (u BetaWebFetchToolResultBlockParamCallerUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfDirect, u.OfCodeExecution20250825, u.OfCodeExecution20260120) +} +func (u *BetaWebFetchToolResultBlockParamCallerUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *BetaWebFetchToolResultBlockParamCallerUnion) asAny() any { + if !param.IsOmitted(u.OfDirect) { + return u.OfDirect + } else if !param.IsOmitted(u.OfCodeExecution20250825) { + return u.OfCodeExecution20250825 + } else if !param.IsOmitted(u.OfCodeExecution20260120) { + return u.OfCodeExecution20260120 + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaWebFetchToolResultBlockParamCallerUnion) GetType() *string { + if vt := u.OfDirect; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfCodeExecution20250825; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfCodeExecution20260120; vt != nil { + return (*string)(&vt.Type) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaWebFetchToolResultBlockParamCallerUnion) GetToolID() *string { + if vt := u.OfCodeExecution20250825; vt != nil { + return (*string)(&vt.ToolID) + } else if vt := u.OfCodeExecution20260120; vt != nil { + return (*string)(&vt.ToolID) + } + return nil +} + +func init() { + apijson.RegisterUnion[BetaWebFetchToolResultBlockParamCallerUnion]( + "type", + apijson.Discriminator[BetaDirectCallerParam]("direct"), + apijson.Discriminator[BetaServerToolCallerParam]("code_execution_20250825"), + apijson.Discriminator[BetaServerToolCaller20260120Param]("code_execution_20260120"), + ) +} + +type BetaWebFetchToolResultErrorBlock struct { + // Any of "invalid_tool_input", "url_too_long", "url_not_allowed", + // "url_not_in_prior_context", "url_not_accessible", "unsupported_content_type", + // "too_many_requests", "max_uses_exceeded", "unavailable". + ErrorCode BetaWebFetchToolResultErrorCode `json:"error_code" api:"required"` + Type constant.WebFetchToolResultError `json:"type" default:"web_fetch_tool_result_error"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ErrorCode respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaWebFetchToolResultErrorBlock) RawJSON() string { return r.JSON.raw } +func (r *BetaWebFetchToolResultErrorBlock) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The properties ErrorCode, Type are required. +type BetaWebFetchToolResultErrorBlockParam struct { + // Any of "invalid_tool_input", "url_too_long", "url_not_allowed", + // "url_not_in_prior_context", "url_not_accessible", "unsupported_content_type", + // "too_many_requests", "max_uses_exceeded", "unavailable". + ErrorCode BetaWebFetchToolResultErrorCode `json:"error_code,omitzero" api:"required"` + // This field can be elided, and will marshal its zero value as + // "web_fetch_tool_result_error". + Type constant.WebFetchToolResultError `json:"type" default:"web_fetch_tool_result_error"` + paramObj +} + +func (r BetaWebFetchToolResultErrorBlockParam) MarshalJSON() (data []byte, err error) { + type shadow BetaWebFetchToolResultErrorBlockParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaWebFetchToolResultErrorBlockParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaWebFetchToolResultErrorCode string + +const ( + BetaWebFetchToolResultErrorCodeInvalidToolInput BetaWebFetchToolResultErrorCode = "invalid_tool_input" + BetaWebFetchToolResultErrorCodeURLTooLong BetaWebFetchToolResultErrorCode = "url_too_long" + BetaWebFetchToolResultErrorCodeURLNotAllowed BetaWebFetchToolResultErrorCode = "url_not_allowed" + BetaWebFetchToolResultErrorCodeURLNotInPriorContext BetaWebFetchToolResultErrorCode = "url_not_in_prior_context" + BetaWebFetchToolResultErrorCodeURLNotAccessible BetaWebFetchToolResultErrorCode = "url_not_accessible" + BetaWebFetchToolResultErrorCodeUnsupportedContentType BetaWebFetchToolResultErrorCode = "unsupported_content_type" + BetaWebFetchToolResultErrorCodeTooManyRequests BetaWebFetchToolResultErrorCode = "too_many_requests" + BetaWebFetchToolResultErrorCodeMaxUsesExceeded BetaWebFetchToolResultErrorCode = "max_uses_exceeded" + BetaWebFetchToolResultErrorCodeUnavailable BetaWebFetchToolResultErrorCode = "unavailable" +) + +type BetaWebSearchResultBlock struct { + EncryptedContent string `json:"encrypted_content" api:"required"` + PageAge string `json:"page_age" api:"required"` + Title string `json:"title" api:"required"` + Type constant.WebSearchResult `json:"type" default:"web_search_result"` + URL string `json:"url" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + EncryptedContent respjson.Field + PageAge respjson.Field + Title respjson.Field + Type respjson.Field + URL respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaWebSearchResultBlock) RawJSON() string { return r.JSON.raw } +func (r *BetaWebSearchResultBlock) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The properties EncryptedContent, Title, Type, URL are required. +type BetaWebSearchResultBlockParam struct { + EncryptedContent string `json:"encrypted_content" api:"required"` + Title string `json:"title" api:"required"` + URL string `json:"url" api:"required"` + PageAge param.Opt[string] `json:"page_age,omitzero"` + // This field can be elided, and will marshal its zero value as + // "web_search_result". + Type constant.WebSearchResult `json:"type" default:"web_search_result"` + paramObj +} + +func (r BetaWebSearchResultBlockParam) MarshalJSON() (data []byte, err error) { + type shadow BetaWebSearchResultBlockParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaWebSearchResultBlockParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The properties Name, Type are required. +type BetaWebSearchTool20250305Param struct { + // Maximum number of times the tool can be used in the API request. + MaxUses param.Opt[int64] `json:"max_uses,omitzero"` + // If true, tool will not be included in initial system prompt. Only loaded when + // returned via tool_reference from tool search. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // When true, guarantees schema validation on tool names and inputs + Strict param.Opt[bool] `json:"strict,omitzero"` + // If provided, only these domains will be included in results. Cannot be used + // alongside `blocked_domains`. + AllowedDomains []string `json:"allowed_domains,omitzero"` + // If provided, these domains will never appear in results. Cannot be used + // alongside `allowed_domains`. + BlockedDomains []string `json:"blocked_domains,omitzero"` + // Any of "direct", "code_execution_20250825", "code_execution_20260120", + // "code_execution_20260521". + AllowedCallers []string `json:"allowed_callers,omitzero"` + // Create a cache control breakpoint at this content block. + CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` + // Parameters for the user's location. Used to provide more relevant search + // results. + UserLocation BetaUserLocationParam `json:"user_location,omitzero"` + // Name of the tool. + // + // This is how the tool will be called by the model and in `tool_use` blocks. + // + // This field can be elided, and will marshal its zero value as "web_search". + Name constant.WebSearch `json:"name" default:"web_search"` + // This field can be elided, and will marshal its zero value as + // "web_search_20250305". + Type constant.WebSearch20250305 `json:"type" default:"web_search_20250305"` + paramObj +} + +func (r BetaWebSearchTool20250305Param) MarshalJSON() (data []byte, err error) { + type shadow BetaWebSearchTool20250305Param + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaWebSearchTool20250305Param) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The properties Name, Type are required. +type BetaWebSearchTool20260209Param struct { + // Maximum number of times the tool can be used in the API request. + MaxUses param.Opt[int64] `json:"max_uses,omitzero"` + // If true, tool will not be included in initial system prompt. Only loaded when + // returned via tool_reference from tool search. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // When true, guarantees schema validation on tool names and inputs + Strict param.Opt[bool] `json:"strict,omitzero"` + // If provided, only these domains will be included in results. Cannot be used + // alongside `blocked_domains`. + AllowedDomains []string `json:"allowed_domains,omitzero"` + // If provided, these domains will never appear in results. Cannot be used + // alongside `allowed_domains`. + BlockedDomains []string `json:"blocked_domains,omitzero"` + // Any of "direct", "code_execution_20250825", "code_execution_20260120", + // "code_execution_20260521". + AllowedCallers []string `json:"allowed_callers,omitzero"` + // Create a cache control breakpoint at this content block. + CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` + // Parameters for the user's location. Used to provide more relevant search + // results. + UserLocation BetaUserLocationParam `json:"user_location,omitzero"` + // Name of the tool. + // + // This is how the tool will be called by the model and in `tool_use` blocks. + // + // This field can be elided, and will marshal its zero value as "web_search". + Name constant.WebSearch `json:"name" default:"web_search"` + // This field can be elided, and will marshal its zero value as + // "web_search_20260209". + Type constant.WebSearch20260209 `json:"type" default:"web_search_20260209"` + paramObj +} + +func (r BetaWebSearchTool20260209Param) MarshalJSON() (data []byte, err error) { + type shadow BetaWebSearchTool20260209Param + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaWebSearchTool20260209Param) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The properties Name, Type are required. +type BetaWebSearchTool20260318Param struct { + // Maximum number of times the tool can be used in the API request. + MaxUses param.Opt[int64] `json:"max_uses,omitzero"` + // If true, tool will not be included in initial system prompt. Only loaded when + // returned via tool_reference from tool search. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // When true, guarantees schema validation on tool names and inputs + Strict param.Opt[bool] `json:"strict,omitzero"` + // If provided, only these domains will be included in results. Cannot be used + // alongside `blocked_domains`. + AllowedDomains []string `json:"allowed_domains,omitzero"` + // If provided, these domains will never appear in results. Cannot be used + // alongside `allowed_domains`. + BlockedDomains []string `json:"blocked_domains,omitzero"` + // Any of "direct", "code_execution_20250825", "code_execution_20260120", + // "code_execution_20260521". + AllowedCallers []string `json:"allowed_callers,omitzero"` + // Create a cache control breakpoint at this content block. + CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` + // How this tool's result blocks appear in the API response when the result was + // consumed by a completed code_execution call in the same turn. 'full' returns the + // complete content (default). 'excluded' drops the nested server_tool_use and + // result block pair entirely. Results from direct calls, or from code_execution + // calls that paused before completing, are always returned in full so they can be + // sent back on the next turn. + // + // Any of "full", "excluded". + ResponseInclusion BetaWebSearchTool20260318ResponseInclusion `json:"response_inclusion,omitzero"` + // Parameters for the user's location. Used to provide more relevant search + // results. + UserLocation BetaUserLocationParam `json:"user_location,omitzero"` + // Name of the tool. + // + // This is how the tool will be called by the model and in `tool_use` blocks. + // + // This field can be elided, and will marshal its zero value as "web_search". + Name constant.WebSearch `json:"name" default:"web_search"` + // This field can be elided, and will marshal its zero value as + // "web_search_20260318". + Type constant.WebSearch20260318 `json:"type" default:"web_search_20260318"` + paramObj +} + +func (r BetaWebSearchTool20260318Param) MarshalJSON() (data []byte, err error) { + type shadow BetaWebSearchTool20260318Param + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaWebSearchTool20260318Param) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// How this tool's result blocks appear in the API response when the result was +// consumed by a completed code_execution call in the same turn. 'full' returns the +// complete content (default). 'excluded' drops the nested server_tool_use and +// result block pair entirely. Results from direct calls, or from code_execution +// calls that paused before completing, are always returned in full so they can be +// sent back on the next turn. +type BetaWebSearchTool20260318ResponseInclusion string + +const ( + BetaWebSearchTool20260318ResponseInclusionFull BetaWebSearchTool20260318ResponseInclusion = "full" + BetaWebSearchTool20260318ResponseInclusionExcluded BetaWebSearchTool20260318ResponseInclusion = "excluded" +) + +// The properties ErrorCode, Type are required. +type BetaWebSearchToolRequestErrorParam struct { + // Any of "invalid_tool_input", "unavailable", "max_uses_exceeded", + // "too_many_requests", "query_too_long", "request_too_large". + ErrorCode BetaWebSearchToolResultErrorCode `json:"error_code,omitzero" api:"required"` + // This field can be elided, and will marshal its zero value as + // "web_search_tool_result_error". + Type constant.WebSearchToolResultError `json:"type" default:"web_search_tool_result_error"` + paramObj +} + +func (r BetaWebSearchToolRequestErrorParam) MarshalJSON() (data []byte, err error) { + type shadow BetaWebSearchToolRequestErrorParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaWebSearchToolRequestErrorParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaWebSearchToolResultBlock struct { + Content BetaWebSearchToolResultBlockContentUnion `json:"content" api:"required"` + ToolUseID string `json:"tool_use_id" api:"required"` + Type constant.WebSearchToolResult `json:"type" default:"web_search_tool_result"` + // Tool invocation directly from the model. + Caller BetaWebSearchToolResultBlockCallerUnion `json:"caller"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Content respjson.Field + ToolUseID respjson.Field + Type respjson.Field + Caller respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaWebSearchToolResultBlock) RawJSON() string { return r.JSON.raw } +func (r *BetaWebSearchToolResultBlock) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaWebSearchToolResultBlockCallerUnion contains all possible properties and +// values from [BetaDirectCaller], [BetaServerToolCaller], +// [BetaServerToolCaller20260120]. +// +// Use the [BetaWebSearchToolResultBlockCallerUnion.AsAny] method to switch on the +// variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaWebSearchToolResultBlockCallerUnion struct { + // Any of "direct", "code_execution_20250825", "code_execution_20260120". + Type string `json:"type"` + ToolID string `json:"tool_id"` + JSON struct { + Type respjson.Field + ToolID respjson.Field + raw string + } `json:"-"` +} + +// anyBetaWebSearchToolResultBlockCaller is implemented by each variant of +// [BetaWebSearchToolResultBlockCallerUnion] to add type safety for the return type +// of [BetaWebSearchToolResultBlockCallerUnion.AsAny] +type anyBetaWebSearchToolResultBlockCaller interface { + implBetaWebSearchToolResultBlockCallerUnion() +} + +func (BetaDirectCaller) implBetaWebSearchToolResultBlockCallerUnion() {} +func (BetaServerToolCaller) implBetaWebSearchToolResultBlockCallerUnion() {} +func (BetaServerToolCaller20260120) implBetaWebSearchToolResultBlockCallerUnion() {} + +// Use the following switch statement to find the correct variant +// +// switch variant := BetaWebSearchToolResultBlockCallerUnion.AsAny().(type) { +// case anthropic.BetaDirectCaller: +// case anthropic.BetaServerToolCaller: +// case anthropic.BetaServerToolCaller20260120: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaWebSearchToolResultBlockCallerUnion) AsAny() anyBetaWebSearchToolResultBlockCaller { + switch u.Type { + case "direct": + return u.AsDirect() + case "code_execution_20250825": + return u.AsCodeExecution20250825() + case "code_execution_20260120": + return u.AsCodeExecution20260120() + } + return nil +} + +func (u BetaWebSearchToolResultBlockCallerUnion) AsDirect() (v BetaDirectCaller) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaWebSearchToolResultBlockCallerUnion) AsCodeExecution20250825() (v BetaServerToolCaller) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaWebSearchToolResultBlockCallerUnion) AsCodeExecution20260120() (v BetaServerToolCaller20260120) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u BetaWebSearchToolResultBlockCallerUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaWebSearchToolResultBlockCallerUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaWebSearchToolResultBlockContentUnion contains all possible properties and +// values from [BetaWebSearchToolResultError], [[]BetaWebSearchResultBlock]. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +// +// If the underlying value is not a json object, one of the following properties +// will be valid: OfBetaWebSearchResultBlockArray] +type BetaWebSearchToolResultBlockContentUnion struct { + // This field will be present if the value is a [[]BetaWebSearchResultBlock] + // instead of an object. + OfBetaWebSearchResultBlockArray []BetaWebSearchResultBlock `json:",inline"` + // This field is from variant [BetaWebSearchToolResultError]. + ErrorCode BetaWebSearchToolResultErrorCode `json:"error_code"` + // This field is from variant [BetaWebSearchToolResultError]. + Type constant.WebSearchToolResultError `json:"type"` + JSON struct { + OfBetaWebSearchResultBlockArray respjson.Field + ErrorCode respjson.Field + Type respjson.Field + raw string + } `json:"-"` +} + +func (u BetaWebSearchToolResultBlockContentUnion) AsResponseWebSearchToolResultError() (v BetaWebSearchToolResultError) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaWebSearchToolResultBlockContentUnion) AsBetaWebSearchResultBlockArray() (v []BetaWebSearchResultBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u BetaWebSearchToolResultBlockContentUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaWebSearchToolResultBlockContentUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The properties Content, ToolUseID, Type are required. +type BetaWebSearchToolResultBlockParam struct { + Content BetaWebSearchToolResultBlockParamContentUnion `json:"content,omitzero" api:"required"` + ToolUseID string `json:"tool_use_id" api:"required"` + // Create a cache control breakpoint at this content block. + CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` + // Tool invocation directly from the model. + Caller BetaWebSearchToolResultBlockParamCallerUnion `json:"caller,omitzero"` + // This field can be elided, and will marshal its zero value as + // "web_search_tool_result". + Type constant.WebSearchToolResult `json:"type" default:"web_search_tool_result"` + paramObj +} + +func (r BetaWebSearchToolResultBlockParam) MarshalJSON() (data []byte, err error) { + type shadow BetaWebSearchToolResultBlockParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaWebSearchToolResultBlockParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaWebSearchToolResultBlockParamCallerUnion struct { + OfDirect *BetaDirectCallerParam `json:",omitzero,inline"` + OfCodeExecution20250825 *BetaServerToolCallerParam `json:",omitzero,inline"` + OfCodeExecution20260120 *BetaServerToolCaller20260120Param `json:",omitzero,inline"` + paramUnion +} + +func (u BetaWebSearchToolResultBlockParamCallerUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfDirect, u.OfCodeExecution20250825, u.OfCodeExecution20260120) +} +func (u *BetaWebSearchToolResultBlockParamCallerUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *BetaWebSearchToolResultBlockParamCallerUnion) asAny() any { + if !param.IsOmitted(u.OfDirect) { + return u.OfDirect + } else if !param.IsOmitted(u.OfCodeExecution20250825) { + return u.OfCodeExecution20250825 + } else if !param.IsOmitted(u.OfCodeExecution20260120) { + return u.OfCodeExecution20260120 + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaWebSearchToolResultBlockParamCallerUnion) GetType() *string { + if vt := u.OfDirect; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfCodeExecution20250825; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfCodeExecution20260120; vt != nil { + return (*string)(&vt.Type) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaWebSearchToolResultBlockParamCallerUnion) GetToolID() *string { + if vt := u.OfCodeExecution20250825; vt != nil { + return (*string)(&vt.ToolID) + } else if vt := u.OfCodeExecution20260120; vt != nil { + return (*string)(&vt.ToolID) + } + return nil +} + +func init() { + apijson.RegisterUnion[BetaWebSearchToolResultBlockParamCallerUnion]( + "type", + apijson.Discriminator[BetaDirectCallerParam]("direct"), + apijson.Discriminator[BetaServerToolCallerParam]("code_execution_20250825"), + apijson.Discriminator[BetaServerToolCaller20260120Param]("code_execution_20260120"), + ) +} + +func BetaNewWebSearchToolRequestError(errorCode BetaWebSearchToolResultErrorCode) BetaWebSearchToolResultBlockParamContentUnion { + var variant BetaWebSearchToolRequestErrorParam + variant.ErrorCode = errorCode + return BetaWebSearchToolResultBlockParamContentUnion{OfError: &variant} +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaWebSearchToolResultBlockParamContentUnion struct { + OfResultBlock []BetaWebSearchResultBlockParam `json:",omitzero,inline"` + OfError *BetaWebSearchToolRequestErrorParam `json:",omitzero,inline"` + paramUnion +} + +func (u BetaWebSearchToolResultBlockParamContentUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfResultBlock, u.OfError) +} +func (u *BetaWebSearchToolResultBlockParamContentUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *BetaWebSearchToolResultBlockParamContentUnion) asAny() any { + if !param.IsOmitted(u.OfResultBlock) { + return &u.OfResultBlock + } else if !param.IsOmitted(u.OfError) { + return u.OfError + } + return nil +} + +type BetaWebSearchToolResultError struct { + // Any of "invalid_tool_input", "unavailable", "max_uses_exceeded", + // "too_many_requests", "query_too_long", "request_too_large". + ErrorCode BetaWebSearchToolResultErrorCode `json:"error_code" api:"required"` + Type constant.WebSearchToolResultError `json:"type" default:"web_search_tool_result_error"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ErrorCode respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaWebSearchToolResultError) RawJSON() string { return r.JSON.raw } +func (r *BetaWebSearchToolResultError) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaWebSearchToolResultErrorCode string + +const ( + BetaWebSearchToolResultErrorCodeInvalidToolInput BetaWebSearchToolResultErrorCode = "invalid_tool_input" + BetaWebSearchToolResultErrorCodeUnavailable BetaWebSearchToolResultErrorCode = "unavailable" + BetaWebSearchToolResultErrorCodeMaxUsesExceeded BetaWebSearchToolResultErrorCode = "max_uses_exceeded" + BetaWebSearchToolResultErrorCodeTooManyRequests BetaWebSearchToolResultErrorCode = "too_many_requests" + BetaWebSearchToolResultErrorCodeQueryTooLong BetaWebSearchToolResultErrorCode = "query_too_long" + BetaWebSearchToolResultErrorCodeRequestTooLarge BetaWebSearchToolResultErrorCode = "request_too_large" +) + +type BetaMessageNewParams struct { + // The maximum number of tokens to generate before stopping. + // + // Note that our models may stop _before_ reaching this maximum. This parameter + // only specifies the absolute maximum number of tokens to generate. + // + // Set to `0` to populate the + // [prompt cache](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#pre-warming-the-cache) + // without generating a response. + // + // Different models have different maximum values for this parameter. See + // [models](https://platform.claude.com/docs/en/about-claude/models/overview) for + // details. + MaxTokens int64 `json:"max_tokens" api:"required"` + // Input messages. + // + // Our models are trained to operate on alternating `user` and `assistant` + // conversational turns. When creating a new `Message`, you specify the prior + // conversational turns with the `messages` parameter, and the model then generates + // the next `Message` in the conversation. Consecutive `user` or `assistant` turns + // in your request will be combined into a single turn. + // + // Each input message must be an object with a `role` and `content`. You can + // specify a single `user`-role message, or you can include multiple `user` and + // `assistant` messages. + // + // If the final message uses the `assistant` role, the response content will + // continue immediately from the content in that message. This can be used to + // constrain part of the model's response. + // + // Example with a single `user` message: + // + // ```json + // [{ "role": "user", "content": "Hello, Claude" }] + // ``` + // + // Example with multiple conversational turns: + // + // ```json + // [ + // + // { "role": "user", "content": "Hello there." }, + // { "role": "assistant", "content": "Hi, I'm Claude. How can I help you?" }, + // { "role": "user", "content": "Can you explain LLMs in plain English?" } + // + // ] + // ``` + // + // Example with a partially-filled response from Claude: + // + // ```json + // [ + // + // { + // "role": "user", + // "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun" + // }, + // { "role": "assistant", "content": "The best answer is (" } + // + // ] + // ``` + // + // Each input message `content` may be either a single `string` or an array of + // content blocks, where each block has a specific `type`. Using a `string` for + // `content` is shorthand for an array of one content block of type `"text"`. The + // following input messages are equivalent: + // + // ```json + // { "role": "user", "content": "Hello, Claude" } + // ``` + // + // ```json + // { "role": "user", "content": [{ "type": "text", "text": "Hello, Claude" }] } + // ``` + // + // See + // [input examples](https://platform.claude.com/docs/en/build-with-claude/working-with-messages). + // + // Note that if you want to include a + // [system prompt](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#give-claude-a-role), + // you can use the top-level `system` parameter — there is no `"system"` role for + // input messages in the Messages API. + // + // There is a limit of 100,000 messages in a single request. + Messages []BetaMessageParam `json:"messages,omitzero" api:"required"` + // The model that will complete your prompt. + // + // See [models](https://docs.anthropic.com/en/docs/models-overview) for additional + // details and options. + Model Model `json:"model,omitzero" api:"required"` + // Specifies the geographic region for inference processing. If not specified, the + // workspace's `default_inference_geo` is used. + InferenceGeo param.Opt[string] `json:"inference_geo,omitzero"` + // Amount of randomness injected into the response. + // + // Defaults to `1.0`. Ranges from `0.0` to `1.0`. Use `temperature` closer to `0.0` + // for analytical / multiple choice, and closer to `1.0` for creative and + // generative tasks. + // + // Note that even with `temperature` of `0.0`, the results will not be fully + // deterministic. + Temperature param.Opt[float64] `json:"temperature,omitzero"` + // Only sample from the top K options for each subsequent token. + // + // Used to remove "long tail" low probability responses. + // [Learn more technical details here](https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277). + // + // Recommended for advanced use cases only. + TopK param.Opt[int64] `json:"top_k,omitzero"` + // Use nucleus sampling. + // + // In nucleus sampling, we compute the cumulative distribution over all the options + // for each subsequent token in decreasing probability order and cut it off once it + // reaches a particular probability specified by `top_p`. + // + // Recommended for advanced use cases only. + TopP param.Opt[float64] `json:"top_p,omitzero"` + // The user profile ID to attribute this request to. Use when acting on behalf of a + // party other than your organization. Requires the `user-profiles` beta header. + UserProfileID param.Opt[string] `header:"anthropic-user-profile-id,omitzero" json:"-"` + // Container identifier for reuse across requests. + Container BetaMessageNewParamsContainerUnion `json:"container,omitzero"` + // The `fallback_credit_token` from a prior refusal's `stop_details`. + // + // When a preceding request was refused and returned a `fallback_credit_token`, + // pass that code here on the retry to have the retry's cache-creation tokens for + // the prefix that was warm on the refused model billed at the cache-read rate. + // Must be redeemed by the same organization and workspace, with the same request + // body (optionally extended by one appended `assistant` message whose content is + // the partial text — with any trailing whitespace stripped from the final text + // block — and paired server-tool blocks streamed before the refusal; the + // appended-assistant form is not available for requests with `output_format` set + // or forced `tool_choice`), on an eligible fallback model, on the same platform, + // and within 5 minutes of the refusal; a mismatch is a 400. A token minted + // mid-server-tool-loop whose partial content was continuable may only be redeemed + // with the appended-assistant form — if an exact-body retry is rejected with a 400 + // saying the token must be redeemed by continuing the partial response, retry with + // the appended-assistant form instead. + // + // When the appended-assistant form is used on a model that otherwise disallows + // assistant-turn prefill, this token also authorizes that one prefill. + FallbackCreditToken BetaMessageNewParamsFallbackCreditTokenUnion `json:"fallback_credit_token,omitzero"` + // Opt-in server-side retry on one or more substitute models when the requested + // model declines for policy reasons. Tried in order: if the first entry also + // declines, the second is tried, and so on. The string "default" requests the + // requested model's server-defined default fallback configuration. + Fallbacks BetaFallbacksParamUnion `json:"fallbacks,omitzero"` + // Inference speed mode. `fast` provides significantly faster output token + // generation at premium pricing. Not all models support `fast`; invalid + // combinations are rejected at create time. + // + // Any of "standard", "fast". + Speed BetaMessageNewParamsSpeed `json:"speed,omitzero"` + // Top-level cache control automatically applies a cache_control marker to the last + // cacheable block in the request. + CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` + // Context management configuration. + // + // This allows you to control how Claude manages context across multiple requests, + // such as whether to clear function results or not. + ContextManagement BetaContextManagementConfigParam `json:"context_management,omitzero"` + // Request-level diagnostics. Currently carries the previous response id for + // prompt-cache divergence reporting. + Diagnostics BetaDiagnosticsParam `json:"diagnostics,omitzero"` + // MCP servers to be utilized in this request + MCPServers []BetaRequestMCPServerURLDefinitionParam `json:"mcp_servers,omitzero"` + // An object describing metadata about the request. + Metadata BetaMetadataParam `json:"metadata,omitzero"` + // Configuration options for the model's output, such as the output format. + OutputConfig BetaOutputConfigParam `json:"output_config,omitzero"` + // Deprecated: Use `output_config.format` instead. See + // [structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs) + // + // A schema to specify Claude's output format in responses. This parameter will be + // removed in a future release. + OutputFormat BetaJSONOutputFormatParam `json:"output_format,omitzero"` + // Determines whether to use priority capacity (if available) or standard capacity + // for this request. + // + // Anthropic offers different levels of service for your API requests. See + // [service-tiers](https://platform.claude.com/docs/en/api/service-tiers) for + // details. + // + // Any of "auto", "standard_only". + ServiceTier BetaMessageNewParamsServiceTier `json:"service_tier,omitzero"` + // Custom text sequences that will cause the model to stop generating. + // + // Our models will normally stop when they have naturally completed their turn, + // which will result in a response `stop_reason` of `"end_turn"`. + // + // If you want the model to stop generating when it encounters custom strings of + // text, you can use the `stop_sequences` parameter. If the model encounters one of + // the custom sequences, the response `stop_reason` value will be `"stop_sequence"` + // and the response `stop_sequence` value will contain the matched stop sequence. + StopSequences []string `json:"stop_sequences,omitzero"` + // System prompt. + // + // A system prompt is a way of providing context and instructions to Claude, such + // as specifying a particular goal or role. See our + // [guide to system prompts](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#give-claude-a-role). + System []BetaTextBlockParam `json:"system,omitzero"` + // Configuration for enabling Claude's extended thinking. + // + // When enabled, responses include `thinking` content blocks showing Claude's + // thinking process before the final answer. Requires a minimum budget of 1,024 + // tokens and counts towards your `max_tokens` limit. + // + // See + // [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking) + // for details. + Thinking BetaThinkingConfigParamUnion `json:"thinking,omitzero"` + // How the model should use the provided tools. The model can use a specific tool, + // any available tool, decide by itself, or not use tools at all. + ToolChoice BetaToolChoiceUnionParam `json:"tool_choice,omitzero"` + // Definitions of tools that the model may use. + // + // If you include `tools` in your API request, the model may return `tool_use` + // content blocks that represent the model's use of those tools. You can then run + // those tools using the tool input generated by the model and then optionally + // return results back to the model using `tool_result` content blocks. + // + // There are two types of tools: **client tools** and **server tools**. The + // behavior described below applies to client tools. For + // [server tools](https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools), + // see their individual documentation as each has its own behavior (e.g., the + // [web search tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool)). + // + // Each tool definition includes: + // + // - `name`: Name of the tool. + // - `description`: Optional, but strongly-recommended description of the tool. + // - `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the + // tool `input` shape that the model will produce in `tool_use` output content + // blocks. + // + // For example, if you defined `tools` as: + // + // ```json + // [ + // + // { + // "name": "get_stock_price", + // "description": "Get the current stock price for a given ticker symbol.", + // "input_schema": { + // "type": "object", + // "properties": { + // "ticker": { + // "type": "string", + // "description": "The stock ticker symbol, e.g. AAPL for Apple Inc." + // } + // }, + // "required": ["ticker"] + // } + // } + // + // ] + // ``` + // + // And then asked the model "What's the S&P 500 at today?", the model might produce + // `tool_use` content blocks in the response like this: + // + // ```json + // [ + // + // { + // "type": "tool_use", + // "id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV", + // "name": "get_stock_price", + // "input": { "ticker": "^GSPC" } + // } + // + // ] + // ``` + // + // You might then run your `get_stock_price` tool with `{"ticker": "^GSPC"}` as an + // input, and return the following back to the model in a subsequent `user` + // message: + // + // ```json + // [ + // + // { + // "type": "tool_result", + // "tool_use_id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV", + // "content": "259.75 USD" + // } + // + // ] + // ``` + // + // Tools can be used for workflows that include running client-side tools and + // functions, or more generally whenever you want the model to produce a particular + // JSON structure of output. + // + // See our + // [guide](https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview) + // for more details. + Tools []BetaToolUnionParam `json:"tools,omitzero"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +func (r BetaMessageNewParams) MarshalJSON() (data []byte, err error) { + type shadow BetaMessageNewParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaMessageNewParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaMessageNewParamsContainerUnion struct { + OfContainers *BetaContainerParams `json:",omitzero,inline"` + OfString param.Opt[string] `json:",omitzero,inline"` + paramUnion +} + +func (u BetaMessageNewParamsContainerUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfContainers, u.OfString) +} +func (u *BetaMessageNewParamsContainerUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *BetaMessageNewParamsContainerUnion) asAny() any { + if !param.IsOmitted(u.OfContainers) { + return u.OfContainers + } else if !param.IsOmitted(u.OfString) { + return &u.OfString.Value + } + return nil +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaMessageNewParamsFallbackCreditTokenUnion struct { + OfString param.Opt[string] `json:",omitzero,inline"` + OfFallbackCreditToken *BetaFallbackCreditTokenParam `json:",omitzero,inline"` + paramUnion +} + +func (u BetaMessageNewParamsFallbackCreditTokenUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfString, u.OfFallbackCreditToken) +} +func (u *BetaMessageNewParamsFallbackCreditTokenUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *BetaMessageNewParamsFallbackCreditTokenUnion) asAny() any { + if !param.IsOmitted(u.OfString) { + return &u.OfString.Value + } else if !param.IsOmitted(u.OfFallbackCreditToken) { + return u.OfFallbackCreditToken + } + return nil +} + +// Determines whether to use priority capacity (if available) or standard capacity +// for this request. +// +// Anthropic offers different levels of service for your API requests. See +// [service-tiers](https://platform.claude.com/docs/en/api/service-tiers) for +// details. +type BetaMessageNewParamsServiceTier string + +const ( + BetaMessageNewParamsServiceTierAuto BetaMessageNewParamsServiceTier = "auto" + BetaMessageNewParamsServiceTierStandardOnly BetaMessageNewParamsServiceTier = "standard_only" +) + +// Inference speed mode. `fast` provides significantly faster output token +// generation at premium pricing. Not all models support `fast`; invalid +// combinations are rejected at create time. +type BetaMessageNewParamsSpeed string + +const ( + BetaMessageNewParamsSpeedStandard BetaMessageNewParamsSpeed = "standard" + BetaMessageNewParamsSpeedFast BetaMessageNewParamsSpeed = "fast" +) + +type BetaMessageCountTokensParams struct { + // Input messages. + // + // Our models are trained to operate on alternating `user` and `assistant` + // conversational turns. When creating a new `Message`, you specify the prior + // conversational turns with the `messages` parameter, and the model then generates + // the next `Message` in the conversation. Consecutive `user` or `assistant` turns + // in your request will be combined into a single turn. + // + // Each input message must be an object with a `role` and `content`. You can + // specify a single `user`-role message, or you can include multiple `user` and + // `assistant` messages. + // + // If the final message uses the `assistant` role, the response content will + // continue immediately from the content in that message. This can be used to + // constrain part of the model's response. + // + // Example with a single `user` message: + // + // ```json + // [{ "role": "user", "content": "Hello, Claude" }] + // ``` + // + // Example with multiple conversational turns: + // + // ```json + // [ + // + // { "role": "user", "content": "Hello there." }, + // { "role": "assistant", "content": "Hi, I'm Claude. How can I help you?" }, + // { "role": "user", "content": "Can you explain LLMs in plain English?" } + // + // ] + // ``` + // + // Example with a partially-filled response from Claude: + // + // ```json + // [ + // + // { + // "role": "user", + // "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun" + // }, + // { "role": "assistant", "content": "The best answer is (" } + // + // ] + // ``` + // + // Each input message `content` may be either a single `string` or an array of + // content blocks, where each block has a specific `type`. Using a `string` for + // `content` is shorthand for an array of one content block of type `"text"`. The + // following input messages are equivalent: + // + // ```json + // { "role": "user", "content": "Hello, Claude" } + // ``` + // + // ```json + // { "role": "user", "content": [{ "type": "text", "text": "Hello, Claude" }] } + // ``` + // + // See + // [input examples](https://platform.claude.com/docs/en/build-with-claude/working-with-messages). + // + // Note that if you want to include a + // [system prompt](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#give-claude-a-role), + // you can use the top-level `system` parameter — there is no `"system"` role for + // input messages in the Messages API. + // + // There is a limit of 100,000 messages in a single request. + Messages []BetaMessageParam `json:"messages,omitzero" api:"required"` + // The model that will complete your prompt. + // + // See [models](https://docs.anthropic.com/en/docs/models-overview) for additional + // details and options. + Model Model `json:"model,omitzero" api:"required"` + // The user profile ID to attribute this request to. Use when acting on behalf of a + // party other than your organization. Requires the `user-profiles` beta header. + UserProfileID param.Opt[string] `header:"anthropic-user-profile-id,omitzero" json:"-"` + // Inference speed mode. `fast` provides significantly faster output token + // generation at premium pricing. Not all models support `fast`; invalid + // combinations are rejected at create time. + // + // Any of "standard", "fast". + Speed BetaMessageCountTokensParamsSpeed `json:"speed,omitzero"` + // Top-level cache control automatically applies a cache_control marker to the last + // cacheable block in the request. + CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` + // Context management configuration. + // + // This allows you to control how Claude manages context across multiple requests, + // such as whether to clear function results or not. + ContextManagement BetaContextManagementConfigParam `json:"context_management,omitzero"` + // MCP servers to be utilized in this request + MCPServers []BetaRequestMCPServerURLDefinitionParam `json:"mcp_servers,omitzero"` + // Configuration options for the model's output, such as the output format. + OutputConfig BetaOutputConfigParam `json:"output_config,omitzero"` + // Deprecated: Use `output_config.format` instead. See + // [structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs) + // + // A schema to specify Claude's output format in responses. This parameter will be + // removed in a future release. + OutputFormat BetaJSONOutputFormatParam `json:"output_format,omitzero"` + // System prompt. + // + // A system prompt is a way of providing context and instructions to Claude, such + // as specifying a particular goal or role. See our + // [guide to system prompts](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#give-claude-a-role). + System BetaMessageCountTokensParamsSystemUnion `json:"system,omitzero"` + // Configuration for enabling Claude's extended thinking. + // + // When enabled, responses include `thinking` content blocks showing Claude's + // thinking process before the final answer. Requires a minimum budget of 1,024 + // tokens and counts towards your `max_tokens` limit. + // + // See + // [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking) + // for details. + Thinking BetaThinkingConfigParamUnion `json:"thinking,omitzero"` + // How the model should use the provided tools. The model can use a specific tool, + // any available tool, decide by itself, or not use tools at all. + ToolChoice BetaToolChoiceUnionParam `json:"tool_choice,omitzero"` + // Definitions of tools that the model may use. + // + // If you include `tools` in your API request, the model may return `tool_use` + // content blocks that represent the model's use of those tools. You can then run + // those tools using the tool input generated by the model and then optionally + // return results back to the model using `tool_result` content blocks. + // + // There are two types of tools: **client tools** and **server tools**. The + // behavior described below applies to client tools. For + // [server tools](https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools), + // see their individual documentation as each has its own behavior (e.g., the + // [web search tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool)). + // + // Each tool definition includes: + // + // - `name`: Name of the tool. + // - `description`: Optional, but strongly-recommended description of the tool. + // - `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the + // tool `input` shape that the model will produce in `tool_use` output content + // blocks. + // + // For example, if you defined `tools` as: + // + // ```json + // [ + // + // { + // "name": "get_stock_price", + // "description": "Get the current stock price for a given ticker symbol.", + // "input_schema": { + // "type": "object", + // "properties": { + // "ticker": { + // "type": "string", + // "description": "The stock ticker symbol, e.g. AAPL for Apple Inc." + // } + // }, + // "required": ["ticker"] + // } + // } + // + // ] + // ``` + // + // And then asked the model "What's the S&P 500 at today?", the model might produce + // `tool_use` content blocks in the response like this: + // + // ```json + // [ + // + // { + // "type": "tool_use", + // "id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV", + // "name": "get_stock_price", + // "input": { "ticker": "^GSPC" } + // } + // + // ] + // ``` + // + // You might then run your `get_stock_price` tool with `{"ticker": "^GSPC"}` as an + // input, and return the following back to the model in a subsequent `user` + // message: + // + // ```json + // [ + // + // { + // "type": "tool_result", + // "tool_use_id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV", + // "content": "259.75 USD" + // } + // + // ] + // ``` + // + // Tools can be used for workflows that include running client-side tools and + // functions, or more generally whenever you want the model to produce a particular + // JSON structure of output. + // + // See our + // [guide](https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview) + // for more details. + Tools []BetaMessageCountTokensParamsToolUnion `json:"tools,omitzero"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +func (r BetaMessageCountTokensParams) MarshalJSON() (data []byte, err error) { + type shadow BetaMessageCountTokensParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaMessageCountTokensParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Inference speed mode. `fast` provides significantly faster output token +// generation at premium pricing. Not all models support `fast`; invalid +// combinations are rejected at create time. +type BetaMessageCountTokensParamsSpeed string + +const ( + BetaMessageCountTokensParamsSpeedStandard BetaMessageCountTokensParamsSpeed = "standard" + BetaMessageCountTokensParamsSpeedFast BetaMessageCountTokensParamsSpeed = "fast" +) + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaMessageCountTokensParamsSystemUnion struct { + OfString param.Opt[string] `json:",omitzero,inline"` + OfBetaTextBlockArray []BetaTextBlockParam `json:",omitzero,inline"` + paramUnion +} + +func (u BetaMessageCountTokensParamsSystemUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfString, u.OfBetaTextBlockArray) +} +func (u *BetaMessageCountTokensParamsSystemUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *BetaMessageCountTokensParamsSystemUnion) asAny() any { + if !param.IsOmitted(u.OfString) { + return &u.OfString.Value + } else if !param.IsOmitted(u.OfBetaTextBlockArray) { + return &u.OfBetaTextBlockArray + } + return nil +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaMessageCountTokensParamsToolUnion struct { + OfTool *BetaToolParam `json:",omitzero,inline"` + OfBashTool20241022 *BetaToolBash20241022Param `json:",omitzero,inline"` + OfBashTool20250124 *BetaToolBash20250124Param `json:",omitzero,inline"` + OfCodeExecutionTool20250522 *BetaCodeExecutionTool20250522Param `json:",omitzero,inline"` + OfCodeExecutionTool20250825 *BetaCodeExecutionTool20250825Param `json:",omitzero,inline"` + OfCodeExecutionTool20260120 *BetaCodeExecutionTool20260120Param `json:",omitzero,inline"` + OfCodeExecutionTool20260521 *BetaCodeExecutionTool20260521Param `json:",omitzero,inline"` + OfBrowserToolset20260801 *BetaBrowserToolset20260801Param `json:",omitzero,inline"` + OfComputerUseTool20241022 *BetaToolComputerUse20241022Param `json:",omitzero,inline"` + OfMemoryTool20250818 *BetaMemoryTool20250818Param `json:",omitzero,inline"` + OfComputerUseTool20250124 *BetaToolComputerUse20250124Param `json:",omitzero,inline"` + OfTextEditor20241022 *BetaToolTextEditor20241022Param `json:",omitzero,inline"` + OfComputerUseTool20251124 *BetaToolComputerUse20251124Param `json:",omitzero,inline"` + OfComputerToolset20260801 *BetaComputerToolset20260801Param `json:",omitzero,inline"` + OfTextEditor20250124 *BetaToolTextEditor20250124Param `json:",omitzero,inline"` + OfTextEditor20250429 *BetaToolTextEditor20250429Param `json:",omitzero,inline"` + OfTextEditor20250728 *BetaToolTextEditor20250728Param `json:",omitzero,inline"` + OfWebSearchTool20250305 *BetaWebSearchTool20250305Param `json:",omitzero,inline"` + OfWebFetchTool20250910 *BetaWebFetchTool20250910Param `json:",omitzero,inline"` + OfWebSearchTool20260209 *BetaWebSearchTool20260209Param `json:",omitzero,inline"` + OfWebFetchTool20260209 *BetaWebFetchTool20260209Param `json:",omitzero,inline"` + OfWebFetchTool20260309 *BetaWebFetchTool20260309Param `json:",omitzero,inline"` + OfWebSearchTool20260318 *BetaWebSearchTool20260318Param `json:",omitzero,inline"` + OfWebFetchTool20260318 *BetaWebFetchTool20260318Param `json:",omitzero,inline"` + OfAdvisorTool20260301 *BetaAdvisorTool20260301Param `json:",omitzero,inline"` + OfToolSearchToolBm25_20251119 *BetaToolSearchToolBm25_20251119Param `json:",omitzero,inline"` + OfToolSearchToolRegex20251119 *BetaToolSearchToolRegex20251119Param `json:",omitzero,inline"` + OfMCPToolset *BetaMCPToolsetParam `json:",omitzero,inline"` + paramUnion +} + +func (u BetaMessageCountTokensParamsToolUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfTool, + u.OfBashTool20241022, + u.OfBashTool20250124, + u.OfCodeExecutionTool20250522, + u.OfCodeExecutionTool20250825, + u.OfCodeExecutionTool20260120, + u.OfCodeExecutionTool20260521, + u.OfBrowserToolset20260801, + u.OfComputerUseTool20241022, + u.OfMemoryTool20250818, + u.OfComputerUseTool20250124, + u.OfTextEditor20241022, + u.OfComputerUseTool20251124, + u.OfComputerToolset20260801, + u.OfTextEditor20250124, + u.OfTextEditor20250429, + u.OfTextEditor20250728, + u.OfWebSearchTool20250305, + u.OfWebFetchTool20250910, + u.OfWebSearchTool20260209, + u.OfWebFetchTool20260209, + u.OfWebFetchTool20260309, + u.OfWebSearchTool20260318, + u.OfWebFetchTool20260318, + u.OfAdvisorTool20260301, + u.OfToolSearchToolBm25_20251119, + u.OfToolSearchToolRegex20251119, + u.OfMCPToolset) +} +func (u *BetaMessageCountTokensParamsToolUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *BetaMessageCountTokensParamsToolUnion) asAny() any { + if !param.IsOmitted(u.OfTool) { + return u.OfTool + } else if !param.IsOmitted(u.OfBashTool20241022) { + return u.OfBashTool20241022 + } else if !param.IsOmitted(u.OfBashTool20250124) { + return u.OfBashTool20250124 + } else if !param.IsOmitted(u.OfCodeExecutionTool20250522) { + return u.OfCodeExecutionTool20250522 + } else if !param.IsOmitted(u.OfCodeExecutionTool20250825) { + return u.OfCodeExecutionTool20250825 + } else if !param.IsOmitted(u.OfCodeExecutionTool20260120) { + return u.OfCodeExecutionTool20260120 + } else if !param.IsOmitted(u.OfCodeExecutionTool20260521) { + return u.OfCodeExecutionTool20260521 + } else if !param.IsOmitted(u.OfBrowserToolset20260801) { + return u.OfBrowserToolset20260801 + } else if !param.IsOmitted(u.OfComputerUseTool20241022) { + return u.OfComputerUseTool20241022 + } else if !param.IsOmitted(u.OfMemoryTool20250818) { + return u.OfMemoryTool20250818 + } else if !param.IsOmitted(u.OfComputerUseTool20250124) { + return u.OfComputerUseTool20250124 + } else if !param.IsOmitted(u.OfTextEditor20241022) { + return u.OfTextEditor20241022 + } else if !param.IsOmitted(u.OfComputerUseTool20251124) { + return u.OfComputerUseTool20251124 + } else if !param.IsOmitted(u.OfComputerToolset20260801) { + return u.OfComputerToolset20260801 + } else if !param.IsOmitted(u.OfTextEditor20250124) { + return u.OfTextEditor20250124 + } else if !param.IsOmitted(u.OfTextEditor20250429) { + return u.OfTextEditor20250429 + } else if !param.IsOmitted(u.OfTextEditor20250728) { + return u.OfTextEditor20250728 + } else if !param.IsOmitted(u.OfWebSearchTool20250305) { + return u.OfWebSearchTool20250305 + } else if !param.IsOmitted(u.OfWebFetchTool20250910) { + return u.OfWebFetchTool20250910 + } else if !param.IsOmitted(u.OfWebSearchTool20260209) { + return u.OfWebSearchTool20260209 + } else if !param.IsOmitted(u.OfWebFetchTool20260209) { + return u.OfWebFetchTool20260209 + } else if !param.IsOmitted(u.OfWebFetchTool20260309) { + return u.OfWebFetchTool20260309 + } else if !param.IsOmitted(u.OfWebSearchTool20260318) { + return u.OfWebSearchTool20260318 + } else if !param.IsOmitted(u.OfWebFetchTool20260318) { + return u.OfWebFetchTool20260318 + } else if !param.IsOmitted(u.OfAdvisorTool20260301) { + return u.OfAdvisorTool20260301 + } else if !param.IsOmitted(u.OfToolSearchToolBm25_20251119) { + return u.OfToolSearchToolBm25_20251119 + } else if !param.IsOmitted(u.OfToolSearchToolRegex20251119) { + return u.OfToolSearchToolRegex20251119 + } else if !param.IsOmitted(u.OfMCPToolset) { + return u.OfMCPToolset + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaMessageCountTokensParamsToolUnion) GetInputSchema() *BetaToolInputSchemaParam { + if vt := u.OfTool; vt != nil { + return &vt.InputSchema + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaMessageCountTokensParamsToolUnion) GetDescription() *string { + if vt := u.OfTool; vt != nil && vt.Description.Valid() { + return &vt.Description.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaMessageCountTokensParamsToolUnion) GetEagerInputStreaming() *bool { + if vt := u.OfTool; vt != nil && vt.EagerInputStreaming.Valid() { + return &vt.EagerInputStreaming.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaMessageCountTokensParamsToolUnion) GetEnableZoom() *bool { + if vt := u.OfComputerUseTool20251124; vt != nil && vt.EnableZoom.Valid() { + return &vt.EnableZoom.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaMessageCountTokensParamsToolUnion) GetMaxCharacters() *int64 { + if vt := u.OfTextEditor20250728; vt != nil && vt.MaxCharacters.Valid() { + return &vt.MaxCharacters.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaMessageCountTokensParamsToolUnion) GetModel() *Model { + if vt := u.OfAdvisorTool20260301; vt != nil { + return &vt.Model + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaMessageCountTokensParamsToolUnion) GetCaching() *BetaCacheControlEphemeralParam { + if vt := u.OfAdvisorTool20260301; vt != nil { + return &vt.Caching + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaMessageCountTokensParamsToolUnion) GetMaxTokens() *int64 { + if vt := u.OfAdvisorTool20260301; vt != nil && vt.MaxTokens.Valid() { + return &vt.MaxTokens.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaMessageCountTokensParamsToolUnion) GetMCPServerName() *string { + if vt := u.OfMCPToolset; vt != nil { + return &vt.MCPServerName + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaMessageCountTokensParamsToolUnion) GetDefaultConfig() *BetaMCPToolDefaultConfigParam { + if vt := u.OfMCPToolset; vt != nil { + return &vt.DefaultConfig + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaMessageCountTokensParamsToolUnion) GetName() *string { + if vt := u.OfTool; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfBashTool20241022; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfBashTool20250124; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfCodeExecutionTool20250522; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfCodeExecutionTool20250825; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfCodeExecutionTool20260120; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfCodeExecutionTool20260521; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfComputerUseTool20241022; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfMemoryTool20250818; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfComputerUseTool20250124; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfTextEditor20241022; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfComputerUseTool20251124; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfTextEditor20250124; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfTextEditor20250429; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfTextEditor20250728; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfWebSearchTool20250305; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfWebFetchTool20250910; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfWebSearchTool20260209; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfWebFetchTool20260209; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfWebFetchTool20260309; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfWebSearchTool20260318; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfWebFetchTool20260318; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfAdvisorTool20260301; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfToolSearchToolRegex20251119; vt != nil { + return (*string)(&vt.Name) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaMessageCountTokensParamsToolUnion) GetDeferLoading() *bool { + if vt := u.OfTool; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfBashTool20241022; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfBashTool20250124; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfCodeExecutionTool20250522; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfCodeExecutionTool20250825; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfCodeExecutionTool20260120; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfCodeExecutionTool20260521; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfComputerUseTool20241022; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfMemoryTool20250818; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfComputerUseTool20250124; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfTextEditor20241022; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfComputerUseTool20251124; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfTextEditor20250124; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfTextEditor20250429; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfTextEditor20250728; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfWebSearchTool20250305; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfWebFetchTool20250910; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfWebSearchTool20260209; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfWebFetchTool20260209; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfWebFetchTool20260309; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfWebSearchTool20260318; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfWebFetchTool20260318; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfAdvisorTool20260301; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfToolSearchToolRegex20251119; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaMessageCountTokensParamsToolUnion) GetStrict() *bool { + if vt := u.OfTool; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfBashTool20241022; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfBashTool20250124; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfCodeExecutionTool20250522; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfCodeExecutionTool20250825; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfCodeExecutionTool20260120; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfCodeExecutionTool20260521; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfComputerUseTool20241022; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfMemoryTool20250818; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfComputerUseTool20250124; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfTextEditor20241022; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfComputerUseTool20251124; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfTextEditor20250124; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfTextEditor20250429; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfTextEditor20250728; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfWebSearchTool20250305; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfWebFetchTool20250910; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfWebSearchTool20260209; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfWebFetchTool20260209; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfWebFetchTool20260309; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfWebSearchTool20260318; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfWebFetchTool20260318; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfAdvisorTool20260301; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfToolSearchToolRegex20251119; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaMessageCountTokensParamsToolUnion) GetType() *string { + if vt := u.OfTool; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfBashTool20241022; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfBashTool20250124; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfCodeExecutionTool20250522; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfCodeExecutionTool20250825; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfCodeExecutionTool20260120; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfCodeExecutionTool20260521; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfBrowserToolset20260801; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfComputerUseTool20241022; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfMemoryTool20250818; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfComputerUseTool20250124; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfTextEditor20241022; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfComputerUseTool20251124; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfComputerToolset20260801; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfTextEditor20250124; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfTextEditor20250429; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfTextEditor20250728; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfWebSearchTool20250305; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfWebFetchTool20250910; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfWebSearchTool20260209; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfWebFetchTool20260209; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfWebFetchTool20260309; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfWebSearchTool20260318; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfWebFetchTool20260318; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfAdvisorTool20260301; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfToolSearchToolRegex20251119; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfMCPToolset; vt != nil { + return (*string)(&vt.Type) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaMessageCountTokensParamsToolUnion) GetDisplayHeightPx() *int64 { + if vt := u.OfComputerUseTool20241022; vt != nil { + return (*int64)(&vt.DisplayHeightPx) + } else if vt := u.OfComputerUseTool20250124; vt != nil { + return (*int64)(&vt.DisplayHeightPx) + } else if vt := u.OfComputerUseTool20251124; vt != nil { + return (*int64)(&vt.DisplayHeightPx) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaMessageCountTokensParamsToolUnion) GetDisplayWidthPx() *int64 { + if vt := u.OfComputerUseTool20241022; vt != nil { + return (*int64)(&vt.DisplayWidthPx) + } else if vt := u.OfComputerUseTool20250124; vt != nil { + return (*int64)(&vt.DisplayWidthPx) + } else if vt := u.OfComputerUseTool20251124; vt != nil { + return (*int64)(&vt.DisplayWidthPx) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaMessageCountTokensParamsToolUnion) GetDisplayNumber() *int64 { + if vt := u.OfComputerUseTool20241022; vt != nil && vt.DisplayNumber.Valid() { + return &vt.DisplayNumber.Value + } else if vt := u.OfComputerUseTool20250124; vt != nil && vt.DisplayNumber.Valid() { + return &vt.DisplayNumber.Value + } else if vt := u.OfComputerUseTool20251124; vt != nil && vt.DisplayNumber.Valid() { + return &vt.DisplayNumber.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaMessageCountTokensParamsToolUnion) GetMaxUses() *int64 { + if vt := u.OfWebSearchTool20250305; vt != nil && vt.MaxUses.Valid() { + return &vt.MaxUses.Value + } else if vt := u.OfWebFetchTool20250910; vt != nil && vt.MaxUses.Valid() { + return &vt.MaxUses.Value + } else if vt := u.OfWebSearchTool20260209; vt != nil && vt.MaxUses.Valid() { + return &vt.MaxUses.Value + } else if vt := u.OfWebFetchTool20260209; vt != nil && vt.MaxUses.Valid() { + return &vt.MaxUses.Value + } else if vt := u.OfWebFetchTool20260309; vt != nil && vt.MaxUses.Valid() { + return &vt.MaxUses.Value + } else if vt := u.OfWebSearchTool20260318; vt != nil && vt.MaxUses.Valid() { + return &vt.MaxUses.Value + } else if vt := u.OfWebFetchTool20260318; vt != nil && vt.MaxUses.Valid() { + return &vt.MaxUses.Value + } else if vt := u.OfAdvisorTool20260301; vt != nil && vt.MaxUses.Valid() { + return &vt.MaxUses.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaMessageCountTokensParamsToolUnion) GetMaxContentTokens() *int64 { + if vt := u.OfWebFetchTool20250910; vt != nil && vt.MaxContentTokens.Valid() { + return &vt.MaxContentTokens.Value + } else if vt := u.OfWebFetchTool20260209; vt != nil && vt.MaxContentTokens.Valid() { + return &vt.MaxContentTokens.Value + } else if vt := u.OfWebFetchTool20260309; vt != nil && vt.MaxContentTokens.Valid() { + return &vt.MaxContentTokens.Value + } else if vt := u.OfWebFetchTool20260318; vt != nil && vt.MaxContentTokens.Valid() { + return &vt.MaxContentTokens.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaMessageCountTokensParamsToolUnion) GetUseCache() *bool { + if vt := u.OfWebFetchTool20260309; vt != nil && vt.UseCache.Valid() { + return &vt.UseCache.Value + } else if vt := u.OfWebFetchTool20260318; vt != nil && vt.UseCache.Valid() { + return &vt.UseCache.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaMessageCountTokensParamsToolUnion) GetResponseInclusion() *string { + if vt := u.OfWebSearchTool20260318; vt != nil { + return (*string)(&vt.ResponseInclusion) + } else if vt := u.OfWebFetchTool20260318; vt != nil { + return (*string)(&vt.ResponseInclusion) + } + return nil +} + +// Returns a pointer to the underlying variant's AllowedCallers property, if +// present. +func (u BetaMessageCountTokensParamsToolUnion) GetAllowedCallers() []string { + if vt := u.OfTool; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfBashTool20241022; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfBashTool20250124; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfCodeExecutionTool20250522; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfCodeExecutionTool20250825; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfCodeExecutionTool20260120; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfCodeExecutionTool20260521; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfBrowserToolset20260801; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfComputerUseTool20241022; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfMemoryTool20250818; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfComputerUseTool20250124; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfTextEditor20241022; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfComputerUseTool20251124; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfComputerToolset20260801; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfTextEditor20250124; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfTextEditor20250429; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfTextEditor20250728; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfWebSearchTool20250305; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfWebFetchTool20250910; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfWebSearchTool20260209; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfWebFetchTool20260209; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfWebFetchTool20260309; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfWebSearchTool20260318; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfWebFetchTool20260318; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfAdvisorTool20260301; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfToolSearchToolRegex20251119; vt != nil { + return vt.AllowedCallers + } + return nil +} + +// Returns a pointer to the underlying variant's CacheControl property, if present. +func (u BetaMessageCountTokensParamsToolUnion) GetCacheControl() *BetaCacheControlEphemeralParam { + if vt := u.OfTool; vt != nil { + return &vt.CacheControl + } else if vt := u.OfBashTool20241022; vt != nil { + return &vt.CacheControl + } else if vt := u.OfBashTool20250124; vt != nil { + return &vt.CacheControl + } else if vt := u.OfCodeExecutionTool20250522; vt != nil { + return &vt.CacheControl + } else if vt := u.OfCodeExecutionTool20250825; vt != nil { + return &vt.CacheControl + } else if vt := u.OfCodeExecutionTool20260120; vt != nil { + return &vt.CacheControl + } else if vt := u.OfCodeExecutionTool20260521; vt != nil { + return &vt.CacheControl + } else if vt := u.OfBrowserToolset20260801; vt != nil { + return &vt.CacheControl + } else if vt := u.OfComputerUseTool20241022; vt != nil { + return &vt.CacheControl + } else if vt := u.OfMemoryTool20250818; vt != nil { + return &vt.CacheControl + } else if vt := u.OfComputerUseTool20250124; vt != nil { + return &vt.CacheControl + } else if vt := u.OfTextEditor20241022; vt != nil { + return &vt.CacheControl + } else if vt := u.OfComputerUseTool20251124; vt != nil { + return &vt.CacheControl + } else if vt := u.OfComputerToolset20260801; vt != nil { + return &vt.CacheControl + } else if vt := u.OfTextEditor20250124; vt != nil { + return &vt.CacheControl + } else if vt := u.OfTextEditor20250429; vt != nil { + return &vt.CacheControl + } else if vt := u.OfTextEditor20250728; vt != nil { + return &vt.CacheControl + } else if vt := u.OfWebSearchTool20250305; vt != nil { + return &vt.CacheControl + } else if vt := u.OfWebFetchTool20250910; vt != nil { + return &vt.CacheControl + } else if vt := u.OfWebSearchTool20260209; vt != nil { + return &vt.CacheControl + } else if vt := u.OfWebFetchTool20260209; vt != nil { + return &vt.CacheControl + } else if vt := u.OfWebFetchTool20260309; vt != nil { + return &vt.CacheControl + } else if vt := u.OfWebSearchTool20260318; vt != nil { + return &vt.CacheControl + } else if vt := u.OfWebFetchTool20260318; vt != nil { + return &vt.CacheControl + } else if vt := u.OfAdvisorTool20260301; vt != nil { + return &vt.CacheControl + } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil { + return &vt.CacheControl + } else if vt := u.OfToolSearchToolRegex20251119; vt != nil { + return &vt.CacheControl + } else if vt := u.OfMCPToolset; vt != nil { + return &vt.CacheControl + } + return nil +} + +// Returns a pointer to the underlying variant's InputExamples property, if +// present. +func (u BetaMessageCountTokensParamsToolUnion) GetInputExamples() []map[string]any { + if vt := u.OfTool; vt != nil { + return vt.InputExamples + } else if vt := u.OfBashTool20241022; vt != nil { + return vt.InputExamples + } else if vt := u.OfBashTool20250124; vt != nil { + return vt.InputExamples + } else if vt := u.OfComputerUseTool20241022; vt != nil { + return vt.InputExamples + } else if vt := u.OfMemoryTool20250818; vt != nil { + return vt.InputExamples + } else if vt := u.OfComputerUseTool20250124; vt != nil { + return vt.InputExamples + } else if vt := u.OfTextEditor20241022; vt != nil { + return vt.InputExamples + } else if vt := u.OfComputerUseTool20251124; vt != nil { + return vt.InputExamples + } else if vt := u.OfTextEditor20250124; vt != nil { + return vt.InputExamples + } else if vt := u.OfTextEditor20250429; vt != nil { + return vt.InputExamples + } else if vt := u.OfTextEditor20250728; vt != nil { + return vt.InputExamples + } + return nil +} + +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u BetaMessageCountTokensParamsToolUnion) GetConfigs() (res betaMessageCountTokensParamsToolUnionConfigs) { + if vt := u.OfBrowserToolset20260801; vt != nil { + res.any = &vt.Configs + } else if vt := u.OfComputerToolset20260801; vt != nil { + res.any = &vt.Configs + } else if vt := u.OfMCPToolset; vt != nil { + res.any = &vt.Configs + } + return +} + +// Can have the runtime types [*BetaBrowserToolsetConfigsParam], +// [*BetaComputerToolsetConfigsParam], [\*map[string]BetaMCPToolConfigParam] +type betaMessageCountTokensParamsToolUnionConfigs struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BetaBrowserToolsetConfigsParam: +// case *anthropic.BetaComputerToolsetConfigsParam: +// case *map[string]anthropic.BetaMCPToolConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u betaMessageCountTokensParamsToolUnionConfigs) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u betaMessageCountTokensParamsToolUnionConfigs) GetCloseTab() *BetaBrowserCloseTabConfigParam { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + return &vt.CloseTab + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaMessageCountTokensParamsToolUnionConfigs) GetFileUpload() *BetaBrowserFileUploadConfigParam { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + return &vt.FileUpload + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaMessageCountTokensParamsToolUnionConfigs) GetFind() *BetaBrowserFindConfigParam { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + return &vt.Find + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaMessageCountTokensParamsToolUnionConfigs) GetFormInput() *BetaBrowserFormInputConfigParam { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + return &vt.FormInput + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaMessageCountTokensParamsToolUnionConfigs) GetGetPageText() *BetaBrowserGetPageTextConfigParam { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + return &vt.GetPageText + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaMessageCountTokensParamsToolUnionConfigs) GetHover() *BetaBrowserHoverConfigParam { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + return &vt.Hover + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaMessageCountTokensParamsToolUnionConfigs) GetJavascriptExec() *BetaBrowserJavascriptExecConfigParam { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + return &vt.JavascriptExec + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaMessageCountTokensParamsToolUnionConfigs) GetListTabs() *BetaBrowserListTabsConfigParam { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + return &vt.ListTabs + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaMessageCountTokensParamsToolUnionConfigs) GetNavigate() *BetaBrowserNavigateConfigParam { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + return &vt.Navigate + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaMessageCountTokensParamsToolUnionConfigs) GetNewTab() *BetaBrowserNewTabConfigParam { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + return &vt.NewTab + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaMessageCountTokensParamsToolUnionConfigs) GetReadConsole() *BetaBrowserReadConsoleConfigParam { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + return &vt.ReadConsole + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaMessageCountTokensParamsToolUnionConfigs) GetReadNetwork() *BetaBrowserReadNetworkConfigParam { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + return &vt.ReadNetwork + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaMessageCountTokensParamsToolUnionConfigs) GetReadPage() *BetaBrowserReadPageConfigParam { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + return &vt.ReadPage + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaMessageCountTokensParamsToolUnionConfigs) GetScrollTo() *BetaBrowserScrollToConfigParam { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + return &vt.ScrollTo + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaMessageCountTokensParamsToolUnionConfigs) GetSwitchTab() *BetaBrowserSwitchTabConfigParam { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + return &vt.SwitchTab + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaMessageCountTokensParamsToolUnionConfigs) GetCursorPosition() *BetaComputerCursorPositionConfigParam { + switch vt := u.any.(type) { + case *BetaComputerToolsetConfigsParam: + return &vt.CursorPosition + } + return nil +} + +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u betaMessageCountTokensParamsToolUnionConfigs) GetDoubleClick() (res betaMessageCountTokensParamsToolUnionConfigsDoubleClick) { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + res.any = &vt.DoubleClick + case *BetaComputerToolsetConfigsParam: + res.any = &vt.DoubleClick + } + return res +} + +// Can have the runtime types [*BetaBrowserDoubleClickConfigParam], +// [*BetaComputerDoubleClickConfigParam] +type betaMessageCountTokensParamsToolUnionConfigsDoubleClick struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BetaBrowserDoubleClickConfigParam: +// case *anthropic.BetaComputerDoubleClickConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u betaMessageCountTokensParamsToolUnionConfigsDoubleClick) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u betaMessageCountTokensParamsToolUnionConfigsDoubleClick) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BetaBrowserDoubleClickConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *BetaComputerDoubleClickConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaMessageCountTokensParamsToolUnionConfigsDoubleClick) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BetaBrowserDoubleClickConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *BetaComputerDoubleClickConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + } + return nil +} + +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u betaMessageCountTokensParamsToolUnionConfigs) GetHoldKey() (res betaMessageCountTokensParamsToolUnionConfigsHoldKey) { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + res.any = &vt.HoldKey + case *BetaComputerToolsetConfigsParam: + res.any = &vt.HoldKey + } + return res +} + +// Can have the runtime types [*BetaBrowserHoldKeyConfigParam], +// [*BetaComputerHoldKeyConfigParam] +type betaMessageCountTokensParamsToolUnionConfigsHoldKey struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BetaBrowserHoldKeyConfigParam: +// case *anthropic.BetaComputerHoldKeyConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u betaMessageCountTokensParamsToolUnionConfigsHoldKey) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u betaMessageCountTokensParamsToolUnionConfigsHoldKey) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BetaBrowserHoldKeyConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *BetaComputerHoldKeyConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaMessageCountTokensParamsToolUnionConfigsHoldKey) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BetaBrowserHoldKeyConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *BetaComputerHoldKeyConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + } + return nil +} + +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u betaMessageCountTokensParamsToolUnionConfigs) GetKey() (res betaMessageCountTokensParamsToolUnionConfigsKey) { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + res.any = &vt.Key + case *BetaComputerToolsetConfigsParam: + res.any = &vt.Key + } + return res } -// Only one field can be non-zero. +// Can have the runtime types [*BetaBrowserKeyConfigParam], +// [*BetaComputerKeyConfigParam] +type betaMessageCountTokensParamsToolUnionConfigsKey struct{ any } + +// Use the following switch statement to get the type of the union: // -// Use [param.IsOmitted] to confirm if a field is set. -type BetaMessageNewParamsContainerUnion struct { - OfContainers *BetaContainerParams `json:",omitzero,inline"` - OfString param.Opt[string] `json:",omitzero,inline"` - paramUnion -} +// switch u.AsAny().(type) { +// case *anthropic.BetaBrowserKeyConfigParam: +// case *anthropic.BetaComputerKeyConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u betaMessageCountTokensParamsToolUnionConfigsKey) AsAny() any { return u.any } -func (u BetaMessageNewParamsContainerUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfContainers, u.OfString) -} -func (u *BetaMessageNewParamsContainerUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) +// Returns a pointer to the underlying variant's property, if present. +func (u betaMessageCountTokensParamsToolUnionConfigsKey) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BetaBrowserKeyConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *BetaComputerKeyConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + } + return nil } -func (u *BetaMessageNewParamsContainerUnion) asAny() any { - if !param.IsOmitted(u.OfContainers) { - return u.OfContainers - } else if !param.IsOmitted(u.OfString) { - return &u.OfString.Value +// Returns a pointer to the underlying variant's property, if present. +func (u betaMessageCountTokensParamsToolUnionConfigsKey) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BetaBrowserKeyConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *BetaComputerKeyConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) } return nil } -// Determines whether to use priority capacity (if available) or standard capacity -// for this request. +// Returns a subunion which exports methods to access subproperties // -// Anthropic offers different levels of service for your API requests. See -// [service-tiers](https://docs.claude.com/en/api/service-tiers) for details. -type BetaMessageNewParamsServiceTier string - -const ( - BetaMessageNewParamsServiceTierAuto BetaMessageNewParamsServiceTier = "auto" - BetaMessageNewParamsServiceTierStandardOnly BetaMessageNewParamsServiceTier = "standard_only" -) - -// The inference speed mode for this request. `"fast"` enables high -// output-tokens-per-second inference. -type BetaMessageNewParamsSpeed string +// Or use AsAny() to get the underlying value +func (u betaMessageCountTokensParamsToolUnionConfigs) GetLeftClick() (res betaMessageCountTokensParamsToolUnionConfigsLeftClick) { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + res.any = &vt.LeftClick + case *BetaComputerToolsetConfigsParam: + res.any = &vt.LeftClick + } + return res +} -const ( - BetaMessageNewParamsSpeedStandard BetaMessageNewParamsSpeed = "standard" - BetaMessageNewParamsSpeedFast BetaMessageNewParamsSpeed = "fast" -) +// Can have the runtime types [*BetaBrowserLeftClickConfigParam], +// [*BetaComputerLeftClickConfigParam] +type betaMessageCountTokensParamsToolUnionConfigsLeftClick struct{ any } -type BetaMessageCountTokensParams struct { - // Input messages. - // - // Our models are trained to operate on alternating `user` and `assistant` - // conversational turns. When creating a new `Message`, you specify the prior - // conversational turns with the `messages` parameter, and the model then generates - // the next `Message` in the conversation. Consecutive `user` or `assistant` turns - // in your request will be combined into a single turn. - // - // Each input message must be an object with a `role` and `content`. You can - // specify a single `user`-role message, or you can include multiple `user` and - // `assistant` messages. - // - // If the final message uses the `assistant` role, the response content will - // continue immediately from the content in that message. This can be used to - // constrain part of the model's response. - // - // Example with a single `user` message: - // - // ```json - // [{ "role": "user", "content": "Hello, Claude" }] - // ``` - // - // Example with multiple conversational turns: - // - // ```json - // [ - // - // { "role": "user", "content": "Hello there." }, - // { "role": "assistant", "content": "Hi, I'm Claude. How can I help you?" }, - // { "role": "user", "content": "Can you explain LLMs in plain English?" } - // - // ] - // ``` - // - // Example with a partially-filled response from Claude: - // - // ```json - // [ - // - // { - // "role": "user", - // "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun" - // }, - // { "role": "assistant", "content": "The best answer is (" } - // - // ] - // ``` - // - // Each input message `content` may be either a single `string` or an array of - // content blocks, where each block has a specific `type`. Using a `string` for - // `content` is shorthand for an array of one content block of type `"text"`. The - // following input messages are equivalent: - // - // ```json - // { "role": "user", "content": "Hello, Claude" } - // ``` - // - // ```json - // { "role": "user", "content": [{ "type": "text", "text": "Hello, Claude" }] } - // ``` - // - // See [input examples](https://docs.claude.com/en/api/messages-examples). - // - // Note that if you want to include a - // [system prompt](https://docs.claude.com/en/docs/system-prompts), you can use the - // top-level `system` parameter — there is no `"system"` role for input messages in - // the Messages API. - // - // There is a limit of 100,000 messages in a single request. - Messages []BetaMessageParam `json:"messages,omitzero" api:"required"` - // The model that will complete your prompt.\n\nSee - // [models](https://docs.anthropic.com/en/docs/models-overview) for additional - // details and options. - Model Model `json:"model,omitzero" api:"required"` - // The inference speed mode for this request. `"fast"` enables high - // output-tokens-per-second inference. - // - // Any of "standard", "fast". - Speed BetaMessageCountTokensParamsSpeed `json:"speed,omitzero"` - // Top-level cache control automatically applies a cache_control marker to the last - // cacheable block in the request. - CacheControl BetaCacheControlEphemeralParam `json:"cache_control,omitzero"` - // Context management configuration. - // - // This allows you to control how Claude manages context across multiple requests, - // such as whether to clear function results or not. - ContextManagement BetaContextManagementConfigParam `json:"context_management,omitzero"` - // MCP servers to be utilized in this request - MCPServers []BetaRequestMCPServerURLDefinitionParam `json:"mcp_servers,omitzero"` - // Configuration options for the model's output, such as the output format. - OutputConfig BetaOutputConfigParam `json:"output_config,omitzero"` - // Deprecated: Use `output_config.format` instead. See - // [structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs) - // - // A schema to specify Claude's output format in responses. This parameter will be - // removed in a future release. - OutputFormat BetaJSONOutputFormatParam `json:"output_format,omitzero"` - // System prompt. - // - // A system prompt is a way of providing context and instructions to Claude, such - // as specifying a particular goal or role. See our - // [guide to system prompts](https://docs.claude.com/en/docs/system-prompts). - System BetaMessageCountTokensParamsSystemUnion `json:"system,omitzero"` - // Configuration for enabling Claude's extended thinking. - // - // When enabled, responses include `thinking` content blocks showing Claude's - // thinking process before the final answer. Requires a minimum budget of 1,024 - // tokens and counts towards your `max_tokens` limit. - // - // See - // [extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking) - // for details. - Thinking BetaThinkingConfigParamUnion `json:"thinking,omitzero"` - // How the model should use the provided tools. The model can use a specific tool, - // any available tool, decide by itself, or not use tools at all. - ToolChoice BetaToolChoiceUnionParam `json:"tool_choice,omitzero"` - // Definitions of tools that the model may use. - // - // If you include `tools` in your API request, the model may return `tool_use` - // content blocks that represent the model's use of those tools. You can then run - // those tools using the tool input generated by the model and then optionally - // return results back to the model using `tool_result` content blocks. - // - // There are two types of tools: **client tools** and **server tools**. The - // behavior described below applies to client tools. For - // [server tools](https://docs.claude.com/en/docs/agents-and-tools/tool-use/overview#server-tools), - // see their individual documentation as each has its own behavior (e.g., the - // [web search tool](https://docs.claude.com/en/docs/agents-and-tools/tool-use/web-search-tool)). - // - // Each tool definition includes: - // - // - `name`: Name of the tool. - // - `description`: Optional, but strongly-recommended description of the tool. - // - `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the - // tool `input` shape that the model will produce in `tool_use` output content - // blocks. - // - // For example, if you defined `tools` as: - // - // ```json - // [ - // - // { - // "name": "get_stock_price", - // "description": "Get the current stock price for a given ticker symbol.", - // "input_schema": { - // "type": "object", - // "properties": { - // "ticker": { - // "type": "string", - // "description": "The stock ticker symbol, e.g. AAPL for Apple Inc." - // } - // }, - // "required": ["ticker"] - // } - // } - // - // ] - // ``` - // - // And then asked the model "What's the S&P 500 at today?", the model might produce - // `tool_use` content blocks in the response like this: - // - // ```json - // [ - // - // { - // "type": "tool_use", - // "id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV", - // "name": "get_stock_price", - // "input": { "ticker": "^GSPC" } - // } - // - // ] - // ``` - // - // You might then run your `get_stock_price` tool with `{"ticker": "^GSPC"}` as an - // input, and return the following back to the model in a subsequent `user` - // message: - // - // ```json - // [ - // - // { - // "type": "tool_result", - // "tool_use_id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV", - // "content": "259.75 USD" - // } - // - // ] - // ``` - // - // Tools can be used for workflows that include running client-side tools and - // functions, or more generally whenever you want the model to produce a particular - // JSON structure of output. - // - // See our [guide](https://docs.claude.com/en/docs/tool-use) for more details. - Tools []BetaMessageCountTokensParamsToolUnion `json:"tools,omitzero"` - // Optional header to specify the beta version(s) you want to use. - Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` - paramObj -} +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BetaBrowserLeftClickConfigParam: +// case *anthropic.BetaComputerLeftClickConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u betaMessageCountTokensParamsToolUnionConfigsLeftClick) AsAny() any { return u.any } -func (r BetaMessageCountTokensParams) MarshalJSON() (data []byte, err error) { - type shadow BetaMessageCountTokensParams - return param.MarshalObject(r, (*shadow)(&r)) +// Returns a pointer to the underlying variant's property, if present. +func (u betaMessageCountTokensParamsToolUnionConfigsLeftClick) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BetaBrowserLeftClickConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *BetaComputerLeftClickConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + } + return nil } -func (r *BetaMessageCountTokensParams) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) + +// Returns a pointer to the underlying variant's property, if present. +func (u betaMessageCountTokensParamsToolUnionConfigsLeftClick) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BetaBrowserLeftClickConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *BetaComputerLeftClickConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + } + return nil } -// The inference speed mode for this request. `"fast"` enables high -// output-tokens-per-second inference. -type BetaMessageCountTokensParamsSpeed string +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u betaMessageCountTokensParamsToolUnionConfigs) GetLeftClickDrag() (res betaMessageCountTokensParamsToolUnionConfigsLeftClickDrag) { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + res.any = &vt.LeftClickDrag + case *BetaComputerToolsetConfigsParam: + res.any = &vt.LeftClickDrag + } + return res +} -const ( - BetaMessageCountTokensParamsSpeedStandard BetaMessageCountTokensParamsSpeed = "standard" - BetaMessageCountTokensParamsSpeedFast BetaMessageCountTokensParamsSpeed = "fast" -) +// Can have the runtime types [*BetaBrowserLeftClickDragConfigParam], +// [*BetaComputerLeftClickDragConfigParam] +type betaMessageCountTokensParamsToolUnionConfigsLeftClickDrag struct{ any } -// Only one field can be non-zero. +// Use the following switch statement to get the type of the union: // -// Use [param.IsOmitted] to confirm if a field is set. -type BetaMessageCountTokensParamsSystemUnion struct { - OfString param.Opt[string] `json:",omitzero,inline"` - OfBetaTextBlockArray []BetaTextBlockParam `json:",omitzero,inline"` - paramUnion -} +// switch u.AsAny().(type) { +// case *anthropic.BetaBrowserLeftClickDragConfigParam: +// case *anthropic.BetaComputerLeftClickDragConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u betaMessageCountTokensParamsToolUnionConfigsLeftClickDrag) AsAny() any { return u.any } -func (u BetaMessageCountTokensParamsSystemUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfString, u.OfBetaTextBlockArray) -} -func (u *BetaMessageCountTokensParamsSystemUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) +// Returns a pointer to the underlying variant's property, if present. +func (u betaMessageCountTokensParamsToolUnionConfigsLeftClickDrag) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BetaBrowserLeftClickDragConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *BetaComputerLeftClickDragConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + } + return nil } -func (u *BetaMessageCountTokensParamsSystemUnion) asAny() any { - if !param.IsOmitted(u.OfString) { - return &u.OfString.Value - } else if !param.IsOmitted(u.OfBetaTextBlockArray) { - return &u.OfBetaTextBlockArray +// Returns a pointer to the underlying variant's property, if present. +func (u betaMessageCountTokensParamsToolUnionConfigsLeftClickDrag) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BetaBrowserLeftClickDragConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *BetaComputerLeftClickDragConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) } return nil } -// Only one field can be non-zero. +// Returns a subunion which exports methods to access subproperties // -// Use [param.IsOmitted] to confirm if a field is set. -type BetaMessageCountTokensParamsToolUnion struct { - OfTool *BetaToolParam `json:",omitzero,inline"` - OfBashTool20241022 *BetaToolBash20241022Param `json:",omitzero,inline"` - OfBashTool20250124 *BetaToolBash20250124Param `json:",omitzero,inline"` - OfCodeExecutionTool20250522 *BetaCodeExecutionTool20250522Param `json:",omitzero,inline"` - OfCodeExecutionTool20250825 *BetaCodeExecutionTool20250825Param `json:",omitzero,inline"` - OfCodeExecutionTool20260120 *BetaCodeExecutionTool20260120Param `json:",omitzero,inline"` - OfComputerUseTool20241022 *BetaToolComputerUse20241022Param `json:",omitzero,inline"` - OfMemoryTool20250818 *BetaMemoryTool20250818Param `json:",omitzero,inline"` - OfComputerUseTool20250124 *BetaToolComputerUse20250124Param `json:",omitzero,inline"` - OfTextEditor20241022 *BetaToolTextEditor20241022Param `json:",omitzero,inline"` - OfComputerUseTool20251124 *BetaToolComputerUse20251124Param `json:",omitzero,inline"` - OfTextEditor20250124 *BetaToolTextEditor20250124Param `json:",omitzero,inline"` - OfTextEditor20250429 *BetaToolTextEditor20250429Param `json:",omitzero,inline"` - OfTextEditor20250728 *BetaToolTextEditor20250728Param `json:",omitzero,inline"` - OfWebSearchTool20250305 *BetaWebSearchTool20250305Param `json:",omitzero,inline"` - OfWebFetchTool20250910 *BetaWebFetchTool20250910Param `json:",omitzero,inline"` - OfWebSearchTool20260209 *BetaWebSearchTool20260209Param `json:",omitzero,inline"` - OfWebFetchTool20260209 *BetaWebFetchTool20260209Param `json:",omitzero,inline"` - OfWebFetchTool20260309 *BetaWebFetchTool20260309Param `json:",omitzero,inline"` - OfAdvisorTool20260301 *BetaAdvisorTool20260301Param `json:",omitzero,inline"` - OfToolSearchToolBm25_20251119 *BetaToolSearchToolBm25_20251119Param `json:",omitzero,inline"` - OfToolSearchToolRegex20251119 *BetaToolSearchToolRegex20251119Param `json:",omitzero,inline"` - OfMCPToolset *BetaMCPToolsetParam `json:",omitzero,inline"` - paramUnion +// Or use AsAny() to get the underlying value +func (u betaMessageCountTokensParamsToolUnionConfigs) GetLeftMouseDown() (res betaMessageCountTokensParamsToolUnionConfigsLeftMouseDown) { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + res.any = &vt.LeftMouseDown + case *BetaComputerToolsetConfigsParam: + res.any = &vt.LeftMouseDown + } + return res } -func (u BetaMessageCountTokensParamsToolUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfTool, - u.OfBashTool20241022, - u.OfBashTool20250124, - u.OfCodeExecutionTool20250522, - u.OfCodeExecutionTool20250825, - u.OfCodeExecutionTool20260120, - u.OfComputerUseTool20241022, - u.OfMemoryTool20250818, - u.OfComputerUseTool20250124, - u.OfTextEditor20241022, - u.OfComputerUseTool20251124, - u.OfTextEditor20250124, - u.OfTextEditor20250429, - u.OfTextEditor20250728, - u.OfWebSearchTool20250305, - u.OfWebFetchTool20250910, - u.OfWebSearchTool20260209, - u.OfWebFetchTool20260209, - u.OfWebFetchTool20260309, - u.OfAdvisorTool20260301, - u.OfToolSearchToolBm25_20251119, - u.OfToolSearchToolRegex20251119, - u.OfMCPToolset) -} -func (u *BetaMessageCountTokensParamsToolUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} +// Can have the runtime types [*BetaBrowserLeftMouseDownConfigParam], +// [*BetaComputerLeftMouseDownConfigParam] +type betaMessageCountTokensParamsToolUnionConfigsLeftMouseDown struct{ any } -func (u *BetaMessageCountTokensParamsToolUnion) asAny() any { - if !param.IsOmitted(u.OfTool) { - return u.OfTool - } else if !param.IsOmitted(u.OfBashTool20241022) { - return u.OfBashTool20241022 - } else if !param.IsOmitted(u.OfBashTool20250124) { - return u.OfBashTool20250124 - } else if !param.IsOmitted(u.OfCodeExecutionTool20250522) { - return u.OfCodeExecutionTool20250522 - } else if !param.IsOmitted(u.OfCodeExecutionTool20250825) { - return u.OfCodeExecutionTool20250825 - } else if !param.IsOmitted(u.OfCodeExecutionTool20260120) { - return u.OfCodeExecutionTool20260120 - } else if !param.IsOmitted(u.OfComputerUseTool20241022) { - return u.OfComputerUseTool20241022 - } else if !param.IsOmitted(u.OfMemoryTool20250818) { - return u.OfMemoryTool20250818 - } else if !param.IsOmitted(u.OfComputerUseTool20250124) { - return u.OfComputerUseTool20250124 - } else if !param.IsOmitted(u.OfTextEditor20241022) { - return u.OfTextEditor20241022 - } else if !param.IsOmitted(u.OfComputerUseTool20251124) { - return u.OfComputerUseTool20251124 - } else if !param.IsOmitted(u.OfTextEditor20250124) { - return u.OfTextEditor20250124 - } else if !param.IsOmitted(u.OfTextEditor20250429) { - return u.OfTextEditor20250429 - } else if !param.IsOmitted(u.OfTextEditor20250728) { - return u.OfTextEditor20250728 - } else if !param.IsOmitted(u.OfWebSearchTool20250305) { - return u.OfWebSearchTool20250305 - } else if !param.IsOmitted(u.OfWebFetchTool20250910) { - return u.OfWebFetchTool20250910 - } else if !param.IsOmitted(u.OfWebSearchTool20260209) { - return u.OfWebSearchTool20260209 - } else if !param.IsOmitted(u.OfWebFetchTool20260209) { - return u.OfWebFetchTool20260209 - } else if !param.IsOmitted(u.OfWebFetchTool20260309) { - return u.OfWebFetchTool20260309 - } else if !param.IsOmitted(u.OfAdvisorTool20260301) { - return u.OfAdvisorTool20260301 - } else if !param.IsOmitted(u.OfToolSearchToolBm25_20251119) { - return u.OfToolSearchToolBm25_20251119 - } else if !param.IsOmitted(u.OfToolSearchToolRegex20251119) { - return u.OfToolSearchToolRegex20251119 - } else if !param.IsOmitted(u.OfMCPToolset) { - return u.OfMCPToolset +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BetaBrowserLeftMouseDownConfigParam: +// case *anthropic.BetaComputerLeftMouseDownConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u betaMessageCountTokensParamsToolUnionConfigsLeftMouseDown) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u betaMessageCountTokensParamsToolUnionConfigsLeftMouseDown) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BetaBrowserLeftMouseDownConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *BetaComputerLeftMouseDownConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u BetaMessageCountTokensParamsToolUnion) GetInputSchema() *BetaToolInputSchemaParam { - if vt := u.OfTool; vt != nil { - return &vt.InputSchema +func (u betaMessageCountTokensParamsToolUnionConfigsLeftMouseDown) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BetaBrowserLeftMouseDownConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *BetaComputerLeftMouseDownConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) } return nil } +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u betaMessageCountTokensParamsToolUnionConfigs) GetLeftMouseUp() (res betaMessageCountTokensParamsToolUnionConfigsLeftMouseUp) { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + res.any = &vt.LeftMouseUp + case *BetaComputerToolsetConfigsParam: + res.any = &vt.LeftMouseUp + } + return res +} + +// Can have the runtime types [*BetaBrowserLeftMouseUpConfigParam], +// [*BetaComputerLeftMouseUpConfigParam] +type betaMessageCountTokensParamsToolUnionConfigsLeftMouseUp struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BetaBrowserLeftMouseUpConfigParam: +// case *anthropic.BetaComputerLeftMouseUpConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u betaMessageCountTokensParamsToolUnionConfigsLeftMouseUp) AsAny() any { return u.any } + // Returns a pointer to the underlying variant's property, if present. -func (u BetaMessageCountTokensParamsToolUnion) GetDescription() *string { - if vt := u.OfTool; vt != nil && vt.Description.Valid() { - return &vt.Description.Value +func (u betaMessageCountTokensParamsToolUnionConfigsLeftMouseUp) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BetaBrowserLeftMouseUpConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *BetaComputerLeftMouseUpConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u BetaMessageCountTokensParamsToolUnion) GetEagerInputStreaming() *bool { - if vt := u.OfTool; vt != nil && vt.EagerInputStreaming.Valid() { - return &vt.EagerInputStreaming.Value +func (u betaMessageCountTokensParamsToolUnionConfigsLeftMouseUp) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BetaBrowserLeftMouseUpConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *BetaComputerLeftMouseUpConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) } return nil } +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u betaMessageCountTokensParamsToolUnionConfigs) GetMiddleClick() (res betaMessageCountTokensParamsToolUnionConfigsMiddleClick) { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + res.any = &vt.MiddleClick + case *BetaComputerToolsetConfigsParam: + res.any = &vt.MiddleClick + } + return res +} + +// Can have the runtime types [*BetaBrowserMiddleClickConfigParam], +// [*BetaComputerMiddleClickConfigParam] +type betaMessageCountTokensParamsToolUnionConfigsMiddleClick struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BetaBrowserMiddleClickConfigParam: +// case *anthropic.BetaComputerMiddleClickConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u betaMessageCountTokensParamsToolUnionConfigsMiddleClick) AsAny() any { return u.any } + // Returns a pointer to the underlying variant's property, if present. -func (u BetaMessageCountTokensParamsToolUnion) GetEnableZoom() *bool { - if vt := u.OfComputerUseTool20251124; vt != nil && vt.EnableZoom.Valid() { - return &vt.EnableZoom.Value +func (u betaMessageCountTokensParamsToolUnionConfigsMiddleClick) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BetaBrowserMiddleClickConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *BetaComputerMiddleClickConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u BetaMessageCountTokensParamsToolUnion) GetMaxCharacters() *int64 { - if vt := u.OfTextEditor20250728; vt != nil && vt.MaxCharacters.Valid() { - return &vt.MaxCharacters.Value +func (u betaMessageCountTokensParamsToolUnionConfigsMiddleClick) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BetaBrowserMiddleClickConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *BetaComputerMiddleClickConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) } return nil } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaMessageCountTokensParamsToolUnion) GetUseCache() *bool { - if vt := u.OfWebFetchTool20260309; vt != nil && vt.UseCache.Valid() { - return &vt.UseCache.Value +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u betaMessageCountTokensParamsToolUnionConfigs) GetMouseMove() (res betaMessageCountTokensParamsToolUnionConfigsMouseMove) { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + res.any = &vt.MouseMove + case *BetaComputerToolsetConfigsParam: + res.any = &vt.MouseMove + } + return res +} + +// Can have the runtime types [*BetaBrowserMouseMoveConfigParam], +// [*BetaComputerMouseMoveConfigParam] +type betaMessageCountTokensParamsToolUnionConfigsMouseMove struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BetaBrowserMouseMoveConfigParam: +// case *anthropic.BetaComputerMouseMoveConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u betaMessageCountTokensParamsToolUnionConfigsMouseMove) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u betaMessageCountTokensParamsToolUnionConfigsMouseMove) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BetaBrowserMouseMoveConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *BetaComputerMouseMoveConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u BetaMessageCountTokensParamsToolUnion) GetModel() *Model { - if vt := u.OfAdvisorTool20260301; vt != nil { - return &vt.Model +func (u betaMessageCountTokensParamsToolUnionConfigsMouseMove) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BetaBrowserMouseMoveConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *BetaComputerMouseMoveConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) } return nil } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaMessageCountTokensParamsToolUnion) GetCaching() *BetaCacheControlEphemeralParam { - if vt := u.OfAdvisorTool20260301; vt != nil { - return &vt.Caching +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u betaMessageCountTokensParamsToolUnionConfigs) GetRightClick() (res betaMessageCountTokensParamsToolUnionConfigsRightClick) { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + res.any = &vt.RightClick + case *BetaComputerToolsetConfigsParam: + res.any = &vt.RightClick } - return nil + return res } +// Can have the runtime types [*BetaBrowserRightClickConfigParam], +// [*BetaComputerRightClickConfigParam] +type betaMessageCountTokensParamsToolUnionConfigsRightClick struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BetaBrowserRightClickConfigParam: +// case *anthropic.BetaComputerRightClickConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u betaMessageCountTokensParamsToolUnionConfigsRightClick) AsAny() any { return u.any } + // Returns a pointer to the underlying variant's property, if present. -func (u BetaMessageCountTokensParamsToolUnion) GetMCPServerName() *string { - if vt := u.OfMCPToolset; vt != nil { - return &vt.MCPServerName +func (u betaMessageCountTokensParamsToolUnionConfigsRightClick) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BetaBrowserRightClickConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *BetaComputerRightClickConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u BetaMessageCountTokensParamsToolUnion) GetConfigs() map[string]BetaMCPToolConfigParam { - if vt := u.OfMCPToolset; vt != nil { - return vt.Configs +func (u betaMessageCountTokensParamsToolUnionConfigsRightClick) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BetaBrowserRightClickConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *BetaComputerRightClickConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) } return nil } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaMessageCountTokensParamsToolUnion) GetDefaultConfig() *BetaMCPToolDefaultConfigParam { - if vt := u.OfMCPToolset; vt != nil { - return &vt.DefaultConfig +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u betaMessageCountTokensParamsToolUnionConfigs) GetScreenshot() (res betaMessageCountTokensParamsToolUnionConfigsScreenshot) { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + res.any = &vt.Screenshot + case *BetaComputerToolsetConfigsParam: + res.any = &vt.Screenshot } - return nil + return res } +// Can have the runtime types [*BetaBrowserScreenshotConfigParam], +// [*BetaComputerScreenshotConfigParam] +type betaMessageCountTokensParamsToolUnionConfigsScreenshot struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BetaBrowserScreenshotConfigParam: +// case *anthropic.BetaComputerScreenshotConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u betaMessageCountTokensParamsToolUnionConfigsScreenshot) AsAny() any { return u.any } + // Returns a pointer to the underlying variant's property, if present. -func (u BetaMessageCountTokensParamsToolUnion) GetName() *string { - if vt := u.OfTool; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfBashTool20241022; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfBashTool20250124; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfCodeExecutionTool20250522; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfCodeExecutionTool20250825; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfCodeExecutionTool20260120; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfComputerUseTool20241022; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfMemoryTool20250818; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfComputerUseTool20250124; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfTextEditor20241022; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfComputerUseTool20251124; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfTextEditor20250124; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfTextEditor20250429; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfTextEditor20250728; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfWebSearchTool20250305; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfWebFetchTool20250910; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfWebSearchTool20260209; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfWebFetchTool20260209; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfWebFetchTool20260309; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfAdvisorTool20260301; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfToolSearchToolRegex20251119; vt != nil { - return (*string)(&vt.Name) +func (u betaMessageCountTokensParamsToolUnionConfigsScreenshot) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BetaBrowserScreenshotConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *BetaComputerScreenshotConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u BetaMessageCountTokensParamsToolUnion) GetDeferLoading() *bool { - if vt := u.OfTool; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfBashTool20241022; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfBashTool20250124; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfCodeExecutionTool20250522; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfCodeExecutionTool20250825; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfCodeExecutionTool20260120; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfComputerUseTool20241022; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfMemoryTool20250818; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfComputerUseTool20250124; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfTextEditor20241022; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfComputerUseTool20251124; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfTextEditor20250124; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfTextEditor20250429; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfTextEditor20250728; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfWebSearchTool20250305; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfWebFetchTool20250910; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfWebSearchTool20260209; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfWebFetchTool20260209; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfWebFetchTool20260309; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfAdvisorTool20260301; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfToolSearchToolRegex20251119; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value +func (u betaMessageCountTokensParamsToolUnionConfigsScreenshot) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BetaBrowserScreenshotConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *BetaComputerScreenshotConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) } return nil } -// Returns a pointer to the underlying variant's property, if present. -func (u BetaMessageCountTokensParamsToolUnion) GetStrict() *bool { - if vt := u.OfTool; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfBashTool20241022; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfBashTool20250124; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfCodeExecutionTool20250522; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfCodeExecutionTool20250825; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfCodeExecutionTool20260120; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfComputerUseTool20241022; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfMemoryTool20250818; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfComputerUseTool20250124; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfTextEditor20241022; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfComputerUseTool20251124; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfTextEditor20250124; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfTextEditor20250429; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfTextEditor20250728; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfWebSearchTool20250305; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfWebFetchTool20250910; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfWebSearchTool20260209; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfWebFetchTool20260209; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfWebFetchTool20260309; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfAdvisorTool20260301; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfToolSearchToolRegex20251119; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u betaMessageCountTokensParamsToolUnionConfigs) GetScroll() (res betaMessageCountTokensParamsToolUnionConfigsScroll) { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + res.any = &vt.Scroll + case *BetaComputerToolsetConfigsParam: + res.any = &vt.Scroll } - return nil + return res } +// Can have the runtime types [*BetaBrowserScrollConfigParam], +// [*BetaComputerScrollConfigParam] +type betaMessageCountTokensParamsToolUnionConfigsScroll struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BetaBrowserScrollConfigParam: +// case *anthropic.BetaComputerScrollConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u betaMessageCountTokensParamsToolUnionConfigsScroll) AsAny() any { return u.any } + // Returns a pointer to the underlying variant's property, if present. -func (u BetaMessageCountTokensParamsToolUnion) GetType() *string { - if vt := u.OfTool; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfBashTool20241022; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfBashTool20250124; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfCodeExecutionTool20250522; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfCodeExecutionTool20250825; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfCodeExecutionTool20260120; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfComputerUseTool20241022; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfMemoryTool20250818; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfComputerUseTool20250124; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfTextEditor20241022; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfComputerUseTool20251124; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfTextEditor20250124; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfTextEditor20250429; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfTextEditor20250728; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfWebSearchTool20250305; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfWebFetchTool20250910; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfWebSearchTool20260209; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfWebFetchTool20260209; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfWebFetchTool20260309; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfAdvisorTool20260301; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfToolSearchToolRegex20251119; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfMCPToolset; vt != nil { - return (*string)(&vt.Type) +func (u betaMessageCountTokensParamsToolUnionConfigsScroll) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BetaBrowserScrollConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *BetaComputerScrollConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaMessageCountTokensParamsToolUnionConfigsScroll) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BetaBrowserScrollConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *BetaComputerScrollConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) } return nil } +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u betaMessageCountTokensParamsToolUnionConfigs) GetTripleClick() (res betaMessageCountTokensParamsToolUnionConfigsTripleClick) { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + res.any = &vt.TripleClick + case *BetaComputerToolsetConfigsParam: + res.any = &vt.TripleClick + } + return res +} + +// Can have the runtime types [*BetaBrowserTripleClickConfigParam], +// [*BetaComputerTripleClickConfigParam] +type betaMessageCountTokensParamsToolUnionConfigsTripleClick struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BetaBrowserTripleClickConfigParam: +// case *anthropic.BetaComputerTripleClickConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u betaMessageCountTokensParamsToolUnionConfigsTripleClick) AsAny() any { return u.any } + // Returns a pointer to the underlying variant's property, if present. -func (u BetaMessageCountTokensParamsToolUnion) GetDisplayHeightPx() *int64 { - if vt := u.OfComputerUseTool20241022; vt != nil { - return (*int64)(&vt.DisplayHeightPx) - } else if vt := u.OfComputerUseTool20250124; vt != nil { - return (*int64)(&vt.DisplayHeightPx) - } else if vt := u.OfComputerUseTool20251124; vt != nil { - return (*int64)(&vt.DisplayHeightPx) +func (u betaMessageCountTokensParamsToolUnionConfigsTripleClick) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BetaBrowserTripleClickConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *BetaComputerTripleClickConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u BetaMessageCountTokensParamsToolUnion) GetDisplayWidthPx() *int64 { - if vt := u.OfComputerUseTool20241022; vt != nil { - return (*int64)(&vt.DisplayWidthPx) - } else if vt := u.OfComputerUseTool20250124; vt != nil { - return (*int64)(&vt.DisplayWidthPx) - } else if vt := u.OfComputerUseTool20251124; vt != nil { - return (*int64)(&vt.DisplayWidthPx) +func (u betaMessageCountTokensParamsToolUnionConfigsTripleClick) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BetaBrowserTripleClickConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *BetaComputerTripleClickConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) } return nil } +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u betaMessageCountTokensParamsToolUnionConfigs) GetType() (res betaMessageCountTokensParamsToolUnionConfigsType) { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + res.any = &vt.Type + case *BetaComputerToolsetConfigsParam: + res.any = &vt.Type + } + return res +} + +// Can have the runtime types [*BetaBrowserTypeConfigParam], +// [*BetaComputerTypeConfigParam] +type betaMessageCountTokensParamsToolUnionConfigsType struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BetaBrowserTypeConfigParam: +// case *anthropic.BetaComputerTypeConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u betaMessageCountTokensParamsToolUnionConfigsType) AsAny() any { return u.any } + // Returns a pointer to the underlying variant's property, if present. -func (u BetaMessageCountTokensParamsToolUnion) GetDisplayNumber() *int64 { - if vt := u.OfComputerUseTool20241022; vt != nil && vt.DisplayNumber.Valid() { - return &vt.DisplayNumber.Value - } else if vt := u.OfComputerUseTool20250124; vt != nil && vt.DisplayNumber.Valid() { - return &vt.DisplayNumber.Value - } else if vt := u.OfComputerUseTool20251124; vt != nil && vt.DisplayNumber.Valid() { - return &vt.DisplayNumber.Value +func (u betaMessageCountTokensParamsToolUnionConfigsType) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BetaBrowserTypeConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *BetaComputerTypeConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u BetaMessageCountTokensParamsToolUnion) GetMaxUses() *int64 { - if vt := u.OfWebSearchTool20250305; vt != nil && vt.MaxUses.Valid() { - return &vt.MaxUses.Value - } else if vt := u.OfWebFetchTool20250910; vt != nil && vt.MaxUses.Valid() { - return &vt.MaxUses.Value - } else if vt := u.OfWebSearchTool20260209; vt != nil && vt.MaxUses.Valid() { - return &vt.MaxUses.Value - } else if vt := u.OfWebFetchTool20260209; vt != nil && vt.MaxUses.Valid() { - return &vt.MaxUses.Value - } else if vt := u.OfWebFetchTool20260309; vt != nil && vt.MaxUses.Valid() { - return &vt.MaxUses.Value - } else if vt := u.OfAdvisorTool20260301; vt != nil && vt.MaxUses.Valid() { - return &vt.MaxUses.Value +func (u betaMessageCountTokensParamsToolUnionConfigsType) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BetaBrowserTypeConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *BetaComputerTypeConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) } return nil } +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u betaMessageCountTokensParamsToolUnionConfigs) GetWait() (res betaMessageCountTokensParamsToolUnionConfigsWait) { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + res.any = &vt.Wait + case *BetaComputerToolsetConfigsParam: + res.any = &vt.Wait + } + return res +} + +// Can have the runtime types [*BetaBrowserWaitConfigParam], +// [*BetaComputerWaitConfigParam] +type betaMessageCountTokensParamsToolUnionConfigsWait struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BetaBrowserWaitConfigParam: +// case *anthropic.BetaComputerWaitConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u betaMessageCountTokensParamsToolUnionConfigsWait) AsAny() any { return u.any } + // Returns a pointer to the underlying variant's property, if present. -func (u BetaMessageCountTokensParamsToolUnion) GetMaxContentTokens() *int64 { - if vt := u.OfWebFetchTool20250910; vt != nil && vt.MaxContentTokens.Valid() { - return &vt.MaxContentTokens.Value - } else if vt := u.OfWebFetchTool20260209; vt != nil && vt.MaxContentTokens.Valid() { - return &vt.MaxContentTokens.Value - } else if vt := u.OfWebFetchTool20260309; vt != nil && vt.MaxContentTokens.Valid() { - return &vt.MaxContentTokens.Value +func (u betaMessageCountTokensParamsToolUnionConfigsWait) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BetaBrowserWaitConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *BetaComputerWaitConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) } return nil } -// Returns a pointer to the underlying variant's AllowedCallers property, if -// present. -func (u BetaMessageCountTokensParamsToolUnion) GetAllowedCallers() []string { - if vt := u.OfTool; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfBashTool20241022; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfBashTool20250124; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfCodeExecutionTool20250522; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfCodeExecutionTool20250825; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfCodeExecutionTool20260120; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfComputerUseTool20241022; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfMemoryTool20250818; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfComputerUseTool20250124; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfTextEditor20241022; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfComputerUseTool20251124; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfTextEditor20250124; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfTextEditor20250429; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfTextEditor20250728; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfWebSearchTool20250305; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfWebFetchTool20250910; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfWebSearchTool20260209; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfWebFetchTool20260209; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfWebFetchTool20260309; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfAdvisorTool20260301; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfToolSearchToolRegex20251119; vt != nil { - return vt.AllowedCallers +// Returns a pointer to the underlying variant's property, if present. +func (u betaMessageCountTokensParamsToolUnionConfigsWait) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BetaBrowserWaitConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *BetaComputerWaitConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) } return nil } -// Returns a pointer to the underlying variant's CacheControl property, if present. -func (u BetaMessageCountTokensParamsToolUnion) GetCacheControl() *BetaCacheControlEphemeralParam { - if vt := u.OfTool; vt != nil { - return &vt.CacheControl - } else if vt := u.OfBashTool20241022; vt != nil { - return &vt.CacheControl - } else if vt := u.OfBashTool20250124; vt != nil { - return &vt.CacheControl - } else if vt := u.OfCodeExecutionTool20250522; vt != nil { - return &vt.CacheControl - } else if vt := u.OfCodeExecutionTool20250825; vt != nil { - return &vt.CacheControl - } else if vt := u.OfCodeExecutionTool20260120; vt != nil { - return &vt.CacheControl - } else if vt := u.OfComputerUseTool20241022; vt != nil { - return &vt.CacheControl - } else if vt := u.OfMemoryTool20250818; vt != nil { - return &vt.CacheControl - } else if vt := u.OfComputerUseTool20250124; vt != nil { - return &vt.CacheControl - } else if vt := u.OfTextEditor20241022; vt != nil { - return &vt.CacheControl - } else if vt := u.OfComputerUseTool20251124; vt != nil { - return &vt.CacheControl - } else if vt := u.OfTextEditor20250124; vt != nil { - return &vt.CacheControl - } else if vt := u.OfTextEditor20250429; vt != nil { - return &vt.CacheControl - } else if vt := u.OfTextEditor20250728; vt != nil { - return &vt.CacheControl - } else if vt := u.OfWebSearchTool20250305; vt != nil { - return &vt.CacheControl - } else if vt := u.OfWebFetchTool20250910; vt != nil { - return &vt.CacheControl - } else if vt := u.OfWebSearchTool20260209; vt != nil { - return &vt.CacheControl - } else if vt := u.OfWebFetchTool20260209; vt != nil { - return &vt.CacheControl - } else if vt := u.OfWebFetchTool20260309; vt != nil { - return &vt.CacheControl - } else if vt := u.OfAdvisorTool20260301; vt != nil { - return &vt.CacheControl - } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil { - return &vt.CacheControl - } else if vt := u.OfToolSearchToolRegex20251119; vt != nil { - return &vt.CacheControl - } else if vt := u.OfMCPToolset; vt != nil { - return &vt.CacheControl +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u betaMessageCountTokensParamsToolUnionConfigs) GetZoom() (res betaMessageCountTokensParamsToolUnionConfigsZoom) { + switch vt := u.any.(type) { + case *BetaBrowserToolsetConfigsParam: + res.any = &vt.Zoom + case *BetaComputerToolsetConfigsParam: + res.any = &vt.Zoom + } + return res +} + +// Can have the runtime types [*BetaBrowserZoomConfigParam], +// [*BetaComputerZoomConfigParam] +type betaMessageCountTokensParamsToolUnionConfigsZoom struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BetaBrowserZoomConfigParam: +// case *anthropic.BetaComputerZoomConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u betaMessageCountTokensParamsToolUnionConfigsZoom) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u betaMessageCountTokensParamsToolUnionConfigsZoom) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BetaBrowserZoomConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *BetaComputerZoomConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) } return nil } -// Returns a pointer to the underlying variant's InputExamples property, if -// present. -func (u BetaMessageCountTokensParamsToolUnion) GetInputExamples() []map[string]any { - if vt := u.OfTool; vt != nil { - return vt.InputExamples - } else if vt := u.OfBashTool20241022; vt != nil { - return vt.InputExamples - } else if vt := u.OfBashTool20250124; vt != nil { - return vt.InputExamples - } else if vt := u.OfComputerUseTool20241022; vt != nil { - return vt.InputExamples - } else if vt := u.OfMemoryTool20250818; vt != nil { - return vt.InputExamples - } else if vt := u.OfComputerUseTool20250124; vt != nil { - return vt.InputExamples - } else if vt := u.OfTextEditor20241022; vt != nil { - return vt.InputExamples - } else if vt := u.OfComputerUseTool20251124; vt != nil { - return vt.InputExamples - } else if vt := u.OfTextEditor20250124; vt != nil { - return vt.InputExamples - } else if vt := u.OfTextEditor20250429; vt != nil { - return vt.InputExamples - } else if vt := u.OfTextEditor20250728; vt != nil { - return vt.InputExamples +// Returns a pointer to the underlying variant's property, if present. +func (u betaMessageCountTokensParamsToolUnionConfigsZoom) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BetaBrowserZoomConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *BetaComputerZoomConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) } return nil } @@ -12361,6 +17891,10 @@ func (u BetaMessageCountTokensParamsToolUnion) GetAllowedDomains() []string { return vt.AllowedDomains } else if vt := u.OfWebFetchTool20260309; vt != nil { return vt.AllowedDomains + } else if vt := u.OfWebSearchTool20260318; vt != nil { + return vt.AllowedDomains + } else if vt := u.OfWebFetchTool20260318; vt != nil { + return vt.AllowedDomains } return nil } @@ -12378,6 +17912,10 @@ func (u BetaMessageCountTokensParamsToolUnion) GetBlockedDomains() []string { return vt.BlockedDomains } else if vt := u.OfWebFetchTool20260309; vt != nil { return vt.BlockedDomains + } else if vt := u.OfWebSearchTool20260318; vt != nil { + return vt.BlockedDomains + } else if vt := u.OfWebFetchTool20260318; vt != nil { + return vt.BlockedDomains } return nil } @@ -12388,6 +17926,8 @@ func (u BetaMessageCountTokensParamsToolUnion) GetUserLocation() *BetaUserLocati return &vt.UserLocation } else if vt := u.OfWebSearchTool20260209; vt != nil { return &vt.UserLocation + } else if vt := u.OfWebSearchTool20260318; vt != nil { + return &vt.UserLocation } return nil } @@ -12400,6 +17940,8 @@ func (u BetaMessageCountTokensParamsToolUnion) GetCitations() *BetaCitationsConf return &vt.Citations } else if vt := u.OfWebFetchTool20260309; vt != nil { return &vt.Citations + } else if vt := u.OfWebFetchTool20260318; vt != nil { + return &vt.Citations } return nil } diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/betamessagebatch.go b/vendor/github.com/anthropics/anthropic-sdk-go/betamessagebatch.go index 4c7a39be3..a70a8018f 100644 --- a/vendor/github.com/anthropics/anthropic-sdk-go/betamessagebatch.go +++ b/vendor/github.com/anthropics/anthropic-sdk-go/betamessagebatch.go @@ -49,11 +49,14 @@ func NewBetaMessageBatchService(opts ...option.RequestOption) (r BetaMessageBatc // can take up to 24 hours to complete. // // Learn more about the Message Batches API in our -// [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) +// [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing) func (r *BetaMessageBatchService) New(ctx context.Context, params BetaMessageBatchNewParams, opts ...option.RequestOption) (res *BetaMessageBatch, err error) { for _, v := range params.Betas { opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) } + if !param.IsOmitted(params.UserProfileID) { + opts = append(opts, option.WithHeader("anthropic-user-profile-id", fmt.Sprintf("%v", params.UserProfileID.Value))) + } opts = slices.Concat(r.Options, opts) opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "message-batches-2024-09-24")}, opts...) path := "v1/messages/batches?beta=true" @@ -66,7 +69,7 @@ func (r *BetaMessageBatchService) New(ctx context.Context, params BetaMessageBat // `results_url` field in the response. // // Learn more about the Message Batches API in our -// [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) +// [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing) func (r *BetaMessageBatchService) Get(ctx context.Context, messageBatchID string, query BetaMessageBatchGetParams, opts ...option.RequestOption) (res *BetaMessageBatch, err error) { for _, v := range query.Betas { opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) @@ -86,7 +89,7 @@ func (r *BetaMessageBatchService) Get(ctx context.Context, messageBatchID string // returned first. // // Learn more about the Message Batches API in our -// [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) +// [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing) func (r *BetaMessageBatchService) List(ctx context.Context, params BetaMessageBatchListParams, opts ...option.RequestOption) (res *pagination.Page[BetaMessageBatch], err error) { var raw *http.Response for _, v := range params.Betas { @@ -111,7 +114,7 @@ func (r *BetaMessageBatchService) List(ctx context.Context, params BetaMessageBa // returned first. // // Learn more about the Message Batches API in our -// [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) +// [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing) func (r *BetaMessageBatchService) ListAutoPaging(ctx context.Context, params BetaMessageBatchListParams, opts ...option.RequestOption) *pagination.PageAutoPager[BetaMessageBatch] { return pagination.NewPageAutoPager(r.List(ctx, params, opts...)) } @@ -122,7 +125,7 @@ func (r *BetaMessageBatchService) ListAutoPaging(ctx context.Context, params Bet // like to delete an in-progress batch, you must first cancel it. // // Learn more about the Message Batches API in our -// [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) +// [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing) func (r *BetaMessageBatchService) Delete(ctx context.Context, messageBatchID string, body BetaMessageBatchDeleteParams, opts ...option.RequestOption) (res *BetaDeletedMessageBatch, err error) { for _, v := range body.Betas { opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) @@ -149,7 +152,7 @@ func (r *BetaMessageBatchService) Delete(ctx context.Context, messageBatchID str // non-interruptible. // // Learn more about the Message Batches API in our -// [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) +// [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing) func (r *BetaMessageBatchService) Cancel(ctx context.Context, messageBatchID string, body BetaMessageBatchCancelParams, opts ...option.RequestOption) (res *BetaMessageBatch, err error) { for _, v := range body.Betas { opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) @@ -172,7 +175,7 @@ func (r *BetaMessageBatchService) Cancel(ctx context.Context, messageBatchID str // requests. Use the `custom_id` field to match results to requests. // // Learn more about the Message Batches API in our -// [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) +// [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing) func (r *BetaMessageBatchService) ResultsStreaming(ctx context.Context, messageBatchID string, query BetaMessageBatchResultsParams, opts ...option.RequestOption) (stream *jsonl.Stream[BetaMessageBatchIndividualResponse]) { var ( raw *http.Response @@ -512,6 +515,11 @@ type BetaMessageBatchNewParams struct { // List of requests for prompt completion. Each is an individual request to create // a Message. Requests []BetaMessageBatchNewParamsRequest `json:"requests,omitzero" api:"required"` + // The user profile ID to attribute the requests in this batch to. Use when acting + // on behalf of a party other than your organization. Requires the `user-profiles` + // beta header. Applies to every request in the batch; an individual request whose + // `user_profile_id` body field conflicts with this header is errored. + UserProfileID param.Opt[string] `header:"anthropic-user-profile-id,omitzero" json:"-"` // Optional header to specify the beta version(s) you want to use. Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` paramObj @@ -534,7 +542,8 @@ type BetaMessageBatchNewParamsRequest struct { CustomID string `json:"custom_id" api:"required"` // Messages API creation parameters for the individual request. // - // See the [Messages API reference](https://docs.claude.com/en/api/messages) for + // See the + // [Messages API reference](https://platform.claude.com/docs/en/api/messages) for // full documentation on available parameters. Params BetaMessageBatchNewParamsRequestParams `json:"params,omitzero" api:"required"` paramObj @@ -550,7 +559,8 @@ func (r *BetaMessageBatchNewParamsRequest) UnmarshalJSON(data []byte) error { // Messages API creation parameters for the individual request. // -// See the [Messages API reference](https://docs.claude.com/en/api/messages) for +// See the +// [Messages API reference](https://platform.claude.com/docs/en/api/messages) for // full documentation on available parameters. // // The properties MaxTokens, Messages, Model are required. @@ -560,8 +570,13 @@ type BetaMessageBatchNewParamsRequestParams struct { // Note that our models may stop _before_ reaching this maximum. This parameter // only specifies the absolute maximum number of tokens to generate. // + // Set to `0` to populate the + // [prompt cache](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#pre-warming-the-cache) + // without generating a response. + // // Different models have different maximum values for this parameter. See - // [models](https://docs.claude.com/en/docs/models-overview) for details. + // [models](https://platform.claude.com/docs/en/about-claude/models/overview) for + // details. MaxTokens int64 `json:"max_tokens" api:"required"` // Input messages. // @@ -624,28 +639,28 @@ type BetaMessageBatchNewParamsRequestParams struct { // { "role": "user", "content": [{ "type": "text", "text": "Hello, Claude" }] } // ``` // - // See [input examples](https://docs.claude.com/en/api/messages-examples). + // See + // [input examples](https://platform.claude.com/docs/en/build-with-claude/working-with-messages). // // Note that if you want to include a - // [system prompt](https://docs.claude.com/en/docs/system-prompts), you can use the - // top-level `system` parameter — there is no `"system"` role for input messages in - // the Messages API. + // [system prompt](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#give-claude-a-role), + // you can use the top-level `system` parameter — there is no `"system"` role for + // input messages in the Messages API. // // There is a limit of 100,000 messages in a single request. Messages []BetaMessageParam `json:"messages,omitzero" api:"required"` - // The model that will complete your prompt.\n\nSee - // [models](https://docs.anthropic.com/en/docs/models-overview) for additional + // The model that will complete your prompt. + // + // See [models](https://docs.anthropic.com/en/docs/models-overview) for additional // details and options. Model Model `json:"model,omitzero" api:"required"` // Specifies the geographic region for inference processing. If not specified, the // workspace's `default_inference_geo` is used. InferenceGeo param.Opt[string] `json:"inference_geo,omitzero"` - // The user profile ID to attribute this request to. Use when acting on behalf of a - // party other than your organization. - UserProfileID param.Opt[string] `json:"user_profile_id,omitzero"` // Whether to incrementally stream the response using server-sent events. // - // See [streaming](https://docs.claude.com/en/api/messages-streaming) for details. + // See [streaming](https://platform.claude.com/docs/en/build-with-claude/streaming) + // for details. Stream param.Opt[bool] `json:"stream,omitzero"` // Amount of randomness injected into the response. // @@ -665,8 +680,7 @@ type BetaMessageBatchNewParamsRequestParams struct { // Used to remove "long tail" low probability responses. // [Learn more technical details here](https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277). // - // Recommended for advanced use cases only. You usually only need to use - // `temperature`. + // Recommended for advanced use cases only. // // Deprecated: Deprecated. Models released after Claude Opus 4.6 do not accept // top_k; any value will be rejected with a 400 error. @@ -675,11 +689,9 @@ type BetaMessageBatchNewParamsRequestParams struct { // // In nucleus sampling, we compute the cumulative distribution over all the options // for each subsequent token in decreasing probability order and cut it off once it - // reaches a particular probability specified by `top_p`. You should either alter - // `temperature` or `top_p`, but not both. + // reaches a particular probability specified by `top_p`. // - // Recommended for advanced use cases only. You usually only need to use - // `temperature`. + // Recommended for advanced use cases only. // // Deprecated: Deprecated. Models released after Claude Opus 4.6 do not support // setting top_p. A value >= 0.99 will be accepted for backwards compatibility, all @@ -687,8 +699,34 @@ type BetaMessageBatchNewParamsRequestParams struct { TopP param.Opt[float64] `json:"top_p,omitzero"` // Container identifier for reuse across requests. Container BetaMessageBatchNewParamsRequestParamsContainerUnion `json:"container,omitzero"` - // The inference speed mode for this request. `"fast"` enables high - // output-tokens-per-second inference. + // The `fallback_credit_token` from a prior refusal's `stop_details`. + // + // When a preceding request was refused and returned a `fallback_credit_token`, + // pass that code here on the retry to have the retry's cache-creation tokens for + // the prefix that was warm on the refused model billed at the cache-read rate. + // Must be redeemed by the same organization and workspace, with the same request + // body (optionally extended by one appended `assistant` message whose content is + // the partial text — with any trailing whitespace stripped from the final text + // block — and paired server-tool blocks streamed before the refusal; the + // appended-assistant form is not available for requests with `output_format` set + // or forced `tool_choice`), on an eligible fallback model, on the same platform, + // and within 5 minutes of the refusal; a mismatch is a 400. A token minted + // mid-server-tool-loop whose partial content was continuable may only be redeemed + // with the appended-assistant form — if an exact-body retry is rejected with a 400 + // saying the token must be redeemed by continuing the partial response, retry with + // the appended-assistant form instead. + // + // When the appended-assistant form is used on a model that otherwise disallows + // assistant-turn prefill, this token also authorizes that one prefill. + FallbackCreditToken BetaMessageBatchNewParamsRequestParamsFallbackCreditTokenUnion `json:"fallback_credit_token,omitzero"` + // Opt-in server-side retry on one or more substitute models when the requested + // model declines for policy reasons. Tried in order: if the first entry also + // declines, the second is tried, and so on. The string "default" requests the + // requested model's server-defined default fallback configuration. + Fallbacks BetaFallbacksParamUnion `json:"fallbacks,omitzero"` + // Inference speed mode. `fast` provides significantly faster output token + // generation at premium pricing. Not all models support `fast`; invalid + // combinations are rejected at create time. // // Any of "standard", "fast". Speed string `json:"speed,omitzero"` @@ -700,6 +738,9 @@ type BetaMessageBatchNewParamsRequestParams struct { // This allows you to control how Claude manages context across multiple requests, // such as whether to clear function results or not. ContextManagement BetaContextManagementConfigParam `json:"context_management,omitzero"` + // Request-level diagnostics. Currently carries the previous response id for + // prompt-cache divergence reporting. + Diagnostics BetaDiagnosticsParam `json:"diagnostics,omitzero"` // MCP servers to be utilized in this request MCPServers []BetaRequestMCPServerURLDefinitionParam `json:"mcp_servers,omitzero"` // An object describing metadata about the request. @@ -718,7 +759,8 @@ type BetaMessageBatchNewParamsRequestParams struct { // for this request. // // Anthropic offers different levels of service for your API requests. See - // [service-tiers](https://docs.claude.com/en/api/service-tiers) for details. + // [service-tiers](https://platform.claude.com/docs/en/api/service-tiers) for + // details. // // Any of "auto", "standard_only". ServiceTier string `json:"service_tier,omitzero"` @@ -736,7 +778,7 @@ type BetaMessageBatchNewParamsRequestParams struct { // // A system prompt is a way of providing context and instructions to Claude, such // as specifying a particular goal or role. See our - // [guide to system prompts](https://docs.claude.com/en/docs/system-prompts). + // [guide to system prompts](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#give-claude-a-role). System []BetaTextBlockParam `json:"system,omitzero"` // Configuration for enabling Claude's extended thinking. // @@ -745,7 +787,7 @@ type BetaMessageBatchNewParamsRequestParams struct { // tokens and counts towards your `max_tokens` limit. // // See - // [extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking) + // [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking) // for details. Thinking BetaThinkingConfigParamUnion `json:"thinking,omitzero"` // How the model should use the provided tools. The model can use a specific tool, @@ -760,9 +802,9 @@ type BetaMessageBatchNewParamsRequestParams struct { // // There are two types of tools: **client tools** and **server tools**. The // behavior described below applies to client tools. For - // [server tools](https://docs.claude.com/en/docs/agents-and-tools/tool-use/overview#server-tools), + // [server tools](https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools), // see their individual documentation as each has its own behavior (e.g., the - // [web search tool](https://docs.claude.com/en/docs/agents-and-tools/tool-use/web-search-tool)). + // [web search tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool)). // // Each tool definition includes: // @@ -831,7 +873,9 @@ type BetaMessageBatchNewParamsRequestParams struct { // functions, or more generally whenever you want the model to produce a particular // JSON structure of output. // - // See our [guide](https://docs.claude.com/en/docs/tool-use) for more details. + // See our + // [guide](https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview) + // for more details. Tools []BetaToolUnionParam `json:"tools,omitzero"` paramObj } @@ -878,6 +922,31 @@ func (u *BetaMessageBatchNewParamsRequestParamsContainerUnion) asAny() any { return nil } +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaMessageBatchNewParamsRequestParamsFallbackCreditTokenUnion struct { + OfString param.Opt[string] `json:",omitzero,inline"` + OfFallbackCreditToken *BetaFallbackCreditTokenParam `json:",omitzero,inline"` + paramUnion +} + +func (u BetaMessageBatchNewParamsRequestParamsFallbackCreditTokenUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfString, u.OfFallbackCreditToken) +} +func (u *BetaMessageBatchNewParamsRequestParamsFallbackCreditTokenUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *BetaMessageBatchNewParamsRequestParamsFallbackCreditTokenUnion) asAny() any { + if !param.IsOmitted(u.OfString) { + return &u.OfString.Value + } else if !param.IsOmitted(u.OfFallbackCreditToken) { + return u.OfFallbackCreditToken + } + return nil +} + type BetaMessageBatchGetParams struct { // Optional header to specify the beta version(s) you want to use. Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` @@ -904,7 +973,7 @@ type BetaMessageBatchListParams struct { // `url.Values`. func (r BetaMessageBatchListParams) URLQuery() (v url.Values, err error) { return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ - ArrayFormat: apiquery.ArrayQueryFormatComma, + ArrayFormat: apiquery.ArrayQueryFormatBrackets, NestedFormat: apiquery.NestedQueryFormatBrackets, }) } diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/betamessageutil.go b/vendor/github.com/anthropics/anthropic-sdk-go/betamessageutil.go index 2ee4755b6..efa9c166d 100644 --- a/vendor/github.com/anthropics/anthropic-sdk-go/betamessageutil.go +++ b/vendor/github.com/anthropics/anthropic-sdk-go/betamessageutil.go @@ -4,13 +4,15 @@ import ( "encoding/json" "fmt" + "github.com/tidwall/sjson" + "github.com/anthropics/anthropic-sdk-go/internal/paramutil" "github.com/anthropics/anthropic-sdk-go/packages/param" ) // Accumulate builds up the Message incrementally from a MessageStreamEvent. The Message then can be used as -// any other Message, except with the caveat that the Message.JSON field which normally can be used to inspect -// the JSON sent over the network may not be populated fully. +// any other Message, including the Message.JSON field, which holds the wire JSON with the streamed deltas +// applied and is complete once message_stop arrives. // // message := anthropic.Message{} // for stream.Next() { @@ -22,76 +24,157 @@ func (acc *BetaMessage) Accumulate(event BetaRawMessageStreamEventUnion) error { return fmt.Errorf("accumulate: cannot accumulate into nil Message") } - switch event := event.AsAny().(type) { - case BetaRawMessageStartEvent: + switch event.Type { + case "message_start": *acc = event.Message - case BetaRawMessageDeltaEvent: + case "message_delta": + // stop_reason, stop_sequence and stop_details are always sent and null is + // their final value when the turn carries no such detail. acc.StopReason = event.Delta.StopReason acc.StopSequence = event.Delta.StopSequence + acc.StopDetails = event.Delta.StopDetails + if event.Delta.JSON.Container.Valid() { + acc.Container = event.Delta.Container + } + // Every usage count here is a cumulative whole-message total, so it + // overwrites rather than adds; the ones that do not apply are omitted, and + // message_start keeps the last word on those. acc.Usage.OutputTokens = event.Usage.OutputTokens - acc.Usage.Iterations = event.Usage.Iterations - acc.ContextManagement = event.ContextManagement - case BetaRawContentBlockStartEvent: + if event.Usage.JSON.InputTokens.Valid() { + acc.Usage.InputTokens = event.Usage.InputTokens + } + if event.Usage.JSON.CacheCreationInputTokens.Valid() { + acc.Usage.CacheCreationInputTokens = event.Usage.CacheCreationInputTokens + } + if event.Usage.JSON.CacheReadInputTokens.Valid() { + acc.Usage.CacheReadInputTokens = event.Usage.CacheReadInputTokens + } + if event.Usage.JSON.ServerToolUse.Valid() { + acc.Usage.ServerToolUse = event.Usage.ServerToolUse + } + if event.Usage.JSON.OutputTokensDetails.Valid() { + acc.Usage.OutputTokensDetails = event.Usage.OutputTokensDetails + } + if event.Usage.JSON.FallbackCredit.Valid() { + acc.Usage.FallbackCredit = event.Usage.FallbackCredit + } + if event.Usage.JSON.Iterations.Valid() { + acc.Usage.Iterations = event.Usage.Iterations + } + if event.JSON.ContextManagement.Valid() { + acc.ContextManagement = event.ContextManagement + acc.JSON.raw, _ = sjson.SetRaw(acc.JSON.raw, "context_management", event.ContextManagement.RawJSON()) + } + acc.JSON.raw = mergeRaw(acc.JSON.raw, "", event.Delta.JSON.raw) + acc.JSON.raw = mergeRaw(acc.JSON.raw, "usage", event.Usage.RawJSON()) + case "content_block_start": + // Content blocks start in index order with no gaps: a start event always + // addresses the slot right after the previous block, even when deltas and + // stops for still-open blocks interleave after it. + if event.Index != int64(len(acc.Content)) { + return fmt.Errorf("received event of type %s for content block at index %d, expected index %d", event.Type, event.Index, len(acc.Content)) + } acc.Content = append(acc.Content, BetaContentBlockUnion{}) - err := acc.Content[len(acc.Content)-1].UnmarshalJSON([]byte(event.ContentBlock.RawJSON())) + err := acc.Content[event.Index].UnmarshalJSON([]byte(event.ContentBlock.RawJSON())) if err != nil { return err } - case BetaRawContentBlockDeltaEvent: - if len(acc.Content) == 0 { - return fmt.Errorf("received event of type %s but there was no content block", event.Type) + // The final hop's fallback block names the model that served the response; + // non-streaming responses already report that model, so relabel the + // accumulated snapshot to match. Last block wins on multi-hop chains. + if fallback, ok := acc.Content[event.Index].AsAny().(BetaFallbackBlock); ok { + acc.Model = fallback.To.Model + acc.JSON.raw, _ = sjson.SetRaw(acc.JSON.raw, "model", jsonString(string(fallback.To.Model))) } - cb := &acc.Content[len(acc.Content)-1] - switch delta := event.Delta.AsAny().(type) { - case BetaTextDelta: - cb.Text += delta.Text - case BetaInputJSONDelta: - if len(delta.PartialJSON) != 0 { + case "content_block_delta": + if err := checkContentBlockIndex(event.Type, event.Index, len(acc.Content)); err != nil { + return err + } + cb := &acc.Content[event.Index] + switch event.Delta.Type { + case "text_delta": + cb.Text += event.Delta.Text + case "input_json_delta": + if len(event.Delta.PartialJSON) != 0 { if string(cb.Input) == "{}" { - cb.Input = []byte(delta.PartialJSON) + cb.Input = []byte(event.Delta.PartialJSON) } else { - cb.Input = append(cb.Input, []byte(delta.PartialJSON)...) + cb.Input = append(cb.Input, event.Delta.PartialJSON...) } } - case BetaThinkingDelta: - cb.Thinking += delta.Thinking - case BetaSignatureDelta: - cb.Signature += delta.Signature - case BetaCitationsDelta: + case "thinking_delta": + cb.Thinking += event.Delta.Thinking + case "signature_delta": + cb.Signature += event.Delta.Signature + case "citations_delta": citation := BetaTextCitationUnion{} - err := citation.UnmarshalJSON([]byte(delta.Citation.RawJSON())) + err := citation.UnmarshalJSON([]byte(event.Delta.Citation.RawJSON())) if err != nil { return fmt.Errorf("could not unmarshal citation delta into citation type: %w", err) } cb.Citations = append(cb.Citations, citation) - case BetaCompactionContentBlockDelta: - cb.Content.OfString = delta.Content + case "compaction_delta": + cb.Content.OfString = event.Delta.Content + cb.EncryptedContent = event.Delta.EncryptedContent } - case BetaRawMessageStopEvent: - // Re-marshal the accumulated message to update JSON.raw so that AsAny() - // returns the accumulated data rather than the original stream data - accJSON, err := json.Marshal(acc) - if err != nil { - return fmt.Errorf("error converting accumulated message to JSON: %w", err) + case "message_stop": + // A block whose stop event never arrived has not been refreshed yet. + for i := range acc.Content { + refreshBetaContentBlockRaw(&acc.Content[i]) } - acc.JSON.raw = string(accJSON) - case BetaRawContentBlockStopEvent: - // Re-marshal the content block to update JSON.raw so that AsAny() - // returns the accumulated data rather than the original stream data - if len(acc.Content) == 0 { - return fmt.Errorf("received event of type %s but there was no content block", event.Type) - } - contentBlock := &acc.Content[len(acc.Content)-1] - cbJSON, err := json.Marshal(contentBlock) - if err != nil { - return fmt.Errorf("error converting content block to JSON: %w", err) + acc.JSON.raw, _ = sjson.SetRaw(acc.JSON.raw, "content", rawArray(acc.Content)) + case "content_block_stop": + if err := checkContentBlockIndex(event.Type, event.Index, len(acc.Content)); err != nil { + return err } - contentBlock.JSON.raw = string(cbJSON) + refreshBetaContentBlockRaw(&acc.Content[event.Index]) } return nil } +// refreshBetaContentBlockRaw overlays the delta-mutated fields onto the block's +// wire JSON, leaving a block that received no deltas byte for byte. +func refreshBetaContentBlockRaw(cb *BetaContentBlockUnion) { + raw := cb.JSON.raw + if cb.Text != "" { + raw, _ = sjson.SetRaw(raw, "text", jsonString(cb.Text)) + } + if cb.Thinking != "" { + raw, _ = sjson.SetRaw(raw, "thinking", jsonString(cb.Thinking)) + } + if cb.Signature != "" { + raw, _ = sjson.SetRaw(raw, "signature", jsonString(cb.Signature)) + } + if json.Valid(cb.Input) { + raw, _ = sjson.SetRaw(raw, "input", string(cb.Input)) + } else if len(cb.Input) > 0 { + // A cut-off tool call left non-JSON input; empty it so the block marshals. + cb.Input = json.RawMessage(`{}`) + } + if len(cb.Citations) > 0 { + raw, _ = sjson.SetRaw(raw, "citations", rawArray(cb.Citations)) + } + if cb.Content.OfString != "" { + raw, _ = sjson.SetRaw(raw, "content", jsonString(cb.Content.OfString)) + } + if cb.EncryptedContent != "" { + raw, _ = sjson.SetRaw(raw, "encrypted_content", jsonString(cb.EncryptedContent)) + } + cb.JSON.raw = raw +} + +// ParseOutput finds the first text content block in the message and unmarshals it +// into dest. This is useful for streaming workflows where you accumulate the message +// first and then parse the structured output. +// +// var msg anthropic.BetaMessage +// for stream.Next() { msg.Accumulate(stream.Current()) } +// msg.ParseOutput(&myStruct) +func (r *BetaMessage) ParseOutput(dest any) error { + return parseOutputContent(r, dest) +} + // Param converters func (r BetaContentBlockUnion) ToParam() BetaContentBlockParamUnion { @@ -147,6 +230,22 @@ func (r BetaAdvisorToolResultBlock) ToParam() BetaAdvisorToolResultBlockParam { var p BetaAdvisorToolResultBlockParam p.Type = r.Type p.ToolUseID = r.ToolUseID + switch { + case r.Content.JSON.ErrorCode.Valid(): + p.Content.OfRequestAdvisorToolResultError = &BetaAdvisorToolResultErrorParam{ + ErrorCode: BetaAdvisorToolResultErrorParamErrorCode(r.Content.ErrorCode), + } + case r.Content.JSON.EncryptedContent.Valid(): + p.Content.OfRequestAdvisorRedactedResultBlock = &BetaAdvisorRedactedResultBlockParam{ + EncryptedContent: r.Content.EncryptedContent, + StopReason: paramutil.ToOpt(r.Content.StopReason, r.Content.JSON.StopReason), + } + default: + p.Content.OfRequestAdvisorResultBlock = &BetaAdvisorResultBlockParam{ + Text: r.Content.Text, + StopReason: paramutil.ToOpt(r.Content.StopReason, r.Content.JSON.StopReason), + } + } return p } @@ -185,6 +284,11 @@ func (variant BetaCompactionBlock) toParamUnion() BetaContentBlockParamUnion { return BetaContentBlockParamUnion{OfCompaction: &p} } +func (variant BetaFallbackBlock) toParamUnion() BetaContentBlockParamUnion { + p := variant.ToParam() + return BetaContentBlockParamUnion{OfFallback: &p} +} + func (r BetaMessage) ToParam() BetaMessageParam { var p BetaMessageParam p.Role = BetaMessageParamRole(r.Role) @@ -234,6 +338,7 @@ func (citationVariant BetaCitationPageLocation) toParamUnion() BetaTextCitationP var citationParam BetaCitationPageLocationParam citationParam.Type = citationVariant.Type citationParam.DocumentTitle = paramutil.ToOpt(citationVariant.DocumentTitle, citationVariant.JSON.DocumentTitle) + citationParam.CitedText = citationVariant.CitedText citationParam.DocumentIndex = citationVariant.DocumentIndex citationParam.EndPageNumber = citationVariant.EndPageNumber citationParam.StartPageNumber = citationVariant.StartPageNumber @@ -256,6 +361,8 @@ func (citationVariant BetaCitationsWebSearchResultLocation) toParamUnion() BetaT citationParam.Type = citationVariant.Type citationParam.CitedText = citationVariant.CitedText citationParam.Title = paramutil.ToOpt(citationVariant.Title, citationVariant.JSON.Title) + citationParam.EncryptedIndex = citationVariant.EncryptedIndex + citationParam.URL = citationVariant.URL return BetaTextCitationParamUnion{OfWebSearchResultLocation: &citationParam} } @@ -265,8 +372,9 @@ func (citationVariant BetaCitationSearchResultLocation) toParamUnion() BetaTextC citationParam.CitedText = citationVariant.CitedText citationParam.Title = paramutil.ToOpt(citationVariant.Title, citationVariant.JSON.Title) citationParam.EndBlockIndex = citationVariant.EndBlockIndex - citationParam.StartBlockIndex = citationVariant.StartBlockIndex + citationParam.SearchResultIndex = citationVariant.SearchResultIndex citationParam.Source = citationVariant.Source + citationParam.StartBlockIndex = citationVariant.StartBlockIndex return BetaTextCitationParamUnion{OfSearchResultLocation: &citationParam} } @@ -284,9 +392,45 @@ func (r BetaToolUseBlock) ToParam() BetaToolUseBlockParam { p.ID = r.ID p.Input = r.Input p.Name = r.Name + p.ToolsetName = paramutil.ToOpt(r.ToolsetName, r.JSON.ToolsetName) + if r.JSON.Caller.Valid() { + p.Caller = r.Caller.toParam() + } return p } +// toParam converts a caller. The other three caller unions share this layout +// and convert through it. +func (r BetaToolUseBlockCallerUnion) toParam() BetaToolUseBlockParamCallerUnion { + var p BetaToolUseBlockParamCallerUnion + switch v := r.AsAny().(type) { + case BetaDirectCaller: + c := v.ToParam() + p.OfDirect = &c + case BetaServerToolCaller: + c := v.ToParam() + p.OfCodeExecution20250825 = &c + case BetaServerToolCaller20260120: + c := v.ToParam() + p.OfCodeExecution20260120 = &c + default: + p = param.Override[BetaToolUseBlockParamCallerUnion](json.RawMessage(r.RawJSON())) + } + return p +} + +func (r BetaServerToolUseBlockCallerUnion) toParam() BetaServerToolUseBlockParamCallerUnion { + return BetaServerToolUseBlockParamCallerUnion(BetaToolUseBlockCallerUnion(r).toParam()) +} + +func (r BetaWebSearchToolResultBlockCallerUnion) toParam() BetaWebSearchToolResultBlockParamCallerUnion { + return BetaWebSearchToolResultBlockParamCallerUnion(BetaToolUseBlockCallerUnion(r).toParam()) +} + +func (r BetaWebFetchToolResultBlockCallerUnion) toParam() BetaWebFetchToolResultBlockParamCallerUnion { + return BetaWebFetchToolResultBlockParamCallerUnion(BetaToolUseBlockCallerUnion(r).toParam()) +} + func (r BetaWebSearchResultBlock) ToParam() BetaWebSearchResultBlockParam { var p BetaWebSearchResultBlockParam p.Type = r.Type @@ -302,7 +446,9 @@ func (r BetaWebSearchToolResultBlock) ToParam() BetaWebSearchToolResultBlockPara p.Type = r.Type p.ToolUseID = r.ToolUseID - if len(r.Content.OfBetaWebSearchResultBlockArray) > 0 { + if r.Content.JSON.OfBetaWebSearchResultBlockArray.Valid() { + // content is required, so send [] rather than omitting it. + p.Content.OfResultBlock = make([]BetaWebSearchResultBlockParam, 0, len(r.Content.OfBetaWebSearchResultBlockArray)) for _, block := range r.Content.OfBetaWebSearchResultBlockArray { p.Content.OfResultBlock = append(p.Content.OfResultBlock, block.ToParam()) } @@ -312,6 +458,9 @@ func (r BetaWebSearchToolResultBlock) ToParam() BetaWebSearchToolResultBlockPara ErrorCode: r.Content.ErrorCode, } } + if r.JSON.Caller.Valid() { + p.Caller = r.Caller.toParam() + } return p } @@ -319,6 +468,16 @@ func (r BetaWebFetchToolResultBlock) ToParam() BetaWebFetchToolResultBlockParam var p BetaWebFetchToolResultBlockParam p.Type = r.Type p.ToolUseID = r.ToolUseID + if r.Content.JSON.ErrorCode.Valid() { + p.Content.OfRequestWebFetchToolResultError = &BetaWebFetchToolResultErrorBlockParam{ + ErrorCode: r.Content.ErrorCode, + } + } else { + p.Content = param.Override[BetaWebFetchToolResultBlockParamContentUnion](json.RawMessage(r.Content.RawJSON())) + } + if r.JSON.Caller.Valid() { + p.Caller = r.Caller.toParam() + } return p } @@ -345,6 +504,9 @@ func (r BetaServerToolUseBlock) ToParam() BetaServerToolUseBlockParam { p.ID = r.ID p.Input = r.Input p.Name = BetaServerToolUseBlockParamName(r.Name) + if r.JSON.Caller.Valid() { + p.Caller = r.Caller.toParam() + } return p } @@ -358,7 +520,7 @@ func (r BetaTextEditorCodeExecutionToolResultBlock) ToParam() BetaTextEditorCode ErrorMessage: paramutil.ToOpt(r.Content.ErrorMessage, r.Content.JSON.ErrorMessage), } } else { - p.Content = param.Override[BetaTextEditorCodeExecutionToolResultBlockParamContentUnion](r.Content.RawJSON()) + p.Content = param.Override[BetaTextEditorCodeExecutionToolResultBlockParamContentUnion](json.RawMessage(r.Content.RawJSON())) } return p } @@ -367,9 +529,12 @@ func (r BetaMCPToolResultBlock) ToParam() BetaRequestMCPToolResultBlockParam { var p BetaRequestMCPToolResultBlockParam p.Type = r.Type p.ToolUseID = r.ToolUseID + p.IsError = paramutil.ToOpt(r.IsError, r.JSON.IsError) if r.Content.JSON.OfString.Valid() { p.Content.OfString = paramutil.ToOpt(r.Content.OfString, r.Content.JSON.OfString) - } else { + } else if r.Content.JSON.OfBetaMCPToolResultBlockContent.Valid() { + // Send [] for an empty result rather than omitting content. + p.Content.OfBetaMCPToolResultBlockContent = make([]BetaTextBlockParam, 0, len(r.Content.OfBetaMCPToolResultBlockContent)) for _, block := range r.Content.OfBetaMCPToolResultBlockContent { p.Content.OfBetaMCPToolResultBlockContent = append(p.Content.OfBetaMCPToolResultBlockContent, block.ToParam()) } @@ -388,6 +553,8 @@ func (r BetaBashCodeExecutionToolResultBlock) ToParam() BetaBashCodeExecutionToo } } else { requestBashContentResult := &BetaBashCodeExecutionResultBlockParam{ + // content is required, so send [] rather than omitting it. + Content: make([]BetaBashCodeExecutionOutputBlockParam, 0, len(r.Content.Content)), ReturnCode: r.Content.ReturnCode, Stderr: r.Content.Stderr, Stdout: r.Content.Stdout, @@ -412,19 +579,30 @@ func (r BetaCodeExecutionToolResultBlock) ToParam() BetaCodeExecutionToolResultB var p BetaCodeExecutionToolResultBlockParam p.Type = r.Type p.ToolUseID = r.ToolUseID - if r.Content.JSON.ErrorCode.Valid() { + // content is required, so send [] rather than omitting it. + files := make([]BetaCodeExecutionOutputBlockParam, 0, len(r.Content.Content)) + for _, block := range r.Content.Content { + files = append(files, block.ToParam()) + } + switch { + case r.Content.JSON.ErrorCode.Valid(): p.Content.OfError = &BetaCodeExecutionToolResultErrorParam{ ErrorCode: r.Content.ErrorCode, } - } else { + case r.Content.JSON.EncryptedStdout.Valid(): + p.Content.OfRequestEncryptedCodeExecutionResultBlock = &BetaEncryptedCodeExecutionResultBlockParam{ + Content: files, + EncryptedStdout: r.Content.EncryptedStdout, + ReturnCode: r.Content.ReturnCode, + Stderr: r.Content.Stderr, + } + default: p.Content.OfResultBlock = &BetaCodeExecutionResultBlockParam{ + Content: files, ReturnCode: r.Content.ReturnCode, Stderr: r.Content.Stderr, Stdout: r.Content.Stdout, } - for _, block := range r.Content.Content { - p.Content.OfResultBlock.Content = append(p.Content.OfResultBlock.Content, block.ToParam()) - } } return p } @@ -442,10 +620,14 @@ func (r BetaToolSearchToolResultBlock) ToParam() BetaToolSearchToolResultBlockPa p.ToolUseID = r.ToolUseID if r.Content.JSON.ErrorCode.Valid() { p.Content.OfRequestToolSearchToolResultError = &BetaToolSearchToolResultErrorParam{ - ErrorCode: BetaToolSearchToolResultErrorParamErrorCode(r.Content.ErrorCode), + ErrorCode: BetaToolSearchToolResultErrorParamErrorCode(r.Content.ErrorCode), + ErrorMessage: paramutil.ToOpt(r.Content.ErrorMessage, r.Content.JSON.ErrorMessage), } } else { - p.Content.OfRequestToolSearchToolSearchResultBlock = &BetaToolSearchToolSearchResultBlockParam{} + p.Content.OfRequestToolSearchToolSearchResultBlock = &BetaToolSearchToolSearchResultBlockParam{ + // tool_references is required, so send [] rather than omitting it. + ToolReferences: make([]BetaToolReferenceBlockParam, 0, len(r.Content.ToolReferences)), + } for _, block := range r.Content.ToolReferences { p.Content.OfRequestToolSearchToolSearchResultBlock.ToolReferences = append( p.Content.OfRequestToolSearchToolSearchResultBlock.ToolReferences, @@ -466,6 +648,20 @@ func (r BetaToolReferenceBlock) ToParam() BetaToolReferenceBlockParam { func (r BetaCompactionBlock) ToParam() BetaCompactionBlockParam { var p BetaCompactionBlockParam p.Type = r.Type - p.Content = param.NewOpt(r.Content) + // A failed compaction has null content, which must stay null rather than + // become "". + p.Content = paramutil.ToOpt(r.Content, r.JSON.Content) + p.EncryptedContent = paramutil.ToOpt(r.EncryptedContent, r.JSON.EncryptedContent) + return p +} + +func (r BetaFallbackBlock) ToParam() BetaFallbackBlockParam { + var p BetaFallbackBlockParam + p.Type = r.Type + p.From = BetaFallbackInfoParam{Model: r.From.Model} + p.To = BetaFallbackInfoParam{Model: r.To.Model} + if r.JSON.Trigger.Valid() { + p.Trigger = json.RawMessage(r.Trigger.RawJSON()) + } return p } diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/betamodel.go b/vendor/github.com/anthropics/anthropic-sdk-go/betamodel.go index b88ec9be9..ef703f7f5 100644 --- a/vendor/github.com/anthropics/anthropic-sdk-go/betamodel.go +++ b/vendor/github.com/anthropics/anthropic-sdk-go/betamodel.go @@ -213,6 +213,10 @@ func (r *BetaModelCapabilities) UnmarshalJSON(data []byte) error { type BetaModelInfo struct { // Unique model identifier. ID string `json:"id" api:"required"` + // Model IDs this model accepts as `fallbacks[i].model` on the Messages API. An + // empty list means the `fallbacks` parameter is not supported for this model as + // primary. + AllowedFallbackModels []string `json:"allowed_fallback_models" api:"required"` // Model capability information. Capabilities BetaModelCapabilities `json:"capabilities" api:"required"` // RFC 3339 datetime string representing the time at which the model was released. @@ -230,15 +234,16 @@ type BetaModelInfo struct { Type constant.Model `json:"type" default:"model"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { - ID respjson.Field - Capabilities respjson.Field - CreatedAt respjson.Field - DisplayName respjson.Field - MaxInputTokens respjson.Field - MaxTokens respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string + ID respjson.Field + AllowedFallbackModels respjson.Field + Capabilities respjson.Field + CreatedAt respjson.Field + DisplayName respjson.Field + MaxInputTokens respjson.Field + MaxTokens respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string } `json:"-"` } @@ -315,7 +320,7 @@ type BetaModelListParams struct { // URLQuery serializes [BetaModelListParams]'s query parameters as `url.Values`. func (r BetaModelListParams) URLQuery() (v url.Values, err error) { return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ - ArrayFormat: apiquery.ArrayQueryFormatComma, + ArrayFormat: apiquery.ArrayQueryFormatBrackets, NestedFormat: apiquery.NestedQueryFormatBrackets, }) } diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/betaorganization.go b/vendor/github.com/anthropics/anthropic-sdk-go/betaorganization.go new file mode 100644 index 000000000..2cecf3797 --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/betaorganization.go @@ -0,0 +1,98 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +package anthropic + +import ( + "context" + "net/http" + "slices" + + "github.com/anthropics/anthropic-sdk-go/internal/apijson" + "github.com/anthropics/anthropic-sdk-go/internal/requestconfig" + "github.com/anthropics/anthropic-sdk-go/option" + "github.com/anthropics/anthropic-sdk-go/packages/respjson" + "github.com/anthropics/anthropic-sdk-go/shared/constant" +) + +// BetaOrganizationService contains methods and other services that help with +// interacting with the anthropic API. +// +// Note, unlike clients, this service does not read variables from the environment +// automatically. You should not instantiate this service directly, and instead use +// the [NewBetaOrganizationService] method instead. +type BetaOrganizationService struct { + Options []option.RequestOption + APIKeys BetaOrganizationAPIKeyService + ExternalKeys BetaOrganizationExternalKeyService + Federation BetaOrganizationFederationService + Invites BetaOrganizationInviteService + ServiceAccounts BetaOrganizationServiceAccountService + Users BetaOrganizationUserService + Workspaces BetaOrganizationWorkspaceService + RateLimits BetaOrganizationRateLimitService +} + +// NewBetaOrganizationService generates a new service that applies the given +// options to each request. These options are applied after the parent client's +// options (if there is one), and before any request-specific options. +func NewBetaOrganizationService(opts ...option.RequestOption) (r BetaOrganizationService) { + r = BetaOrganizationService{} + r.Options = opts + r.APIKeys = NewBetaOrganizationAPIKeyService(opts...) + r.ExternalKeys = NewBetaOrganizationExternalKeyService(opts...) + r.Federation = NewBetaOrganizationFederationService(opts...) + r.Invites = NewBetaOrganizationInviteService(opts...) + r.ServiceAccounts = NewBetaOrganizationServiceAccountService(opts...) + r.Users = NewBetaOrganizationUserService(opts...) + r.Workspaces = NewBetaOrganizationWorkspaceService(opts...) + r.RateLimits = NewBetaOrganizationRateLimitService(opts...) + return +} + +// Retrieve information about the organization associated with the authenticated +// API key. +func (r *BetaOrganizationService) Get(ctx context.Context, opts ...option.RequestOption) (res *BetaOrganization, err error) { + opts = slices.Concat(r.Options, opts) + path := "v1/organizations/me?beta=true" + err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...) + return res, err +} + +type BetaOrganization struct { + // ID of the Organization. + ID string `json:"id" api:"required" format:"uuid"` + // Name of the Organization. + Name string `json:"name" api:"required"` + // Object type. + // + // For Organizations, this is always `"organization"`. + Type constant.Organization `json:"type" default:"organization"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + Name respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaOrganization) RawJSON() string { return r.JSON.raw } +func (r *BetaOrganization) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaOrganizationRole string + +const ( + BetaOrganizationRoleAdmin BetaOrganizationRole = "admin" + BetaOrganizationRoleBilling BetaOrganizationRole = "billing" + BetaOrganizationRoleClaudeCodeUser BetaOrganizationRole = "claude_code_user" + BetaOrganizationRoleDeveloper BetaOrganizationRole = "developer" + BetaOrganizationRoleManaged BetaOrganizationRole = "managed" + BetaOrganizationRoleMembershipAdmin BetaOrganizationRole = "membership_admin" + BetaOrganizationRoleOwner BetaOrganizationRole = "owner" + BetaOrganizationRolePrimaryOwner BetaOrganizationRole = "primary_owner" + BetaOrganizationRoleUser BetaOrganizationRole = "user" +) diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/betaorganizationapikey.go b/vendor/github.com/anthropics/anthropic-sdk-go/betaorganizationapikey.go new file mode 100644 index 000000000..4536b2dbb --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/betaorganizationapikey.go @@ -0,0 +1,469 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +package anthropic + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/url" + "slices" + "time" + + "github.com/anthropics/anthropic-sdk-go/internal/apijson" + "github.com/anthropics/anthropic-sdk-go/internal/apiquery" + "github.com/anthropics/anthropic-sdk-go/internal/requestconfig" + "github.com/anthropics/anthropic-sdk-go/option" + "github.com/anthropics/anthropic-sdk-go/packages/pagination" + "github.com/anthropics/anthropic-sdk-go/packages/param" + "github.com/anthropics/anthropic-sdk-go/packages/respjson" + "github.com/anthropics/anthropic-sdk-go/shared/constant" +) + +// BetaOrganizationAPIKeyService contains methods and other services that help with +// interacting with the anthropic API. +// +// Note, unlike clients, this service does not read variables from the environment +// automatically. You should not instantiate this service directly, and instead use +// the [NewBetaOrganizationAPIKeyService] method instead. +type BetaOrganizationAPIKeyService struct { + Options []option.RequestOption +} + +// NewBetaOrganizationAPIKeyService generates a new service that applies the given +// options to each request. These options are applied after the parent client's +// options (if there is one), and before any request-specific options. +func NewBetaOrganizationAPIKeyService(opts ...option.RequestOption) (r BetaOrganizationAPIKeyService) { + r = BetaOrganizationAPIKeyService{} + r.Options = opts + return +} + +// Get API Key +func (r *BetaOrganizationAPIKeyService) Get(ctx context.Context, apiKeyID string, opts ...option.RequestOption) (res *BetaAPIKey, err error) { + opts = slices.Concat(r.Options, opts) + if apiKeyID == "" { + err = errors.New("missing required api_key_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/organizations/api_keys/%s?beta=true", apiKeyID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...) + return res, err +} + +// Update API Key +func (r *BetaOrganizationAPIKeyService) Update(ctx context.Context, apiKeyID string, body BetaOrganizationAPIKeyUpdateParams, opts ...option.RequestOption) (res *BetaAPIKey, err error) { + opts = slices.Concat(r.Options, opts) + if apiKeyID == "" { + err = errors.New("missing required api_key_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/organizations/api_keys/%s?beta=true", apiKeyID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...) + return res, err +} + +// List API Keys +func (r *BetaOrganizationAPIKeyService) List(ctx context.Context, query BetaOrganizationAPIKeyListParams, opts ...option.RequestOption) (res *pagination.Page[BetaAPIKey], err error) { + var raw *http.Response + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithResponseInto(&raw)}, opts...) + path := "v1/organizations/api_keys?beta=true" + cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, query, &res, opts...) + if err != nil { + return nil, err + } + err = cfg.Execute() + if err != nil { + return nil, err + } + res.SetPageConfig(cfg, raw) + return res, nil +} + +// List API Keys +func (r *BetaOrganizationAPIKeyService) ListAutoPaging(ctx context.Context, query BetaOrganizationAPIKeyListParams, opts ...option.RequestOption) *pagination.PageAutoPager[BetaAPIKey] { + return pagination.NewPageAutoPager(r.List(ctx, query, opts...)) +} + +type BetaAPIKey struct { + // ID of the API key. + ID string `json:"id" api:"required"` + // RFC 3339 datetime string indicating when the API Key was created. + CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"` + // The ID and type of the actor that created the API key, or `null` when the + // creator is not recorded (legacy, workload-identity-federated, or system-created + // keys). + CreatedBy BetaAPIKeyCreatedBy `json:"created_by" api:"required"` + // RFC 3339 datetime string indicating when the API Key expires, or `null` if it + // never expires. + ExpiresAt time.Time `json:"expires_at" api:"required" format:"date-time"` + // Name of the API key. + Name string `json:"name" api:"required"` + // Partially redacted hint for the API key. + PartialKeyHint string `json:"partial_key_hint" api:"required"` + // The principal the API key acts as (a User or a Service Account), or `null` if + // the API key is not bound to a principal. + Principal BetaAPIKeyPrincipalUnion `json:"principal" api:"required"` + // Where the API key belongs: its Workspace + // (`{"type": "workspace", "workspace_id": "wrkspc_..."}`, with the Workspace's + // real ID even when it is the organization's default Workspace), or the + // organization (`{"type": "organization"}`) for a principal-bound API key that has + // no Workspace. + Scope BetaAPIKeyScopeUnion `json:"scope" api:"required"` + // Status of the API key. + // + // Any of "active", "archived", "expired", "inactive". + Status BetaAPIKeyStatus `json:"status" api:"required"` + // Object type. + // + // For API Keys, this is always `"api_key"`. + Type constant.APIKey `json:"type" default:"api_key"` + // Deprecated: use `scope` instead. ID of the Workspace associated with the API + // key, or `null` if the API key belongs to the default Workspace. Also `null` for + // a principal-bound API key that has no Workspace; `scope` tells the two apart. + // + // Deprecated: Use `scope` instead. `workspace_id` is `null` both for an API key in + // the default Workspace and for a principal-bound API key that has no Workspace. + WorkspaceID string `json:"workspace_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + CreatedAt respjson.Field + CreatedBy respjson.Field + ExpiresAt respjson.Field + Name respjson.Field + PartialKeyHint respjson.Field + Principal respjson.Field + Scope respjson.Field + Status respjson.Field + Type respjson.Field + WorkspaceID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaAPIKey) RawJSON() string { return r.JSON.raw } +func (r *BetaAPIKey) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaAPIKeyPrincipalUnion contains all possible properties and values from +// [BetaAPIKeyUserActor], [BetaAPIKeyServiceAccountActor]. +// +// Use the [BetaAPIKeyPrincipalUnion.AsAny] method to switch on the variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaAPIKeyPrincipalUnion struct { + // Any of "user_actor", "service_account_actor". + Type string `json:"type"` + // This field is from variant [BetaAPIKeyUserActor]. + UserID string `json:"user_id"` + // This field is from variant [BetaAPIKeyServiceAccountActor]. + ServiceAccountID string `json:"service_account_id"` + JSON struct { + Type respjson.Field + UserID respjson.Field + ServiceAccountID respjson.Field + raw string + } `json:"-"` +} + +// anyBetaAPIKeyPrincipal is implemented by each variant of +// [BetaAPIKeyPrincipalUnion] to add type safety for the return type of +// [BetaAPIKeyPrincipalUnion.AsAny] +type anyBetaAPIKeyPrincipal interface { + implBetaAPIKeyPrincipalUnion() +} + +func (BetaAPIKeyUserActor) implBetaAPIKeyPrincipalUnion() {} +func (BetaAPIKeyServiceAccountActor) implBetaAPIKeyPrincipalUnion() {} + +// Use the following switch statement to find the correct variant +// +// switch variant := BetaAPIKeyPrincipalUnion.AsAny().(type) { +// case anthropic.BetaAPIKeyUserActor: +// case anthropic.BetaAPIKeyServiceAccountActor: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaAPIKeyPrincipalUnion) AsAny() anyBetaAPIKeyPrincipal { + switch u.Type { + case "user_actor": + return u.AsUserActor() + case "service_account_actor": + return u.AsServiceAccountActor() + } + return nil +} + +func (u BetaAPIKeyPrincipalUnion) AsUserActor() (v BetaAPIKeyUserActor) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaAPIKeyPrincipalUnion) AsServiceAccountActor() (v BetaAPIKeyServiceAccountActor) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u BetaAPIKeyPrincipalUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaAPIKeyPrincipalUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaAPIKeyScopeUnion contains all possible properties and values from +// [BetaAPIKeyOrganizationScope], [BetaAPIKeyWorkspaceScope]. +// +// Use the [BetaAPIKeyScopeUnion.AsAny] method to switch on the variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaAPIKeyScopeUnion struct { + // Any of "organization", "workspace". + Type string `json:"type"` + // This field is from variant [BetaAPIKeyWorkspaceScope]. + WorkspaceID string `json:"workspace_id"` + JSON struct { + Type respjson.Field + WorkspaceID respjson.Field + raw string + } `json:"-"` +} + +// anyBetaAPIKeyScope is implemented by each variant of [BetaAPIKeyScopeUnion] to +// add type safety for the return type of [BetaAPIKeyScopeUnion.AsAny] +type anyBetaAPIKeyScope interface { + implBetaAPIKeyScopeUnion() +} + +func (BetaAPIKeyOrganizationScope) implBetaAPIKeyScopeUnion() {} +func (BetaAPIKeyWorkspaceScope) implBetaAPIKeyScopeUnion() {} + +// Use the following switch statement to find the correct variant +// +// switch variant := BetaAPIKeyScopeUnion.AsAny().(type) { +// case anthropic.BetaAPIKeyOrganizationScope: +// case anthropic.BetaAPIKeyWorkspaceScope: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaAPIKeyScopeUnion) AsAny() anyBetaAPIKeyScope { + switch u.Type { + case "organization": + return u.AsOrganization() + case "workspace": + return u.AsWorkspace() + } + return nil +} + +func (u BetaAPIKeyScopeUnion) AsOrganization() (v BetaAPIKeyOrganizationScope) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaAPIKeyScopeUnion) AsWorkspace() (v BetaAPIKeyWorkspaceScope) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u BetaAPIKeyScopeUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaAPIKeyScopeUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Status of the API key. +type BetaAPIKeyStatus string + +const ( + BetaAPIKeyStatusActive BetaAPIKeyStatus = "active" + BetaAPIKeyStatusArchived BetaAPIKeyStatus = "archived" + BetaAPIKeyStatusExpired BetaAPIKeyStatus = "expired" + BetaAPIKeyStatusInactive BetaAPIKeyStatus = "inactive" +) + +type BetaAPIKeyCreatedBy struct { + // ID of the actor that created the object. + ID string `json:"id" api:"required"` + // Type of the actor that created the object. + // + // Any of "service_account", "user". + Type BetaAPIKeyCreatedByType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaAPIKeyCreatedBy) RawJSON() string { return r.JSON.raw } +func (r *BetaAPIKeyCreatedBy) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Type of the actor that created the object. +type BetaAPIKeyCreatedByType string + +const ( + BetaAPIKeyCreatedByTypeServiceAccount BetaAPIKeyCreatedByType = "service_account" + BetaAPIKeyCreatedByTypeUser BetaAPIKeyCreatedByType = "user" +) + +type BetaAPIKeyOrganizationScope struct { + // Scope type. Always `"organization"`: the API key has no Workspace. Only a + // principal-bound API key can have this scope. + Type constant.Organization `json:"type" default:"organization"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaAPIKeyOrganizationScope) RawJSON() string { return r.JSON.raw } +func (r *BetaAPIKeyOrganizationScope) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaAPIKeyServiceAccountActor struct { + // ID of the Service Account the API key acts as. + ServiceAccountID string `json:"service_account_id" api:"required"` + // Principal type. Always `"service_account_actor"` for a Service Account. + Type constant.ServiceAccountActor `json:"type" default:"service_account_actor"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ServiceAccountID respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaAPIKeyServiceAccountActor) RawJSON() string { return r.JSON.raw } +func (r *BetaAPIKeyServiceAccountActor) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaAPIKeyUserActor struct { + // Principal type. Always `"user_actor"` for a User. + Type constant.UserActor `json:"type" default:"user_actor"` + // ID of the User the API key acts as. + UserID string `json:"user_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Type respjson.Field + UserID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaAPIKeyUserActor) RawJSON() string { return r.JSON.raw } +func (r *BetaAPIKeyUserActor) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaAPIKeyWorkspaceScope struct { + // Scope type. Always `"workspace"`: the API key belongs to one Workspace. + Type constant.Workspace `json:"type" default:"workspace"` + // ID of the Workspace the API key belongs to. Unlike the deprecated top-level + // `workspace_id`, this is the Workspace's real ID even for the organization's + // default Workspace. + WorkspaceID string `json:"workspace_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Type respjson.Field + WorkspaceID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaAPIKeyWorkspaceScope) RawJSON() string { return r.JSON.raw } +func (r *BetaAPIKeyWorkspaceScope) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaOrganizationAPIKeyUpdateParams struct { + // Name of the API key. + Name param.Opt[string] `json:"name,omitzero"` + // Status of the API key. + // + // Any of "active", "archived", "inactive". + Status BetaOrganizationAPIKeyUpdateParamsStatus `json:"status,omitzero"` + paramObj +} + +func (r BetaOrganizationAPIKeyUpdateParams) MarshalJSON() (data []byte, err error) { + type shadow BetaOrganizationAPIKeyUpdateParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaOrganizationAPIKeyUpdateParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Status of the API key. +type BetaOrganizationAPIKeyUpdateParamsStatus string + +const ( + BetaOrganizationAPIKeyUpdateParamsStatusActive BetaOrganizationAPIKeyUpdateParamsStatus = "active" + BetaOrganizationAPIKeyUpdateParamsStatusArchived BetaOrganizationAPIKeyUpdateParamsStatus = "archived" + BetaOrganizationAPIKeyUpdateParamsStatusInactive BetaOrganizationAPIKeyUpdateParamsStatus = "inactive" +) + +type BetaOrganizationAPIKeyListParams struct { + // Filter by the ID of the User who created the object. + CreatedByUserID param.Opt[string] `query:"created_by_user_id,omitzero" json:"-"` + // Filter by Workspace ID. + WorkspaceID param.Opt[string] `query:"workspace_id,omitzero" json:"-"` + // ID of the object to use as a cursor for pagination. When provided, returns the + // page of results immediately after this object. + AfterID param.Opt[string] `query:"after_id,omitzero" json:"-"` + // ID of the object to use as a cursor for pagination. When provided, returns the + // page of results immediately before this object. + BeforeID param.Opt[string] `query:"before_id,omitzero" json:"-"` + // Number of items to return per page. + // + // Defaults to `20`. Ranges from `1` to `1000`. + Limit param.Opt[int64] `query:"limit,omitzero" json:"-"` + // Filter by API key status. + // + // Any of "active", "archived", "expired", "inactive". + Status BetaOrganizationAPIKeyListParamsStatus `query:"status,omitzero" json:"-"` + paramObj +} + +// URLQuery serializes [BetaOrganizationAPIKeyListParams]'s query parameters as +// `url.Values`. +func (r BetaOrganizationAPIKeyListParams) URLQuery() (v url.Values, err error) { + return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ + ArrayFormat: apiquery.ArrayQueryFormatBrackets, + NestedFormat: apiquery.NestedQueryFormatBrackets, + }) +} + +// Filter by API key status. +type BetaOrganizationAPIKeyListParamsStatus string + +const ( + BetaOrganizationAPIKeyListParamsStatusActive BetaOrganizationAPIKeyListParamsStatus = "active" + BetaOrganizationAPIKeyListParamsStatusArchived BetaOrganizationAPIKeyListParamsStatus = "archived" + BetaOrganizationAPIKeyListParamsStatusExpired BetaOrganizationAPIKeyListParamsStatus = "expired" + BetaOrganizationAPIKeyListParamsStatusInactive BetaOrganizationAPIKeyListParamsStatus = "inactive" +) diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/betaorganizationexternalkey.go b/vendor/github.com/anthropics/anthropic-sdk-go/betaorganizationexternalkey.go new file mode 100644 index 000000000..b696a4baf --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/betaorganizationexternalkey.go @@ -0,0 +1,875 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +package anthropic + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/url" + "slices" + "time" + + "github.com/anthropics/anthropic-sdk-go/internal/apijson" + "github.com/anthropics/anthropic-sdk-go/internal/apiquery" + "github.com/anthropics/anthropic-sdk-go/internal/requestconfig" + "github.com/anthropics/anthropic-sdk-go/option" + "github.com/anthropics/anthropic-sdk-go/packages/pagination" + "github.com/anthropics/anthropic-sdk-go/packages/param" + "github.com/anthropics/anthropic-sdk-go/packages/respjson" + "github.com/anthropics/anthropic-sdk-go/shared/constant" +) + +// BetaOrganizationExternalKeyService contains methods and other services that help +// with interacting with the anthropic API. +// +// Note, unlike clients, this service does not read variables from the environment +// automatically. You should not instantiate this service directly, and instead use +// the [NewBetaOrganizationExternalKeyService] method instead. +type BetaOrganizationExternalKeyService struct { + Options []option.RequestOption +} + +// NewBetaOrganizationExternalKeyService generates a new service that applies the +// given options to each request. These options are applied after the parent +// client's options (if there is one), and before any request-specific options. +func NewBetaOrganizationExternalKeyService(opts ...option.RequestOption) (r BetaOrganizationExternalKeyService) { + r = BetaOrganizationExternalKeyService{} + r.Options = opts + return +} + +// Create an external key config owned by the caller's organization. +func (r *BetaOrganizationExternalKeyService) New(ctx context.Context, body BetaOrganizationExternalKeyNewParams, opts ...option.RequestOption) (res *BetaExternalKey, err error) { + opts = slices.Concat(r.Options, opts) + path := "v1/organizations/external_keys?beta=true" + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...) + return res, err +} + +// Retrieve a single external key config in the caller's organization by ID. +func (r *BetaOrganizationExternalKeyService) Get(ctx context.Context, externalKeyID string, opts ...option.RequestOption) (res *BetaExternalKey, err error) { + opts = slices.Concat(r.Options, opts) + if externalKeyID == "" { + err = errors.New("missing required external_key_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/organizations/external_keys/%s?beta=true", externalKeyID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...) + return res, err +} + +// Partially update an external key config. Omitted fields are left unchanged. +// +// `display_name` is always editable. `geo` and `provider_config` cannot be changed +// once any workspace references this config, because previously encrypted data +// requires the original key identity to decrypt. +func (r *BetaOrganizationExternalKeyService) Update(ctx context.Context, externalKeyID string, body BetaOrganizationExternalKeyUpdateParams, opts ...option.RequestOption) (res *BetaExternalKey, err error) { + opts = slices.Concat(r.Options, opts) + if externalKeyID == "" { + err = errors.New("missing required external_key_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/organizations/external_keys/%s?beta=true", externalKeyID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...) + return res, err +} + +// List external key configs in the caller's organization. +// +// Results are ordered by creation time (newest first). Use the `next_page` cursor +// from the response to fetch subsequent pages. +func (r *BetaOrganizationExternalKeyService) List(ctx context.Context, query BetaOrganizationExternalKeyListParams, opts ...option.RequestOption) (res *pagination.PageCursor[BetaExternalKey], err error) { + var raw *http.Response + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithResponseInto(&raw)}, opts...) + path := "v1/organizations/external_keys?beta=true" + cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, query, &res, opts...) + if err != nil { + return nil, err + } + err = cfg.Execute() + if err != nil { + return nil, err + } + res.SetPageConfig(cfg, raw) + return res, nil +} + +// List external key configs in the caller's organization. +// +// Results are ordered by creation time (newest first). Use the `next_page` cursor +// from the response to fetch subsequent pages. +func (r *BetaOrganizationExternalKeyService) ListAutoPaging(ctx context.Context, query BetaOrganizationExternalKeyListParams, opts ...option.RequestOption) *pagination.PageCursorAutoPager[BetaExternalKey] { + return pagination.NewPageCursorAutoPager(r.List(ctx, query, opts...)) +} + +// Delete an external key config. +// +// The request is rejected if any workspace still references this config. +func (r *BetaOrganizationExternalKeyService) Delete(ctx context.Context, externalKeyID string, opts ...option.RequestOption) (res *BetaOrganizationExternalKeyDeleteResponse, err error) { + opts = slices.Concat(r.Options, opts) + if externalKeyID == "" { + err = errors.New("missing required external_key_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/organizations/external_keys/%s?beta=true", externalKeyID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodDelete, path, nil, &res, opts...) + return res, err +} + +// Validate an external key config against the customer's KMS. +// +// Anthropic performs an encrypt/decrypt roundtrip against the configured KMS key +// and waits up to 30 seconds for the result. The response status is `success` if +// the roundtrip succeeded, or `failure` with an error message if it failed or +// timed out. +func (r *BetaOrganizationExternalKeyService) Validate(ctx context.Context, externalKeyID string, opts ...option.RequestOption) (res *BetaOrganizationExternalKeyValidateResponse, err error) { + opts = slices.Concat(r.Options, opts) + if externalKeyID == "" { + err = errors.New("missing required external_key_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/organizations/external_keys/%s/validate?beta=true", externalKeyID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, nil, &res, opts...) + return res, err +} + +type BetaAWSExternalKeyConfig struct { + // Full ARN of the AWS KMS key. + KMSARN string `json:"kms_arn" api:"required"` + Type constant.AWS `json:"type" default:"aws"` + // AWS region. Derived from `kms_arn` if omitted. + Region string `json:"region" api:"nullable"` + // IAM role ARN. Deprecated — Anthropic reaches the KMS key via a managed + // intermediate role; this field is ignored. + // + // Deprecated: deprecated + RoleARN string `json:"role_arn" api:"nullable"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + KMSARN respjson.Field + Type respjson.Field + Region respjson.Field + RoleARN respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaAWSExternalKeyConfig) RawJSON() string { return r.JSON.raw } +func (r *BetaAWSExternalKeyConfig) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// ToParam converts this BetaAWSExternalKeyConfig to a +// BetaAWSExternalKeyConfigParam. +// +// Warning: the fields of the param type will not be present. ToParam should only +// be used at the last possible moment before sending a request. Test for this with +// BetaAWSExternalKeyConfigParam.Overrides() +func (r BetaAWSExternalKeyConfig) ToParam() BetaAWSExternalKeyConfigParam { + return param.Override[BetaAWSExternalKeyConfigParam](json.RawMessage(r.RawJSON())) +} + +// The properties KMSARN, Type are required. +type BetaAWSExternalKeyConfigParam struct { + // Full ARN of the AWS KMS key. + KMSARN string `json:"kms_arn" api:"required"` + // AWS region. Derived from `kms_arn` if omitted. + Region param.Opt[string] `json:"region,omitzero"` + // IAM role ARN. Deprecated — Anthropic reaches the KMS key via a managed + // intermediate role; this field is ignored. + // + // Deprecated: deprecated + RoleARN param.Opt[string] `json:"role_arn,omitzero"` + // This field can be elided, and will marshal its zero value as "aws". + Type constant.AWS `json:"type" default:"aws"` + paramObj +} + +func (r BetaAWSExternalKeyConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaAWSExternalKeyConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaAWSExternalKeyConfigParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaAzureExternalKeyConfig struct { + // Name of the key within the vault. + KeyName string `json:"key_name" api:"required"` + // Azure AD tenant ID. + TenantID string `json:"tenant_id" api:"required"` + Type constant.Azure `json:"type" default:"azure"` + // Key Vault data-plane URI — `https://{vault-name}.vault.azure.net` or + // `https://{hsm-name}.managedhsm.azure.net`. + VaultURI string `json:"vault_uri" api:"required"` + // Azure AD application (client) ID. Omit to use Anthropic's multitenant app. + // Provide only if using a single-tenant app registration in the customer's + // directory. + ClientID string `json:"client_id" api:"nullable"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + KeyName respjson.Field + TenantID respjson.Field + Type respjson.Field + VaultURI respjson.Field + ClientID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaAzureExternalKeyConfig) RawJSON() string { return r.JSON.raw } +func (r *BetaAzureExternalKeyConfig) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Azure Key Vault provider configuration. +// +// The properties KeyName, TenantID, Type, VaultURI are required. +type BetaAzureExternalKeyConfigParam struct { + // Name of the key within the vault. + KeyName string `json:"key_name" api:"required"` + // Azure AD tenant ID. + TenantID string `json:"tenant_id" api:"required"` + // Key Vault data-plane URI — `https://{vault-name}.vault.azure.net` or + // `https://{hsm-name}.managedhsm.azure.net`. + VaultURI string `json:"vault_uri" api:"required"` + // Azure AD application (client) ID. Omit to use Anthropic's multitenant app. + // Provide only if using a single-tenant app registration in the customer's + // directory. + ClientID param.Opt[string] `json:"client_id,omitzero"` + // This field can be elided, and will marshal its zero value as "azure". + Type constant.Azure `json:"type" default:"azure"` + paramObj +} + +func (r BetaAzureExternalKeyConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaAzureExternalKeyConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaAzureExternalKeyConfigParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// CMEK external key config belonging to the caller's organization. +// +// Configs are organization-scoped. Workspaces attach to a config; once any +// workspace references it, the provider fields become effectively immutable +// (existing encrypted data needs the config for decrypt). +type BetaExternalKey struct { + // Identifier of the external key config. A tagged ID prefixed `ekey_`, or — for + // organizations on the Claude Platform on AWS — the AWS KMS key ARN. + ID string `json:"id" api:"required"` + // Whether any workspace uses this config to encrypt its data — counting live and + // archived workspaces (an archived workspace's data remains encrypted under the + // config), excluding deleted ones. Only an attached config is used by the + // encryption path; an `unattached` config is inert and can be deleted. + Attachment BetaExternalKeyAttachmentUnion `json:"attachment" api:"required"` + CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"` + // Human-friendly display name. Null if none was set. + DisplayName string `json:"display_name" api:"required"` + // Data residency geo. Selects which regional validator handles this key's + // encrypt/decrypt roundtrips. + Geo string `json:"geo" api:"required"` + // KMS provider identity and auth coordinates. + ProviderConfig BetaExternalKeyProviderConfigUnion `json:"provider_config" api:"required"` + Type constant.ExternalKey `json:"type" default:"external_key"` + UpdatedAt time.Time `json:"updated_at" api:"required" format:"date-time"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + Attachment respjson.Field + CreatedAt respjson.Field + DisplayName respjson.Field + Geo respjson.Field + ProviderConfig respjson.Field + Type respjson.Field + UpdatedAt respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaExternalKey) RawJSON() string { return r.JSON.raw } +func (r *BetaExternalKey) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaExternalKeyAttachmentUnion contains all possible properties and values from +// [BetaExternalKeyAttachedAttachment], [BetaExternalKeyUnattachedAttachment]. +// +// Use the [BetaExternalKeyAttachmentUnion.AsAny] method to switch on the variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaExternalKeyAttachmentUnion struct { + // Any of "attached", "unattached". + Type string `json:"type"` + JSON struct { + Type respjson.Field + raw string + } `json:"-"` +} + +// anyBetaExternalKeyAttachment is implemented by each variant of +// [BetaExternalKeyAttachmentUnion] to add type safety for the return type of +// [BetaExternalKeyAttachmentUnion.AsAny] +type anyBetaExternalKeyAttachment interface { + implBetaExternalKeyAttachmentUnion() +} + +func (BetaExternalKeyAttachedAttachment) implBetaExternalKeyAttachmentUnion() {} +func (BetaExternalKeyUnattachedAttachment) implBetaExternalKeyAttachmentUnion() {} + +// Use the following switch statement to find the correct variant +// +// switch variant := BetaExternalKeyAttachmentUnion.AsAny().(type) { +// case anthropic.BetaExternalKeyAttachedAttachment: +// case anthropic.BetaExternalKeyUnattachedAttachment: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaExternalKeyAttachmentUnion) AsAny() anyBetaExternalKeyAttachment { + switch u.Type { + case "attached": + return u.AsAttached() + case "unattached": + return u.AsUnattached() + } + return nil +} + +func (u BetaExternalKeyAttachmentUnion) AsAttached() (v BetaExternalKeyAttachedAttachment) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaExternalKeyAttachmentUnion) AsUnattached() (v BetaExternalKeyUnattachedAttachment) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u BetaExternalKeyAttachmentUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaExternalKeyAttachmentUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaExternalKeyProviderConfigUnion contains all possible properties and values +// from [BetaAWSExternalKeyConfig], [BetaGCPExternalKeyConfig], +// [BetaAzureExternalKeyConfig]. +// +// Use the [BetaExternalKeyProviderConfigUnion.AsAny] method to switch on the +// variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaExternalKeyProviderConfigUnion struct { + // This field is from variant [BetaAWSExternalKeyConfig]. + KMSARN string `json:"kms_arn"` + // Any of "aws", "gcp", "azure". + Type string `json:"type"` + // This field is from variant [BetaAWSExternalKeyConfig]. + Region string `json:"region"` + // This field is from variant [BetaAWSExternalKeyConfig]. + RoleARN string `json:"role_arn"` + KeyName string `json:"key_name"` + // This field is from variant [BetaAzureExternalKeyConfig]. + TenantID string `json:"tenant_id"` + // This field is from variant [BetaAzureExternalKeyConfig]. + VaultURI string `json:"vault_uri"` + // This field is from variant [BetaAzureExternalKeyConfig]. + ClientID string `json:"client_id"` + JSON struct { + KMSARN respjson.Field + Type respjson.Field + Region respjson.Field + RoleARN respjson.Field + KeyName respjson.Field + TenantID respjson.Field + VaultURI respjson.Field + ClientID respjson.Field + raw string + } `json:"-"` +} + +// anyBetaExternalKeyProviderConfig is implemented by each variant of +// [BetaExternalKeyProviderConfigUnion] to add type safety for the return type of +// [BetaExternalKeyProviderConfigUnion.AsAny] +type anyBetaExternalKeyProviderConfig interface { + implBetaExternalKeyProviderConfigUnion() +} + +func (BetaAWSExternalKeyConfig) implBetaExternalKeyProviderConfigUnion() {} +func (BetaGCPExternalKeyConfig) implBetaExternalKeyProviderConfigUnion() {} +func (BetaAzureExternalKeyConfig) implBetaExternalKeyProviderConfigUnion() {} + +// Use the following switch statement to find the correct variant +// +// switch variant := BetaExternalKeyProviderConfigUnion.AsAny().(type) { +// case anthropic.BetaAWSExternalKeyConfig: +// case anthropic.BetaGCPExternalKeyConfig: +// case anthropic.BetaAzureExternalKeyConfig: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaExternalKeyProviderConfigUnion) AsAny() anyBetaExternalKeyProviderConfig { + switch u.Type { + case "aws": + return u.AsAWS() + case "gcp": + return u.AsGCP() + case "azure": + return u.AsAzure() + } + return nil +} + +func (u BetaExternalKeyProviderConfigUnion) AsAWS() (v BetaAWSExternalKeyConfig) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaExternalKeyProviderConfigUnion) AsGCP() (v BetaGCPExternalKeyConfig) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaExternalKeyProviderConfigUnion) AsAzure() (v BetaAzureExternalKeyConfig) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u BetaExternalKeyProviderConfigUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaExternalKeyProviderConfigUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaExternalKeyAttachedAttachment struct { + Type constant.Attached `json:"type" default:"attached"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaExternalKeyAttachedAttachment) RawJSON() string { return r.JSON.raw } +func (r *BetaExternalKeyAttachedAttachment) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaExternalKeyUnattachedAttachment struct { + Type constant.Unattached `json:"type" default:"unattached"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaExternalKeyUnattachedAttachment) RawJSON() string { return r.JSON.raw } +func (r *BetaExternalKeyUnattachedAttachment) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaGCPExternalKeyConfig struct { + // Full resource name of the Cloud KMS key. + KeyName string `json:"key_name" api:"required"` + Type constant.GCP `json:"type" default:"gcp"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + KeyName respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaGCPExternalKeyConfig) RawJSON() string { return r.JSON.raw } +func (r *BetaGCPExternalKeyConfig) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// ToParam converts this BetaGCPExternalKeyConfig to a +// BetaGCPExternalKeyConfigParam. +// +// Warning: the fields of the param type will not be present. ToParam should only +// be used at the last possible moment before sending a request. Test for this with +// BetaGCPExternalKeyConfigParam.Overrides() +func (r BetaGCPExternalKeyConfig) ToParam() BetaGCPExternalKeyConfigParam { + return param.Override[BetaGCPExternalKeyConfigParam](json.RawMessage(r.RawJSON())) +} + +// The properties KeyName, Type are required. +type BetaGCPExternalKeyConfigParam struct { + // Full resource name of the Cloud KMS key. + KeyName string `json:"key_name" api:"required"` + // This field can be elided, and will marshal its zero value as "gcp". + Type constant.GCP `json:"type" default:"gcp"` + paramObj +} + +func (r BetaGCPExternalKeyConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaGCPExternalKeyConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaGCPExternalKeyConfigParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaOrganizationExternalKeyDeleteResponse struct { + // ID of the deleted External Key. + ID string `json:"id" api:"required"` + Type constant.ExternalKeyDeleted `json:"type" default:"external_key_deleted"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaOrganizationExternalKeyDeleteResponse) RawJSON() string { return r.JSON.raw } +func (r *BetaOrganizationExternalKeyDeleteResponse) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Result of a validation roundtrip against the customer's KMS. +// +// HTTP 200 for both outcomes — the operation completed; `status` says whether the +// key works. +type BetaOrganizationExternalKeyValidateResponse struct { + // Error message when status is `failure`. Null otherwise. + Error string `json:"error" api:"required"` + // `success` — encrypt/decrypt roundtrip succeeded. `failure` — the roundtrip + // failed or timed out; see `error`. + // + // Any of "failure", "success". + Status BetaOrganizationExternalKeyValidateResponseStatus `json:"status" api:"required"` + Type constant.ExternalKeyValidation `json:"type" default:"external_key_validation"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Error respjson.Field + Status respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaOrganizationExternalKeyValidateResponse) RawJSON() string { return r.JSON.raw } +func (r *BetaOrganizationExternalKeyValidateResponse) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// `success` — encrypt/decrypt roundtrip succeeded. `failure` — the roundtrip +// failed or timed out; see `error`. +type BetaOrganizationExternalKeyValidateResponseStatus string + +const ( + BetaOrganizationExternalKeyValidateResponseStatusFailure BetaOrganizationExternalKeyValidateResponseStatus = "failure" + BetaOrganizationExternalKeyValidateResponseStatusSuccess BetaOrganizationExternalKeyValidateResponseStatus = "success" +) + +type BetaOrganizationExternalKeyNewParams struct { + // KMS provider identity and auth coordinates. + ProviderConfig BetaOrganizationExternalKeyNewParamsProviderConfigUnion `json:"provider_config,omitzero" api:"required"` + // Human-friendly display name. + DisplayName param.Opt[string] `json:"display_name,omitzero"` + // Data residency geo. Only `us` is supported. + // + // Any of "us". + Geo BetaOrganizationExternalKeyNewParamsGeo `json:"geo,omitzero"` + paramObj +} + +func (r BetaOrganizationExternalKeyNewParams) MarshalJSON() (data []byte, err error) { + type shadow BetaOrganizationExternalKeyNewParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaOrganizationExternalKeyNewParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaOrganizationExternalKeyNewParamsProviderConfigUnion struct { + OfAWS *BetaAWSExternalKeyConfigParam `json:",omitzero,inline"` + OfGCP *BetaGCPExternalKeyConfigParam `json:",omitzero,inline"` + OfAzure *BetaAzureExternalKeyConfigParam `json:",omitzero,inline"` + paramUnion +} + +func (u BetaOrganizationExternalKeyNewParamsProviderConfigUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfAWS, u.OfGCP, u.OfAzure) +} +func (u *BetaOrganizationExternalKeyNewParamsProviderConfigUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *BetaOrganizationExternalKeyNewParamsProviderConfigUnion) asAny() any { + if !param.IsOmitted(u.OfAWS) { + return u.OfAWS + } else if !param.IsOmitted(u.OfGCP) { + return u.OfGCP + } else if !param.IsOmitted(u.OfAzure) { + return u.OfAzure + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaOrganizationExternalKeyNewParamsProviderConfigUnion) GetKMSARN() *string { + if vt := u.OfAWS; vt != nil { + return &vt.KMSARN + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaOrganizationExternalKeyNewParamsProviderConfigUnion) GetRegion() *string { + if vt := u.OfAWS; vt != nil && vt.Region.Valid() { + return &vt.Region.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaOrganizationExternalKeyNewParamsProviderConfigUnion) GetRoleARN() *string { + if vt := u.OfAWS; vt != nil && vt.RoleARN.Valid() { + return &vt.RoleARN.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaOrganizationExternalKeyNewParamsProviderConfigUnion) GetTenantID() *string { + if vt := u.OfAzure; vt != nil { + return &vt.TenantID + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaOrganizationExternalKeyNewParamsProviderConfigUnion) GetVaultURI() *string { + if vt := u.OfAzure; vt != nil { + return &vt.VaultURI + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaOrganizationExternalKeyNewParamsProviderConfigUnion) GetClientID() *string { + if vt := u.OfAzure; vt != nil && vt.ClientID.Valid() { + return &vt.ClientID.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaOrganizationExternalKeyNewParamsProviderConfigUnion) GetType() *string { + if vt := u.OfAWS; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfGCP; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfAzure; vt != nil { + return (*string)(&vt.Type) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaOrganizationExternalKeyNewParamsProviderConfigUnion) GetKeyName() *string { + if vt := u.OfGCP; vt != nil { + return (*string)(&vt.KeyName) + } else if vt := u.OfAzure; vt != nil { + return (*string)(&vt.KeyName) + } + return nil +} + +func init() { + apijson.RegisterUnion[BetaOrganizationExternalKeyNewParamsProviderConfigUnion]( + "type", + apijson.Discriminator[BetaAWSExternalKeyConfigParam]("aws"), + apijson.Discriminator[BetaGCPExternalKeyConfigParam]("gcp"), + apijson.Discriminator[BetaAzureExternalKeyConfigParam]("azure"), + ) +} + +// Data residency geo. Only `us` is supported. +type BetaOrganizationExternalKeyNewParamsGeo string + +const ( + BetaOrganizationExternalKeyNewParamsGeoUs BetaOrganizationExternalKeyNewParamsGeo = "us" +) + +type BetaOrganizationExternalKeyUpdateParams struct { + // Human-friendly display name. + DisplayName param.Opt[string] `json:"display_name,omitzero"` + // Data residency geo. Only `us` is supported. + // + // Any of "us". + Geo BetaOrganizationExternalKeyUpdateParamsGeo `json:"geo,omitzero"` + // KMS provider identity and auth coordinates. + ProviderConfig BetaOrganizationExternalKeyUpdateParamsProviderConfigUnion `json:"provider_config,omitzero"` + paramObj +} + +func (r BetaOrganizationExternalKeyUpdateParams) MarshalJSON() (data []byte, err error) { + type shadow BetaOrganizationExternalKeyUpdateParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaOrganizationExternalKeyUpdateParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Data residency geo. Only `us` is supported. +type BetaOrganizationExternalKeyUpdateParamsGeo string + +const ( + BetaOrganizationExternalKeyUpdateParamsGeoUs BetaOrganizationExternalKeyUpdateParamsGeo = "us" +) + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaOrganizationExternalKeyUpdateParamsProviderConfigUnion struct { + OfAWS *BetaAWSExternalKeyConfigParam `json:",omitzero,inline"` + OfGCP *BetaGCPExternalKeyConfigParam `json:",omitzero,inline"` + OfAzure *BetaAzureExternalKeyConfigParam `json:",omitzero,inline"` + paramUnion +} + +func (u BetaOrganizationExternalKeyUpdateParamsProviderConfigUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfAWS, u.OfGCP, u.OfAzure) +} +func (u *BetaOrganizationExternalKeyUpdateParamsProviderConfigUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *BetaOrganizationExternalKeyUpdateParamsProviderConfigUnion) asAny() any { + if !param.IsOmitted(u.OfAWS) { + return u.OfAWS + } else if !param.IsOmitted(u.OfGCP) { + return u.OfGCP + } else if !param.IsOmitted(u.OfAzure) { + return u.OfAzure + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaOrganizationExternalKeyUpdateParamsProviderConfigUnion) GetKMSARN() *string { + if vt := u.OfAWS; vt != nil { + return &vt.KMSARN + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaOrganizationExternalKeyUpdateParamsProviderConfigUnion) GetRegion() *string { + if vt := u.OfAWS; vt != nil && vt.Region.Valid() { + return &vt.Region.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaOrganizationExternalKeyUpdateParamsProviderConfigUnion) GetRoleARN() *string { + if vt := u.OfAWS; vt != nil && vt.RoleARN.Valid() { + return &vt.RoleARN.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaOrganizationExternalKeyUpdateParamsProviderConfigUnion) GetTenantID() *string { + if vt := u.OfAzure; vt != nil { + return &vt.TenantID + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaOrganizationExternalKeyUpdateParamsProviderConfigUnion) GetVaultURI() *string { + if vt := u.OfAzure; vt != nil { + return &vt.VaultURI + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaOrganizationExternalKeyUpdateParamsProviderConfigUnion) GetClientID() *string { + if vt := u.OfAzure; vt != nil && vt.ClientID.Valid() { + return &vt.ClientID.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaOrganizationExternalKeyUpdateParamsProviderConfigUnion) GetType() *string { + if vt := u.OfAWS; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfGCP; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfAzure; vt != nil { + return (*string)(&vt.Type) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaOrganizationExternalKeyUpdateParamsProviderConfigUnion) GetKeyName() *string { + if vt := u.OfGCP; vt != nil { + return (*string)(&vt.KeyName) + } else if vt := u.OfAzure; vt != nil { + return (*string)(&vt.KeyName) + } + return nil +} + +func init() { + apijson.RegisterUnion[BetaOrganizationExternalKeyUpdateParamsProviderConfigUnion]( + "type", + apijson.Discriminator[BetaAWSExternalKeyConfigParam]("aws"), + apijson.Discriminator[BetaGCPExternalKeyConfigParam]("gcp"), + apijson.Discriminator[BetaAzureExternalKeyConfigParam]("azure"), + ) +} + +type BetaOrganizationExternalKeyListParams struct { + // Opaque cursor from a previous response's `next_page`. + Page param.Opt[string] `query:"page,omitzero" json:"-"` + // Number of results per page. + Limit param.Opt[int64] `query:"limit,omitzero" json:"-"` + paramObj +} + +// URLQuery serializes [BetaOrganizationExternalKeyListParams]'s query parameters +// as `url.Values`. +func (r BetaOrganizationExternalKeyListParams) URLQuery() (v url.Values, err error) { + return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ + ArrayFormat: apiquery.ArrayQueryFormatBrackets, + NestedFormat: apiquery.NestedQueryFormatBrackets, + }) +} diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/betaorganizationfederation.go b/vendor/github.com/anthropics/anthropic-sdk-go/betaorganizationfederation.go new file mode 100644 index 000000000..ee86f4750 --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/betaorganizationfederation.go @@ -0,0 +1,30 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +package anthropic + +import ( + "github.com/anthropics/anthropic-sdk-go/option" +) + +// BetaOrganizationFederationService contains methods and other services that help +// with interacting with the anthropic API. +// +// Note, unlike clients, this service does not read variables from the environment +// automatically. You should not instantiate this service directly, and instead use +// the [NewBetaOrganizationFederationService] method instead. +type BetaOrganizationFederationService struct { + Options []option.RequestOption + Issuers BetaOrganizationFederationIssuerService + Rules BetaOrganizationFederationRuleService +} + +// NewBetaOrganizationFederationService generates a new service that applies the +// given options to each request. These options are applied after the parent +// client's options (if there is one), and before any request-specific options. +func NewBetaOrganizationFederationService(opts ...option.RequestOption) (r BetaOrganizationFederationService) { + r = BetaOrganizationFederationService{} + r.Options = opts + r.Issuers = NewBetaOrganizationFederationIssuerService(opts...) + r.Rules = NewBetaOrganizationFederationRuleService(opts...) + return +} diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/betaorganizationfederationissuer.go b/vendor/github.com/anthropics/anthropic-sdk-go/betaorganizationfederationissuer.go new file mode 100644 index 000000000..f3e2d2639 --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/betaorganizationfederationissuer.go @@ -0,0 +1,779 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +package anthropic + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/url" + "slices" + "time" + + "github.com/anthropics/anthropic-sdk-go/internal/apijson" + "github.com/anthropics/anthropic-sdk-go/internal/apiquery" + "github.com/anthropics/anthropic-sdk-go/internal/requestconfig" + "github.com/anthropics/anthropic-sdk-go/option" + "github.com/anthropics/anthropic-sdk-go/packages/pagination" + "github.com/anthropics/anthropic-sdk-go/packages/param" + "github.com/anthropics/anthropic-sdk-go/packages/respjson" + "github.com/anthropics/anthropic-sdk-go/shared/constant" +) + +// BetaOrganizationFederationIssuerService contains methods and other services that +// help with interacting with the anthropic API. +// +// Note, unlike clients, this service does not read variables from the environment +// automatically. You should not instantiate this service directly, and instead use +// the [NewBetaOrganizationFederationIssuerService] method instead. +type BetaOrganizationFederationIssuerService struct { + Options []option.RequestOption +} + +// NewBetaOrganizationFederationIssuerService generates a new service that applies +// the given options to each request. These options are applied after the parent +// client's options (if there is one), and before any request-specific options. +func NewBetaOrganizationFederationIssuerService(opts ...option.RequestOption) (r BetaOrganizationFederationIssuerService) { + r = BetaOrganizationFederationIssuerService{} + r.Options = opts + return +} + +// **Requires an OAuth access token with the `org:admin` scope**, from +// `ant auth login --scope org:admin` or a workload identity federation rule; Admin +// API keys are not accepted. See +// [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api). +// +// Register an OIDC issuer that Anthropic will trust for workload identity +// federation in your organization. +// +// The `jwks` field controls how the issuer's signing keys are obtained and takes +// one of three shapes selected by `type`: `discovery` (resolve keys through OIDC +// discovery), `explicit_url` (fetch keys from a fixed JWKS URL), or `inline` +// (provide a static key set). When `jwks.type` is `discovery` and no +// `discovery_base` is set, the issuer URL must be publicly reachable over HTTPS so +// Anthropic can fetch the discovery document; for `explicit_url` and `inline` +// modes the issuer URL is only matched as the JWT's `iss` claim and is not +// fetched. +func (r *BetaOrganizationFederationIssuerService) New(ctx context.Context, params BetaOrganizationFederationIssuerNewParams, opts ...option.RequestOption) (res *BetaFederationIssuer, err error) { + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + path := "v1/organizations/federation_issuers?beta=true" + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, params, &res, opts...) + return res, err +} + +// **Requires an OAuth access token with the `org:admin` scope**, from +// `ant auth login --scope org:admin` or a workload identity federation rule; Admin +// API keys are not accepted. See +// [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api). +// +// Retrieve a federation issuer by its ID (`fdis_...`). +func (r *BetaOrganizationFederationIssuerService) Get(ctx context.Context, federationIssuerID string, query BetaOrganizationFederationIssuerGetParams, opts ...option.RequestOption) (res *BetaFederationIssuer, err error) { + for _, v := range query.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + if federationIssuerID == "" { + err = errors.New("missing required federation_issuer_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/organizations/federation_issuers/%s?beta=true", federationIssuerID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...) + return res, err +} + +// **Requires an OAuth access token with the `org:admin` scope**, from +// `ant auth login --scope org:admin` or a workload identity federation rule; Admin +// API keys are not accepted. See +// [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api). +// +// Partially update a federation issuer. +// +// Setting `jwks` replaces the full JWKS shape at once. Archived issuers cannot be +// updated; this returns 400. Create a new issuer instead. +// +// Updating an issuer that backs a rule with a scope outside `workspace:developer` +// or `workspace:inference` requires a Console session. +func (r *BetaOrganizationFederationIssuerService) Update(ctx context.Context, federationIssuerID string, params BetaOrganizationFederationIssuerUpdateParams, opts ...option.RequestOption) (res *BetaFederationIssuer, err error) { + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + if federationIssuerID == "" { + err = errors.New("missing required federation_issuer_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/organizations/federation_issuers/%s?beta=true", federationIssuerID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, params, &res, opts...) + return res, err +} + +// **Requires an OAuth access token with the `org:admin` scope**, from +// `ant auth login --scope org:admin` or a workload identity federation rule; Admin +// API keys are not accepted. See +// [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api). +// +// List federation issuers in your organization. +// +// Archived issuers are excluded unless `include_archived=true`. +func (r *BetaOrganizationFederationIssuerService) List(ctx context.Context, params BetaOrganizationFederationIssuerListParams, opts ...option.RequestOption) (res *pagination.PageCursor[BetaFederationIssuer], err error) { + var raw *http.Response + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithResponseInto(&raw)}, opts...) + path := "v1/organizations/federation_issuers?beta=true" + cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, params, &res, opts...) + if err != nil { + return nil, err + } + err = cfg.Execute() + if err != nil { + return nil, err + } + res.SetPageConfig(cfg, raw) + return res, nil +} + +// **Requires an OAuth access token with the `org:admin` scope**, from +// `ant auth login --scope org:admin` or a workload identity federation rule; Admin +// API keys are not accepted. See +// [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api). +// +// List federation issuers in your organization. +// +// Archived issuers are excluded unless `include_archived=true`. +func (r *BetaOrganizationFederationIssuerService) ListAutoPaging(ctx context.Context, params BetaOrganizationFederationIssuerListParams, opts ...option.RequestOption) *pagination.PageCursorAutoPager[BetaFederationIssuer] { + return pagination.NewPageCursorAutoPager(r.List(ctx, params, opts...)) +} + +// **Requires an OAuth access token with the `org:admin` scope**, from +// `ant auth login --scope org:admin` or a workload identity federation rule; Admin +// API keys are not accepted. See +// [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api). +// +// Archive a federation issuer. +// +// Idempotent; re-archiving returns the issuer with its original `archived_at`. +// Rejected with 400 if any live (non-archived) federation rule still references +// the issuer; archive those rules first (a rule's issuer cannot be changed), or +// recreate them against another issuer. +func (r *BetaOrganizationFederationIssuerService) Archive(ctx context.Context, federationIssuerID string, body BetaOrganizationFederationIssuerArchiveParams, opts ...option.RequestOption) (res *BetaFederationIssuer, err error) { + for _, v := range body.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + if federationIssuerID == "" { + err = errors.New("missing required federation_issuer_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/organizations/federation_issuers/%s/archive?beta=true", federationIssuerID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, nil, &res, opts...) + return res, err +} + +// Registered external OIDC identity provider. +// +// Records an external IdP the organization trusts for the RFC 7523 jwt-bearer +// grant. The `issuer_url` must match the JWT `iss` claim exactly. +type BetaFederationIssuer struct { + // Tagged ID of the federation issuer. + ID string `json:"id" api:"required"` + // If set, all rules referencing this issuer reject token exchange. + ArchivedAt time.Time `json:"archived_at" api:"required" format:"date-time"` + // Tagged ID (`user_`/`svac_`) of the actor that archived this issuer. + ArchivedByActorID string `json:"archived_by_actor_id" api:"required"` + // Whether the jwt-bearer exchange enforces JTI single-use (replay protection) for + // tokens from this issuer. Applies only to assertions carrying a `jti` claim; + // tokens without one are accepted without single-use enforcement. + CheckJTI bool `json:"check_jti" api:"required"` + // When this issuer was created. + CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"` + // Tagged ID (`user_`/`svac_`) of the actor that created this issuer. + CreatedByActorID string `json:"created_by_actor_id" api:"required"` + // The `iss` claim value. Incoming JWTs must match exactly. + IssuerURL string `json:"issuer_url" api:"required"` + // How signing keys are obtained for signature verification. + JWKS BetaFederationIssuerJWKSUnion `json:"jwks" api:"required"` + // If set, Anthropic's JWKS poller has paused polling for this issuer after + // repeated fetch failures. Re-enable by sending `jwks_polling_disabled: false` via + // the issuer update endpoint (POST) once the upstream JWKS endpoint is fixed. An + // OAuth caller cannot send this when the issuer backs a rule with any scope other + // than `workspace:developer` or `workspace:inference`; use a Console session. + JWKSPollingDisabledAt time.Time `json:"jwks_polling_disabled_at" api:"required" format:"date-time"` + // Maximum allowed iat→exp spread for assertions from this issuer (1-176400 + // seconds, i.e. up to 49h). Assertions must carry both `iat` and `exp`; a missing + // `iat` is rejected. + MaxJWTLifetimeSeconds int64 `json:"max_jwt_lifetime_seconds" api:"required"` + // Admin-chosen slug identifier. + Name string `json:"name" api:"required"` + // Status of automatic JWKS polling for a federation issuer. + // + // Anthropic periodically fetches the issuer's signing keys in the background. + // These fields summarize the most recent fetches so the health of the JWKS + // endpoint can be monitored. + PollStatus BetaFederationIssuerPollStatus `json:"poll_status" api:"required"` + Type constant.FederationIssuer `json:"type" default:"federation_issuer"` + // When this issuer was last updated. + UpdatedAt time.Time `json:"updated_at" api:"required" format:"date-time"` + // Tagged ID (`user_`/`svac_`) of the actor that last updated this issuer. + UpdatedByActorID string `json:"updated_by_actor_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + ArchivedAt respjson.Field + ArchivedByActorID respjson.Field + CheckJTI respjson.Field + CreatedAt respjson.Field + CreatedByActorID respjson.Field + IssuerURL respjson.Field + JWKS respjson.Field + JWKSPollingDisabledAt respjson.Field + MaxJWTLifetimeSeconds respjson.Field + Name respjson.Field + PollStatus respjson.Field + Type respjson.Field + UpdatedAt respjson.Field + UpdatedByActorID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaFederationIssuer) RawJSON() string { return r.JSON.raw } +func (r *BetaFederationIssuer) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaFederationIssuerJWKSUnion contains all possible properties and values from +// [BetaJWKSDiscovery], [BetaJWKSExplicitURL], [BetaJWKSInline]. +// +// Use the [BetaFederationIssuerJWKSUnion.AsAny] method to switch on the variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaFederationIssuerJWKSUnion struct { + // Any of "discovery", "explicit_url", "inline". + Type string `json:"type"` + CACertPEM string `json:"ca_cert_pem"` + // This field is from variant [BetaJWKSDiscovery]. + DiscoveryBase string `json:"discovery_base"` + // This field is from variant [BetaJWKSExplicitURL]. + URL string `json:"url"` + // This field is from variant [BetaJWKSInline]. + Keys []map[string]any `json:"keys"` + JSON struct { + Type respjson.Field + CACertPEM respjson.Field + DiscoveryBase respjson.Field + URL respjson.Field + Keys respjson.Field + raw string + } `json:"-"` +} + +// anyBetaFederationIssuerJWKS is implemented by each variant of +// [BetaFederationIssuerJWKSUnion] to add type safety for the return type of +// [BetaFederationIssuerJWKSUnion.AsAny] +type anyBetaFederationIssuerJWKS interface { + implBetaFederationIssuerJWKSUnion() +} + +func (BetaJWKSDiscovery) implBetaFederationIssuerJWKSUnion() {} +func (BetaJWKSExplicitURL) implBetaFederationIssuerJWKSUnion() {} +func (BetaJWKSInline) implBetaFederationIssuerJWKSUnion() {} + +// Use the following switch statement to find the correct variant +// +// switch variant := BetaFederationIssuerJWKSUnion.AsAny().(type) { +// case anthropic.BetaJWKSDiscovery: +// case anthropic.BetaJWKSExplicitURL: +// case anthropic.BetaJWKSInline: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaFederationIssuerJWKSUnion) AsAny() anyBetaFederationIssuerJWKS { + switch u.Type { + case "discovery": + return u.AsDiscovery() + case "explicit_url": + return u.AsExplicitURL() + case "inline": + return u.AsInline() + } + return nil +} + +func (u BetaFederationIssuerJWKSUnion) AsDiscovery() (v BetaJWKSDiscovery) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaFederationIssuerJWKSUnion) AsExplicitURL() (v BetaJWKSExplicitURL) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaFederationIssuerJWKSUnion) AsInline() (v BetaJWKSInline) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u BetaFederationIssuerJWKSUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaFederationIssuerJWKSUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Status of automatic JWKS polling for a federation issuer. +// +// Anthropic periodically fetches the issuer's signing keys in the background. +// These fields summarize the most recent fetches so the health of the JWKS +// endpoint can be monitored. +type BetaFederationIssuerPollStatus struct { + // Consecutive fetch failures since the last success. + ConsecutiveFailures int64 `json:"consecutive_failures" api:"required"` + // When the last successful fetch completed. + LastFetchedAt time.Time `json:"last_fetched_at" api:"required" format:"date-time"` + // When the next fetch is scheduled. Null if paused. + NextPollAt time.Time `json:"next_poll_at" api:"required" format:"date-time"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ConsecutiveFailures respjson.Field + LastFetchedAt respjson.Field + NextPollAt respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaFederationIssuerPollStatus) RawJSON() string { return r.JSON.raw } +func (r *BetaFederationIssuerPollStatus) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// JWKS via the issuer's OIDC discovery document. +type BetaJWKSDiscovery struct { + Type constant.Discovery `json:"type" default:"discovery"` + // Optional custom CA (PEM) for TLS verification of the JWKS fetch. + CACertPEM string `json:"ca_cert_pem" api:"nullable"` + // Set when the discovery URL differs from `issuer_url`. + DiscoveryBase string `json:"discovery_base" api:"nullable"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Type respjson.Field + CACertPEM respjson.Field + DiscoveryBase respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaJWKSDiscovery) RawJSON() string { return r.JSON.raw } +func (r *BetaJWKSDiscovery) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// ToParam converts this BetaJWKSDiscovery to a BetaJWKSDiscoveryParam. +// +// Warning: the fields of the param type will not be present. ToParam should only +// be used at the last possible moment before sending a request. Test for this with +// BetaJWKSDiscoveryParam.Overrides() +func (r BetaJWKSDiscovery) ToParam() BetaJWKSDiscoveryParam { + return param.Override[BetaJWKSDiscoveryParam](json.RawMessage(r.RawJSON())) +} + +// JWKS via the issuer's OIDC discovery document. +// +// The property Type is required. +type BetaJWKSDiscoveryParam struct { + // Optional custom CA (PEM) for TLS verification of the JWKS fetch. + CACertPEM param.Opt[string] `json:"ca_cert_pem,omitzero"` + // Set when the discovery URL differs from `issuer_url`. + DiscoveryBase param.Opt[string] `json:"discovery_base,omitzero"` + // This field can be elided, and will marshal its zero value as "discovery". + Type constant.Discovery `json:"type" default:"discovery"` + paramObj +} + +func (r BetaJWKSDiscoveryParam) MarshalJSON() (data []byte, err error) { + type shadow BetaJWKSDiscoveryParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaJWKSDiscoveryParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// JWKS fetched from a fixed endpoint. +type BetaJWKSExplicitURL struct { + Type constant.ExplicitURL `json:"type" default:"explicit_url"` + // JWKS endpoint. + URL string `json:"url" api:"required"` + // Optional custom CA (PEM) for TLS verification of the JWKS fetch. + CACertPEM string `json:"ca_cert_pem" api:"nullable"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Type respjson.Field + URL respjson.Field + CACertPEM respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaJWKSExplicitURL) RawJSON() string { return r.JSON.raw } +func (r *BetaJWKSExplicitURL) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// ToParam converts this BetaJWKSExplicitURL to a BetaJWKSExplicitURLParam. +// +// Warning: the fields of the param type will not be present. ToParam should only +// be used at the last possible moment before sending a request. Test for this with +// BetaJWKSExplicitURLParam.Overrides() +func (r BetaJWKSExplicitURL) ToParam() BetaJWKSExplicitURLParam { + return param.Override[BetaJWKSExplicitURLParam](json.RawMessage(r.RawJSON())) +} + +// JWKS fetched from a fixed endpoint. +// +// The properties Type, URL are required. +type BetaJWKSExplicitURLParam struct { + // JWKS endpoint. + URL string `json:"url" api:"required"` + // Optional custom CA (PEM) for TLS verification of the JWKS fetch. + CACertPEM param.Opt[string] `json:"ca_cert_pem,omitzero"` + // This field can be elided, and will marshal its zero value as "explicit_url". + Type constant.ExplicitURL `json:"type" default:"explicit_url"` + paramObj +} + +func (r BetaJWKSExplicitURLParam) MarshalJSON() (data []byte, err error) { + type shadow BetaJWKSExplicitURLParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaJWKSExplicitURLParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// JWKS supplied directly; no network fetch. +type BetaJWKSInline struct { + // Inline JWK objects. + Keys []map[string]any `json:"keys" api:"required"` + Type constant.Inline `json:"type" default:"inline"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Keys respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaJWKSInline) RawJSON() string { return r.JSON.raw } +func (r *BetaJWKSInline) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// ToParam converts this BetaJWKSInline to a BetaJWKSInlineParam. +// +// Warning: the fields of the param type will not be present. ToParam should only +// be used at the last possible moment before sending a request. Test for this with +// BetaJWKSInlineParam.Overrides() +func (r BetaJWKSInline) ToParam() BetaJWKSInlineParam { + return param.Override[BetaJWKSInlineParam](json.RawMessage(r.RawJSON())) +} + +// JWKS supplied directly; no network fetch. +// +// The properties Keys, Type are required. +type BetaJWKSInlineParam struct { + // Inline JWK objects. + Keys []map[string]any `json:"keys,omitzero" api:"required"` + // This field can be elided, and will marshal its zero value as "inline". + Type constant.Inline `json:"type" default:"inline"` + paramObj +} + +func (r BetaJWKSInlineParam) MarshalJSON() (data []byte, err error) { + type shadow BetaJWKSInlineParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaJWKSInlineParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaOrganizationFederationIssuerNewParams struct { + // The `iss` claim value to match against. + IssuerURL string `json:"issuer_url" api:"required"` + // Slug identifier (lowercase, digits, hyphens). Unique within the organization; a + // duplicate name returns 409. + Name string `json:"name" api:"required"` + // Whether the jwt-bearer exchange enforces JTI single-use (replay protection) for + // tokens from this issuer. Defaults to true. Applies only to assertions carrying a + // `jti` claim; tokens without one are accepted without single-use enforcement. + CheckJTI param.Opt[bool] `json:"check_jti,omitzero"` + // Maximum allowed iat→exp spread for assertions from this issuer (1-176400 + // seconds, i.e. up to 49h). Defaults to 3600 (1h). Assertions must carry both + // `iat` and `exp`; a missing `iat` is rejected. + MaxJWTLifetimeSeconds param.Opt[int64] `json:"max_jwt_lifetime_seconds,omitzero"` + // How signing keys are obtained. Defaults to OIDC discovery. + JWKS BetaOrganizationFederationIssuerNewParamsJWKSUnion `json:"jwks,omitzero"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +func (r BetaOrganizationFederationIssuerNewParams) MarshalJSON() (data []byte, err error) { + type shadow BetaOrganizationFederationIssuerNewParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaOrganizationFederationIssuerNewParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaOrganizationFederationIssuerNewParamsJWKSUnion struct { + OfDiscovery *BetaJWKSDiscoveryParam `json:",omitzero,inline"` + OfExplicitURL *BetaJWKSExplicitURLParam `json:",omitzero,inline"` + OfInline *BetaJWKSInlineParam `json:",omitzero,inline"` + paramUnion +} + +func (u BetaOrganizationFederationIssuerNewParamsJWKSUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfDiscovery, u.OfExplicitURL, u.OfInline) +} +func (u *BetaOrganizationFederationIssuerNewParamsJWKSUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *BetaOrganizationFederationIssuerNewParamsJWKSUnion) asAny() any { + if !param.IsOmitted(u.OfDiscovery) { + return u.OfDiscovery + } else if !param.IsOmitted(u.OfExplicitURL) { + return u.OfExplicitURL + } else if !param.IsOmitted(u.OfInline) { + return u.OfInline + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaOrganizationFederationIssuerNewParamsJWKSUnion) GetDiscoveryBase() *string { + if vt := u.OfDiscovery; vt != nil && vt.DiscoveryBase.Valid() { + return &vt.DiscoveryBase.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaOrganizationFederationIssuerNewParamsJWKSUnion) GetURL() *string { + if vt := u.OfExplicitURL; vt != nil { + return &vt.URL + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaOrganizationFederationIssuerNewParamsJWKSUnion) GetKeys() []map[string]any { + if vt := u.OfInline; vt != nil { + return vt.Keys + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaOrganizationFederationIssuerNewParamsJWKSUnion) GetType() *string { + if vt := u.OfDiscovery; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfExplicitURL; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfInline; vt != nil { + return (*string)(&vt.Type) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaOrganizationFederationIssuerNewParamsJWKSUnion) GetCACertPEM() *string { + if vt := u.OfDiscovery; vt != nil && vt.CACertPEM.Valid() { + return &vt.CACertPEM.Value + } else if vt := u.OfExplicitURL; vt != nil && vt.CACertPEM.Valid() { + return &vt.CACertPEM.Value + } + return nil +} + +func init() { + apijson.RegisterUnion[BetaOrganizationFederationIssuerNewParamsJWKSUnion]( + "type", + apijson.Discriminator[BetaJWKSDiscoveryParam]("discovery"), + apijson.Discriminator[BetaJWKSExplicitURLParam]("explicit_url"), + apijson.Discriminator[BetaJWKSInlineParam]("inline"), + ) +} + +type BetaOrganizationFederationIssuerGetParams struct { + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +type BetaOrganizationFederationIssuerUpdateParams struct { + // Whether the jwt-bearer exchange enforces JTI single-use (replay protection) for + // tokens from this issuer. Applies only to assertions carrying a `jti` claim; + // tokens without one are accepted without single-use enforcement. + CheckJTI param.Opt[bool] `json:"check_jti,omitzero"` + // Replaces the `iss` claim value to match against. For discovery-mode issuers + // without a `discovery_base`, this is also the URL Anthropic fetches the OIDC + // discovery document and signing keys from, so changing it repoints the JWKS + // source. Changing the issuer URL to a well-known shared platform is rejected + // while any live rule under this issuer would not constrain tenant identity. + IssuerURL param.Opt[string] `json:"issuer_url,omitzero"` + // Only `false` is accepted, to re-enable polling after the system pauses it. + // Polling is paused automatically; sending `true` is rejected. + JWKSPollingDisabled param.Opt[bool] `json:"jwks_polling_disabled,omitzero"` + // Maximum allowed iat→exp spread for assertions from this issuer (1-176400 + // seconds, i.e. up to 49h). Assertions must carry both `iat` and `exp`; a missing + // `iat` is rejected. + MaxJWTLifetimeSeconds param.Opt[int64] `json:"max_jwt_lifetime_seconds,omitzero"` + // Replaces the slug identifier (lowercase, digits, hyphens). Unique within the + // organization; a duplicate name returns 409. + Name param.Opt[string] `json:"name,omitzero"` + // Replaces the entire JWKS configuration. + JWKS BetaOrganizationFederationIssuerUpdateParamsJWKSUnion `json:"jwks,omitzero"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +func (r BetaOrganizationFederationIssuerUpdateParams) MarshalJSON() (data []byte, err error) { + type shadow BetaOrganizationFederationIssuerUpdateParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaOrganizationFederationIssuerUpdateParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaOrganizationFederationIssuerUpdateParamsJWKSUnion struct { + OfDiscovery *BetaJWKSDiscoveryParam `json:",omitzero,inline"` + OfExplicitURL *BetaJWKSExplicitURLParam `json:",omitzero,inline"` + OfInline *BetaJWKSInlineParam `json:",omitzero,inline"` + paramUnion +} + +func (u BetaOrganizationFederationIssuerUpdateParamsJWKSUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfDiscovery, u.OfExplicitURL, u.OfInline) +} +func (u *BetaOrganizationFederationIssuerUpdateParamsJWKSUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *BetaOrganizationFederationIssuerUpdateParamsJWKSUnion) asAny() any { + if !param.IsOmitted(u.OfDiscovery) { + return u.OfDiscovery + } else if !param.IsOmitted(u.OfExplicitURL) { + return u.OfExplicitURL + } else if !param.IsOmitted(u.OfInline) { + return u.OfInline + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaOrganizationFederationIssuerUpdateParamsJWKSUnion) GetDiscoveryBase() *string { + if vt := u.OfDiscovery; vt != nil && vt.DiscoveryBase.Valid() { + return &vt.DiscoveryBase.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaOrganizationFederationIssuerUpdateParamsJWKSUnion) GetURL() *string { + if vt := u.OfExplicitURL; vt != nil { + return &vt.URL + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaOrganizationFederationIssuerUpdateParamsJWKSUnion) GetKeys() []map[string]any { + if vt := u.OfInline; vt != nil { + return vt.Keys + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaOrganizationFederationIssuerUpdateParamsJWKSUnion) GetType() *string { + if vt := u.OfDiscovery; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfExplicitURL; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfInline; vt != nil { + return (*string)(&vt.Type) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaOrganizationFederationIssuerUpdateParamsJWKSUnion) GetCACertPEM() *string { + if vt := u.OfDiscovery; vt != nil && vt.CACertPEM.Valid() { + return &vt.CACertPEM.Value + } else if vt := u.OfExplicitURL; vt != nil && vt.CACertPEM.Valid() { + return &vt.CACertPEM.Value + } + return nil +} + +func init() { + apijson.RegisterUnion[BetaOrganizationFederationIssuerUpdateParamsJWKSUnion]( + "type", + apijson.Discriminator[BetaJWKSDiscoveryParam]("discovery"), + apijson.Discriminator[BetaJWKSExplicitURLParam]("explicit_url"), + apijson.Discriminator[BetaJWKSInlineParam]("inline"), + ) +} + +type BetaOrganizationFederationIssuerListParams struct { + // Opaque cursor from a previous response's `next_page`. + Page param.Opt[string] `query:"page,omitzero" json:"-"` + // Include archived resources. Defaults to false. + IncludeArchived param.Opt[bool] `query:"include_archived,omitzero" json:"-"` + // Number of results per page. + Limit param.Opt[int64] `query:"limit,omitzero" json:"-"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +// URLQuery serializes [BetaOrganizationFederationIssuerListParams]'s query +// parameters as `url.Values`. +func (r BetaOrganizationFederationIssuerListParams) URLQuery() (v url.Values, err error) { + return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ + ArrayFormat: apiquery.ArrayQueryFormatBrackets, + NestedFormat: apiquery.NestedQueryFormatBrackets, + }) +} + +type BetaOrganizationFederationIssuerArchiveParams struct { + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/betaorganizationfederationrule.go b/vendor/github.com/anthropics/anthropic-sdk-go/betaorganizationfederationrule.go new file mode 100644 index 000000000..804078f10 --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/betaorganizationfederationrule.go @@ -0,0 +1,583 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +package anthropic + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/url" + "slices" + "time" + + "github.com/anthropics/anthropic-sdk-go/internal/apijson" + "github.com/anthropics/anthropic-sdk-go/internal/apiquery" + "github.com/anthropics/anthropic-sdk-go/internal/requestconfig" + "github.com/anthropics/anthropic-sdk-go/option" + "github.com/anthropics/anthropic-sdk-go/packages/pagination" + "github.com/anthropics/anthropic-sdk-go/packages/param" + "github.com/anthropics/anthropic-sdk-go/packages/respjson" + "github.com/anthropics/anthropic-sdk-go/shared/constant" +) + +// BetaOrganizationFederationRuleService contains methods and other services that +// help with interacting with the anthropic API. +// +// Note, unlike clients, this service does not read variables from the environment +// automatically. You should not instantiate this service directly, and instead use +// the [NewBetaOrganizationFederationRuleService] method instead. +type BetaOrganizationFederationRuleService struct { + Options []option.RequestOption + Workspaces BetaOrganizationFederationRuleWorkspaceService +} + +// NewBetaOrganizationFederationRuleService generates a new service that applies +// the given options to each request. These options are applied after the parent +// client's options (if there is one), and before any request-specific options. +func NewBetaOrganizationFederationRuleService(opts ...option.RequestOption) (r BetaOrganizationFederationRuleService) { + r = BetaOrganizationFederationRuleService{} + r.Options = opts + r.Workspaces = NewBetaOrganizationFederationRuleWorkspaceService(opts...) + return +} + +// **Requires an OAuth access token with the `org:admin` scope**, from +// `ant auth login --scope org:admin` or a workload identity federation rule; Admin +// API keys are not accepted. See +// [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api). +// +// Create a federation rule owned by your organization. +// +// The referenced issuer and the target service account must already exist in the +// same organization; invalid references are rejected with a 400 error. The +// workspace reference is validated. Membership is not checked at rule creation: +// token exchange resolves a single enabled workspace per call and is rejected +// unless the target service account is a member of that workspace (it is +// implicitly a member of the default workspace). Rules on well-known shared +// issuers (GitHub Actions, GitLab, Buildkite, Terraform Cloud, Google) must +// constrain tenant identity via an identity-bearing claim, a tenant-pinning +// subject prefix (such as `repo:YOUR_ORG/...`), or a CEL condition referencing one +// of those identity claims (e.g. `claims.repository_owner`). OAuth callers may +// only manage rules whose `oauth_scope` is `workspace:developer` or +// `workspace:inference`; other scopes require a Console session. +func (r *BetaOrganizationFederationRuleService) New(ctx context.Context, params BetaOrganizationFederationRuleNewParams, opts ...option.RequestOption) (res *BetaFederationRule, err error) { + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + path := "v1/organizations/federation_rules?beta=true" + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, params, &res, opts...) + return res, err +} + +// **Requires an OAuth access token with the `org:admin` scope**, from +// `ant auth login --scope org:admin` or a workload identity federation rule; Admin +// API keys are not accepted. See +// [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api). +// +// Retrieve a federation rule by its ID (`fdrl_...`). +func (r *BetaOrganizationFederationRuleService) Get(ctx context.Context, federationRuleID string, query BetaOrganizationFederationRuleGetParams, opts ...option.RequestOption) (res *BetaFederationRule, err error) { + for _, v := range query.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + if federationRuleID == "" { + err = errors.New("missing required federation_rule_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/organizations/federation_rules/%s?beta=true", federationRuleID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...) + return res, err +} + +// **Requires an OAuth access token with the `org:admin` scope**, from +// `ant auth login --scope org:admin` or a workload identity federation rule; Admin +// API keys are not accepted. See +// [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api). +// +// Partially update a federation rule. +// +// `issuer_id` is immutable. `match` and `target` are replaced as whole objects +// when set. Referenced service accounts and workspaces must exist in your +// organization; invalid references are rejected with a 400 error. Archived rules +// cannot be updated; this returns 400. Create a new rule instead. Rules on +// well-known shared issuers (GitHub Actions, GitLab, Buildkite, Terraform Cloud, +// Google) must constrain tenant identity via an identity-bearing claim, a +// tenant-pinning subject prefix (such as `repo:YOUR_ORG/...`), or a CEL condition +// referencing one of those identity claims (e.g. `claims.repository_owner`). On +// these issuers the requirement is re-checked on every update; if an existing +// rule's stored match does not yet constrain tenant identity, any update (even a +// rename or description change) must also supply a conforming `match` in the same +// request. OAuth callers may only manage rules whose `oauth_scope` is +// `workspace:developer` or `workspace:inference`; other scopes require a Console +// session. +func (r *BetaOrganizationFederationRuleService) Update(ctx context.Context, federationRuleID string, params BetaOrganizationFederationRuleUpdateParams, opts ...option.RequestOption) (res *BetaFederationRule, err error) { + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + if federationRuleID == "" { + err = errors.New("missing required federation_rule_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/organizations/federation_rules/%s?beta=true", federationRuleID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, params, &res, opts...) + return res, err +} + +// **Requires an OAuth access token with the `org:admin` scope**, from +// `ant auth login --scope org:admin` or a workload identity federation rule; Admin +// API keys are not accepted. See +// [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api). +// +// List federation rules in your organization. +// +// Optionally filter by issuer with `issuer_id`. Archived rules are excluded unless +// `include_archived=true`. +func (r *BetaOrganizationFederationRuleService) List(ctx context.Context, params BetaOrganizationFederationRuleListParams, opts ...option.RequestOption) (res *pagination.PageCursor[BetaFederationRule], err error) { + var raw *http.Response + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithResponseInto(&raw)}, opts...) + path := "v1/organizations/federation_rules?beta=true" + cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, params, &res, opts...) + if err != nil { + return nil, err + } + err = cfg.Execute() + if err != nil { + return nil, err + } + res.SetPageConfig(cfg, raw) + return res, nil +} + +// **Requires an OAuth access token with the `org:admin` scope**, from +// `ant auth login --scope org:admin` or a workload identity federation rule; Admin +// API keys are not accepted. See +// [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api). +// +// List federation rules in your organization. +// +// Optionally filter by issuer with `issuer_id`. Archived rules are excluded unless +// `include_archived=true`. +func (r *BetaOrganizationFederationRuleService) ListAutoPaging(ctx context.Context, params BetaOrganizationFederationRuleListParams, opts ...option.RequestOption) *pagination.PageCursorAutoPager[BetaFederationRule] { + return pagination.NewPageCursorAutoPager(r.List(ctx, params, opts...)) +} + +// **Requires an OAuth access token with the `org:admin` scope**, from +// `ant auth login --scope org:admin` or a workload identity federation rule; Admin +// API keys are not accepted. See +// [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api). +// +// Archive a federation rule. +// +// Token exchange through this rule stops immediately. Idempotent; re-archiving +// returns the rule with its original `archived_at`. Archiving clears the rule's +// workspace targeting (`workspace_id` and `workspace_ids` are emptied). Tokens +// already minted before archive remain valid until they expire. OAuth callers may +// only manage rules whose `oauth_scope` is `workspace:developer` or +// `workspace:inference`; other scopes require a Console session. +func (r *BetaOrganizationFederationRuleService) Archive(ctx context.Context, federationRuleID string, body BetaOrganizationFederationRuleArchiveParams, opts ...option.RequestOption) (res *BetaFederationRule, err error) { + for _, v := range body.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + if federationRuleID == "" { + err = errors.New("missing required federation_rule_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/organizations/federation_rules/%s/archive?beta=true", federationRuleID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, nil, &res, opts...) + return res, err +} + +// Authorization rule binding an external OIDC identity to Anthropic. +// +// Evaluates the match conditions and mints an OAuth access token for the resolved +// target, scoped to a single workspace where the rule is enabled (chosen by the +// caller at exchange time when the rule is enabled for more than one). For rules +// enabled via `workspace_ids` or `applies_to_all_workspaces`, the target service +// account must be a member of that workspace (it is implicitly a member of the +// default workspace); rules carrying only the legacy `workspace_id` binding do not +// enforce this. +type BetaFederationRule struct { + // Tagged ID of the federation rule. + ID string `json:"id" api:"required"` + // When true, this rule is enabled for every workspace in the org (including ones + // created after the rule). `workspace_ids` is ignored at exchange time. + AppliesToAllWorkspaces bool `json:"applies_to_all_workspaces" api:"required"` + // If set, this rule is archived and rejects token exchange. + ArchivedAt time.Time `json:"archived_at" api:"required" format:"date-time"` + // Tagged ID (`user_`/`svac_`) of the actor that archived this rule. + ArchivedByActorID string `json:"archived_by_actor_id" api:"required"` + // CEL expressions extracting named values from claims. Not yet supported; always + // null. + Attributes map[string]string `json:"attributes" api:"required"` + // When this rule was created. + CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"` + // Tagged ID (`user_`/`svac_`) of the actor that created this rule. + CreatedByActorID string `json:"created_by_actor_id" api:"required"` + // Optional free-text description. + Description string `json:"description" api:"required"` + // Tagged ID of the issuer whose tokens this rule accepts. + IssuerID string `json:"issuer_id" api:"required"` + // Issuer's display name at read time. + IssuerName string `json:"issuer_name" api:"required"` + // Conditions the verified JWT must satisfy for this rule to apply. All populated + // matcher fields must pass. + Match BetaFederationRuleMatch `json:"match" api:"required"` + // Admin-chosen slug identifier. + Name string `json:"name" api:"required"` + // Space-separated OAuth scopes granted on the minted token. + OAuthScope string `json:"oauth_scope" api:"required"` + // Identity that tokens minted via this rule act as. Currently always a + // `service_account` target. + Target BetaServiceAccountTarget `json:"target" api:"required"` + // Lifetime in seconds of access tokens minted via this rule. Minted tokens are + // capped at `max(60, min(this value, 2 × remaining assertion validity))` seconds. + TokenLifetimeSeconds int64 `json:"token_lifetime_seconds" api:"required"` + Type constant.FederationRule `json:"type" default:"federation_rule"` + // When this rule was last updated. + UpdatedAt time.Time `json:"updated_at" api:"required" format:"date-time"` + // Tagged ID (`user_`/`svac_`) of the actor that last updated this rule. + UpdatedByActorID string `json:"updated_by_actor_id" api:"required"` + // Legacy single-workspace binding. Prefer `workspace_ids` and the + // `/federation_rules/{federation_rule_id}/workspaces` sub-resource for managing + // workspace enablement. + WorkspaceID string `json:"workspace_id" api:"required"` + // Tagged IDs of the workspaces this rule is enabled for. May be empty for older + // rules that only carry the legacy `workspace_id` binding. Ignored at exchange + // time when `applies_to_all_workspaces` is true (the list may still be non-empty). + WorkspaceIDs []string `json:"workspace_ids" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + AppliesToAllWorkspaces respjson.Field + ArchivedAt respjson.Field + ArchivedByActorID respjson.Field + Attributes respjson.Field + CreatedAt respjson.Field + CreatedByActorID respjson.Field + Description respjson.Field + IssuerID respjson.Field + IssuerName respjson.Field + Match respjson.Field + Name respjson.Field + OAuthScope respjson.Field + Target respjson.Field + TokenLifetimeSeconds respjson.Field + Type respjson.Field + UpdatedAt respjson.Field + UpdatedByActorID respjson.Field + WorkspaceID respjson.Field + WorkspaceIDs respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaFederationRule) RawJSON() string { return r.JSON.raw } +func (r *BetaFederationRule) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Does the incoming JWT qualify? +// +// All populated fields must pass; omitted fields are skipped. At least one of +// `subject_prefix` (other than a wildcard-only value like `*`), `claims`, or +// `condition` is required; `audience` alone is not sufficient. +type BetaFederationRuleMatch struct { + // Exact match against the `aud` claim (any element if array). When omitted, the + // JWT's `aud` must still equal Anthropic's expected audience for the issuer; + // setting this field overrides that default. + Audience string `json:"audience" api:"nullable"` + // Exact-match `{claim: value}` pairs against top-level claims. Only string-valued + // claims can be matched; use `condition` for non-string claims. + Claims map[string]string `json:"claims" api:"nullable"` + // CEL expression over claims for logic the structural fields can't express. Must + // evaluate to a boolean and may reference only the `claims` variable; a + // constant-true expression (such as `true`) is rejected with 400. + Condition string `json:"condition" api:"nullable"` + // Match the verified JWT `sub` claim. Exact match unless the value ends with `*`, + // in which case it is a prefix match. Example: + // `repo:my-org/my-repo:ref:refs/heads/main`. + SubjectPrefix string `json:"subject_prefix" api:"nullable"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Audience respjson.Field + Claims respjson.Field + Condition respjson.Field + SubjectPrefix respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaFederationRuleMatch) RawJSON() string { return r.JSON.raw } +func (r *BetaFederationRuleMatch) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// ToParam converts this BetaFederationRuleMatch to a BetaFederationRuleMatchParam. +// +// Warning: the fields of the param type will not be present. ToParam should only +// be used at the last possible moment before sending a request. Test for this with +// BetaFederationRuleMatchParam.Overrides() +func (r BetaFederationRuleMatch) ToParam() BetaFederationRuleMatchParam { + return param.Override[BetaFederationRuleMatchParam](json.RawMessage(r.RawJSON())) +} + +// Does the incoming JWT qualify? +// +// All populated fields must pass; omitted fields are skipped. At least one of +// `subject_prefix` (other than a wildcard-only value like `*`), `claims`, or +// `condition` is required; `audience` alone is not sufficient. +type BetaFederationRuleMatchParam struct { + // Exact match against the `aud` claim (any element if array). When omitted, the + // JWT's `aud` must still equal Anthropic's expected audience for the issuer; + // setting this field overrides that default. + Audience param.Opt[string] `json:"audience,omitzero"` + // CEL expression over claims for logic the structural fields can't express. Must + // evaluate to a boolean and may reference only the `claims` variable; a + // constant-true expression (such as `true`) is rejected with 400. + Condition param.Opt[string] `json:"condition,omitzero"` + // Match the verified JWT `sub` claim. Exact match unless the value ends with `*`, + // in which case it is a prefix match. Example: + // `repo:my-org/my-repo:ref:refs/heads/main`. + SubjectPrefix param.Opt[string] `json:"subject_prefix,omitzero"` + // Exact-match `{claim: value}` pairs against top-level claims. Only string-valued + // claims can be matched; use `condition` for non-string claims. + Claims map[string]string `json:"claims,omitzero"` + paramObj +} + +func (r BetaFederationRuleMatchParam) MarshalJSON() (data []byte, err error) { + type shadow BetaFederationRuleMatchParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaFederationRuleMatchParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaFederationRuleWorkspace struct { + // When this workspace was enabled for the rule. + CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"` + // Tagged ID (`user_...` or `svac_...`) of the actor that enabled this workspace + // for the rule, if known. + CreatedByActorID string `json:"created_by_actor_id" api:"required"` + // Tagged ID of the federation rule. + FederationRuleID string `json:"federation_rule_id" api:"required"` + Type constant.FederationRuleWorkspace `json:"type" default:"federation_rule_workspace"` + // Tagged ID of the workspace this rule is enabled for. + WorkspaceID string `json:"workspace_id" api:"required"` + // Workspace display name. Populated when listing; null in the enable response. + WorkspaceName string `json:"workspace_name" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + CreatedAt respjson.Field + CreatedByActorID respjson.Field + FederationRuleID respjson.Field + Type respjson.Field + WorkspaceID respjson.Field + WorkspaceName respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaFederationRuleWorkspace) RawJSON() string { return r.JSON.raw } +func (r *BetaFederationRuleWorkspace) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Bind to a fixed service account by ID. +type BetaServiceAccountTarget struct { + // Tagged ID of the service account to mint tokens for. + ServiceAccountID string `json:"service_account_id" api:"required"` + Type constant.ServiceAccount `json:"type" default:"service_account"` + // Service account's display name at read time. Ignored on writes. + ServiceAccountName string `json:"service_account_name" api:"nullable"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ServiceAccountID respjson.Field + Type respjson.Field + ServiceAccountName respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaServiceAccountTarget) RawJSON() string { return r.JSON.raw } +func (r *BetaServiceAccountTarget) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// ToParam converts this BetaServiceAccountTarget to a +// BetaServiceAccountTargetParam. +// +// Warning: the fields of the param type will not be present. ToParam should only +// be used at the last possible moment before sending a request. Test for this with +// BetaServiceAccountTargetParam.Overrides() +func (r BetaServiceAccountTarget) ToParam() BetaServiceAccountTargetParam { + return param.Override[BetaServiceAccountTargetParam](json.RawMessage(r.RawJSON())) +} + +// Bind to a fixed service account by ID. +// +// The properties ServiceAccountID, Type are required. +type BetaServiceAccountTargetParam struct { + // Tagged ID of the service account to mint tokens for. + ServiceAccountID string `json:"service_account_id" api:"required"` + // Service account's display name at read time. Ignored on writes. + ServiceAccountName param.Opt[string] `json:"service_account_name,omitzero"` + // This field can be elided, and will marshal its zero value as "service_account". + Type constant.ServiceAccount `json:"type" default:"service_account"` + paramObj +} + +func (r BetaServiceAccountTargetParam) MarshalJSON() (data []byte, err error) { + type shadow BetaServiceAccountTargetParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaServiceAccountTargetParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaOrganizationFederationRuleNewParams struct { + // Tagged ID of the federation issuer. + IssuerID string `json:"issuer_id" api:"required"` + // Conditions the verified JWT must satisfy for this rule to apply. At least one of + // `subject_prefix` (other than a wildcard-only value like `*`), `claims`, or + // `condition` is required; `audience` alone is not sufficient. + Match BetaFederationRuleMatchParam `json:"match,omitzero" api:"required"` + // Slug identifier (lowercase, digits, hyphens). Unique within the organization; a + // duplicate name returns 409. + Name string `json:"name" api:"required"` + // Space-separated OAuth scopes. OAuth callers may only set `workspace:developer` + // or `workspace:inference`; other scopes (such as `org:admin`) require a Console + // session. + OAuthScope string `json:"oauth_scope" api:"required"` + // Identity that tokens minted via this rule act as. Currently always a + // `service_account` target. + Target BetaServiceAccountTargetParam `json:"target,omitzero" api:"required"` + // Optional free-text description. + Description param.Opt[string] `json:"description,omitzero"` + // Tagged ID of the workspace to enable this rule for. Required unless + // `applies_to_all_workspaces` is true. Additional workspaces can be added via the + // `/federation_rules/{federation_rule_id}/workspaces` sub-resource. + WorkspaceID param.Opt[string] `json:"workspace_id,omitzero"` + // When true, enable this rule for every workspace in the org (including workspaces + // created later). + AppliesToAllWorkspaces param.Opt[bool] `json:"applies_to_all_workspaces,omitzero"` + // Lifetime in seconds for access tokens minted via this rule (60-86400). Defaults + // to 3600 (1h). Minted tokens are capped at + // `max(60, min(this value, 2 × remaining assertion validity))` seconds. + TokenLifetimeSeconds param.Opt[int64] `json:"token_lifetime_seconds,omitzero"` + // CEL expressions `{name: expr}` extracting named values from claims. Not yet + // supported; any non-empty value is rejected with 400. + Attributes map[string]string `json:"attributes,omitzero"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +func (r BetaOrganizationFederationRuleNewParams) MarshalJSON() (data []byte, err error) { + type shadow BetaOrganizationFederationRuleNewParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaOrganizationFederationRuleNewParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaOrganizationFederationRuleGetParams struct { + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +type BetaOrganizationFederationRuleUpdateParams struct { + // When true, enables this rule for every workspace in the org (including + // workspaces created later). Setting `false` is rejected with 400 if no workspace + // would remain enabled; a rule with only a legacy `workspace_id` binding continues + // to mint. + AppliesToAllWorkspaces param.Opt[bool] `json:"applies_to_all_workspaces,omitzero"` + // Replaces the description. Omit to leave unchanged; send `null` to clear (the + // field is stored as an empty string). + Description param.Opt[string] `json:"description,omitzero"` + // Replaces the slug identifier (lowercase, digits, hyphens). Unique within the + // organization; a duplicate name returns 409. + Name param.Opt[string] `json:"name,omitzero"` + // Replaces the space-separated OAuth scopes granted on minted tokens. OAuth + // callers may only set `workspace:developer` or `workspace:inference`; other + // scopes (such as `org:admin`) require a Console session. + OAuthScope param.Opt[string] `json:"oauth_scope,omitzero"` + // Replaces the lifetime in seconds for access tokens minted via this rule + // (60-86400). Minted tokens are capped at + // `max(60, min(this value, 2 × remaining assertion validity))` seconds. + TokenLifetimeSeconds param.Opt[int64] `json:"token_lifetime_seconds,omitzero"` + // Replaces the existing single workspace enablement (the previous one is removed). + // Rejected with 400 if the rule is enabled for more than one workspace; use the + // `/federation_rules/{federation_rule_id}/workspaces` sub-resource instead. + WorkspaceID param.Opt[string] `json:"workspace_id,omitzero"` + // Replaces the CEL expressions `{name: expr}` extracting named values from claims. + // Send null to clear them. Not yet supported; any non-empty value is rejected + // with 400. + Attributes map[string]string `json:"attributes,omitzero"` + // Does the incoming JWT qualify? + // + // All populated fields must pass; omitted fields are skipped. At least one of + // `subject_prefix` (other than a wildcard-only value like `*`), `claims`, or + // `condition` is required; `audience` alone is not sufficient. + Match BetaFederationRuleMatchParam `json:"match,omitzero"` + // Bind to a fixed service account by ID. + Target BetaServiceAccountTargetParam `json:"target,omitzero"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +func (r BetaOrganizationFederationRuleUpdateParams) MarshalJSON() (data []byte, err error) { + type shadow BetaOrganizationFederationRuleUpdateParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaOrganizationFederationRuleUpdateParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaOrganizationFederationRuleListParams struct { + // Filter to rules referencing this federation issuer. + IssuerID param.Opt[string] `query:"issuer_id,omitzero" json:"-"` + // Opaque cursor from a previous response's `next_page`. + Page param.Opt[string] `query:"page,omitzero" json:"-"` + // Include archived resources. Defaults to false. + IncludeArchived param.Opt[bool] `query:"include_archived,omitzero" json:"-"` + // Number of results per page. + Limit param.Opt[int64] `query:"limit,omitzero" json:"-"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +// URLQuery serializes [BetaOrganizationFederationRuleListParams]'s query +// parameters as `url.Values`. +func (r BetaOrganizationFederationRuleListParams) URLQuery() (v url.Values, err error) { + return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ + ArrayFormat: apiquery.ArrayQueryFormatBrackets, + NestedFormat: apiquery.NestedQueryFormatBrackets, + }) +} + +type BetaOrganizationFederationRuleArchiveParams struct { + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/betaorganizationfederationruleworkspace.go b/vendor/github.com/anthropics/anthropic-sdk-go/betaorganizationfederationruleworkspace.go new file mode 100644 index 000000000..755e98baa --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/betaorganizationfederationruleworkspace.go @@ -0,0 +1,214 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +package anthropic + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "slices" + + "github.com/anthropics/anthropic-sdk-go/internal/apijson" + "github.com/anthropics/anthropic-sdk-go/internal/apiquery" + "github.com/anthropics/anthropic-sdk-go/internal/requestconfig" + "github.com/anthropics/anthropic-sdk-go/option" + "github.com/anthropics/anthropic-sdk-go/packages/pagination" + "github.com/anthropics/anthropic-sdk-go/packages/param" + "github.com/anthropics/anthropic-sdk-go/packages/respjson" + "github.com/anthropics/anthropic-sdk-go/shared/constant" +) + +// BetaOrganizationFederationRuleWorkspaceService contains methods and other +// services that help with interacting with the anthropic API. +// +// Note, unlike clients, this service does not read variables from the environment +// automatically. You should not instantiate this service directly, and instead use +// the [NewBetaOrganizationFederationRuleWorkspaceService] method instead. +type BetaOrganizationFederationRuleWorkspaceService struct { + Options []option.RequestOption +} + +// NewBetaOrganizationFederationRuleWorkspaceService generates a new service that +// applies the given options to each request. These options are applied after the +// parent client's options (if there is one), and before any request-specific +// options. +func NewBetaOrganizationFederationRuleWorkspaceService(opts ...option.RequestOption) (r BetaOrganizationFederationRuleWorkspaceService) { + r = BetaOrganizationFederationRuleWorkspaceService{} + r.Options = opts + return +} + +// **Requires an OAuth access token with the `org:admin` scope**, from +// `ant auth login --scope org:admin` or a workload identity federation rule; Admin +// API keys are not accepted. See +// [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api). +// +// List workspaces where this federation rule is enabled. +// +// Returns all workspace enablements in a single response; the `limit` and `page` +// parameters are accepted but have no effect, and `next_page` is always `null`. +// Returns explicit per-workspace enablements only; for rules with +// `applies_to_all_workspaces` or a legacy single `workspace_id`, check those +// fields on the rule itself. +func (r *BetaOrganizationFederationRuleWorkspaceService) List(ctx context.Context, federationRuleID string, params BetaOrganizationFederationRuleWorkspaceListParams, opts ...option.RequestOption) (res *pagination.PageCursor[BetaFederationRuleWorkspace], err error) { + var raw *http.Response + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithResponseInto(&raw)}, opts...) + if federationRuleID == "" { + err = errors.New("missing required federation_rule_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/organizations/federation_rules/%s/workspaces?beta=true", federationRuleID) + cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, params, &res, opts...) + if err != nil { + return nil, err + } + err = cfg.Execute() + if err != nil { + return nil, err + } + res.SetPageConfig(cfg, raw) + return res, nil +} + +// **Requires an OAuth access token with the `org:admin` scope**, from +// `ant auth login --scope org:admin` or a workload identity federation rule; Admin +// API keys are not accepted. See +// [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api). +// +// List workspaces where this federation rule is enabled. +// +// Returns all workspace enablements in a single response; the `limit` and `page` +// parameters are accepted but have no effect, and `next_page` is always `null`. +// Returns explicit per-workspace enablements only; for rules with +// `applies_to_all_workspaces` or a legacy single `workspace_id`, check those +// fields on the rule itself. +func (r *BetaOrganizationFederationRuleWorkspaceService) ListAutoPaging(ctx context.Context, federationRuleID string, params BetaOrganizationFederationRuleWorkspaceListParams, opts ...option.RequestOption) *pagination.PageCursorAutoPager[BetaFederationRuleWorkspace] { + return pagination.NewPageCursorAutoPager(r.List(ctx, federationRuleID, params, opts...)) +} + +// **Requires an OAuth access token with the `org:admin` scope**, from +// `ant auth login --scope org:admin` or a workload identity federation rule; Admin +// API keys are not accepted. See +// [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api). +// +// Enable a federation rule for a workspace. +// +// Idempotent; re-enabling returns the existing enablement. The rule and workspace +// must both belong to your organization. Membership of the rule's target service +// account in this workspace is not checked at enablement: token exchange into this +// workspace is rejected unless the target is a member (it is implicitly a member +// of the default workspace). Archived rules are rejected with 400. OAuth callers +// may only manage rules whose `oauth_scope` is `workspace:developer` or +// `workspace:inference`; other scopes require a Console session. +func (r *BetaOrganizationFederationRuleWorkspaceService) Add(ctx context.Context, federationRuleID string, params BetaOrganizationFederationRuleWorkspaceAddParams, opts ...option.RequestOption) (res *BetaFederationRuleWorkspace, err error) { + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + if federationRuleID == "" { + err = errors.New("missing required federation_rule_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/organizations/federation_rules/%s/workspaces?beta=true", federationRuleID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, params, &res, opts...) + return res, err +} + +// **Requires an OAuth access token with the `org:admin` scope**, from +// `ant auth login --scope org:admin` or a workload identity federation rule; Admin +// API keys are not accepted. See +// [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api). +// +// Disable a federation rule for a workspace. +// +// Idempotent; succeeds even if the enablement was already removed. OAuth callers +// may only manage rules whose `oauth_scope` is `workspace:developer` or +// `workspace:inference`; other scopes require a Console session. +func (r *BetaOrganizationFederationRuleWorkspaceService) Remove(ctx context.Context, workspaceID string, params BetaOrganizationFederationRuleWorkspaceRemoveParams, opts ...option.RequestOption) (res *BetaOrganizationFederationRuleWorkspaceRemoveResponse, err error) { + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + if params.FederationRuleID == "" { + err = errors.New("missing required federation_rule_id parameter") + return nil, err + } + if workspaceID == "" { + err = errors.New("missing required workspace_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/organizations/federation_rules/%s/workspaces/%s?beta=true", params.FederationRuleID, workspaceID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodDelete, path, nil, &res, opts...) + return res, err +} + +type BetaOrganizationFederationRuleWorkspaceRemoveResponse struct { + // Tagged ID of the federation rule. + FederationRuleID string `json:"federation_rule_id" api:"required"` + Type constant.FederationRuleWorkspaceDeleted `json:"type" default:"federation_rule_workspace_deleted"` + // Tagged ID of the workspace named in the delete request. Removal is idempotent. + WorkspaceID string `json:"workspace_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + FederationRuleID respjson.Field + Type respjson.Field + WorkspaceID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaOrganizationFederationRuleWorkspaceRemoveResponse) RawJSON() string { return r.JSON.raw } +func (r *BetaOrganizationFederationRuleWorkspaceRemoveResponse) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaOrganizationFederationRuleWorkspaceListParams struct { + // Opaque cursor from a previous response's `next_page`. + Page param.Opt[string] `query:"page,omitzero" json:"-"` + // Number of results per page. + Limit param.Opt[int64] `query:"limit,omitzero" json:"-"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +// URLQuery serializes [BetaOrganizationFederationRuleWorkspaceListParams]'s query +// parameters as `url.Values`. +func (r BetaOrganizationFederationRuleWorkspaceListParams) URLQuery() (v url.Values, err error) { + return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ + ArrayFormat: apiquery.ArrayQueryFormatBrackets, + NestedFormat: apiquery.NestedQueryFormatBrackets, + }) +} + +type BetaOrganizationFederationRuleWorkspaceAddParams struct { + // Tagged ID of the workspace to enable this rule for. + WorkspaceID string `json:"workspace_id" api:"required"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +func (r BetaOrganizationFederationRuleWorkspaceAddParams) MarshalJSON() (data []byte, err error) { + type shadow BetaOrganizationFederationRuleWorkspaceAddParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaOrganizationFederationRuleWorkspaceAddParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaOrganizationFederationRuleWorkspaceRemoveParams struct { + // ID of the federation rule. + FederationRuleID string `path:"federation_rule_id" api:"required" json:"-"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/betaorganizationinvite.go b/vendor/github.com/anthropics/anthropic-sdk-go/betaorganizationinvite.go new file mode 100644 index 000000000..dd1aa08e3 --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/betaorganizationinvite.go @@ -0,0 +1,264 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +package anthropic + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "slices" + "time" + + "github.com/anthropics/anthropic-sdk-go/internal/apijson" + "github.com/anthropics/anthropic-sdk-go/internal/apiquery" + "github.com/anthropics/anthropic-sdk-go/internal/requestconfig" + "github.com/anthropics/anthropic-sdk-go/option" + "github.com/anthropics/anthropic-sdk-go/packages/pagination" + "github.com/anthropics/anthropic-sdk-go/packages/param" + "github.com/anthropics/anthropic-sdk-go/packages/respjson" + "github.com/anthropics/anthropic-sdk-go/shared/constant" +) + +// BetaOrganizationInviteService contains methods and other services that help with +// interacting with the anthropic API. +// +// Note, unlike clients, this service does not read variables from the environment +// automatically. You should not instantiate this service directly, and instead use +// the [NewBetaOrganizationInviteService] method instead. +type BetaOrganizationInviteService struct { + Options []option.RequestOption +} + +// NewBetaOrganizationInviteService generates a new service that applies the given +// options to each request. These options are applied after the parent client's +// options (if there is one), and before any request-specific options. +func NewBetaOrganizationInviteService(opts ...option.RequestOption) (r BetaOrganizationInviteService) { + r = BetaOrganizationInviteService{} + r.Options = opts + return +} + +// Invite a user to join the organization by email. +// +// On plans that draw members from a finite pool of purchased seats, the invite +// automatically consumes a seat from the lowest tier with availability; there is +// no seat-tier parameter. When no seat is free the request fails with a 400 error +// rather than purchasing a seat. +func (r *BetaOrganizationInviteService) New(ctx context.Context, body BetaOrganizationInviteNewParams, opts ...option.RequestOption) (res *BetaOrganizationInvite, err error) { + opts = slices.Concat(r.Options, opts) + path := "v1/organizations/invites?beta=true" + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...) + return res, err +} + +// Retrieve an invite by ID. +func (r *BetaOrganizationInviteService) Get(ctx context.Context, inviteID string, opts ...option.RequestOption) (res *BetaOrganizationInvite, err error) { + opts = slices.Concat(r.Options, opts) + if inviteID == "" { + err = errors.New("missing required invite_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/organizations/invites/%s?beta=true", inviteID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...) + return res, err +} + +// List the organization's invites. +func (r *BetaOrganizationInviteService) List(ctx context.Context, query BetaOrganizationInviteListParams, opts ...option.RequestOption) (res *pagination.Page[BetaOrganizationInvite], err error) { + var raw *http.Response + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithResponseInto(&raw)}, opts...) + path := "v1/organizations/invites?beta=true" + cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, query, &res, opts...) + if err != nil { + return nil, err + } + err = cfg.Execute() + if err != nil { + return nil, err + } + res.SetPageConfig(cfg, raw) + return res, nil +} + +// List the organization's invites. +func (r *BetaOrganizationInviteService) ListAutoPaging(ctx context.Context, query BetaOrganizationInviteListParams, opts ...option.RequestOption) *pagination.PageAutoPager[BetaOrganizationInvite] { + return pagination.NewPageAutoPager(r.List(ctx, query, opts...)) +} + +// Delete a pending invite. +func (r *BetaOrganizationInviteService) Delete(ctx context.Context, inviteID string, opts ...option.RequestOption) (res *BetaOrganizationInviteDeleteResponse, err error) { + opts = slices.Concat(r.Options, opts) + if inviteID == "" { + err = errors.New("missing required invite_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/organizations/invites/%s?beta=true", inviteID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodDelete, path, nil, &res, opts...) + return res, err +} + +type BetaOrganizationInvite struct { + // ID of the Invite. + ID string `json:"id" api:"required"` + // RFC 3339 datetime string indicating when the Invite was accepted, or null. + AcceptedAt time.Time `json:"accepted_at" api:"required" format:"date-time"` + // Email of the User being invited. + Email string `json:"email" api:"required"` + // RFC 3339 datetime string indicating when the Invite expires. + ExpiresAt time.Time `json:"expires_at" api:"required" format:"date-time"` + // RFC 3339 datetime string indicating when the Invite was created. + InvitedAt time.Time `json:"invited_at" api:"required" format:"date-time"` + // RBAC group IDs recorded on the Invite (Claude Enterprise organizations), to be + // assigned to the User when the Invite is accepted. `[]` when none. + RBACGroupIDs []string `json:"rbac_group_ids" api:"required"` + // Organization role of the User. + // + // Any of "admin", "billing", "claude_code_user", "developer", "managed", + // "membership_admin", "owner", "primary_owner", "user". + Role BetaOrganizationRole `json:"role" api:"required"` + // Status of the Invite. + // + // Any of "accepted", "deleted", "expired", "pending". + Status BetaOrganizationInviteStatus `json:"status" api:"required"` + // Object type. + // + // For Invites, this is always `"invite"`. + Type constant.Invite `json:"type" default:"invite"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + AcceptedAt respjson.Field + Email respjson.Field + ExpiresAt respjson.Field + InvitedAt respjson.Field + RBACGroupIDs respjson.Field + Role respjson.Field + Status respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaOrganizationInvite) RawJSON() string { return r.JSON.raw } +func (r *BetaOrganizationInvite) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Status of the Invite. +type BetaOrganizationInviteStatus string + +const ( + BetaOrganizationInviteStatusAccepted BetaOrganizationInviteStatus = "accepted" + BetaOrganizationInviteStatusDeleted BetaOrganizationInviteStatus = "deleted" + BetaOrganizationInviteStatusExpired BetaOrganizationInviteStatus = "expired" + BetaOrganizationInviteStatusPending BetaOrganizationInviteStatus = "pending" +) + +type BetaOrganizationInviteDeleteResponse struct { + // ID of the Invite. + ID string `json:"id" api:"required"` + // Deleted object type. + // + // For Invites, this is always `"invite_deleted"`. + Type constant.InviteDeleted `json:"type" default:"invite_deleted"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaOrganizationInviteDeleteResponse) RawJSON() string { return r.JSON.raw } +func (r *BetaOrganizationInviteDeleteResponse) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaOrganizationInviteNewParams struct { + // Email of the User. + Email string `json:"email" api:"required" format:"email"` + // Role for the invited User. + // + // The accepted values depend on the organization type. Console and API + // organizations accept `user`, `developer`, `billing`, and `claude_code_user`; + // `admin` cannot be assigned through the API. Claude Enterprise organizations + // accept `user` and `managed`. + // + // Any of "billing", "claude_code_user", "developer", "managed", "user". + Role BetaOrganizationInviteNewParamsRole `json:"role,omitzero" api:"required"` + // RBAC group IDs to assign to the User when the Invite is accepted. A non-empty + // array is accepted only for a Claude Enterprise organization with RBAC groups, + // and requires the key to carry the `write:rbac_groups` scope. + RBACGroupIDs []string `json:"rbac_group_ids,omitzero"` + paramObj +} + +func (r BetaOrganizationInviteNewParams) MarshalJSON() (data []byte, err error) { + type shadow BetaOrganizationInviteNewParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaOrganizationInviteNewParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Role for the invited User. +// +// The accepted values depend on the organization type. Console and API +// organizations accept `user`, `developer`, `billing`, and `claude_code_user`; +// `admin` cannot be assigned through the API. Claude Enterprise organizations +// accept `user` and `managed`. +type BetaOrganizationInviteNewParamsRole string + +const ( + BetaOrganizationInviteNewParamsRoleBilling BetaOrganizationInviteNewParamsRole = "billing" + BetaOrganizationInviteNewParamsRoleClaudeCodeUser BetaOrganizationInviteNewParamsRole = "claude_code_user" + BetaOrganizationInviteNewParamsRoleDeveloper BetaOrganizationInviteNewParamsRole = "developer" + BetaOrganizationInviteNewParamsRoleManaged BetaOrganizationInviteNewParamsRole = "managed" + BetaOrganizationInviteNewParamsRoleUser BetaOrganizationInviteNewParamsRole = "user" +) + +type BetaOrganizationInviteListParams struct { + // ID of the object to use as a cursor for pagination. When provided, returns the + // page of results immediately after this object. + AfterID param.Opt[string] `query:"after_id,omitzero" json:"-"` + // ID of the object to use as a cursor for pagination. When provided, returns the + // page of results immediately before this object. + BeforeID param.Opt[string] `query:"before_id,omitzero" json:"-"` + // Filter by the email address the Invite was sent to. Matches the same way as the + // Users list's `email` filter (normalized, case-insensitive). + Email param.Opt[string] `query:"email,omitzero" format:"email" json:"-"` + // Number of items to return per page. + // + // Defaults to `20`. Ranges from `1` to `1000`. + Limit param.Opt[int64] `query:"limit,omitzero" json:"-"` + // Filter to items whose `role` equals one of the supplied values. Repeatable; + // values are OR'ed together. + // + // Accepted values depend on the organization type: Console and API organizations + // accept `user`, `developer`, `billing`, `admin`, and `claude_code_user`; Claude + // Enterprise organizations accept `user`, `owner`, `primary_owner`, + // `membership_admin`, and `managed`. + Roles []string `query:"roles,omitzero" json:"-"` + // Filter by Invite status. Repeatable; values are OR'ed together. Omit to return + // `pending`, `accepted`, and `expired` Invites alike. + // + // Any of "accepted", "expired", "pending". + Statuses []string `query:"statuses,omitzero" json:"-"` + paramObj +} + +// URLQuery serializes [BetaOrganizationInviteListParams]'s query parameters as +// `url.Values`. +func (r BetaOrganizationInviteListParams) URLQuery() (v url.Values, err error) { + return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ + ArrayFormat: apiquery.ArrayQueryFormatBrackets, + NestedFormat: apiquery.NestedQueryFormatBrackets, + }) +} diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/betaorganizationratelimit.go b/vendor/github.com/anthropics/anthropic-sdk-go/betaorganizationratelimit.go new file mode 100644 index 000000000..74800e637 --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/betaorganizationratelimit.go @@ -0,0 +1,186 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +package anthropic + +import ( + "context" + "net/http" + "net/url" + "slices" + + "github.com/anthropics/anthropic-sdk-go/internal/apijson" + "github.com/anthropics/anthropic-sdk-go/internal/apiquery" + "github.com/anthropics/anthropic-sdk-go/internal/requestconfig" + "github.com/anthropics/anthropic-sdk-go/option" + "github.com/anthropics/anthropic-sdk-go/packages/pagination" + "github.com/anthropics/anthropic-sdk-go/packages/param" + "github.com/anthropics/anthropic-sdk-go/packages/respjson" + "github.com/anthropics/anthropic-sdk-go/shared/constant" +) + +// BetaOrganizationRateLimitService contains methods and other services that help +// with interacting with the anthropic API. +// +// Note, unlike clients, this service does not read variables from the environment +// automatically. You should not instantiate this service directly, and instead use +// the [NewBetaOrganizationRateLimitService] method instead. +type BetaOrganizationRateLimitService struct { + Options []option.RequestOption +} + +// NewBetaOrganizationRateLimitService generates a new service that applies the +// given options to each request. These options are applied after the parent +// client's options (if there is one), and before any request-specific options. +func NewBetaOrganizationRateLimitService(opts ...option.RequestOption) (r BetaOrganizationRateLimitService) { + r = BetaOrganizationRateLimitService{} + r.Options = opts + return +} + +// List Messages API rate limits for your organization. +// +// Each entry corresponds to one rate-limit group (either a model family or an +// API-surface category such as the Files API or Message Batches) and contains the +// set of limiter values that apply to it. +// +// This endpoint currently returns every matching entry in a single page regardless +// of `limit`; follow `next_page` so that clients keep working when pagination is +// enabled. +func (r *BetaOrganizationRateLimitService) List(ctx context.Context, query BetaOrganizationRateLimitListParams, opts ...option.RequestOption) (res *pagination.PageCursor[BetaOrganizationRateLimit], err error) { + var raw *http.Response + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithResponseInto(&raw)}, opts...) + path := "v1/organizations/rate_limits?beta=true" + cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, query, &res, opts...) + if err != nil { + return nil, err + } + err = cfg.Execute() + if err != nil { + return nil, err + } + res.SetPageConfig(cfg, raw) + return res, nil +} + +// List Messages API rate limits for your organization. +// +// Each entry corresponds to one rate-limit group (either a model family or an +// API-surface category such as the Files API or Message Batches) and contains the +// set of limiter values that apply to it. +// +// This endpoint currently returns every matching entry in a single page regardless +// of `limit`; follow `next_page` so that clients keep working when pagination is +// enabled. +func (r *BetaOrganizationRateLimitService) ListAutoPaging(ctx context.Context, query BetaOrganizationRateLimitListParams, opts ...option.RequestOption) *pagination.PageCursorAutoPager[BetaOrganizationRateLimit] { + return pagination.NewPageCursorAutoPager(r.List(ctx, query, opts...)) +} + +type BetaOrganizationRateLimit struct { + // Stable identifier for this rate-limit group within the organization. + ID string `json:"id" api:"required"` + // The kind of rate-limit group this entry represents. `model_group` entries apply + // to a family of models (listed in `models`); other values apply to an API-surface + // category and have `models` set to `null`. + // + // Any of "batch", "files", "model_group", "skills", "token_count", "web_search". + GroupType BetaOrganizationRateLimitGroupType `json:"group_type" api:"required"` + // The limiter values that apply to this group. + Limits []BetaOrganizationRateLimitValue `json:"limits" api:"required"` + // Model names this entry's limits apply to, including aliases. `null` when + // `group_type` is not `"model_group"`. + Models []string `json:"models" api:"required"` + // Object type. Always `rate_limit` for organization rate-limit entries. + Type constant.RateLimit `json:"type" default:"rate_limit"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + GroupType respjson.Field + Limits respjson.Field + Models respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaOrganizationRateLimit) RawJSON() string { return r.JSON.raw } +func (r *BetaOrganizationRateLimit) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The kind of rate-limit group this entry represents. `model_group` entries apply +// to a family of models (listed in `models`); other values apply to an API-surface +// category and have `models` set to `null`. +type BetaOrganizationRateLimitGroupType string + +const ( + BetaOrganizationRateLimitGroupTypeBatch BetaOrganizationRateLimitGroupType = "batch" + BetaOrganizationRateLimitGroupTypeFiles BetaOrganizationRateLimitGroupType = "files" + BetaOrganizationRateLimitGroupTypeModelGroup BetaOrganizationRateLimitGroupType = "model_group" + BetaOrganizationRateLimitGroupTypeSkills BetaOrganizationRateLimitGroupType = "skills" + BetaOrganizationRateLimitGroupTypeTokenCount BetaOrganizationRateLimitGroupType = "token_count" + BetaOrganizationRateLimitGroupTypeWebSearch BetaOrganizationRateLimitGroupType = "web_search" +) + +type BetaOrganizationRateLimitValue struct { + // The limiter type (for example, `requests_per_minute` or + // `input_tokens_per_minute`). + Type string `json:"type" api:"required"` + // The configured limit value for this limiter type. + Value int64 `json:"value" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Type respjson.Field + Value respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaOrganizationRateLimitValue) RawJSON() string { return r.JSON.raw } +func (r *BetaOrganizationRateLimitValue) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaOrganizationRateLimitListParams struct { + // Maximum number of items to return per page. Ranges from `1` to `1000`. + // + // Accepted for request-shape compatibility and currently ignored: every entry is + // returned in a single page. + Limit param.Opt[int64] `query:"limit,omitzero" json:"-"` + // Filter to the single entry containing this model. Accepts full model names and + // aliases. Returns 404 if the model is not found or has no rate limits for this + // organization. + Model param.Opt[string] `query:"model,omitzero" json:"-"` + // Opaque cursor from a previous response's `next_page`. + Page param.Opt[string] `query:"page,omitzero" json:"-"` + // Filter by group type. + // + // Any of "batch", "files", "model_group", "skills", "token_count", "web_search". + GroupType BetaOrganizationRateLimitListParamsGroupType `query:"group_type,omitzero" json:"-"` + paramObj +} + +// URLQuery serializes [BetaOrganizationRateLimitListParams]'s query parameters as +// `url.Values`. +func (r BetaOrganizationRateLimitListParams) URLQuery() (v url.Values, err error) { + return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ + ArrayFormat: apiquery.ArrayQueryFormatBrackets, + NestedFormat: apiquery.NestedQueryFormatBrackets, + }) +} + +// Filter by group type. +type BetaOrganizationRateLimitListParamsGroupType string + +const ( + BetaOrganizationRateLimitListParamsGroupTypeBatch BetaOrganizationRateLimitListParamsGroupType = "batch" + BetaOrganizationRateLimitListParamsGroupTypeFiles BetaOrganizationRateLimitListParamsGroupType = "files" + BetaOrganizationRateLimitListParamsGroupTypeModelGroup BetaOrganizationRateLimitListParamsGroupType = "model_group" + BetaOrganizationRateLimitListParamsGroupTypeSkills BetaOrganizationRateLimitListParamsGroupType = "skills" + BetaOrganizationRateLimitListParamsGroupTypeTokenCount BetaOrganizationRateLimitListParamsGroupType = "token_count" + BetaOrganizationRateLimitListParamsGroupTypeWebSearch BetaOrganizationRateLimitListParamsGroupType = "web_search" +) diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/betaorganizationserviceaccount.go b/vendor/github.com/anthropics/anthropic-sdk-go/betaorganizationserviceaccount.go new file mode 100644 index 000000000..e24261e48 --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/betaorganizationserviceaccount.go @@ -0,0 +1,376 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +package anthropic + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "slices" + "time" + + "github.com/anthropics/anthropic-sdk-go/internal/apijson" + "github.com/anthropics/anthropic-sdk-go/internal/apiquery" + "github.com/anthropics/anthropic-sdk-go/internal/requestconfig" + "github.com/anthropics/anthropic-sdk-go/option" + "github.com/anthropics/anthropic-sdk-go/packages/pagination" + "github.com/anthropics/anthropic-sdk-go/packages/param" + "github.com/anthropics/anthropic-sdk-go/packages/respjson" + "github.com/anthropics/anthropic-sdk-go/shared/constant" +) + +// BetaOrganizationServiceAccountService contains methods and other services that +// help with interacting with the anthropic API. +// +// Note, unlike clients, this service does not read variables from the environment +// automatically. You should not instantiate this service directly, and instead use +// the [NewBetaOrganizationServiceAccountService] method instead. +type BetaOrganizationServiceAccountService struct { + Options []option.RequestOption + Workspaces BetaOrganizationServiceAccountWorkspaceService +} + +// NewBetaOrganizationServiceAccountService generates a new service that applies +// the given options to each request. These options are applied after the parent +// client's options (if there is one), and before any request-specific options. +func NewBetaOrganizationServiceAccountService(opts ...option.RequestOption) (r BetaOrganizationServiceAccountService) { + r = BetaOrganizationServiceAccountService{} + r.Options = opts + r.Workspaces = NewBetaOrganizationServiceAccountWorkspaceService(opts...) + return +} + +// **Requires an OAuth access token with the `org:admin` scope**, from +// `ant auth login --scope org:admin` or a workload identity federation rule; Admin +// API keys are not accepted. See +// [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api). +// +// Create a service account. +// +// A service account is a named workload identity that federation rules target. +// `organization_role` is `developer` (default) or `admin`; a rule may only be +// created or retargeted to grant `org:admin` scope when the target's +// `organization_role` is `admin`. Creating an `admin`-role service account +// requires an interactive credential (a user OAuth token or a Console session) — a +// workload may only create `developer`-role service accounts. +func (r *BetaOrganizationServiceAccountService) New(ctx context.Context, params BetaOrganizationServiceAccountNewParams, opts ...option.RequestOption) (res *BetaServiceAccount, err error) { + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + path := "v1/organizations/service_accounts?beta=true" + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, params, &res, opts...) + return res, err +} + +// **Requires an OAuth access token with the `org:admin` scope**, from +// `ant auth login --scope org:admin` or a workload identity federation rule; Admin +// API keys are not accepted. See +// [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api). +// +// Retrieve a service account by its ID (`svac_...`). +func (r *BetaOrganizationServiceAccountService) Get(ctx context.Context, serviceAccountID string, query BetaOrganizationServiceAccountGetParams, opts ...option.RequestOption) (res *BetaServiceAccount, err error) { + for _, v := range query.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + if serviceAccountID == "" { + err = errors.New("missing required service_account_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/organizations/service_accounts/%s?beta=true", serviceAccountID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...) + return res, err +} + +// **Requires an OAuth access token with the `org:admin` scope**, from +// `ant auth login --scope org:admin` or a workload identity federation rule; Admin +// API keys are not accepted. See +// [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api). +// +// Update a service account. +// +// Only `description` and `organization_role` are mutable; `name` cannot be +// changed. Archived service accounts cannot be updated; this returns 400. Setting +// `organization_role` to `admin` (even when unchanged) requires an interactive +// credential (a user OAuth token or a Console session). +func (r *BetaOrganizationServiceAccountService) Update(ctx context.Context, serviceAccountID string, params BetaOrganizationServiceAccountUpdateParams, opts ...option.RequestOption) (res *BetaServiceAccount, err error) { + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + if serviceAccountID == "" { + err = errors.New("missing required service_account_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/organizations/service_accounts/%s?beta=true", serviceAccountID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, params, &res, opts...) + return res, err +} + +// **Requires an OAuth access token with the `org:admin` scope**, from +// `ant auth login --scope org:admin` or a workload identity federation rule; Admin +// API keys are not accepted. See +// [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api). +// +// List service accounts in the caller's organization. +// +// Results are ordered by creation time, newest first. Use `limit` and the +// `next_page` cursor to paginate; set `include_archived=true` to include archived +// service accounts. +func (r *BetaOrganizationServiceAccountService) List(ctx context.Context, params BetaOrganizationServiceAccountListParams, opts ...option.RequestOption) (res *pagination.PageCursor[BetaServiceAccount], err error) { + var raw *http.Response + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithResponseInto(&raw)}, opts...) + path := "v1/organizations/service_accounts?beta=true" + cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, params, &res, opts...) + if err != nil { + return nil, err + } + err = cfg.Execute() + if err != nil { + return nil, err + } + res.SetPageConfig(cfg, raw) + return res, nil +} + +// **Requires an OAuth access token with the `org:admin` scope**, from +// `ant auth login --scope org:admin` or a workload identity federation rule; Admin +// API keys are not accepted. See +// [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api). +// +// List service accounts in the caller's organization. +// +// Results are ordered by creation time, newest first. Use `limit` and the +// `next_page` cursor to paginate; set `include_archived=true` to include archived +// service accounts. +func (r *BetaOrganizationServiceAccountService) ListAutoPaging(ctx context.Context, params BetaOrganizationServiceAccountListParams, opts ...option.RequestOption) *pagination.PageCursorAutoPager[BetaServiceAccount] { + return pagination.NewPageCursorAutoPager(r.List(ctx, params, opts...)) +} + +// **Requires an OAuth access token with the `org:admin` scope**, from +// `ant auth login --scope org:admin` or a workload identity federation rule; Admin +// API keys are not accepted. See +// [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api). +// +// Archive a service account. +// +// Idempotent; re-archiving returns the service account with its original +// `archived_at`. Rejected with 400 if any live (non-archived) federation rule +// still targets this service account, same as issuer archival; archive those rules +// first or change their target to another service account. +func (r *BetaOrganizationServiceAccountService) Archive(ctx context.Context, serviceAccountID string, body BetaOrganizationServiceAccountArchiveParams, opts ...option.RequestOption) (res *BetaServiceAccount, err error) { + for _, v := range body.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + if serviceAccountID == "" { + err = errors.New("missing required service_account_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/organizations/service_accounts/%s/archive?beta=true", serviceAccountID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, nil, &res, opts...) + return res, err +} + +// Named non-human identity within the caller's organization. +// +// A service account is a pure identity: name + org. Authorization lives on +// whatever references it (federation rules). +type BetaServiceAccount struct { + // Tagged ID of the service account. + ID string `json:"id" api:"required"` + // If set, this service account is archived. + ArchivedAt time.Time `json:"archived_at" api:"required" format:"date-time"` + // Tagged ID (`user_`/`svac_`) of the actor that archived this service account. + ArchivedByActorID string `json:"archived_by_actor_id" api:"required"` + // When this service account was created. + CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"` + // Tagged ID (`user_`/`svac_`) of the actor that created this service account. + CreatedByActorID string `json:"created_by_actor_id" api:"required"` + // Optional free-text description. + Description string `json:"description" api:"required"` + // Admin-chosen slug identifier. + Name string `json:"name" api:"required"` + // Org-level role. A federation rule may only be created or retargeted to grant + // `org:admin` scope when this is `admin`. A rule granting `org:admin` whose target + // is later demoted to `developer` is rejected at token exchange. Rules granting + // `org:admin` are managed in the Console. + // + // Any of "admin", "developer". + OrganizationRole BetaServiceAccountOrganizationRole `json:"organization_role" api:"required"` + Type constant.ServiceAccount `json:"type" default:"service_account"` + // When this service account was last updated. + UpdatedAt time.Time `json:"updated_at" api:"required" format:"date-time"` + // Tagged ID (`user_`/`svac_`) of the actor that last updated this service account. + UpdatedByActorID string `json:"updated_by_actor_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + ArchivedAt respjson.Field + ArchivedByActorID respjson.Field + CreatedAt respjson.Field + CreatedByActorID respjson.Field + Description respjson.Field + Name respjson.Field + OrganizationRole respjson.Field + Type respjson.Field + UpdatedAt respjson.Field + UpdatedByActorID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaServiceAccount) RawJSON() string { return r.JSON.raw } +func (r *BetaServiceAccount) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Org-level role. A federation rule may only be created or retargeted to grant +// `org:admin` scope when this is `admin`. A rule granting `org:admin` whose target +// is later demoted to `developer` is rejected at token exchange. Rules granting +// `org:admin` are managed in the Console. +type BetaServiceAccountOrganizationRole string + +const ( + BetaServiceAccountOrganizationRoleAdmin BetaServiceAccountOrganizationRole = "admin" + BetaServiceAccountOrganizationRoleDeveloper BetaServiceAccountOrganizationRole = "developer" +) + +type BetaServiceAccountWorkspaceMember struct { + // Tagged ID (`user_...`/`svac_...`) of the actor who created this membership. + CreatedByActorID string `json:"created_by_actor_id" api:"required"` + // True when this is the implicit default-workspace membership every service + // account has when no explicit membership exists. Implicit memberships have role + // `workspace_user` and cannot be removed. + Implicit bool `json:"implicit" api:"required"` + // Tagged service account ID (`svac_...`). + ServiceAccountID string `json:"service_account_id" api:"required"` + Type constant.ServiceAccountWorkspaceMember `json:"type" default:"service_account_workspace_member"` + // Tagged workspace ID (`wrkspc_...`). + WorkspaceID string `json:"workspace_id" api:"required"` + // Role of the service account in this workspace. Service accounts cannot hold the + // `workspace_billing` role. + // + // Any of "workspace_admin", "workspace_billing", "workspace_developer", + // "workspace_restricted_developer", "workspace_user". + WorkspaceRole BetaWorkspaceRole `json:"workspace_role" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + CreatedByActorID respjson.Field + Implicit respjson.Field + ServiceAccountID respjson.Field + Type respjson.Field + WorkspaceID respjson.Field + WorkspaceRole respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaServiceAccountWorkspaceMember) RawJSON() string { return r.JSON.raw } +func (r *BetaServiceAccountWorkspaceMember) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaOrganizationServiceAccountNewParams struct { + // Slug identifier (lowercase, digits, hyphens). Unique within the organization; a + // duplicate name returns 409. + Name string `json:"name" api:"required"` + // Optional free-text description. + Description param.Opt[string] `json:"description,omitzero"` + // Org-level role. Defaults to `developer`. + // + // Any of "admin", "developer". + OrganizationRole BetaOrganizationServiceAccountNewParamsOrganizationRole `json:"organization_role,omitzero"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +func (r BetaOrganizationServiceAccountNewParams) MarshalJSON() (data []byte, err error) { + type shadow BetaOrganizationServiceAccountNewParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaOrganizationServiceAccountNewParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Org-level role. Defaults to `developer`. +type BetaOrganizationServiceAccountNewParamsOrganizationRole string + +const ( + BetaOrganizationServiceAccountNewParamsOrganizationRoleAdmin BetaOrganizationServiceAccountNewParamsOrganizationRole = "admin" + BetaOrganizationServiceAccountNewParamsOrganizationRoleDeveloper BetaOrganizationServiceAccountNewParamsOrganizationRole = "developer" +) + +type BetaOrganizationServiceAccountGetParams struct { + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +type BetaOrganizationServiceAccountUpdateParams struct { + // Replaces the description. Omit to leave unchanged; send `null` to clear (the + // field is stored as an empty string). + Description param.Opt[string] `json:"description,omitzero"` + // Replaces the org-level role. Omit or send `null` to leave unchanged. + // + // Any of "admin", "developer". + OrganizationRole BetaOrganizationServiceAccountUpdateParamsOrganizationRole `json:"organization_role,omitzero"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +func (r BetaOrganizationServiceAccountUpdateParams) MarshalJSON() (data []byte, err error) { + type shadow BetaOrganizationServiceAccountUpdateParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaOrganizationServiceAccountUpdateParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Replaces the org-level role. Omit or send `null` to leave unchanged. +type BetaOrganizationServiceAccountUpdateParamsOrganizationRole string + +const ( + BetaOrganizationServiceAccountUpdateParamsOrganizationRoleAdmin BetaOrganizationServiceAccountUpdateParamsOrganizationRole = "admin" + BetaOrganizationServiceAccountUpdateParamsOrganizationRoleDeveloper BetaOrganizationServiceAccountUpdateParamsOrganizationRole = "developer" +) + +type BetaOrganizationServiceAccountListParams struct { + // Opaque cursor from a previous response's `next_page`. + Page param.Opt[string] `query:"page,omitzero" json:"-"` + // Include archived resources. Defaults to false. + IncludeArchived param.Opt[bool] `query:"include_archived,omitzero" json:"-"` + // Number of results per page. + Limit param.Opt[int64] `query:"limit,omitzero" json:"-"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +// URLQuery serializes [BetaOrganizationServiceAccountListParams]'s query +// parameters as `url.Values`. +func (r BetaOrganizationServiceAccountListParams) URLQuery() (v url.Values, err error) { + return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ + ArrayFormat: apiquery.ArrayQueryFormatBrackets, + NestedFormat: apiquery.NestedQueryFormatBrackets, + }) +} + +type BetaOrganizationServiceAccountArchiveParams struct { + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/betaorganizationserviceaccountworkspace.go b/vendor/github.com/anthropics/anthropic-sdk-go/betaorganizationserviceaccountworkspace.go new file mode 100644 index 000000000..b23c991a8 --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/betaorganizationserviceaccountworkspace.go @@ -0,0 +1,234 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +package anthropic + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "slices" + + "github.com/anthropics/anthropic-sdk-go/internal/apijson" + "github.com/anthropics/anthropic-sdk-go/internal/apiquery" + "github.com/anthropics/anthropic-sdk-go/internal/requestconfig" + "github.com/anthropics/anthropic-sdk-go/option" + "github.com/anthropics/anthropic-sdk-go/packages/pagination" + "github.com/anthropics/anthropic-sdk-go/packages/param" + "github.com/anthropics/anthropic-sdk-go/packages/respjson" + "github.com/anthropics/anthropic-sdk-go/shared/constant" +) + +// BetaOrganizationServiceAccountWorkspaceService contains methods and other +// services that help with interacting with the anthropic API. +// +// Note, unlike clients, this service does not read variables from the environment +// automatically. You should not instantiate this service directly, and instead use +// the [NewBetaOrganizationServiceAccountWorkspaceService] method instead. +type BetaOrganizationServiceAccountWorkspaceService struct { + Options []option.RequestOption +} + +// NewBetaOrganizationServiceAccountWorkspaceService generates a new service that +// applies the given options to each request. These options are applied after the +// parent client's options (if there is one), and before any request-specific +// options. +func NewBetaOrganizationServiceAccountWorkspaceService(opts ...option.RequestOption) (r BetaOrganizationServiceAccountWorkspaceService) { + r = BetaOrganizationServiceAccountWorkspaceService{} + r.Options = opts + return +} + +// **Requires an OAuth access token with the `org:admin` scope**, from +// `ant auth login --scope org:admin` or a workload identity federation rule; Admin +// API keys are not accepted. See +// [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api). +// +// List the workspaces a service account is a member of. +// +// Each entry includes the service account's `workspace_role` in that workspace. +// Use `limit` and the `next_page` cursor to paginate. When the service account has +// no explicit default-workspace membership, the implicit (`implicit: true`) +// membership is returned as the first entry on the first page; with `limit=1` the +// first page may return up to 2 entries (the implicit entry plus one explicit +// membership) so a pagination cursor can be derived. Memberships are returned only +// while the service account is active. Without a `page` cursor, an archived +// service account returns an empty list. A `page` cursor that does not match an +// active membership returns a 400 invalid-request error. A cursor stops matching +// when the membership is removed, the workspace is deleted, or the service account +// is archived. Restart pagination from the first page to recover. +func (r *BetaOrganizationServiceAccountWorkspaceService) List(ctx context.Context, serviceAccountID string, params BetaOrganizationServiceAccountWorkspaceListParams, opts ...option.RequestOption) (res *pagination.PageCursor[BetaServiceAccountWorkspaceMember], err error) { + var raw *http.Response + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithResponseInto(&raw)}, opts...) + if serviceAccountID == "" { + err = errors.New("missing required service_account_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/organizations/service_accounts/%s/workspaces?beta=true", serviceAccountID) + cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, params, &res, opts...) + if err != nil { + return nil, err + } + err = cfg.Execute() + if err != nil { + return nil, err + } + res.SetPageConfig(cfg, raw) + return res, nil +} + +// **Requires an OAuth access token with the `org:admin` scope**, from +// `ant auth login --scope org:admin` or a workload identity federation rule; Admin +// API keys are not accepted. See +// [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api). +// +// List the workspaces a service account is a member of. +// +// Each entry includes the service account's `workspace_role` in that workspace. +// Use `limit` and the `next_page` cursor to paginate. When the service account has +// no explicit default-workspace membership, the implicit (`implicit: true`) +// membership is returned as the first entry on the first page; with `limit=1` the +// first page may return up to 2 entries (the implicit entry plus one explicit +// membership) so a pagination cursor can be derived. Memberships are returned only +// while the service account is active. Without a `page` cursor, an archived +// service account returns an empty list. A `page` cursor that does not match an +// active membership returns a 400 invalid-request error. A cursor stops matching +// when the membership is removed, the workspace is deleted, or the service account +// is archived. Restart pagination from the first page to recover. +func (r *BetaOrganizationServiceAccountWorkspaceService) ListAutoPaging(ctx context.Context, serviceAccountID string, params BetaOrganizationServiceAccountWorkspaceListParams, opts ...option.RequestOption) *pagination.PageCursorAutoPager[BetaServiceAccountWorkspaceMember] { + return pagination.NewPageCursorAutoPager(r.List(ctx, serviceAccountID, params, opts...)) +} + +// **Requires an OAuth access token with the `org:admin` scope**, from +// `ant auth login --scope org:admin` or a workload identity federation rule; Admin +// API keys are not accepted. See +// [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api). +// +// Add a service account to a workspace with the given `workspace_role`. +// +// Mirror of `POST /workspaces/{workspace_id}/service_accounts`, addressed from the +// service-account side; both create the same membership. If the service account is +// already an explicit member of the workspace, its `workspace_role` is replaced +// with the value supplied here. Archived workspaces return 400. Archived service +// accounts cannot be added and are rejected. +func (r *BetaOrganizationServiceAccountWorkspaceService) Add(ctx context.Context, serviceAccountID string, params BetaOrganizationServiceAccountWorkspaceAddParams, opts ...option.RequestOption) (res *BetaServiceAccountWorkspaceMember, err error) { + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + if serviceAccountID == "" { + err = errors.New("missing required service_account_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/organizations/service_accounts/%s/workspaces?beta=true", serviceAccountID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, params, &res, opts...) + return res, err +} + +// **Requires an OAuth access token with the `org:admin` scope**, from +// `ant auth login --scope org:admin` or a workload identity federation rule; Admin +// API keys are not accepted. See +// [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api). +// +// Remove a service account from a workspace. +// +// Mirror of +// `DELETE /workspaces/{workspace_id}/service_accounts/{service_account_id}`, +// addressed from the service-account side. Removal is idempotent (returns 200 even +// if the membership was already removed). A DELETE against the implicit +// default-workspace membership returns 200 but is a no-op and the membership +// persists; deleting an explicit default-workspace row reverts to the implicit +// `workspace_user` membership. Archived workspaces return 400. +func (r *BetaOrganizationServiceAccountWorkspaceService) Remove(ctx context.Context, workspaceID string, params BetaOrganizationServiceAccountWorkspaceRemoveParams, opts ...option.RequestOption) (res *BetaOrganizationServiceAccountWorkspaceRemoveResponse, err error) { + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + if params.ServiceAccountID == "" { + err = errors.New("missing required service_account_id parameter") + return nil, err + } + if workspaceID == "" { + err = errors.New("missing required workspace_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/organizations/service_accounts/%s/workspaces/%s?beta=true", params.ServiceAccountID, workspaceID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodDelete, path, nil, &res, opts...) + return res, err +} + +type BetaOrganizationServiceAccountWorkspaceRemoveResponse struct { + // Tagged service account ID (`svac_...`) named in the delete request. Removal is + // idempotent; see the endpoint description for the implicit-membership no-op. + ServiceAccountID string `json:"service_account_id" api:"required"` + Type constant.ServiceAccountWorkspaceMemberDeleted `json:"type" default:"service_account_workspace_member_deleted"` + // Tagged workspace ID (`wrkspc_...`) named in the delete request. + WorkspaceID string `json:"workspace_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ServiceAccountID respjson.Field + Type respjson.Field + WorkspaceID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaOrganizationServiceAccountWorkspaceRemoveResponse) RawJSON() string { return r.JSON.raw } +func (r *BetaOrganizationServiceAccountWorkspaceRemoveResponse) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaOrganizationServiceAccountWorkspaceListParams struct { + // Opaque cursor from a previous response's `next_page`. + Page param.Opt[string] `query:"page,omitzero" json:"-"` + // Number of results per page. + Limit param.Opt[int64] `query:"limit,omitzero" json:"-"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +// URLQuery serializes [BetaOrganizationServiceAccountWorkspaceListParams]'s query +// parameters as `url.Values`. +func (r BetaOrganizationServiceAccountWorkspaceListParams) URLQuery() (v url.Values, err error) { + return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ + ArrayFormat: apiquery.ArrayQueryFormatBrackets, + NestedFormat: apiquery.NestedQueryFormatBrackets, + }) +} + +type BetaOrganizationServiceAccountWorkspaceAddParams struct { + // Tagged workspace ID to add the service account to. + WorkspaceID string `json:"workspace_id" api:"required"` + // Role to assign to the service account in this workspace. + // + // Any of "workspace_admin", "workspace_developer", + // "workspace_restricted_developer", "workspace_user". + WorkspaceRole BetaNoBillingWorkspaceRole `json:"workspace_role,omitzero" api:"required"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +func (r BetaOrganizationServiceAccountWorkspaceAddParams) MarshalJSON() (data []byte, err error) { + type shadow BetaOrganizationServiceAccountWorkspaceAddParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaOrganizationServiceAccountWorkspaceAddParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaOrganizationServiceAccountWorkspaceRemoveParams struct { + // ID of the service account. + ServiceAccountID string `path:"service_account_id" api:"required" json:"-"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/betaorganizationuser.go b/vendor/github.com/anthropics/anthropic-sdk-go/betaorganizationuser.go new file mode 100644 index 000000000..663f58668 --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/betaorganizationuser.go @@ -0,0 +1,229 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +package anthropic + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "slices" + "time" + + "github.com/anthropics/anthropic-sdk-go/internal/apijson" + "github.com/anthropics/anthropic-sdk-go/internal/apiquery" + "github.com/anthropics/anthropic-sdk-go/internal/requestconfig" + "github.com/anthropics/anthropic-sdk-go/option" + "github.com/anthropics/anthropic-sdk-go/packages/pagination" + "github.com/anthropics/anthropic-sdk-go/packages/param" + "github.com/anthropics/anthropic-sdk-go/packages/respjson" + "github.com/anthropics/anthropic-sdk-go/shared/constant" +) + +// BetaOrganizationUserService contains methods and other services that help with +// interacting with the anthropic API. +// +// Note, unlike clients, this service does not read variables from the environment +// automatically. You should not instantiate this service directly, and instead use +// the [NewBetaOrganizationUserService] method instead. +type BetaOrganizationUserService struct { + Options []option.RequestOption +} + +// NewBetaOrganizationUserService generates a new service that applies the given +// options to each request. These options are applied after the parent client's +// options (if there is one), and before any request-specific options. +func NewBetaOrganizationUserService(opts ...option.RequestOption) (r BetaOrganizationUserService) { + r = BetaOrganizationUserService{} + r.Options = opts + return +} + +// Retrieve a member of the organization by user ID. +func (r *BetaOrganizationUserService) Get(ctx context.Context, userID string, opts ...option.RequestOption) (res *BetaOrganizationUser, err error) { + opts = slices.Concat(r.Options, opts) + if userID == "" { + err = errors.New("missing required user_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/organizations/users/%s?beta=true", userID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...) + return res, err +} + +// Update a member's organization role. +func (r *BetaOrganizationUserService) Update(ctx context.Context, userID string, body BetaOrganizationUserUpdateParams, opts ...option.RequestOption) (res *BetaOrganizationUser, err error) { + opts = slices.Concat(r.Options, opts) + if userID == "" { + err = errors.New("missing required user_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/organizations/users/%s?beta=true", userID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...) + return res, err +} + +// List the organization's members. +func (r *BetaOrganizationUserService) List(ctx context.Context, query BetaOrganizationUserListParams, opts ...option.RequestOption) (res *pagination.Page[BetaOrganizationUser], err error) { + var raw *http.Response + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithResponseInto(&raw)}, opts...) + path := "v1/organizations/users?beta=true" + cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, query, &res, opts...) + if err != nil { + return nil, err + } + err = cfg.Execute() + if err != nil { + return nil, err + } + res.SetPageConfig(cfg, raw) + return res, nil +} + +// List the organization's members. +func (r *BetaOrganizationUserService) ListAutoPaging(ctx context.Context, query BetaOrganizationUserListParams, opts ...option.RequestOption) *pagination.PageAutoPager[BetaOrganizationUser] { + return pagination.NewPageAutoPager(r.List(ctx, query, opts...)) +} + +// Remove a member from the organization. +func (r *BetaOrganizationUserService) Remove(ctx context.Context, userID string, opts ...option.RequestOption) (res *BetaOrganizationUserRemoveResponse, err error) { + opts = slices.Concat(r.Options, opts) + if userID == "" { + err = errors.New("missing required user_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/organizations/users/%s?beta=true", userID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodDelete, path, nil, &res, opts...) + return res, err +} + +type BetaOrganizationUser struct { + // ID of the User. + ID string `json:"id" api:"required"` + // RFC 3339 datetime string indicating when the User joined the Organization. + AddedAt time.Time `json:"added_at" api:"required" format:"date-time"` + // Email of the User. + Email string `json:"email" api:"required"` + // Name of the User. + Name string `json:"name" api:"required"` + // Organization role of the User. + // + // Any of "admin", "billing", "claude_code_user", "developer", "managed", + // "membership_admin", "owner", "primary_owner", "user". + Role BetaOrganizationRole `json:"role" api:"required"` + // Object type. + // + // For Users, this is always `"user"`. + Type constant.User `json:"type" default:"user"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + AddedAt respjson.Field + Email respjson.Field + Name respjson.Field + Role respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaOrganizationUser) RawJSON() string { return r.JSON.raw } +func (r *BetaOrganizationUser) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaOrganizationUserRemoveResponse struct { + // ID of the User. + ID string `json:"id" api:"required"` + // Deleted object type. + // + // For Users, this is always `"user_deleted"`. + Type constant.UserDeleted `json:"type" default:"user_deleted"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaOrganizationUserRemoveResponse) RawJSON() string { return r.JSON.raw } +func (r *BetaOrganizationUserRemoveResponse) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaOrganizationUserUpdateParams struct { + // New role for the User. + // + // The accepted values depend on the organization type. Console and API + // organizations accept `user`, `developer`, `billing`, and `claude_code_user`; + // `admin` cannot be assigned through the API. Claude Enterprise organizations + // accept `user` and `managed`. + // + // Any of "billing", "claude_code_user", "developer", "managed", "user". + Role BetaOrganizationUserUpdateParamsRole `json:"role,omitzero" api:"required"` + paramObj +} + +func (r BetaOrganizationUserUpdateParams) MarshalJSON() (data []byte, err error) { + type shadow BetaOrganizationUserUpdateParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaOrganizationUserUpdateParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// New role for the User. +// +// The accepted values depend on the organization type. Console and API +// organizations accept `user`, `developer`, `billing`, and `claude_code_user`; +// `admin` cannot be assigned through the API. Claude Enterprise organizations +// accept `user` and `managed`. +type BetaOrganizationUserUpdateParamsRole string + +const ( + BetaOrganizationUserUpdateParamsRoleBilling BetaOrganizationUserUpdateParamsRole = "billing" + BetaOrganizationUserUpdateParamsRoleClaudeCodeUser BetaOrganizationUserUpdateParamsRole = "claude_code_user" + BetaOrganizationUserUpdateParamsRoleDeveloper BetaOrganizationUserUpdateParamsRole = "developer" + BetaOrganizationUserUpdateParamsRoleManaged BetaOrganizationUserUpdateParamsRole = "managed" + BetaOrganizationUserUpdateParamsRoleUser BetaOrganizationUserUpdateParamsRole = "user" +) + +type BetaOrganizationUserListParams struct { + // ID of the object to use as a cursor for pagination. When provided, returns the + // page of results immediately after this object. + AfterID param.Opt[string] `query:"after_id,omitzero" json:"-"` + // ID of the object to use as a cursor for pagination. When provided, returns the + // page of results immediately before this object. + BeforeID param.Opt[string] `query:"before_id,omitzero" json:"-"` + // Filter by user email. + Email param.Opt[string] `query:"email,omitzero" format:"email" json:"-"` + // Number of items to return per page. + // + // Defaults to `20`. Ranges from `1` to `1000`. + Limit param.Opt[int64] `query:"limit,omitzero" json:"-"` + // Filter to items whose `role` equals one of the supplied values. Repeatable; + // values are OR'ed together. + // + // Accepted values depend on the organization type: Console and API organizations + // accept `user`, `developer`, `billing`, `admin`, and `claude_code_user`; Claude + // Enterprise organizations accept `user`, `owner`, `primary_owner`, + // `membership_admin`, and `managed`. + Roles []string `query:"roles,omitzero" json:"-"` + paramObj +} + +// URLQuery serializes [BetaOrganizationUserListParams]'s query parameters as +// `url.Values`. +func (r BetaOrganizationUserListParams) URLQuery() (v url.Values, err error) { + return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ + ArrayFormat: apiquery.ArrayQueryFormatBrackets, + NestedFormat: apiquery.NestedQueryFormatBrackets, + }) +} diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/betaorganizationworkspace.go b/vendor/github.com/anthropics/anthropic-sdk-go/betaorganizationworkspace.go new file mode 100644 index 000000000..5a5bfddbf --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/betaorganizationworkspace.go @@ -0,0 +1,508 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +package anthropic + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/url" + "slices" + "time" + + "github.com/anthropics/anthropic-sdk-go/internal/apijson" + "github.com/anthropics/anthropic-sdk-go/internal/apiquery" + "github.com/anthropics/anthropic-sdk-go/internal/requestconfig" + "github.com/anthropics/anthropic-sdk-go/option" + "github.com/anthropics/anthropic-sdk-go/packages/pagination" + "github.com/anthropics/anthropic-sdk-go/packages/param" + "github.com/anthropics/anthropic-sdk-go/packages/respjson" + "github.com/anthropics/anthropic-sdk-go/shared/constant" +) + +// BetaOrganizationWorkspaceService contains methods and other services that help +// with interacting with the anthropic API. +// +// Note, unlike clients, this service does not read variables from the environment +// automatically. You should not instantiate this service directly, and instead use +// the [NewBetaOrganizationWorkspaceService] method instead. +type BetaOrganizationWorkspaceService struct { + Options []option.RequestOption + RateLimits BetaOrganizationWorkspaceRateLimitService + Members BetaOrganizationWorkspaceMemberService + ServiceAccounts BetaOrganizationWorkspaceServiceAccountService +} + +// NewBetaOrganizationWorkspaceService generates a new service that applies the +// given options to each request. These options are applied after the parent +// client's options (if there is one), and before any request-specific options. +func NewBetaOrganizationWorkspaceService(opts ...option.RequestOption) (r BetaOrganizationWorkspaceService) { + r = BetaOrganizationWorkspaceService{} + r.Options = opts + r.RateLimits = NewBetaOrganizationWorkspaceRateLimitService(opts...) + r.Members = NewBetaOrganizationWorkspaceMemberService(opts...) + r.ServiceAccounts = NewBetaOrganizationWorkspaceServiceAccountService(opts...) + return +} + +// Create Workspace +func (r *BetaOrganizationWorkspaceService) New(ctx context.Context, params BetaOrganizationWorkspaceNewParams, opts ...option.RequestOption) (res *BetaWorkspace, err error) { + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + path := "v1/organizations/workspaces?beta=true" + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, params, &res, opts...) + return res, err +} + +// Get Workspace +func (r *BetaOrganizationWorkspaceService) Get(ctx context.Context, workspaceID string, opts ...option.RequestOption) (res *BetaWorkspace, err error) { + opts = slices.Concat(r.Options, opts) + if workspaceID == "" { + err = errors.New("missing required workspace_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/organizations/workspaces/%s?beta=true", workspaceID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...) + return res, err +} + +// Update Workspace +func (r *BetaOrganizationWorkspaceService) Update(ctx context.Context, workspaceID string, body BetaOrganizationWorkspaceUpdateParams, opts ...option.RequestOption) (res *BetaWorkspace, err error) { + opts = slices.Concat(r.Options, opts) + if workspaceID == "" { + err = errors.New("missing required workspace_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/organizations/workspaces/%s?beta=true", workspaceID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...) + return res, err +} + +// List Workspaces +func (r *BetaOrganizationWorkspaceService) List(ctx context.Context, query BetaOrganizationWorkspaceListParams, opts ...option.RequestOption) (res *pagination.Page[BetaWorkspace], err error) { + var raw *http.Response + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithResponseInto(&raw)}, opts...) + path := "v1/organizations/workspaces?beta=true" + cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, query, &res, opts...) + if err != nil { + return nil, err + } + err = cfg.Execute() + if err != nil { + return nil, err + } + res.SetPageConfig(cfg, raw) + return res, nil +} + +// List Workspaces +func (r *BetaOrganizationWorkspaceService) ListAutoPaging(ctx context.Context, query BetaOrganizationWorkspaceListParams, opts ...option.RequestOption) *pagination.PageAutoPager[BetaWorkspace] { + return pagination.NewPageAutoPager(r.List(ctx, query, opts...)) +} + +// Archive Workspace +func (r *BetaOrganizationWorkspaceService) Archive(ctx context.Context, workspaceID string, opts ...option.RequestOption) (res *BetaWorkspace, err error) { + opts = slices.Concat(r.Options, opts) + if workspaceID == "" { + err = errors.New("missing required workspace_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/organizations/workspaces/%s/archive?beta=true", workspaceID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, nil, &res, opts...) + return res, err +} + +type BetaAllowedInferenceGeo string + +const ( + BetaAllowedInferenceGeoGlobal BetaAllowedInferenceGeo = "global" + BetaAllowedInferenceGeoUs BetaAllowedInferenceGeo = "us" +) + +type BetaDataResidency struct { + // Permitted inference geo values. 'unrestricted' means all geos are allowed. + AllowedInferenceGeos BetaDataResidencyAllowedInferenceGeosUnion `json:"allowed_inference_geos" api:"required"` + // Default inference geo applied when requests omit the parameter. + DefaultInferenceGeo string `json:"default_inference_geo" api:"required"` + // Geographic region for workspace data storage. Immutable after creation. + WorkspaceGeo string `json:"workspace_geo" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + AllowedInferenceGeos respjson.Field + DefaultInferenceGeo respjson.Field + WorkspaceGeo respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaDataResidency) RawJSON() string { return r.JSON.raw } +func (r *BetaDataResidency) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaDataResidencyAllowedInferenceGeosUnion contains all possible properties and +// values from [[]string], [constant.Unrestricted]. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +// +// If the underlying value is not a json object, one of the following properties +// will be valid: OfGeos OfUnrestricted] +type BetaDataResidencyAllowedInferenceGeosUnion struct { + // This field will be present if the value is a [[]string] instead of an object. + OfGeos []string `json:",inline"` + // This field will be present if the value is a [constant.Unrestricted] instead of + // an object. + OfUnrestricted constant.Unrestricted `json:",inline"` + JSON struct { + OfGeos respjson.Field + OfUnrestricted respjson.Field + raw string + } `json:"-"` +} + +func (u BetaDataResidencyAllowedInferenceGeosUnion) AsGeos() (v []string) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaDataResidencyAllowedInferenceGeosUnion) AsUnrestricted() (v constant.Unrestricted) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u BetaDataResidencyAllowedInferenceGeosUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaDataResidencyAllowedInferenceGeosUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaDataResidencyCreateConfigParam struct { + // Permitted inference geo values. Defaults to 'unrestricted' if omitted, which + // allows all geos. Use the string 'unrestricted' to allow all geos, or a list of + // specific geos. + AllowedInferenceGeos BetaDataResidencyCreateConfigAllowedInferenceGeosUnionParam `json:"allowed_inference_geos,omitzero"` + // Default inference geo applied when requests omit the parameter. Defaults to + // 'global' if omitted. Must be a member of `allowed_inference_geos` unless + // `allowed_inference_geos` is `"unrestricted"`. + // + // Any of "global", "us". + DefaultInferenceGeo BetaDataResidencyCreateConfigDefaultInferenceGeo `json:"default_inference_geo,omitzero"` + // Geographic region for workspace data storage. Immutable after creation. Defaults + // to 'us' if omitted. + // + // Any of "us". + WorkspaceGeo BetaDataResidencyCreateConfigWorkspaceGeo `json:"workspace_geo,omitzero"` + paramObj +} + +func (r BetaDataResidencyCreateConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaDataResidencyCreateConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaDataResidencyCreateConfigParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaDataResidencyCreateConfigAllowedInferenceGeosUnionParam struct { + OfGeos []BetaAllowedInferenceGeo `json:",omitzero,inline"` + // Construct this variant with constant.ValueOf[constant.Unrestricted]() + OfUnrestricted constant.Unrestricted `json:",omitzero,inline"` + paramUnion +} + +func (u BetaDataResidencyCreateConfigAllowedInferenceGeosUnionParam) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfGeos, u.OfUnrestricted) +} +func (u *BetaDataResidencyCreateConfigAllowedInferenceGeosUnionParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *BetaDataResidencyCreateConfigAllowedInferenceGeosUnionParam) asAny() any { + if !param.IsOmitted(u.OfGeos) { + return &u.OfGeos + } else if !param.IsOmitted(u.OfUnrestricted) { + return &u.OfUnrestricted + } + return nil +} + +// Default inference geo applied when requests omit the parameter. Defaults to +// 'global' if omitted. Must be a member of `allowed_inference_geos` unless +// `allowed_inference_geos` is `"unrestricted"`. +type BetaDataResidencyCreateConfigDefaultInferenceGeo string + +const ( + BetaDataResidencyCreateConfigDefaultInferenceGeoGlobal BetaDataResidencyCreateConfigDefaultInferenceGeo = "global" + BetaDataResidencyCreateConfigDefaultInferenceGeoUs BetaDataResidencyCreateConfigDefaultInferenceGeo = "us" +) + +// Geographic region for workspace data storage. Immutable after creation. Defaults +// to 'us' if omitted. +type BetaDataResidencyCreateConfigWorkspaceGeo string + +const ( + BetaDataResidencyCreateConfigWorkspaceGeoUs BetaDataResidencyCreateConfigWorkspaceGeo = "us" +) + +type BetaDataResidencyUpdateConfigParam struct { + // Permitted inference geo values. Use 'unrestricted' to allow all geos, or a list + // of specific geos. + AllowedInferenceGeos BetaDataResidencyUpdateConfigAllowedInferenceGeosUnionParam `json:"allowed_inference_geos,omitzero"` + // Default inference geo applied when requests omit the parameter. Must be a member + // of `allowed_inference_geos` unless `allowed_inference_geos` is `"unrestricted"`. + // + // Any of "global", "us". + DefaultInferenceGeo BetaDataResidencyUpdateConfigDefaultInferenceGeo `json:"default_inference_geo,omitzero"` + paramObj +} + +func (r BetaDataResidencyUpdateConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BetaDataResidencyUpdateConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaDataResidencyUpdateConfigParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaDataResidencyUpdateConfigAllowedInferenceGeosUnionParam struct { + OfGeos []BetaAllowedInferenceGeo `json:",omitzero,inline"` + // Construct this variant with constant.ValueOf[constant.Unrestricted]() + OfUnrestricted constant.Unrestricted `json:",omitzero,inline"` + paramUnion +} + +func (u BetaDataResidencyUpdateConfigAllowedInferenceGeosUnionParam) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfGeos, u.OfUnrestricted) +} +func (u *BetaDataResidencyUpdateConfigAllowedInferenceGeosUnionParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *BetaDataResidencyUpdateConfigAllowedInferenceGeosUnionParam) asAny() any { + if !param.IsOmitted(u.OfGeos) { + return &u.OfGeos + } else if !param.IsOmitted(u.OfUnrestricted) { + return &u.OfUnrestricted + } + return nil +} + +// Default inference geo applied when requests omit the parameter. Must be a member +// of `allowed_inference_geos` unless `allowed_inference_geos` is `"unrestricted"`. +type BetaDataResidencyUpdateConfigDefaultInferenceGeo string + +const ( + BetaDataResidencyUpdateConfigDefaultInferenceGeoGlobal BetaDataResidencyUpdateConfigDefaultInferenceGeo = "global" + BetaDataResidencyUpdateConfigDefaultInferenceGeoUs BetaDataResidencyUpdateConfigDefaultInferenceGeo = "us" +) + +type BetaNoBillingWorkspaceRole string + +const ( + BetaNoBillingWorkspaceRoleWorkspaceAdmin BetaNoBillingWorkspaceRole = "workspace_admin" + BetaNoBillingWorkspaceRoleWorkspaceDeveloper BetaNoBillingWorkspaceRole = "workspace_developer" + BetaNoBillingWorkspaceRoleWorkspaceRestrictedDeveloper BetaNoBillingWorkspaceRole = "workspace_restricted_developer" + BetaNoBillingWorkspaceRoleWorkspaceUser BetaNoBillingWorkspaceRole = "workspace_user" +) + +type BetaWorkspace struct { + // ID of the Workspace. + ID string `json:"id" api:"required"` + // RFC 3339 datetime string indicating when the Workspace was archived, or `null` + // if the Workspace is not archived. + ArchivedAt time.Time `json:"archived_at" api:"required" format:"date-time"` + // Identifier for this Workspace's encryption compartment. When you configure a + // customer-managed encryption key (CMEK) on AWS, reference this value in your KMS + // key-policy condition so the key is scoped to this compartment. On GCP and Azure, + // Anthropic enforces the compartment binding automatically; you do not need to + // reference this value in your key configuration. See the CMEK integration guide + // for the required key configuration, including the value used during key + // validation. + CompartmentID string `json:"compartment_id" api:"required"` + // RFC 3339 datetime string indicating when the Workspace was created. + CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"` + // Data residency configuration. + DataResidency BetaDataResidency `json:"data_residency" api:"required"` + // Hex color code representing the Workspace in the Anthropic Console. + DisplayColor string `json:"display_color" api:"required"` + // ID of the customer-managed encryption key (CMEK) configuration to use for this + // Workspace. Setting this field requires CMEK to be enabled for your organization. + // When set, data stored for this Workspace is encrypted with the referenced key. + // Create key configurations with the External Keys API. This field is write-once: + // once a key is attached to a Workspace it cannot be detached or replaced. To + // rotate key material, rotate the underlying key on your cloud KMS; the + // `external_key_id` stays the same. + ExternalKeyID string `json:"external_key_id" api:"required"` + // Name of the Workspace. + Name string `json:"name" api:"required"` + // User-defined tags as string key-value pairs. Keys may not begin with + // `anthropic`. + Tags map[string]string `json:"tags" api:"required"` + // Object type. + // + // For Workspaces, this is always `"workspace"`. + Type constant.Workspace `json:"type" default:"workspace"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + ArchivedAt respjson.Field + CompartmentID respjson.Field + CreatedAt respjson.Field + DataResidency respjson.Field + DisplayColor respjson.Field + ExternalKeyID respjson.Field + Name respjson.Field + Tags respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaWorkspace) RawJSON() string { return r.JSON.raw } +func (r *BetaWorkspace) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaWorkspaceMember struct { + // Object type. + // + // For Workspace Members, this is always `"workspace_member"`. + Type constant.WorkspaceMember `json:"type" default:"workspace_member"` + // ID of the User. + UserID string `json:"user_id" api:"required"` + // ID of the Workspace. + WorkspaceID string `json:"workspace_id" api:"required"` + // Role of the Workspace Member. + // + // Any of "workspace_admin", "workspace_billing", "workspace_developer", + // "workspace_restricted_developer", "workspace_user". + WorkspaceRole BetaWorkspaceRole `json:"workspace_role" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Type respjson.Field + UserID respjson.Field + WorkspaceID respjson.Field + WorkspaceRole respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaWorkspaceMember) RawJSON() string { return r.JSON.raw } +func (r *BetaWorkspaceMember) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaWorkspaceRole string + +const ( + BetaWorkspaceRoleWorkspaceAdmin BetaWorkspaceRole = "workspace_admin" + BetaWorkspaceRoleWorkspaceBilling BetaWorkspaceRole = "workspace_billing" + BetaWorkspaceRoleWorkspaceDeveloper BetaWorkspaceRole = "workspace_developer" + BetaWorkspaceRoleWorkspaceRestrictedDeveloper BetaWorkspaceRole = "workspace_restricted_developer" + BetaWorkspaceRoleWorkspaceUser BetaWorkspaceRole = "workspace_user" +) + +type BetaOrganizationWorkspaceNewParams struct { + // Name of the Workspace. + Name string `json:"name" api:"required"` + // Hex color code representing the Workspace in the Anthropic Console. + DisplayColor param.Opt[string] `json:"display_color,omitzero"` + // ID of the customer-managed encryption key (CMEK) configuration to use for this + // Workspace. Setting this field requires CMEK to be enabled for your organization. + // When set, data stored for this Workspace is encrypted with the referenced key. + // Create key configurations with the External Keys API. This field is write-once: + // once a key is attached to a Workspace it cannot be detached or replaced. To + // rotate key material, rotate the underlying key on your cloud KMS; the + // `external_key_id` stays the same. + ExternalKeyID param.Opt[string] `json:"external_key_id,omitzero"` + // User-defined tags as string key-value pairs. Keys may not begin with + // `anthropic`. + Tags map[string]string `json:"tags,omitzero"` + // Data residency configuration for the workspace. If omitted, defaults to + // `workspace_geo: "us"`, `allowed_inference_geos: "unrestricted"`, and + // `default_inference_geo: "global"`. + DataResidency BetaDataResidencyCreateConfigParam `json:"data_residency,omitzero"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +func (r BetaOrganizationWorkspaceNewParams) MarshalJSON() (data []byte, err error) { + type shadow BetaOrganizationWorkspaceNewParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaOrganizationWorkspaceNewParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaOrganizationWorkspaceUpdateParams struct { + // Hex color code representing the Workspace in the Anthropic Console. + DisplayColor param.Opt[string] `json:"display_color,omitzero"` + // ID of the customer-managed encryption key (CMEK) configuration to use for this + // Workspace. Setting this field requires CMEK to be enabled for your organization. + // When set, data stored for this Workspace is encrypted with the referenced key. + // Create key configurations with the External Keys API. This field is write-once: + // once a key is attached to a Workspace it cannot be detached or replaced. To + // rotate key material, rotate the underlying key on your cloud KMS; the + // `external_key_id` stays the same. + ExternalKeyID param.Opt[string] `json:"external_key_id,omitzero"` + // Name of the Workspace. + Name param.Opt[string] `json:"name,omitzero"` + // User-defined tags as string key-value pairs. Keys may not begin with + // `anthropic`. + Tags map[string]string `json:"tags,omitzero"` + // Data residency configuration for the workspace. + DataResidency BetaDataResidencyUpdateConfigParam `json:"data_residency,omitzero"` + paramObj +} + +func (r BetaOrganizationWorkspaceUpdateParams) MarshalJSON() (data []byte, err error) { + type shadow BetaOrganizationWorkspaceUpdateParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaOrganizationWorkspaceUpdateParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaOrganizationWorkspaceListParams struct { + // ID of the object to use as a cursor for pagination. When provided, returns the + // page of results immediately after this object. + AfterID param.Opt[string] `query:"after_id,omitzero" json:"-"` + // ID of the object to use as a cursor for pagination. When provided, returns the + // page of results immediately before this object. + BeforeID param.Opt[string] `query:"before_id,omitzero" json:"-"` + // Whether to include Workspaces that have been archived in the response + IncludeArchived param.Opt[bool] `query:"include_archived,omitzero" json:"-"` + // Number of items to return per page. + // + // Defaults to `20`. Ranges from `1` to `1000`. + Limit param.Opt[int64] `query:"limit,omitzero" json:"-"` + paramObj +} + +// URLQuery serializes [BetaOrganizationWorkspaceListParams]'s query parameters as +// `url.Values`. +func (r BetaOrganizationWorkspaceListParams) URLQuery() (v url.Values, err error) { + return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ + ArrayFormat: apiquery.ArrayQueryFormatBrackets, + NestedFormat: apiquery.NestedQueryFormatBrackets, + }) +} diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/betaorganizationworkspacemember.go b/vendor/github.com/anthropics/anthropic-sdk-go/betaorganizationworkspacemember.go new file mode 100644 index 000000000..d84e609f7 --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/betaorganizationworkspacemember.go @@ -0,0 +1,225 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +package anthropic + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "slices" + + "github.com/anthropics/anthropic-sdk-go/internal/apijson" + "github.com/anthropics/anthropic-sdk-go/internal/apiquery" + "github.com/anthropics/anthropic-sdk-go/internal/requestconfig" + "github.com/anthropics/anthropic-sdk-go/option" + "github.com/anthropics/anthropic-sdk-go/packages/pagination" + "github.com/anthropics/anthropic-sdk-go/packages/param" + "github.com/anthropics/anthropic-sdk-go/packages/respjson" + "github.com/anthropics/anthropic-sdk-go/shared/constant" +) + +// BetaOrganizationWorkspaceMemberService contains methods and other services that +// help with interacting with the anthropic API. +// +// Note, unlike clients, this service does not read variables from the environment +// automatically. You should not instantiate this service directly, and instead use +// the [NewBetaOrganizationWorkspaceMemberService] method instead. +type BetaOrganizationWorkspaceMemberService struct { + Options []option.RequestOption +} + +// NewBetaOrganizationWorkspaceMemberService generates a new service that applies +// the given options to each request. These options are applied after the parent +// client's options (if there is one), and before any request-specific options. +func NewBetaOrganizationWorkspaceMemberService(opts ...option.RequestOption) (r BetaOrganizationWorkspaceMemberService) { + r = BetaOrganizationWorkspaceMemberService{} + r.Options = opts + return +} + +// Get Workspace Member +func (r *BetaOrganizationWorkspaceMemberService) Get(ctx context.Context, userID string, query BetaOrganizationWorkspaceMemberGetParams, opts ...option.RequestOption) (res *BetaWorkspaceMember, err error) { + opts = slices.Concat(r.Options, opts) + if query.WorkspaceID == "" { + err = errors.New("missing required workspace_id parameter") + return nil, err + } + if userID == "" { + err = errors.New("missing required user_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/organizations/workspaces/%s/members/%s?beta=true", query.WorkspaceID, userID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...) + return res, err +} + +// Update Workspace Member +func (r *BetaOrganizationWorkspaceMemberService) Update(ctx context.Context, userID string, params BetaOrganizationWorkspaceMemberUpdateParams, opts ...option.RequestOption) (res *BetaWorkspaceMember, err error) { + opts = slices.Concat(r.Options, opts) + if params.WorkspaceID == "" { + err = errors.New("missing required workspace_id parameter") + return nil, err + } + if userID == "" { + err = errors.New("missing required user_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/organizations/workspaces/%s/members/%s?beta=true", params.WorkspaceID, userID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, params, &res, opts...) + return res, err +} + +// List Workspace Members +func (r *BetaOrganizationWorkspaceMemberService) List(ctx context.Context, workspaceID string, query BetaOrganizationWorkspaceMemberListParams, opts ...option.RequestOption) (res *pagination.Page[BetaWorkspaceMember], err error) { + var raw *http.Response + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithResponseInto(&raw)}, opts...) + if workspaceID == "" { + err = errors.New("missing required workspace_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/organizations/workspaces/%s/members?beta=true", workspaceID) + cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, query, &res, opts...) + if err != nil { + return nil, err + } + err = cfg.Execute() + if err != nil { + return nil, err + } + res.SetPageConfig(cfg, raw) + return res, nil +} + +// List Workspace Members +func (r *BetaOrganizationWorkspaceMemberService) ListAutoPaging(ctx context.Context, workspaceID string, query BetaOrganizationWorkspaceMemberListParams, opts ...option.RequestOption) *pagination.PageAutoPager[BetaWorkspaceMember] { + return pagination.NewPageAutoPager(r.List(ctx, workspaceID, query, opts...)) +} + +// Create Workspace Member +func (r *BetaOrganizationWorkspaceMemberService) Add(ctx context.Context, workspaceID string, body BetaOrganizationWorkspaceMemberAddParams, opts ...option.RequestOption) (res *BetaWorkspaceMember, err error) { + opts = slices.Concat(r.Options, opts) + if workspaceID == "" { + err = errors.New("missing required workspace_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/organizations/workspaces/%s/members?beta=true", workspaceID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...) + return res, err +} + +// Delete Workspace Member +func (r *BetaOrganizationWorkspaceMemberService) Remove(ctx context.Context, userID string, body BetaOrganizationWorkspaceMemberRemoveParams, opts ...option.RequestOption) (res *BetaOrganizationWorkspaceMemberRemoveResponse, err error) { + opts = slices.Concat(r.Options, opts) + if body.WorkspaceID == "" { + err = errors.New("missing required workspace_id parameter") + return nil, err + } + if userID == "" { + err = errors.New("missing required user_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/organizations/workspaces/%s/members/%s?beta=true", body.WorkspaceID, userID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodDelete, path, nil, &res, opts...) + return res, err +} + +type BetaOrganizationWorkspaceMemberRemoveResponse struct { + // Deleted object type. + // + // For Workspace Members, this is always `"workspace_member_deleted"`. + Type constant.WorkspaceMemberDeleted `json:"type" default:"workspace_member_deleted"` + // ID of the User. + UserID string `json:"user_id" api:"required"` + // ID of the Workspace. + WorkspaceID string `json:"workspace_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Type respjson.Field + UserID respjson.Field + WorkspaceID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaOrganizationWorkspaceMemberRemoveResponse) RawJSON() string { return r.JSON.raw } +func (r *BetaOrganizationWorkspaceMemberRemoveResponse) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaOrganizationWorkspaceMemberGetParams struct { + // ID of the Workspace. + WorkspaceID string `path:"workspace_id" api:"required" json:"-"` + paramObj +} + +type BetaOrganizationWorkspaceMemberUpdateParams struct { + // ID of the Workspace. + WorkspaceID string `path:"workspace_id" api:"required" json:"-"` + // New workspace role for the User. + // + // Any of "workspace_admin", "workspace_billing", "workspace_developer", + // "workspace_restricted_developer", "workspace_user". + WorkspaceRole BetaWorkspaceRole `json:"workspace_role,omitzero" api:"required"` + paramObj +} + +func (r BetaOrganizationWorkspaceMemberUpdateParams) MarshalJSON() (data []byte, err error) { + type shadow BetaOrganizationWorkspaceMemberUpdateParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaOrganizationWorkspaceMemberUpdateParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaOrganizationWorkspaceMemberListParams struct { + // ID of the object to use as a cursor for pagination. When provided, returns the + // page of results immediately after this object. + AfterID param.Opt[string] `query:"after_id,omitzero" json:"-"` + // ID of the object to use as a cursor for pagination. When provided, returns the + // page of results immediately before this object. + BeforeID param.Opt[string] `query:"before_id,omitzero" json:"-"` + // Number of items to return per page. + // + // Defaults to `20`. Ranges from `1` to `1000`. + Limit param.Opt[int64] `query:"limit,omitzero" json:"-"` + paramObj +} + +// URLQuery serializes [BetaOrganizationWorkspaceMemberListParams]'s query +// parameters as `url.Values`. +func (r BetaOrganizationWorkspaceMemberListParams) URLQuery() (v url.Values, err error) { + return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ + ArrayFormat: apiquery.ArrayQueryFormatBrackets, + NestedFormat: apiquery.NestedQueryFormatBrackets, + }) +} + +type BetaOrganizationWorkspaceMemberAddParams struct { + // ID of the User. + UserID string `json:"user_id" api:"required"` + // Role of the new Workspace Member. Cannot be `workspace_billing`. + // + // Any of "workspace_admin", "workspace_developer", + // "workspace_restricted_developer", "workspace_user". + WorkspaceRole BetaNoBillingWorkspaceRole `json:"workspace_role,omitzero" api:"required"` + paramObj +} + +func (r BetaOrganizationWorkspaceMemberAddParams) MarshalJSON() (data []byte, err error) { + type shadow BetaOrganizationWorkspaceMemberAddParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaOrganizationWorkspaceMemberAddParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaOrganizationWorkspaceMemberRemoveParams struct { + // ID of the Workspace. + WorkspaceID string `path:"workspace_id" api:"required" json:"-"` + paramObj +} diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/betaorganizationworkspaceratelimit.go b/vendor/github.com/anthropics/anthropic-sdk-go/betaorganizationworkspaceratelimit.go new file mode 100644 index 000000000..58cbed9b9 --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/betaorganizationworkspaceratelimit.go @@ -0,0 +1,197 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +package anthropic + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "slices" + + "github.com/anthropics/anthropic-sdk-go/internal/apijson" + "github.com/anthropics/anthropic-sdk-go/internal/apiquery" + "github.com/anthropics/anthropic-sdk-go/internal/requestconfig" + "github.com/anthropics/anthropic-sdk-go/option" + "github.com/anthropics/anthropic-sdk-go/packages/pagination" + "github.com/anthropics/anthropic-sdk-go/packages/param" + "github.com/anthropics/anthropic-sdk-go/packages/respjson" + "github.com/anthropics/anthropic-sdk-go/shared/constant" +) + +// BetaOrganizationWorkspaceRateLimitService contains methods and other services +// that help with interacting with the anthropic API. +// +// Note, unlike clients, this service does not read variables from the environment +// automatically. You should not instantiate this service directly, and instead use +// the [NewBetaOrganizationWorkspaceRateLimitService] method instead. +type BetaOrganizationWorkspaceRateLimitService struct { + Options []option.RequestOption +} + +// NewBetaOrganizationWorkspaceRateLimitService generates a new service that +// applies the given options to each request. These options are applied after the +// parent client's options (if there is one), and before any request-specific +// options. +func NewBetaOrganizationWorkspaceRateLimitService(opts ...option.RequestOption) (r BetaOrganizationWorkspaceRateLimitService) { + r = BetaOrganizationWorkspaceRateLimitService{} + r.Options = opts + return +} + +// List rate-limit overrides configured for a workspace. +// +// Returns only the groups and limiter types that have a workspace-level override. +// Groups without overrides inherit the organization limits and are not listed; use +// `GET /v1/organizations/rate_limits` to see those. +// +// This endpoint currently returns every matching entry in a single page regardless +// of `limit`; follow `next_page` so that clients keep working when pagination is +// enabled. +func (r *BetaOrganizationWorkspaceRateLimitService) List(ctx context.Context, workspaceID string, query BetaOrganizationWorkspaceRateLimitListParams, opts ...option.RequestOption) (res *pagination.PageCursor[BetaWorkspaceRateLimit], err error) { + var raw *http.Response + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithResponseInto(&raw)}, opts...) + if workspaceID == "" { + err = errors.New("missing required workspace_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/organizations/workspaces/%s/rate_limits?beta=true", workspaceID) + cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, query, &res, opts...) + if err != nil { + return nil, err + } + err = cfg.Execute() + if err != nil { + return nil, err + } + res.SetPageConfig(cfg, raw) + return res, nil +} + +// List rate-limit overrides configured for a workspace. +// +// Returns only the groups and limiter types that have a workspace-level override. +// Groups without overrides inherit the organization limits and are not listed; use +// `GET /v1/organizations/rate_limits` to see those. +// +// This endpoint currently returns every matching entry in a single page regardless +// of `limit`; follow `next_page` so that clients keep working when pagination is +// enabled. +func (r *BetaOrganizationWorkspaceRateLimitService) ListAutoPaging(ctx context.Context, workspaceID string, query BetaOrganizationWorkspaceRateLimitListParams, opts ...option.RequestOption) *pagination.PageCursorAutoPager[BetaWorkspaceRateLimit] { + return pagination.NewPageCursorAutoPager(r.List(ctx, workspaceID, query, opts...)) +} + +type BetaWorkspaceRateLimit struct { + // The kind of rate-limit group this entry represents. `model_group` entries apply + // to a family of models (listed in `models`); other values apply to an API-surface + // category and have `models` set to `null`. + // + // Any of "batch", "files", "model_group", "skills", "token_count", "web_search". + GroupType BetaWorkspaceRateLimitGroupType `json:"group_type" api:"required"` + // The limiter values overridden for this group in this workspace. Limiter types + // without a workspace override are omitted and inherit the organization value. + Limits []BetaWorkspaceRateLimitValue `json:"limits" api:"required"` + // Model names this entry's limits apply to, including aliases. `null` when + // `group_type` is not `"model_group"`. + Models []string `json:"models" api:"required"` + // The `id` of the RateLimit group this override applies to. + RateLimitID string `json:"rate_limit_id" api:"required"` + // Object type. Always `workspace_rate_limit` for workspace rate-limit entries. + Type constant.WorkspaceRateLimit `json:"type" default:"workspace_rate_limit"` + // ID of the Workspace this override applies to. + WorkspaceID string `json:"workspace_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + GroupType respjson.Field + Limits respjson.Field + Models respjson.Field + RateLimitID respjson.Field + Type respjson.Field + WorkspaceID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaWorkspaceRateLimit) RawJSON() string { return r.JSON.raw } +func (r *BetaWorkspaceRateLimit) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The kind of rate-limit group this entry represents. `model_group` entries apply +// to a family of models (listed in `models`); other values apply to an API-surface +// category and have `models` set to `null`. +type BetaWorkspaceRateLimitGroupType string + +const ( + BetaWorkspaceRateLimitGroupTypeBatch BetaWorkspaceRateLimitGroupType = "batch" + BetaWorkspaceRateLimitGroupTypeFiles BetaWorkspaceRateLimitGroupType = "files" + BetaWorkspaceRateLimitGroupTypeModelGroup BetaWorkspaceRateLimitGroupType = "model_group" + BetaWorkspaceRateLimitGroupTypeSkills BetaWorkspaceRateLimitGroupType = "skills" + BetaWorkspaceRateLimitGroupTypeTokenCount BetaWorkspaceRateLimitGroupType = "token_count" + BetaWorkspaceRateLimitGroupTypeWebSearch BetaWorkspaceRateLimitGroupType = "web_search" +) + +type BetaWorkspaceRateLimitValue struct { + // The organization-level value for the same limiter type, for reference. `null` + // when the organization has no limit configured for this limiter type. + OrgLimit int64 `json:"org_limit" api:"required"` + // The limiter type (for example, `requests_per_minute` or + // `input_tokens_per_minute`). + Type string `json:"type" api:"required"` + // The workspace-level override value for this limiter type. + Value int64 `json:"value" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + OrgLimit respjson.Field + Type respjson.Field + Value respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaWorkspaceRateLimitValue) RawJSON() string { return r.JSON.raw } +func (r *BetaWorkspaceRateLimitValue) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaOrganizationWorkspaceRateLimitListParams struct { + // Maximum number of items to return per page. Ranges from `1` to `1000`. + // + // Accepted for request-shape compatibility and currently ignored: every entry is + // returned in a single page. + Limit param.Opt[int64] `query:"limit,omitzero" json:"-"` + // Opaque cursor from a previous response's `next_page`. + Page param.Opt[string] `query:"page,omitzero" json:"-"` + // Filter by group type. + // + // Any of "batch", "files", "model_group", "skills", "token_count", "web_search". + GroupType BetaOrganizationWorkspaceRateLimitListParamsGroupType `query:"group_type,omitzero" json:"-"` + paramObj +} + +// URLQuery serializes [BetaOrganizationWorkspaceRateLimitListParams]'s query +// parameters as `url.Values`. +func (r BetaOrganizationWorkspaceRateLimitListParams) URLQuery() (v url.Values, err error) { + return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ + ArrayFormat: apiquery.ArrayQueryFormatBrackets, + NestedFormat: apiquery.NestedQueryFormatBrackets, + }) +} + +// Filter by group type. +type BetaOrganizationWorkspaceRateLimitListParamsGroupType string + +const ( + BetaOrganizationWorkspaceRateLimitListParamsGroupTypeBatch BetaOrganizationWorkspaceRateLimitListParamsGroupType = "batch" + BetaOrganizationWorkspaceRateLimitListParamsGroupTypeFiles BetaOrganizationWorkspaceRateLimitListParamsGroupType = "files" + BetaOrganizationWorkspaceRateLimitListParamsGroupTypeModelGroup BetaOrganizationWorkspaceRateLimitListParamsGroupType = "model_group" + BetaOrganizationWorkspaceRateLimitListParamsGroupTypeSkills BetaOrganizationWorkspaceRateLimitListParamsGroupType = "skills" + BetaOrganizationWorkspaceRateLimitListParamsGroupTypeTokenCount BetaOrganizationWorkspaceRateLimitListParamsGroupType = "token_count" + BetaOrganizationWorkspaceRateLimitListParamsGroupTypeWebSearch BetaOrganizationWorkspaceRateLimitListParamsGroupType = "web_search" +) diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/betaorganizationworkspaceserviceaccount.go b/vendor/github.com/anthropics/anthropic-sdk-go/betaorganizationworkspaceserviceaccount.go new file mode 100644 index 000000000..b4f331570 --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/betaorganizationworkspaceserviceaccount.go @@ -0,0 +1,311 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +package anthropic + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "slices" + + "github.com/anthropics/anthropic-sdk-go/internal/apijson" + "github.com/anthropics/anthropic-sdk-go/internal/apiquery" + "github.com/anthropics/anthropic-sdk-go/internal/requestconfig" + "github.com/anthropics/anthropic-sdk-go/option" + "github.com/anthropics/anthropic-sdk-go/packages/pagination" + "github.com/anthropics/anthropic-sdk-go/packages/param" + "github.com/anthropics/anthropic-sdk-go/packages/respjson" + "github.com/anthropics/anthropic-sdk-go/shared/constant" +) + +// BetaOrganizationWorkspaceServiceAccountService contains methods and other +// services that help with interacting with the anthropic API. +// +// Note, unlike clients, this service does not read variables from the environment +// automatically. You should not instantiate this service directly, and instead use +// the [NewBetaOrganizationWorkspaceServiceAccountService] method instead. +type BetaOrganizationWorkspaceServiceAccountService struct { + Options []option.RequestOption +} + +// NewBetaOrganizationWorkspaceServiceAccountService generates a new service that +// applies the given options to each request. These options are applied after the +// parent client's options (if there is one), and before any request-specific +// options. +func NewBetaOrganizationWorkspaceServiceAccountService(opts ...option.RequestOption) (r BetaOrganizationWorkspaceServiceAccountService) { + r = BetaOrganizationWorkspaceServiceAccountService{} + r.Options = opts + return +} + +// **Requires an OAuth access token with the `org:admin` scope**, from +// `ant auth login --scope org:admin` or a workload identity federation rule; Admin +// API keys are not accepted. See +// [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api). +// +// Retrieve a service account's membership in a workspace. +// +// Returns the membership record, including the service account's `workspace_role` +// in this workspace. Archived workspaces return 400. For the default workspace, +// returns the implicit (`implicit: true`) membership when no explicit membership +// exists; an explicitly added membership is returned with its assigned role. An +// archived service account returns 404. +func (r *BetaOrganizationWorkspaceServiceAccountService) Get(ctx context.Context, serviceAccountID string, params BetaOrganizationWorkspaceServiceAccountGetParams, opts ...option.RequestOption) (res *BetaServiceAccountWorkspaceMember, err error) { + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + if params.WorkspaceID == "" { + err = errors.New("missing required workspace_id parameter") + return nil, err + } + if serviceAccountID == "" { + err = errors.New("missing required service_account_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/organizations/workspaces/%s/service_accounts/%s?beta=true", params.WorkspaceID, serviceAccountID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...) + return res, err +} + +// **Requires an OAuth access token with the `org:admin` scope**, from +// `ant auth login --scope org:admin` or a workload identity federation rule; Admin +// API keys are not accepted. See +// [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api). +// +// Change a service account's role in a workspace. +// +// The new `workspace_role` replaces the current one. Only explicit memberships can +// be updated; to set a role on the implicit default-workspace membership, add the +// service account explicitly with +// `POST /workspaces/{workspace_id}/service_accounts`. Archived workspaces +// return 400. Archived service accounts cannot be updated and are rejected. +func (r *BetaOrganizationWorkspaceServiceAccountService) Update(ctx context.Context, serviceAccountID string, params BetaOrganizationWorkspaceServiceAccountUpdateParams, opts ...option.RequestOption) (res *BetaServiceAccountWorkspaceMember, err error) { + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + if params.WorkspaceID == "" { + err = errors.New("missing required workspace_id parameter") + return nil, err + } + if serviceAccountID == "" { + err = errors.New("missing required service_account_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/organizations/workspaces/%s/service_accounts/%s?beta=true", params.WorkspaceID, serviceAccountID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, params, &res, opts...) + return res, err +} + +// **Requires an OAuth access token with the `org:admin` scope**, from +// `ant auth login --scope org:admin` or a workload identity federation rule; Admin +// API keys are not accepted. See +// [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api). +// +// List the service accounts that are members of a workspace. +// +// Each entry includes the service account's `workspace_role`. Use `limit` and the +// `next_page` cursor to paginate. Archived workspaces return 400; use +// `GET /service_accounts/{id}/workspaces` to audit memberships of an archived +// workspace. The implicit default-workspace membership is not included in this +// list. Memberships of archived service accounts are omitted from the results. +func (r *BetaOrganizationWorkspaceServiceAccountService) List(ctx context.Context, workspaceID string, params BetaOrganizationWorkspaceServiceAccountListParams, opts ...option.RequestOption) (res *pagination.PageCursor[BetaServiceAccountWorkspaceMember], err error) { + var raw *http.Response + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithResponseInto(&raw)}, opts...) + if workspaceID == "" { + err = errors.New("missing required workspace_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/organizations/workspaces/%s/service_accounts?beta=true", workspaceID) + cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, params, &res, opts...) + if err != nil { + return nil, err + } + err = cfg.Execute() + if err != nil { + return nil, err + } + res.SetPageConfig(cfg, raw) + return res, nil +} + +// **Requires an OAuth access token with the `org:admin` scope**, from +// `ant auth login --scope org:admin` or a workload identity federation rule; Admin +// API keys are not accepted. See +// [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api). +// +// List the service accounts that are members of a workspace. +// +// Each entry includes the service account's `workspace_role`. Use `limit` and the +// `next_page` cursor to paginate. Archived workspaces return 400; use +// `GET /service_accounts/{id}/workspaces` to audit memberships of an archived +// workspace. The implicit default-workspace membership is not included in this +// list. Memberships of archived service accounts are omitted from the results. +func (r *BetaOrganizationWorkspaceServiceAccountService) ListAutoPaging(ctx context.Context, workspaceID string, params BetaOrganizationWorkspaceServiceAccountListParams, opts ...option.RequestOption) *pagination.PageCursorAutoPager[BetaServiceAccountWorkspaceMember] { + return pagination.NewPageCursorAutoPager(r.List(ctx, workspaceID, params, opts...)) +} + +// **Requires an OAuth access token with the `org:admin` scope**, from +// `ant auth login --scope org:admin` or a workload identity federation rule; Admin +// API keys are not accepted. See +// [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api). +// +// Add a service account to a workspace with the given `workspace_role`. +// +// The role determines what the service account can do in the workspace and which +// workspace-scoped permissions it can be granted when authenticating through +// federation. Every service account is already an implicit `workspace_user` member +// of the default workspace; adding it explicitly assigns a chosen role. If the +// service account is already an explicit member of the workspace, its +// `workspace_role` is replaced with the value supplied here. Archived workspaces +// return 400. Archived service accounts cannot be added and are rejected. +func (r *BetaOrganizationWorkspaceServiceAccountService) Add(ctx context.Context, workspaceID string, params BetaOrganizationWorkspaceServiceAccountAddParams, opts ...option.RequestOption) (res *BetaServiceAccountWorkspaceMember, err error) { + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + if workspaceID == "" { + err = errors.New("missing required workspace_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/organizations/workspaces/%s/service_accounts?beta=true", workspaceID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, params, &res, opts...) + return res, err +} + +// **Requires an OAuth access token with the `org:admin` scope**, from +// `ant auth login --scope org:admin` or a workload identity federation rule; Admin +// API keys are not accepted. See +// [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api). +// +// Remove a service account from a workspace. +// +// Removal is idempotent (returns 200 even if the membership was already removed). +// A DELETE against the implicit default-workspace membership returns 200 but is a +// no-op and the membership persists; deleting an explicit default-workspace row +// reverts to the implicit `workspace_user` membership. Archived workspaces +// return 400. +func (r *BetaOrganizationWorkspaceServiceAccountService) Remove(ctx context.Context, serviceAccountID string, params BetaOrganizationWorkspaceServiceAccountRemoveParams, opts ...option.RequestOption) (res *BetaOrganizationWorkspaceServiceAccountRemoveResponse, err error) { + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + if params.WorkspaceID == "" { + err = errors.New("missing required workspace_id parameter") + return nil, err + } + if serviceAccountID == "" { + err = errors.New("missing required service_account_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/organizations/workspaces/%s/service_accounts/%s?beta=true", params.WorkspaceID, serviceAccountID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodDelete, path, nil, &res, opts...) + return res, err +} + +type BetaOrganizationWorkspaceServiceAccountRemoveResponse struct { + // Tagged service account ID (`svac_...`) named in the delete request. Removal is + // idempotent; see the endpoint description for the implicit-membership no-op. + ServiceAccountID string `json:"service_account_id" api:"required"` + Type constant.ServiceAccountWorkspaceMemberDeleted `json:"type" default:"service_account_workspace_member_deleted"` + // Tagged workspace ID (`wrkspc_...`) named in the delete request. + WorkspaceID string `json:"workspace_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ServiceAccountID respjson.Field + Type respjson.Field + WorkspaceID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaOrganizationWorkspaceServiceAccountRemoveResponse) RawJSON() string { return r.JSON.raw } +func (r *BetaOrganizationWorkspaceServiceAccountRemoveResponse) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaOrganizationWorkspaceServiceAccountGetParams struct { + // ID of the workspace. + WorkspaceID string `path:"workspace_id" api:"required" json:"-"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +type BetaOrganizationWorkspaceServiceAccountUpdateParams struct { + // ID of the workspace. + WorkspaceID string `path:"workspace_id" api:"required" json:"-"` + // New role for the service account in this workspace. + // + // Any of "workspace_admin", "workspace_developer", + // "workspace_restricted_developer", "workspace_user". + WorkspaceRole BetaNoBillingWorkspaceRole `json:"workspace_role,omitzero" api:"required"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +func (r BetaOrganizationWorkspaceServiceAccountUpdateParams) MarshalJSON() (data []byte, err error) { + type shadow BetaOrganizationWorkspaceServiceAccountUpdateParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaOrganizationWorkspaceServiceAccountUpdateParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaOrganizationWorkspaceServiceAccountListParams struct { + // Opaque cursor from a previous response's `next_page`. + Page param.Opt[string] `query:"page,omitzero" json:"-"` + // Number of results per page. + Limit param.Opt[int64] `query:"limit,omitzero" json:"-"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +// URLQuery serializes [BetaOrganizationWorkspaceServiceAccountListParams]'s query +// parameters as `url.Values`. +func (r BetaOrganizationWorkspaceServiceAccountListParams) URLQuery() (v url.Values, err error) { + return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ + ArrayFormat: apiquery.ArrayQueryFormatBrackets, + NestedFormat: apiquery.NestedQueryFormatBrackets, + }) +} + +type BetaOrganizationWorkspaceServiceAccountAddParams struct { + // Tagged service account ID to add. + ServiceAccountID string `json:"service_account_id" api:"required"` + // Role to assign to the service account in this workspace. + // + // Any of "workspace_admin", "workspace_developer", + // "workspace_restricted_developer", "workspace_user". + WorkspaceRole BetaNoBillingWorkspaceRole `json:"workspace_role,omitzero" api:"required"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +func (r BetaOrganizationWorkspaceServiceAccountAddParams) MarshalJSON() (data []byte, err error) { + type shadow BetaOrganizationWorkspaceServiceAccountAddParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaOrganizationWorkspaceServiceAccountAddParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaOrganizationWorkspaceServiceAccountRemoveParams struct { + // ID of the workspace. + WorkspaceID string `path:"workspace_id" api:"required" json:"-"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/betaparse.go b/vendor/github.com/anthropics/anthropic-sdk-go/betaparse.go new file mode 100644 index 000000000..344f649ab --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/betaparse.go @@ -0,0 +1,114 @@ +package anthropic + +import ( + "encoding/json" + "errors" + "fmt" + "reflect" + "sync" + + "github.com/invopop/jsonschema" +) + +// ErrStructuredOutputParse is returned (wrapped) by [BetaMessageService.New] +// when the API request succeeds but the response body can't be unmarshaled +// into the struct pointer passed as Schema. The *BetaMessage is still +// returned in that case — check it alongside the error: +// +// msg, err := client.Beta.Messages.New(ctx, params) +// if errors.Is(err, anthropic.ErrStructuredOutputParse) { +// // msg is valid; the model's response didn't match the struct shape. +// } +var ErrStructuredOutputParse = errors.New("anthropic: failed to parse structured output") + +// schemaCache caches the final json.RawMessage (post-transform) keyed by +// reflect.Type, so repeated requests with the same struct type skip reflection, +// transformation, and marshaling. +// +// Entries are never evicted. This is fine for the common case where a program +// uses a fixed set of struct types (typically < 100, ~1KB each). Programs that +// synthesize types dynamically via reflect.StructOf with per-request shapes +// should precompute their schemas instead of relying on this cache. +var schemaCache sync.Map // reflect.Type → json.RawMessage + +// schemaToRaw converts a value to a json.RawMessage JSON schema suitable for the wire. +// If v is already a json.RawMessage, it is returned as-is. +// If v is a map[string]any, it is marshaled directly to json.RawMessage. +// If v is a struct pointer, the SDK reflects the type into a JSON schema, transforms it, +// and returns the result as json.RawMessage. +func schemaToRaw(v any) (json.RawMessage, error) { + if v == nil { + return nil, nil + } + + switch s := v.(type) { + case json.RawMessage: + return s, nil + case map[string]any: + b, err := json.Marshal(s) + if err != nil { + return nil, fmt.Errorf("anthropic: failed to marshal schema: %w", err) + } + return json.RawMessage(b), nil + } + + val := reflect.ValueOf(v) + if val.Kind() != reflect.Ptr || val.IsNil() { + return nil, fmt.Errorf("anthropic: Schema must be a non-nil pointer to a struct, map[string]any, or json.RawMessage, got %T", v) + } + if val.Elem().Kind() != reflect.Struct { + return nil, fmt.Errorf("anthropic: Schema must be a pointer to a struct, got pointer to %s", val.Elem().Kind()) + } + + // Cache the final json.RawMessage by reflect.Type so repeated requests + // with the same struct type skip reflection, transformation, and marshaling. + t := val.Elem().Type() + if cached, ok := schemaCache.Load(t); ok { + return cached.(json.RawMessage), nil + } + + reflector := jsonschema.Reflector{DoNotReference: true} + schema := reflector.Reflect(val.Interface()) + + // Transform the schema in-place on the typed struct, then marshal once. + transformSchema(schema) + + result, err := json.Marshal(schema) + if err != nil { + return nil, fmt.Errorf("anthropic: failed to marshal JSON schema: %w", err) + } + + raw := json.RawMessage(result) + schemaCache.Store(t, raw) + return raw, nil +} + +// outputFormatDest checks both OutputFormat.Schema and OutputConfig.Format.Schema +// for a struct pointer and returns it. Returns (nil, false) if neither has one. +func outputFormatDest(params BetaMessageNewParams) (any, bool) { + for _, schema := range []any{params.OutputFormat.Schema, params.OutputConfig.Format.Schema} { + if schema == nil { + continue + } + val := reflect.ValueOf(schema) + if val.Kind() == reflect.Ptr && !val.IsNil() && val.Elem().Kind() == reflect.Struct { + return schema, true + } + } + return nil, false +} + +// parseOutputContent finds the first text content block in the message +// and unmarshals it into dest. Errors are wrapped with ErrStructuredOutputParse +// so callers can distinguish parse failures via errors.Is. +func parseOutputContent(msg *BetaMessage, dest any) error { + for _, block := range msg.Content { + if block.Type == "text" { + if err := json.Unmarshal([]byte(block.Text), dest); err != nil { + return fmt.Errorf("%w: %w", ErrStructuredOutputParse, err) + } + return nil + } + } + return fmt.Errorf("%w: no text content block found in response", ErrStructuredOutputParse) +} diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/betasession.go b/vendor/github.com/anthropics/anthropic-sdk-go/betasession.go index 374ea2919..d2984dd02 100644 --- a/vendor/github.com/anthropics/anthropic-sdk-go/betasession.go +++ b/vendor/github.com/anthropics/anthropic-sdk-go/betasession.go @@ -14,6 +14,7 @@ import ( "github.com/anthropics/anthropic-sdk-go/internal/apijson" "github.com/anthropics/anthropic-sdk-go/internal/apiquery" + "github.com/anthropics/anthropic-sdk-go/internal/paramutil" "github.com/anthropics/anthropic-sdk-go/internal/requestconfig" "github.com/anthropics/anthropic-sdk-go/option" "github.com/anthropics/anthropic-sdk-go/packages/pagination" @@ -31,6 +32,7 @@ type BetaSessionService struct { Options []option.RequestOption Events BetaSessionEventService Resources BetaSessionResourceService + Threads BetaSessionThreadService } // NewBetaSessionService generates a new service that applies the given options to @@ -41,6 +43,7 @@ func NewBetaSessionService(opts ...option.RequestOption) (r BetaSessionService) r.Options = opts r.Events = NewBetaSessionEventService(opts...) r.Resources = NewBetaSessionResourceService(opts...) + r.Threads = NewBetaSessionThreadService(opts...) return } @@ -89,7 +92,7 @@ func (r *BetaSessionService) Update(ctx context.Context, sessionID string, param } // List Sessions -func (r *BetaSessionService) List(ctx context.Context, params BetaSessionListParams, opts ...option.RequestOption) (res *pagination.PageCursor[BetaManagedAgentsSession], err error) { +func (r *BetaSessionService) List(ctx context.Context, params BetaSessionListParams, opts ...option.RequestOption) (res *pagination.BidirectionalPageCursor[BetaManagedAgentsSession], err error) { var raw *http.Response for _, v := range params.Betas { opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) @@ -110,8 +113,8 @@ func (r *BetaSessionService) List(ctx context.Context, params BetaSessionListPar } // List Sessions -func (r *BetaSessionService) ListAutoPaging(ctx context.Context, params BetaSessionListParams, opts ...option.RequestOption) *pagination.PageCursorAutoPager[BetaManagedAgentsSession] { - return pagination.NewPageCursorAutoPager(r.List(ctx, params, opts...)) +func (r *BetaSessionService) ListAutoPaging(ctx context.Context, params BetaSessionListParams, opts ...option.RequestOption) *pagination.BidirectionalPageCursorAutoPager[BetaManagedAgentsSession] { + return pagination.NewBidirectionalPageCursorAutoPager(r.List(ctx, params, opts...)) } // Delete Session @@ -146,6 +149,61 @@ func (r *BetaSessionService) Archive(ctx context.Context, sessionID string, body return res, err } +// Platform advisor roster entry: a model the session's primary thread may consult +// mid-turn. At most one per roster; the entry occupies the roster name +// `anthropic.advisor`. +// +// The properties Model, Type are required. +type BetaManagedAgentsAdvisorParams struct { + // A Claude model id. The model must be permitted as an advisor for this agent's + // model — see the sessions/threads/advisor spec. + Model string `json:"model" api:"required"` + // Any of "advisor". + Type BetaManagedAgentsAdvisorParamsType `json:"type,omitzero" api:"required"` + paramObj +} + +func (r BetaManagedAgentsAdvisorParams) MarshalJSON() (data []byte, err error) { + type shadow BetaManagedAgentsAdvisorParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaManagedAgentsAdvisorParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsAdvisorParamsType string + +const ( + BetaManagedAgentsAdvisorParamsTypeAdvisor BetaManagedAgentsAdvisorParamsType = "advisor" +) + +type BetaManagedAgentsAgentMessagePreview struct { + // The id the buffered agent.message will carry if it is emitted. Matches the + // event_id on this preview's event_delta events. + ID string `json:"id" api:"required"` + // Any of "agent.message". + Type BetaManagedAgentsAgentMessagePreviewType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsAgentMessagePreview) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsAgentMessagePreview) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsAgentMessagePreviewType string + +const ( + BetaManagedAgentsAgentMessagePreviewTypeAgentMessage BetaManagedAgentsAgentMessagePreviewType = "agent.message" +) + // Specification for an Agent. Provide a specific `version` or use the short-form // `agent="agent_id"` for the most recent version // @@ -175,6 +233,261 @@ const ( BetaManagedAgentsAgentParamsTypeAgent BetaManagedAgentsAgentParamsType = "agent" ) +type BetaManagedAgentsAgentThinkingPreview struct { + // The id the buffered agent.thinking will carry if it is emitted. Start-only — no + // event_delta events follow. + ID string `json:"id" api:"required"` + // Any of "agent.thinking". + Type BetaManagedAgentsAgentThinkingPreviewType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsAgentThinkingPreview) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsAgentThinkingPreview) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsAgentThinkingPreviewType string + +const ( + BetaManagedAgentsAgentThinkingPreviewTypeAgentThinking BetaManagedAgentsAgentThinkingPreviewType = "agent.thinking" +) + +// Reference to an `agent` plus optional configuration overrides. Each provided +// field replaces the agent's value for the caller's use; the agent resource is +// unchanged. +// +// The properties ID, Type are required. +type BetaManagedAgentsAgentWithOverridesParams struct { + // The `agent` ID. + ID string `json:"id" api:"required"` + // Any of "agent_with_overrides". + Type BetaManagedAgentsAgentWithOverridesParamsType `json:"type,omitzero" api:"required"` + // Replacement system prompt. Up to 100,000 characters. Set to null to clear the + // agent's system prompt; omit to preserve it. + System param.Opt[string] `json:"system,omitzero"` + // The specific `agent` version to use. Omit to use the latest version. + Version param.Opt[int64] `json:"version,omitzero"` + // Replacement MCP server list. Full replacement: the provided array becomes the + // MCP servers. Send an empty array to clear; omit to preserve the agent's servers. + MCPServers []BetaManagedAgentsURLMCPServerParams `json:"mcp_servers,omitzero"` + // Replacement model. Accepts the model string, e.g. `claude-opus-5`, or a + // `model_config` object. Omit to use the agent's model. + Model BetaManagedAgentsModelConfigParams `json:"model,omitzero"` + // Replacement skill list. Full replacement: the provided array becomes the skills. + // Send an empty array to clear; omit to preserve the agent's skills. + Skills []BetaManagedAgentsSkillParamsUnion `json:"skills,omitzero"` + // Replacement tool list. Full replacement: the provided array becomes the tool + // configuration. Send an empty array to clear; omit to preserve the agent's tools. + Tools []BetaManagedAgentsAgentWithOverridesParamsToolUnion `json:"tools,omitzero"` + paramObj +} + +func (r BetaManagedAgentsAgentWithOverridesParams) MarshalJSON() (data []byte, err error) { + type shadow BetaManagedAgentsAgentWithOverridesParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaManagedAgentsAgentWithOverridesParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsAgentWithOverridesParamsType string + +const ( + BetaManagedAgentsAgentWithOverridesParamsTypeAgentWithOverrides BetaManagedAgentsAgentWithOverridesParamsType = "agent_with_overrides" +) + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaManagedAgentsAgentWithOverridesParamsToolUnion struct { + OfAgentToolset20260401 *BetaManagedAgentsAgentToolset20260401Params `json:",omitzero,inline"` + OfMCPToolset *BetaManagedAgentsMCPToolsetParams `json:",omitzero,inline"` + OfCustom *BetaManagedAgentsCustomToolParams `json:",omitzero,inline"` + paramUnion +} + +func (u BetaManagedAgentsAgentWithOverridesParamsToolUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfAgentToolset20260401, u.OfMCPToolset, u.OfCustom) +} +func (u *BetaManagedAgentsAgentWithOverridesParamsToolUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *BetaManagedAgentsAgentWithOverridesParamsToolUnion) asAny() any { + if !param.IsOmitted(u.OfAgentToolset20260401) { + return u.OfAgentToolset20260401 + } else if !param.IsOmitted(u.OfMCPToolset) { + return u.OfMCPToolset + } else if !param.IsOmitted(u.OfCustom) { + return u.OfCustom + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaManagedAgentsAgentWithOverridesParamsToolUnion) GetMCPServerName() *string { + if vt := u.OfMCPToolset; vt != nil { + return &vt.MCPServerName + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaManagedAgentsAgentWithOverridesParamsToolUnion) GetDescription() *string { + if vt := u.OfCustom; vt != nil { + return &vt.Description + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaManagedAgentsAgentWithOverridesParamsToolUnion) GetInputSchema() *BetaManagedAgentsCustomToolInputSchemaParam { + if vt := u.OfCustom; vt != nil { + return &vt.InputSchema + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaManagedAgentsAgentWithOverridesParamsToolUnion) GetName() *string { + if vt := u.OfCustom; vt != nil { + return &vt.Name + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaManagedAgentsAgentWithOverridesParamsToolUnion) GetType() *string { + if vt := u.OfAgentToolset20260401; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfMCPToolset; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfCustom; vt != nil { + return (*string)(&vt.Type) + } + return nil +} + +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u BetaManagedAgentsAgentWithOverridesParamsToolUnion) GetConfigs() (res betaManagedAgentsAgentWithOverridesParamsToolUnionConfigs) { + if vt := u.OfAgentToolset20260401; vt != nil { + res.any = &vt.Configs + } else if vt := u.OfMCPToolset; vt != nil { + res.any = &vt.Configs + } + return +} + +// Can have the runtime types [_[]BetaManagedAgentsAgentToolConfigParamsUnion], +// [_[]BetaManagedAgentsMCPToolConfigParams] +type betaManagedAgentsAgentWithOverridesParamsToolUnionConfigs struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *[]anthropic.BetaManagedAgentsAgentToolConfigParamsUnion: +// case *[]anthropic.BetaManagedAgentsMCPToolConfigParams: +// default: +// fmt.Errorf("not present") +// } +func (u betaManagedAgentsAgentWithOverridesParamsToolUnionConfigs) AsAny() any { return u.any } + +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u BetaManagedAgentsAgentWithOverridesParamsToolUnion) GetDefaultConfig() (res betaManagedAgentsAgentWithOverridesParamsToolUnionDefaultConfig) { + if vt := u.OfAgentToolset20260401; vt != nil { + res.any = &vt.DefaultConfig + } else if vt := u.OfMCPToolset; vt != nil { + res.any = &vt.DefaultConfig + } + return +} + +// Can have the runtime types [*BetaManagedAgentsAgentToolsetDefaultConfigParams], +// [*BetaManagedAgentsMCPToolsetDefaultConfigParams] +type betaManagedAgentsAgentWithOverridesParamsToolUnionDefaultConfig struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BetaManagedAgentsAgentToolsetDefaultConfigParams: +// case *anthropic.BetaManagedAgentsMCPToolsetDefaultConfigParams: +// default: +// fmt.Errorf("not present") +// } +func (u betaManagedAgentsAgentWithOverridesParamsToolUnionDefaultConfig) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u betaManagedAgentsAgentWithOverridesParamsToolUnionDefaultConfig) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BetaManagedAgentsAgentToolsetDefaultConfigParams: + return paramutil.AddrIfPresent(vt.Enabled) + case *BetaManagedAgentsMCPToolsetDefaultConfigParams: + return paramutil.AddrIfPresent(vt.Enabled) + } + return nil +} + +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u betaManagedAgentsAgentWithOverridesParamsToolUnionDefaultConfig) GetPermissionPolicy() (res betaManagedAgentsAgentWithOverridesParamsToolUnionDefaultConfigPermissionPolicy) { + switch vt := u.any.(type) { + case *BetaManagedAgentsAgentToolsetDefaultConfigParams: + res.any = vt.PermissionPolicy + case *BetaManagedAgentsMCPToolsetDefaultConfigParams: + res.any = vt.PermissionPolicy + } + return res +} + +// Can have the runtime types [*BetaManagedAgentsAlwaysAllowPolicyParam], +// [*BetaManagedAgentsAlwaysAskPolicyParam] +type betaManagedAgentsAgentWithOverridesParamsToolUnionDefaultConfigPermissionPolicy struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BetaManagedAgentsAlwaysAllowPolicyParam: +// case *anthropic.BetaManagedAgentsAlwaysAskPolicyParam: +// default: +// fmt.Errorf("not present") +// } +func (u betaManagedAgentsAgentWithOverridesParamsToolUnionDefaultConfigPermissionPolicy) AsAny() any { + return u.any +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaManagedAgentsAgentWithOverridesParamsToolUnionDefaultConfigPermissionPolicy) GetType() *string { + switch vt := u.any.(type) { + case *BetaManagedAgentsAgentToolsetDefaultConfigParamsPermissionPolicyUnion: + return vt.GetType() + case *BetaManagedAgentsMCPToolsetDefaultConfigParamsPermissionPolicyUnion: + return vt.GetType() + } + return nil +} + +func init() { + apijson.RegisterUnion[BetaManagedAgentsAgentWithOverridesParamsToolUnion]( + "type", + apijson.Discriminator[BetaManagedAgentsAgentToolset20260401Params]("agent_toolset_20260401"), + apijson.Discriminator[BetaManagedAgentsMCPToolsetParams]("mcp_toolset"), + apijson.Discriminator[BetaManagedAgentsCustomToolParams]("custom"), + ) +} + type BetaManagedAgentsBranchCheckout struct { // Branch name to check out. Name string `json:"name" api:"required"` @@ -228,6 +541,64 @@ func (r *BetaManagedAgentsBranchCheckoutParam) UnmarshalJSON(data []byte) error return apijson.UnmarshalRoot(data, r) } +// A hard spend ceiling. The session stops issuing new model requests once the +// tracked list cost reaches `max_list_cost`. +type BetaManagedAgentsBudgetLimit struct { + // A monetary amount in a specific currency. + MaxListCost BetaMonetaryAmount `json:"max_list_cost" api:"required"` + // Any of "limit". + Type BetaManagedAgentsBudgetLimitType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + MaxListCost respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsBudgetLimit) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsBudgetLimit) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// ToParam converts this BetaManagedAgentsBudgetLimit to a +// BetaManagedAgentsBudgetLimitParam. +// +// Warning: the fields of the param type will not be present. ToParam should only +// be used at the last possible moment before sending a request. Test for this with +// BetaManagedAgentsBudgetLimitParam.Overrides() +func (r BetaManagedAgentsBudgetLimit) ToParam() BetaManagedAgentsBudgetLimitParam { + return param.Override[BetaManagedAgentsBudgetLimitParam](json.RawMessage(r.RawJSON())) +} + +type BetaManagedAgentsBudgetLimitType string + +const ( + BetaManagedAgentsBudgetLimitTypeLimit BetaManagedAgentsBudgetLimitType = "limit" +) + +// A hard spend ceiling. The session stops issuing new model requests once the +// tracked list cost reaches `max_list_cost`. +// +// The properties MaxListCost, Type are required. +type BetaManagedAgentsBudgetLimitParam struct { + // A monetary amount in a specific currency. + MaxListCost BetaMonetaryAmountParam `json:"max_list_cost,omitzero" api:"required"` + // Any of "limit". + Type BetaManagedAgentsBudgetLimitType `json:"type,omitzero" api:"required"` + paramObj +} + +func (r BetaManagedAgentsBudgetLimitParam) MarshalJSON() (data []byte, err error) { + type shadow BetaManagedAgentsBudgetLimitParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaManagedAgentsBudgetLimitParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + // Prompt-cache creation token usage broken down by cache lifetime. type BetaManagedAgentsCacheCreationUsage struct { // Tokens used to create 1-hour ephemeral cache entries. @@ -328,6 +699,83 @@ const ( BetaManagedAgentsDeletedSessionTypeSessionDeleted BetaManagedAgentsDeletedSessionType = "session_deleted" ) +type BetaManagedAgentsDeltaContent struct { + // Regular text content. + Content BetaManagedAgentsTextBlock `json:"content" api:"required"` + // Any of "content_delta". + Type BetaManagedAgentsDeltaContentType `json:"type" api:"required"` + // Which entry in the previewed event's content array this fragment lands in. + // Insert content as that entry when the index is new; append to the existing entry + // otherwise. + Index int64 `json:"index"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Content respjson.Field + Type respjson.Field + Index respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsDeltaContent) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsDeltaContent) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsDeltaContentType string + +const ( + BetaManagedAgentsDeltaContentTypeContentDelta BetaManagedAgentsDeltaContentType = "content_delta" +) + +// An incremental update to an event that is still being streamed. Deltas are +// best-effort and may stop early; when the buffered event with id == event_id is +// produced it carries the complete content. A model request that ends early (an +// error or interrupt) produces no buffered event — its terminal +// span.model_request_end closes the preview. Only sent on stream connections that +// opt in via event_deltas; never appears in event history. +type BetaManagedAgentsDeltaEvent struct { + // One fragment of the previewed event. The delta type is named for the previewed + // event's field it streams into: agent.message events stream content_delta + // fragments, each a partial element of the content array. + Delta BetaManagedAgentsDeltaContent `json:"delta" api:"required"` + // The id of the event being previewed. Matches event.id on the corresponding + // event_start and the buffered event that reconciles the preview. + EventID string `json:"event_id" api:"required"` + // Any of "event_delta". + Type BetaManagedAgentsDeltaEventType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Delta respjson.Field + EventID respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsDeltaEvent) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsDeltaEvent) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsDeltaEventType string + +const ( + BetaManagedAgentsDeltaEventTypeEventDelta BetaManagedAgentsDeltaEventType = "event_delta" +) + +// EventDeltaType enum +type BetaManagedAgentsDeltaType string + +const ( + BetaManagedAgentsDeltaTypeAgentMessage BetaManagedAgentsDeltaType = "agent.message" + BetaManagedAgentsDeltaTypeAgentThinking BetaManagedAgentsDeltaType = "agent.thinking" +) + // Mount a file uploaded via the Files API into the session. // // The properties FileID, Type are required. @@ -445,59 +893,395 @@ func init() { ) } -// A Managed Agents `session`. -type BetaManagedAgentsSession struct { - ID string `json:"id" api:"required"` - // Resolved `agent` definition for a `session`. Snapshot of the `agent` at - // `session` creation time. - Agent BetaManagedAgentsSessionAgent `json:"agent" api:"required"` - // A timestamp in RFC 3339 format - ArchivedAt time.Time `json:"archived_at" api:"required" format:"date-time"` - // A timestamp in RFC 3339 format - CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"` - EnvironmentID string `json:"environment_id" api:"required"` - Metadata map[string]string `json:"metadata" api:"required"` - Resources []BetaManagedAgentsSessionResourceUnion `json:"resources" api:"required"` - // Timing statistics for a session. - Stats BetaManagedAgentsSessionStats `json:"stats" api:"required"` - // SessionStatus enum +// Parameters for attaching a memory store to an agent session. +// +// The properties MemoryStoreID, Type are required. +type BetaManagedAgentsMemoryStoreResourceParam struct { + // The memory store ID (memstore\_...). Must belong to the caller's organization + // and workspace. + MemoryStoreID string `json:"memory_store_id" api:"required"` + // Any of "memory_store". + Type BetaManagedAgentsMemoryStoreResourceParamType `json:"type,omitzero" api:"required"` + // Per-attachment guidance for the agent on how to use this store. Rendered into + // the memory section of the system prompt. Max 4096 chars. + Instructions param.Opt[string] `json:"instructions,omitzero"` + // Access mode for an attached memory store. // - // Any of "rescheduling", "running", "idle", "terminated". - Status BetaManagedAgentsSessionStatus `json:"status" api:"required"` - Title string `json:"title" api:"required"` - // Any of "session". - Type BetaManagedAgentsSessionType `json:"type" api:"required"` - // A timestamp in RFC 3339 format - UpdatedAt time.Time `json:"updated_at" api:"required" format:"date-time"` - // Cumulative token usage for a session across all turns. - Usage BetaManagedAgentsSessionUsage `json:"usage" api:"required"` - // Vault IDs attached to the session at creation. Empty when no vaults were - // supplied. - VaultIDs []string `json:"vault_ids" api:"required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ID respjson.Field - Agent respjson.Field - ArchivedAt respjson.Field - CreatedAt respjson.Field - EnvironmentID respjson.Field - Metadata respjson.Field - Resources respjson.Field - Stats respjson.Field - Status respjson.Field - Title respjson.Field - Type respjson.Field - UpdatedAt respjson.Field - Usage respjson.Field - VaultIDs respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` + // Any of "read_write", "read_only". + Access BetaManagedAgentsMemoryStoreResourceParamAccess `json:"access,omitzero"` + paramObj } -// Returns the unmodified JSON received from the API -func (r BetaManagedAgentsSession) RawJSON() string { return r.JSON.raw } -func (r *BetaManagedAgentsSession) UnmarshalJSON(data []byte) error { +func (r BetaManagedAgentsMemoryStoreResourceParam) MarshalJSON() (data []byte, err error) { + type shadow BetaManagedAgentsMemoryStoreResourceParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaManagedAgentsMemoryStoreResourceParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsMemoryStoreResourceParamType string + +const ( + BetaManagedAgentsMemoryStoreResourceParamTypeMemoryStore BetaManagedAgentsMemoryStoreResourceParamType = "memory_store" +) + +// Access mode for an attached memory store. +type BetaManagedAgentsMemoryStoreResourceParamAccess string + +const ( + BetaManagedAgentsMemoryStoreResourceParamAccessReadWrite BetaManagedAgentsMemoryStoreResourceParamAccess = "read_write" + BetaManagedAgentsMemoryStoreResourceParamAccessReadOnly BetaManagedAgentsMemoryStoreResourceParamAccess = "read_only" +) + +// Resolved coordinator topology with a concrete agent roster. +type BetaManagedAgentsMultiagent struct { + // Agents the coordinator may spawn as session threads, each resolved to a specific + // version. + Agents []BetaManagedAgentsMultiagentAgentUnion `json:"agents" api:"required"` + // Any of "coordinator". + Type BetaManagedAgentsMultiagentType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Agents respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsMultiagent) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsMultiagent) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaManagedAgentsMultiagentAgentUnion contains all possible properties and +// values from [BetaManagedAgentsAgentReference], [BetaManagedAgentsAdvisor]. +// +// Use the [BetaManagedAgentsMultiagentAgentUnion.AsAny] method to switch on the +// variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaManagedAgentsMultiagentAgentUnion struct { + // This field is from variant [BetaManagedAgentsAgentReference]. + ID string `json:"id"` + // Any of "agent", "advisor". + Type string `json:"type"` + // This field is from variant [BetaManagedAgentsAgentReference]. + Version int64 `json:"version"` + // This field is from variant [BetaManagedAgentsAdvisor]. + Model string `json:"model"` + JSON struct { + ID respjson.Field + Type respjson.Field + Version respjson.Field + Model respjson.Field + raw string + } `json:"-"` +} + +// anyBetaManagedAgentsMultiagentAgent is implemented by each variant of +// [BetaManagedAgentsMultiagentAgentUnion] to add type safety for the return type +// of [BetaManagedAgentsMultiagentAgentUnion.AsAny] +type anyBetaManagedAgentsMultiagentAgent interface { + implBetaManagedAgentsMultiagentAgentUnion() +} + +func (BetaManagedAgentsAgentReference) implBetaManagedAgentsMultiagentAgentUnion() {} +func (BetaManagedAgentsAdvisor) implBetaManagedAgentsMultiagentAgentUnion() {} + +// Use the following switch statement to find the correct variant +// +// switch variant := BetaManagedAgentsMultiagentAgentUnion.AsAny().(type) { +// case anthropic.BetaManagedAgentsAgentReference: +// case anthropic.BetaManagedAgentsAdvisor: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaManagedAgentsMultiagentAgentUnion) AsAny() anyBetaManagedAgentsMultiagentAgent { + switch u.Type { + case "agent": + return u.AsAgent() + case "advisor": + return u.AsAdvisor() + } + return nil +} + +func (u BetaManagedAgentsMultiagentAgentUnion) AsAgent() (v BetaManagedAgentsAgentReference) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsMultiagentAgentUnion) AsAdvisor() (v BetaManagedAgentsAdvisor) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u BetaManagedAgentsMultiagentAgentUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaManagedAgentsMultiagentAgentUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsMultiagentType string + +const ( + BetaManagedAgentsMultiagentTypeCoordinator BetaManagedAgentsMultiagentType = "coordinator" +) + +// A coordinator topology: the session's primary thread orchestrates work by +// spawning session threads, each running an agent drawn from the `agents` roster. +// +// The properties Agents, Type are required. +type BetaManagedAgentsMultiagentParams struct { + // Agents the coordinator may spawn as session threads. 1–20 entries. Each entry is + // an agent ID string, a versioned `{"type":"agent","id","version"}` reference, or + // `{"type":"self"}` to allow recursive self-invocation. Entries must reference + // distinct agents (after resolving `self` and string forms); at most one `self`. + // Referenced agents must exist, must not be archived, and must not themselves have + // `multiagent` set (depth limit 1). + Agents []BetaManagedAgentsMultiagentRosterEntryParamsUnion `json:"agents,omitzero" api:"required"` + // Any of "coordinator". + Type BetaManagedAgentsMultiagentParamsType `json:"type,omitzero" api:"required"` + paramObj +} + +func (r BetaManagedAgentsMultiagentParams) MarshalJSON() (data []byte, err error) { + type shadow BetaManagedAgentsMultiagentParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaManagedAgentsMultiagentParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsMultiagentParamsType string + +const ( + BetaManagedAgentsMultiagentParamsTypeCoordinator BetaManagedAgentsMultiagentParamsType = "coordinator" +) + +func BetaManagedAgentsMultiagentRosterEntryParamsOfBetaManagedAgentsAgents(id string, type_ BetaManagedAgentsAgentParamsType) BetaManagedAgentsMultiagentRosterEntryParamsUnion { + var variant BetaManagedAgentsAgentParams + variant.ID = id + variant.Type = type_ + return BetaManagedAgentsMultiagentRosterEntryParamsUnion{OfBetaManagedAgentsAgents: &variant} +} + +func BetaManagedAgentsMultiagentRosterEntryParamsOfBetaManagedAgentsMultiagentSelfs(type_ BetaManagedAgentsMultiagentSelfParamsType) BetaManagedAgentsMultiagentRosterEntryParamsUnion { + var variant BetaManagedAgentsMultiagentSelfParams + variant.Type = type_ + return BetaManagedAgentsMultiagentRosterEntryParamsUnion{OfBetaManagedAgentsMultiagentSelfs: &variant} +} + +func BetaManagedAgentsMultiagentRosterEntryParamsOfBetaManagedAgentsAdvisors(model string, type_ BetaManagedAgentsAdvisorParamsType) BetaManagedAgentsMultiagentRosterEntryParamsUnion { + var variant BetaManagedAgentsAdvisorParams + variant.Model = model + variant.Type = type_ + return BetaManagedAgentsMultiagentRosterEntryParamsUnion{OfBetaManagedAgentsAdvisors: &variant} +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaManagedAgentsMultiagentRosterEntryParamsUnion struct { + OfString param.Opt[string] `json:",omitzero,inline"` + OfBetaManagedAgentsAgents *BetaManagedAgentsAgentParams `json:",omitzero,inline"` + OfBetaManagedAgentsMultiagentSelfs *BetaManagedAgentsMultiagentSelfParams `json:",omitzero,inline"` + OfBetaManagedAgentsAdvisors *BetaManagedAgentsAdvisorParams `json:",omitzero,inline"` + paramUnion +} + +func (u BetaManagedAgentsMultiagentRosterEntryParamsUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfString, u.OfBetaManagedAgentsAgents, u.OfBetaManagedAgentsMultiagentSelfs, u.OfBetaManagedAgentsAdvisors) +} +func (u *BetaManagedAgentsMultiagentRosterEntryParamsUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *BetaManagedAgentsMultiagentRosterEntryParamsUnion) asAny() any { + if !param.IsOmitted(u.OfString) { + return &u.OfString.Value + } else if !param.IsOmitted(u.OfBetaManagedAgentsAgents) { + return u.OfBetaManagedAgentsAgents + } else if !param.IsOmitted(u.OfBetaManagedAgentsMultiagentSelfs) { + return u.OfBetaManagedAgentsMultiagentSelfs + } else if !param.IsOmitted(u.OfBetaManagedAgentsAdvisors) { + return u.OfBetaManagedAgentsAdvisors + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaManagedAgentsMultiagentRosterEntryParamsUnion) GetID() *string { + if vt := u.OfBetaManagedAgentsAgents; vt != nil { + return &vt.ID + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaManagedAgentsMultiagentRosterEntryParamsUnion) GetVersion() *int64 { + if vt := u.OfBetaManagedAgentsAgents; vt != nil && vt.Version.Valid() { + return &vt.Version.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaManagedAgentsMultiagentRosterEntryParamsUnion) GetModel() *string { + if vt := u.OfBetaManagedAgentsAdvisors; vt != nil { + return &vt.Model + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaManagedAgentsMultiagentRosterEntryParamsUnion) GetType() *string { + if vt := u.OfBetaManagedAgentsAgents; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfBetaManagedAgentsMultiagentSelfs; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfBetaManagedAgentsAdvisors; vt != nil { + return (*string)(&vt.Type) + } + return nil +} + +// Evaluation state for a single outcome defined via a define_outcome event. +type BetaManagedAgentsOutcomeEvaluationResource struct { + // A timestamp in RFC 3339 format + CompletedAt time.Time `json:"completed_at" api:"required" format:"date-time"` + // What the agent should produce. + Description string `json:"description" api:"required"` + // Grader's verdict text from the most recent evaluation. For satisfied, explains + // why criteria are met; for needs_revision (intermediate), what's missing; for + // failed, why unrecoverable. + Explanation string `json:"explanation" api:"required"` + // 0-indexed revision cycle the outcome is currently on. + Iteration int64 `json:"iteration" api:"required"` + // Server-generated outc\_ ID for this outcome. + OutcomeID string `json:"outcome_id" api:"required"` + // Current evaluation state. `pending` before the agent begins work; `running` + // while producing or revising; `evaluating` while the grader scores; + // `satisfied`/`max_iterations_reached`/`failed`/`interrupted` are terminal. + Result string `json:"result" api:"required"` + // Any of "outcome_evaluation". + Type BetaManagedAgentsOutcomeEvaluationResourceType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + CompletedAt respjson.Field + Description respjson.Field + Explanation respjson.Field + Iteration respjson.Field + OutcomeID respjson.Field + Result respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsOutcomeEvaluationResource) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsOutcomeEvaluationResource) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsOutcomeEvaluationResourceType string + +const ( + BetaManagedAgentsOutcomeEvaluationResourceTypeOutcomeEvaluation BetaManagedAgentsOutcomeEvaluationResourceType = "outcome_evaluation" +) + +// Cumulative count of server-executed tool invocations, broken down by tool. +type BetaManagedAgentsServerToolUsage struct { + // Number of server-executed web fetch requests. + WebFetchRequests int64 `json:"web_fetch_requests"` + // Number of server-executed web search requests. + WebSearchRequests int64 `json:"web_search_requests"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + WebFetchRequests respjson.Field + WebSearchRequests respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsServerToolUsage) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsServerToolUsage) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// A Managed Agents `session`. +type BetaManagedAgentsSession struct { + ID string `json:"id" api:"required"` + // Resolved `agent` definition for a `session`. Snapshot of the `agent` at + // `session` creation time. + Agent BetaManagedAgentsSessionAgent `json:"agent" api:"required"` + // A timestamp in RFC 3339 format + ArchivedAt time.Time `json:"archived_at" api:"required" format:"date-time"` + // A hard spend ceiling. The session stops issuing new model requests once the + // tracked list cost reaches `max_list_cost`. + Budget BetaManagedAgentsBudgetLimit `json:"budget" api:"required"` + // A timestamp in RFC 3339 format + CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"` + EnvironmentID string `json:"environment_id" api:"required"` + Metadata map[string]string `json:"metadata" api:"required"` + // Per-outcome evaluation state. One entry per define_outcome event sent to the + // session. + OutcomeEvaluations []BetaManagedAgentsOutcomeEvaluationResource `json:"outcome_evaluations" api:"required"` + Resources []BetaManagedAgentsSessionResourceUnion `json:"resources" api:"required"` + // Timing statistics for a session. + Stats BetaManagedAgentsSessionStats `json:"stats" api:"required"` + // SessionStatus enum + // + // Any of "rescheduling", "running", "idle", "terminated". + Status BetaManagedAgentsSessionStatus `json:"status" api:"required"` + Title string `json:"title" api:"required"` + // Any of "session". + Type BetaManagedAgentsSessionType `json:"type" api:"required"` + // A timestamp in RFC 3339 format + UpdatedAt time.Time `json:"updated_at" api:"required" format:"date-time"` + // Cumulative token usage for a session across all turns. + Usage BetaManagedAgentsSessionUsage `json:"usage" api:"required"` + // Vault IDs attached to the session at creation. Empty when no vaults were + // supplied. + VaultIDs []string `json:"vault_ids" api:"required"` + // Deployment ID when the session was created from a deployment reference. Null + // otherwise. + DeploymentID string `json:"deployment_id" api:"nullable"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + Agent respjson.Field + ArchivedAt respjson.Field + Budget respjson.Field + CreatedAt respjson.Field + EnvironmentID respjson.Field + Metadata respjson.Field + OutcomeEvaluations respjson.Field + Resources respjson.Field + Stats respjson.Field + Status respjson.Field + Title respjson.Field + Type respjson.Field + UpdatedAt respjson.Field + Usage respjson.Field + VaultIDs respjson.Field + DeploymentID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsSession) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsSession) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } @@ -524,11 +1308,14 @@ type BetaManagedAgentsSessionAgent struct { Description string `json:"description" api:"required"` MCPServers []BetaManagedAgentsMCPServerURLDefinition `json:"mcp_servers" api:"required"` // Model identifier and configuration. - Model BetaManagedAgentsModelConfig `json:"model" api:"required"` - Name string `json:"name" api:"required"` - Skills []BetaManagedAgentsSessionAgentSkillUnion `json:"skills" api:"required"` - System string `json:"system" api:"required"` - Tools []BetaManagedAgentsSessionAgentToolUnion `json:"tools" api:"required"` + Model BetaManagedAgentsModelConfig `json:"model" api:"required"` + // Resolved coordinator topology with full agent definitions for each roster + // member. + Multiagent BetaManagedAgentsSessionMultiagentCoordinator `json:"multiagent" api:"required"` + Name string `json:"name" api:"required"` + Skills []BetaManagedAgentsSessionAgentSkillUnion `json:"skills" api:"required"` + System string `json:"system" api:"required"` + Tools []BetaManagedAgentsSessionAgentToolUnion `json:"tools" api:"required"` // Any of "agent". Type BetaManagedAgentsSessionAgentType `json:"type" api:"required"` Version int64 `json:"version" api:"required"` @@ -538,6 +1325,7 @@ type BetaManagedAgentsSessionAgent struct { Description respjson.Field MCPServers respjson.Field Model respjson.Field + Multiagent respjson.Field Name respjson.Field Skills respjson.Field System respjson.Field @@ -629,7 +1417,7 @@ func (r *BetaManagedAgentsSessionAgentSkillUnion) UnmarshalJSON(data []byte) err // // Use the methods beginning with 'As' to cast the union to one of its variants. type BetaManagedAgentsSessionAgentToolUnion struct { - // This field is a union of [[]BetaManagedAgentsAgentToolConfig], + // This field is a union of [[]BetaManagedAgentsAgentToolConfigUnion], // [[]BetaManagedAgentsMCPToolConfig] Configs BetaManagedAgentsSessionAgentToolUnionConfigs `json:"configs"` // This field is a union of [BetaManagedAgentsAgentToolsetDefaultConfig], @@ -724,8 +1512,8 @@ func (r *BetaManagedAgentsSessionAgentToolUnion) UnmarshalJSON(data []byte) erro // OfBetaManagedAgentsMCPToolConfigArray] type BetaManagedAgentsSessionAgentToolUnionConfigs struct { // This field will be present if the value is a - // [[]BetaManagedAgentsAgentToolConfig] instead of an object. - OfBetaManagedAgentsAgentToolConfigArray []BetaManagedAgentsAgentToolConfig `json:",inline"` + // [[]BetaManagedAgentsAgentToolConfigUnion] instead of an object. + OfBetaManagedAgentsAgentToolConfigArray []BetaManagedAgentsAgentToolConfigUnion `json:",inline"` // This field will be present if the value is a [[]BetaManagedAgentsMCPToolConfig] // instead of an object. OfBetaManagedAgentsMCPToolConfigArray []BetaManagedAgentsMCPToolConfig `json:",inline"` @@ -789,95 +1577,926 @@ const ( BetaManagedAgentsSessionAgentTypeAgent BetaManagedAgentsSessionAgentType = "agent" ) -// Timing statistics for a session. -type BetaManagedAgentsSessionStats struct { - // Cumulative time in seconds the session spent in running status. Excludes idle - // time. - ActiveSeconds float64 `json:"active_seconds"` - // Elapsed time since session creation in seconds. For terminated sessions, frozen - // at the final update. - DurationSeconds float64 `json:"duration_seconds"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ActiveSeconds respjson.Field - DurationSeconds respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r BetaManagedAgentsSessionStats) RawJSON() string { return r.JSON.raw } -func (r *BetaManagedAgentsSessionStats) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Cumulative token usage for a session across all turns. -type BetaManagedAgentsSessionUsage struct { - // Prompt-cache creation token usage broken down by cache lifetime. - CacheCreation BetaManagedAgentsCacheCreationUsage `json:"cache_creation"` - // Total tokens read from prompt cache. - CacheReadInputTokens int64 `json:"cache_read_input_tokens"` - // Total input tokens consumed across all turns. - InputTokens int64 `json:"input_tokens"` - // Total output tokens generated across all turns. - OutputTokens int64 `json:"output_tokens"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - CacheCreation respjson.Field - CacheReadInputTokens respjson.Field - InputTokens respjson.Field - OutputTokens respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r BetaManagedAgentsSessionUsage) RawJSON() string { return r.JSON.raw } -func (r *BetaManagedAgentsSessionUsage) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type BetaSessionNewParams struct { - // Agent identifier. Accepts the `agent` ID string, which pins the latest version - // for the session, or an `agent` object with both id and version specified. - Agent BetaSessionNewParamsAgentUnion `json:"agent,omitzero" api:"required"` - // ID of the `environment` defining the container configuration for this session. - EnvironmentID string `json:"environment_id" api:"required"` - // Human-readable session title. - Title param.Opt[string] `json:"title,omitzero"` - // Arbitrary key-value metadata attached to the session. Maximum 16 pairs, keys up - // to 64 chars, values up to 512 chars. - Metadata map[string]string `json:"metadata,omitzero"` - // Resources (e.g. repositories, files) to mount into the session's container. - Resources []BetaSessionNewParamsResourceUnion `json:"resources,omitzero"` - // Vault IDs for stored credentials the agent can use during the session. - VaultIDs []string `json:"vault_ids,omitzero"` - // Optional header to specify the beta version(s) you want to use. - Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` +// Mid-session agent configuration update. Only `tools` and `mcp_servers` are +// updatable. Full replacement: the provided array becomes the new value. To +// preserve existing entries, GET the session, modify the array, and POST it back. +type BetaManagedAgentsSessionAgentUpdateParam struct { + // Replacement MCP server list. Full replacement: the provided array becomes the + // new value. Send an empty array to clear; omit to preserve. + MCPServers []BetaManagedAgentsURLMCPServerParams `json:"mcp_servers,omitzero"` + // Replacement tool list. Full replacement: the provided array becomes the new + // value. Send an empty array to clear; omit to preserve. + Tools []BetaManagedAgentsSessionAgentUpdateToolUnionParam `json:"tools,omitzero"` paramObj } -func (r BetaSessionNewParams) MarshalJSON() (data []byte, err error) { - type shadow BetaSessionNewParams +func (r BetaManagedAgentsSessionAgentUpdateParam) MarshalJSON() (data []byte, err error) { + type shadow BetaManagedAgentsSessionAgentUpdateParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *BetaSessionNewParams) UnmarshalJSON(data []byte) error { +func (r *BetaManagedAgentsSessionAgentUpdateParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } // Only one field can be non-zero. // // Use [param.IsOmitted] to confirm if a field is set. -type BetaSessionNewParamsAgentUnion struct { - OfString param.Opt[string] `json:",omitzero,inline"` - OfBetaManagedAgentsAgents *BetaManagedAgentsAgentParams `json:",omitzero,inline"` +type BetaManagedAgentsSessionAgentUpdateToolUnionParam struct { + OfAgentToolset20260401 *BetaManagedAgentsAgentToolset20260401Params `json:",omitzero,inline"` + OfMCPToolset *BetaManagedAgentsMCPToolsetParams `json:",omitzero,inline"` + OfCustom *BetaManagedAgentsCustomToolParams `json:",omitzero,inline"` paramUnion } -func (u BetaSessionNewParamsAgentUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfString, u.OfBetaManagedAgentsAgents) +func (u BetaManagedAgentsSessionAgentUpdateToolUnionParam) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfAgentToolset20260401, u.OfMCPToolset, u.OfCustom) +} +func (u *BetaManagedAgentsSessionAgentUpdateToolUnionParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *BetaManagedAgentsSessionAgentUpdateToolUnionParam) asAny() any { + if !param.IsOmitted(u.OfAgentToolset20260401) { + return u.OfAgentToolset20260401 + } else if !param.IsOmitted(u.OfMCPToolset) { + return u.OfMCPToolset + } else if !param.IsOmitted(u.OfCustom) { + return u.OfCustom + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaManagedAgentsSessionAgentUpdateToolUnionParam) GetMCPServerName() *string { + if vt := u.OfMCPToolset; vt != nil { + return &vt.MCPServerName + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaManagedAgentsSessionAgentUpdateToolUnionParam) GetDescription() *string { + if vt := u.OfCustom; vt != nil { + return &vt.Description + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaManagedAgentsSessionAgentUpdateToolUnionParam) GetInputSchema() *BetaManagedAgentsCustomToolInputSchemaParam { + if vt := u.OfCustom; vt != nil { + return &vt.InputSchema + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaManagedAgentsSessionAgentUpdateToolUnionParam) GetName() *string { + if vt := u.OfCustom; vt != nil { + return &vt.Name + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaManagedAgentsSessionAgentUpdateToolUnionParam) GetType() *string { + if vt := u.OfAgentToolset20260401; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfMCPToolset; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfCustom; vt != nil { + return (*string)(&vt.Type) + } + return nil +} + +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u BetaManagedAgentsSessionAgentUpdateToolUnionParam) GetConfigs() (res betaManagedAgentsSessionAgentUpdateToolUnionParamConfigs) { + if vt := u.OfAgentToolset20260401; vt != nil { + res.any = &vt.Configs + } else if vt := u.OfMCPToolset; vt != nil { + res.any = &vt.Configs + } + return +} + +// Can have the runtime types [_[]BetaManagedAgentsAgentToolConfigParamsUnion], +// [_[]BetaManagedAgentsMCPToolConfigParams] +type betaManagedAgentsSessionAgentUpdateToolUnionParamConfigs struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *[]anthropic.BetaManagedAgentsAgentToolConfigParamsUnion: +// case *[]anthropic.BetaManagedAgentsMCPToolConfigParams: +// default: +// fmt.Errorf("not present") +// } +func (u betaManagedAgentsSessionAgentUpdateToolUnionParamConfigs) AsAny() any { return u.any } + +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u BetaManagedAgentsSessionAgentUpdateToolUnionParam) GetDefaultConfig() (res betaManagedAgentsSessionAgentUpdateToolUnionParamDefaultConfig) { + if vt := u.OfAgentToolset20260401; vt != nil { + res.any = &vt.DefaultConfig + } else if vt := u.OfMCPToolset; vt != nil { + res.any = &vt.DefaultConfig + } + return +} + +// Can have the runtime types [*BetaManagedAgentsAgentToolsetDefaultConfigParams], +// [*BetaManagedAgentsMCPToolsetDefaultConfigParams] +type betaManagedAgentsSessionAgentUpdateToolUnionParamDefaultConfig struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BetaManagedAgentsAgentToolsetDefaultConfigParams: +// case *anthropic.BetaManagedAgentsMCPToolsetDefaultConfigParams: +// default: +// fmt.Errorf("not present") +// } +func (u betaManagedAgentsSessionAgentUpdateToolUnionParamDefaultConfig) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u betaManagedAgentsSessionAgentUpdateToolUnionParamDefaultConfig) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BetaManagedAgentsAgentToolsetDefaultConfigParams: + return paramutil.AddrIfPresent(vt.Enabled) + case *BetaManagedAgentsMCPToolsetDefaultConfigParams: + return paramutil.AddrIfPresent(vt.Enabled) + } + return nil +} + +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u betaManagedAgentsSessionAgentUpdateToolUnionParamDefaultConfig) GetPermissionPolicy() (res betaManagedAgentsSessionAgentUpdateToolUnionParamDefaultConfigPermissionPolicy) { + switch vt := u.any.(type) { + case *BetaManagedAgentsAgentToolsetDefaultConfigParams: + res.any = vt.PermissionPolicy + case *BetaManagedAgentsMCPToolsetDefaultConfigParams: + res.any = vt.PermissionPolicy + } + return res +} + +// Can have the runtime types [*BetaManagedAgentsAlwaysAllowPolicyParam], +// [*BetaManagedAgentsAlwaysAskPolicyParam] +type betaManagedAgentsSessionAgentUpdateToolUnionParamDefaultConfigPermissionPolicy struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BetaManagedAgentsAlwaysAllowPolicyParam: +// case *anthropic.BetaManagedAgentsAlwaysAskPolicyParam: +// default: +// fmt.Errorf("not present") +// } +func (u betaManagedAgentsSessionAgentUpdateToolUnionParamDefaultConfigPermissionPolicy) AsAny() any { + return u.any +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaManagedAgentsSessionAgentUpdateToolUnionParamDefaultConfigPermissionPolicy) GetType() *string { + switch vt := u.any.(type) { + case *BetaManagedAgentsAgentToolsetDefaultConfigParamsPermissionPolicyUnion: + return vt.GetType() + case *BetaManagedAgentsMCPToolsetDefaultConfigParamsPermissionPolicyUnion: + return vt.GetType() + } + return nil +} + +func init() { + apijson.RegisterUnion[BetaManagedAgentsSessionAgentUpdateToolUnionParam]( + "type", + apijson.Discriminator[BetaManagedAgentsAgentToolset20260401Params]("agent_toolset_20260401"), + apijson.Discriminator[BetaManagedAgentsMCPToolsetParams]("mcp_toolset"), + apijson.Discriminator[BetaManagedAgentsCustomToolParams]("custom"), + ) +} + +// Resolved coordinator topology with full agent definitions for each roster +// member. +type BetaManagedAgentsSessionMultiagentCoordinator struct { + // Full `agent` definitions the coordinator may spawn as session threads. + Agents []BetaManagedAgentsSessionMultiagentCoordinatorAgentUnion `json:"agents" api:"required"` + // Any of "coordinator". + Type BetaManagedAgentsSessionMultiagentCoordinatorType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Agents respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsSessionMultiagentCoordinator) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsSessionMultiagentCoordinator) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaManagedAgentsSessionMultiagentCoordinatorAgentUnion contains all possible +// properties and values from [BetaManagedAgentsSessionThreadAgent], +// [BetaManagedAgentsAdvisor]. +// +// Use the [BetaManagedAgentsSessionMultiagentCoordinatorAgentUnion.AsAny] method +// to switch on the variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaManagedAgentsSessionMultiagentCoordinatorAgentUnion struct { + // This field is from variant [BetaManagedAgentsSessionThreadAgent]. + ID string `json:"id"` + // This field is from variant [BetaManagedAgentsSessionThreadAgent]. + Description string `json:"description"` + // This field is from variant [BetaManagedAgentsSessionThreadAgent]. + MCPServers []BetaManagedAgentsMCPServerURLDefinition `json:"mcp_servers"` + // This field is a union of [BetaManagedAgentsModelConfig], [string] + Model BetaManagedAgentsSessionMultiagentCoordinatorAgentUnionModel `json:"model"` + // This field is from variant [BetaManagedAgentsSessionThreadAgent]. + Name string `json:"name"` + // This field is from variant [BetaManagedAgentsSessionThreadAgent]. + Skills []BetaManagedAgentsSessionThreadAgentSkillUnion `json:"skills"` + // This field is from variant [BetaManagedAgentsSessionThreadAgent]. + System string `json:"system"` + // This field is from variant [BetaManagedAgentsSessionThreadAgent]. + Tools []BetaManagedAgentsSessionThreadAgentToolUnion `json:"tools"` + // Any of "agent", "advisor". + Type string `json:"type"` + // This field is from variant [BetaManagedAgentsSessionThreadAgent]. + Version int64 `json:"version"` + JSON struct { + ID respjson.Field + Description respjson.Field + MCPServers respjson.Field + Model respjson.Field + Name respjson.Field + Skills respjson.Field + System respjson.Field + Tools respjson.Field + Type respjson.Field + Version respjson.Field + raw string + } `json:"-"` +} + +// anyBetaManagedAgentsSessionMultiagentCoordinatorAgent is implemented by each +// variant of [BetaManagedAgentsSessionMultiagentCoordinatorAgentUnion] to add type +// safety for the return type of +// [BetaManagedAgentsSessionMultiagentCoordinatorAgentUnion.AsAny] +type anyBetaManagedAgentsSessionMultiagentCoordinatorAgent interface { + implBetaManagedAgentsSessionMultiagentCoordinatorAgentUnion() +} + +func (BetaManagedAgentsSessionThreadAgent) implBetaManagedAgentsSessionMultiagentCoordinatorAgentUnion() { +} +func (BetaManagedAgentsAdvisor) implBetaManagedAgentsSessionMultiagentCoordinatorAgentUnion() {} + +// Use the following switch statement to find the correct variant +// +// switch variant := BetaManagedAgentsSessionMultiagentCoordinatorAgentUnion.AsAny().(type) { +// case anthropic.BetaManagedAgentsSessionThreadAgent: +// case anthropic.BetaManagedAgentsAdvisor: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaManagedAgentsSessionMultiagentCoordinatorAgentUnion) AsAny() anyBetaManagedAgentsSessionMultiagentCoordinatorAgent { + switch u.Type { + case "agent": + return u.AsAgent() + case "advisor": + return u.AsAdvisor() + } + return nil +} + +func (u BetaManagedAgentsSessionMultiagentCoordinatorAgentUnion) AsAgent() (v BetaManagedAgentsSessionThreadAgent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsSessionMultiagentCoordinatorAgentUnion) AsAdvisor() (v BetaManagedAgentsAdvisor) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u BetaManagedAgentsSessionMultiagentCoordinatorAgentUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaManagedAgentsSessionMultiagentCoordinatorAgentUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaManagedAgentsSessionMultiagentCoordinatorAgentUnionModel is an implicit +// subunion of [BetaManagedAgentsSessionMultiagentCoordinatorAgentUnion]. +// BetaManagedAgentsSessionMultiagentCoordinatorAgentUnionModel provides convenient +// access to the sub-properties of the union. +// +// For type safety it is recommended to directly use a variant of the +// [BetaManagedAgentsSessionMultiagentCoordinatorAgentUnion]. +// +// If the underlying value is not a json object, one of the following properties +// will be valid: OfString] +type BetaManagedAgentsSessionMultiagentCoordinatorAgentUnionModel struct { + // This field will be present if the value is a [string] instead of an object. + OfString string `json:",inline"` + // This field is from variant [BetaManagedAgentsModelConfig]. + ID BetaManagedAgentsModel `json:"id"` + // This field is from variant [BetaManagedAgentsModelConfig]. + Effort BetaManagedAgentsModelConfigEffortUnion `json:"effort"` + // This field is from variant [BetaManagedAgentsModelConfig]. + InferenceGeo string `json:"inference_geo"` + // This field is from variant [BetaManagedAgentsModelConfig]. + Speed BetaManagedAgentsModelConfigSpeed `json:"speed"` + JSON struct { + OfString respjson.Field + ID respjson.Field + Effort respjson.Field + InferenceGeo respjson.Field + Speed respjson.Field + raw string + } `json:"-"` +} + +func (r *BetaManagedAgentsSessionMultiagentCoordinatorAgentUnionModel) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsSessionMultiagentCoordinatorType string + +const ( + BetaManagedAgentsSessionMultiagentCoordinatorTypeCoordinator BetaManagedAgentsSessionMultiagentCoordinatorType = "coordinator" +) + +// Timing statistics for a session. +type BetaManagedAgentsSessionStats struct { + // Cumulative time in seconds the session spent in running status. Excludes idle + // time. + ActiveSeconds float64 `json:"active_seconds"` + // Elapsed time since session creation in seconds. For terminated sessions, frozen + // at the final update. + DurationSeconds float64 `json:"duration_seconds"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ActiveSeconds respjson.Field + DurationSeconds respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsSessionStats) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsSessionStats) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Emitted when an UpdateSession request changed at least one field. Carries only +// the fields that changed; absent fields were not part of the update. The new +// configuration applies from the next turn. +type BetaManagedAgentsSessionUpdatedEvent struct { + // Unique identifier for this event. + ID string `json:"id" api:"required"` + // A timestamp in RFC 3339 format + ProcessedAt time.Time `json:"processed_at" api:"required" format:"date-time"` + // Any of "session.updated". + Type BetaManagedAgentsSessionUpdatedEventType `json:"type" api:"required"` + // Resolved `agent` definition for a `session`. Snapshot of the `agent` at + // `session` creation time. + Agent BetaManagedAgentsSessionAgent `json:"agent" api:"nullable"` + // A hard spend ceiling. The session stops issuing new model requests once the + // tracked list cost reaches `max_list_cost`. + Budget BetaManagedAgentsBudgetLimit `json:"budget" api:"nullable"` + // The session's full metadata bag after the update. Present when the update set + // non-empty metadata; absent when metadata was unchanged or cleared to empty. + Metadata map[string]string `json:"metadata"` + // The session's new title. Present only when the update changed it. + Title string `json:"title" api:"nullable"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + ProcessedAt respjson.Field + Type respjson.Field + Agent respjson.Field + Budget respjson.Field + Metadata respjson.Field + Title respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsSessionUpdatedEvent) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsSessionUpdatedEvent) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsSessionUpdatedEventType string + +const ( + BetaManagedAgentsSessionUpdatedEventTypeSessionUpdated BetaManagedAgentsSessionUpdatedEventType = "session.updated" +) + +// Cumulative token usage for a session across all turns. +type BetaManagedAgentsSessionUsage struct { + // Cumulative time in seconds during which the session had at least one thread in + // running status. Overlapping activity from concurrent threads is counted once, + // unlike `stats.active_seconds`, which sums each thread's own active time. This is + // the duration the session's runtime cost is priced on. + ActiveSeconds float64 `json:"active_seconds"` + // Prompt-cache creation token usage broken down by cache lifetime. + CacheCreation BetaManagedAgentsCacheCreationUsage `json:"cache_creation"` + // Total tokens read from prompt cache. + CacheReadInputTokens int64 `json:"cache_read_input_tokens"` + // Total input tokens consumed across all turns. + InputTokens int64 `json:"input_tokens"` + // A monetary amount in a specific currency. + ListCost BetaMonetaryAmount `json:"list_cost" api:"nullable"` + // Total output tokens generated across all turns. + OutputTokens int64 `json:"output_tokens"` + // Cumulative count of server-executed tool invocations, broken down by tool. + ServerToolUse BetaManagedAgentsServerToolUsage `json:"server_tool_use" api:"nullable"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ActiveSeconds respjson.Field + CacheCreation respjson.Field + CacheReadInputTokens respjson.Field + InputTokens respjson.Field + ListCost respjson.Field + OutputTokens respjson.Field + ServerToolUse respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsSessionUsage) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsSessionUsage) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Periodic snapshot of the session's cumulative usage and tracked list cost. +type BetaManagedAgentsSessionUsageEvent struct { + // Unique identifier for this event. + ID string `json:"id" api:"required"` + // A timestamp in RFC 3339 format + ProcessedAt time.Time `json:"processed_at" api:"required" format:"date-time"` + // Any of "session.usage". + Type BetaManagedAgentsSessionUsageEventType `json:"type" api:"required"` + // Point-in-time snapshot of a session's cumulative usage. + Usage BetaManagedAgentsSessionUsageSnapshot `json:"usage" api:"required"` + // A hard spend ceiling. The session stops issuing new model requests once the + // tracked list cost reaches `max_list_cost`. + Budget BetaManagedAgentsBudgetLimit `json:"budget" api:"nullable"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + ProcessedAt respjson.Field + Type respjson.Field + Usage respjson.Field + Budget respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsSessionUsageEvent) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsSessionUsageEvent) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsSessionUsageEventType string + +const ( + BetaManagedAgentsSessionUsageEventTypeSessionUsage BetaManagedAgentsSessionUsageEventType = "session.usage" +) + +// Opens a preview of a buffered event. Carries the previewed event's type and id +// only. Followed by zero or more event_delta events with the same event id, +// normally concluded by the buffered event carrying that id. If the producing +// model request ends without that event (an error or interrupt mid-stream), its +// terminal span.model_request_end closes the preview. Only sent on stream +// connections that opt in via event_deltas; never appears in event history. +type BetaManagedAgentsStartEvent struct { + // The previewed event's type and id. The event type determines which delta types + // the preview's event_delta events carry: agent.message events stream + // content_delta fragments; agent.thinking previews are start-only — no deltas + // follow, and the buffered agent.thinking with the same id concludes them. + Event BetaManagedAgentsStartEventPreviewUnion `json:"event" api:"required"` + // Any of "event_start". + Type BetaManagedAgentsStartEventType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Event respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsStartEvent) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsStartEvent) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsStartEventType string + +const ( + BetaManagedAgentsStartEventTypeEventStart BetaManagedAgentsStartEventType = "event_start" +) + +// BetaManagedAgentsStartEventPreviewUnion contains all possible properties and +// values from [BetaManagedAgentsAgentMessagePreview], +// [BetaManagedAgentsAgentThinkingPreview]. +// +// Use the [BetaManagedAgentsStartEventPreviewUnion.AsAny] method to switch on the +// variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaManagedAgentsStartEventPreviewUnion struct { + ID string `json:"id"` + // Any of "agent.message", "agent.thinking". + Type string `json:"type"` + JSON struct { + ID respjson.Field + Type respjson.Field + raw string + } `json:"-"` +} + +// anyBetaManagedAgentsStartEventPreview is implemented by each variant of +// [BetaManagedAgentsStartEventPreviewUnion] to add type safety for the return type +// of [BetaManagedAgentsStartEventPreviewUnion.AsAny] +type anyBetaManagedAgentsStartEventPreview interface { + implBetaManagedAgentsStartEventPreviewUnion() +} + +func (BetaManagedAgentsAgentMessagePreview) implBetaManagedAgentsStartEventPreviewUnion() {} +func (BetaManagedAgentsAgentThinkingPreview) implBetaManagedAgentsStartEventPreviewUnion() {} + +// Use the following switch statement to find the correct variant +// +// switch variant := BetaManagedAgentsStartEventPreviewUnion.AsAny().(type) { +// case anthropic.BetaManagedAgentsAgentMessagePreview: +// case anthropic.BetaManagedAgentsAgentThinkingPreview: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaManagedAgentsStartEventPreviewUnion) AsAny() anyBetaManagedAgentsStartEventPreview { + switch u.Type { + case "agent.message": + return u.AsAgentMessage() + case "agent.thinking": + return u.AsAgentThinking() + } + return nil +} + +func (u BetaManagedAgentsStartEventPreviewUnion) AsAgentMessage() (v BetaManagedAgentsAgentMessagePreview) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsStartEventPreviewUnion) AsAgentThinking() (v BetaManagedAgentsAgentThinkingPreview) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u BetaManagedAgentsStartEventPreviewUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaManagedAgentsStartEventPreviewUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Regular text content. +type BetaManagedAgentsSystemContentBlock struct { + // The text content. + Text string `json:"text" api:"required"` + // Any of "text". + Type BetaManagedAgentsSystemContentBlockType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Text respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsSystemContentBlock) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsSystemContentBlock) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// ToParam converts this BetaManagedAgentsSystemContentBlock to a +// BetaManagedAgentsSystemContentBlockParam. +// +// Warning: the fields of the param type will not be present. ToParam should only +// be used at the last possible moment before sending a request. Test for this with +// BetaManagedAgentsSystemContentBlockParam.Overrides() +func (r BetaManagedAgentsSystemContentBlock) ToParam() BetaManagedAgentsSystemContentBlockParam { + return param.Override[BetaManagedAgentsSystemContentBlockParam](json.RawMessage(r.RawJSON())) +} + +type BetaManagedAgentsSystemContentBlockType string + +const ( + BetaManagedAgentsSystemContentBlockTypeText BetaManagedAgentsSystemContentBlockType = "text" +) + +// Regular text content. +// +// The properties Text, Type are required. +type BetaManagedAgentsSystemContentBlockParam struct { + // The text content. + Text string `json:"text" api:"required"` + // Any of "text". + Type BetaManagedAgentsSystemContentBlockType `json:"type,omitzero" api:"required"` + paramObj +} + +func (r BetaManagedAgentsSystemContentBlockParam) MarshalJSON() (data []byte, err error) { + type shadow BetaManagedAgentsSystemContentBlockParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaManagedAgentsSystemContentBlockParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// A mid-conversation system message event. Carries system-role content that is +// appended to the session as a `role: "system"` turn. +type BetaManagedAgentsSystemMessageEvent struct { + // Unique identifier for this event. + ID string `json:"id" api:"required"` + // System content blocks. Text-only. + Content []BetaManagedAgentsSystemContentBlock `json:"content" api:"required"` + // Any of "system.message". + Type BetaManagedAgentsSystemMessageEventType `json:"type" api:"required"` + // A timestamp in RFC 3339 format + ProcessedAt time.Time `json:"processed_at" api:"nullable" format:"date-time"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + Content respjson.Field + Type respjson.Field + ProcessedAt respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsSystemMessageEvent) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsSystemMessageEvent) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsSystemMessageEventType string + +const ( + BetaManagedAgentsSystemMessageEventTypeSystemMessage BetaManagedAgentsSystemMessageEventType = "system.message" +) + +// Event sent by the client providing the result of an agent-toolset tool +// execution. Only valid on `self_hosted` environments, where sandbox-routed tools +// are executed by the client rather than the server. +type BetaManagedAgentsUserToolResultEvent struct { + // Unique identifier for this event. + ID string `json:"id" api:"required"` + // The id of the `agent.tool_use` event this result corresponds to, which can be + // found in the last `session.status_idle` + // [event's](https://platform.claude.com/docs/en/api/beta/sessions/events/list#beta_managed_agents_session_requires_action.event_ids) + // `stop_reason.event_ids` field. + ToolUseID string `json:"tool_use_id" api:"required"` + // Any of "user.tool_result". + Type BetaManagedAgentsUserToolResultEventType `json:"type" api:"required"` + // The result content returned by the tool. + Content []BetaManagedAgentsUserToolResultEventContentUnion `json:"content"` + // Whether the tool execution resulted in an error. + IsError bool `json:"is_error" api:"nullable"` + // A timestamp in RFC 3339 format + ProcessedAt time.Time `json:"processed_at" api:"nullable" format:"date-time"` + // Routes this result to a subagent thread. Copy from the `agent.tool_use` event's + // `session_thread_id`. + SessionThreadID string `json:"session_thread_id" api:"nullable"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + ToolUseID respjson.Field + Type respjson.Field + Content respjson.Field + IsError respjson.Field + ProcessedAt respjson.Field + SessionThreadID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsUserToolResultEvent) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsUserToolResultEvent) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsUserToolResultEventType string + +const ( + BetaManagedAgentsUserToolResultEventTypeUserToolResult BetaManagedAgentsUserToolResultEventType = "user.tool_result" +) + +// BetaManagedAgentsUserToolResultEventContentUnion contains all possible +// properties and values from [BetaManagedAgentsTextBlock], +// [BetaManagedAgentsImageBlock], [BetaManagedAgentsDocumentBlock], +// [BetaManagedAgentsSearchResultBlock]. +// +// Use the [BetaManagedAgentsUserToolResultEventContentUnion.AsAny] method to +// switch on the variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaManagedAgentsUserToolResultEventContentUnion struct { + // This field is from variant [BetaManagedAgentsTextBlock]. + Text string `json:"text"` + // Any of "text", "image", "document", "search_result". + Type string `json:"type"` + // This field is a union of [BetaManagedAgentsImageBlockSourceUnion], + // [BetaManagedAgentsDocumentBlockSourceUnion], [string] + Source BetaManagedAgentsUserToolResultEventContentUnionSource `json:"source"` + // This field is from variant [BetaManagedAgentsDocumentBlock]. + Context string `json:"context"` + Title string `json:"title"` + // This field is from variant [BetaManagedAgentsSearchResultBlock]. + Citations BetaManagedAgentsSearchResultCitations `json:"citations"` + // This field is from variant [BetaManagedAgentsSearchResultBlock]. + Content []BetaManagedAgentsSearchResultContent `json:"content"` + JSON struct { + Text respjson.Field + Type respjson.Field + Source respjson.Field + Context respjson.Field + Title respjson.Field + Citations respjson.Field + Content respjson.Field + raw string + } `json:"-"` +} + +// anyBetaManagedAgentsUserToolResultEventContent is implemented by each variant of +// [BetaManagedAgentsUserToolResultEventContentUnion] to add type safety for the +// return type of [BetaManagedAgentsUserToolResultEventContentUnion.AsAny] +type anyBetaManagedAgentsUserToolResultEventContent interface { + implBetaManagedAgentsUserToolResultEventContentUnion() +} + +func (BetaManagedAgentsTextBlock) implBetaManagedAgentsUserToolResultEventContentUnion() {} +func (BetaManagedAgentsImageBlock) implBetaManagedAgentsUserToolResultEventContentUnion() {} +func (BetaManagedAgentsDocumentBlock) implBetaManagedAgentsUserToolResultEventContentUnion() {} +func (BetaManagedAgentsSearchResultBlock) implBetaManagedAgentsUserToolResultEventContentUnion() {} + +// Use the following switch statement to find the correct variant +// +// switch variant := BetaManagedAgentsUserToolResultEventContentUnion.AsAny().(type) { +// case anthropic.BetaManagedAgentsTextBlock: +// case anthropic.BetaManagedAgentsImageBlock: +// case anthropic.BetaManagedAgentsDocumentBlock: +// case anthropic.BetaManagedAgentsSearchResultBlock: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaManagedAgentsUserToolResultEventContentUnion) AsAny() anyBetaManagedAgentsUserToolResultEventContent { + switch u.Type { + case "text": + return u.AsText() + case "image": + return u.AsImage() + case "document": + return u.AsDocument() + case "search_result": + return u.AsSearchResult() + } + return nil +} + +func (u BetaManagedAgentsUserToolResultEventContentUnion) AsText() (v BetaManagedAgentsTextBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsUserToolResultEventContentUnion) AsImage() (v BetaManagedAgentsImageBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsUserToolResultEventContentUnion) AsDocument() (v BetaManagedAgentsDocumentBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsUserToolResultEventContentUnion) AsSearchResult() (v BetaManagedAgentsSearchResultBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u BetaManagedAgentsUserToolResultEventContentUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaManagedAgentsUserToolResultEventContentUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaManagedAgentsUserToolResultEventContentUnionSource is an implicit subunion +// of [BetaManagedAgentsUserToolResultEventContentUnion]. +// BetaManagedAgentsUserToolResultEventContentUnionSource provides convenient +// access to the sub-properties of the union. +// +// For type safety it is recommended to directly use a variant of the +// [BetaManagedAgentsUserToolResultEventContentUnion]. +// +// If the underlying value is not a json object, one of the following properties +// will be valid: OfString] +type BetaManagedAgentsUserToolResultEventContentUnionSource struct { + // This field will be present if the value is a [string] instead of an object. + OfString string `json:",inline"` + Data string `json:"data"` + MediaType string `json:"media_type"` + Type string `json:"type"` + URL string `json:"url"` + FileID string `json:"file_id"` + JSON struct { + OfString respjson.Field + Data respjson.Field + MediaType respjson.Field + Type respjson.Field + URL respjson.Field + FileID respjson.Field + raw string + } `json:"-"` +} + +func (r *BetaManagedAgentsUserToolResultEventContentUnionSource) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaSessionNewParams struct { + // Agent identifier. Accepts the `agent` ID string, which pins the latest version + // for the session, or an `agent` object with both id and version specified. + Agent BetaSessionNewParamsAgentUnion `json:"agent,omitzero" api:"required"` + // ID of the `environment` defining the container configuration for this session. + EnvironmentID string `json:"environment_id" api:"required"` + // Human-readable session title. + Title param.Opt[string] `json:"title,omitzero"` + // A hard spend ceiling. The session stops issuing new model requests once the + // tracked list cost reaches `max_list_cost`. + Budget BetaManagedAgentsBudgetLimitParam `json:"budget,omitzero"` + // Initial events to send to the `session` at creation, processed in order. + // Supports `user.message` and `user.define_outcome` events. Maximum 50 events. + InitialEvents []BetaSessionNewParamsInitialEventUnion `json:"initial_events,omitzero"` + // Arbitrary key-value metadata attached to the session. Maximum 16 pairs, keys up + // to 64 chars, values up to 512 chars. + Metadata map[string]string `json:"metadata,omitzero"` + // Resources (e.g. repositories, files) to mount into the session's container. + Resources []BetaSessionNewParamsResourceUnion `json:"resources,omitzero"` + // Vault IDs for stored credentials the agent can use during the session. + VaultIDs []string `json:"vault_ids,omitzero"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +func (r BetaSessionNewParams) MarshalJSON() (data []byte, err error) { + type shadow BetaSessionNewParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaSessionNewParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaSessionNewParamsAgentUnion struct { + OfString param.Opt[string] `json:",omitzero,inline"` + OfBetaManagedAgentsAgents *BetaManagedAgentsAgentParams `json:",omitzero,inline"` + OfBetaManagedAgentsAgentWithOverridess *BetaManagedAgentsAgentWithOverridesParams `json:",omitzero,inline"` + paramUnion +} + +func (u BetaSessionNewParamsAgentUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfString, u.OfBetaManagedAgentsAgents, u.OfBetaManagedAgentsAgentWithOverridess) } func (u *BetaSessionNewParamsAgentUnion) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, u) @@ -888,21 +2507,169 @@ func (u *BetaSessionNewParamsAgentUnion) asAny() any { return &u.OfString.Value } else if !param.IsOmitted(u.OfBetaManagedAgentsAgents) { return u.OfBetaManagedAgentsAgents + } else if !param.IsOmitted(u.OfBetaManagedAgentsAgentWithOverridess) { + return u.OfBetaManagedAgentsAgentWithOverridess + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaSessionNewParamsAgentUnion) GetMCPServers() []BetaManagedAgentsURLMCPServerParams { + if vt := u.OfBetaManagedAgentsAgentWithOverridess; vt != nil { + return vt.MCPServers + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaSessionNewParamsAgentUnion) GetModel() *BetaManagedAgentsModelConfigParams { + if vt := u.OfBetaManagedAgentsAgentWithOverridess; vt != nil { + return &vt.Model + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaSessionNewParamsAgentUnion) GetSkills() []BetaManagedAgentsSkillParamsUnion { + if vt := u.OfBetaManagedAgentsAgentWithOverridess; vt != nil { + return vt.Skills + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaSessionNewParamsAgentUnion) GetSystem() *string { + if vt := u.OfBetaManagedAgentsAgentWithOverridess; vt != nil && vt.System.Valid() { + return &vt.System.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaSessionNewParamsAgentUnion) GetTools() []BetaManagedAgentsAgentWithOverridesParamsToolUnion { + if vt := u.OfBetaManagedAgentsAgentWithOverridess; vt != nil { + return vt.Tools + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaSessionNewParamsAgentUnion) GetID() *string { + if vt := u.OfBetaManagedAgentsAgents; vt != nil { + return (*string)(&vt.ID) + } else if vt := u.OfBetaManagedAgentsAgentWithOverridess; vt != nil { + return (*string)(&vt.ID) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaSessionNewParamsAgentUnion) GetType() *string { + if vt := u.OfBetaManagedAgentsAgents; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfBetaManagedAgentsAgentWithOverridess; vt != nil { + return (*string)(&vt.Type) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaSessionNewParamsAgentUnion) GetVersion() *int64 { + if vt := u.OfBetaManagedAgentsAgents; vt != nil && vt.Version.Valid() { + return &vt.Version.Value + } else if vt := u.OfBetaManagedAgentsAgentWithOverridess; vt != nil && vt.Version.Valid() { + return &vt.Version.Value } return nil } +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaSessionNewParamsInitialEventUnion struct { + OfUserMessage *BetaManagedAgentsUserMessageEventParams `json:",omitzero,inline"` + OfUserDefineOutcome *BetaManagedAgentsUserDefineOutcomeEventParams `json:",omitzero,inline"` + paramUnion +} + +func (u BetaSessionNewParamsInitialEventUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfUserMessage, u.OfUserDefineOutcome) +} +func (u *BetaSessionNewParamsInitialEventUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *BetaSessionNewParamsInitialEventUnion) asAny() any { + if !param.IsOmitted(u.OfUserMessage) { + return u.OfUserMessage + } else if !param.IsOmitted(u.OfUserDefineOutcome) { + return u.OfUserDefineOutcome + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaSessionNewParamsInitialEventUnion) GetContent() []BetaManagedAgentsUserMessageEventParamsContentUnion { + if vt := u.OfUserMessage; vt != nil { + return vt.Content + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaSessionNewParamsInitialEventUnion) GetDescription() *string { + if vt := u.OfUserDefineOutcome; vt != nil { + return &vt.Description + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaSessionNewParamsInitialEventUnion) GetRubric() *BetaManagedAgentsUserDefineOutcomeEventParamsRubricUnion { + if vt := u.OfUserDefineOutcome; vt != nil { + return &vt.Rubric + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaSessionNewParamsInitialEventUnion) GetMaxIterations() *int64 { + if vt := u.OfUserDefineOutcome; vt != nil && vt.MaxIterations.Valid() { + return &vt.MaxIterations.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaSessionNewParamsInitialEventUnion) GetType() *string { + if vt := u.OfUserMessage; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfUserDefineOutcome; vt != nil { + return (*string)(&vt.Type) + } + return nil +} + +func init() { + apijson.RegisterUnion[BetaSessionNewParamsInitialEventUnion]( + "type", + apijson.Discriminator[BetaManagedAgentsUserMessageEventParams]("user.message"), + apijson.Discriminator[BetaManagedAgentsUserDefineOutcomeEventParams]("user.define_outcome"), + ) +} + // Only one field can be non-zero. // // Use [param.IsOmitted] to confirm if a field is set. type BetaSessionNewParamsResourceUnion struct { OfGitHubRepository *BetaManagedAgentsGitHubRepositoryResourceParams `json:",omitzero,inline"` OfFile *BetaManagedAgentsFileResourceParams `json:",omitzero,inline"` + OfMemoryStore *BetaManagedAgentsMemoryStoreResourceParam `json:",omitzero,inline"` paramUnion } func (u BetaSessionNewParamsResourceUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfGitHubRepository, u.OfFile) + return param.MarshalUnion(u, u.OfGitHubRepository, u.OfFile, u.OfMemoryStore) } func (u *BetaSessionNewParamsResourceUnion) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, u) @@ -913,6 +2680,8 @@ func (u *BetaSessionNewParamsResourceUnion) asAny() any { return u.OfGitHubRepository } else if !param.IsOmitted(u.OfFile) { return u.OfFile + } else if !param.IsOmitted(u.OfMemoryStore) { + return u.OfMemoryStore } return nil } @@ -949,12 +2718,38 @@ func (u BetaSessionNewParamsResourceUnion) GetFileID() *string { return nil } +// Returns a pointer to the underlying variant's property, if present. +func (u BetaSessionNewParamsResourceUnion) GetMemoryStoreID() *string { + if vt := u.OfMemoryStore; vt != nil { + return &vt.MemoryStoreID + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaSessionNewParamsResourceUnion) GetAccess() *string { + if vt := u.OfMemoryStore; vt != nil { + return (*string)(&vt.Access) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaSessionNewParamsResourceUnion) GetInstructions() *string { + if vt := u.OfMemoryStore; vt != nil && vt.Instructions.Valid() { + return &vt.Instructions.Value + } + return nil +} + // Returns a pointer to the underlying variant's property, if present. func (u BetaSessionNewParamsResourceUnion) GetType() *string { if vt := u.OfGitHubRepository; vt != nil { return (*string)(&vt.Type) } else if vt := u.OfFile; vt != nil { return (*string)(&vt.Type) + } else if vt := u.OfMemoryStore; vt != nil { + return (*string)(&vt.Type) } return nil } @@ -974,6 +2769,7 @@ func init() { "type", apijson.Discriminator[BetaManagedAgentsGitHubRepositoryResourceParams]("github_repository"), apijson.Discriminator[BetaManagedAgentsFileResourceParams]("file"), + apijson.Discriminator[BetaManagedAgentsMemoryStoreResourceParam]("memory_store"), ) } @@ -989,6 +2785,13 @@ type BetaSessionUpdateParams struct { // Metadata patch. Set a key to a string to upsert it, or to null to delete it. // Omit the field to preserve. Metadata map[string]string `json:"metadata,omitzero"` + // Mid-session agent configuration update. Only `tools` and `mcp_servers` are + // updatable. Full replacement: the provided array becomes the new value. To + // preserve existing entries, GET the session, modify the array, and POST it back. + Agent BetaManagedAgentsSessionAgentUpdateParam `json:"agent,omitzero"` + // A hard spend ceiling. The session stops issuing new model requests once the + // tracked list cost reaches `max_list_cost`. + Budget BetaManagedAgentsBudgetLimitParam `json:"budget,omitzero"` // Vault IDs (`vlt_*`) to attach to the session. Not yet supported; requests // setting this field are rejected. Reserved for future use. VaultIDs []string `json:"vault_ids,omitzero"` @@ -1018,17 +2821,27 @@ type BetaSessionListParams struct { CreatedAtLt param.Opt[time.Time] `query:"created_at[lt],omitzero" format:"date-time" json:"-"` // Return sessions created at or before this time (inclusive). CreatedAtLte param.Opt[time.Time] `query:"created_at[lte],omitzero" format:"date-time" json:"-"` + // Filter sessions created by this deployment ID. + DeploymentID param.Opt[string] `query:"deployment_id,omitzero" json:"-"` // When true, includes archived sessions. Default: false (exclude archived). IncludeArchived param.Opt[bool] `query:"include_archived,omitzero" json:"-"` // Maximum number of results to return. Limit param.Opt[int64] `query:"limit,omitzero" json:"-"` - // Opaque pagination cursor from a previous response's next_page. + // Filter sessions whose resources contain a memory_store with this memory store + // ID. + MemoryStoreID param.Opt[string] `query:"memory_store_id,omitzero" json:"-"` + // Opaque pagination cursor from a previous response. Page param.Opt[string] `query:"page,omitzero" json:"-"` // Sort direction for results, ordered by created_at. Defaults to desc (newest // first). // // Any of "asc", "desc". Order BetaSessionListParamsOrder `query:"order,omitzero" json:"-"` + // Filter by session status. Repeat the parameter to match any of multiple + // statuses. + // + // Any of "rescheduling", "running", "idle", "terminated". + Statuses []string `query:"statuses,omitzero" json:"-"` // Optional header to specify the beta version(s) you want to use. Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` paramObj @@ -1037,7 +2850,7 @@ type BetaSessionListParams struct { // URLQuery serializes [BetaSessionListParams]'s query parameters as `url.Values`. func (r BetaSessionListParams) URLQuery() (v url.Values, err error) { return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ - ArrayFormat: apiquery.ArrayQueryFormatComma, + ArrayFormat: apiquery.ArrayQueryFormatBrackets, NestedFormat: apiquery.NestedQueryFormatBrackets, }) } diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/betasessionevent.go b/vendor/github.com/anthropics/anthropic-sdk-go/betasessionevent.go index 9e9e38aa1..4741f2db8 100644 --- a/vendor/github.com/anthropics/anthropic-sdk-go/betasessionevent.go +++ b/vendor/github.com/anthropics/anthropic-sdk-go/betasessionevent.go @@ -88,12 +88,12 @@ func (r *BetaSessionEventService) Send(ctx context.Context, sessionID string, pa } // Stream Events -func (r *BetaSessionEventService) StreamEvents(ctx context.Context, sessionID string, query BetaSessionEventStreamParams, opts ...option.RequestOption) (stream *ssestream.Stream[BetaManagedAgentsStreamSessionEventsUnion]) { +func (r *BetaSessionEventService) StreamEvents(ctx context.Context, sessionID string, params BetaSessionEventStreamParams, opts ...option.RequestOption) (stream *ssestream.Stream[BetaManagedAgentsStreamSessionEventsUnion]) { var ( raw *http.Response err error ) - for _, v := range query.Betas { + for _, v := range params.Betas { opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) } opts = slices.Concat(r.Options, opts) @@ -103,7 +103,7 @@ func (r *BetaSessionEventService) StreamEvents(ctx context.Context, sessionID st return ssestream.NewStream[BetaManagedAgentsStreamSessionEventsUnion](nil, err) } path := fmt.Sprintf("v1/sessions/%s/events/stream?beta=true", sessionID) - err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &raw, opts...) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, params, &raw, opts...) return ssestream.NewStream[BetaManagedAgentsStreamSessionEventsUnion](ssestream.NewDecoder(raw), err) } @@ -120,15 +120,20 @@ type BetaManagedAgentsAgentCustomToolUseEvent struct { ProcessedAt time.Time `json:"processed_at" api:"required" format:"date-time"` // Any of "agent.custom_tool_use". Type BetaManagedAgentsAgentCustomToolUseEventType `json:"type" api:"required"` + // When set, this event was cross-posted from a subagent's thread to surface its + // custom tool use on the primary thread's stream. Empty on the thread's own + // events. Echo this on a `user.custom_tool_result` event to route the result back. + SessionThreadID string `json:"session_thread_id" api:"nullable"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { - ID respjson.Field - Input respjson.Field - Name respjson.Field - ProcessedAt respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string + ID respjson.Field + Input respjson.Field + Name respjson.Field + ProcessedAt respjson.Field + Type respjson.Field + SessionThreadID respjson.Field + ExtraFields map[string]respjson.Field + raw string } `json:"-"` } @@ -185,7 +190,8 @@ const ( // BetaManagedAgentsAgentMCPToolResultEventContentUnion contains all possible // properties and values from [BetaManagedAgentsTextBlock], -// [BetaManagedAgentsImageBlock], [BetaManagedAgentsDocumentBlock]. +// [BetaManagedAgentsImageBlock], [BetaManagedAgentsDocumentBlock], +// [BetaManagedAgentsSearchResultBlock]. // // Use the [BetaManagedAgentsAgentMCPToolResultEventContentUnion.AsAny] method to // switch on the variant. @@ -194,22 +200,27 @@ const ( type BetaManagedAgentsAgentMCPToolResultEventContentUnion struct { // This field is from variant [BetaManagedAgentsTextBlock]. Text string `json:"text"` - // Any of "text", "image", "document". + // Any of "text", "image", "document", "search_result". Type string `json:"type"` // This field is a union of [BetaManagedAgentsImageBlockSourceUnion], - // [BetaManagedAgentsDocumentBlockSourceUnion] + // [BetaManagedAgentsDocumentBlockSourceUnion], [string] Source BetaManagedAgentsAgentMCPToolResultEventContentUnionSource `json:"source"` // This field is from variant [BetaManagedAgentsDocumentBlock]. Context string `json:"context"` - // This field is from variant [BetaManagedAgentsDocumentBlock]. - Title string `json:"title"` - JSON struct { - Text respjson.Field - Type respjson.Field - Source respjson.Field - Context respjson.Field - Title respjson.Field - raw string + Title string `json:"title"` + // This field is from variant [BetaManagedAgentsSearchResultBlock]. + Citations BetaManagedAgentsSearchResultCitations `json:"citations"` + // This field is from variant [BetaManagedAgentsSearchResultBlock]. + Content []BetaManagedAgentsSearchResultContent `json:"content"` + JSON struct { + Text respjson.Field + Type respjson.Field + Source respjson.Field + Context respjson.Field + Title respjson.Field + Citations respjson.Field + Content respjson.Field + raw string } `json:"-"` } @@ -224,6 +235,8 @@ type anyBetaManagedAgentsAgentMCPToolResultEventContent interface { func (BetaManagedAgentsTextBlock) implBetaManagedAgentsAgentMCPToolResultEventContentUnion() {} func (BetaManagedAgentsImageBlock) implBetaManagedAgentsAgentMCPToolResultEventContentUnion() {} func (BetaManagedAgentsDocumentBlock) implBetaManagedAgentsAgentMCPToolResultEventContentUnion() {} +func (BetaManagedAgentsSearchResultBlock) implBetaManagedAgentsAgentMCPToolResultEventContentUnion() { +} // Use the following switch statement to find the correct variant // @@ -231,6 +244,7 @@ func (BetaManagedAgentsDocumentBlock) implBetaManagedAgentsAgentMCPToolResultEve // case anthropic.BetaManagedAgentsTextBlock: // case anthropic.BetaManagedAgentsImageBlock: // case anthropic.BetaManagedAgentsDocumentBlock: +// case anthropic.BetaManagedAgentsSearchResultBlock: // default: // fmt.Errorf("no variant present") // } @@ -242,6 +256,8 @@ func (u BetaManagedAgentsAgentMCPToolResultEventContentUnion) AsAny() anyBetaMan return u.AsImage() case "document": return u.AsDocument() + case "search_result": + return u.AsSearchResult() } return nil } @@ -261,6 +277,11 @@ func (u BetaManagedAgentsAgentMCPToolResultEventContentUnion) AsDocument() (v Be return } +func (u BetaManagedAgentsAgentMCPToolResultEventContentUnion) AsSearchResult() (v BetaManagedAgentsSearchResultBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + // Returns the unmodified JSON received from the API func (u BetaManagedAgentsAgentMCPToolResultEventContentUnion) RawJSON() string { return u.JSON.raw } @@ -275,13 +296,19 @@ func (r *BetaManagedAgentsAgentMCPToolResultEventContentUnion) UnmarshalJSON(dat // // For type safety it is recommended to directly use a variant of the // [BetaManagedAgentsAgentMCPToolResultEventContentUnion]. +// +// If the underlying value is not a json object, one of the following properties +// will be valid: OfString] type BetaManagedAgentsAgentMCPToolResultEventContentUnionSource struct { + // This field will be present if the value is a [string] instead of an object. + OfString string `json:",inline"` Data string `json:"data"` MediaType string `json:"media_type"` Type string `json:"type"` URL string `json:"url"` FileID string `json:"file_id"` JSON struct { + OfString respjson.Field Data respjson.Field MediaType respjson.Field Type respjson.Field @@ -313,6 +340,11 @@ type BetaManagedAgentsAgentMCPToolUseEvent struct { // // Any of "allow", "ask", "deny". EvaluatedPermission BetaManagedAgentsAgentMCPToolUseEventEvaluatedPermission `json:"evaluated_permission"` + // When set, this event was cross-posted from a subagent's thread to surface its + // permission request on the primary thread's stream. Empty on the thread's own + // events. Echo this on a `user.tool_confirmation` event to route the approval + // back. + SessionThreadID string `json:"session_thread_id" api:"nullable"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ID respjson.Field @@ -322,6 +354,7 @@ type BetaManagedAgentsAgentMCPToolUseEvent struct { ProcessedAt respjson.Field Type respjson.Field EvaluatedPermission respjson.Field + SessionThreadID respjson.Field ExtraFields map[string]respjson.Field raw string } `json:"-"` @@ -353,7 +386,7 @@ type BetaManagedAgentsAgentMessageEvent struct { // Unique identifier for this event. ID string `json:"id" api:"required"` // Array of text blocks comprising the agent response. - Content []BetaManagedAgentsTextBlock `json:"content" api:"required"` + Content []BetaManagedAgentsAgentMessageEventContentUnion `json:"content" api:"required"` // A timestamp in RFC 3339 format ProcessedAt time.Time `json:"processed_at" api:"required" format:"date-time"` // Any of "agent.message". @@ -375,6 +408,70 @@ func (r *BetaManagedAgentsAgentMessageEvent) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } +// BetaManagedAgentsAgentMessageEventContentUnion contains all possible properties +// and values from [BetaManagedAgentsTextBlock], [BetaManagedAgentsRedactedBlock]. +// +// Use the [BetaManagedAgentsAgentMessageEventContentUnion.AsAny] method to switch +// on the variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaManagedAgentsAgentMessageEventContentUnion struct { + // This field is from variant [BetaManagedAgentsTextBlock]. + Text string `json:"text"` + // Any of "text", "redacted". + Type string `json:"type"` + JSON struct { + Text respjson.Field + Type respjson.Field + raw string + } `json:"-"` +} + +// anyBetaManagedAgentsAgentMessageEventContent is implemented by each variant of +// [BetaManagedAgentsAgentMessageEventContentUnion] to add type safety for the +// return type of [BetaManagedAgentsAgentMessageEventContentUnion.AsAny] +type anyBetaManagedAgentsAgentMessageEventContent interface { + implBetaManagedAgentsAgentMessageEventContentUnion() +} + +func (BetaManagedAgentsTextBlock) implBetaManagedAgentsAgentMessageEventContentUnion() {} +func (BetaManagedAgentsRedactedBlock) implBetaManagedAgentsAgentMessageEventContentUnion() {} + +// Use the following switch statement to find the correct variant +// +// switch variant := BetaManagedAgentsAgentMessageEventContentUnion.AsAny().(type) { +// case anthropic.BetaManagedAgentsTextBlock: +// case anthropic.BetaManagedAgentsRedactedBlock: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaManagedAgentsAgentMessageEventContentUnion) AsAny() anyBetaManagedAgentsAgentMessageEventContent { + switch u.Type { + case "text": + return u.AsText() + case "redacted": + return u.AsRedacted() + } + return nil +} + +func (u BetaManagedAgentsAgentMessageEventContentUnion) AsText() (v BetaManagedAgentsTextBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsAgentMessageEventContentUnion) AsRedacted() (v BetaManagedAgentsRedactedBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u BetaManagedAgentsAgentMessageEventContentUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaManagedAgentsAgentMessageEventContentUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + type BetaManagedAgentsAgentMessageEventType string const ( @@ -442,61 +539,58 @@ const ( BetaManagedAgentsAgentThreadContextCompactedEventTypeAgentThreadContextCompacted BetaManagedAgentsAgentThreadContextCompactedEventType = "agent.thread_context_compacted" ) -// Event representing the result of an agent tool execution. -type BetaManagedAgentsAgentToolResultEvent struct { +// Delivery event written to the target thread's input stream when an +// agent-to-agent message arrives. +type BetaManagedAgentsAgentThreadMessageReceivedEvent struct { // Unique identifier for this event. ID string `json:"id" api:"required"` + // Message content blocks. + Content []BetaManagedAgentsAgentThreadMessageReceivedEventContentUnion `json:"content" api:"required"` + // Public `sthr_` ID of the thread that sent the message. + FromSessionThreadID string `json:"from_session_thread_id" api:"required"` // A timestamp in RFC 3339 format ProcessedAt time.Time `json:"processed_at" api:"required" format:"date-time"` - // The id of the `agent.tool_use` event this result corresponds to. - ToolUseID string `json:"tool_use_id" api:"required"` - // Any of "agent.tool_result". - Type BetaManagedAgentsAgentToolResultEventType `json:"type" api:"required"` - // The result content returned by the tool. - Content []BetaManagedAgentsAgentToolResultEventContentUnion `json:"content"` - // Whether the tool execution resulted in an error. - IsError bool `json:"is_error" api:"nullable"` + // Any of "agent.thread_message_received". + Type BetaManagedAgentsAgentThreadMessageReceivedEventType `json:"type" api:"required"` + // Name of the callable agent this message came from. Absent when received from the + // primary agent. + FromAgentName string `json:"from_agent_name" api:"nullable"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { - ID respjson.Field - ProcessedAt respjson.Field - ToolUseID respjson.Field - Type respjson.Field - Content respjson.Field - IsError respjson.Field - ExtraFields map[string]respjson.Field - raw string + ID respjson.Field + Content respjson.Field + FromSessionThreadID respjson.Field + ProcessedAt respjson.Field + Type respjson.Field + FromAgentName respjson.Field + ExtraFields map[string]respjson.Field + raw string } `json:"-"` } // Returns the unmodified JSON received from the API -func (r BetaManagedAgentsAgentToolResultEvent) RawJSON() string { return r.JSON.raw } -func (r *BetaManagedAgentsAgentToolResultEvent) UnmarshalJSON(data []byte) error { +func (r BetaManagedAgentsAgentThreadMessageReceivedEvent) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsAgentThreadMessageReceivedEvent) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type BetaManagedAgentsAgentToolResultEventType string - -const ( - BetaManagedAgentsAgentToolResultEventTypeAgentToolResult BetaManagedAgentsAgentToolResultEventType = "agent.tool_result" -) - -// BetaManagedAgentsAgentToolResultEventContentUnion contains all possible -// properties and values from [BetaManagedAgentsTextBlock], -// [BetaManagedAgentsImageBlock], [BetaManagedAgentsDocumentBlock]. +// BetaManagedAgentsAgentThreadMessageReceivedEventContentUnion contains all +// possible properties and values from [BetaManagedAgentsTextBlock], +// [BetaManagedAgentsImageBlock], [BetaManagedAgentsDocumentBlock], +// [BetaManagedAgentsRedactedBlock]. // -// Use the [BetaManagedAgentsAgentToolResultEventContentUnion.AsAny] method to -// switch on the variant. +// Use the [BetaManagedAgentsAgentThreadMessageReceivedEventContentUnion.AsAny] +// method to switch on the variant. // // Use the methods beginning with 'As' to cast the union to one of its variants. -type BetaManagedAgentsAgentToolResultEventContentUnion struct { +type BetaManagedAgentsAgentThreadMessageReceivedEventContentUnion struct { // This field is from variant [BetaManagedAgentsTextBlock]. Text string `json:"text"` - // Any of "text", "image", "document". + // Any of "text", "image", "document", "redacted". Type string `json:"type"` // This field is a union of [BetaManagedAgentsImageBlockSourceUnion], // [BetaManagedAgentsDocumentBlockSourceUnion] - Source BetaManagedAgentsAgentToolResultEventContentUnionSource `json:"source"` + Source BetaManagedAgentsAgentThreadMessageReceivedEventContentUnionSource `json:"source"` // This field is from variant [BetaManagedAgentsDocumentBlock]. Context string `json:"context"` // This field is from variant [BetaManagedAgentsDocumentBlock]. @@ -511,27 +605,34 @@ type BetaManagedAgentsAgentToolResultEventContentUnion struct { } `json:"-"` } -// anyBetaManagedAgentsAgentToolResultEventContent is implemented by each variant -// of [BetaManagedAgentsAgentToolResultEventContentUnion] to add type safety for -// the return type of [BetaManagedAgentsAgentToolResultEventContentUnion.AsAny] -type anyBetaManagedAgentsAgentToolResultEventContent interface { - implBetaManagedAgentsAgentToolResultEventContentUnion() +// anyBetaManagedAgentsAgentThreadMessageReceivedEventContent is implemented by +// each variant of [BetaManagedAgentsAgentThreadMessageReceivedEventContentUnion] +// to add type safety for the return type of +// [BetaManagedAgentsAgentThreadMessageReceivedEventContentUnion.AsAny] +type anyBetaManagedAgentsAgentThreadMessageReceivedEventContent interface { + implBetaManagedAgentsAgentThreadMessageReceivedEventContentUnion() } -func (BetaManagedAgentsTextBlock) implBetaManagedAgentsAgentToolResultEventContentUnion() {} -func (BetaManagedAgentsImageBlock) implBetaManagedAgentsAgentToolResultEventContentUnion() {} -func (BetaManagedAgentsDocumentBlock) implBetaManagedAgentsAgentToolResultEventContentUnion() {} +func (BetaManagedAgentsTextBlock) implBetaManagedAgentsAgentThreadMessageReceivedEventContentUnion() { +} +func (BetaManagedAgentsImageBlock) implBetaManagedAgentsAgentThreadMessageReceivedEventContentUnion() { +} +func (BetaManagedAgentsDocumentBlock) implBetaManagedAgentsAgentThreadMessageReceivedEventContentUnion() { +} +func (BetaManagedAgentsRedactedBlock) implBetaManagedAgentsAgentThreadMessageReceivedEventContentUnion() { +} // Use the following switch statement to find the correct variant // -// switch variant := BetaManagedAgentsAgentToolResultEventContentUnion.AsAny().(type) { +// switch variant := BetaManagedAgentsAgentThreadMessageReceivedEventContentUnion.AsAny().(type) { // case anthropic.BetaManagedAgentsTextBlock: // case anthropic.BetaManagedAgentsImageBlock: // case anthropic.BetaManagedAgentsDocumentBlock: +// case anthropic.BetaManagedAgentsRedactedBlock: // default: // fmt.Errorf("no variant present") // } -func (u BetaManagedAgentsAgentToolResultEventContentUnion) AsAny() anyBetaManagedAgentsAgentToolResultEventContent { +func (u BetaManagedAgentsAgentThreadMessageReceivedEventContentUnion) AsAny() anyBetaManagedAgentsAgentThreadMessageReceivedEventContent { switch u.Type { case "text": return u.AsText() @@ -539,40 +640,50 @@ func (u BetaManagedAgentsAgentToolResultEventContentUnion) AsAny() anyBetaManage return u.AsImage() case "document": return u.AsDocument() + case "redacted": + return u.AsRedacted() } return nil } -func (u BetaManagedAgentsAgentToolResultEventContentUnion) AsText() (v BetaManagedAgentsTextBlock) { +func (u BetaManagedAgentsAgentThreadMessageReceivedEventContentUnion) AsText() (v BetaManagedAgentsTextBlock) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return } -func (u BetaManagedAgentsAgentToolResultEventContentUnion) AsImage() (v BetaManagedAgentsImageBlock) { +func (u BetaManagedAgentsAgentThreadMessageReceivedEventContentUnion) AsImage() (v BetaManagedAgentsImageBlock) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return } -func (u BetaManagedAgentsAgentToolResultEventContentUnion) AsDocument() (v BetaManagedAgentsDocumentBlock) { +func (u BetaManagedAgentsAgentThreadMessageReceivedEventContentUnion) AsDocument() (v BetaManagedAgentsDocumentBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsAgentThreadMessageReceivedEventContentUnion) AsRedacted() (v BetaManagedAgentsRedactedBlock) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return } // Returns the unmodified JSON received from the API -func (u BetaManagedAgentsAgentToolResultEventContentUnion) RawJSON() string { return u.JSON.raw } +func (u BetaManagedAgentsAgentThreadMessageReceivedEventContentUnion) RawJSON() string { + return u.JSON.raw +} -func (r *BetaManagedAgentsAgentToolResultEventContentUnion) UnmarshalJSON(data []byte) error { +func (r *BetaManagedAgentsAgentThreadMessageReceivedEventContentUnion) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// BetaManagedAgentsAgentToolResultEventContentUnionSource is an implicit subunion -// of [BetaManagedAgentsAgentToolResultEventContentUnion]. -// BetaManagedAgentsAgentToolResultEventContentUnionSource provides convenient -// access to the sub-properties of the union. +// BetaManagedAgentsAgentThreadMessageReceivedEventContentUnionSource is an +// implicit subunion of +// [BetaManagedAgentsAgentThreadMessageReceivedEventContentUnion]. +// BetaManagedAgentsAgentThreadMessageReceivedEventContentUnionSource provides +// convenient access to the sub-properties of the union. // // For type safety it is recommended to directly use a variant of the -// [BetaManagedAgentsAgentToolResultEventContentUnion]. -type BetaManagedAgentsAgentToolResultEventContentUnionSource struct { +// [BetaManagedAgentsAgentThreadMessageReceivedEventContentUnion]. +type BetaManagedAgentsAgentThreadMessageReceivedEventContentUnionSource struct { Data string `json:"data"` MediaType string `json:"media_type"` Type string `json:"type"` @@ -588,98 +699,446 @@ type BetaManagedAgentsAgentToolResultEventContentUnionSource struct { } `json:"-"` } -func (r *BetaManagedAgentsAgentToolResultEventContentUnionSource) UnmarshalJSON(data []byte) error { +func (r *BetaManagedAgentsAgentThreadMessageReceivedEventContentUnionSource) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// Event emitted when the agent invokes a built-in agent tool. -type BetaManagedAgentsAgentToolUseEvent struct { +type BetaManagedAgentsAgentThreadMessageReceivedEventType string + +const ( + BetaManagedAgentsAgentThreadMessageReceivedEventTypeAgentThreadMessageReceived BetaManagedAgentsAgentThreadMessageReceivedEventType = "agent.thread_message_received" +) + +// Observability event emitted to the sender's output stream when an agent-to-agent +// message is sent. +type BetaManagedAgentsAgentThreadMessageSentEvent struct { // Unique identifier for this event. ID string `json:"id" api:"required"` - // Input parameters for the tool call. - Input map[string]any `json:"input" api:"required"` - // Name of the agent tool being used. - Name string `json:"name" api:"required"` + // Message content blocks. + Content []BetaManagedAgentsAgentThreadMessageSentEventContentUnion `json:"content" api:"required"` // A timestamp in RFC 3339 format ProcessedAt time.Time `json:"processed_at" api:"required" format:"date-time"` - // Any of "agent.tool_use". - Type BetaManagedAgentsAgentToolUseEventType `json:"type" api:"required"` - // AgentEvaluatedPermission enum - // - // Any of "allow", "ask", "deny". - EvaluatedPermission BetaManagedAgentsAgentToolUseEventEvaluatedPermission `json:"evaluated_permission"` + // Public `sthr_` ID of the thread the message was sent to. + ToSessionThreadID string `json:"to_session_thread_id" api:"required"` + // Any of "agent.thread_message_sent". + Type BetaManagedAgentsAgentThreadMessageSentEventType `json:"type" api:"required"` + // Name of the callable agent this message was sent to. Absent when sent to the + // primary agent. + ToAgentName string `json:"to_agent_name" api:"nullable"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { - ID respjson.Field - Input respjson.Field - Name respjson.Field - ProcessedAt respjson.Field - Type respjson.Field - EvaluatedPermission respjson.Field - ExtraFields map[string]respjson.Field - raw string + ID respjson.Field + Content respjson.Field + ProcessedAt respjson.Field + ToSessionThreadID respjson.Field + Type respjson.Field + ToAgentName respjson.Field + ExtraFields map[string]respjson.Field + raw string } `json:"-"` } // Returns the unmodified JSON received from the API -func (r BetaManagedAgentsAgentToolUseEvent) RawJSON() string { return r.JSON.raw } -func (r *BetaManagedAgentsAgentToolUseEvent) UnmarshalJSON(data []byte) error { +func (r BetaManagedAgentsAgentThreadMessageSentEvent) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsAgentThreadMessageSentEvent) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type BetaManagedAgentsAgentToolUseEventType string - -const ( - BetaManagedAgentsAgentToolUseEventTypeAgentToolUse BetaManagedAgentsAgentToolUseEventType = "agent.tool_use" -) - -// AgentEvaluatedPermission enum -type BetaManagedAgentsAgentToolUseEventEvaluatedPermission string - -const ( - BetaManagedAgentsAgentToolUseEventEvaluatedPermissionAllow BetaManagedAgentsAgentToolUseEventEvaluatedPermission = "allow" - BetaManagedAgentsAgentToolUseEventEvaluatedPermissionAsk BetaManagedAgentsAgentToolUseEventEvaluatedPermission = "ask" - BetaManagedAgentsAgentToolUseEventEvaluatedPermissionDeny BetaManagedAgentsAgentToolUseEventEvaluatedPermission = "deny" -) - -// Base64-encoded document data. -type BetaManagedAgentsBase64DocumentSource struct { - // Base64-encoded document data. - Data string `json:"data" api:"required"` - // MIME type of the document (e.g., "application/pdf"). - MediaType string `json:"media_type" api:"required"` - // Any of "base64". - Type BetaManagedAgentsBase64DocumentSourceType `json:"type" api:"required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Data respjson.Field - MediaType respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string +// BetaManagedAgentsAgentThreadMessageSentEventContentUnion contains all possible +// properties and values from [BetaManagedAgentsTextBlock], +// [BetaManagedAgentsImageBlock], [BetaManagedAgentsDocumentBlock], +// [BetaManagedAgentsRedactedBlock]. +// +// Use the [BetaManagedAgentsAgentThreadMessageSentEventContentUnion.AsAny] method +// to switch on the variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaManagedAgentsAgentThreadMessageSentEventContentUnion struct { + // This field is from variant [BetaManagedAgentsTextBlock]. + Text string `json:"text"` + // Any of "text", "image", "document", "redacted". + Type string `json:"type"` + // This field is a union of [BetaManagedAgentsImageBlockSourceUnion], + // [BetaManagedAgentsDocumentBlockSourceUnion] + Source BetaManagedAgentsAgentThreadMessageSentEventContentUnionSource `json:"source"` + // This field is from variant [BetaManagedAgentsDocumentBlock]. + Context string `json:"context"` + // This field is from variant [BetaManagedAgentsDocumentBlock]. + Title string `json:"title"` + JSON struct { + Text respjson.Field + Type respjson.Field + Source respjson.Field + Context respjson.Field + Title respjson.Field + raw string } `json:"-"` } -// Returns the unmodified JSON received from the API -func (r BetaManagedAgentsBase64DocumentSource) RawJSON() string { return r.JSON.raw } -func (r *BetaManagedAgentsBase64DocumentSource) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +// anyBetaManagedAgentsAgentThreadMessageSentEventContent is implemented by each +// variant of [BetaManagedAgentsAgentThreadMessageSentEventContentUnion] to add +// type safety for the return type of +// [BetaManagedAgentsAgentThreadMessageSentEventContentUnion.AsAny] +type anyBetaManagedAgentsAgentThreadMessageSentEventContent interface { + implBetaManagedAgentsAgentThreadMessageSentEventContentUnion() } -// ToParam converts this BetaManagedAgentsBase64DocumentSource to a -// BetaManagedAgentsBase64DocumentSourceParam. +func (BetaManagedAgentsTextBlock) implBetaManagedAgentsAgentThreadMessageSentEventContentUnion() {} +func (BetaManagedAgentsImageBlock) implBetaManagedAgentsAgentThreadMessageSentEventContentUnion() {} +func (BetaManagedAgentsDocumentBlock) implBetaManagedAgentsAgentThreadMessageSentEventContentUnion() { +} +func (BetaManagedAgentsRedactedBlock) implBetaManagedAgentsAgentThreadMessageSentEventContentUnion() { +} + +// Use the following switch statement to find the correct variant // -// Warning: the fields of the param type will not be present. ToParam should only -// be used at the last possible moment before sending a request. Test for this with -// BetaManagedAgentsBase64DocumentSourceParam.Overrides() -func (r BetaManagedAgentsBase64DocumentSource) ToParam() BetaManagedAgentsBase64DocumentSourceParam { - return param.Override[BetaManagedAgentsBase64DocumentSourceParam](json.RawMessage(r.RawJSON())) +// switch variant := BetaManagedAgentsAgentThreadMessageSentEventContentUnion.AsAny().(type) { +// case anthropic.BetaManagedAgentsTextBlock: +// case anthropic.BetaManagedAgentsImageBlock: +// case anthropic.BetaManagedAgentsDocumentBlock: +// case anthropic.BetaManagedAgentsRedactedBlock: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaManagedAgentsAgentThreadMessageSentEventContentUnion) AsAny() anyBetaManagedAgentsAgentThreadMessageSentEventContent { + switch u.Type { + case "text": + return u.AsText() + case "image": + return u.AsImage() + case "document": + return u.AsDocument() + case "redacted": + return u.AsRedacted() + } + return nil } -type BetaManagedAgentsBase64DocumentSourceType string +func (u BetaManagedAgentsAgentThreadMessageSentEventContentUnion) AsText() (v BetaManagedAgentsTextBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} -const ( - BetaManagedAgentsBase64DocumentSourceTypeBase64 BetaManagedAgentsBase64DocumentSourceType = "base64" +func (u BetaManagedAgentsAgentThreadMessageSentEventContentUnion) AsImage() (v BetaManagedAgentsImageBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsAgentThreadMessageSentEventContentUnion) AsDocument() (v BetaManagedAgentsDocumentBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsAgentThreadMessageSentEventContentUnion) AsRedacted() (v BetaManagedAgentsRedactedBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u BetaManagedAgentsAgentThreadMessageSentEventContentUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaManagedAgentsAgentThreadMessageSentEventContentUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaManagedAgentsAgentThreadMessageSentEventContentUnionSource is an implicit +// subunion of [BetaManagedAgentsAgentThreadMessageSentEventContentUnion]. +// BetaManagedAgentsAgentThreadMessageSentEventContentUnionSource provides +// convenient access to the sub-properties of the union. +// +// For type safety it is recommended to directly use a variant of the +// [BetaManagedAgentsAgentThreadMessageSentEventContentUnion]. +type BetaManagedAgentsAgentThreadMessageSentEventContentUnionSource struct { + Data string `json:"data"` + MediaType string `json:"media_type"` + Type string `json:"type"` + URL string `json:"url"` + FileID string `json:"file_id"` + JSON struct { + Data respjson.Field + MediaType respjson.Field + Type respjson.Field + URL respjson.Field + FileID respjson.Field + raw string + } `json:"-"` +} + +func (r *BetaManagedAgentsAgentThreadMessageSentEventContentUnionSource) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsAgentThreadMessageSentEventType string + +const ( + BetaManagedAgentsAgentThreadMessageSentEventTypeAgentThreadMessageSent BetaManagedAgentsAgentThreadMessageSentEventType = "agent.thread_message_sent" +) + +// Event representing the result of an agent tool execution. +type BetaManagedAgentsAgentToolResultEvent struct { + // Unique identifier for this event. + ID string `json:"id" api:"required"` + // A timestamp in RFC 3339 format + ProcessedAt time.Time `json:"processed_at" api:"required" format:"date-time"` + // The id of the `agent.tool_use` event this result corresponds to. + ToolUseID string `json:"tool_use_id" api:"required"` + // Any of "agent.tool_result". + Type BetaManagedAgentsAgentToolResultEventType `json:"type" api:"required"` + // The result content returned by the tool. + Content []BetaManagedAgentsAgentToolResultEventContentUnion `json:"content"` + // Whether the tool execution resulted in an error. + IsError bool `json:"is_error" api:"nullable"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + ProcessedAt respjson.Field + ToolUseID respjson.Field + Type respjson.Field + Content respjson.Field + IsError respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsAgentToolResultEvent) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsAgentToolResultEvent) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsAgentToolResultEventType string + +const ( + BetaManagedAgentsAgentToolResultEventTypeAgentToolResult BetaManagedAgentsAgentToolResultEventType = "agent.tool_result" +) + +// BetaManagedAgentsAgentToolResultEventContentUnion contains all possible +// properties and values from [BetaManagedAgentsTextBlock], +// [BetaManagedAgentsImageBlock], [BetaManagedAgentsDocumentBlock], +// [BetaManagedAgentsSearchResultBlock]. +// +// Use the [BetaManagedAgentsAgentToolResultEventContentUnion.AsAny] method to +// switch on the variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaManagedAgentsAgentToolResultEventContentUnion struct { + // This field is from variant [BetaManagedAgentsTextBlock]. + Text string `json:"text"` + // Any of "text", "image", "document", "search_result". + Type string `json:"type"` + // This field is a union of [BetaManagedAgentsImageBlockSourceUnion], + // [BetaManagedAgentsDocumentBlockSourceUnion], [string] + Source BetaManagedAgentsAgentToolResultEventContentUnionSource `json:"source"` + // This field is from variant [BetaManagedAgentsDocumentBlock]. + Context string `json:"context"` + Title string `json:"title"` + // This field is from variant [BetaManagedAgentsSearchResultBlock]. + Citations BetaManagedAgentsSearchResultCitations `json:"citations"` + // This field is from variant [BetaManagedAgentsSearchResultBlock]. + Content []BetaManagedAgentsSearchResultContent `json:"content"` + JSON struct { + Text respjson.Field + Type respjson.Field + Source respjson.Field + Context respjson.Field + Title respjson.Field + Citations respjson.Field + Content respjson.Field + raw string + } `json:"-"` +} + +// anyBetaManagedAgentsAgentToolResultEventContent is implemented by each variant +// of [BetaManagedAgentsAgentToolResultEventContentUnion] to add type safety for +// the return type of [BetaManagedAgentsAgentToolResultEventContentUnion.AsAny] +type anyBetaManagedAgentsAgentToolResultEventContent interface { + implBetaManagedAgentsAgentToolResultEventContentUnion() +} + +func (BetaManagedAgentsTextBlock) implBetaManagedAgentsAgentToolResultEventContentUnion() {} +func (BetaManagedAgentsImageBlock) implBetaManagedAgentsAgentToolResultEventContentUnion() {} +func (BetaManagedAgentsDocumentBlock) implBetaManagedAgentsAgentToolResultEventContentUnion() {} +func (BetaManagedAgentsSearchResultBlock) implBetaManagedAgentsAgentToolResultEventContentUnion() {} + +// Use the following switch statement to find the correct variant +// +// switch variant := BetaManagedAgentsAgentToolResultEventContentUnion.AsAny().(type) { +// case anthropic.BetaManagedAgentsTextBlock: +// case anthropic.BetaManagedAgentsImageBlock: +// case anthropic.BetaManagedAgentsDocumentBlock: +// case anthropic.BetaManagedAgentsSearchResultBlock: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaManagedAgentsAgentToolResultEventContentUnion) AsAny() anyBetaManagedAgentsAgentToolResultEventContent { + switch u.Type { + case "text": + return u.AsText() + case "image": + return u.AsImage() + case "document": + return u.AsDocument() + case "search_result": + return u.AsSearchResult() + } + return nil +} + +func (u BetaManagedAgentsAgentToolResultEventContentUnion) AsText() (v BetaManagedAgentsTextBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsAgentToolResultEventContentUnion) AsImage() (v BetaManagedAgentsImageBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsAgentToolResultEventContentUnion) AsDocument() (v BetaManagedAgentsDocumentBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsAgentToolResultEventContentUnion) AsSearchResult() (v BetaManagedAgentsSearchResultBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u BetaManagedAgentsAgentToolResultEventContentUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaManagedAgentsAgentToolResultEventContentUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaManagedAgentsAgentToolResultEventContentUnionSource is an implicit subunion +// of [BetaManagedAgentsAgentToolResultEventContentUnion]. +// BetaManagedAgentsAgentToolResultEventContentUnionSource provides convenient +// access to the sub-properties of the union. +// +// For type safety it is recommended to directly use a variant of the +// [BetaManagedAgentsAgentToolResultEventContentUnion]. +// +// If the underlying value is not a json object, one of the following properties +// will be valid: OfString] +type BetaManagedAgentsAgentToolResultEventContentUnionSource struct { + // This field will be present if the value is a [string] instead of an object. + OfString string `json:",inline"` + Data string `json:"data"` + MediaType string `json:"media_type"` + Type string `json:"type"` + URL string `json:"url"` + FileID string `json:"file_id"` + JSON struct { + OfString respjson.Field + Data respjson.Field + MediaType respjson.Field + Type respjson.Field + URL respjson.Field + FileID respjson.Field + raw string + } `json:"-"` +} + +func (r *BetaManagedAgentsAgentToolResultEventContentUnionSource) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Event emitted when the agent invokes a built-in agent tool. +type BetaManagedAgentsAgentToolUseEvent struct { + // Unique identifier for this event. + ID string `json:"id" api:"required"` + // Input parameters for the tool call. + Input map[string]any `json:"input" api:"required"` + // Name of the agent tool being used. + Name string `json:"name" api:"required"` + // A timestamp in RFC 3339 format + ProcessedAt time.Time `json:"processed_at" api:"required" format:"date-time"` + // Any of "agent.tool_use". + Type BetaManagedAgentsAgentToolUseEventType `json:"type" api:"required"` + // AgentEvaluatedPermission enum + // + // Any of "allow", "ask", "deny". + EvaluatedPermission BetaManagedAgentsAgentToolUseEventEvaluatedPermission `json:"evaluated_permission"` + // When set, this event was cross-posted from a subagent's thread to surface its + // permission request on the primary thread's stream. Empty on the thread's own + // events. Echo this on a `user.tool_confirmation` event to route the approval + // back. + SessionThreadID string `json:"session_thread_id" api:"nullable"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + Input respjson.Field + Name respjson.Field + ProcessedAt respjson.Field + Type respjson.Field + EvaluatedPermission respjson.Field + SessionThreadID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsAgentToolUseEvent) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsAgentToolUseEvent) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsAgentToolUseEventType string + +const ( + BetaManagedAgentsAgentToolUseEventTypeAgentToolUse BetaManagedAgentsAgentToolUseEventType = "agent.tool_use" +) + +// AgentEvaluatedPermission enum +type BetaManagedAgentsAgentToolUseEventEvaluatedPermission string + +const ( + BetaManagedAgentsAgentToolUseEventEvaluatedPermissionAllow BetaManagedAgentsAgentToolUseEventEvaluatedPermission = "allow" + BetaManagedAgentsAgentToolUseEventEvaluatedPermissionAsk BetaManagedAgentsAgentToolUseEventEvaluatedPermission = "ask" + BetaManagedAgentsAgentToolUseEventEvaluatedPermissionDeny BetaManagedAgentsAgentToolUseEventEvaluatedPermission = "deny" +) + +// Base64-encoded document data. +type BetaManagedAgentsBase64DocumentSource struct { + // Base64-encoded document data. + Data string `json:"data" api:"required"` + // MIME type of the document (e.g., "application/pdf"). + MediaType string `json:"media_type" api:"required"` + // Any of "base64". + Type BetaManagedAgentsBase64DocumentSourceType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Data respjson.Field + MediaType respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsBase64DocumentSource) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsBase64DocumentSource) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// ToParam converts this BetaManagedAgentsBase64DocumentSource to a +// BetaManagedAgentsBase64DocumentSourceParam. +// +// Warning: the fields of the param type will not be present. ToParam should only +// be used at the last possible moment before sending a request. Test for this with +// BetaManagedAgentsBase64DocumentSourceParam.Overrides() +func (r BetaManagedAgentsBase64DocumentSource) ToParam() BetaManagedAgentsBase64DocumentSourceParam { + return param.Override[BetaManagedAgentsBase64DocumentSourceParam](json.RawMessage(r.RawJSON())) +} + +type BetaManagedAgentsBase64DocumentSourceType string + +const ( + BetaManagedAgentsBase64DocumentSourceTypeBase64 BetaManagedAgentsBase64DocumentSourceType = "base64" ) // Base64-encoded document data. @@ -758,49 +1217,157 @@ type BetaManagedAgentsBase64ImageSourceParam struct { paramObj } -func (r BetaManagedAgentsBase64ImageSourceParam) MarshalJSON() (data []byte, err error) { - type shadow BetaManagedAgentsBase64ImageSourceParam - return param.MarshalObject(r, (*shadow)(&r)) +func (r BetaManagedAgentsBase64ImageSourceParam) MarshalJSON() (data []byte, err error) { + type shadow BetaManagedAgentsBase64ImageSourceParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaManagedAgentsBase64ImageSourceParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The caller's organization or workspace cannot make model requests — out of +// credits or spend limit reached. Retrying with the same credentials will not +// succeed; the caller must resolve the billing state. +type BetaManagedAgentsBillingError struct { + // Human-readable error description. + Message string `json:"message" api:"required"` + // What the client should do next in response to this error. + RetryStatus BetaManagedAgentsBillingErrorRetryStatusUnion `json:"retry_status" api:"required"` + // Any of "billing_error". + Type BetaManagedAgentsBillingErrorType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Message respjson.Field + RetryStatus respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsBillingError) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsBillingError) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaManagedAgentsBillingErrorRetryStatusUnion contains all possible properties +// and values from [BetaManagedAgentsRetryStatusRetrying], +// [BetaManagedAgentsRetryStatusExhausted], [BetaManagedAgentsRetryStatusTerminal]. +// +// Use the [BetaManagedAgentsBillingErrorRetryStatusUnion.AsAny] method to switch +// on the variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaManagedAgentsBillingErrorRetryStatusUnion struct { + // Any of "retrying", "exhausted", "terminal". + Type string `json:"type"` + JSON struct { + Type respjson.Field + raw string + } `json:"-"` +} + +// anyBetaManagedAgentsBillingErrorRetryStatus is implemented by each variant of +// [BetaManagedAgentsBillingErrorRetryStatusUnion] to add type safety for the +// return type of [BetaManagedAgentsBillingErrorRetryStatusUnion.AsAny] +type anyBetaManagedAgentsBillingErrorRetryStatus interface { + implBetaManagedAgentsBillingErrorRetryStatusUnion() +} + +func (BetaManagedAgentsRetryStatusRetrying) implBetaManagedAgentsBillingErrorRetryStatusUnion() {} +func (BetaManagedAgentsRetryStatusExhausted) implBetaManagedAgentsBillingErrorRetryStatusUnion() {} +func (BetaManagedAgentsRetryStatusTerminal) implBetaManagedAgentsBillingErrorRetryStatusUnion() {} + +// Use the following switch statement to find the correct variant +// +// switch variant := BetaManagedAgentsBillingErrorRetryStatusUnion.AsAny().(type) { +// case anthropic.BetaManagedAgentsRetryStatusRetrying: +// case anthropic.BetaManagedAgentsRetryStatusExhausted: +// case anthropic.BetaManagedAgentsRetryStatusTerminal: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaManagedAgentsBillingErrorRetryStatusUnion) AsAny() anyBetaManagedAgentsBillingErrorRetryStatus { + switch u.Type { + case "retrying": + return u.AsRetrying() + case "exhausted": + return u.AsExhausted() + case "terminal": + return u.AsTerminal() + } + return nil +} + +func (u BetaManagedAgentsBillingErrorRetryStatusUnion) AsRetrying() (v BetaManagedAgentsRetryStatusRetrying) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -func (r *BetaManagedAgentsBase64ImageSourceParam) UnmarshalJSON(data []byte) error { + +func (u BetaManagedAgentsBillingErrorRetryStatusUnion) AsExhausted() (v BetaManagedAgentsRetryStatusExhausted) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsBillingErrorRetryStatusUnion) AsTerminal() (v BetaManagedAgentsRetryStatusTerminal) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u BetaManagedAgentsBillingErrorRetryStatusUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaManagedAgentsBillingErrorRetryStatusUnion) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The caller's organization or workspace cannot make model requests — out of -// credits or spend limit reached. Retrying with the same credentials will not -// succeed; the caller must resolve the billing state. -type BetaManagedAgentsBillingError struct { +type BetaManagedAgentsBillingErrorType string + +const ( + BetaManagedAgentsBillingErrorTypeBillingError BetaManagedAgentsBillingErrorType = "billing_error" +) + +// An `environment_variable` credential's `auth.networking.allowed_hosts` includes +// a host the environment's network policy does not permit. +type BetaManagedAgentsCredentialHostUnreachableError struct { + // ID of the affected credential. + CredentialID string `json:"credential_id" api:"required"` // Human-readable error description. Message string `json:"message" api:"required"` // What the client should do next in response to this error. - RetryStatus BetaManagedAgentsBillingErrorRetryStatusUnion `json:"retry_status" api:"required"` - // Any of "billing_error". - Type BetaManagedAgentsBillingErrorType `json:"type" api:"required"` + RetryStatus BetaManagedAgentsCredentialHostUnreachableErrorRetryStatusUnion `json:"retry_status" api:"required"` + // Any of "credential_host_unreachable_error". + Type BetaManagedAgentsCredentialHostUnreachableErrorType `json:"type" api:"required"` + // ID of the vault containing the affected credential. + VaultID string `json:"vault_id" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { - Message respjson.Field - RetryStatus respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string + CredentialID respjson.Field + Message respjson.Field + RetryStatus respjson.Field + Type respjson.Field + VaultID respjson.Field + ExtraFields map[string]respjson.Field + raw string } `json:"-"` } // Returns the unmodified JSON received from the API -func (r BetaManagedAgentsBillingError) RawJSON() string { return r.JSON.raw } -func (r *BetaManagedAgentsBillingError) UnmarshalJSON(data []byte) error { +func (r BetaManagedAgentsCredentialHostUnreachableError) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsCredentialHostUnreachableError) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// BetaManagedAgentsBillingErrorRetryStatusUnion contains all possible properties -// and values from [BetaManagedAgentsRetryStatusRetrying], +// BetaManagedAgentsCredentialHostUnreachableErrorRetryStatusUnion contains all +// possible properties and values from [BetaManagedAgentsRetryStatusRetrying], // [BetaManagedAgentsRetryStatusExhausted], [BetaManagedAgentsRetryStatusTerminal]. // -// Use the [BetaManagedAgentsBillingErrorRetryStatusUnion.AsAny] method to switch -// on the variant. +// Use the [BetaManagedAgentsCredentialHostUnreachableErrorRetryStatusUnion.AsAny] +// method to switch on the variant. // // Use the methods beginning with 'As' to cast the union to one of its variants. -type BetaManagedAgentsBillingErrorRetryStatusUnion struct { +type BetaManagedAgentsCredentialHostUnreachableErrorRetryStatusUnion struct { // Any of "retrying", "exhausted", "terminal". Type string `json:"type"` JSON struct { @@ -809,27 +1376,32 @@ type BetaManagedAgentsBillingErrorRetryStatusUnion struct { } `json:"-"` } -// anyBetaManagedAgentsBillingErrorRetryStatus is implemented by each variant of -// [BetaManagedAgentsBillingErrorRetryStatusUnion] to add type safety for the -// return type of [BetaManagedAgentsBillingErrorRetryStatusUnion.AsAny] -type anyBetaManagedAgentsBillingErrorRetryStatus interface { - implBetaManagedAgentsBillingErrorRetryStatusUnion() +// anyBetaManagedAgentsCredentialHostUnreachableErrorRetryStatus is implemented by +// each variant of +// [BetaManagedAgentsCredentialHostUnreachableErrorRetryStatusUnion] to add type +// safety for the return type of +// [BetaManagedAgentsCredentialHostUnreachableErrorRetryStatusUnion.AsAny] +type anyBetaManagedAgentsCredentialHostUnreachableErrorRetryStatus interface { + implBetaManagedAgentsCredentialHostUnreachableErrorRetryStatusUnion() } -func (BetaManagedAgentsRetryStatusRetrying) implBetaManagedAgentsBillingErrorRetryStatusUnion() {} -func (BetaManagedAgentsRetryStatusExhausted) implBetaManagedAgentsBillingErrorRetryStatusUnion() {} -func (BetaManagedAgentsRetryStatusTerminal) implBetaManagedAgentsBillingErrorRetryStatusUnion() {} +func (BetaManagedAgentsRetryStatusRetrying) implBetaManagedAgentsCredentialHostUnreachableErrorRetryStatusUnion() { +} +func (BetaManagedAgentsRetryStatusExhausted) implBetaManagedAgentsCredentialHostUnreachableErrorRetryStatusUnion() { +} +func (BetaManagedAgentsRetryStatusTerminal) implBetaManagedAgentsCredentialHostUnreachableErrorRetryStatusUnion() { +} // Use the following switch statement to find the correct variant // -// switch variant := BetaManagedAgentsBillingErrorRetryStatusUnion.AsAny().(type) { +// switch variant := BetaManagedAgentsCredentialHostUnreachableErrorRetryStatusUnion.AsAny().(type) { // case anthropic.BetaManagedAgentsRetryStatusRetrying: // case anthropic.BetaManagedAgentsRetryStatusExhausted: // case anthropic.BetaManagedAgentsRetryStatusTerminal: // default: // fmt.Errorf("no variant present") // } -func (u BetaManagedAgentsBillingErrorRetryStatusUnion) AsAny() anyBetaManagedAgentsBillingErrorRetryStatus { +func (u BetaManagedAgentsCredentialHostUnreachableErrorRetryStatusUnion) AsAny() anyBetaManagedAgentsCredentialHostUnreachableErrorRetryStatus { switch u.Type { case "retrying": return u.AsRetrying() @@ -841,32 +1413,34 @@ func (u BetaManagedAgentsBillingErrorRetryStatusUnion) AsAny() anyBetaManagedAge return nil } -func (u BetaManagedAgentsBillingErrorRetryStatusUnion) AsRetrying() (v BetaManagedAgentsRetryStatusRetrying) { +func (u BetaManagedAgentsCredentialHostUnreachableErrorRetryStatusUnion) AsRetrying() (v BetaManagedAgentsRetryStatusRetrying) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return } -func (u BetaManagedAgentsBillingErrorRetryStatusUnion) AsExhausted() (v BetaManagedAgentsRetryStatusExhausted) { +func (u BetaManagedAgentsCredentialHostUnreachableErrorRetryStatusUnion) AsExhausted() (v BetaManagedAgentsRetryStatusExhausted) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return } -func (u BetaManagedAgentsBillingErrorRetryStatusUnion) AsTerminal() (v BetaManagedAgentsRetryStatusTerminal) { +func (u BetaManagedAgentsCredentialHostUnreachableErrorRetryStatusUnion) AsTerminal() (v BetaManagedAgentsRetryStatusTerminal) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return } // Returns the unmodified JSON received from the API -func (u BetaManagedAgentsBillingErrorRetryStatusUnion) RawJSON() string { return u.JSON.raw } +func (u BetaManagedAgentsCredentialHostUnreachableErrorRetryStatusUnion) RawJSON() string { + return u.JSON.raw +} -func (r *BetaManagedAgentsBillingErrorRetryStatusUnion) UnmarshalJSON(data []byte) error { +func (r *BetaManagedAgentsCredentialHostUnreachableErrorRetryStatusUnion) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type BetaManagedAgentsBillingErrorType string +type BetaManagedAgentsCredentialHostUnreachableErrorType string const ( - BetaManagedAgentsBillingErrorTypeBillingError BetaManagedAgentsBillingErrorType = "billing_error" + BetaManagedAgentsCredentialHostUnreachableErrorTypeCredentialHostUnreachableError BetaManagedAgentsCredentialHostUnreachableErrorType = "credential_host_unreachable_error" ) // Document content, either specified directly as base64 data, as text, or as a @@ -1145,6 +1719,33 @@ func BetaManagedAgentsEventParamsOfUserCustomToolResult(customToolUseID string) return BetaManagedAgentsEventParamsUnion{OfUserCustomToolResult: &userCustomToolResult} } +func BetaManagedAgentsEventParamsOfUserDefineOutcome[ + T BetaManagedAgentsFileRubricParams | BetaManagedAgentsTextRubricParams, +](description string, rubric T, type_ BetaManagedAgentsUserDefineOutcomeEventParamsType) BetaManagedAgentsEventParamsUnion { + var userDefineOutcome BetaManagedAgentsUserDefineOutcomeEventParams + userDefineOutcome.Description = description + switch v := any(rubric).(type) { + case BetaManagedAgentsFileRubricParams: + userDefineOutcome.Rubric.OfFile = &v + case BetaManagedAgentsTextRubricParams: + userDefineOutcome.Rubric.OfText = &v + } + userDefineOutcome.Type = type_ + return BetaManagedAgentsEventParamsUnion{OfUserDefineOutcome: &userDefineOutcome} +} + +func BetaManagedAgentsEventParamsOfUserToolResult(toolUseID string) BetaManagedAgentsEventParamsUnion { + var userToolResult BetaManagedAgentsUserToolResultEventParams + userToolResult.ToolUseID = toolUseID + return BetaManagedAgentsEventParamsUnion{OfUserToolResult: &userToolResult} +} + +func BetaManagedAgentsEventParamsOfSystemMessage(content []BetaManagedAgentsSystemContentBlockParam) BetaManagedAgentsEventParamsUnion { + var systemMessage BetaManagedAgentsSystemMessageEventParams + systemMessage.Content = content + return BetaManagedAgentsEventParamsUnion{OfSystemMessage: &systemMessage} +} + // Only one field can be non-zero. // // Use [param.IsOmitted] to confirm if a field is set. @@ -1153,11 +1754,20 @@ type BetaManagedAgentsEventParamsUnion struct { OfUserInterrupt *BetaManagedAgentsUserInterruptEventParams `json:",omitzero,inline"` OfUserToolConfirmation *BetaManagedAgentsUserToolConfirmationEventParams `json:",omitzero,inline"` OfUserCustomToolResult *BetaManagedAgentsUserCustomToolResultEventParams `json:",omitzero,inline"` + OfUserDefineOutcome *BetaManagedAgentsUserDefineOutcomeEventParams `json:",omitzero,inline"` + OfUserToolResult *BetaManagedAgentsUserToolResultEventParams `json:",omitzero,inline"` + OfSystemMessage *BetaManagedAgentsSystemMessageEventParams `json:",omitzero,inline"` paramUnion } func (u BetaManagedAgentsEventParamsUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfUserMessage, u.OfUserInterrupt, u.OfUserToolConfirmation, u.OfUserCustomToolResult) + return param.MarshalUnion(u, u.OfUserMessage, + u.OfUserInterrupt, + u.OfUserToolConfirmation, + u.OfUserCustomToolResult, + u.OfUserDefineOutcome, + u.OfUserToolResult, + u.OfSystemMessage) } func (u *BetaManagedAgentsEventParamsUnion) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, u) @@ -1172,22 +1782,28 @@ func (u *BetaManagedAgentsEventParamsUnion) asAny() any { return u.OfUserToolConfirmation } else if !param.IsOmitted(u.OfUserCustomToolResult) { return u.OfUserCustomToolResult + } else if !param.IsOmitted(u.OfUserDefineOutcome) { + return u.OfUserDefineOutcome + } else if !param.IsOmitted(u.OfUserToolResult) { + return u.OfUserToolResult + } else if !param.IsOmitted(u.OfSystemMessage) { + return u.OfSystemMessage } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u BetaManagedAgentsEventParamsUnion) GetResult() *string { - if vt := u.OfUserToolConfirmation; vt != nil { - return (*string)(&vt.Result) +func (u BetaManagedAgentsEventParamsUnion) GetSessionThreadID() *string { + if vt := u.OfUserInterrupt; vt != nil && vt.SessionThreadID.Valid() { + return &vt.SessionThreadID.Value } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u BetaManagedAgentsEventParamsUnion) GetToolUseID() *string { +func (u BetaManagedAgentsEventParamsUnion) GetResult() *string { if vt := u.OfUserToolConfirmation; vt != nil { - return &vt.ToolUseID + return (*string)(&vt.Result) } return nil } @@ -1209,9 +1825,25 @@ func (u BetaManagedAgentsEventParamsUnion) GetCustomToolUseID() *string { } // Returns a pointer to the underlying variant's property, if present. -func (u BetaManagedAgentsEventParamsUnion) GetIsError() *bool { - if vt := u.OfUserCustomToolResult; vt != nil && vt.IsError.Valid() { - return &vt.IsError.Value +func (u BetaManagedAgentsEventParamsUnion) GetDescription() *string { + if vt := u.OfUserDefineOutcome; vt != nil { + return &vt.Description + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaManagedAgentsEventParamsUnion) GetRubric() *BetaManagedAgentsUserDefineOutcomeEventParamsRubricUnion { + if vt := u.OfUserDefineOutcome; vt != nil { + return &vt.Rubric + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaManagedAgentsEventParamsUnion) GetMaxIterations() *int64 { + if vt := u.OfUserDefineOutcome; vt != nil && vt.MaxIterations.Valid() { + return &vt.MaxIterations.Value } return nil } @@ -1226,6 +1858,32 @@ func (u BetaManagedAgentsEventParamsUnion) GetType() *string { return (*string)(&vt.Type) } else if vt := u.OfUserCustomToolResult; vt != nil { return (*string)(&vt.Type) + } else if vt := u.OfUserDefineOutcome; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfUserToolResult; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfSystemMessage; vt != nil { + return (*string)(&vt.Type) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaManagedAgentsEventParamsUnion) GetToolUseID() *string { + if vt := u.OfUserToolConfirmation; vt != nil { + return (*string)(&vt.ToolUseID) + } else if vt := u.OfUserToolResult; vt != nil { + return (*string)(&vt.ToolUseID) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaManagedAgentsEventParamsUnion) GetIsError() *bool { + if vt := u.OfUserCustomToolResult; vt != nil && vt.IsError.Valid() { + return &vt.IsError.Value + } else if vt := u.OfUserToolResult; vt != nil && vt.IsError.Valid() { + return &vt.IsError.Value } return nil } @@ -1238,13 +1896,19 @@ func (u BetaManagedAgentsEventParamsUnion) GetContent() (res betaManagedAgentsEv res.any = &vt.Content } else if vt := u.OfUserCustomToolResult; vt != nil { res.any = &vt.Content + } else if vt := u.OfUserToolResult; vt != nil { + res.any = &vt.Content + } else if vt := u.OfSystemMessage; vt != nil { + res.any = &vt.Content } return } // Can have the runtime types // [_[]BetaManagedAgentsUserMessageEventParamsContentUnion], -// [_[]BetaManagedAgentsUserCustomToolResultEventParamsContentUnion] +// [_[]BetaManagedAgentsUserCustomToolResultEventParamsContentUnion], +// [_[]BetaManagedAgentsUserToolResultEventParamsContentUnion], +// [_[]BetaManagedAgentsSystemContentBlockParam] type betaManagedAgentsEventParamsUnionContent struct{ any } // Use the following switch statement to get the type of the union: @@ -1252,6 +1916,8 @@ type betaManagedAgentsEventParamsUnionContent struct{ any } // switch u.AsAny().(type) { // case *[]anthropic.BetaManagedAgentsUserMessageEventParamsContentUnion: // case *[]anthropic.BetaManagedAgentsUserCustomToolResultEventParamsContentUnion: +// case *[]anthropic.BetaManagedAgentsUserToolResultEventParamsContentUnion: +// case *[]anthropic.BetaManagedAgentsSystemContentBlockParam: // default: // fmt.Errorf("not present") // } @@ -1264,6 +1930,9 @@ func init() { apijson.Discriminator[BetaManagedAgentsUserInterruptEventParams]("user.interrupt"), apijson.Discriminator[BetaManagedAgentsUserToolConfirmationEventParams]("user.tool_confirmation"), apijson.Discriminator[BetaManagedAgentsUserCustomToolResultEventParams]("user.custom_tool_result"), + apijson.Discriminator[BetaManagedAgentsUserDefineOutcomeEventParams]("user.define_outcome"), + apijson.Discriminator[BetaManagedAgentsUserToolResultEventParams]("user.tool_result"), + apijson.Discriminator[BetaManagedAgentsSystemMessageEventParams]("system.message"), ) } @@ -1379,6 +2048,58 @@ func (r *BetaManagedAgentsFileImageSourceParam) UnmarshalJSON(data []byte) error return apijson.UnmarshalRoot(data, r) } +// Rubric referenced by a file uploaded via the Files API. +type BetaManagedAgentsFileRubric struct { + // ID of the rubric file. + FileID string `json:"file_id" api:"required"` + // Any of "file". + Type BetaManagedAgentsFileRubricType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + FileID respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsFileRubric) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsFileRubric) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsFileRubricType string + +const ( + BetaManagedAgentsFileRubricTypeFile BetaManagedAgentsFileRubricType = "file" +) + +// Rubric referenced by a file uploaded via the Files API. +// +// The properties FileID, Type are required. +type BetaManagedAgentsFileRubricParams struct { + // ID of the rubric file. + FileID string `json:"file_id" api:"required"` + // Any of "file". + Type BetaManagedAgentsFileRubricParamsType `json:"type,omitzero" api:"required"` + paramObj +} + +func (r BetaManagedAgentsFileRubricParams) MarshalJSON() (data []byte, err error) { + type shadow BetaManagedAgentsFileRubricParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaManagedAgentsFileRubricParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsFileRubricParamsType string + +const ( + BetaManagedAgentsFileRubricParamsTypeFile BetaManagedAgentsFileRubricParamsType = "file" +) + // Image content specified directly as base64 data or as a reference via a URL. type BetaManagedAgentsImageBlock struct { // Union type for image source variants. @@ -2207,6 +2928,57 @@ func (r *BetaManagedAgentsPlainTextDocumentSourceParam) UnmarshalJSON(data []byt return apijson.UnmarshalRoot(data, r) } +// Placeholder for content withheld by Anthropic model policy. +type BetaManagedAgentsRedactedBlock struct { + // Any of "redacted". + Type BetaManagedAgentsRedactedBlockType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsRedactedBlock) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsRedactedBlock) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// ToParam converts this BetaManagedAgentsRedactedBlock to a +// BetaManagedAgentsRedactedBlockParam. +// +// Warning: the fields of the param type will not be present. ToParam should only +// be used at the last possible moment before sending a request. Test for this with +// BetaManagedAgentsRedactedBlockParam.Overrides() +func (r BetaManagedAgentsRedactedBlock) ToParam() BetaManagedAgentsRedactedBlockParam { + return param.Override[BetaManagedAgentsRedactedBlockParam](json.RawMessage(r.RawJSON())) +} + +type BetaManagedAgentsRedactedBlockType string + +const ( + BetaManagedAgentsRedactedBlockTypeRedacted BetaManagedAgentsRedactedBlockType = "redacted" +) + +// Placeholder for content withheld by Anthropic model policy. +// +// The property Type is required. +type BetaManagedAgentsRedactedBlockParam struct { + // Any of "redacted". + Type BetaManagedAgentsRedactedBlockType `json:"type,omitzero" api:"required"` + paramObj +} + +func (r BetaManagedAgentsRedactedBlockParam) MarshalJSON() (data []byte, err error) { + type shadow BetaManagedAgentsRedactedBlockParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaManagedAgentsRedactedBlockParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + // This turn is dead; queued inputs are flushed and the session returns to idle. // Client may send a new prompt. type BetaManagedAgentsRetryStatusExhausted struct { @@ -2221,50 +2993,193 @@ type BetaManagedAgentsRetryStatusExhausted struct { } // Returns the unmodified JSON received from the API -func (r BetaManagedAgentsRetryStatusExhausted) RawJSON() string { return r.JSON.raw } -func (r *BetaManagedAgentsRetryStatusExhausted) UnmarshalJSON(data []byte) error { +func (r BetaManagedAgentsRetryStatusExhausted) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsRetryStatusExhausted) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsRetryStatusExhaustedType string + +const ( + BetaManagedAgentsRetryStatusExhaustedTypeExhausted BetaManagedAgentsRetryStatusExhaustedType = "exhausted" +) + +// The server is retrying automatically. Client should wait; the same error type +// may fire again as retrying, then once as exhausted when the retry budget runs +// out. +type BetaManagedAgentsRetryStatusRetrying struct { + // Any of "retrying". + Type BetaManagedAgentsRetryStatusRetryingType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsRetryStatusRetrying) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsRetryStatusRetrying) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsRetryStatusRetryingType string + +const ( + BetaManagedAgentsRetryStatusRetryingTypeRetrying BetaManagedAgentsRetryStatusRetryingType = "retrying" +) + +// The session encountered a terminal error and will transition to `terminated` +// state. +type BetaManagedAgentsRetryStatusTerminal struct { + // Any of "terminal". + Type BetaManagedAgentsRetryStatusTerminalType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsRetryStatusTerminal) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsRetryStatusTerminal) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsRetryStatusTerminalType string + +const ( + BetaManagedAgentsRetryStatusTerminalTypeTerminal BetaManagedAgentsRetryStatusTerminalType = "terminal" +) + +// A block containing a web search result. +type BetaManagedAgentsSearchResultBlock struct { + // Citation settings for a search result. + Citations BetaManagedAgentsSearchResultCitations `json:"citations" api:"required"` + // Array of text content blocks from the search result. + Content []BetaManagedAgentsSearchResultContent `json:"content" api:"required"` + // The URL source of the search result. + Source string `json:"source" api:"required"` + // The title of the search result. + Title string `json:"title" api:"required"` + // Any of "search_result". + Type BetaManagedAgentsSearchResultBlockType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Citations respjson.Field + Content respjson.Field + Source respjson.Field + Title respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsSearchResultBlock) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsSearchResultBlock) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type BetaManagedAgentsRetryStatusExhaustedType string +// ToParam converts this BetaManagedAgentsSearchResultBlock to a +// BetaManagedAgentsSearchResultBlockParam. +// +// Warning: the fields of the param type will not be present. ToParam should only +// be used at the last possible moment before sending a request. Test for this with +// BetaManagedAgentsSearchResultBlockParam.Overrides() +func (r BetaManagedAgentsSearchResultBlock) ToParam() BetaManagedAgentsSearchResultBlockParam { + return param.Override[BetaManagedAgentsSearchResultBlockParam](json.RawMessage(r.RawJSON())) +} + +type BetaManagedAgentsSearchResultBlockType string const ( - BetaManagedAgentsRetryStatusExhaustedTypeExhausted BetaManagedAgentsRetryStatusExhaustedType = "exhausted" + BetaManagedAgentsSearchResultBlockTypeSearchResult BetaManagedAgentsSearchResultBlockType = "search_result" ) -// The server is retrying automatically. Client should wait; the same error type -// may fire again as retrying, then once as exhausted when the retry budget runs -// out. -type BetaManagedAgentsRetryStatusRetrying struct { - // Any of "retrying". - Type BetaManagedAgentsRetryStatusRetryingType `json:"type" api:"required"` +// A block containing a web search result. +// +// The properties Citations, Content, Source, Title, Type are required. +type BetaManagedAgentsSearchResultBlockParam struct { + // Citation settings for a search result. + Citations BetaManagedAgentsSearchResultCitationsParam `json:"citations,omitzero" api:"required"` + // Array of text content blocks from the search result. + Content []BetaManagedAgentsSearchResultContentParam `json:"content,omitzero" api:"required"` + // The URL source of the search result. + Source string `json:"source" api:"required"` + // The title of the search result. + Title string `json:"title" api:"required"` + // Any of "search_result". + Type BetaManagedAgentsSearchResultBlockType `json:"type,omitzero" api:"required"` + paramObj +} + +func (r BetaManagedAgentsSearchResultBlockParam) MarshalJSON() (data []byte, err error) { + type shadow BetaManagedAgentsSearchResultBlockParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaManagedAgentsSearchResultBlockParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Citation settings for a search result. +type BetaManagedAgentsSearchResultCitations struct { + // Whether citations are enabled for this search result. + Enabled bool `json:"enabled" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { - Type respjson.Field + Enabled respjson.Field ExtraFields map[string]respjson.Field raw string } `json:"-"` } // Returns the unmodified JSON received from the API -func (r BetaManagedAgentsRetryStatusRetrying) RawJSON() string { return r.JSON.raw } -func (r *BetaManagedAgentsRetryStatusRetrying) UnmarshalJSON(data []byte) error { +func (r BetaManagedAgentsSearchResultCitations) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsSearchResultCitations) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type BetaManagedAgentsRetryStatusRetryingType string +// ToParam converts this BetaManagedAgentsSearchResultCitations to a +// BetaManagedAgentsSearchResultCitationsParam. +// +// Warning: the fields of the param type will not be present. ToParam should only +// be used at the last possible moment before sending a request. Test for this with +// BetaManagedAgentsSearchResultCitationsParam.Overrides() +func (r BetaManagedAgentsSearchResultCitations) ToParam() BetaManagedAgentsSearchResultCitationsParam { + return param.Override[BetaManagedAgentsSearchResultCitationsParam](json.RawMessage(r.RawJSON())) +} -const ( - BetaManagedAgentsRetryStatusRetryingTypeRetrying BetaManagedAgentsRetryStatusRetryingType = "retrying" -) +// Citation settings for a search result. +// +// The property Enabled is required. +type BetaManagedAgentsSearchResultCitationsParam struct { + // Whether citations are enabled for this search result. + Enabled bool `json:"enabled" api:"required"` + paramObj +} -// The session encountered a terminal error and will transition to `terminated` -// state. -type BetaManagedAgentsRetryStatusTerminal struct { - // Any of "terminal". - Type BetaManagedAgentsRetryStatusTerminalType `json:"type" api:"required"` +func (r BetaManagedAgentsSearchResultCitationsParam) MarshalJSON() (data []byte, err error) { + type shadow BetaManagedAgentsSearchResultCitationsParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaManagedAgentsSearchResultCitationsParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Text content within a search result. +type BetaManagedAgentsSearchResultContent struct { + // The text content. + Text string `json:"text" api:"required"` + // Any of "text". + Type BetaManagedAgentsSearchResultContentType `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { + Text respjson.Field Type respjson.Field ExtraFields map[string]respjson.Field raw string @@ -2272,17 +3187,46 @@ type BetaManagedAgentsRetryStatusTerminal struct { } // Returns the unmodified JSON received from the API -func (r BetaManagedAgentsRetryStatusTerminal) RawJSON() string { return r.JSON.raw } -func (r *BetaManagedAgentsRetryStatusTerminal) UnmarshalJSON(data []byte) error { +func (r BetaManagedAgentsSearchResultContent) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsSearchResultContent) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type BetaManagedAgentsRetryStatusTerminalType string +// ToParam converts this BetaManagedAgentsSearchResultContent to a +// BetaManagedAgentsSearchResultContentParam. +// +// Warning: the fields of the param type will not be present. ToParam should only +// be used at the last possible moment before sending a request. Test for this with +// BetaManagedAgentsSearchResultContentParam.Overrides() +func (r BetaManagedAgentsSearchResultContent) ToParam() BetaManagedAgentsSearchResultContentParam { + return param.Override[BetaManagedAgentsSearchResultContentParam](json.RawMessage(r.RawJSON())) +} + +type BetaManagedAgentsSearchResultContentType string const ( - BetaManagedAgentsRetryStatusTerminalTypeTerminal BetaManagedAgentsRetryStatusTerminalType = "terminal" + BetaManagedAgentsSearchResultContentTypeText BetaManagedAgentsSearchResultContentType = "text" ) +// Text content within a search result. +// +// The properties Text, Type are required. +type BetaManagedAgentsSearchResultContentParam struct { + // The text content. + Text string `json:"text" api:"required"` + // Any of "text". + Type BetaManagedAgentsSearchResultContentType `json:"type,omitzero" api:"required"` + paramObj +} + +func (r BetaManagedAgentsSearchResultContentParam) MarshalJSON() (data []byte, err error) { + type shadow BetaManagedAgentsSearchResultContentParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaManagedAgentsSearchResultContentParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + // Events that were successfully sent to the session. type BetaManagedAgentsSendSessionEvents struct { // Sent events @@ -2305,7 +3249,9 @@ func (r *BetaManagedAgentsSendSessionEvents) UnmarshalJSON(data []byte) error { // values from [BetaManagedAgentsUserMessageEvent], // [BetaManagedAgentsUserInterruptEvent], // [BetaManagedAgentsUserToolConfirmationEvent], -// [BetaManagedAgentsUserCustomToolResultEvent]. +// [BetaManagedAgentsUserCustomToolResultEvent], +// [BetaManagedAgentsUserDefineOutcomeEvent], +// [BetaManagedAgentsUserToolResultEvent], [BetaManagedAgentsSystemMessageEvent]. // // Use the [BetaManagedAgentsSendSessionEventsDataUnion.AsAny] method to switch on // the variant. @@ -2314,32 +3260,47 @@ func (r *BetaManagedAgentsSendSessionEvents) UnmarshalJSON(data []byte) error { type BetaManagedAgentsSendSessionEventsDataUnion struct { ID string `json:"id"` // This field is a union of [[]BetaManagedAgentsUserMessageEventContentUnion], - // [[]BetaManagedAgentsUserCustomToolResultEventContentUnion] + // [[]BetaManagedAgentsUserCustomToolResultEventContentUnion], + // [[]BetaManagedAgentsUserToolResultEventContentUnion], + // [[]BetaManagedAgentsSystemContentBlock] Content BetaManagedAgentsSendSessionEventsDataUnionContent `json:"content"` // Any of "user.message", "user.interrupt", "user.tool_confirmation", - // "user.custom_tool_result". - Type string `json:"type"` - ProcessedAt time.Time `json:"processed_at"` + // "user.custom_tool_result", "user.define_outcome", "user.tool_result", + // "system.message". + Type string `json:"type"` + ProcessedAt time.Time `json:"processed_at"` + SessionThreadID string `json:"session_thread_id"` // This field is from variant [BetaManagedAgentsUserToolConfirmationEvent]. - Result BetaManagedAgentsUserToolConfirmationEventResult `json:"result"` - // This field is from variant [BetaManagedAgentsUserToolConfirmationEvent]. - ToolUseID string `json:"tool_use_id"` + Result BetaManagedAgentsUserToolConfirmationEventResult `json:"result"` + ToolUseID string `json:"tool_use_id"` // This field is from variant [BetaManagedAgentsUserToolConfirmationEvent]. DenyMessage string `json:"deny_message"` // This field is from variant [BetaManagedAgentsUserCustomToolResultEvent]. CustomToolUseID string `json:"custom_tool_use_id"` - // This field is from variant [BetaManagedAgentsUserCustomToolResultEvent]. - IsError bool `json:"is_error"` - JSON struct { + IsError bool `json:"is_error"` + // This field is from variant [BetaManagedAgentsUserDefineOutcomeEvent]. + Description string `json:"description"` + // This field is from variant [BetaManagedAgentsUserDefineOutcomeEvent]. + MaxIterations int64 `json:"max_iterations"` + // This field is from variant [BetaManagedAgentsUserDefineOutcomeEvent]. + OutcomeID string `json:"outcome_id"` + // This field is from variant [BetaManagedAgentsUserDefineOutcomeEvent]. + Rubric BetaManagedAgentsUserDefineOutcomeEventRubricUnion `json:"rubric"` + JSON struct { ID respjson.Field Content respjson.Field Type respjson.Field ProcessedAt respjson.Field + SessionThreadID respjson.Field Result respjson.Field ToolUseID respjson.Field DenyMessage respjson.Field CustomToolUseID respjson.Field IsError respjson.Field + Description respjson.Field + MaxIterations respjson.Field + OutcomeID respjson.Field + Rubric respjson.Field raw string } `json:"-"` } @@ -2355,6 +3316,9 @@ func (BetaManagedAgentsUserMessageEvent) implBetaManagedAgentsSendSessionEventsD func (BetaManagedAgentsUserInterruptEvent) implBetaManagedAgentsSendSessionEventsDataUnion() {} func (BetaManagedAgentsUserToolConfirmationEvent) implBetaManagedAgentsSendSessionEventsDataUnion() {} func (BetaManagedAgentsUserCustomToolResultEvent) implBetaManagedAgentsSendSessionEventsDataUnion() {} +func (BetaManagedAgentsUserDefineOutcomeEvent) implBetaManagedAgentsSendSessionEventsDataUnion() {} +func (BetaManagedAgentsUserToolResultEvent) implBetaManagedAgentsSendSessionEventsDataUnion() {} +func (BetaManagedAgentsSystemMessageEvent) implBetaManagedAgentsSendSessionEventsDataUnion() {} // Use the following switch statement to find the correct variant // @@ -2363,6 +3327,9 @@ func (BetaManagedAgentsUserCustomToolResultEvent) implBetaManagedAgentsSendSessi // case anthropic.BetaManagedAgentsUserInterruptEvent: // case anthropic.BetaManagedAgentsUserToolConfirmationEvent: // case anthropic.BetaManagedAgentsUserCustomToolResultEvent: +// case anthropic.BetaManagedAgentsUserDefineOutcomeEvent: +// case anthropic.BetaManagedAgentsUserToolResultEvent: +// case anthropic.BetaManagedAgentsSystemMessageEvent: // default: // fmt.Errorf("no variant present") // } @@ -2376,6 +3343,12 @@ func (u BetaManagedAgentsSendSessionEventsDataUnion) AsAny() anyBetaManagedAgent return u.AsUserToolConfirmation() case "user.custom_tool_result": return u.AsUserCustomToolResult() + case "user.define_outcome": + return u.AsUserDefineOutcome() + case "user.tool_result": + return u.AsUserToolResult() + case "system.message": + return u.AsSystemMessage() } return nil } @@ -2400,6 +3373,21 @@ func (u BetaManagedAgentsSendSessionEventsDataUnion) AsUserCustomToolResult() (v return } +func (u BetaManagedAgentsSendSessionEventsDataUnion) AsUserDefineOutcome() (v BetaManagedAgentsUserDefineOutcomeEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsSendSessionEventsDataUnion) AsUserToolResult() (v BetaManagedAgentsUserToolResultEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsSendSessionEventsDataUnion) AsSystemMessage() (v BetaManagedAgentsSystemMessageEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + // Returns the unmodified JSON received from the API func (u BetaManagedAgentsSendSessionEventsDataUnion) RawJSON() string { return u.JSON.raw } @@ -2417,7 +3405,9 @@ func (r *BetaManagedAgentsSendSessionEventsDataUnion) UnmarshalJSON(data []byte) // // If the underlying value is not a json object, one of the following properties // will be valid: OfBetaManagedAgentsUserMessageEventContentArray -// OfBetaManagedAgentsUserCustomToolResultEventContentArray] +// OfBetaManagedAgentsUserCustomToolResultEventContentArray +// OfBetaManagedAgentsUserToolResultEventContentArray +// OfBetaManagedAgentsSystemContentBlockArray] type BetaManagedAgentsSendSessionEventsDataUnionContent struct { // This field will be present if the value is a // [[]BetaManagedAgentsUserMessageEventContentUnion] instead of an object. @@ -2425,9 +3415,17 @@ type BetaManagedAgentsSendSessionEventsDataUnionContent struct { // This field will be present if the value is a // [[]BetaManagedAgentsUserCustomToolResultEventContentUnion] instead of an object. OfBetaManagedAgentsUserCustomToolResultEventContentArray []BetaManagedAgentsUserCustomToolResultEventContentUnion `json:",inline"` - JSON struct { + // This field will be present if the value is a + // [[]BetaManagedAgentsUserToolResultEventContentUnion] instead of an object. + OfBetaManagedAgentsUserToolResultEventContentArray []BetaManagedAgentsUserToolResultEventContentUnion `json:",inline"` + // This field will be present if the value is a + // [[]BetaManagedAgentsSystemContentBlock] instead of an object. + OfBetaManagedAgentsSystemContentBlockArray []BetaManagedAgentsSystemContentBlock `json:",inline"` + JSON struct { OfBetaManagedAgentsUserMessageEventContentArray respjson.Field OfBetaManagedAgentsUserCustomToolResultEventContentArray respjson.Field + OfBetaManagedAgentsUserToolResultEventContentArray respjson.Field + OfBetaManagedAgentsSystemContentBlockArray respjson.Field raw string } `json:"-"` } @@ -2436,6 +3434,33 @@ func (r *BetaManagedAgentsSendSessionEventsDataUnionContent) UnmarshalJSON(data return apijson.UnmarshalRoot(data, r) } +// The agent stopped because the session's tracked list cost reached its budget, or +// because its usage includes a model with no list price (which the budget cannot +// measure). Raise the budget to continue — or, if raising is rejected because a +// model has no list price, remove the budget. +type BetaManagedAgentsSessionBudgetReached struct { + // Any of "budget_reached". + Type BetaManagedAgentsSessionBudgetReachedType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsSessionBudgetReached) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsSessionBudgetReached) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsSessionBudgetReachedType string + +const ( + BetaManagedAgentsSessionBudgetReachedTypeBudgetReached BetaManagedAgentsSessionBudgetReachedType = "budget_reached" +) + // Emitted when a session has been deleted. Terminates any active event stream — no // further events will be emitted for this session. type BetaManagedAgentsSessionDeletedEvent struct { @@ -2527,7 +3552,8 @@ func (r *BetaManagedAgentsSessionErrorEvent) UnmarshalJSON(data []byte) error { // [BetaManagedAgentsModelRequestFailedError], // [BetaManagedAgentsMCPConnectionFailedError], // [BetaManagedAgentsMCPAuthenticationFailedError], -// [BetaManagedAgentsBillingError]. +// [BetaManagedAgentsBillingError], +// [BetaManagedAgentsCredentialHostUnreachableError]. // // Use the [BetaManagedAgentsSessionErrorEventErrorUnion.AsAny] method to switch on // the variant. @@ -2541,18 +3567,26 @@ type BetaManagedAgentsSessionErrorEventErrorUnion struct { // [BetaManagedAgentsModelRequestFailedErrorRetryStatusUnion], // [BetaManagedAgentsMCPConnectionFailedErrorRetryStatusUnion], // [BetaManagedAgentsMCPAuthenticationFailedErrorRetryStatusUnion], - // [BetaManagedAgentsBillingErrorRetryStatusUnion] + // [BetaManagedAgentsBillingErrorRetryStatusUnion], + // [BetaManagedAgentsCredentialHostUnreachableErrorRetryStatusUnion] RetryStatus BetaManagedAgentsSessionErrorEventErrorUnionRetryStatus `json:"retry_status"` // Any of "unknown_error", "model_overloaded_error", "model_rate_limited_error", // "model_request_failed_error", "mcp_connection_failed_error", - // "mcp_authentication_failed_error", "billing_error". + // "mcp_authentication_failed_error", "billing_error", + // "credential_host_unreachable_error". Type string `json:"type"` MCPServerName string `json:"mcp_server_name"` - JSON struct { + // This field is from variant [BetaManagedAgentsCredentialHostUnreachableError]. + CredentialID string `json:"credential_id"` + // This field is from variant [BetaManagedAgentsCredentialHostUnreachableError]. + VaultID string `json:"vault_id"` + JSON struct { Message respjson.Field RetryStatus respjson.Field Type respjson.Field MCPServerName respjson.Field + CredentialID respjson.Field + VaultID respjson.Field raw string } `json:"-"` } @@ -2572,6 +3606,8 @@ func (BetaManagedAgentsMCPConnectionFailedError) implBetaManagedAgentsSessionErr func (BetaManagedAgentsMCPAuthenticationFailedError) implBetaManagedAgentsSessionErrorEventErrorUnion() { } func (BetaManagedAgentsBillingError) implBetaManagedAgentsSessionErrorEventErrorUnion() {} +func (BetaManagedAgentsCredentialHostUnreachableError) implBetaManagedAgentsSessionErrorEventErrorUnion() { +} // Use the following switch statement to find the correct variant // @@ -2583,6 +3619,7 @@ func (BetaManagedAgentsBillingError) implBetaManagedAgentsSessionErrorEventError // case anthropic.BetaManagedAgentsMCPConnectionFailedError: // case anthropic.BetaManagedAgentsMCPAuthenticationFailedError: // case anthropic.BetaManagedAgentsBillingError: +// case anthropic.BetaManagedAgentsCredentialHostUnreachableError: // default: // fmt.Errorf("no variant present") // } @@ -2602,6 +3639,8 @@ func (u BetaManagedAgentsSessionErrorEventErrorUnion) AsAny() anyBetaManagedAgen return u.AsMCPAuthenticationFailedError() case "billing_error": return u.AsBillingError() + case "credential_host_unreachable_error": + return u.AsCredentialHostUnreachableError() } return nil } @@ -2641,6 +3680,11 @@ func (u BetaManagedAgentsSessionErrorEventErrorUnion) AsBillingError() (v BetaMa return } +func (u BetaManagedAgentsSessionErrorEventErrorUnion) AsCredentialHostUnreachableError() (v BetaManagedAgentsCredentialHostUnreachableError) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + // Returns the unmodified JSON received from the API func (u BetaManagedAgentsSessionErrorEventErrorUnion) RawJSON() string { return u.JSON.raw } @@ -2682,15 +3726,29 @@ const ( // [BetaManagedAgentsAgentMCPToolUseEvent], // [BetaManagedAgentsAgentMCPToolResultEvent], // [BetaManagedAgentsAgentToolUseEvent], [BetaManagedAgentsAgentToolResultEvent], +// [BetaManagedAgentsAgentThreadMessageReceivedEvent], +// [BetaManagedAgentsAgentThreadMessageSentEvent], // [BetaManagedAgentsAgentThreadContextCompactedEvent], // [BetaManagedAgentsSessionErrorEvent], // [BetaManagedAgentsSessionStatusRescheduledEvent], // [BetaManagedAgentsSessionStatusRunningEvent], // [BetaManagedAgentsSessionStatusIdleEvent], // [BetaManagedAgentsSessionStatusTerminatedEvent], +// [BetaManagedAgentsSessionThreadCreatedEvent], +// [BetaManagedAgentsSpanOutcomeEvaluationStartEvent], +// [BetaManagedAgentsSpanOutcomeEvaluationEndEvent], // [BetaManagedAgentsSpanModelRequestStartEvent], // [BetaManagedAgentsSpanModelRequestEndEvent], -// [BetaManagedAgentsSessionDeletedEvent]. +// [BetaManagedAgentsSpanOutcomeEvaluationOngoingEvent], +// [BetaManagedAgentsUserDefineOutcomeEvent], +// [BetaManagedAgentsSessionDeletedEvent], +// [BetaManagedAgentsSessionThreadStatusRunningEvent], +// [BetaManagedAgentsSessionThreadStatusIdleEvent], +// [BetaManagedAgentsSessionThreadStatusTerminatedEvent], +// [BetaManagedAgentsUserToolResultEvent], +// [BetaManagedAgentsSessionThreadStatusRescheduledEvent], +// [BetaManagedAgentsSessionUpdatedEvent], [BetaManagedAgentsSystemMessageEvent], +// [BetaManagedAgentsSessionUsageEvent]. // // Use the [BetaManagedAgentsSessionEventUnion.AsAny] method to switch on the // variant. @@ -2700,22 +3758,33 @@ type BetaManagedAgentsSessionEventUnion struct { ID string `json:"id"` // This field is a union of [[]BetaManagedAgentsUserMessageEventContentUnion], // [[]BetaManagedAgentsUserCustomToolResultEventContentUnion], - // [[]BetaManagedAgentsTextBlock], + // [[]BetaManagedAgentsAgentMessageEventContentUnion], // [[]BetaManagedAgentsAgentMCPToolResultEventContentUnion], - // [[]BetaManagedAgentsAgentToolResultEventContentUnion] + // [[]BetaManagedAgentsAgentToolResultEventContentUnion], + // [[]BetaManagedAgentsAgentThreadMessageReceivedEventContentUnion], + // [[]BetaManagedAgentsAgentThreadMessageSentEventContentUnion], + // [[]BetaManagedAgentsUserToolResultEventContentUnion], + // [[]BetaManagedAgentsSystemContentBlock] Content BetaManagedAgentsSessionEventUnionContent `json:"content"` // Any of "user.message", "user.interrupt", "user.tool_confirmation", // "user.custom_tool_result", "agent.custom_tool_use", "agent.message", // "agent.thinking", "agent.mcp_tool_use", "agent.mcp_tool_result", - // "agent.tool_use", "agent.tool_result", "agent.thread_context_compacted", - // "session.error", "session.status_rescheduled", "session.status_running", - // "session.status_idle", "session.status_terminated", "span.model_request_start", - // "span.model_request_end", "session.deleted". - Type string `json:"type"` - ProcessedAt time.Time `json:"processed_at"` - // This field is from variant [BetaManagedAgentsUserToolConfirmationEvent]. - Result BetaManagedAgentsUserToolConfirmationEventResult `json:"result"` - ToolUseID string `json:"tool_use_id"` + // "agent.tool_use", "agent.tool_result", "agent.thread_message_received", + // "agent.thread_message_sent", "agent.thread_context_compacted", "session.error", + // "session.status_rescheduled", "session.status_running", "session.status_idle", + // "session.status_terminated", "session.thread_created", + // "span.outcome_evaluation_start", "span.outcome_evaluation_end", + // "span.model_request_start", "span.model_request_end", + // "span.outcome_evaluation_ongoing", "user.define_outcome", "session.deleted", + // "session.thread_status_running", "session.thread_status_idle", + // "session.thread_status_terminated", "user.tool_result", + // "session.thread_status_rescheduled", "session.updated", "system.message", + // "session.usage". + Type string `json:"type"` + ProcessedAt time.Time `json:"processed_at"` + SessionThreadID string `json:"session_thread_id"` + Result string `json:"result"` + ToolUseID string `json:"tool_use_id"` // This field is from variant [BetaManagedAgentsUserToolConfirmationEvent]. DenyMessage string `json:"deny_message"` // This field is from variant [BetaManagedAgentsUserCustomToolResultEvent]. @@ -2728,34 +3797,86 @@ type BetaManagedAgentsSessionEventUnion struct { EvaluatedPermission string `json:"evaluated_permission"` // This field is from variant [BetaManagedAgentsAgentMCPToolResultEvent]. MCPToolUseID string `json:"mcp_tool_use_id"` + // This field is from variant [BetaManagedAgentsAgentThreadMessageReceivedEvent]. + FromSessionThreadID string `json:"from_session_thread_id"` + // This field is from variant [BetaManagedAgentsAgentThreadMessageReceivedEvent]. + FromAgentName string `json:"from_agent_name"` + // This field is from variant [BetaManagedAgentsAgentThreadMessageSentEvent]. + ToSessionThreadID string `json:"to_session_thread_id"` + // This field is from variant [BetaManagedAgentsAgentThreadMessageSentEvent]. + ToAgentName string `json:"to_agent_name"` // This field is from variant [BetaManagedAgentsSessionErrorEvent]. Error BetaManagedAgentsSessionErrorEventErrorUnion `json:"error"` - // This field is from variant [BetaManagedAgentsSessionStatusIdleEvent]. - StopReason BetaManagedAgentsSessionStatusIdleEventStopReasonUnion `json:"stop_reason"` + // This field is a union of + // [BetaManagedAgentsSessionStatusIdleEventStopReasonUnion], + // [BetaManagedAgentsSessionThreadStatusIdleEventStopReasonUnion] + StopReason BetaManagedAgentsSessionEventUnionStopReason `json:"stop_reason"` + AgentName string `json:"agent_name"` + Iteration int64 `json:"iteration"` + OutcomeID string `json:"outcome_id"` + // This field is from variant [BetaManagedAgentsSpanOutcomeEvaluationEndEvent]. + Explanation string `json:"explanation"` + // This field is from variant [BetaManagedAgentsSpanOutcomeEvaluationEndEvent]. + OutcomeEvaluationStartID string `json:"outcome_evaluation_start_id"` + // This field is a union of [BetaManagedAgentsSpanModelUsage], + // [BetaManagedAgentsSessionUsageSnapshot] + Usage BetaManagedAgentsSessionEventUnionUsage `json:"usage"` // This field is from variant [BetaManagedAgentsSpanModelRequestEndEvent]. ModelRequestStartID string `json:"model_request_start_id"` // This field is from variant [BetaManagedAgentsSpanModelRequestEndEvent]. ModelUsage BetaManagedAgentsSpanModelUsage `json:"model_usage"` - JSON struct { - ID respjson.Field - Content respjson.Field - Type respjson.Field - ProcessedAt respjson.Field - Result respjson.Field - ToolUseID respjson.Field - DenyMessage respjson.Field - CustomToolUseID respjson.Field - IsError respjson.Field - Input respjson.Field - Name respjson.Field - MCPServerName respjson.Field - EvaluatedPermission respjson.Field - MCPToolUseID respjson.Field - Error respjson.Field - StopReason respjson.Field - ModelRequestStartID respjson.Field - ModelUsage respjson.Field - raw string + // This field is from variant [BetaManagedAgentsUserDefineOutcomeEvent]. + Description string `json:"description"` + // This field is from variant [BetaManagedAgentsUserDefineOutcomeEvent]. + MaxIterations int64 `json:"max_iterations"` + // This field is from variant [BetaManagedAgentsUserDefineOutcomeEvent]. + Rubric BetaManagedAgentsUserDefineOutcomeEventRubricUnion `json:"rubric"` + // This field is from variant [BetaManagedAgentsSessionUpdatedEvent]. + Agent BetaManagedAgentsSessionAgent `json:"agent"` + // This field is from variant [BetaManagedAgentsSessionUpdatedEvent]. + Budget BetaManagedAgentsBudgetLimit `json:"budget"` + // This field is from variant [BetaManagedAgentsSessionUpdatedEvent]. + Metadata map[string]string `json:"metadata"` + // This field is from variant [BetaManagedAgentsSessionUpdatedEvent]. + Title string `json:"title"` + JSON struct { + ID respjson.Field + Content respjson.Field + Type respjson.Field + ProcessedAt respjson.Field + SessionThreadID respjson.Field + Result respjson.Field + ToolUseID respjson.Field + DenyMessage respjson.Field + CustomToolUseID respjson.Field + IsError respjson.Field + Input respjson.Field + Name respjson.Field + MCPServerName respjson.Field + EvaluatedPermission respjson.Field + MCPToolUseID respjson.Field + FromSessionThreadID respjson.Field + FromAgentName respjson.Field + ToSessionThreadID respjson.Field + ToAgentName respjson.Field + Error respjson.Field + StopReason respjson.Field + AgentName respjson.Field + Iteration respjson.Field + OutcomeID respjson.Field + Explanation respjson.Field + OutcomeEvaluationStartID respjson.Field + Usage respjson.Field + ModelRequestStartID respjson.Field + ModelUsage respjson.Field + Description respjson.Field + MaxIterations respjson.Field + Rubric respjson.Field + Agent respjson.Field + Budget respjson.Field + Metadata respjson.Field + Title respjson.Field + raw string } `json:"-"` } @@ -2766,26 +3887,42 @@ type anyBetaManagedAgentsSessionEvent interface { implBetaManagedAgentsSessionEventUnion() } -func (BetaManagedAgentsUserMessageEvent) implBetaManagedAgentsSessionEventUnion() {} -func (BetaManagedAgentsUserInterruptEvent) implBetaManagedAgentsSessionEventUnion() {} -func (BetaManagedAgentsUserToolConfirmationEvent) implBetaManagedAgentsSessionEventUnion() {} -func (BetaManagedAgentsUserCustomToolResultEvent) implBetaManagedAgentsSessionEventUnion() {} -func (BetaManagedAgentsAgentCustomToolUseEvent) implBetaManagedAgentsSessionEventUnion() {} -func (BetaManagedAgentsAgentMessageEvent) implBetaManagedAgentsSessionEventUnion() {} -func (BetaManagedAgentsAgentThinkingEvent) implBetaManagedAgentsSessionEventUnion() {} -func (BetaManagedAgentsAgentMCPToolUseEvent) implBetaManagedAgentsSessionEventUnion() {} -func (BetaManagedAgentsAgentMCPToolResultEvent) implBetaManagedAgentsSessionEventUnion() {} -func (BetaManagedAgentsAgentToolUseEvent) implBetaManagedAgentsSessionEventUnion() {} -func (BetaManagedAgentsAgentToolResultEvent) implBetaManagedAgentsSessionEventUnion() {} -func (BetaManagedAgentsAgentThreadContextCompactedEvent) implBetaManagedAgentsSessionEventUnion() {} -func (BetaManagedAgentsSessionErrorEvent) implBetaManagedAgentsSessionEventUnion() {} -func (BetaManagedAgentsSessionStatusRescheduledEvent) implBetaManagedAgentsSessionEventUnion() {} -func (BetaManagedAgentsSessionStatusRunningEvent) implBetaManagedAgentsSessionEventUnion() {} -func (BetaManagedAgentsSessionStatusIdleEvent) implBetaManagedAgentsSessionEventUnion() {} -func (BetaManagedAgentsSessionStatusTerminatedEvent) implBetaManagedAgentsSessionEventUnion() {} -func (BetaManagedAgentsSpanModelRequestStartEvent) implBetaManagedAgentsSessionEventUnion() {} -func (BetaManagedAgentsSpanModelRequestEndEvent) implBetaManagedAgentsSessionEventUnion() {} -func (BetaManagedAgentsSessionDeletedEvent) implBetaManagedAgentsSessionEventUnion() {} +func (BetaManagedAgentsUserMessageEvent) implBetaManagedAgentsSessionEventUnion() {} +func (BetaManagedAgentsUserInterruptEvent) implBetaManagedAgentsSessionEventUnion() {} +func (BetaManagedAgentsUserToolConfirmationEvent) implBetaManagedAgentsSessionEventUnion() {} +func (BetaManagedAgentsUserCustomToolResultEvent) implBetaManagedAgentsSessionEventUnion() {} +func (BetaManagedAgentsAgentCustomToolUseEvent) implBetaManagedAgentsSessionEventUnion() {} +func (BetaManagedAgentsAgentMessageEvent) implBetaManagedAgentsSessionEventUnion() {} +func (BetaManagedAgentsAgentThinkingEvent) implBetaManagedAgentsSessionEventUnion() {} +func (BetaManagedAgentsAgentMCPToolUseEvent) implBetaManagedAgentsSessionEventUnion() {} +func (BetaManagedAgentsAgentMCPToolResultEvent) implBetaManagedAgentsSessionEventUnion() {} +func (BetaManagedAgentsAgentToolUseEvent) implBetaManagedAgentsSessionEventUnion() {} +func (BetaManagedAgentsAgentToolResultEvent) implBetaManagedAgentsSessionEventUnion() {} +func (BetaManagedAgentsAgentThreadMessageReceivedEvent) implBetaManagedAgentsSessionEventUnion() {} +func (BetaManagedAgentsAgentThreadMessageSentEvent) implBetaManagedAgentsSessionEventUnion() {} +func (BetaManagedAgentsAgentThreadContextCompactedEvent) implBetaManagedAgentsSessionEventUnion() {} +func (BetaManagedAgentsSessionErrorEvent) implBetaManagedAgentsSessionEventUnion() {} +func (BetaManagedAgentsSessionStatusRescheduledEvent) implBetaManagedAgentsSessionEventUnion() {} +func (BetaManagedAgentsSessionStatusRunningEvent) implBetaManagedAgentsSessionEventUnion() {} +func (BetaManagedAgentsSessionStatusIdleEvent) implBetaManagedAgentsSessionEventUnion() {} +func (BetaManagedAgentsSessionStatusTerminatedEvent) implBetaManagedAgentsSessionEventUnion() {} +func (BetaManagedAgentsSessionThreadCreatedEvent) implBetaManagedAgentsSessionEventUnion() {} +func (BetaManagedAgentsSpanOutcomeEvaluationStartEvent) implBetaManagedAgentsSessionEventUnion() {} +func (BetaManagedAgentsSpanOutcomeEvaluationEndEvent) implBetaManagedAgentsSessionEventUnion() {} +func (BetaManagedAgentsSpanModelRequestStartEvent) implBetaManagedAgentsSessionEventUnion() {} +func (BetaManagedAgentsSpanModelRequestEndEvent) implBetaManagedAgentsSessionEventUnion() {} +func (BetaManagedAgentsSpanOutcomeEvaluationOngoingEvent) implBetaManagedAgentsSessionEventUnion() {} +func (BetaManagedAgentsUserDefineOutcomeEvent) implBetaManagedAgentsSessionEventUnion() {} +func (BetaManagedAgentsSessionDeletedEvent) implBetaManagedAgentsSessionEventUnion() {} +func (BetaManagedAgentsSessionThreadStatusRunningEvent) implBetaManagedAgentsSessionEventUnion() {} +func (BetaManagedAgentsSessionThreadStatusIdleEvent) implBetaManagedAgentsSessionEventUnion() {} +func (BetaManagedAgentsSessionThreadStatusTerminatedEvent) implBetaManagedAgentsSessionEventUnion() {} +func (BetaManagedAgentsUserToolResultEvent) implBetaManagedAgentsSessionEventUnion() {} +func (BetaManagedAgentsSessionThreadStatusRescheduledEvent) implBetaManagedAgentsSessionEventUnion() { +} +func (BetaManagedAgentsSessionUpdatedEvent) implBetaManagedAgentsSessionEventUnion() {} +func (BetaManagedAgentsSystemMessageEvent) implBetaManagedAgentsSessionEventUnion() {} +func (BetaManagedAgentsSessionUsageEvent) implBetaManagedAgentsSessionEventUnion() {} // Use the following switch statement to find the correct variant // @@ -2801,15 +3938,30 @@ func (BetaManagedAgentsSessionDeletedEvent) implBetaManagedAgentsSessionEventUni // case anthropic.BetaManagedAgentsAgentMCPToolResultEvent: // case anthropic.BetaManagedAgentsAgentToolUseEvent: // case anthropic.BetaManagedAgentsAgentToolResultEvent: +// case anthropic.BetaManagedAgentsAgentThreadMessageReceivedEvent: +// case anthropic.BetaManagedAgentsAgentThreadMessageSentEvent: // case anthropic.BetaManagedAgentsAgentThreadContextCompactedEvent: // case anthropic.BetaManagedAgentsSessionErrorEvent: // case anthropic.BetaManagedAgentsSessionStatusRescheduledEvent: // case anthropic.BetaManagedAgentsSessionStatusRunningEvent: // case anthropic.BetaManagedAgentsSessionStatusIdleEvent: // case anthropic.BetaManagedAgentsSessionStatusTerminatedEvent: +// case anthropic.BetaManagedAgentsSessionThreadCreatedEvent: +// case anthropic.BetaManagedAgentsSpanOutcomeEvaluationStartEvent: +// case anthropic.BetaManagedAgentsSpanOutcomeEvaluationEndEvent: // case anthropic.BetaManagedAgentsSpanModelRequestStartEvent: // case anthropic.BetaManagedAgentsSpanModelRequestEndEvent: +// case anthropic.BetaManagedAgentsSpanOutcomeEvaluationOngoingEvent: +// case anthropic.BetaManagedAgentsUserDefineOutcomeEvent: // case anthropic.BetaManagedAgentsSessionDeletedEvent: +// case anthropic.BetaManagedAgentsSessionThreadStatusRunningEvent: +// case anthropic.BetaManagedAgentsSessionThreadStatusIdleEvent: +// case anthropic.BetaManagedAgentsSessionThreadStatusTerminatedEvent: +// case anthropic.BetaManagedAgentsUserToolResultEvent: +// case anthropic.BetaManagedAgentsSessionThreadStatusRescheduledEvent: +// case anthropic.BetaManagedAgentsSessionUpdatedEvent: +// case anthropic.BetaManagedAgentsSystemMessageEvent: +// case anthropic.BetaManagedAgentsSessionUsageEvent: // default: // fmt.Errorf("no variant present") // } @@ -2837,6 +3989,10 @@ func (u BetaManagedAgentsSessionEventUnion) AsAny() anyBetaManagedAgentsSessionE return u.AsAgentToolUse() case "agent.tool_result": return u.AsAgentToolResult() + case "agent.thread_message_received": + return u.AsAgentThreadMessageReceived() + case "agent.thread_message_sent": + return u.AsAgentThreadMessageSent() case "agent.thread_context_compacted": return u.AsAgentThreadContextCompacted() case "session.error": @@ -2849,12 +4005,38 @@ func (u BetaManagedAgentsSessionEventUnion) AsAny() anyBetaManagedAgentsSessionE return u.AsSessionStatusIdle() case "session.status_terminated": return u.AsSessionStatusTerminated() + case "session.thread_created": + return u.AsSessionThreadCreated() + case "span.outcome_evaluation_start": + return u.AsSpanOutcomeEvaluationStart() + case "span.outcome_evaluation_end": + return u.AsSpanOutcomeEvaluationEnd() case "span.model_request_start": return u.AsSpanModelRequestStart() case "span.model_request_end": return u.AsSpanModelRequestEnd() + case "span.outcome_evaluation_ongoing": + return u.AsSpanOutcomeEvaluationOngoing() + case "user.define_outcome": + return u.AsUserDefineOutcome() case "session.deleted": return u.AsSessionDeleted() + case "session.thread_status_running": + return u.AsSessionThreadStatusRunning() + case "session.thread_status_idle": + return u.AsSessionThreadStatusIdle() + case "session.thread_status_terminated": + return u.AsSessionThreadStatusTerminated() + case "user.tool_result": + return u.AsUserToolResult() + case "session.thread_status_rescheduled": + return u.AsSessionThreadStatusRescheduled() + case "session.updated": + return u.AsSessionUpdated() + case "system.message": + return u.AsSystemMessage() + case "session.usage": + return u.AsSessionUsage() } return nil } @@ -2914,6 +4096,16 @@ func (u BetaManagedAgentsSessionEventUnion) AsAgentToolResult() (v BetaManagedAg return } +func (u BetaManagedAgentsSessionEventUnion) AsAgentThreadMessageReceived() (v BetaManagedAgentsAgentThreadMessageReceivedEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsSessionEventUnion) AsAgentThreadMessageSent() (v BetaManagedAgentsAgentThreadMessageSentEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + func (u BetaManagedAgentsSessionEventUnion) AsAgentThreadContextCompacted() (v BetaManagedAgentsAgentThreadContextCompactedEvent) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return @@ -2944,6 +4136,21 @@ func (u BetaManagedAgentsSessionEventUnion) AsSessionStatusTerminated() (v BetaM return } +func (u BetaManagedAgentsSessionEventUnion) AsSessionThreadCreated() (v BetaManagedAgentsSessionThreadCreatedEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsSessionEventUnion) AsSpanOutcomeEvaluationStart() (v BetaManagedAgentsSpanOutcomeEvaluationStartEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsSessionEventUnion) AsSpanOutcomeEvaluationEnd() (v BetaManagedAgentsSpanOutcomeEvaluationEndEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + func (u BetaManagedAgentsSessionEventUnion) AsSpanModelRequestStart() (v BetaManagedAgentsSpanModelRequestStartEvent) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return @@ -2954,58 +4161,194 @@ func (u BetaManagedAgentsSessionEventUnion) AsSpanModelRequestEnd() (v BetaManag return } +func (u BetaManagedAgentsSessionEventUnion) AsSpanOutcomeEvaluationOngoing() (v BetaManagedAgentsSpanOutcomeEvaluationOngoingEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsSessionEventUnion) AsUserDefineOutcome() (v BetaManagedAgentsUserDefineOutcomeEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + func (u BetaManagedAgentsSessionEventUnion) AsSessionDeleted() (v BetaManagedAgentsSessionDeletedEvent) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return } +func (u BetaManagedAgentsSessionEventUnion) AsSessionThreadStatusRunning() (v BetaManagedAgentsSessionThreadStatusRunningEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsSessionEventUnion) AsSessionThreadStatusIdle() (v BetaManagedAgentsSessionThreadStatusIdleEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsSessionEventUnion) AsSessionThreadStatusTerminated() (v BetaManagedAgentsSessionThreadStatusTerminatedEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsSessionEventUnion) AsUserToolResult() (v BetaManagedAgentsUserToolResultEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsSessionEventUnion) AsSessionThreadStatusRescheduled() (v BetaManagedAgentsSessionThreadStatusRescheduledEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsSessionEventUnion) AsSessionUpdated() (v BetaManagedAgentsSessionUpdatedEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsSessionEventUnion) AsSystemMessage() (v BetaManagedAgentsSystemMessageEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsSessionEventUnion) AsSessionUsage() (v BetaManagedAgentsSessionUsageEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + // Returns the unmodified JSON received from the API func (u BetaManagedAgentsSessionEventUnion) RawJSON() string { return u.JSON.raw } -func (r *BetaManagedAgentsSessionEventUnion) UnmarshalJSON(data []byte) error { +func (r *BetaManagedAgentsSessionEventUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaManagedAgentsSessionEventUnionContent is an implicit subunion of +// [BetaManagedAgentsSessionEventUnion]. BetaManagedAgentsSessionEventUnionContent +// provides convenient access to the sub-properties of the union. +// +// For type safety it is recommended to directly use a variant of the +// [BetaManagedAgentsSessionEventUnion]. +// +// If the underlying value is not a json object, one of the following properties +// will be valid: OfBetaManagedAgentsUserMessageEventContentArray +// OfBetaManagedAgentsUserCustomToolResultEventContentArray +// OfBetaManagedAgentsAgentMessageEventContentArray +// OfBetaManagedAgentsAgentMCPToolResultEventContentArray +// OfBetaManagedAgentsAgentToolResultEventContentArray +// OfBetaManagedAgentsAgentThreadMessageReceivedEventContentArray +// OfBetaManagedAgentsAgentThreadMessageSentEventContentArray +// OfBetaManagedAgentsUserToolResultEventContentArray +// OfBetaManagedAgentsSystemContentBlockArray] +type BetaManagedAgentsSessionEventUnionContent struct { + // This field will be present if the value is a + // [[]BetaManagedAgentsUserMessageEventContentUnion] instead of an object. + OfBetaManagedAgentsUserMessageEventContentArray []BetaManagedAgentsUserMessageEventContentUnion `json:",inline"` + // This field will be present if the value is a + // [[]BetaManagedAgentsUserCustomToolResultEventContentUnion] instead of an object. + OfBetaManagedAgentsUserCustomToolResultEventContentArray []BetaManagedAgentsUserCustomToolResultEventContentUnion `json:",inline"` + // This field will be present if the value is a + // [[]BetaManagedAgentsAgentMessageEventContentUnion] instead of an object. + OfBetaManagedAgentsAgentMessageEventContentArray []BetaManagedAgentsAgentMessageEventContentUnion `json:",inline"` + // This field will be present if the value is a + // [[]BetaManagedAgentsAgentMCPToolResultEventContentUnion] instead of an object. + OfBetaManagedAgentsAgentMCPToolResultEventContentArray []BetaManagedAgentsAgentMCPToolResultEventContentUnion `json:",inline"` + // This field will be present if the value is a + // [[]BetaManagedAgentsAgentToolResultEventContentUnion] instead of an object. + OfBetaManagedAgentsAgentToolResultEventContentArray []BetaManagedAgentsAgentToolResultEventContentUnion `json:",inline"` + // This field will be present if the value is a + // [[]BetaManagedAgentsAgentThreadMessageReceivedEventContentUnion] instead of an + // object. + OfBetaManagedAgentsAgentThreadMessageReceivedEventContentArray []BetaManagedAgentsAgentThreadMessageReceivedEventContentUnion `json:",inline"` + // This field will be present if the value is a + // [[]BetaManagedAgentsAgentThreadMessageSentEventContentUnion] instead of an + // object. + OfBetaManagedAgentsAgentThreadMessageSentEventContentArray []BetaManagedAgentsAgentThreadMessageSentEventContentUnion `json:",inline"` + // This field will be present if the value is a + // [[]BetaManagedAgentsUserToolResultEventContentUnion] instead of an object. + OfBetaManagedAgentsUserToolResultEventContentArray []BetaManagedAgentsUserToolResultEventContentUnion `json:",inline"` + // This field will be present if the value is a + // [[]BetaManagedAgentsSystemContentBlock] instead of an object. + OfBetaManagedAgentsSystemContentBlockArray []BetaManagedAgentsSystemContentBlock `json:",inline"` + JSON struct { + OfBetaManagedAgentsUserMessageEventContentArray respjson.Field + OfBetaManagedAgentsUserCustomToolResultEventContentArray respjson.Field + OfBetaManagedAgentsAgentMessageEventContentArray respjson.Field + OfBetaManagedAgentsAgentMCPToolResultEventContentArray respjson.Field + OfBetaManagedAgentsAgentToolResultEventContentArray respjson.Field + OfBetaManagedAgentsAgentThreadMessageReceivedEventContentArray respjson.Field + OfBetaManagedAgentsAgentThreadMessageSentEventContentArray respjson.Field + OfBetaManagedAgentsUserToolResultEventContentArray respjson.Field + OfBetaManagedAgentsSystemContentBlockArray respjson.Field + raw string + } `json:"-"` +} + +func (r *BetaManagedAgentsSessionEventUnionContent) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaManagedAgentsSessionEventUnionStopReason is an implicit subunion of +// [BetaManagedAgentsSessionEventUnion]. +// BetaManagedAgentsSessionEventUnionStopReason provides convenient access to the +// sub-properties of the union. +// +// For type safety it is recommended to directly use a variant of the +// [BetaManagedAgentsSessionEventUnion]. +type BetaManagedAgentsSessionEventUnionStopReason struct { + Type string `json:"type"` + // This field is from variant + // [BetaManagedAgentsSessionStatusIdleEventStopReasonUnion], + // [BetaManagedAgentsSessionThreadStatusIdleEventStopReasonUnion]. + EventIDs []string `json:"event_ids"` + JSON struct { + Type respjson.Field + EventIDs respjson.Field + raw string + } `json:"-"` +} + +func (r *BetaManagedAgentsSessionEventUnionStopReason) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// BetaManagedAgentsSessionEventUnionContent is an implicit subunion of -// [BetaManagedAgentsSessionEventUnion]. BetaManagedAgentsSessionEventUnionContent +// BetaManagedAgentsSessionEventUnionUsage is an implicit subunion of +// [BetaManagedAgentsSessionEventUnion]. BetaManagedAgentsSessionEventUnionUsage // provides convenient access to the sub-properties of the union. // // For type safety it is recommended to directly use a variant of the // [BetaManagedAgentsSessionEventUnion]. -// -// If the underlying value is not a json object, one of the following properties -// will be valid: OfBetaManagedAgentsUserMessageEventContentArray -// OfBetaManagedAgentsUserCustomToolResultEventContentArray -// OfBetaManagedAgentsTextBlockArray -// OfBetaManagedAgentsAgentMCPToolResultEventContentArray -// OfBetaManagedAgentsAgentToolResultEventContentArray] -type BetaManagedAgentsSessionEventUnionContent struct { - // This field will be present if the value is a - // [[]BetaManagedAgentsUserMessageEventContentUnion] instead of an object. - OfBetaManagedAgentsUserMessageEventContentArray []BetaManagedAgentsUserMessageEventContentUnion `json:",inline"` - // This field will be present if the value is a - // [[]BetaManagedAgentsUserCustomToolResultEventContentUnion] instead of an object. - OfBetaManagedAgentsUserCustomToolResultEventContentArray []BetaManagedAgentsUserCustomToolResultEventContentUnion `json:",inline"` - // This field will be present if the value is a [[]BetaManagedAgentsTextBlock] - // instead of an object. - OfBetaManagedAgentsTextBlockArray []BetaManagedAgentsTextBlock `json:",inline"` - // This field will be present if the value is a - // [[]BetaManagedAgentsAgentMCPToolResultEventContentUnion] instead of an object. - OfBetaManagedAgentsAgentMCPToolResultEventContentArray []BetaManagedAgentsAgentMCPToolResultEventContentUnion `json:",inline"` - // This field will be present if the value is a - // [[]BetaManagedAgentsAgentToolResultEventContentUnion] instead of an object. - OfBetaManagedAgentsAgentToolResultEventContentArray []BetaManagedAgentsAgentToolResultEventContentUnion `json:",inline"` - JSON struct { - OfBetaManagedAgentsUserMessageEventContentArray respjson.Field - OfBetaManagedAgentsUserCustomToolResultEventContentArray respjson.Field - OfBetaManagedAgentsTextBlockArray respjson.Field - OfBetaManagedAgentsAgentMCPToolResultEventContentArray respjson.Field - OfBetaManagedAgentsAgentToolResultEventContentArray respjson.Field - raw string +type BetaManagedAgentsSessionEventUnionUsage struct { + // This field is from variant [BetaManagedAgentsSpanModelUsage]. + CacheCreationInputTokens int64 `json:"cache_creation_input_tokens"` + CacheReadInputTokens int64 `json:"cache_read_input_tokens"` + InputTokens int64 `json:"input_tokens"` + OutputTokens int64 `json:"output_tokens"` + // This field is from variant [BetaManagedAgentsSpanModelUsage]. + Speed BetaManagedAgentsSpanModelUsageSpeed `json:"speed"` + // This field is from variant [BetaManagedAgentsSessionUsageSnapshot]. + ActiveSeconds float64 `json:"active_seconds"` + // This field is from variant [BetaManagedAgentsSessionUsageSnapshot]. + CacheCreation BetaManagedAgentsCacheCreationUsage `json:"cache_creation"` + // This field is from variant [BetaManagedAgentsSessionUsageSnapshot]. + ListCost BetaMonetaryAmount `json:"list_cost"` + // This field is from variant [BetaManagedAgentsSessionUsageSnapshot]. + ServerToolUse BetaManagedAgentsServerToolUsage `json:"server_tool_use"` + JSON struct { + CacheCreationInputTokens respjson.Field + CacheReadInputTokens respjson.Field + InputTokens respjson.Field + OutputTokens respjson.Field + Speed respjson.Field + ActiveSeconds respjson.Field + CacheCreation respjson.Field + ListCost respjson.Field + ServerToolUse respjson.Field + raw string } `json:"-"` } -func (r *BetaManagedAgentsSessionEventUnionContent) UnmarshalJSON(data []byte) error { +func (r *BetaManagedAgentsSessionEventUnionUsage) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } @@ -3039,8 +4382,8 @@ const ( BetaManagedAgentsSessionRequiresActionTypeRequiresAction BetaManagedAgentsSessionRequiresActionType = "requires_action" ) -// The turn ended because the retry budget was exhausted (`max_iterations` hit or -// an error escalated to `retry_status: 'exhausted'`). +// The turn ended because repeated errors exhausted the retry budget or an error +// escalated to `retry_status: 'exhausted'`. type BetaManagedAgentsSessionRetriesExhausted struct { // Any of "retries_exhausted". Type BetaManagedAgentsSessionRetriesExhaustedType `json:"type" api:"required"` @@ -3094,14 +4437,15 @@ func (r *BetaManagedAgentsSessionStatusIdleEvent) UnmarshalJSON(data []byte) err // BetaManagedAgentsSessionStatusIdleEventStopReasonUnion contains all possible // properties and values from [BetaManagedAgentsSessionEndTurn], // [BetaManagedAgentsSessionRequiresAction], -// [BetaManagedAgentsSessionRetriesExhausted]. +// [BetaManagedAgentsSessionRetriesExhausted], +// [BetaManagedAgentsSessionBudgetReached]. // // Use the [BetaManagedAgentsSessionStatusIdleEventStopReasonUnion.AsAny] method to // switch on the variant. // // Use the methods beginning with 'As' to cast the union to one of its variants. type BetaManagedAgentsSessionStatusIdleEventStopReasonUnion struct { - // Any of "end_turn", "requires_action", "retries_exhausted". + // Any of "end_turn", "requires_action", "retries_exhausted", "budget_reached". Type string `json:"type"` // This field is from variant [BetaManagedAgentsSessionRequiresAction]. EventIDs []string `json:"event_ids"` @@ -3125,6 +4469,8 @@ func (BetaManagedAgentsSessionRequiresAction) implBetaManagedAgentsSessionStatus } func (BetaManagedAgentsSessionRetriesExhausted) implBetaManagedAgentsSessionStatusIdleEventStopReasonUnion() { } +func (BetaManagedAgentsSessionBudgetReached) implBetaManagedAgentsSessionStatusIdleEventStopReasonUnion() { +} // Use the following switch statement to find the correct variant // @@ -3132,6 +4478,7 @@ func (BetaManagedAgentsSessionRetriesExhausted) implBetaManagedAgentsSessionStat // case anthropic.BetaManagedAgentsSessionEndTurn: // case anthropic.BetaManagedAgentsSessionRequiresAction: // case anthropic.BetaManagedAgentsSessionRetriesExhausted: +// case anthropic.BetaManagedAgentsSessionBudgetReached: // default: // fmt.Errorf("no variant present") // } @@ -3143,6 +4490,8 @@ func (u BetaManagedAgentsSessionStatusIdleEventStopReasonUnion) AsAny() anyBetaM return u.AsRequiresAction() case "retries_exhausted": return u.AsRetriesExhausted() + case "budget_reached": + return u.AsBudgetReached() } return nil } @@ -3162,6 +4511,11 @@ func (u BetaManagedAgentsSessionStatusIdleEventStopReasonUnion) AsRetriesExhaust return } +func (u BetaManagedAgentsSessionStatusIdleEventStopReasonUnion) AsBudgetReached() (v BetaManagedAgentsSessionBudgetReached) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + // Returns the unmodified JSON received from the API func (u BetaManagedAgentsSessionStatusIdleEventStopReasonUnion) RawJSON() string { return u.JSON.raw } @@ -3195,77 +4549,396 @@ type BetaManagedAgentsSessionStatusRescheduledEvent struct { } // Returns the unmodified JSON received from the API -func (r BetaManagedAgentsSessionStatusRescheduledEvent) RawJSON() string { return r.JSON.raw } -func (r *BetaManagedAgentsSessionStatusRescheduledEvent) UnmarshalJSON(data []byte) error { +func (r BetaManagedAgentsSessionStatusRescheduledEvent) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsSessionStatusRescheduledEvent) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsSessionStatusRescheduledEventType string + +const ( + BetaManagedAgentsSessionStatusRescheduledEventTypeSessionStatusRescheduled BetaManagedAgentsSessionStatusRescheduledEventType = "session.status_rescheduled" +) + +// Indicates the session is actively running and the agent is working. +type BetaManagedAgentsSessionStatusRunningEvent struct { + // Unique identifier for this event. + ID string `json:"id" api:"required"` + // A timestamp in RFC 3339 format + ProcessedAt time.Time `json:"processed_at" api:"required" format:"date-time"` + // Any of "session.status_running". + Type BetaManagedAgentsSessionStatusRunningEventType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + ProcessedAt respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsSessionStatusRunningEvent) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsSessionStatusRunningEvent) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsSessionStatusRunningEventType string + +const ( + BetaManagedAgentsSessionStatusRunningEventTypeSessionStatusRunning BetaManagedAgentsSessionStatusRunningEventType = "session.status_running" +) + +// Indicates the session has terminated, either due to an error or completion. +type BetaManagedAgentsSessionStatusTerminatedEvent struct { + // Unique identifier for this event. + ID string `json:"id" api:"required"` + // A timestamp in RFC 3339 format + ProcessedAt time.Time `json:"processed_at" api:"required" format:"date-time"` + // Any of "session.status_terminated". + Type BetaManagedAgentsSessionStatusTerminatedEventType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + ProcessedAt respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsSessionStatusTerminatedEvent) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsSessionStatusTerminatedEvent) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsSessionStatusTerminatedEventType string + +const ( + BetaManagedAgentsSessionStatusTerminatedEventTypeSessionStatusTerminated BetaManagedAgentsSessionStatusTerminatedEventType = "session.status_terminated" +) + +// Emitted when a subagent is spawned as a new thread. Written to the parent +// thread's output stream so clients observing the session see child creation. +type BetaManagedAgentsSessionThreadCreatedEvent struct { + // Unique identifier for this event. + ID string `json:"id" api:"required"` + // Name of the callable agent the thread runs. + AgentName string `json:"agent_name" api:"required"` + // A timestamp in RFC 3339 format + ProcessedAt time.Time `json:"processed_at" api:"required" format:"date-time"` + // Public `sthr_` ID of the newly created thread. + SessionThreadID string `json:"session_thread_id" api:"required"` + // Any of "session.thread_created". + Type BetaManagedAgentsSessionThreadCreatedEventType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + AgentName respjson.Field + ProcessedAt respjson.Field + SessionThreadID respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsSessionThreadCreatedEvent) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsSessionThreadCreatedEvent) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsSessionThreadCreatedEventType string + +const ( + BetaManagedAgentsSessionThreadCreatedEventTypeSessionThreadCreated BetaManagedAgentsSessionThreadCreatedEventType = "session.thread_created" +) + +// A session thread has yielded and is awaiting input. Emitted on the thread's own +// stream and cross-posted to the primary stream for child threads. +type BetaManagedAgentsSessionThreadStatusIdleEvent struct { + // Unique identifier for this event. + ID string `json:"id" api:"required"` + // Name of the agent the thread runs. + AgentName string `json:"agent_name" api:"required"` + // A timestamp in RFC 3339 format + ProcessedAt time.Time `json:"processed_at" api:"required" format:"date-time"` + // Public sthr\_ ID of the thread that went idle. + SessionThreadID string `json:"session_thread_id" api:"required"` + // The agent completed its turn naturally and is ready for the next user message. + StopReason BetaManagedAgentsSessionThreadStatusIdleEventStopReasonUnion `json:"stop_reason" api:"required"` + // Any of "session.thread_status_idle". + Type BetaManagedAgentsSessionThreadStatusIdleEventType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + AgentName respjson.Field + ProcessedAt respjson.Field + SessionThreadID respjson.Field + StopReason respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsSessionThreadStatusIdleEvent) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsSessionThreadStatusIdleEvent) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaManagedAgentsSessionThreadStatusIdleEventStopReasonUnion contains all +// possible properties and values from [BetaManagedAgentsSessionEndTurn], +// [BetaManagedAgentsSessionRequiresAction], +// [BetaManagedAgentsSessionRetriesExhausted], +// [BetaManagedAgentsSessionBudgetReached]. +// +// Use the [BetaManagedAgentsSessionThreadStatusIdleEventStopReasonUnion.AsAny] +// method to switch on the variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaManagedAgentsSessionThreadStatusIdleEventStopReasonUnion struct { + // Any of "end_turn", "requires_action", "retries_exhausted", "budget_reached". + Type string `json:"type"` + // This field is from variant [BetaManagedAgentsSessionRequiresAction]. + EventIDs []string `json:"event_ids"` + JSON struct { + Type respjson.Field + EventIDs respjson.Field + raw string + } `json:"-"` +} + +// anyBetaManagedAgentsSessionThreadStatusIdleEventStopReason is implemented by +// each variant of [BetaManagedAgentsSessionThreadStatusIdleEventStopReasonUnion] +// to add type safety for the return type of +// [BetaManagedAgentsSessionThreadStatusIdleEventStopReasonUnion.AsAny] +type anyBetaManagedAgentsSessionThreadStatusIdleEventStopReason interface { + implBetaManagedAgentsSessionThreadStatusIdleEventStopReasonUnion() +} + +func (BetaManagedAgentsSessionEndTurn) implBetaManagedAgentsSessionThreadStatusIdleEventStopReasonUnion() { +} +func (BetaManagedAgentsSessionRequiresAction) implBetaManagedAgentsSessionThreadStatusIdleEventStopReasonUnion() { +} +func (BetaManagedAgentsSessionRetriesExhausted) implBetaManagedAgentsSessionThreadStatusIdleEventStopReasonUnion() { +} +func (BetaManagedAgentsSessionBudgetReached) implBetaManagedAgentsSessionThreadStatusIdleEventStopReasonUnion() { +} + +// Use the following switch statement to find the correct variant +// +// switch variant := BetaManagedAgentsSessionThreadStatusIdleEventStopReasonUnion.AsAny().(type) { +// case anthropic.BetaManagedAgentsSessionEndTurn: +// case anthropic.BetaManagedAgentsSessionRequiresAction: +// case anthropic.BetaManagedAgentsSessionRetriesExhausted: +// case anthropic.BetaManagedAgentsSessionBudgetReached: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaManagedAgentsSessionThreadStatusIdleEventStopReasonUnion) AsAny() anyBetaManagedAgentsSessionThreadStatusIdleEventStopReason { + switch u.Type { + case "end_turn": + return u.AsEndTurn() + case "requires_action": + return u.AsRequiresAction() + case "retries_exhausted": + return u.AsRetriesExhausted() + case "budget_reached": + return u.AsBudgetReached() + } + return nil +} + +func (u BetaManagedAgentsSessionThreadStatusIdleEventStopReasonUnion) AsEndTurn() (v BetaManagedAgentsSessionEndTurn) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsSessionThreadStatusIdleEventStopReasonUnion) AsRequiresAction() (v BetaManagedAgentsSessionRequiresAction) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsSessionThreadStatusIdleEventStopReasonUnion) AsRetriesExhausted() (v BetaManagedAgentsSessionRetriesExhausted) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsSessionThreadStatusIdleEventStopReasonUnion) AsBudgetReached() (v BetaManagedAgentsSessionBudgetReached) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u BetaManagedAgentsSessionThreadStatusIdleEventStopReasonUnion) RawJSON() string { + return u.JSON.raw +} + +func (r *BetaManagedAgentsSessionThreadStatusIdleEventStopReasonUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsSessionThreadStatusIdleEventType string + +const ( + BetaManagedAgentsSessionThreadStatusIdleEventTypeSessionThreadStatusIdle BetaManagedAgentsSessionThreadStatusIdleEventType = "session.thread_status_idle" +) + +// A session thread hit a transient error and is retrying automatically. Emitted on +// the thread's own stream and cross-posted to the primary stream for child +// threads. +type BetaManagedAgentsSessionThreadStatusRescheduledEvent struct { + // Unique identifier for this event. + ID string `json:"id" api:"required"` + // Name of the agent the thread runs. + AgentName string `json:"agent_name" api:"required"` + // A timestamp in RFC 3339 format + ProcessedAt time.Time `json:"processed_at" api:"required" format:"date-time"` + // Public sthr\_ ID of the thread that is retrying. + SessionThreadID string `json:"session_thread_id" api:"required"` + // Any of "session.thread_status_rescheduled". + Type BetaManagedAgentsSessionThreadStatusRescheduledEventType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + AgentName respjson.Field + ProcessedAt respjson.Field + SessionThreadID respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsSessionThreadStatusRescheduledEvent) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsSessionThreadStatusRescheduledEvent) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsSessionThreadStatusRescheduledEventType string + +const ( + BetaManagedAgentsSessionThreadStatusRescheduledEventTypeSessionThreadStatusRescheduled BetaManagedAgentsSessionThreadStatusRescheduledEventType = "session.thread_status_rescheduled" +) + +// A session thread has begun executing. Emitted on the thread's own stream and +// cross-posted to the primary stream for child threads. +type BetaManagedAgentsSessionThreadStatusRunningEvent struct { + // Unique identifier for this event. + ID string `json:"id" api:"required"` + // Name of the agent the thread runs. + AgentName string `json:"agent_name" api:"required"` + // A timestamp in RFC 3339 format + ProcessedAt time.Time `json:"processed_at" api:"required" format:"date-time"` + // Public sthr\_ ID of the thread that started running. + SessionThreadID string `json:"session_thread_id" api:"required"` + // Any of "session.thread_status_running". + Type BetaManagedAgentsSessionThreadStatusRunningEventType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + AgentName respjson.Field + ProcessedAt respjson.Field + SessionThreadID respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsSessionThreadStatusRunningEvent) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsSessionThreadStatusRunningEvent) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type BetaManagedAgentsSessionStatusRescheduledEventType string +type BetaManagedAgentsSessionThreadStatusRunningEventType string const ( - BetaManagedAgentsSessionStatusRescheduledEventTypeSessionStatusRescheduled BetaManagedAgentsSessionStatusRescheduledEventType = "session.status_rescheduled" + BetaManagedAgentsSessionThreadStatusRunningEventTypeSessionThreadStatusRunning BetaManagedAgentsSessionThreadStatusRunningEventType = "session.thread_status_running" ) -// Indicates the session is actively running and the agent is working. -type BetaManagedAgentsSessionStatusRunningEvent struct { +// A session thread has terminated and will accept no further input. Emitted on the +// thread's own stream and cross-posted to the primary stream for child threads. +type BetaManagedAgentsSessionThreadStatusTerminatedEvent struct { // Unique identifier for this event. ID string `json:"id" api:"required"` + // Name of the agent the thread runs. + AgentName string `json:"agent_name" api:"required"` // A timestamp in RFC 3339 format ProcessedAt time.Time `json:"processed_at" api:"required" format:"date-time"` - // Any of "session.status_running". - Type BetaManagedAgentsSessionStatusRunningEventType `json:"type" api:"required"` + // Public sthr\_ ID of the thread that terminated. + SessionThreadID string `json:"session_thread_id" api:"required"` + // Any of "session.thread_status_terminated". + Type BetaManagedAgentsSessionThreadStatusTerminatedEventType `json:"type" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { - ID respjson.Field - ProcessedAt respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string + ID respjson.Field + AgentName respjson.Field + ProcessedAt respjson.Field + SessionThreadID respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string } `json:"-"` } // Returns the unmodified JSON received from the API -func (r BetaManagedAgentsSessionStatusRunningEvent) RawJSON() string { return r.JSON.raw } -func (r *BetaManagedAgentsSessionStatusRunningEvent) UnmarshalJSON(data []byte) error { +func (r BetaManagedAgentsSessionThreadStatusTerminatedEvent) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsSessionThreadStatusTerminatedEvent) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type BetaManagedAgentsSessionStatusRunningEventType string +type BetaManagedAgentsSessionThreadStatusTerminatedEventType string const ( - BetaManagedAgentsSessionStatusRunningEventTypeSessionStatusRunning BetaManagedAgentsSessionStatusRunningEventType = "session.status_running" + BetaManagedAgentsSessionThreadStatusTerminatedEventTypeSessionThreadStatusTerminated BetaManagedAgentsSessionThreadStatusTerminatedEventType = "session.thread_status_terminated" ) -// Indicates the session has terminated, either due to an error or completion. -type BetaManagedAgentsSessionStatusTerminatedEvent struct { - // Unique identifier for this event. - ID string `json:"id" api:"required"` - // A timestamp in RFC 3339 format - ProcessedAt time.Time `json:"processed_at" api:"required" format:"date-time"` - // Any of "session.status_terminated". - Type BetaManagedAgentsSessionStatusTerminatedEventType `json:"type" api:"required"` +// Point-in-time snapshot of a session's cumulative usage. +type BetaManagedAgentsSessionUsageSnapshot struct { + // Cumulative time in seconds during which the session had at least one thread in + // running status. Overlapping activity from concurrent threads is counted once. + // This is the duration the session's runtime cost is priced on. + ActiveSeconds float64 `json:"active_seconds"` + // Prompt-cache creation token usage broken down by cache lifetime. + CacheCreation BetaManagedAgentsCacheCreationUsage `json:"cache_creation"` + // Total tokens read from prompt cache. + CacheReadInputTokens int64 `json:"cache_read_input_tokens"` + // Total input tokens consumed across all turns. + InputTokens int64 `json:"input_tokens"` + // A monetary amount in a specific currency. + ListCost BetaMonetaryAmount `json:"list_cost"` + // Total output tokens generated across all turns. + OutputTokens int64 `json:"output_tokens"` + // Cumulative count of server-executed tool invocations, broken down by tool. + ServerToolUse BetaManagedAgentsServerToolUsage `json:"server_tool_use"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { - ID respjson.Field - ProcessedAt respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string + ActiveSeconds respjson.Field + CacheCreation respjson.Field + CacheReadInputTokens respjson.Field + InputTokens respjson.Field + ListCost respjson.Field + OutputTokens respjson.Field + ServerToolUse respjson.Field + ExtraFields map[string]respjson.Field + raw string } `json:"-"` } // Returns the unmodified JSON received from the API -func (r BetaManagedAgentsSessionStatusTerminatedEvent) RawJSON() string { return r.JSON.raw } -func (r *BetaManagedAgentsSessionStatusTerminatedEvent) UnmarshalJSON(data []byte) error { +func (r BetaManagedAgentsSessionUsageSnapshot) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsSessionUsageSnapshot) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type BetaManagedAgentsSessionStatusTerminatedEventType string - -const ( - BetaManagedAgentsSessionStatusTerminatedEventTypeSessionStatusTerminated BetaManagedAgentsSessionStatusTerminatedEventType = "session.status_terminated" -) - // Emitted when a model request completes. type BetaManagedAgentsSpanModelRequestEndEvent struct { // Unique identifier for this event. @@ -3379,6 +5052,142 @@ const ( BetaManagedAgentsSpanModelUsageSpeedFast BetaManagedAgentsSpanModelUsageSpeed = "fast" ) +// Emitted when an outcome evaluation cycle completes. Carries the verdict and +// aggregate token usage. A verdict of `needs_revision` means another evaluation +// cycle follows; `satisfied`, `max_iterations_reached`, `failed`, or `interrupted` +// are terminal — no further evaluation cycles follow. +type BetaManagedAgentsSpanOutcomeEvaluationEndEvent struct { + // Unique identifier for this event. + ID string `json:"id" api:"required"` + // Human-readable explanation of the verdict. For `needs_revision`, describes which + // criteria failed and why. + Explanation string `json:"explanation" api:"required"` + // 0-indexed revision cycle, matching the corresponding + // `span.outcome_evaluation_start`. + Iteration int64 `json:"iteration" api:"required"` + // The id of the corresponding `span.outcome_evaluation_start` event. + OutcomeEvaluationStartID string `json:"outcome_evaluation_start_id" api:"required"` + // The `outc_` ID of the outcome being evaluated. + OutcomeID string `json:"outcome_id" api:"required"` + // A timestamp in RFC 3339 format + ProcessedAt time.Time `json:"processed_at" api:"required" format:"date-time"` + // Evaluation verdict. 'satisfied': criteria met, session goes idle. + // 'needs_revision': criteria not met, another revision cycle follows. + // 'max_iterations_reached': evaluation budget exhausted with criteria still unmet + // — one final acknowledgment turn follows before the session goes idle, but no + // further evaluation runs. 'failed': grader determined the rubric does not apply + // to the deliverables. 'interrupted': user sent an interrupt while evaluation was + // in progress. + Result string `json:"result" api:"required"` + // Any of "span.outcome_evaluation_end". + Type BetaManagedAgentsSpanOutcomeEvaluationEndEventType `json:"type" api:"required"` + // Token usage for a single model request. + Usage BetaManagedAgentsSpanModelUsage `json:"usage" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + Explanation respjson.Field + Iteration respjson.Field + OutcomeEvaluationStartID respjson.Field + OutcomeID respjson.Field + ProcessedAt respjson.Field + Result respjson.Field + Type respjson.Field + Usage respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsSpanOutcomeEvaluationEndEvent) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsSpanOutcomeEvaluationEndEvent) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsSpanOutcomeEvaluationEndEventType string + +const ( + BetaManagedAgentsSpanOutcomeEvaluationEndEventTypeSpanOutcomeEvaluationEnd BetaManagedAgentsSpanOutcomeEvaluationEndEventType = "span.outcome_evaluation_end" +) + +// Periodic heartbeat emitted while an outcome evaluation cycle is in progress. +// Distinguishes 'evaluation is actively running' from 'evaluation is stuck' +// between the corresponding `span.outcome_evaluation_start` and +// `span.outcome_evaluation_end` events. +type BetaManagedAgentsSpanOutcomeEvaluationOngoingEvent struct { + // Unique identifier for this event. + ID string `json:"id" api:"required"` + // 0-indexed revision cycle, matching the corresponding + // `span.outcome_evaluation_start`. + Iteration int64 `json:"iteration" api:"required"` + // The `outc_` ID of the outcome being evaluated. + OutcomeID string `json:"outcome_id" api:"required"` + // A timestamp in RFC 3339 format + ProcessedAt time.Time `json:"processed_at" api:"required" format:"date-time"` + // Any of "span.outcome_evaluation_ongoing". + Type BetaManagedAgentsSpanOutcomeEvaluationOngoingEventType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + Iteration respjson.Field + OutcomeID respjson.Field + ProcessedAt respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsSpanOutcomeEvaluationOngoingEvent) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsSpanOutcomeEvaluationOngoingEvent) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsSpanOutcomeEvaluationOngoingEventType string + +const ( + BetaManagedAgentsSpanOutcomeEvaluationOngoingEventTypeSpanOutcomeEvaluationOngoing BetaManagedAgentsSpanOutcomeEvaluationOngoingEventType = "span.outcome_evaluation_ongoing" +) + +// Emitted when an outcome evaluation cycle begins. +type BetaManagedAgentsSpanOutcomeEvaluationStartEvent struct { + // Unique identifier for this event. + ID string `json:"id" api:"required"` + // 0-indexed revision cycle. 0 is the first evaluation; 1 is the re-evaluation + // after the first revision; etc. + Iteration int64 `json:"iteration" api:"required"` + // The `outc_` ID of the outcome being evaluated. + OutcomeID string `json:"outcome_id" api:"required"` + // A timestamp in RFC 3339 format + ProcessedAt time.Time `json:"processed_at" api:"required" format:"date-time"` + // Any of "span.outcome_evaluation_start". + Type BetaManagedAgentsSpanOutcomeEvaluationStartEventType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + Iteration respjson.Field + OutcomeID respjson.Field + ProcessedAt respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsSpanOutcomeEvaluationStartEvent) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsSpanOutcomeEvaluationStartEvent) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsSpanOutcomeEvaluationStartEventType string + +const ( + BetaManagedAgentsSpanOutcomeEvaluationStartEventTypeSpanOutcomeEvaluationStart BetaManagedAgentsSpanOutcomeEvaluationStartEventType = "span.outcome_evaluation_start" +) + // BetaManagedAgentsStreamSessionEventsUnion contains all possible properties and // values from [BetaManagedAgentsUserMessageEvent], // [BetaManagedAgentsUserInterruptEvent], @@ -3389,15 +5198,30 @@ const ( // [BetaManagedAgentsAgentMCPToolUseEvent], // [BetaManagedAgentsAgentMCPToolResultEvent], // [BetaManagedAgentsAgentToolUseEvent], [BetaManagedAgentsAgentToolResultEvent], +// [BetaManagedAgentsAgentThreadMessageReceivedEvent], +// [BetaManagedAgentsAgentThreadMessageSentEvent], // [BetaManagedAgentsAgentThreadContextCompactedEvent], // [BetaManagedAgentsSessionErrorEvent], // [BetaManagedAgentsSessionStatusRescheduledEvent], // [BetaManagedAgentsSessionStatusRunningEvent], // [BetaManagedAgentsSessionStatusIdleEvent], // [BetaManagedAgentsSessionStatusTerminatedEvent], +// [BetaManagedAgentsSessionThreadCreatedEvent], +// [BetaManagedAgentsSpanOutcomeEvaluationStartEvent], +// [BetaManagedAgentsSpanOutcomeEvaluationEndEvent], // [BetaManagedAgentsSpanModelRequestStartEvent], // [BetaManagedAgentsSpanModelRequestEndEvent], -// [BetaManagedAgentsSessionDeletedEvent]. +// [BetaManagedAgentsSpanOutcomeEvaluationOngoingEvent], +// [BetaManagedAgentsUserDefineOutcomeEvent], +// [BetaManagedAgentsSessionDeletedEvent], +// [BetaManagedAgentsSessionThreadStatusRunningEvent], +// [BetaManagedAgentsSessionThreadStatusIdleEvent], +// [BetaManagedAgentsSessionThreadStatusTerminatedEvent], +// [BetaManagedAgentsUserToolResultEvent], +// [BetaManagedAgentsSessionThreadStatusRescheduledEvent], +// [BetaManagedAgentsSessionUpdatedEvent], [BetaManagedAgentsStartEvent], +// [BetaManagedAgentsDeltaEvent], [BetaManagedAgentsSystemMessageEvent], +// [BetaManagedAgentsSessionUsageEvent]. // // Use the [BetaManagedAgentsStreamSessionEventsUnion.AsAny] method to switch on // the variant. @@ -3407,22 +5231,33 @@ type BetaManagedAgentsStreamSessionEventsUnion struct { ID string `json:"id"` // This field is a union of [[]BetaManagedAgentsUserMessageEventContentUnion], // [[]BetaManagedAgentsUserCustomToolResultEventContentUnion], - // [[]BetaManagedAgentsTextBlock], + // [[]BetaManagedAgentsAgentMessageEventContentUnion], // [[]BetaManagedAgentsAgentMCPToolResultEventContentUnion], - // [[]BetaManagedAgentsAgentToolResultEventContentUnion] + // [[]BetaManagedAgentsAgentToolResultEventContentUnion], + // [[]BetaManagedAgentsAgentThreadMessageReceivedEventContentUnion], + // [[]BetaManagedAgentsAgentThreadMessageSentEventContentUnion], + // [[]BetaManagedAgentsUserToolResultEventContentUnion], + // [[]BetaManagedAgentsSystemContentBlock] Content BetaManagedAgentsStreamSessionEventsUnionContent `json:"content"` // Any of "user.message", "user.interrupt", "user.tool_confirmation", // "user.custom_tool_result", "agent.custom_tool_use", "agent.message", // "agent.thinking", "agent.mcp_tool_use", "agent.mcp_tool_result", - // "agent.tool_use", "agent.tool_result", "agent.thread_context_compacted", - // "session.error", "session.status_rescheduled", "session.status_running", - // "session.status_idle", "session.status_terminated", "span.model_request_start", - // "span.model_request_end", "session.deleted". - Type string `json:"type"` - ProcessedAt time.Time `json:"processed_at"` - // This field is from variant [BetaManagedAgentsUserToolConfirmationEvent]. - Result BetaManagedAgentsUserToolConfirmationEventResult `json:"result"` - ToolUseID string `json:"tool_use_id"` + // "agent.tool_use", "agent.tool_result", "agent.thread_message_received", + // "agent.thread_message_sent", "agent.thread_context_compacted", "session.error", + // "session.status_rescheduled", "session.status_running", "session.status_idle", + // "session.status_terminated", "session.thread_created", + // "span.outcome_evaluation_start", "span.outcome_evaluation_end", + // "span.model_request_start", "span.model_request_end", + // "span.outcome_evaluation_ongoing", "user.define_outcome", "session.deleted", + // "session.thread_status_running", "session.thread_status_idle", + // "session.thread_status_terminated", "user.tool_result", + // "session.thread_status_rescheduled", "session.updated", "event_start", + // "event_delta", "system.message", "session.usage". + Type string `json:"type"` + ProcessedAt time.Time `json:"processed_at"` + SessionThreadID string `json:"session_thread_id"` + Result string `json:"result"` + ToolUseID string `json:"tool_use_id"` // This field is from variant [BetaManagedAgentsUserToolConfirmationEvent]. DenyMessage string `json:"deny_message"` // This field is from variant [BetaManagedAgentsUserCustomToolResultEvent]. @@ -3435,34 +5270,95 @@ type BetaManagedAgentsStreamSessionEventsUnion struct { EvaluatedPermission string `json:"evaluated_permission"` // This field is from variant [BetaManagedAgentsAgentMCPToolResultEvent]. MCPToolUseID string `json:"mcp_tool_use_id"` + // This field is from variant [BetaManagedAgentsAgentThreadMessageReceivedEvent]. + FromSessionThreadID string `json:"from_session_thread_id"` + // This field is from variant [BetaManagedAgentsAgentThreadMessageReceivedEvent]. + FromAgentName string `json:"from_agent_name"` + // This field is from variant [BetaManagedAgentsAgentThreadMessageSentEvent]. + ToSessionThreadID string `json:"to_session_thread_id"` + // This field is from variant [BetaManagedAgentsAgentThreadMessageSentEvent]. + ToAgentName string `json:"to_agent_name"` // This field is from variant [BetaManagedAgentsSessionErrorEvent]. Error BetaManagedAgentsSessionErrorEventErrorUnion `json:"error"` - // This field is from variant [BetaManagedAgentsSessionStatusIdleEvent]. - StopReason BetaManagedAgentsSessionStatusIdleEventStopReasonUnion `json:"stop_reason"` + // This field is a union of + // [BetaManagedAgentsSessionStatusIdleEventStopReasonUnion], + // [BetaManagedAgentsSessionThreadStatusIdleEventStopReasonUnion] + StopReason BetaManagedAgentsStreamSessionEventsUnionStopReason `json:"stop_reason"` + AgentName string `json:"agent_name"` + Iteration int64 `json:"iteration"` + OutcomeID string `json:"outcome_id"` + // This field is from variant [BetaManagedAgentsSpanOutcomeEvaluationEndEvent]. + Explanation string `json:"explanation"` + // This field is from variant [BetaManagedAgentsSpanOutcomeEvaluationEndEvent]. + OutcomeEvaluationStartID string `json:"outcome_evaluation_start_id"` + // This field is a union of [BetaManagedAgentsSpanModelUsage], + // [BetaManagedAgentsSessionUsageSnapshot] + Usage BetaManagedAgentsStreamSessionEventsUnionUsage `json:"usage"` // This field is from variant [BetaManagedAgentsSpanModelRequestEndEvent]. ModelRequestStartID string `json:"model_request_start_id"` // This field is from variant [BetaManagedAgentsSpanModelRequestEndEvent]. ModelUsage BetaManagedAgentsSpanModelUsage `json:"model_usage"` - JSON struct { - ID respjson.Field - Content respjson.Field - Type respjson.Field - ProcessedAt respjson.Field - Result respjson.Field - ToolUseID respjson.Field - DenyMessage respjson.Field - CustomToolUseID respjson.Field - IsError respjson.Field - Input respjson.Field - Name respjson.Field - MCPServerName respjson.Field - EvaluatedPermission respjson.Field - MCPToolUseID respjson.Field - Error respjson.Field - StopReason respjson.Field - ModelRequestStartID respjson.Field - ModelUsage respjson.Field - raw string + // This field is from variant [BetaManagedAgentsUserDefineOutcomeEvent]. + Description string `json:"description"` + // This field is from variant [BetaManagedAgentsUserDefineOutcomeEvent]. + MaxIterations int64 `json:"max_iterations"` + // This field is from variant [BetaManagedAgentsUserDefineOutcomeEvent]. + Rubric BetaManagedAgentsUserDefineOutcomeEventRubricUnion `json:"rubric"` + // This field is from variant [BetaManagedAgentsSessionUpdatedEvent]. + Agent BetaManagedAgentsSessionAgent `json:"agent"` + // This field is from variant [BetaManagedAgentsSessionUpdatedEvent]. + Budget BetaManagedAgentsBudgetLimit `json:"budget"` + // This field is from variant [BetaManagedAgentsSessionUpdatedEvent]. + Metadata map[string]string `json:"metadata"` + // This field is from variant [BetaManagedAgentsSessionUpdatedEvent]. + Title string `json:"title"` + // This field is from variant [BetaManagedAgentsStartEvent]. + Event BetaManagedAgentsStartEventPreviewUnion `json:"event"` + // This field is from variant [BetaManagedAgentsDeltaEvent]. + Delta BetaManagedAgentsDeltaContent `json:"delta"` + // This field is from variant [BetaManagedAgentsDeltaEvent]. + EventID string `json:"event_id"` + JSON struct { + ID respjson.Field + Content respjson.Field + Type respjson.Field + ProcessedAt respjson.Field + SessionThreadID respjson.Field + Result respjson.Field + ToolUseID respjson.Field + DenyMessage respjson.Field + CustomToolUseID respjson.Field + IsError respjson.Field + Input respjson.Field + Name respjson.Field + MCPServerName respjson.Field + EvaluatedPermission respjson.Field + MCPToolUseID respjson.Field + FromSessionThreadID respjson.Field + FromAgentName respjson.Field + ToSessionThreadID respjson.Field + ToAgentName respjson.Field + Error respjson.Field + StopReason respjson.Field + AgentName respjson.Field + Iteration respjson.Field + OutcomeID respjson.Field + Explanation respjson.Field + OutcomeEvaluationStartID respjson.Field + Usage respjson.Field + ModelRequestStartID respjson.Field + ModelUsage respjson.Field + Description respjson.Field + MaxIterations respjson.Field + Rubric respjson.Field + Agent respjson.Field + Budget respjson.Field + Metadata respjson.Field + Title respjson.Field + Event respjson.Field + Delta respjson.Field + EventID respjson.Field + raw string } `json:"-"` } @@ -3484,6 +5380,9 @@ func (BetaManagedAgentsAgentMCPToolUseEvent) implBetaManagedAgentsStreamSessionE func (BetaManagedAgentsAgentMCPToolResultEvent) implBetaManagedAgentsStreamSessionEventsUnion() {} func (BetaManagedAgentsAgentToolUseEvent) implBetaManagedAgentsStreamSessionEventsUnion() {} func (BetaManagedAgentsAgentToolResultEvent) implBetaManagedAgentsStreamSessionEventsUnion() {} +func (BetaManagedAgentsAgentThreadMessageReceivedEvent) implBetaManagedAgentsStreamSessionEventsUnion() { +} +func (BetaManagedAgentsAgentThreadMessageSentEvent) implBetaManagedAgentsStreamSessionEventsUnion() {} func (BetaManagedAgentsAgentThreadContextCompactedEvent) implBetaManagedAgentsStreamSessionEventsUnion() { } func (BetaManagedAgentsSessionErrorEvent) implBetaManagedAgentsStreamSessionEventsUnion() {} @@ -3493,9 +5392,31 @@ func (BetaManagedAgentsSessionStatusRunningEvent) implBetaManagedAgentsStreamSes func (BetaManagedAgentsSessionStatusIdleEvent) implBetaManagedAgentsStreamSessionEventsUnion() {} func (BetaManagedAgentsSessionStatusTerminatedEvent) implBetaManagedAgentsStreamSessionEventsUnion() { } +func (BetaManagedAgentsSessionThreadCreatedEvent) implBetaManagedAgentsStreamSessionEventsUnion() {} +func (BetaManagedAgentsSpanOutcomeEvaluationStartEvent) implBetaManagedAgentsStreamSessionEventsUnion() { +} +func (BetaManagedAgentsSpanOutcomeEvaluationEndEvent) implBetaManagedAgentsStreamSessionEventsUnion() { +} func (BetaManagedAgentsSpanModelRequestStartEvent) implBetaManagedAgentsStreamSessionEventsUnion() {} func (BetaManagedAgentsSpanModelRequestEndEvent) implBetaManagedAgentsStreamSessionEventsUnion() {} -func (BetaManagedAgentsSessionDeletedEvent) implBetaManagedAgentsStreamSessionEventsUnion() {} +func (BetaManagedAgentsSpanOutcomeEvaluationOngoingEvent) implBetaManagedAgentsStreamSessionEventsUnion() { +} +func (BetaManagedAgentsUserDefineOutcomeEvent) implBetaManagedAgentsStreamSessionEventsUnion() {} +func (BetaManagedAgentsSessionDeletedEvent) implBetaManagedAgentsStreamSessionEventsUnion() {} +func (BetaManagedAgentsSessionThreadStatusRunningEvent) implBetaManagedAgentsStreamSessionEventsUnion() { +} +func (BetaManagedAgentsSessionThreadStatusIdleEvent) implBetaManagedAgentsStreamSessionEventsUnion() { +} +func (BetaManagedAgentsSessionThreadStatusTerminatedEvent) implBetaManagedAgentsStreamSessionEventsUnion() { +} +func (BetaManagedAgentsUserToolResultEvent) implBetaManagedAgentsStreamSessionEventsUnion() {} +func (BetaManagedAgentsSessionThreadStatusRescheduledEvent) implBetaManagedAgentsStreamSessionEventsUnion() { +} +func (BetaManagedAgentsSessionUpdatedEvent) implBetaManagedAgentsStreamSessionEventsUnion() {} +func (BetaManagedAgentsStartEvent) implBetaManagedAgentsStreamSessionEventsUnion() {} +func (BetaManagedAgentsDeltaEvent) implBetaManagedAgentsStreamSessionEventsUnion() {} +func (BetaManagedAgentsSystemMessageEvent) implBetaManagedAgentsStreamSessionEventsUnion() {} +func (BetaManagedAgentsSessionUsageEvent) implBetaManagedAgentsStreamSessionEventsUnion() {} // Use the following switch statement to find the correct variant // @@ -3511,15 +5432,32 @@ func (BetaManagedAgentsSessionDeletedEvent) implBetaManagedAgentsStreamSessionEv // case anthropic.BetaManagedAgentsAgentMCPToolResultEvent: // case anthropic.BetaManagedAgentsAgentToolUseEvent: // case anthropic.BetaManagedAgentsAgentToolResultEvent: +// case anthropic.BetaManagedAgentsAgentThreadMessageReceivedEvent: +// case anthropic.BetaManagedAgentsAgentThreadMessageSentEvent: // case anthropic.BetaManagedAgentsAgentThreadContextCompactedEvent: // case anthropic.BetaManagedAgentsSessionErrorEvent: // case anthropic.BetaManagedAgentsSessionStatusRescheduledEvent: // case anthropic.BetaManagedAgentsSessionStatusRunningEvent: // case anthropic.BetaManagedAgentsSessionStatusIdleEvent: // case anthropic.BetaManagedAgentsSessionStatusTerminatedEvent: +// case anthropic.BetaManagedAgentsSessionThreadCreatedEvent: +// case anthropic.BetaManagedAgentsSpanOutcomeEvaluationStartEvent: +// case anthropic.BetaManagedAgentsSpanOutcomeEvaluationEndEvent: // case anthropic.BetaManagedAgentsSpanModelRequestStartEvent: // case anthropic.BetaManagedAgentsSpanModelRequestEndEvent: +// case anthropic.BetaManagedAgentsSpanOutcomeEvaluationOngoingEvent: +// case anthropic.BetaManagedAgentsUserDefineOutcomeEvent: // case anthropic.BetaManagedAgentsSessionDeletedEvent: +// case anthropic.BetaManagedAgentsSessionThreadStatusRunningEvent: +// case anthropic.BetaManagedAgentsSessionThreadStatusIdleEvent: +// case anthropic.BetaManagedAgentsSessionThreadStatusTerminatedEvent: +// case anthropic.BetaManagedAgentsUserToolResultEvent: +// case anthropic.BetaManagedAgentsSessionThreadStatusRescheduledEvent: +// case anthropic.BetaManagedAgentsSessionUpdatedEvent: +// case anthropic.BetaManagedAgentsStartEvent: +// case anthropic.BetaManagedAgentsDeltaEvent: +// case anthropic.BetaManagedAgentsSystemMessageEvent: +// case anthropic.BetaManagedAgentsSessionUsageEvent: // default: // fmt.Errorf("no variant present") // } @@ -3547,6 +5485,10 @@ func (u BetaManagedAgentsStreamSessionEventsUnion) AsAny() anyBetaManagedAgentsS return u.AsAgentToolUse() case "agent.tool_result": return u.AsAgentToolResult() + case "agent.thread_message_received": + return u.AsAgentThreadMessageReceived() + case "agent.thread_message_sent": + return u.AsAgentThreadMessageSent() case "agent.thread_context_compacted": return u.AsAgentThreadContextCompacted() case "session.error": @@ -3559,12 +5501,42 @@ func (u BetaManagedAgentsStreamSessionEventsUnion) AsAny() anyBetaManagedAgentsS return u.AsSessionStatusIdle() case "session.status_terminated": return u.AsSessionStatusTerminated() + case "session.thread_created": + return u.AsSessionThreadCreated() + case "span.outcome_evaluation_start": + return u.AsSpanOutcomeEvaluationStart() + case "span.outcome_evaluation_end": + return u.AsSpanOutcomeEvaluationEnd() case "span.model_request_start": return u.AsSpanModelRequestStart() case "span.model_request_end": return u.AsSpanModelRequestEnd() + case "span.outcome_evaluation_ongoing": + return u.AsSpanOutcomeEvaluationOngoing() + case "user.define_outcome": + return u.AsUserDefineOutcome() case "session.deleted": return u.AsSessionDeleted() + case "session.thread_status_running": + return u.AsSessionThreadStatusRunning() + case "session.thread_status_idle": + return u.AsSessionThreadStatusIdle() + case "session.thread_status_terminated": + return u.AsSessionThreadStatusTerminated() + case "user.tool_result": + return u.AsUserToolResult() + case "session.thread_status_rescheduled": + return u.AsSessionThreadStatusRescheduled() + case "session.updated": + return u.AsSessionUpdated() + case "event_start": + return u.AsEventStart() + case "event_delta": + return u.AsEventDelta() + case "system.message": + return u.AsSystemMessage() + case "session.usage": + return u.AsSessionUsage() } return nil } @@ -3624,6 +5596,16 @@ func (u BetaManagedAgentsStreamSessionEventsUnion) AsAgentToolResult() (v BetaMa return } +func (u BetaManagedAgentsStreamSessionEventsUnion) AsAgentThreadMessageReceived() (v BetaManagedAgentsAgentThreadMessageReceivedEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsStreamSessionEventsUnion) AsAgentThreadMessageSent() (v BetaManagedAgentsAgentThreadMessageSentEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + func (u BetaManagedAgentsStreamSessionEventsUnion) AsAgentThreadContextCompacted() (v BetaManagedAgentsAgentThreadContextCompactedEvent) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return @@ -3654,6 +5636,21 @@ func (u BetaManagedAgentsStreamSessionEventsUnion) AsSessionStatusTerminated() ( return } +func (u BetaManagedAgentsStreamSessionEventsUnion) AsSessionThreadCreated() (v BetaManagedAgentsSessionThreadCreatedEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsStreamSessionEventsUnion) AsSpanOutcomeEvaluationStart() (v BetaManagedAgentsSpanOutcomeEvaluationStartEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsStreamSessionEventsUnion) AsSpanOutcomeEvaluationEnd() (v BetaManagedAgentsSpanOutcomeEvaluationEndEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + func (u BetaManagedAgentsStreamSessionEventsUnion) AsSpanModelRequestStart() (v BetaManagedAgentsSpanModelRequestStartEvent) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return @@ -3664,62 +5661,239 @@ func (u BetaManagedAgentsStreamSessionEventsUnion) AsSpanModelRequestEnd() (v Be return } +func (u BetaManagedAgentsStreamSessionEventsUnion) AsSpanOutcomeEvaluationOngoing() (v BetaManagedAgentsSpanOutcomeEvaluationOngoingEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsStreamSessionEventsUnion) AsUserDefineOutcome() (v BetaManagedAgentsUserDefineOutcomeEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + func (u BetaManagedAgentsStreamSessionEventsUnion) AsSessionDeleted() (v BetaManagedAgentsSessionDeletedEvent) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return } -// Returns the unmodified JSON received from the API -func (u BetaManagedAgentsStreamSessionEventsUnion) RawJSON() string { return u.JSON.raw } - -func (r *BetaManagedAgentsStreamSessionEventsUnion) UnmarshalJSON(data []byte) error { +func (u BetaManagedAgentsStreamSessionEventsUnion) AsSessionThreadStatusRunning() (v BetaManagedAgentsSessionThreadStatusRunningEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsStreamSessionEventsUnion) AsSessionThreadStatusIdle() (v BetaManagedAgentsSessionThreadStatusIdleEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsStreamSessionEventsUnion) AsSessionThreadStatusTerminated() (v BetaManagedAgentsSessionThreadStatusTerminatedEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsStreamSessionEventsUnion) AsUserToolResult() (v BetaManagedAgentsUserToolResultEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsStreamSessionEventsUnion) AsSessionThreadStatusRescheduled() (v BetaManagedAgentsSessionThreadStatusRescheduledEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsStreamSessionEventsUnion) AsSessionUpdated() (v BetaManagedAgentsSessionUpdatedEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsStreamSessionEventsUnion) AsEventStart() (v BetaManagedAgentsStartEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsStreamSessionEventsUnion) AsEventDelta() (v BetaManagedAgentsDeltaEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsStreamSessionEventsUnion) AsSystemMessage() (v BetaManagedAgentsSystemMessageEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsStreamSessionEventsUnion) AsSessionUsage() (v BetaManagedAgentsSessionUsageEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u BetaManagedAgentsStreamSessionEventsUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaManagedAgentsStreamSessionEventsUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaManagedAgentsStreamSessionEventsUnionContent is an implicit subunion of +// [BetaManagedAgentsStreamSessionEventsUnion]. +// BetaManagedAgentsStreamSessionEventsUnionContent provides convenient access to +// the sub-properties of the union. +// +// For type safety it is recommended to directly use a variant of the +// [BetaManagedAgentsStreamSessionEventsUnion]. +// +// If the underlying value is not a json object, one of the following properties +// will be valid: OfBetaManagedAgentsUserMessageEventContentArray +// OfBetaManagedAgentsUserCustomToolResultEventContentArray +// OfBetaManagedAgentsAgentMessageEventContentArray +// OfBetaManagedAgentsAgentMCPToolResultEventContentArray +// OfBetaManagedAgentsAgentToolResultEventContentArray +// OfBetaManagedAgentsAgentThreadMessageReceivedEventContentArray +// OfBetaManagedAgentsAgentThreadMessageSentEventContentArray +// OfBetaManagedAgentsUserToolResultEventContentArray +// OfBetaManagedAgentsSystemContentBlockArray] +type BetaManagedAgentsStreamSessionEventsUnionContent struct { + // This field will be present if the value is a + // [[]BetaManagedAgentsUserMessageEventContentUnion] instead of an object. + OfBetaManagedAgentsUserMessageEventContentArray []BetaManagedAgentsUserMessageEventContentUnion `json:",inline"` + // This field will be present if the value is a + // [[]BetaManagedAgentsUserCustomToolResultEventContentUnion] instead of an object. + OfBetaManagedAgentsUserCustomToolResultEventContentArray []BetaManagedAgentsUserCustomToolResultEventContentUnion `json:",inline"` + // This field will be present if the value is a + // [[]BetaManagedAgentsAgentMessageEventContentUnion] instead of an object. + OfBetaManagedAgentsAgentMessageEventContentArray []BetaManagedAgentsAgentMessageEventContentUnion `json:",inline"` + // This field will be present if the value is a + // [[]BetaManagedAgentsAgentMCPToolResultEventContentUnion] instead of an object. + OfBetaManagedAgentsAgentMCPToolResultEventContentArray []BetaManagedAgentsAgentMCPToolResultEventContentUnion `json:",inline"` + // This field will be present if the value is a + // [[]BetaManagedAgentsAgentToolResultEventContentUnion] instead of an object. + OfBetaManagedAgentsAgentToolResultEventContentArray []BetaManagedAgentsAgentToolResultEventContentUnion `json:",inline"` + // This field will be present if the value is a + // [[]BetaManagedAgentsAgentThreadMessageReceivedEventContentUnion] instead of an + // object. + OfBetaManagedAgentsAgentThreadMessageReceivedEventContentArray []BetaManagedAgentsAgentThreadMessageReceivedEventContentUnion `json:",inline"` + // This field will be present if the value is a + // [[]BetaManagedAgentsAgentThreadMessageSentEventContentUnion] instead of an + // object. + OfBetaManagedAgentsAgentThreadMessageSentEventContentArray []BetaManagedAgentsAgentThreadMessageSentEventContentUnion `json:",inline"` + // This field will be present if the value is a + // [[]BetaManagedAgentsUserToolResultEventContentUnion] instead of an object. + OfBetaManagedAgentsUserToolResultEventContentArray []BetaManagedAgentsUserToolResultEventContentUnion `json:",inline"` + // This field will be present if the value is a + // [[]BetaManagedAgentsSystemContentBlock] instead of an object. + OfBetaManagedAgentsSystemContentBlockArray []BetaManagedAgentsSystemContentBlock `json:",inline"` + JSON struct { + OfBetaManagedAgentsUserMessageEventContentArray respjson.Field + OfBetaManagedAgentsUserCustomToolResultEventContentArray respjson.Field + OfBetaManagedAgentsAgentMessageEventContentArray respjson.Field + OfBetaManagedAgentsAgentMCPToolResultEventContentArray respjson.Field + OfBetaManagedAgentsAgentToolResultEventContentArray respjson.Field + OfBetaManagedAgentsAgentThreadMessageReceivedEventContentArray respjson.Field + OfBetaManagedAgentsAgentThreadMessageSentEventContentArray respjson.Field + OfBetaManagedAgentsUserToolResultEventContentArray respjson.Field + OfBetaManagedAgentsSystemContentBlockArray respjson.Field + raw string + } `json:"-"` +} + +func (r *BetaManagedAgentsStreamSessionEventsUnionContent) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaManagedAgentsStreamSessionEventsUnionStopReason is an implicit subunion of +// [BetaManagedAgentsStreamSessionEventsUnion]. +// BetaManagedAgentsStreamSessionEventsUnionStopReason provides convenient access +// to the sub-properties of the union. +// +// For type safety it is recommended to directly use a variant of the +// [BetaManagedAgentsStreamSessionEventsUnion]. +type BetaManagedAgentsStreamSessionEventsUnionStopReason struct { + Type string `json:"type"` + // This field is from variant + // [BetaManagedAgentsSessionStatusIdleEventStopReasonUnion], + // [BetaManagedAgentsSessionThreadStatusIdleEventStopReasonUnion]. + EventIDs []string `json:"event_ids"` + JSON struct { + Type respjson.Field + EventIDs respjson.Field + raw string + } `json:"-"` +} + +func (r *BetaManagedAgentsStreamSessionEventsUnionStopReason) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// BetaManagedAgentsStreamSessionEventsUnionContent is an implicit subunion of +// BetaManagedAgentsStreamSessionEventsUnionUsage is an implicit subunion of // [BetaManagedAgentsStreamSessionEventsUnion]. -// BetaManagedAgentsStreamSessionEventsUnionContent provides convenient access to -// the sub-properties of the union. +// BetaManagedAgentsStreamSessionEventsUnionUsage provides convenient access to the +// sub-properties of the union. // // For type safety it is recommended to directly use a variant of the // [BetaManagedAgentsStreamSessionEventsUnion]. -// -// If the underlying value is not a json object, one of the following properties -// will be valid: OfBetaManagedAgentsUserMessageEventContentArray -// OfBetaManagedAgentsUserCustomToolResultEventContentArray -// OfBetaManagedAgentsTextBlockArray -// OfBetaManagedAgentsAgentMCPToolResultEventContentArray -// OfBetaManagedAgentsAgentToolResultEventContentArray] -type BetaManagedAgentsStreamSessionEventsUnionContent struct { - // This field will be present if the value is a - // [[]BetaManagedAgentsUserMessageEventContentUnion] instead of an object. - OfBetaManagedAgentsUserMessageEventContentArray []BetaManagedAgentsUserMessageEventContentUnion `json:",inline"` - // This field will be present if the value is a - // [[]BetaManagedAgentsUserCustomToolResultEventContentUnion] instead of an object. - OfBetaManagedAgentsUserCustomToolResultEventContentArray []BetaManagedAgentsUserCustomToolResultEventContentUnion `json:",inline"` - // This field will be present if the value is a [[]BetaManagedAgentsTextBlock] - // instead of an object. - OfBetaManagedAgentsTextBlockArray []BetaManagedAgentsTextBlock `json:",inline"` - // This field will be present if the value is a - // [[]BetaManagedAgentsAgentMCPToolResultEventContentUnion] instead of an object. - OfBetaManagedAgentsAgentMCPToolResultEventContentArray []BetaManagedAgentsAgentMCPToolResultEventContentUnion `json:",inline"` - // This field will be present if the value is a - // [[]BetaManagedAgentsAgentToolResultEventContentUnion] instead of an object. - OfBetaManagedAgentsAgentToolResultEventContentArray []BetaManagedAgentsAgentToolResultEventContentUnion `json:",inline"` - JSON struct { - OfBetaManagedAgentsUserMessageEventContentArray respjson.Field - OfBetaManagedAgentsUserCustomToolResultEventContentArray respjson.Field - OfBetaManagedAgentsTextBlockArray respjson.Field - OfBetaManagedAgentsAgentMCPToolResultEventContentArray respjson.Field - OfBetaManagedAgentsAgentToolResultEventContentArray respjson.Field - raw string +type BetaManagedAgentsStreamSessionEventsUnionUsage struct { + // This field is from variant [BetaManagedAgentsSpanModelUsage]. + CacheCreationInputTokens int64 `json:"cache_creation_input_tokens"` + CacheReadInputTokens int64 `json:"cache_read_input_tokens"` + InputTokens int64 `json:"input_tokens"` + OutputTokens int64 `json:"output_tokens"` + // This field is from variant [BetaManagedAgentsSpanModelUsage]. + Speed BetaManagedAgentsSpanModelUsageSpeed `json:"speed"` + // This field is from variant [BetaManagedAgentsSessionUsageSnapshot]. + ActiveSeconds float64 `json:"active_seconds"` + // This field is from variant [BetaManagedAgentsSessionUsageSnapshot]. + CacheCreation BetaManagedAgentsCacheCreationUsage `json:"cache_creation"` + // This field is from variant [BetaManagedAgentsSessionUsageSnapshot]. + ListCost BetaMonetaryAmount `json:"list_cost"` + // This field is from variant [BetaManagedAgentsSessionUsageSnapshot]. + ServerToolUse BetaManagedAgentsServerToolUsage `json:"server_tool_use"` + JSON struct { + CacheCreationInputTokens respjson.Field + CacheReadInputTokens respjson.Field + InputTokens respjson.Field + OutputTokens respjson.Field + Speed respjson.Field + ActiveSeconds respjson.Field + CacheCreation respjson.Field + ListCost respjson.Field + ServerToolUse respjson.Field + raw string } `json:"-"` } -func (r *BetaManagedAgentsStreamSessionEventsUnionContent) UnmarshalJSON(data []byte) error { +func (r *BetaManagedAgentsStreamSessionEventsUnionUsage) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Privileged context for the accompanying turn and all subsequent turns, appended +// to the session's system context as a `role: "system"` turn rather than replacing +// the top-level system prompt. At most one per request: it must be the final event +// and immediately follow the `user.message`, `user.tool_result`, or +// `user.custom_tool_result` it accompanies. Only supported on models that accept +// mid-conversation system messages. +// +// The properties Content, Type are required. +type BetaManagedAgentsSystemMessageEventParams struct { + // System content blocks to append. Text-only. + Content []BetaManagedAgentsSystemContentBlockParam `json:"content,omitzero" api:"required"` + // Any of "system.message". + Type BetaManagedAgentsSystemMessageEventParamsType `json:"type,omitzero" api:"required"` + paramObj +} + +func (r BetaManagedAgentsSystemMessageEventParams) MarshalJSON() (data []byte, err error) { + type shadow BetaManagedAgentsSystemMessageEventParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaManagedAgentsSystemMessageEventParams) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } +type BetaManagedAgentsSystemMessageEventParamsType string + +const ( + BetaManagedAgentsSystemMessageEventParamsTypeSystemMessage BetaManagedAgentsSystemMessageEventParamsType = "system.message" +) + // Regular text content. type BetaManagedAgentsTextBlock struct { // The text content. @@ -3776,6 +5950,59 @@ func (r *BetaManagedAgentsTextBlockParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } +// Rubric content provided inline as text. +type BetaManagedAgentsTextRubric struct { + // Rubric content. Plain text or markdown — the grader treats it as freeform text. + Content string `json:"content" api:"required"` + // Any of "text". + Type BetaManagedAgentsTextRubricType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Content respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsTextRubric) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsTextRubric) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsTextRubricType string + +const ( + BetaManagedAgentsTextRubricTypeText BetaManagedAgentsTextRubricType = "text" +) + +// Rubric content provided inline as text. +// +// The properties Content, Type are required. +type BetaManagedAgentsTextRubricParams struct { + // Rubric content. Plain text or markdown — the grader treats it as freeform text. + // Maximum 262144 characters. + Content string `json:"content" api:"required"` + // Any of "text". + Type BetaManagedAgentsTextRubricParamsType `json:"type,omitzero" api:"required"` + paramObj +} + +func (r BetaManagedAgentsTextRubricParams) MarshalJSON() (data []byte, err error) { + type shadow BetaManagedAgentsTextRubricParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaManagedAgentsTextRubricParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsTextRubricParamsType string + +const ( + BetaManagedAgentsTextRubricParamsTypeText BetaManagedAgentsTextRubricParamsType = "text" +) + // An unknown or unexpected error occurred during session execution. A fallback // variant; clients that don't recognize a new error code can match on // `retry_status` and `message` alone. @@ -4008,6 +6235,9 @@ type BetaManagedAgentsUserCustomToolResultEvent struct { IsError bool `json:"is_error" api:"nullable"` // A timestamp in RFC 3339 format ProcessedAt time.Time `json:"processed_at" api:"nullable" format:"date-time"` + // Routes this result to a subagent thread. Copy from the `agent.custom_tool_use` + // event's `session_thread_id`. + SessionThreadID string `json:"session_thread_id" api:"nullable"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ID respjson.Field @@ -4016,6 +6246,7 @@ type BetaManagedAgentsUserCustomToolResultEvent struct { Content respjson.Field IsError respjson.Field ProcessedAt respjson.Field + SessionThreadID respjson.Field ExtraFields map[string]respjson.Field raw string } `json:"-"` @@ -4035,7 +6266,8 @@ const ( // BetaManagedAgentsUserCustomToolResultEventContentUnion contains all possible // properties and values from [BetaManagedAgentsTextBlock], -// [BetaManagedAgentsImageBlock], [BetaManagedAgentsDocumentBlock]. +// [BetaManagedAgentsImageBlock], [BetaManagedAgentsDocumentBlock], +// [BetaManagedAgentsSearchResultBlock]. // // Use the [BetaManagedAgentsUserCustomToolResultEventContentUnion.AsAny] method to // switch on the variant. @@ -4044,22 +6276,27 @@ const ( type BetaManagedAgentsUserCustomToolResultEventContentUnion struct { // This field is from variant [BetaManagedAgentsTextBlock]. Text string `json:"text"` - // Any of "text", "image", "document". + // Any of "text", "image", "document", "search_result". Type string `json:"type"` // This field is a union of [BetaManagedAgentsImageBlockSourceUnion], - // [BetaManagedAgentsDocumentBlockSourceUnion] + // [BetaManagedAgentsDocumentBlockSourceUnion], [string] Source BetaManagedAgentsUserCustomToolResultEventContentUnionSource `json:"source"` // This field is from variant [BetaManagedAgentsDocumentBlock]. Context string `json:"context"` - // This field is from variant [BetaManagedAgentsDocumentBlock]. - Title string `json:"title"` - JSON struct { - Text respjson.Field - Type respjson.Field - Source respjson.Field - Context respjson.Field - Title respjson.Field - raw string + Title string `json:"title"` + // This field is from variant [BetaManagedAgentsSearchResultBlock]. + Citations BetaManagedAgentsSearchResultCitations `json:"citations"` + // This field is from variant [BetaManagedAgentsSearchResultBlock]. + Content []BetaManagedAgentsSearchResultContent `json:"content"` + JSON struct { + Text respjson.Field + Type respjson.Field + Source respjson.Field + Context respjson.Field + Title respjson.Field + Citations respjson.Field + Content respjson.Field + raw string } `json:"-"` } @@ -4074,6 +6311,8 @@ type anyBetaManagedAgentsUserCustomToolResultEventContent interface { func (BetaManagedAgentsTextBlock) implBetaManagedAgentsUserCustomToolResultEventContentUnion() {} func (BetaManagedAgentsImageBlock) implBetaManagedAgentsUserCustomToolResultEventContentUnion() {} func (BetaManagedAgentsDocumentBlock) implBetaManagedAgentsUserCustomToolResultEventContentUnion() {} +func (BetaManagedAgentsSearchResultBlock) implBetaManagedAgentsUserCustomToolResultEventContentUnion() { +} // Use the following switch statement to find the correct variant // @@ -4081,6 +6320,7 @@ func (BetaManagedAgentsDocumentBlock) implBetaManagedAgentsUserCustomToolResultE // case anthropic.BetaManagedAgentsTextBlock: // case anthropic.BetaManagedAgentsImageBlock: // case anthropic.BetaManagedAgentsDocumentBlock: +// case anthropic.BetaManagedAgentsSearchResultBlock: // default: // fmt.Errorf("no variant present") // } @@ -4092,6 +6332,8 @@ func (u BetaManagedAgentsUserCustomToolResultEventContentUnion) AsAny() anyBetaM return u.AsImage() case "document": return u.AsDocument() + case "search_result": + return u.AsSearchResult() } return nil } @@ -4111,6 +6353,11 @@ func (u BetaManagedAgentsUserCustomToolResultEventContentUnion) AsDocument() (v return } +func (u BetaManagedAgentsUserCustomToolResultEventContentUnion) AsSearchResult() (v BetaManagedAgentsSearchResultBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + // Returns the unmodified JSON received from the API func (u BetaManagedAgentsUserCustomToolResultEventContentUnion) RawJSON() string { return u.JSON.raw } @@ -4125,13 +6372,19 @@ func (r *BetaManagedAgentsUserCustomToolResultEventContentUnion) UnmarshalJSON(d // // For type safety it is recommended to directly use a variant of the // [BetaManagedAgentsUserCustomToolResultEventContentUnion]. +// +// If the underlying value is not a json object, one of the following properties +// will be valid: OfString] type BetaManagedAgentsUserCustomToolResultEventContentUnionSource struct { + // This field will be present if the value is a [string] instead of an object. + OfString string `json:",inline"` Data string `json:"data"` MediaType string `json:"media_type"` Type string `json:"type"` URL string `json:"url"` FileID string `json:"file_id"` JSON struct { + OfString respjson.Field Data respjson.Field MediaType respjson.Field Type respjson.Field @@ -4181,14 +6434,15 @@ const ( // // Use [param.IsOmitted] to confirm if a field is set. type BetaManagedAgentsUserCustomToolResultEventParamsContentUnion struct { - OfText *BetaManagedAgentsTextBlockParam `json:",omitzero,inline"` - OfImage *BetaManagedAgentsImageBlockParam `json:",omitzero,inline"` - OfDocument *BetaManagedAgentsDocumentBlockParam `json:",omitzero,inline"` + OfText *BetaManagedAgentsTextBlockParam `json:",omitzero,inline"` + OfImage *BetaManagedAgentsImageBlockParam `json:",omitzero,inline"` + OfDocument *BetaManagedAgentsDocumentBlockParam `json:",omitzero,inline"` + OfSearchResult *BetaManagedAgentsSearchResultBlockParam `json:",omitzero,inline"` paramUnion } func (u BetaManagedAgentsUserCustomToolResultEventParamsContentUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfText, u.OfImage, u.OfDocument) + return param.MarshalUnion(u, u.OfText, u.OfImage, u.OfDocument, u.OfSearchResult) } func (u *BetaManagedAgentsUserCustomToolResultEventParamsContentUnion) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, u) @@ -4201,6 +6455,8 @@ func (u *BetaManagedAgentsUserCustomToolResultEventParamsContentUnion) asAny() a return u.OfImage } else if !param.IsOmitted(u.OfDocument) { return u.OfDocument + } else if !param.IsOmitted(u.OfSearchResult) { + return u.OfSearchResult } return nil } @@ -4222,9 +6478,17 @@ func (u BetaManagedAgentsUserCustomToolResultEventParamsContentUnion) GetContext } // Returns a pointer to the underlying variant's property, if present. -func (u BetaManagedAgentsUserCustomToolResultEventParamsContentUnion) GetTitle() *string { - if vt := u.OfDocument; vt != nil && vt.Title.Valid() { - return &vt.Title.Value +func (u BetaManagedAgentsUserCustomToolResultEventParamsContentUnion) GetCitations() *BetaManagedAgentsSearchResultCitationsParam { + if vt := u.OfSearchResult; vt != nil { + return &vt.Citations + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaManagedAgentsUserCustomToolResultEventParamsContentUnion) GetContent() []BetaManagedAgentsSearchResultContentParam { + if vt := u.OfSearchResult; vt != nil { + return vt.Content } return nil } @@ -4237,6 +6501,18 @@ func (u BetaManagedAgentsUserCustomToolResultEventParamsContentUnion) GetType() return (*string)(&vt.Type) } else if vt := u.OfDocument; vt != nil { return (*string)(&vt.Type) + } else if vt := u.OfSearchResult; vt != nil { + return (*string)(&vt.Type) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaManagedAgentsUserCustomToolResultEventParamsContentUnion) GetTitle() *string { + if vt := u.OfDocument; vt != nil && vt.Title.Valid() { + return &vt.Title.Value + } else if vt := u.OfSearchResult; vt != nil { + return (*string)(&vt.Title) } return nil } @@ -4249,6 +6525,8 @@ func (u BetaManagedAgentsUserCustomToolResultEventParamsContentUnion) GetSource( res.any = vt.Source.asAny() } else if vt := u.OfDocument; vt != nil { res.any = vt.Source.asAny() + } else if vt := u.OfSearchResult; vt != nil { + res.any = &vt.Source } return } @@ -4259,7 +6537,7 @@ func (u BetaManagedAgentsUserCustomToolResultEventParamsContentUnion) GetSource( // [*BetaManagedAgentsBase64DocumentSourceParam], // [*BetaManagedAgentsPlainTextDocumentSourceParam], // [*BetaManagedAgentsURLDocumentSourceParam], -// [*BetaManagedAgentsFileDocumentSourceParam] +// [*BetaManagedAgentsFileDocumentSourceParam], [*string] type betaManagedAgentsUserCustomToolResultEventParamsContentUnionSource struct{ any } // Use the following switch statement to get the type of the union: @@ -4272,6 +6550,7 @@ type betaManagedAgentsUserCustomToolResultEventParamsContentUnionSource struct{ // case *anthropic.BetaManagedAgentsPlainTextDocumentSourceParam: // case *anthropic.BetaManagedAgentsURLDocumentSourceParam: // case *anthropic.BetaManagedAgentsFileDocumentSourceParam: +// case *string: // default: // fmt.Errorf("not present") // } @@ -4288,59 +6567,261 @@ func (u betaManagedAgentsUserCustomToolResultEventParamsContentUnionSource) GetD return nil } -// Returns a pointer to the underlying variant's property, if present. -func (u betaManagedAgentsUserCustomToolResultEventParamsContentUnionSource) GetMediaType() *string { - switch vt := u.any.(type) { - case *BetaManagedAgentsImageBlockSourceUnionParam: - return vt.GetMediaType() - case *BetaManagedAgentsDocumentBlockSourceUnionParam: - return vt.GetMediaType() +// Returns a pointer to the underlying variant's property, if present. +func (u betaManagedAgentsUserCustomToolResultEventParamsContentUnionSource) GetMediaType() *string { + switch vt := u.any.(type) { + case *BetaManagedAgentsImageBlockSourceUnionParam: + return vt.GetMediaType() + case *BetaManagedAgentsDocumentBlockSourceUnionParam: + return vt.GetMediaType() + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaManagedAgentsUserCustomToolResultEventParamsContentUnionSource) GetType() *string { + switch vt := u.any.(type) { + case *BetaManagedAgentsImageBlockSourceUnionParam: + return vt.GetType() + case *BetaManagedAgentsDocumentBlockSourceUnionParam: + return vt.GetType() + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaManagedAgentsUserCustomToolResultEventParamsContentUnionSource) GetURL() *string { + switch vt := u.any.(type) { + case *BetaManagedAgentsImageBlockSourceUnionParam: + return vt.GetURL() + case *BetaManagedAgentsDocumentBlockSourceUnionParam: + return vt.GetURL() + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaManagedAgentsUserCustomToolResultEventParamsContentUnionSource) GetFileID() *string { + switch vt := u.any.(type) { + case *BetaManagedAgentsImageBlockSourceUnionParam: + return vt.GetFileID() + case *BetaManagedAgentsDocumentBlockSourceUnionParam: + return vt.GetFileID() + } + return nil +} + +func init() { + apijson.RegisterUnion[BetaManagedAgentsUserCustomToolResultEventParamsContentUnion]( + "type", + apijson.Discriminator[BetaManagedAgentsTextBlockParam]("text"), + apijson.Discriminator[BetaManagedAgentsImageBlockParam]("image"), + apijson.Discriminator[BetaManagedAgentsDocumentBlockParam]("document"), + apijson.Discriminator[BetaManagedAgentsSearchResultBlockParam]("search_result"), + ) +} + +// Echo of a `user.define_outcome` input event. Carries the server-generated +// `outcome_id` that subsequent `span.outcome_evaluation_*` events reference. +type BetaManagedAgentsUserDefineOutcomeEvent struct { + // Unique identifier for this event. + ID string `json:"id" api:"required"` + // What the agent should produce. Copied from the input event. + Description string `json:"description" api:"required"` + // Evaluate-then-revise cycles before giving up. Default 3, max 20. + MaxIterations int64 `json:"max_iterations" api:"required"` + // Server-generated `outc_` ID for this outcome. Referenced by + // `span.outcome_evaluation_*` events and the session's `outcome_evaluations` list. + OutcomeID string `json:"outcome_id" api:"required"` + // A timestamp in RFC 3339 format + ProcessedAt time.Time `json:"processed_at" api:"required" format:"date-time"` + // Rubric for grading the quality of an outcome. + Rubric BetaManagedAgentsUserDefineOutcomeEventRubricUnion `json:"rubric" api:"required"` + // Any of "user.define_outcome". + Type BetaManagedAgentsUserDefineOutcomeEventType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + Description respjson.Field + MaxIterations respjson.Field + OutcomeID respjson.Field + ProcessedAt respjson.Field + Rubric respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsUserDefineOutcomeEvent) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsUserDefineOutcomeEvent) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaManagedAgentsUserDefineOutcomeEventRubricUnion contains all possible +// properties and values from [BetaManagedAgentsFileRubric], +// [BetaManagedAgentsTextRubric]. +// +// Use the [BetaManagedAgentsUserDefineOutcomeEventRubricUnion.AsAny] method to +// switch on the variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaManagedAgentsUserDefineOutcomeEventRubricUnion struct { + // This field is from variant [BetaManagedAgentsFileRubric]. + FileID string `json:"file_id"` + // Any of "file", "text". + Type string `json:"type"` + // This field is from variant [BetaManagedAgentsTextRubric]. + Content string `json:"content"` + JSON struct { + FileID respjson.Field + Type respjson.Field + Content respjson.Field + raw string + } `json:"-"` +} + +// anyBetaManagedAgentsUserDefineOutcomeEventRubric is implemented by each variant +// of [BetaManagedAgentsUserDefineOutcomeEventRubricUnion] to add type safety for +// the return type of [BetaManagedAgentsUserDefineOutcomeEventRubricUnion.AsAny] +type anyBetaManagedAgentsUserDefineOutcomeEventRubric interface { + implBetaManagedAgentsUserDefineOutcomeEventRubricUnion() +} + +func (BetaManagedAgentsFileRubric) implBetaManagedAgentsUserDefineOutcomeEventRubricUnion() {} +func (BetaManagedAgentsTextRubric) implBetaManagedAgentsUserDefineOutcomeEventRubricUnion() {} + +// Use the following switch statement to find the correct variant +// +// switch variant := BetaManagedAgentsUserDefineOutcomeEventRubricUnion.AsAny().(type) { +// case anthropic.BetaManagedAgentsFileRubric: +// case anthropic.BetaManagedAgentsTextRubric: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaManagedAgentsUserDefineOutcomeEventRubricUnion) AsAny() anyBetaManagedAgentsUserDefineOutcomeEventRubric { + switch u.Type { + case "file": + return u.AsFile() + case "text": + return u.AsText() + } + return nil +} + +func (u BetaManagedAgentsUserDefineOutcomeEventRubricUnion) AsFile() (v BetaManagedAgentsFileRubric) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsUserDefineOutcomeEventRubricUnion) AsText() (v BetaManagedAgentsTextRubric) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u BetaManagedAgentsUserDefineOutcomeEventRubricUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaManagedAgentsUserDefineOutcomeEventRubricUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsUserDefineOutcomeEventType string + +const ( + BetaManagedAgentsUserDefineOutcomeEventTypeUserDefineOutcome BetaManagedAgentsUserDefineOutcomeEventType = "user.define_outcome" +) + +// Parameters for defining an outcome the agent should work toward. The agent +// begins work on receipt. +// +// The properties Description, Rubric, Type are required. +type BetaManagedAgentsUserDefineOutcomeEventParams struct { + // What the agent should produce. This is the task specification. + Description string `json:"description" api:"required"` + // Rubric for grading the quality of an outcome. + Rubric BetaManagedAgentsUserDefineOutcomeEventParamsRubricUnion `json:"rubric,omitzero" api:"required"` + // Any of "user.define_outcome". + Type BetaManagedAgentsUserDefineOutcomeEventParamsType `json:"type,omitzero" api:"required"` + // Eval→revision cycles before giving up. Default 3, max 20. + MaxIterations param.Opt[int64] `json:"max_iterations,omitzero"` + paramObj +} + +func (r BetaManagedAgentsUserDefineOutcomeEventParams) MarshalJSON() (data []byte, err error) { + type shadow BetaManagedAgentsUserDefineOutcomeEventParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaManagedAgentsUserDefineOutcomeEventParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaManagedAgentsUserDefineOutcomeEventParamsRubricUnion struct { + OfFile *BetaManagedAgentsFileRubricParams `json:",omitzero,inline"` + OfText *BetaManagedAgentsTextRubricParams `json:",omitzero,inline"` + paramUnion +} + +func (u BetaManagedAgentsUserDefineOutcomeEventParamsRubricUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfFile, u.OfText) +} +func (u *BetaManagedAgentsUserDefineOutcomeEventParamsRubricUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *BetaManagedAgentsUserDefineOutcomeEventParamsRubricUnion) asAny() any { + if !param.IsOmitted(u.OfFile) { + return u.OfFile + } else if !param.IsOmitted(u.OfText) { + return u.OfText } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u betaManagedAgentsUserCustomToolResultEventParamsContentUnionSource) GetType() *string { - switch vt := u.any.(type) { - case *BetaManagedAgentsImageBlockSourceUnionParam: - return vt.GetType() - case *BetaManagedAgentsDocumentBlockSourceUnionParam: - return vt.GetType() +func (u BetaManagedAgentsUserDefineOutcomeEventParamsRubricUnion) GetFileID() *string { + if vt := u.OfFile; vt != nil { + return &vt.FileID } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u betaManagedAgentsUserCustomToolResultEventParamsContentUnionSource) GetURL() *string { - switch vt := u.any.(type) { - case *BetaManagedAgentsImageBlockSourceUnionParam: - return vt.GetURL() - case *BetaManagedAgentsDocumentBlockSourceUnionParam: - return vt.GetURL() +func (u BetaManagedAgentsUserDefineOutcomeEventParamsRubricUnion) GetContent() *string { + if vt := u.OfText; vt != nil { + return &vt.Content } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u betaManagedAgentsUserCustomToolResultEventParamsContentUnionSource) GetFileID() *string { - switch vt := u.any.(type) { - case *BetaManagedAgentsImageBlockSourceUnionParam: - return vt.GetFileID() - case *BetaManagedAgentsDocumentBlockSourceUnionParam: - return vt.GetFileID() +func (u BetaManagedAgentsUserDefineOutcomeEventParamsRubricUnion) GetType() *string { + if vt := u.OfFile; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfText; vt != nil { + return (*string)(&vt.Type) } return nil } func init() { - apijson.RegisterUnion[BetaManagedAgentsUserCustomToolResultEventParamsContentUnion]( + apijson.RegisterUnion[BetaManagedAgentsUserDefineOutcomeEventParamsRubricUnion]( "type", - apijson.Discriminator[BetaManagedAgentsTextBlockParam]("text"), - apijson.Discriminator[BetaManagedAgentsImageBlockParam]("image"), - apijson.Discriminator[BetaManagedAgentsDocumentBlockParam]("document"), + apijson.Discriminator[BetaManagedAgentsFileRubricParams]("file"), + apijson.Discriminator[BetaManagedAgentsTextRubricParams]("text"), ) } +type BetaManagedAgentsUserDefineOutcomeEventParamsType string + +const ( + BetaManagedAgentsUserDefineOutcomeEventParamsTypeUserDefineOutcome BetaManagedAgentsUserDefineOutcomeEventParamsType = "user.define_outcome" +) + // An interrupt event that pauses agent execution and returns control to the user. type BetaManagedAgentsUserInterruptEvent struct { // Unique identifier for this event. @@ -4349,13 +6830,18 @@ type BetaManagedAgentsUserInterruptEvent struct { Type BetaManagedAgentsUserInterruptEventType `json:"type" api:"required"` // A timestamp in RFC 3339 format ProcessedAt time.Time `json:"processed_at" api:"nullable" format:"date-time"` + // If absent, interrupts every non-archived thread in a multiagent session (or the + // primary alone in a single-agent session). If present, interrupts only the named + // thread. + SessionThreadID string `json:"session_thread_id" api:"nullable"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { - ID respjson.Field - Type respjson.Field - ProcessedAt respjson.Field - ExtraFields map[string]respjson.Field - raw string + ID respjson.Field + Type respjson.Field + ProcessedAt respjson.Field + SessionThreadID respjson.Field + ExtraFields map[string]respjson.Field + raw string } `json:"-"` } @@ -4377,6 +6863,10 @@ const ( type BetaManagedAgentsUserInterruptEventParams struct { // Any of "user.interrupt". Type BetaManagedAgentsUserInterruptEventParamsType `json:"type,omitzero" api:"required"` + // If absent, interrupts every non-archived thread in a multiagent session (or the + // primary alone in a single-agent session). If present, interrupts only the named + // thread. + SessionThreadID param.Opt[string] `json:"session_thread_id,omitzero"` paramObj } @@ -4423,7 +6913,7 @@ func (r *BetaManagedAgentsUserMessageEvent) UnmarshalJSON(data []byte) error { // BetaManagedAgentsUserMessageEventContentUnion contains all possible properties // and values from [BetaManagedAgentsTextBlock], [BetaManagedAgentsImageBlock], -// [BetaManagedAgentsDocumentBlock]. +// [BetaManagedAgentsDocumentBlock], [BetaManagedAgentsRedactedBlock]. // // Use the [BetaManagedAgentsUserMessageEventContentUnion.AsAny] method to switch // on the variant. @@ -4432,7 +6922,7 @@ func (r *BetaManagedAgentsUserMessageEvent) UnmarshalJSON(data []byte) error { type BetaManagedAgentsUserMessageEventContentUnion struct { // This field is from variant [BetaManagedAgentsTextBlock]. Text string `json:"text"` - // Any of "text", "image", "document". + // Any of "text", "image", "document", "redacted". Type string `json:"type"` // This field is a union of [BetaManagedAgentsImageBlockSourceUnion], // [BetaManagedAgentsDocumentBlockSourceUnion] @@ -4461,6 +6951,7 @@ type anyBetaManagedAgentsUserMessageEventContent interface { func (BetaManagedAgentsTextBlock) implBetaManagedAgentsUserMessageEventContentUnion() {} func (BetaManagedAgentsImageBlock) implBetaManagedAgentsUserMessageEventContentUnion() {} func (BetaManagedAgentsDocumentBlock) implBetaManagedAgentsUserMessageEventContentUnion() {} +func (BetaManagedAgentsRedactedBlock) implBetaManagedAgentsUserMessageEventContentUnion() {} // Use the following switch statement to find the correct variant // @@ -4468,6 +6959,7 @@ func (BetaManagedAgentsDocumentBlock) implBetaManagedAgentsUserMessageEventConte // case anthropic.BetaManagedAgentsTextBlock: // case anthropic.BetaManagedAgentsImageBlock: // case anthropic.BetaManagedAgentsDocumentBlock: +// case anthropic.BetaManagedAgentsRedactedBlock: // default: // fmt.Errorf("no variant present") // } @@ -4479,6 +6971,8 @@ func (u BetaManagedAgentsUserMessageEventContentUnion) AsAny() anyBetaManagedAge return u.AsImage() case "document": return u.AsDocument() + case "redacted": + return u.AsRedacted() } return nil } @@ -4498,6 +6992,11 @@ func (u BetaManagedAgentsUserMessageEventContentUnion) AsDocument() (v BetaManag return } +func (u BetaManagedAgentsUserMessageEventContentUnion) AsRedacted() (v BetaManagedAgentsRedactedBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + // Returns the unmodified JSON received from the API func (u BetaManagedAgentsUserMessageEventContentUnion) RawJSON() string { return u.JSON.raw } @@ -4564,11 +7063,12 @@ type BetaManagedAgentsUserMessageEventParamsContentUnion struct { OfText *BetaManagedAgentsTextBlockParam `json:",omitzero,inline"` OfImage *BetaManagedAgentsImageBlockParam `json:",omitzero,inline"` OfDocument *BetaManagedAgentsDocumentBlockParam `json:",omitzero,inline"` + OfRedacted *BetaManagedAgentsRedactedBlockParam `json:",omitzero,inline"` paramUnion } func (u BetaManagedAgentsUserMessageEventParamsContentUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfText, u.OfImage, u.OfDocument) + return param.MarshalUnion(u, u.OfText, u.OfImage, u.OfDocument, u.OfRedacted) } func (u *BetaManagedAgentsUserMessageEventParamsContentUnion) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, u) @@ -4581,6 +7081,8 @@ func (u *BetaManagedAgentsUserMessageEventParamsContentUnion) asAny() any { return u.OfImage } else if !param.IsOmitted(u.OfDocument) { return u.OfDocument + } else if !param.IsOmitted(u.OfRedacted) { + return u.OfRedacted } return nil } @@ -4617,6 +7119,8 @@ func (u BetaManagedAgentsUserMessageEventParamsContentUnion) GetType() *string { return (*string)(&vt.Type) } else if vt := u.OfDocument; vt != nil { return (*string)(&vt.Type) + } else if vt := u.OfRedacted; vt != nil { + return (*string)(&vt.Type) } return nil } @@ -4718,6 +7222,7 @@ func init() { apijson.Discriminator[BetaManagedAgentsTextBlockParam]("text"), apijson.Discriminator[BetaManagedAgentsImageBlockParam]("image"), apijson.Discriminator[BetaManagedAgentsDocumentBlockParam]("document"), + apijson.Discriminator[BetaManagedAgentsRedactedBlockParam]("redacted"), ) } @@ -4747,16 +7252,21 @@ type BetaManagedAgentsUserToolConfirmationEvent struct { DenyMessage string `json:"deny_message" api:"nullable"` // A timestamp in RFC 3339 format ProcessedAt time.Time `json:"processed_at" api:"nullable" format:"date-time"` + // When set, the confirmation routes to this subagent's thread rather than the + // primary. Echo this from the `session_thread_id` on the `agent.tool_use` or + // `agent.mcp_tool_use` event that prompted the approval. + SessionThreadID string `json:"session_thread_id" api:"nullable"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { - ID respjson.Field - Result respjson.Field - ToolUseID respjson.Field - Type respjson.Field - DenyMessage respjson.Field - ProcessedAt respjson.Field - ExtraFields map[string]respjson.Field - raw string + ID respjson.Field + Result respjson.Field + ToolUseID respjson.Field + Type respjson.Field + DenyMessage respjson.Field + ProcessedAt respjson.Field + SessionThreadID respjson.Field + ExtraFields map[string]respjson.Field + raw string } `json:"-"` } @@ -4823,16 +7333,256 @@ const ( BetaManagedAgentsUserToolConfirmationEventParamsTypeUserToolConfirmation BetaManagedAgentsUserToolConfirmationEventParamsType = "user.tool_confirmation" ) +// Parameters for providing the result of an agent-toolset tool execution. Only +// valid on `self_hosted` environments, where sandbox-routed tools are executed by +// the client rather than the server. +// +// The properties ToolUseID, Type are required. +type BetaManagedAgentsUserToolResultEventParams struct { + // The id of the `agent.tool_use` event this result corresponds to, which can be + // found in the last `session.status_idle` + // [event's](https://platform.claude.com/docs/en/api/beta/sessions/events/list#beta_managed_agents_session_requires_action.event_ids) + // `stop_reason.event_ids` field. + ToolUseID string `json:"tool_use_id" api:"required"` + // Any of "user.tool_result". + Type BetaManagedAgentsUserToolResultEventParamsType `json:"type,omitzero" api:"required"` + // Whether the tool execution resulted in an error. + IsError param.Opt[bool] `json:"is_error,omitzero"` + // The result content returned by the tool. + Content []BetaManagedAgentsUserToolResultEventParamsContentUnion `json:"content,omitzero"` + paramObj +} + +func (r BetaManagedAgentsUserToolResultEventParams) MarshalJSON() (data []byte, err error) { + type shadow BetaManagedAgentsUserToolResultEventParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaManagedAgentsUserToolResultEventParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsUserToolResultEventParamsType string + +const ( + BetaManagedAgentsUserToolResultEventParamsTypeUserToolResult BetaManagedAgentsUserToolResultEventParamsType = "user.tool_result" +) + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaManagedAgentsUserToolResultEventParamsContentUnion struct { + OfText *BetaManagedAgentsTextBlockParam `json:",omitzero,inline"` + OfImage *BetaManagedAgentsImageBlockParam `json:",omitzero,inline"` + OfDocument *BetaManagedAgentsDocumentBlockParam `json:",omitzero,inline"` + OfSearchResult *BetaManagedAgentsSearchResultBlockParam `json:",omitzero,inline"` + paramUnion +} + +func (u BetaManagedAgentsUserToolResultEventParamsContentUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfText, u.OfImage, u.OfDocument, u.OfSearchResult) +} +func (u *BetaManagedAgentsUserToolResultEventParamsContentUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *BetaManagedAgentsUserToolResultEventParamsContentUnion) asAny() any { + if !param.IsOmitted(u.OfText) { + return u.OfText + } else if !param.IsOmitted(u.OfImage) { + return u.OfImage + } else if !param.IsOmitted(u.OfDocument) { + return u.OfDocument + } else if !param.IsOmitted(u.OfSearchResult) { + return u.OfSearchResult + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaManagedAgentsUserToolResultEventParamsContentUnion) GetText() *string { + if vt := u.OfText; vt != nil { + return &vt.Text + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaManagedAgentsUserToolResultEventParamsContentUnion) GetContext() *string { + if vt := u.OfDocument; vt != nil && vt.Context.Valid() { + return &vt.Context.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaManagedAgentsUserToolResultEventParamsContentUnion) GetCitations() *BetaManagedAgentsSearchResultCitationsParam { + if vt := u.OfSearchResult; vt != nil { + return &vt.Citations + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaManagedAgentsUserToolResultEventParamsContentUnion) GetContent() []BetaManagedAgentsSearchResultContentParam { + if vt := u.OfSearchResult; vt != nil { + return vt.Content + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaManagedAgentsUserToolResultEventParamsContentUnion) GetType() *string { + if vt := u.OfText; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfImage; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfDocument; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfSearchResult; vt != nil { + return (*string)(&vt.Type) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaManagedAgentsUserToolResultEventParamsContentUnion) GetTitle() *string { + if vt := u.OfDocument; vt != nil && vt.Title.Valid() { + return &vt.Title.Value + } else if vt := u.OfSearchResult; vt != nil { + return (*string)(&vt.Title) + } + return nil +} + +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u BetaManagedAgentsUserToolResultEventParamsContentUnion) GetSource() (res betaManagedAgentsUserToolResultEventParamsContentUnionSource) { + if vt := u.OfImage; vt != nil { + res.any = vt.Source.asAny() + } else if vt := u.OfDocument; vt != nil { + res.any = vt.Source.asAny() + } else if vt := u.OfSearchResult; vt != nil { + res.any = &vt.Source + } + return +} + +// Can have the runtime types [*BetaManagedAgentsBase64ImageSourceParam], +// [*BetaManagedAgentsURLImageSourceParam], +// [*BetaManagedAgentsFileImageSourceParam], +// [*BetaManagedAgentsBase64DocumentSourceParam], +// [*BetaManagedAgentsPlainTextDocumentSourceParam], +// [*BetaManagedAgentsURLDocumentSourceParam], +// [*BetaManagedAgentsFileDocumentSourceParam], [*string] +type betaManagedAgentsUserToolResultEventParamsContentUnionSource struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BetaManagedAgentsBase64ImageSourceParam: +// case *anthropic.BetaManagedAgentsURLImageSourceParam: +// case *anthropic.BetaManagedAgentsFileImageSourceParam: +// case *anthropic.BetaManagedAgentsBase64DocumentSourceParam: +// case *anthropic.BetaManagedAgentsPlainTextDocumentSourceParam: +// case *anthropic.BetaManagedAgentsURLDocumentSourceParam: +// case *anthropic.BetaManagedAgentsFileDocumentSourceParam: +// case *string: +// default: +// fmt.Errorf("not present") +// } +func (u betaManagedAgentsUserToolResultEventParamsContentUnionSource) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u betaManagedAgentsUserToolResultEventParamsContentUnionSource) GetData() *string { + switch vt := u.any.(type) { + case *BetaManagedAgentsImageBlockSourceUnionParam: + return vt.GetData() + case *BetaManagedAgentsDocumentBlockSourceUnionParam: + return vt.GetData() + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaManagedAgentsUserToolResultEventParamsContentUnionSource) GetMediaType() *string { + switch vt := u.any.(type) { + case *BetaManagedAgentsImageBlockSourceUnionParam: + return vt.GetMediaType() + case *BetaManagedAgentsDocumentBlockSourceUnionParam: + return vt.GetMediaType() + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaManagedAgentsUserToolResultEventParamsContentUnionSource) GetType() *string { + switch vt := u.any.(type) { + case *BetaManagedAgentsImageBlockSourceUnionParam: + return vt.GetType() + case *BetaManagedAgentsDocumentBlockSourceUnionParam: + return vt.GetType() + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaManagedAgentsUserToolResultEventParamsContentUnionSource) GetURL() *string { + switch vt := u.any.(type) { + case *BetaManagedAgentsImageBlockSourceUnionParam: + return vt.GetURL() + case *BetaManagedAgentsDocumentBlockSourceUnionParam: + return vt.GetURL() + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u betaManagedAgentsUserToolResultEventParamsContentUnionSource) GetFileID() *string { + switch vt := u.any.(type) { + case *BetaManagedAgentsImageBlockSourceUnionParam: + return vt.GetFileID() + case *BetaManagedAgentsDocumentBlockSourceUnionParam: + return vt.GetFileID() + } + return nil +} + +func init() { + apijson.RegisterUnion[BetaManagedAgentsUserToolResultEventParamsContentUnion]( + "type", + apijson.Discriminator[BetaManagedAgentsTextBlockParam]("text"), + apijson.Discriminator[BetaManagedAgentsImageBlockParam]("image"), + apijson.Discriminator[BetaManagedAgentsDocumentBlockParam]("document"), + apijson.Discriminator[BetaManagedAgentsSearchResultBlockParam]("search_result"), + ) +} + type BetaSessionEventListParams struct { + // Return events created after this time (exclusive). Compared against the event's + // `processed_at` value. + CreatedAtGt param.Opt[time.Time] `query:"created_at[gt],omitzero" format:"date-time" json:"-"` + // Return events created at or after this time (inclusive). Compared against the + // event's `processed_at` value. + CreatedAtGte param.Opt[time.Time] `query:"created_at[gte],omitzero" format:"date-time" json:"-"` + // Return events created before this time (exclusive). Compared against the event's + // `processed_at` value. + CreatedAtLt param.Opt[time.Time] `query:"created_at[lt],omitzero" format:"date-time" json:"-"` + // Return events created at or before this time (inclusive). Compared against the + // event's `processed_at` value. + CreatedAtLte param.Opt[time.Time] `query:"created_at[lte],omitzero" format:"date-time" json:"-"` // Query parameter for limit Limit param.Opt[int64] `query:"limit,omitzero" json:"-"` // Opaque pagination cursor from a previous response's next_page. Page param.Opt[string] `query:"page,omitzero" json:"-"` - // Sort direction for results, ordered by created_at. Defaults to asc - // (chronological). + // Sort direction for results, ordered by the event's `processed_at`. Defaults to + // asc (chronological). // // Any of "asc", "desc". Order BetaSessionEventListParamsOrder `query:"order,omitzero" json:"-"` + // Filter by event type. Values match the `type` field on returned events (for + // example, `user.message` or `agent.tool_use`). Omit to return all event types. + Types []string `query:"types,omitzero" json:"-"` // Optional header to specify the beta version(s) you want to use. Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` paramObj @@ -4842,13 +7592,13 @@ type BetaSessionEventListParams struct { // `url.Values`. func (r BetaSessionEventListParams) URLQuery() (v url.Values, err error) { return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ - ArrayFormat: apiquery.ArrayQueryFormatComma, + ArrayFormat: apiquery.ArrayQueryFormatBrackets, NestedFormat: apiquery.NestedQueryFormatBrackets, }) } -// Sort direction for results, ordered by created_at. Defaults to asc -// (chronological). +// Sort direction for results, ordered by the event's `processed_at`. Defaults to +// asc (chronological). type BetaSessionEventListParamsOrder string const ( @@ -4873,7 +7623,27 @@ func (r *BetaSessionEventSendParams) UnmarshalJSON(data []byte) error { } type BetaSessionEventStreamParams struct { + // When set, this connection also receives streaming deltas (`event_start`, + // `event_delta`) while an event is being produced, before the event itself + // arrives. Deltas are best-effort; when the final event is produced it carries the + // complete content. A model request that ends early (an error or interrupt) + // produces no final event — its terminal `span.model_request_end` closes the + // preview. Accepts one or more event types to preview and may be repeated: + // `agent.message` streams `content_delta` fragments; `agent.thinking` is + // start-only — a signal that the agent has begun extended thinking, concluded by + // the `agent.thinking` event itself. Only previews of the requested event types + // are sent. + EventDeltas []BetaManagedAgentsDeltaType `query:"event_deltas,omitzero" json:"-"` // Optional header to specify the beta version(s) you want to use. Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` paramObj } + +// URLQuery serializes [BetaSessionEventStreamParams]'s query parameters as +// `url.Values`. +func (r BetaSessionEventStreamParams) URLQuery() (v url.Values, err error) { + return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ + ArrayFormat: apiquery.ArrayQueryFormatBrackets, + NestedFormat: apiquery.NestedQueryFormatBrackets, + }) +} diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/betasessionresource.go b/vendor/github.com/anthropics/anthropic-sdk-go/betasessionresource.go index f90920629..d9f6f9266 100644 --- a/vendor/github.com/anthropics/anthropic-sdk-go/betasessionresource.go +++ b/vendor/github.com/anthropics/anthropic-sdk-go/betasessionresource.go @@ -314,9 +314,66 @@ func (r *BetaManagedAgentsGitHubRepositoryResourceCheckoutUnion) UnmarshalJSON(d return apijson.UnmarshalRoot(data, r) } +// A memory store attached to an agent session. +type BetaManagedAgentsMemoryStoreResource struct { + // The memory store ID (memstore\_...). Must belong to the caller's organization + // and workspace. + MemoryStoreID string `json:"memory_store_id" api:"required"` + // Any of "memory_store". + Type BetaManagedAgentsMemoryStoreResourceType `json:"type" api:"required"` + // Access mode for an attached memory store. + // + // Any of "read_write", "read_only". + Access BetaManagedAgentsMemoryStoreResourceAccess `json:"access" api:"nullable"` + // Description of the memory store, snapshotted at attach time. Rendered into the + // agent's system prompt. Empty string when the store has no description. + Description string `json:"description"` + // Per-attachment guidance for the agent on how to use this store. Rendered into + // the memory section of the system prompt. Max 4096 chars. + Instructions string `json:"instructions" api:"nullable"` + // Filesystem path where the store is mounted in the session container, e.g. + // /mnt/memory/user-preferences. Derived from the store's name. Output-only. + MountPath string `json:"mount_path" api:"nullable"` + // Display name of the memory store, snapshotted at attach time. Later edits to the + // store's name do not propagate to this resource. + Name string `json:"name" api:"nullable"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + MemoryStoreID respjson.Field + Type respjson.Field + Access respjson.Field + Description respjson.Field + Instructions respjson.Field + MountPath respjson.Field + Name respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsMemoryStoreResource) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsMemoryStoreResource) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsMemoryStoreResourceType string + +const ( + BetaManagedAgentsMemoryStoreResourceTypeMemoryStore BetaManagedAgentsMemoryStoreResourceType = "memory_store" +) + +// Access mode for an attached memory store. +type BetaManagedAgentsMemoryStoreResourceAccess string + +const ( + BetaManagedAgentsMemoryStoreResourceAccessReadWrite BetaManagedAgentsMemoryStoreResourceAccess = "read_write" + BetaManagedAgentsMemoryStoreResourceAccessReadOnly BetaManagedAgentsMemoryStoreResourceAccess = "read_only" +) + // BetaManagedAgentsSessionResourceUnion contains all possible properties and // values from [BetaManagedAgentsGitHubRepositoryResource], -// [BetaManagedAgentsFileResource]. +// [BetaManagedAgentsFileResource], [BetaManagedAgentsMemoryStoreResource]. // // Use the [BetaManagedAgentsSessionResourceUnion.AsAny] method to switch on the // variant. @@ -326,7 +383,7 @@ type BetaManagedAgentsSessionResourceUnion struct { ID string `json:"id"` CreatedAt time.Time `json:"created_at"` MountPath string `json:"mount_path"` - // Any of "github_repository", "file". + // Any of "github_repository", "file", "memory_store". Type string `json:"type"` UpdatedAt time.Time `json:"updated_at"` // This field is from variant [BetaManagedAgentsGitHubRepositoryResource]. @@ -335,16 +392,31 @@ type BetaManagedAgentsSessionResourceUnion struct { Checkout BetaManagedAgentsGitHubRepositoryResourceCheckoutUnion `json:"checkout"` // This field is from variant [BetaManagedAgentsFileResource]. FileID string `json:"file_id"` - JSON struct { - ID respjson.Field - CreatedAt respjson.Field - MountPath respjson.Field - Type respjson.Field - UpdatedAt respjson.Field - URL respjson.Field - Checkout respjson.Field - FileID respjson.Field - raw string + // This field is from variant [BetaManagedAgentsMemoryStoreResource]. + MemoryStoreID string `json:"memory_store_id"` + // This field is from variant [BetaManagedAgentsMemoryStoreResource]. + Access BetaManagedAgentsMemoryStoreResourceAccess `json:"access"` + // This field is from variant [BetaManagedAgentsMemoryStoreResource]. + Description string `json:"description"` + // This field is from variant [BetaManagedAgentsMemoryStoreResource]. + Instructions string `json:"instructions"` + // This field is from variant [BetaManagedAgentsMemoryStoreResource]. + Name string `json:"name"` + JSON struct { + ID respjson.Field + CreatedAt respjson.Field + MountPath respjson.Field + Type respjson.Field + UpdatedAt respjson.Field + URL respjson.Field + Checkout respjson.Field + FileID respjson.Field + MemoryStoreID respjson.Field + Access respjson.Field + Description respjson.Field + Instructions respjson.Field + Name respjson.Field + raw string } `json:"-"` } @@ -357,12 +429,14 @@ type anyBetaManagedAgentsSessionResource interface { func (BetaManagedAgentsGitHubRepositoryResource) implBetaManagedAgentsSessionResourceUnion() {} func (BetaManagedAgentsFileResource) implBetaManagedAgentsSessionResourceUnion() {} +func (BetaManagedAgentsMemoryStoreResource) implBetaManagedAgentsSessionResourceUnion() {} // Use the following switch statement to find the correct variant // // switch variant := BetaManagedAgentsSessionResourceUnion.AsAny().(type) { // case anthropic.BetaManagedAgentsGitHubRepositoryResource: // case anthropic.BetaManagedAgentsFileResource: +// case anthropic.BetaManagedAgentsMemoryStoreResource: // default: // fmt.Errorf("no variant present") // } @@ -372,6 +446,8 @@ func (u BetaManagedAgentsSessionResourceUnion) AsAny() anyBetaManagedAgentsSessi return u.AsGitHubRepository() case "file": return u.AsFile() + case "memory_store": + return u.AsMemoryStore() } return nil } @@ -386,6 +462,11 @@ func (u BetaManagedAgentsSessionResourceUnion) AsFile() (v BetaManagedAgentsFile return } +func (u BetaManagedAgentsSessionResourceUnion) AsMemoryStore() (v BetaManagedAgentsMemoryStoreResource) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + // Returns the unmodified JSON received from the API func (u BetaManagedAgentsSessionResourceUnion) RawJSON() string { return u.JSON.raw } @@ -395,7 +476,7 @@ func (r *BetaManagedAgentsSessionResourceUnion) UnmarshalJSON(data []byte) error // BetaSessionResourceGetResponseUnion contains all possible properties and values // from [BetaManagedAgentsGitHubRepositoryResource], -// [BetaManagedAgentsFileResource]. +// [BetaManagedAgentsFileResource], [BetaManagedAgentsMemoryStoreResource]. // // Use the [BetaSessionResourceGetResponseUnion.AsAny] method to switch on the // variant. @@ -405,7 +486,7 @@ type BetaSessionResourceGetResponseUnion struct { ID string `json:"id"` CreatedAt time.Time `json:"created_at"` MountPath string `json:"mount_path"` - // Any of "github_repository", "file". + // Any of "github_repository", "file", "memory_store". Type string `json:"type"` UpdatedAt time.Time `json:"updated_at"` // This field is from variant [BetaManagedAgentsGitHubRepositoryResource]. @@ -414,16 +495,31 @@ type BetaSessionResourceGetResponseUnion struct { Checkout BetaManagedAgentsGitHubRepositoryResourceCheckoutUnion `json:"checkout"` // This field is from variant [BetaManagedAgentsFileResource]. FileID string `json:"file_id"` - JSON struct { - ID respjson.Field - CreatedAt respjson.Field - MountPath respjson.Field - Type respjson.Field - UpdatedAt respjson.Field - URL respjson.Field - Checkout respjson.Field - FileID respjson.Field - raw string + // This field is from variant [BetaManagedAgentsMemoryStoreResource]. + MemoryStoreID string `json:"memory_store_id"` + // This field is from variant [BetaManagedAgentsMemoryStoreResource]. + Access BetaManagedAgentsMemoryStoreResourceAccess `json:"access"` + // This field is from variant [BetaManagedAgentsMemoryStoreResource]. + Description string `json:"description"` + // This field is from variant [BetaManagedAgentsMemoryStoreResource]. + Instructions string `json:"instructions"` + // This field is from variant [BetaManagedAgentsMemoryStoreResource]. + Name string `json:"name"` + JSON struct { + ID respjson.Field + CreatedAt respjson.Field + MountPath respjson.Field + Type respjson.Field + UpdatedAt respjson.Field + URL respjson.Field + Checkout respjson.Field + FileID respjson.Field + MemoryStoreID respjson.Field + Access respjson.Field + Description respjson.Field + Instructions respjson.Field + Name respjson.Field + raw string } `json:"-"` } @@ -436,12 +532,14 @@ type anyBetaSessionResourceGetResponse interface { func (BetaManagedAgentsGitHubRepositoryResource) implBetaSessionResourceGetResponseUnion() {} func (BetaManagedAgentsFileResource) implBetaSessionResourceGetResponseUnion() {} +func (BetaManagedAgentsMemoryStoreResource) implBetaSessionResourceGetResponseUnion() {} // Use the following switch statement to find the correct variant // // switch variant := BetaSessionResourceGetResponseUnion.AsAny().(type) { // case anthropic.BetaManagedAgentsGitHubRepositoryResource: // case anthropic.BetaManagedAgentsFileResource: +// case anthropic.BetaManagedAgentsMemoryStoreResource: // default: // fmt.Errorf("no variant present") // } @@ -451,6 +549,8 @@ func (u BetaSessionResourceGetResponseUnion) AsAny() anyBetaSessionResourceGetRe return u.AsGitHubRepository() case "file": return u.AsFile() + case "memory_store": + return u.AsMemoryStore() } return nil } @@ -465,6 +565,11 @@ func (u BetaSessionResourceGetResponseUnion) AsFile() (v BetaManagedAgentsFileRe return } +func (u BetaSessionResourceGetResponseUnion) AsMemoryStore() (v BetaManagedAgentsMemoryStoreResource) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + // Returns the unmodified JSON received from the API func (u BetaSessionResourceGetResponseUnion) RawJSON() string { return u.JSON.raw } @@ -474,7 +579,7 @@ func (r *BetaSessionResourceGetResponseUnion) UnmarshalJSON(data []byte) error { // BetaSessionResourceUpdateResponseUnion contains all possible properties and // values from [BetaManagedAgentsGitHubRepositoryResource], -// [BetaManagedAgentsFileResource]. +// [BetaManagedAgentsFileResource], [BetaManagedAgentsMemoryStoreResource]. // // Use the [BetaSessionResourceUpdateResponseUnion.AsAny] method to switch on the // variant. @@ -484,7 +589,7 @@ type BetaSessionResourceUpdateResponseUnion struct { ID string `json:"id"` CreatedAt time.Time `json:"created_at"` MountPath string `json:"mount_path"` - // Any of "github_repository", "file". + // Any of "github_repository", "file", "memory_store". Type string `json:"type"` UpdatedAt time.Time `json:"updated_at"` // This field is from variant [BetaManagedAgentsGitHubRepositoryResource]. @@ -493,16 +598,31 @@ type BetaSessionResourceUpdateResponseUnion struct { Checkout BetaManagedAgentsGitHubRepositoryResourceCheckoutUnion `json:"checkout"` // This field is from variant [BetaManagedAgentsFileResource]. FileID string `json:"file_id"` - JSON struct { - ID respjson.Field - CreatedAt respjson.Field - MountPath respjson.Field - Type respjson.Field - UpdatedAt respjson.Field - URL respjson.Field - Checkout respjson.Field - FileID respjson.Field - raw string + // This field is from variant [BetaManagedAgentsMemoryStoreResource]. + MemoryStoreID string `json:"memory_store_id"` + // This field is from variant [BetaManagedAgentsMemoryStoreResource]. + Access BetaManagedAgentsMemoryStoreResourceAccess `json:"access"` + // This field is from variant [BetaManagedAgentsMemoryStoreResource]. + Description string `json:"description"` + // This field is from variant [BetaManagedAgentsMemoryStoreResource]. + Instructions string `json:"instructions"` + // This field is from variant [BetaManagedAgentsMemoryStoreResource]. + Name string `json:"name"` + JSON struct { + ID respjson.Field + CreatedAt respjson.Field + MountPath respjson.Field + Type respjson.Field + UpdatedAt respjson.Field + URL respjson.Field + Checkout respjson.Field + FileID respjson.Field + MemoryStoreID respjson.Field + Access respjson.Field + Description respjson.Field + Instructions respjson.Field + Name respjson.Field + raw string } `json:"-"` } @@ -515,12 +635,14 @@ type anyBetaSessionResourceUpdateResponse interface { func (BetaManagedAgentsGitHubRepositoryResource) implBetaSessionResourceUpdateResponseUnion() {} func (BetaManagedAgentsFileResource) implBetaSessionResourceUpdateResponseUnion() {} +func (BetaManagedAgentsMemoryStoreResource) implBetaSessionResourceUpdateResponseUnion() {} // Use the following switch statement to find the correct variant // // switch variant := BetaSessionResourceUpdateResponseUnion.AsAny().(type) { // case anthropic.BetaManagedAgentsGitHubRepositoryResource: // case anthropic.BetaManagedAgentsFileResource: +// case anthropic.BetaManagedAgentsMemoryStoreResource: // default: // fmt.Errorf("no variant present") // } @@ -530,6 +652,8 @@ func (u BetaSessionResourceUpdateResponseUnion) AsAny() anyBetaSessionResourceUp return u.AsGitHubRepository() case "file": return u.AsFile() + case "memory_store": + return u.AsMemoryStore() } return nil } @@ -544,6 +668,11 @@ func (u BetaSessionResourceUpdateResponseUnion) AsFile() (v BetaManagedAgentsFil return } +func (u BetaSessionResourceUpdateResponseUnion) AsMemoryStore() (v BetaManagedAgentsMemoryStoreResource) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + // Returns the unmodified JSON received from the API func (u BetaSessionResourceUpdateResponseUnion) RawJSON() string { return u.JSON.raw } @@ -591,7 +720,7 @@ type BetaSessionResourceListParams struct { // `url.Values`. func (r BetaSessionResourceListParams) URLQuery() (v url.Values, err error) { return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ - ArrayFormat: apiquery.ArrayQueryFormatComma, + ArrayFormat: apiquery.ArrayQueryFormatBrackets, NestedFormat: apiquery.NestedQueryFormatBrackets, }) } diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/betasessionthread.go b/vendor/github.com/anthropics/anthropic-sdk-go/betasessionthread.go new file mode 100644 index 000000000..88fabd3b6 --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/betasessionthread.go @@ -0,0 +1,1089 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +package anthropic + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/url" + "slices" + "time" + + "github.com/anthropics/anthropic-sdk-go/internal/apijson" + "github.com/anthropics/anthropic-sdk-go/internal/apiquery" + "github.com/anthropics/anthropic-sdk-go/internal/requestconfig" + "github.com/anthropics/anthropic-sdk-go/option" + "github.com/anthropics/anthropic-sdk-go/packages/pagination" + "github.com/anthropics/anthropic-sdk-go/packages/param" + "github.com/anthropics/anthropic-sdk-go/packages/respjson" +) + +// BetaSessionThreadService contains methods and other services that help with +// interacting with the anthropic API. +// +// Note, unlike clients, this service does not read variables from the environment +// automatically. You should not instantiate this service directly, and instead use +// the [NewBetaSessionThreadService] method instead. +type BetaSessionThreadService struct { + Options []option.RequestOption + Events BetaSessionThreadEventService +} + +// NewBetaSessionThreadService generates a new service that applies the given +// options to each request. These options are applied after the parent client's +// options (if there is one), and before any request-specific options. +func NewBetaSessionThreadService(opts ...option.RequestOption) (r BetaSessionThreadService) { + r = BetaSessionThreadService{} + r.Options = opts + r.Events = NewBetaSessionThreadEventService(opts...) + return +} + +// Get Session Thread +func (r *BetaSessionThreadService) Get(ctx context.Context, threadID string, params BetaSessionThreadGetParams, opts ...option.RequestOption) (res *BetaManagedAgentsSessionThread, err error) { + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "managed-agents-2026-04-01")}, opts...) + if params.SessionID == "" { + err = errors.New("missing required session_id parameter") + return nil, err + } + if threadID == "" { + err = errors.New("missing required thread_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/sessions/%s/threads/%s?beta=true", params.SessionID, threadID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...) + return res, err +} + +// List Session Threads +func (r *BetaSessionThreadService) List(ctx context.Context, sessionID string, params BetaSessionThreadListParams, opts ...option.RequestOption) (res *pagination.PageCursor[BetaManagedAgentsSessionThread], err error) { + var raw *http.Response + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "managed-agents-2026-04-01"), option.WithResponseInto(&raw)}, opts...) + if sessionID == "" { + err = errors.New("missing required session_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/sessions/%s/threads?beta=true", sessionID) + cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, params, &res, opts...) + if err != nil { + return nil, err + } + err = cfg.Execute() + if err != nil { + return nil, err + } + res.SetPageConfig(cfg, raw) + return res, nil +} + +// List Session Threads +func (r *BetaSessionThreadService) ListAutoPaging(ctx context.Context, sessionID string, params BetaSessionThreadListParams, opts ...option.RequestOption) *pagination.PageCursorAutoPager[BetaManagedAgentsSessionThread] { + return pagination.NewPageCursorAutoPager(r.List(ctx, sessionID, params, opts...)) +} + +// Archive Session Thread +func (r *BetaSessionThreadService) Archive(ctx context.Context, threadID string, params BetaSessionThreadArchiveParams, opts ...option.RequestOption) (res *BetaManagedAgentsSessionThread, err error) { + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "managed-agents-2026-04-01")}, opts...) + if params.SessionID == "" { + err = errors.New("missing required session_id parameter") + return nil, err + } + if threadID == "" { + err = errors.New("missing required thread_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/sessions/%s/threads/%s/archive?beta=true", params.SessionID, threadID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, nil, &res, opts...) + return res, err +} + +// An execution thread within a `session`. Each session has one primary thread plus +// zero or more child threads spawned by the coordinator. +type BetaManagedAgentsSessionThread struct { + // Unique identifier for this thread. + ID string `json:"id" api:"required"` + // The resolved agent a session thread runs: a saved-agent snapshot, the platform + // advisor entry, or an inline-defined (ephemeral) agent snapshot. + Agent BetaManagedAgentsSessionThreadAgentUnion `json:"agent" api:"required"` + // A timestamp in RFC 3339 format + ArchivedAt time.Time `json:"archived_at" api:"required" format:"date-time"` + // A timestamp in RFC 3339 format + CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"` + // Parent thread that spawned this thread. Null for the primary thread. + ParentThreadID string `json:"parent_thread_id" api:"required"` + // The session this thread belongs to. + SessionID string `json:"session_id" api:"required"` + // Timing statistics for a session thread. + Stats BetaManagedAgentsSessionThreadStats `json:"stats" api:"required"` + // SessionThreadStatus enum + // + // Any of "running", "idle", "rescheduling", "terminated". + Status BetaManagedAgentsSessionThreadStatus `json:"status" api:"required"` + // Any of "session_thread". + Type BetaManagedAgentsSessionThreadType `json:"type" api:"required"` + // A timestamp in RFC 3339 format + UpdatedAt time.Time `json:"updated_at" api:"required" format:"date-time"` + // Cumulative token usage for a session thread across all turns. + Usage BetaManagedAgentsSessionThreadUsage `json:"usage" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + Agent respjson.Field + ArchivedAt respjson.Field + CreatedAt respjson.Field + ParentThreadID respjson.Field + SessionID respjson.Field + Stats respjson.Field + Status respjson.Field + Type respjson.Field + UpdatedAt respjson.Field + Usage respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsSessionThread) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsSessionThread) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaManagedAgentsSessionThreadAgentUnion contains all possible properties and +// values from [BetaManagedAgentsSessionThreadAgent], [BetaManagedAgentsAdvisor]. +// +// Use the [BetaManagedAgentsSessionThreadAgentUnion.AsAny] method to switch on the +// variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaManagedAgentsSessionThreadAgentUnion struct { + // This field is from variant [BetaManagedAgentsSessionThreadAgent]. + ID string `json:"id"` + // This field is from variant [BetaManagedAgentsSessionThreadAgent]. + Description string `json:"description"` + // This field is from variant [BetaManagedAgentsSessionThreadAgent]. + MCPServers []BetaManagedAgentsMCPServerURLDefinition `json:"mcp_servers"` + // This field is a union of [BetaManagedAgentsModelConfig], [string] + Model BetaManagedAgentsSessionThreadAgentUnionModel `json:"model"` + // This field is from variant [BetaManagedAgentsSessionThreadAgent]. + Name string `json:"name"` + // This field is from variant [BetaManagedAgentsSessionThreadAgent]. + Skills []BetaManagedAgentsSessionThreadAgentSkillUnion `json:"skills"` + // This field is from variant [BetaManagedAgentsSessionThreadAgent]. + System string `json:"system"` + // This field is from variant [BetaManagedAgentsSessionThreadAgent]. + Tools []BetaManagedAgentsSessionThreadAgentToolUnion `json:"tools"` + // Any of "agent", "advisor". + Type string `json:"type"` + // This field is from variant [BetaManagedAgentsSessionThreadAgent]. + Version int64 `json:"version"` + JSON struct { + ID respjson.Field + Description respjson.Field + MCPServers respjson.Field + Model respjson.Field + Name respjson.Field + Skills respjson.Field + System respjson.Field + Tools respjson.Field + Type respjson.Field + Version respjson.Field + raw string + } `json:"-"` +} + +// anyBetaManagedAgentsSessionThreadAgent is implemented by each variant of +// [BetaManagedAgentsSessionThreadAgentUnion] to add type safety for the return +// type of [BetaManagedAgentsSessionThreadAgentUnion.AsAny] +type anyBetaManagedAgentsSessionThreadAgent interface { + implBetaManagedAgentsSessionThreadAgentUnion() +} + +func (BetaManagedAgentsSessionThreadAgent) implBetaManagedAgentsSessionThreadAgentUnion() {} +func (BetaManagedAgentsAdvisor) implBetaManagedAgentsSessionThreadAgentUnion() {} + +// Use the following switch statement to find the correct variant +// +// switch variant := BetaManagedAgentsSessionThreadAgentUnion.AsAny().(type) { +// case anthropic.BetaManagedAgentsSessionThreadAgent: +// case anthropic.BetaManagedAgentsAdvisor: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaManagedAgentsSessionThreadAgentUnion) AsAny() anyBetaManagedAgentsSessionThreadAgent { + switch u.Type { + case "agent": + return u.AsAgent() + case "advisor": + return u.AsAdvisor() + } + return nil +} + +func (u BetaManagedAgentsSessionThreadAgentUnion) AsAgent() (v BetaManagedAgentsSessionThreadAgent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsSessionThreadAgentUnion) AsAdvisor() (v BetaManagedAgentsAdvisor) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u BetaManagedAgentsSessionThreadAgentUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaManagedAgentsSessionThreadAgentUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaManagedAgentsSessionThreadAgentUnionModel is an implicit subunion of +// [BetaManagedAgentsSessionThreadAgentUnion]. +// BetaManagedAgentsSessionThreadAgentUnionModel provides convenient access to the +// sub-properties of the union. +// +// For type safety it is recommended to directly use a variant of the +// [BetaManagedAgentsSessionThreadAgentUnion]. +// +// If the underlying value is not a json object, one of the following properties +// will be valid: OfString] +type BetaManagedAgentsSessionThreadAgentUnionModel struct { + // This field will be present if the value is a [string] instead of an object. + OfString string `json:",inline"` + // This field is from variant [BetaManagedAgentsModelConfig]. + ID BetaManagedAgentsModel `json:"id"` + // This field is from variant [BetaManagedAgentsModelConfig]. + Effort BetaManagedAgentsModelConfigEffortUnion `json:"effort"` + // This field is from variant [BetaManagedAgentsModelConfig]. + InferenceGeo string `json:"inference_geo"` + // This field is from variant [BetaManagedAgentsModelConfig]. + Speed BetaManagedAgentsModelConfigSpeed `json:"speed"` + JSON struct { + OfString respjson.Field + ID respjson.Field + Effort respjson.Field + InferenceGeo respjson.Field + Speed respjson.Field + raw string + } `json:"-"` +} + +func (r *BetaManagedAgentsSessionThreadAgentUnionModel) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsSessionThreadType string + +const ( + BetaManagedAgentsSessionThreadTypeSessionThread BetaManagedAgentsSessionThreadType = "session_thread" +) + +// Timing statistics for a session thread. +type BetaManagedAgentsSessionThreadStats struct { + // Cumulative time in seconds the thread spent actively running. Excludes idle + // time. + ActiveSeconds float64 `json:"active_seconds"` + // Elapsed time since thread creation in seconds. For archived threads, frozen at + // the final update. + DurationSeconds float64 `json:"duration_seconds"` + // Time in seconds for the thread to begin running. Zero for child threads, which + // start immediately. + StartupSeconds float64 `json:"startup_seconds"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ActiveSeconds respjson.Field + DurationSeconds respjson.Field + StartupSeconds respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsSessionThreadStats) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsSessionThreadStats) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// SessionThreadStatus enum +type BetaManagedAgentsSessionThreadStatus string + +const ( + BetaManagedAgentsSessionThreadStatusRunning BetaManagedAgentsSessionThreadStatus = "running" + BetaManagedAgentsSessionThreadStatusIdle BetaManagedAgentsSessionThreadStatus = "idle" + BetaManagedAgentsSessionThreadStatusRescheduling BetaManagedAgentsSessionThreadStatus = "rescheduling" + BetaManagedAgentsSessionThreadStatusTerminated BetaManagedAgentsSessionThreadStatus = "terminated" +) + +// Cumulative token usage for a session thread across all turns. +type BetaManagedAgentsSessionThreadUsage struct { + // Cumulative time in seconds this thread spent in running status. Equal to + // `stats.active_seconds`; surfaced here so a thread's usage carries every quantity + // its cost is priced on. + ActiveSeconds float64 `json:"active_seconds"` + // Prompt-cache creation token usage broken down by cache lifetime. + CacheCreation BetaManagedAgentsCacheCreationUsage `json:"cache_creation"` + // Total tokens read from prompt cache. + CacheReadInputTokens int64 `json:"cache_read_input_tokens"` + // Total input tokens consumed across all turns. + InputTokens int64 `json:"input_tokens"` + // A monetary amount in a specific currency. + ListCost BetaMonetaryAmount `json:"list_cost" api:"nullable"` + // Total output tokens generated across all turns. + OutputTokens int64 `json:"output_tokens"` + // Cumulative count of server-executed tool invocations, broken down by tool. + ServerToolUse BetaManagedAgentsServerToolUsage `json:"server_tool_use" api:"nullable"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ActiveSeconds respjson.Field + CacheCreation respjson.Field + CacheReadInputTokens respjson.Field + InputTokens respjson.Field + ListCost respjson.Field + OutputTokens respjson.Field + ServerToolUse respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsSessionThreadUsage) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsSessionThreadUsage) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaManagedAgentsStreamSessionThreadEventsUnion contains all possible properties +// and values from [BetaManagedAgentsUserMessageEvent], +// [BetaManagedAgentsUserInterruptEvent], +// [BetaManagedAgentsUserToolConfirmationEvent], +// [BetaManagedAgentsUserCustomToolResultEvent], +// [BetaManagedAgentsAgentCustomToolUseEvent], +// [BetaManagedAgentsAgentMessageEvent], [BetaManagedAgentsAgentThinkingEvent], +// [BetaManagedAgentsAgentMCPToolUseEvent], +// [BetaManagedAgentsAgentMCPToolResultEvent], +// [BetaManagedAgentsAgentToolUseEvent], [BetaManagedAgentsAgentToolResultEvent], +// [BetaManagedAgentsAgentThreadMessageReceivedEvent], +// [BetaManagedAgentsAgentThreadMessageSentEvent], +// [BetaManagedAgentsAgentThreadContextCompactedEvent], +// [BetaManagedAgentsSessionErrorEvent], +// [BetaManagedAgentsSessionStatusRescheduledEvent], +// [BetaManagedAgentsSessionStatusRunningEvent], +// [BetaManagedAgentsSessionStatusIdleEvent], +// [BetaManagedAgentsSessionStatusTerminatedEvent], +// [BetaManagedAgentsSessionThreadCreatedEvent], +// [BetaManagedAgentsSpanOutcomeEvaluationStartEvent], +// [BetaManagedAgentsSpanOutcomeEvaluationEndEvent], +// [BetaManagedAgentsSpanModelRequestStartEvent], +// [BetaManagedAgentsSpanModelRequestEndEvent], +// [BetaManagedAgentsSpanOutcomeEvaluationOngoingEvent], +// [BetaManagedAgentsUserDefineOutcomeEvent], +// [BetaManagedAgentsSessionDeletedEvent], +// [BetaManagedAgentsSessionThreadStatusRunningEvent], +// [BetaManagedAgentsSessionThreadStatusIdleEvent], +// [BetaManagedAgentsSessionThreadStatusTerminatedEvent], +// [BetaManagedAgentsUserToolResultEvent], +// [BetaManagedAgentsSessionThreadStatusRescheduledEvent], +// [BetaManagedAgentsSessionUpdatedEvent], [BetaManagedAgentsStartEvent], +// [BetaManagedAgentsDeltaEvent], [BetaManagedAgentsSystemMessageEvent], +// [BetaManagedAgentsSessionUsageEvent]. +// +// Use the [BetaManagedAgentsStreamSessionThreadEventsUnion.AsAny] method to switch +// on the variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaManagedAgentsStreamSessionThreadEventsUnion struct { + ID string `json:"id"` + // This field is a union of [[]BetaManagedAgentsUserMessageEventContentUnion], + // [[]BetaManagedAgentsUserCustomToolResultEventContentUnion], + // [[]BetaManagedAgentsAgentMessageEventContentUnion], + // [[]BetaManagedAgentsAgentMCPToolResultEventContentUnion], + // [[]BetaManagedAgentsAgentToolResultEventContentUnion], + // [[]BetaManagedAgentsAgentThreadMessageReceivedEventContentUnion], + // [[]BetaManagedAgentsAgentThreadMessageSentEventContentUnion], + // [[]BetaManagedAgentsUserToolResultEventContentUnion], + // [[]BetaManagedAgentsSystemContentBlock] + Content BetaManagedAgentsStreamSessionThreadEventsUnionContent `json:"content"` + // Any of "user.message", "user.interrupt", "user.tool_confirmation", + // "user.custom_tool_result", "agent.custom_tool_use", "agent.message", + // "agent.thinking", "agent.mcp_tool_use", "agent.mcp_tool_result", + // "agent.tool_use", "agent.tool_result", "agent.thread_message_received", + // "agent.thread_message_sent", "agent.thread_context_compacted", "session.error", + // "session.status_rescheduled", "session.status_running", "session.status_idle", + // "session.status_terminated", "session.thread_created", + // "span.outcome_evaluation_start", "span.outcome_evaluation_end", + // "span.model_request_start", "span.model_request_end", + // "span.outcome_evaluation_ongoing", "user.define_outcome", "session.deleted", + // "session.thread_status_running", "session.thread_status_idle", + // "session.thread_status_terminated", "user.tool_result", + // "session.thread_status_rescheduled", "session.updated", "event_start", + // "event_delta", "system.message", "session.usage". + Type string `json:"type"` + ProcessedAt time.Time `json:"processed_at"` + SessionThreadID string `json:"session_thread_id"` + Result string `json:"result"` + ToolUseID string `json:"tool_use_id"` + // This field is from variant [BetaManagedAgentsUserToolConfirmationEvent]. + DenyMessage string `json:"deny_message"` + // This field is from variant [BetaManagedAgentsUserCustomToolResultEvent]. + CustomToolUseID string `json:"custom_tool_use_id"` + IsError bool `json:"is_error"` + Input any `json:"input"` + Name string `json:"name"` + // This field is from variant [BetaManagedAgentsAgentMCPToolUseEvent]. + MCPServerName string `json:"mcp_server_name"` + EvaluatedPermission string `json:"evaluated_permission"` + // This field is from variant [BetaManagedAgentsAgentMCPToolResultEvent]. + MCPToolUseID string `json:"mcp_tool_use_id"` + // This field is from variant [BetaManagedAgentsAgentThreadMessageReceivedEvent]. + FromSessionThreadID string `json:"from_session_thread_id"` + // This field is from variant [BetaManagedAgentsAgentThreadMessageReceivedEvent]. + FromAgentName string `json:"from_agent_name"` + // This field is from variant [BetaManagedAgentsAgentThreadMessageSentEvent]. + ToSessionThreadID string `json:"to_session_thread_id"` + // This field is from variant [BetaManagedAgentsAgentThreadMessageSentEvent]. + ToAgentName string `json:"to_agent_name"` + // This field is from variant [BetaManagedAgentsSessionErrorEvent]. + Error BetaManagedAgentsSessionErrorEventErrorUnion `json:"error"` + // This field is a union of + // [BetaManagedAgentsSessionStatusIdleEventStopReasonUnion], + // [BetaManagedAgentsSessionThreadStatusIdleEventStopReasonUnion] + StopReason BetaManagedAgentsStreamSessionThreadEventsUnionStopReason `json:"stop_reason"` + AgentName string `json:"agent_name"` + Iteration int64 `json:"iteration"` + OutcomeID string `json:"outcome_id"` + // This field is from variant [BetaManagedAgentsSpanOutcomeEvaluationEndEvent]. + Explanation string `json:"explanation"` + // This field is from variant [BetaManagedAgentsSpanOutcomeEvaluationEndEvent]. + OutcomeEvaluationStartID string `json:"outcome_evaluation_start_id"` + // This field is a union of [BetaManagedAgentsSpanModelUsage], + // [BetaManagedAgentsSessionUsageSnapshot] + Usage BetaManagedAgentsStreamSessionThreadEventsUnionUsage `json:"usage"` + // This field is from variant [BetaManagedAgentsSpanModelRequestEndEvent]. + ModelRequestStartID string `json:"model_request_start_id"` + // This field is from variant [BetaManagedAgentsSpanModelRequestEndEvent]. + ModelUsage BetaManagedAgentsSpanModelUsage `json:"model_usage"` + // This field is from variant [BetaManagedAgentsUserDefineOutcomeEvent]. + Description string `json:"description"` + // This field is from variant [BetaManagedAgentsUserDefineOutcomeEvent]. + MaxIterations int64 `json:"max_iterations"` + // This field is from variant [BetaManagedAgentsUserDefineOutcomeEvent]. + Rubric BetaManagedAgentsUserDefineOutcomeEventRubricUnion `json:"rubric"` + // This field is from variant [BetaManagedAgentsSessionUpdatedEvent]. + Agent BetaManagedAgentsSessionAgent `json:"agent"` + // This field is from variant [BetaManagedAgentsSessionUpdatedEvent]. + Budget BetaManagedAgentsBudgetLimit `json:"budget"` + // This field is from variant [BetaManagedAgentsSessionUpdatedEvent]. + Metadata map[string]string `json:"metadata"` + // This field is from variant [BetaManagedAgentsSessionUpdatedEvent]. + Title string `json:"title"` + // This field is from variant [BetaManagedAgentsStartEvent]. + Event BetaManagedAgentsStartEventPreviewUnion `json:"event"` + // This field is from variant [BetaManagedAgentsDeltaEvent]. + Delta BetaManagedAgentsDeltaContent `json:"delta"` + // This field is from variant [BetaManagedAgentsDeltaEvent]. + EventID string `json:"event_id"` + JSON struct { + ID respjson.Field + Content respjson.Field + Type respjson.Field + ProcessedAt respjson.Field + SessionThreadID respjson.Field + Result respjson.Field + ToolUseID respjson.Field + DenyMessage respjson.Field + CustomToolUseID respjson.Field + IsError respjson.Field + Input respjson.Field + Name respjson.Field + MCPServerName respjson.Field + EvaluatedPermission respjson.Field + MCPToolUseID respjson.Field + FromSessionThreadID respjson.Field + FromAgentName respjson.Field + ToSessionThreadID respjson.Field + ToAgentName respjson.Field + Error respjson.Field + StopReason respjson.Field + AgentName respjson.Field + Iteration respjson.Field + OutcomeID respjson.Field + Explanation respjson.Field + OutcomeEvaluationStartID respjson.Field + Usage respjson.Field + ModelRequestStartID respjson.Field + ModelUsage respjson.Field + Description respjson.Field + MaxIterations respjson.Field + Rubric respjson.Field + Agent respjson.Field + Budget respjson.Field + Metadata respjson.Field + Title respjson.Field + Event respjson.Field + Delta respjson.Field + EventID respjson.Field + raw string + } `json:"-"` +} + +// anyBetaManagedAgentsStreamSessionThreadEvents is implemented by each variant of +// [BetaManagedAgentsStreamSessionThreadEventsUnion] to add type safety for the +// return type of [BetaManagedAgentsStreamSessionThreadEventsUnion.AsAny] +type anyBetaManagedAgentsStreamSessionThreadEvents interface { + implBetaManagedAgentsStreamSessionThreadEventsUnion() +} + +func (BetaManagedAgentsUserMessageEvent) implBetaManagedAgentsStreamSessionThreadEventsUnion() {} +func (BetaManagedAgentsUserInterruptEvent) implBetaManagedAgentsStreamSessionThreadEventsUnion() {} +func (BetaManagedAgentsUserToolConfirmationEvent) implBetaManagedAgentsStreamSessionThreadEventsUnion() { +} +func (BetaManagedAgentsUserCustomToolResultEvent) implBetaManagedAgentsStreamSessionThreadEventsUnion() { +} +func (BetaManagedAgentsAgentCustomToolUseEvent) implBetaManagedAgentsStreamSessionThreadEventsUnion() { +} +func (BetaManagedAgentsAgentMessageEvent) implBetaManagedAgentsStreamSessionThreadEventsUnion() {} +func (BetaManagedAgentsAgentThinkingEvent) implBetaManagedAgentsStreamSessionThreadEventsUnion() {} +func (BetaManagedAgentsAgentMCPToolUseEvent) implBetaManagedAgentsStreamSessionThreadEventsUnion() {} +func (BetaManagedAgentsAgentMCPToolResultEvent) implBetaManagedAgentsStreamSessionThreadEventsUnion() { +} +func (BetaManagedAgentsAgentToolUseEvent) implBetaManagedAgentsStreamSessionThreadEventsUnion() {} +func (BetaManagedAgentsAgentToolResultEvent) implBetaManagedAgentsStreamSessionThreadEventsUnion() {} +func (BetaManagedAgentsAgentThreadMessageReceivedEvent) implBetaManagedAgentsStreamSessionThreadEventsUnion() { +} +func (BetaManagedAgentsAgentThreadMessageSentEvent) implBetaManagedAgentsStreamSessionThreadEventsUnion() { +} +func (BetaManagedAgentsAgentThreadContextCompactedEvent) implBetaManagedAgentsStreamSessionThreadEventsUnion() { +} +func (BetaManagedAgentsSessionErrorEvent) implBetaManagedAgentsStreamSessionThreadEventsUnion() {} +func (BetaManagedAgentsSessionStatusRescheduledEvent) implBetaManagedAgentsStreamSessionThreadEventsUnion() { +} +func (BetaManagedAgentsSessionStatusRunningEvent) implBetaManagedAgentsStreamSessionThreadEventsUnion() { +} +func (BetaManagedAgentsSessionStatusIdleEvent) implBetaManagedAgentsStreamSessionThreadEventsUnion() { +} +func (BetaManagedAgentsSessionStatusTerminatedEvent) implBetaManagedAgentsStreamSessionThreadEventsUnion() { +} +func (BetaManagedAgentsSessionThreadCreatedEvent) implBetaManagedAgentsStreamSessionThreadEventsUnion() { +} +func (BetaManagedAgentsSpanOutcomeEvaluationStartEvent) implBetaManagedAgentsStreamSessionThreadEventsUnion() { +} +func (BetaManagedAgentsSpanOutcomeEvaluationEndEvent) implBetaManagedAgentsStreamSessionThreadEventsUnion() { +} +func (BetaManagedAgentsSpanModelRequestStartEvent) implBetaManagedAgentsStreamSessionThreadEventsUnion() { +} +func (BetaManagedAgentsSpanModelRequestEndEvent) implBetaManagedAgentsStreamSessionThreadEventsUnion() { +} +func (BetaManagedAgentsSpanOutcomeEvaluationOngoingEvent) implBetaManagedAgentsStreamSessionThreadEventsUnion() { +} +func (BetaManagedAgentsUserDefineOutcomeEvent) implBetaManagedAgentsStreamSessionThreadEventsUnion() { +} +func (BetaManagedAgentsSessionDeletedEvent) implBetaManagedAgentsStreamSessionThreadEventsUnion() {} +func (BetaManagedAgentsSessionThreadStatusRunningEvent) implBetaManagedAgentsStreamSessionThreadEventsUnion() { +} +func (BetaManagedAgentsSessionThreadStatusIdleEvent) implBetaManagedAgentsStreamSessionThreadEventsUnion() { +} +func (BetaManagedAgentsSessionThreadStatusTerminatedEvent) implBetaManagedAgentsStreamSessionThreadEventsUnion() { +} +func (BetaManagedAgentsUserToolResultEvent) implBetaManagedAgentsStreamSessionThreadEventsUnion() {} +func (BetaManagedAgentsSessionThreadStatusRescheduledEvent) implBetaManagedAgentsStreamSessionThreadEventsUnion() { +} +func (BetaManagedAgentsSessionUpdatedEvent) implBetaManagedAgentsStreamSessionThreadEventsUnion() {} +func (BetaManagedAgentsStartEvent) implBetaManagedAgentsStreamSessionThreadEventsUnion() {} +func (BetaManagedAgentsDeltaEvent) implBetaManagedAgentsStreamSessionThreadEventsUnion() {} +func (BetaManagedAgentsSystemMessageEvent) implBetaManagedAgentsStreamSessionThreadEventsUnion() {} +func (BetaManagedAgentsSessionUsageEvent) implBetaManagedAgentsStreamSessionThreadEventsUnion() {} + +// Use the following switch statement to find the correct variant +// +// switch variant := BetaManagedAgentsStreamSessionThreadEventsUnion.AsAny().(type) { +// case anthropic.BetaManagedAgentsUserMessageEvent: +// case anthropic.BetaManagedAgentsUserInterruptEvent: +// case anthropic.BetaManagedAgentsUserToolConfirmationEvent: +// case anthropic.BetaManagedAgentsUserCustomToolResultEvent: +// case anthropic.BetaManagedAgentsAgentCustomToolUseEvent: +// case anthropic.BetaManagedAgentsAgentMessageEvent: +// case anthropic.BetaManagedAgentsAgentThinkingEvent: +// case anthropic.BetaManagedAgentsAgentMCPToolUseEvent: +// case anthropic.BetaManagedAgentsAgentMCPToolResultEvent: +// case anthropic.BetaManagedAgentsAgentToolUseEvent: +// case anthropic.BetaManagedAgentsAgentToolResultEvent: +// case anthropic.BetaManagedAgentsAgentThreadMessageReceivedEvent: +// case anthropic.BetaManagedAgentsAgentThreadMessageSentEvent: +// case anthropic.BetaManagedAgentsAgentThreadContextCompactedEvent: +// case anthropic.BetaManagedAgentsSessionErrorEvent: +// case anthropic.BetaManagedAgentsSessionStatusRescheduledEvent: +// case anthropic.BetaManagedAgentsSessionStatusRunningEvent: +// case anthropic.BetaManagedAgentsSessionStatusIdleEvent: +// case anthropic.BetaManagedAgentsSessionStatusTerminatedEvent: +// case anthropic.BetaManagedAgentsSessionThreadCreatedEvent: +// case anthropic.BetaManagedAgentsSpanOutcomeEvaluationStartEvent: +// case anthropic.BetaManagedAgentsSpanOutcomeEvaluationEndEvent: +// case anthropic.BetaManagedAgentsSpanModelRequestStartEvent: +// case anthropic.BetaManagedAgentsSpanModelRequestEndEvent: +// case anthropic.BetaManagedAgentsSpanOutcomeEvaluationOngoingEvent: +// case anthropic.BetaManagedAgentsUserDefineOutcomeEvent: +// case anthropic.BetaManagedAgentsSessionDeletedEvent: +// case anthropic.BetaManagedAgentsSessionThreadStatusRunningEvent: +// case anthropic.BetaManagedAgentsSessionThreadStatusIdleEvent: +// case anthropic.BetaManagedAgentsSessionThreadStatusTerminatedEvent: +// case anthropic.BetaManagedAgentsUserToolResultEvent: +// case anthropic.BetaManagedAgentsSessionThreadStatusRescheduledEvent: +// case anthropic.BetaManagedAgentsSessionUpdatedEvent: +// case anthropic.BetaManagedAgentsStartEvent: +// case anthropic.BetaManagedAgentsDeltaEvent: +// case anthropic.BetaManagedAgentsSystemMessageEvent: +// case anthropic.BetaManagedAgentsSessionUsageEvent: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaManagedAgentsStreamSessionThreadEventsUnion) AsAny() anyBetaManagedAgentsStreamSessionThreadEvents { + switch u.Type { + case "user.message": + return u.AsUserMessage() + case "user.interrupt": + return u.AsUserInterrupt() + case "user.tool_confirmation": + return u.AsUserToolConfirmation() + case "user.custom_tool_result": + return u.AsUserCustomToolResult() + case "agent.custom_tool_use": + return u.AsAgentCustomToolUse() + case "agent.message": + return u.AsAgentMessage() + case "agent.thinking": + return u.AsAgentThinking() + case "agent.mcp_tool_use": + return u.AsAgentMCPToolUse() + case "agent.mcp_tool_result": + return u.AsAgentMCPToolResult() + case "agent.tool_use": + return u.AsAgentToolUse() + case "agent.tool_result": + return u.AsAgentToolResult() + case "agent.thread_message_received": + return u.AsAgentThreadMessageReceived() + case "agent.thread_message_sent": + return u.AsAgentThreadMessageSent() + case "agent.thread_context_compacted": + return u.AsAgentThreadContextCompacted() + case "session.error": + return u.AsSessionError() + case "session.status_rescheduled": + return u.AsSessionStatusRescheduled() + case "session.status_running": + return u.AsSessionStatusRunning() + case "session.status_idle": + return u.AsSessionStatusIdle() + case "session.status_terminated": + return u.AsSessionStatusTerminated() + case "session.thread_created": + return u.AsSessionThreadCreated() + case "span.outcome_evaluation_start": + return u.AsSpanOutcomeEvaluationStart() + case "span.outcome_evaluation_end": + return u.AsSpanOutcomeEvaluationEnd() + case "span.model_request_start": + return u.AsSpanModelRequestStart() + case "span.model_request_end": + return u.AsSpanModelRequestEnd() + case "span.outcome_evaluation_ongoing": + return u.AsSpanOutcomeEvaluationOngoing() + case "user.define_outcome": + return u.AsUserDefineOutcome() + case "session.deleted": + return u.AsSessionDeleted() + case "session.thread_status_running": + return u.AsSessionThreadStatusRunning() + case "session.thread_status_idle": + return u.AsSessionThreadStatusIdle() + case "session.thread_status_terminated": + return u.AsSessionThreadStatusTerminated() + case "user.tool_result": + return u.AsUserToolResult() + case "session.thread_status_rescheduled": + return u.AsSessionThreadStatusRescheduled() + case "session.updated": + return u.AsSessionUpdated() + case "event_start": + return u.AsEventStart() + case "event_delta": + return u.AsEventDelta() + case "system.message": + return u.AsSystemMessage() + case "session.usage": + return u.AsSessionUsage() + } + return nil +} + +func (u BetaManagedAgentsStreamSessionThreadEventsUnion) AsUserMessage() (v BetaManagedAgentsUserMessageEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsStreamSessionThreadEventsUnion) AsUserInterrupt() (v BetaManagedAgentsUserInterruptEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsStreamSessionThreadEventsUnion) AsUserToolConfirmation() (v BetaManagedAgentsUserToolConfirmationEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsStreamSessionThreadEventsUnion) AsUserCustomToolResult() (v BetaManagedAgentsUserCustomToolResultEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsStreamSessionThreadEventsUnion) AsAgentCustomToolUse() (v BetaManagedAgentsAgentCustomToolUseEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsStreamSessionThreadEventsUnion) AsAgentMessage() (v BetaManagedAgentsAgentMessageEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsStreamSessionThreadEventsUnion) AsAgentThinking() (v BetaManagedAgentsAgentThinkingEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsStreamSessionThreadEventsUnion) AsAgentMCPToolUse() (v BetaManagedAgentsAgentMCPToolUseEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsStreamSessionThreadEventsUnion) AsAgentMCPToolResult() (v BetaManagedAgentsAgentMCPToolResultEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsStreamSessionThreadEventsUnion) AsAgentToolUse() (v BetaManagedAgentsAgentToolUseEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsStreamSessionThreadEventsUnion) AsAgentToolResult() (v BetaManagedAgentsAgentToolResultEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsStreamSessionThreadEventsUnion) AsAgentThreadMessageReceived() (v BetaManagedAgentsAgentThreadMessageReceivedEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsStreamSessionThreadEventsUnion) AsAgentThreadMessageSent() (v BetaManagedAgentsAgentThreadMessageSentEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsStreamSessionThreadEventsUnion) AsAgentThreadContextCompacted() (v BetaManagedAgentsAgentThreadContextCompactedEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsStreamSessionThreadEventsUnion) AsSessionError() (v BetaManagedAgentsSessionErrorEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsStreamSessionThreadEventsUnion) AsSessionStatusRescheduled() (v BetaManagedAgentsSessionStatusRescheduledEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsStreamSessionThreadEventsUnion) AsSessionStatusRunning() (v BetaManagedAgentsSessionStatusRunningEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsStreamSessionThreadEventsUnion) AsSessionStatusIdle() (v BetaManagedAgentsSessionStatusIdleEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsStreamSessionThreadEventsUnion) AsSessionStatusTerminated() (v BetaManagedAgentsSessionStatusTerminatedEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsStreamSessionThreadEventsUnion) AsSessionThreadCreated() (v BetaManagedAgentsSessionThreadCreatedEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsStreamSessionThreadEventsUnion) AsSpanOutcomeEvaluationStart() (v BetaManagedAgentsSpanOutcomeEvaluationStartEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsStreamSessionThreadEventsUnion) AsSpanOutcomeEvaluationEnd() (v BetaManagedAgentsSpanOutcomeEvaluationEndEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsStreamSessionThreadEventsUnion) AsSpanModelRequestStart() (v BetaManagedAgentsSpanModelRequestStartEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsStreamSessionThreadEventsUnion) AsSpanModelRequestEnd() (v BetaManagedAgentsSpanModelRequestEndEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsStreamSessionThreadEventsUnion) AsSpanOutcomeEvaluationOngoing() (v BetaManagedAgentsSpanOutcomeEvaluationOngoingEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsStreamSessionThreadEventsUnion) AsUserDefineOutcome() (v BetaManagedAgentsUserDefineOutcomeEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsStreamSessionThreadEventsUnion) AsSessionDeleted() (v BetaManagedAgentsSessionDeletedEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsStreamSessionThreadEventsUnion) AsSessionThreadStatusRunning() (v BetaManagedAgentsSessionThreadStatusRunningEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsStreamSessionThreadEventsUnion) AsSessionThreadStatusIdle() (v BetaManagedAgentsSessionThreadStatusIdleEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsStreamSessionThreadEventsUnion) AsSessionThreadStatusTerminated() (v BetaManagedAgentsSessionThreadStatusTerminatedEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsStreamSessionThreadEventsUnion) AsUserToolResult() (v BetaManagedAgentsUserToolResultEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsStreamSessionThreadEventsUnion) AsSessionThreadStatusRescheduled() (v BetaManagedAgentsSessionThreadStatusRescheduledEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsStreamSessionThreadEventsUnion) AsSessionUpdated() (v BetaManagedAgentsSessionUpdatedEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsStreamSessionThreadEventsUnion) AsEventStart() (v BetaManagedAgentsStartEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsStreamSessionThreadEventsUnion) AsEventDelta() (v BetaManagedAgentsDeltaEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsStreamSessionThreadEventsUnion) AsSystemMessage() (v BetaManagedAgentsSystemMessageEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsStreamSessionThreadEventsUnion) AsSessionUsage() (v BetaManagedAgentsSessionUsageEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u BetaManagedAgentsStreamSessionThreadEventsUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaManagedAgentsStreamSessionThreadEventsUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaManagedAgentsStreamSessionThreadEventsUnionContent is an implicit subunion +// of [BetaManagedAgentsStreamSessionThreadEventsUnion]. +// BetaManagedAgentsStreamSessionThreadEventsUnionContent provides convenient +// access to the sub-properties of the union. +// +// For type safety it is recommended to directly use a variant of the +// [BetaManagedAgentsStreamSessionThreadEventsUnion]. +// +// If the underlying value is not a json object, one of the following properties +// will be valid: OfBetaManagedAgentsUserMessageEventContentArray +// OfBetaManagedAgentsUserCustomToolResultEventContentArray +// OfBetaManagedAgentsAgentMessageEventContentArray +// OfBetaManagedAgentsAgentMCPToolResultEventContentArray +// OfBetaManagedAgentsAgentToolResultEventContentArray +// OfBetaManagedAgentsAgentThreadMessageReceivedEventContentArray +// OfBetaManagedAgentsAgentThreadMessageSentEventContentArray +// OfBetaManagedAgentsUserToolResultEventContentArray +// OfBetaManagedAgentsSystemContentBlockArray] +type BetaManagedAgentsStreamSessionThreadEventsUnionContent struct { + // This field will be present if the value is a + // [[]BetaManagedAgentsUserMessageEventContentUnion] instead of an object. + OfBetaManagedAgentsUserMessageEventContentArray []BetaManagedAgentsUserMessageEventContentUnion `json:",inline"` + // This field will be present if the value is a + // [[]BetaManagedAgentsUserCustomToolResultEventContentUnion] instead of an object. + OfBetaManagedAgentsUserCustomToolResultEventContentArray []BetaManagedAgentsUserCustomToolResultEventContentUnion `json:",inline"` + // This field will be present if the value is a + // [[]BetaManagedAgentsAgentMessageEventContentUnion] instead of an object. + OfBetaManagedAgentsAgentMessageEventContentArray []BetaManagedAgentsAgentMessageEventContentUnion `json:",inline"` + // This field will be present if the value is a + // [[]BetaManagedAgentsAgentMCPToolResultEventContentUnion] instead of an object. + OfBetaManagedAgentsAgentMCPToolResultEventContentArray []BetaManagedAgentsAgentMCPToolResultEventContentUnion `json:",inline"` + // This field will be present if the value is a + // [[]BetaManagedAgentsAgentToolResultEventContentUnion] instead of an object. + OfBetaManagedAgentsAgentToolResultEventContentArray []BetaManagedAgentsAgentToolResultEventContentUnion `json:",inline"` + // This field will be present if the value is a + // [[]BetaManagedAgentsAgentThreadMessageReceivedEventContentUnion] instead of an + // object. + OfBetaManagedAgentsAgentThreadMessageReceivedEventContentArray []BetaManagedAgentsAgentThreadMessageReceivedEventContentUnion `json:",inline"` + // This field will be present if the value is a + // [[]BetaManagedAgentsAgentThreadMessageSentEventContentUnion] instead of an + // object. + OfBetaManagedAgentsAgentThreadMessageSentEventContentArray []BetaManagedAgentsAgentThreadMessageSentEventContentUnion `json:",inline"` + // This field will be present if the value is a + // [[]BetaManagedAgentsUserToolResultEventContentUnion] instead of an object. + OfBetaManagedAgentsUserToolResultEventContentArray []BetaManagedAgentsUserToolResultEventContentUnion `json:",inline"` + // This field will be present if the value is a + // [[]BetaManagedAgentsSystemContentBlock] instead of an object. + OfBetaManagedAgentsSystemContentBlockArray []BetaManagedAgentsSystemContentBlock `json:",inline"` + JSON struct { + OfBetaManagedAgentsUserMessageEventContentArray respjson.Field + OfBetaManagedAgentsUserCustomToolResultEventContentArray respjson.Field + OfBetaManagedAgentsAgentMessageEventContentArray respjson.Field + OfBetaManagedAgentsAgentMCPToolResultEventContentArray respjson.Field + OfBetaManagedAgentsAgentToolResultEventContentArray respjson.Field + OfBetaManagedAgentsAgentThreadMessageReceivedEventContentArray respjson.Field + OfBetaManagedAgentsAgentThreadMessageSentEventContentArray respjson.Field + OfBetaManagedAgentsUserToolResultEventContentArray respjson.Field + OfBetaManagedAgentsSystemContentBlockArray respjson.Field + raw string + } `json:"-"` +} + +func (r *BetaManagedAgentsStreamSessionThreadEventsUnionContent) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaManagedAgentsStreamSessionThreadEventsUnionStopReason is an implicit +// subunion of [BetaManagedAgentsStreamSessionThreadEventsUnion]. +// BetaManagedAgentsStreamSessionThreadEventsUnionStopReason provides convenient +// access to the sub-properties of the union. +// +// For type safety it is recommended to directly use a variant of the +// [BetaManagedAgentsStreamSessionThreadEventsUnion]. +type BetaManagedAgentsStreamSessionThreadEventsUnionStopReason struct { + Type string `json:"type"` + // This field is from variant + // [BetaManagedAgentsSessionStatusIdleEventStopReasonUnion], + // [BetaManagedAgentsSessionThreadStatusIdleEventStopReasonUnion]. + EventIDs []string `json:"event_ids"` + JSON struct { + Type respjson.Field + EventIDs respjson.Field + raw string + } `json:"-"` +} + +func (r *BetaManagedAgentsStreamSessionThreadEventsUnionStopReason) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaManagedAgentsStreamSessionThreadEventsUnionUsage is an implicit subunion of +// [BetaManagedAgentsStreamSessionThreadEventsUnion]. +// BetaManagedAgentsStreamSessionThreadEventsUnionUsage provides convenient access +// to the sub-properties of the union. +// +// For type safety it is recommended to directly use a variant of the +// [BetaManagedAgentsStreamSessionThreadEventsUnion]. +type BetaManagedAgentsStreamSessionThreadEventsUnionUsage struct { + // This field is from variant [BetaManagedAgentsSpanModelUsage]. + CacheCreationInputTokens int64 `json:"cache_creation_input_tokens"` + CacheReadInputTokens int64 `json:"cache_read_input_tokens"` + InputTokens int64 `json:"input_tokens"` + OutputTokens int64 `json:"output_tokens"` + // This field is from variant [BetaManagedAgentsSpanModelUsage]. + Speed BetaManagedAgentsSpanModelUsageSpeed `json:"speed"` + // This field is from variant [BetaManagedAgentsSessionUsageSnapshot]. + ActiveSeconds float64 `json:"active_seconds"` + // This field is from variant [BetaManagedAgentsSessionUsageSnapshot]. + CacheCreation BetaManagedAgentsCacheCreationUsage `json:"cache_creation"` + // This field is from variant [BetaManagedAgentsSessionUsageSnapshot]. + ListCost BetaMonetaryAmount `json:"list_cost"` + // This field is from variant [BetaManagedAgentsSessionUsageSnapshot]. + ServerToolUse BetaManagedAgentsServerToolUsage `json:"server_tool_use"` + JSON struct { + CacheCreationInputTokens respjson.Field + CacheReadInputTokens respjson.Field + InputTokens respjson.Field + OutputTokens respjson.Field + Speed respjson.Field + ActiveSeconds respjson.Field + CacheCreation respjson.Field + ListCost respjson.Field + ServerToolUse respjson.Field + raw string + } `json:"-"` +} + +func (r *BetaManagedAgentsStreamSessionThreadEventsUnionUsage) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaSessionThreadGetParams struct { + SessionID string `path:"session_id" api:"required" json:"-"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +type BetaSessionThreadListParams struct { + // Maximum results per page. Defaults to 1000. + Limit param.Opt[int64] `query:"limit,omitzero" json:"-"` + // Opaque pagination cursor from a previous response's next_page. Forward-only. + Page param.Opt[string] `query:"page,omitzero" json:"-"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +// URLQuery serializes [BetaSessionThreadListParams]'s query parameters as +// `url.Values`. +func (r BetaSessionThreadListParams) URLQuery() (v url.Values, err error) { + return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ + ArrayFormat: apiquery.ArrayQueryFormatBrackets, + NestedFormat: apiquery.NestedQueryFormatBrackets, + }) +} + +type BetaSessionThreadArchiveParams struct { + SessionID string `path:"session_id" api:"required" json:"-"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/betasessionthreadevent.go b/vendor/github.com/anthropics/anthropic-sdk-go/betasessionthreadevent.go new file mode 100644 index 000000000..fd6f49fad --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/betasessionthreadevent.go @@ -0,0 +1,143 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +package anthropic + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "slices" + + "github.com/anthropics/anthropic-sdk-go/internal/apiquery" + "github.com/anthropics/anthropic-sdk-go/internal/requestconfig" + "github.com/anthropics/anthropic-sdk-go/option" + "github.com/anthropics/anthropic-sdk-go/packages/pagination" + "github.com/anthropics/anthropic-sdk-go/packages/param" + "github.com/anthropics/anthropic-sdk-go/packages/ssestream" +) + +// BetaSessionThreadEventService contains methods and other services that help with +// interacting with the anthropic API. +// +// Note, unlike clients, this service does not read variables from the environment +// automatically. You should not instantiate this service directly, and instead use +// the [NewBetaSessionThreadEventService] method instead. +type BetaSessionThreadEventService struct { + Options []option.RequestOption +} + +// NewBetaSessionThreadEventService generates a new service that applies the given +// options to each request. These options are applied after the parent client's +// options (if there is one), and before any request-specific options. +func NewBetaSessionThreadEventService(opts ...option.RequestOption) (r BetaSessionThreadEventService) { + r = BetaSessionThreadEventService{} + r.Options = opts + return +} + +// List Session Thread Events +func (r *BetaSessionThreadEventService) List(ctx context.Context, threadID string, params BetaSessionThreadEventListParams, opts ...option.RequestOption) (res *pagination.PageCursor[BetaManagedAgentsSessionEventUnion], err error) { + var raw *http.Response + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "managed-agents-2026-04-01"), option.WithResponseInto(&raw)}, opts...) + if params.SessionID == "" { + err = errors.New("missing required session_id parameter") + return nil, err + } + if threadID == "" { + err = errors.New("missing required thread_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/sessions/%s/threads/%s/events?beta=true", params.SessionID, threadID) + cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, params, &res, opts...) + if err != nil { + return nil, err + } + err = cfg.Execute() + if err != nil { + return nil, err + } + res.SetPageConfig(cfg, raw) + return res, nil +} + +// List Session Thread Events +func (r *BetaSessionThreadEventService) ListAutoPaging(ctx context.Context, threadID string, params BetaSessionThreadEventListParams, opts ...option.RequestOption) *pagination.PageCursorAutoPager[BetaManagedAgentsSessionEventUnion] { + return pagination.NewPageCursorAutoPager(r.List(ctx, threadID, params, opts...)) +} + +// Stream Session Thread Events +func (r *BetaSessionThreadEventService) StreamEvents(ctx context.Context, threadID string, params BetaSessionThreadEventStreamParams, opts ...option.RequestOption) (stream *ssestream.Stream[BetaManagedAgentsStreamSessionThreadEventsUnion]) { + var ( + raw *http.Response + err error + ) + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "managed-agents-2026-04-01")}, opts...) + if params.SessionID == "" { + err = errors.New("missing required session_id parameter") + return ssestream.NewStream[BetaManagedAgentsStreamSessionThreadEventsUnion](nil, err) + } + if threadID == "" { + err = errors.New("missing required thread_id parameter") + return ssestream.NewStream[BetaManagedAgentsStreamSessionThreadEventsUnion](nil, err) + } + path := fmt.Sprintf("v1/sessions/%s/threads/%s/stream?beta=true", params.SessionID, threadID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, params, &raw, opts...) + return ssestream.NewStream[BetaManagedAgentsStreamSessionThreadEventsUnion](ssestream.NewDecoder(raw), err) +} + +type BetaSessionThreadEventListParams struct { + SessionID string `path:"session_id" api:"required" json:"-"` + // Query parameter for limit + Limit param.Opt[int64] `query:"limit,omitzero" json:"-"` + // Query parameter for page + Page param.Opt[string] `query:"page,omitzero" json:"-"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +// URLQuery serializes [BetaSessionThreadEventListParams]'s query parameters as +// `url.Values`. +func (r BetaSessionThreadEventListParams) URLQuery() (v url.Values, err error) { + return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ + ArrayFormat: apiquery.ArrayQueryFormatBrackets, + NestedFormat: apiquery.NestedQueryFormatBrackets, + }) +} + +type BetaSessionThreadEventStreamParams struct { + SessionID string `path:"session_id" api:"required" json:"-"` + // When set, this connection also receives streaming deltas (`event_start`, + // `event_delta`) while an event is being produced, before the event itself + // arrives. Deltas are best-effort; when the final event is produced it carries the + // complete content. A model request that ends early (an error or interrupt) + // produces no final event — its terminal `span.model_request_end` closes the + // preview. Accepts one or more event types to preview and may be repeated: + // `agent.message` streams `content_delta` fragments; `agent.thinking` is + // start-only — a signal that the agent has begun extended thinking, concluded by + // the `agent.thinking` event itself. Only previews of the requested event types + // are sent. + EventDeltas []BetaManagedAgentsDeltaType `query:"event_deltas,omitzero" json:"-"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +// URLQuery serializes [BetaSessionThreadEventStreamParams]'s query parameters as +// `url.Values`. +func (r BetaSessionThreadEventStreamParams) URLQuery() (v url.Values, err error) { + return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ + ArrayFormat: apiquery.ArrayQueryFormatBrackets, + NestedFormat: apiquery.NestedQueryFormatBrackets, + }) +} diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/betasessiontoolrunner.go b/vendor/github.com/anthropics/anthropic-sdk-go/betasessiontoolrunner.go new file mode 100644 index 000000000..ab374910c --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/betasessiontoolrunner.go @@ -0,0 +1,1425 @@ +package anthropic + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "iter" + "log/slog" + "math/rand/v2" + "sync" + "time" + + "github.com/anthropics/anthropic-sdk-go/internal/sendwindow" + "github.com/anthropics/anthropic-sdk-go/internal/stainlessheader" + "github.com/anthropics/anthropic-sdk-go/option" + "github.com/anthropics/anthropic-sdk-go/packages/param" + "golang.org/x/sync/errgroup" +) + +// DefaultMaxIdle is used for [SessionToolRunnerOptions.MaxIdle] when it is nil: +// once the session goes idle with stop_reason "end_turn", the runner keeps +// running for this long before stopping (any new event resets the countdown). +const DefaultMaxIdle = 60 * time.Second + +const ( + sessionRunnerStreamBackoffStart = 500 * time.Millisecond + sessionRunnerStreamBackoffCap = 10 * time.Second + // sessionRunnerStreamHealthyAfter is how long a stream must stay open + // before the reconnect backoff resets. + sessionRunnerStreamHealthyAfter = 5 * time.Second + sessionRunnerResultsBuffer = 32 // enough to absorb a brief consumer pause without back-pressuring dispatch + sessionRunnerToolUseQueueBuffer = 32 +) + +// Backoff between tool-result send retries; vars so tests can shrink them. +var ( + sessionRunnerSendBackoffStart = 1 * time.Second + sessionRunnerSendBackoffCap = 30 * time.Second +) + +// Defaults for the tunable per-runner timeouts. Each is overridable via the +// matching [SessionToolRunnerOptions] field (ToolTimeout / SendTimeout / +// DrainTimeout); a zero option falls back to the default here, so the +// out-of-the-box behavior is identical when nothing is set. +const ( + defaultSessionRunnerToolTimeout = 120 * time.Second + defaultSessionRunnerSendTimeout = 15 * time.Second + defaultSessionRunnerDrainTimeout = 30 * time.Second +) + +// defaultSessionRunnerSendRetryWindow bounds how long a transiently failing +// tool-result send keeps retrying when the runner is used on its own: the +// server's default work-item lease TTL. lib/environments.EnvironmentWorker +// overrides it with the live TTL from each lease heartbeat (internal/sendwindow), +// so a send is only abandoned once the lease can no longer be ours. +const defaultSessionRunnerSendRetryWindow = 5 * time.Minute + +// Sentinel errors returned via (*SessionToolRunner).Err so consumers can +// distinguish normal end-of-session from idle bailout. +var ( + // ErrSessionTerminated means the server emitted session.status_terminated + // or session.deleted. Iteration ends normally; the consumer's outer loop + // can move on. + ErrSessionTerminated = errors.New("session terminated") + + // ErrIdleTimeout means the session went idle with stop_reason "end_turn" + // and stayed quiet for MaxIdle. The consumer chose this timeout, so treat + // it as expected. + ErrIdleTimeout = errors.New("session idle after end_turn") +) + +// SessionToolRunnerOptions configures a [SessionToolRunner]. The +// managed-agents session id is not part of this struct — it is a positional +// argument to NewToolRunner, matching list/send/stream on the events resource. +type SessionToolRunnerOptions struct { + // Tools is the registry of locally-executable tools, in the same + // [BetaTool] shape (*BetaMessageService).NewToolRunner accepts. The runner + // looks up each agent.tool_use and agent.custom_tool_use event's Name + // against this slice and routes to the matching tool. Use + // agenttoolset.BetaAgentToolset20260401(env) (from + // github.com/anthropics/anthropic-sdk-go/tools/agenttoolset) for the + // standard agent_toolset_20260401 set; filter or extend the slice to + // customise. Tool lifetime — including Close on tools that implement + // io.Closer — is the caller's responsibility: the runner never closes + // tools, so the same slice can be reused across multiple sessions. + Tools []BetaTool + + // MaxIdle is how long the runner keeps running after the session goes idle + // with stop_reason "end_turn" before it stops; any new event resets the + // countdown and it re-arms on the next "end_turn" idle. The countdown is + // deferred while a confirmation-gated call is held or still dispatching, + // and starts fresh once the last such call resolves. nil uses + // [DefaultMaxIdle] (60s). A non-nil value <= 0 disables it — the runner + // then only stops on session termination, the consumer breaking out, or + // ctx cancellation. + MaxIdle *time.Duration + + // Logger receives non-fatal warnings (transient stream errors, send + // retries). Defaults to slog.Default(). + Logger *slog.Logger + + // RequestOptions are applied to every request the runner issues — the + // event stream, the reconcile list, and the tool-result send. The runner + // additionally tags each request with an x-stainless-helper header of + // its own (appended last, so it always wins on a collision with a + // caller-supplied tag). + // + // Self-hosted-environment callers must pass the environment key here. + // option.WithAuthToken alone only ADDS an Authorization header — the + // parent client's WithAPIKey middleware still emits X-Api-Key on every + // request, so both creds would land on the wire and the server rejects + // the dual auth on the events stream. Pair the bearer with an explicit + // X-Api-Key delete: + // + // RequestOptions: []option.RequestOption{ + // option.WithHeaderDel("X-Api-Key"), + // option.WithAuthToken(environmentKey), + // } + RequestOptions []option.RequestOption + + // ToolTimeout bounds a single tool's Execute call; a tool that runs longer + // is cancelled and reported as an error result. Zero uses the default of + // 120s. + ToolTimeout time.Duration + + // SendTimeout bounds a single attempt to post a tool-result event back to + // the session; transient failures are retried with exponential backoff + // for a bounded window (5m by default). Zero uses the default of 15s. + SendTimeout time.Duration + + // DrainTimeout bounds how long Close waits for in-flight tool executions + // to finish before it logs a warning and returns. Zero uses the default of + // 30s. + DrainTimeout time.Duration +} + +// DispatchedToolCall describes a single tool-use event that the runner has +// executed locally and (attempted to) post a result for. The consumer observes +// one of these per iteration of (*SessionToolRunner).Next. +// +// The runner dispatches both kinds of tool-call event the session API emits: +// agent.tool_use (the builtin agent_toolset_20260401 tools, answered with +// user.tool_result) and agent.custom_tool_use (user-defined function tools, +// answered with user.custom_tool_result). The Custom field reports which kind +// this dispatch came from and selects which embedded-event pair is populated — +// ToolUse/Result for a builtin call, CustomToolUse/CustomResult for a custom +// one. The flat top-level convenience fields (ToolUseID / Name / IsError / +// Posted) are populated for both kinds; read whichever is more convenient, +// they describe the same dispatch. The raw tool input lives on the triggering +// event (ToolUse.Input / CustomToolUse.Input) and the tool's output blocks on +// the posted result (Result.Content / CustomResult.Content). +// +// IsError is true if the tool reported failure or exceeded its per-call +// timeout. Posted is orthogonal to IsError: it reports whether a result event +// was successfully sent back to the session. Posted=false means the agent will +// not see a result from this runner, regardless of IsError — either because +// the send failed or because the tool name is not one this runner owns and the +// runner deliberately posted nothing and left the id pending for its owner. +type DispatchedToolCall struct { + // Custom reports whether this dispatch was triggered by an + // agent.custom_tool_use event (a user-defined function tool) rather than an + // agent.tool_use event (a builtin agent_toolset_20260401 tool). It selects + // which of the ToolUse/CustomToolUse and Result/CustomResult pairs below is + // populated; the other pair is left zero. + Custom bool + + // Confirmation is the verdict that gated this call, if any. "allow" + // means the call required user confirmation and was approved before it + // ran; "deny" means the user denied it or the server evaluated its + // permission to "deny" — the tool was never executed and nothing was + // posted (Posted=false, IsError=false, no Result). Empty means the call + // needed no confirmation. + Confirmation string + + // ToolUse is the full agent.tool_use event that triggered this dispatch, + // exactly as it arrived on the stream (or via reconcile). Populated only + // when Custom is false. + ToolUse BetaManagedAgentsAgentToolUseEvent + + // CustomToolUse is the full agent.custom_tool_use event that triggered this + // dispatch, exactly as it arrived on the stream (or via reconcile). + // Populated only when Custom is true. + CustomToolUse BetaManagedAgentsAgentCustomToolUseEvent + + // Result is the user.tool_result event the runner built and posted back to + // the session for a builtin agent.tool_use. Populated only when Custom is + // false. Read Result.Content for the tool's output blocks; the flat + // IsError mirrors Result.IsError and Posted reports whether the send + // succeeded. + Result BetaManagedAgentsUserToolResultEventParams + + // CustomResult is the user.custom_tool_result event the runner built and + // posted back to the session for an agent.custom_tool_use. Populated only + // when Custom is true. Read CustomResult.Content for the tool's output + // blocks; the flat IsError mirrors CustomResult.IsError and Posted + // reports whether the send succeeded. + CustomResult BetaManagedAgentsUserCustomToolResultEventParams + + // ToolUseID is the id of the tool-use event that triggered this dispatch + // (flat convenience copy of ToolUse.ID / CustomToolUse.ID). It is the id + // the posted result event references — tool_use_id for a builtin call, + // custom_tool_use_id for a custom one. Use it to correlate logs with the + // session history. + ToolUseID string + + // Name is the tool name from the tool-use event (flat convenience copy of + // ToolUse.Name / CustomToolUse.Name). + Name string + + // IsError captures whether the tool's outcome should be surfaced to the + // agent as an error. + IsError bool + + // Posted reports whether a result event for this call reached the session. + // False on a permanent 4xx or exhausted retries, and also false — with no + // result event ever built — for a tool name this runner does not own when + // it deliberately posts nothing and leaves the id pending for its owner. + Posted bool +} + +// SessionToolRunner attaches to a managed-agents session, executes incoming +// agent.tool_use and agent.custom_tool_use events via a local tool registry, +// and posts the matching user.tool_result / user.custom_tool_result events +// back. agent.mcp_tool_use events are left alone — MCP tools are server-side. +// It is the sessions-side counterpart to (*BetaMessageService).NewToolRunner: +// it does ONLY the tool-execution loop — attach to the event stream, reconcile +// via the events list endpoint, dispatch the registered tools, post results, +// and the idle-after-end_turn timeout. +// Lease heartbeating, work claiming, and skill download are not its concern — +// see [github.com/anthropics/anthropic-sdk-go/lib/environments.EnvironmentWorker] +// for the full self-hosted runner composition. +// +// A SessionToolRunner is NOT safe for concurrent use. All methods must be +// called from a single goroutine. Tool BetaTool.Execute handlers ARE called +// from a background goroutine, but only one at a time per runner (serial +// execution per the agent.tool_use contract). +// +// A call the server gated with evaluated_permission "ask" (the always_ask +// policy — or any unrecognized value, failing closed) is held until its +// user.tool_confirmation arrives: only an explicit "allow" runs it. A "deny" +// verdict — or a call the server already evaluated to "deny" — is never +// executed and posts nothing, but IS yielded (Confirmation="deny", +// Posted=false, no Result) so the caller can observe it. While a call is held +// the server parks the session at stop_reason "requires_action" and the +// runner waits until the verdict arrives, the session terminates, or ctx is +// cancelled — wrap in [environments.EnvironmentWorker] for lease-driven +// detach, or pass a context.WithTimeout for a wall-clock bound. +// +// Tool lifetime is the caller's responsibility; the runner never closes tools, +// so the same Tools slice can be reused across multiple sessions. +// +// Typical usage: +// +// r := client.Beta.Sessions.Events.NewToolRunner(ctx, sessionID, anthropic.SessionToolRunnerOptions{ +// Tools: agenttoolset.BetaAgentToolset20260401(&agenttoolset.AgentToolContext{Workdir: "."}), +// }) +// defer r.Close() +// for r.Next() { +// call := r.Current() +// // observe call.Name, call.IsError, call.Posted +// } +// if err := r.Err(); err != nil && !errors.Is(err, anthropic.ErrSessionTerminated) { +// log.Print(err) +// } +type SessionToolRunner struct { + eventService *BetaSessionEventService + sessionID string + opts SessionToolRunnerOptions + log *slog.Logger + byName map[string]BetaTool + + // reqOpts are applied to every request the runner issues: the caller's + // SessionToolRunnerOptions.RequestOptions plus the runner's own + // x-stainless-helper telemetry header. Immutable after construction. + reqOpts []option.RequestOption + + // ctx is the runner's internal context — a child of the caller's ctx — + // used by all background loops. cancel terminates them. + ctx context.Context + cancel context.CancelFunc + + // started/closed are plain bools; Next/Close/All are documented as + // single-goroutine. + started bool + closed bool + + // Set on start(); read-only after. + group *errgroup.Group + results chan DispatchedToolCall + + // Tracks in-flight tool executions for the drain phase. + inFlight sync.WaitGroup + + // Dedup sets — touched by the stream goroutine, the reconcile pass before + // each stream reconnect, and the dispatch goroutine. `seen` prevents + // re-dispatching the same tool_use across reconcile+stream overlaps; + // `answered` prevents re-executing a tool whose result the server already + // has. One mutex covers both — they're always touched together at low + // frequency. + mu sync.Mutex + seen map[string]struct{} + answered map[string]struct{} + // Confirmation gating (always_ask tools). `confirmationVerdicts` records + // every user.tool_confirmation verdict by tool_use_id (persistent for the + // run, like seen/answered). `awaitingConfirmation` holds the ask-gated tool + // calls whose verdict has not yet arrived. Both are only touched from the + // stream goroutine (streamLoop / reconcile), so no lock is needed for them. + confirmationVerdicts map[string]string + awaitingConfirmation map[string]pendingToolUse + + // idle owns the single stop-countdown, armed off the server's + // session.status_idle stop_reason, including its deferral while + // confirmation-gated tool work is outstanding. + idle *idleClock + + // sendWindow overrides defaultSessionRunnerSendRetryWindow when carried on + // the construction ctx (EnvironmentWorker's live lease TTL); nil otherwise. + sendWindow *sendwindow.Window + + // constructErr is set only at construction and is immutable thereafter; + // safe to read without a lock. Used to bail out of Next/start when required + // options are missing. + constructErr error + + // terminalErr is the first sentinel/wrapped error any loop produced. + // Surfaced via Err() after the results channel drains. + terminalErrMu sync.Mutex + terminalErr error + + // Yielded value most recently read from results. + current DispatchedToolCall +} + +// NewToolRunner returns a [SessionToolRunner] bound to ctx and this event +// service for the given managed-agents session. It is the sessions-side +// counterpart to (*BetaMessageService).NewToolRunner. sessionID is a leading +// positional argument, matching list/send/stream on the events resource. The +// first call to Next launches background goroutines (stream, dispatch). +// Logger defaults to slog.Default(). +// +// sessionID is validated here: if it is empty, Next returns false on the first +// call and Err returns the corresponding error. The returned pointer is never +// nil so `defer r.Close()` is always safe. +func (r *BetaSessionEventService) NewToolRunner(ctx context.Context, sessionID string, opts SessionToolRunnerOptions) *SessionToolRunner { + log := opts.Logger + if log == nil { + log = slog.Default() + } + log = log.With( + slog.String("component", "session-tool-runner"), + slog.String("session_id", sessionID), + ) + byName := make(map[string]BetaTool, len(opts.Tools)) + for _, t := range opts.Tools { + byName[t.Name()] = t + } + internalCtx, cancel := context.WithCancel(ctx) + reqOpts := make([]option.RequestOption, 0, len(opts.RequestOptions)+1) + reqOpts = append(reqOpts, opts.RequestOptions...) + reqOpts = append(reqOpts, stainlessheader.With(stainlessheader.SessionToolRunner)) + rn := &SessionToolRunner{ + eventService: r, + sessionID: sessionID, + opts: opts, + log: log, + byName: byName, + reqOpts: reqOpts, + ctx: internalCtx, + cancel: cancel, + sendWindow: sendwindow.FromContext(ctx), + seen: map[string]struct{}{}, + answered: map[string]struct{}{}, + } + rn.confirmationVerdicts = map[string]string{} + rn.awaitingConfirmation = map[string]pendingToolUse{} + rn.idle = newIdleClock(rn.maxIdle()) + if sessionID == "" { + rn.constructErr = errors.New("anthropic: NewToolRunner requires a non-empty session id") + } + return rn +} + +// NewSessionToolRunner is the package-level equivalent of +// (*BetaSessionEventService).NewToolRunner — useful when you have a [Client] +// value. Prefer client.Beta.Sessions.Events.NewToolRunner in new code. +func NewSessionToolRunner(ctx context.Context, client Client, sessionID string, opts SessionToolRunnerOptions) *SessionToolRunner { + return client.Beta.Sessions.Events.NewToolRunner(ctx, sessionID, opts) +} + +// Next advances the runner. Returns true if a new DispatchedToolCall is +// available via Current. Returns false when the bound context is cancelled, +// Close has been called, the session terminated, or MaxIdle elapsed (check Err +// to distinguish). +func (r *SessionToolRunner) Next() bool { + if r.constructErr != nil { + return false + } + r.start() + select { + case <-r.ctx.Done(): + return false + case call, ok := <-r.results: + if !ok { + return false + } + r.current = call + return true + } +} + +// Current returns the most recent DispatchedToolCall. Only valid after Next +// returned true. +func (r *SessionToolRunner) Current() DispatchedToolCall { + return r.current +} + +// Err returns the first non-recoverable error, or nil if iteration ended via +// the consumer's ctx cancellation or Close. Distinguish causes with errors.Is +// against [ErrSessionTerminated] and [ErrIdleTimeout]. Construction-time option +// errors are surfaced here as well. +func (r *SessionToolRunner) Err() error { + if r.constructErr != nil { + return r.constructErr + } + r.terminalErrMu.Lock() + defer r.terminalErrMu.Unlock() + return r.terminalErr +} + +// Close stops all background goroutines and waits for the cleanup goroutine +// (which drains in-flight tools) to finish. Safe to call multiple times. Always +// returns nil — the signature satisfies io.Closer so callers can `defer +// r.Close()` uniformly. The runner never closes the tools it was given. +func (r *SessionToolRunner) Close() error { + if r.closed { + return nil + } + r.closed = true + // Mark started so a late Next becomes a no-op. + r.started = true + r.cancel() + if r.results == nil { + return nil + } + for range r.results { //nolint:revive // drain channel; body intentionally empty + } + return nil +} + +// All returns a Go 1.23 range-over-func iterator yielding DispatchedToolCall +// values. On the final iteration err carries Err. +func (r *SessionToolRunner) All() iter.Seq2[DispatchedToolCall, error] { + return func(yield func(DispatchedToolCall, error) bool) { + for r.Next() { + if !yield(r.Current(), nil) { + return + } + } + if err := r.Err(); err != nil { + yield(DispatchedToolCall{}, err) + } + } +} + +// start lazily launches the background goroutines on the first Next call. +// Idempotent via the started flag. +func (r *SessionToolRunner) start() { + if r.started { + return + } + r.started = true + if r.constructErr != nil { + return + } + r.results = make(chan DispatchedToolCall, sessionRunnerResultsBuffer) + toolUseQ := make(chan pendingToolUse, sessionRunnerToolUseQueueBuffer) + g, gctx := errgroup.WithContext(r.ctx) + r.group = g + + g.Go(func() error { return r.streamLoop(gctx, toolUseQ) }) + g.Go(func() error { return r.dispatchLoop(gctx, toolUseQ) }) + g.Go(func() error { return r.idleWatchdog(gctx) }) + + go r.coordinate(g) +} + +func (r *SessionToolRunner) coordinate(g *errgroup.Group) { + groupErr := g.Wait() + r.setTerminalErr(groupErr) + r.drainInFlight() + r.cancel() + close(r.results) +} + +// drainInFlight waits up to the configured drain timeout (opts.DrainTimeout, or +// defaultSessionRunnerDrainTimeout) for any in-flight tool executions to +// complete, then logs a warning and returns. On timeout the waiter goroutine +// below stays blocked on r.inFlight.Wait() — and pins the runner state it closes +// over — until each tool actually returns; that is bounded by the per-tool +// timeout (opts.ToolTimeout, or defaultSessionRunnerToolTimeout), not unbounded, +// but it does mean a slow tool can outlive Close. +func (r *SessionToolRunner) drainInFlight() { + drainTimeout := r.drainTimeout() + done := make(chan struct{}) + go func() { + r.inFlight.Wait() + close(done) + }() + t := time.NewTimer(drainTimeout) + defer t.Stop() + select { + case <-done: + case <-t.C: + r.log.Warn("drain timeout exceeded; in-flight tools may still be running", + slog.Duration("drain_timeout", drainTimeout)) + } +} + +func (r *SessionToolRunner) setTerminalErr(err error) { + if err == nil { + return + } + r.terminalErrMu.Lock() + defer r.terminalErrMu.Unlock() + if r.terminalErr == nil { + r.terminalErr = err + } +} + +// pendingToolUse is a tool-call event the stream loop (or the reconcile pass) +// has picked up and queued for dispatch. Exactly one of toolUse / customToolUse +// is populated, selected by custom: an agent.tool_use is answered with a +// user.tool_result, an agent.custom_tool_use with a user.custom_tool_result. +// confirmation is the verdict that released it onto the queue — "allow" for an +// ask-gated call the user approved, "" for a call that needed no confirmation. +// Denied calls never reach the queue. +type pendingToolUse struct { + custom bool + toolUse BetaManagedAgentsAgentToolUseEvent + customToolUse BetaManagedAgentsAgentCustomToolUseEvent + confirmation string +} + +// id returns the tool-use event id — the key for the seen/answered dedup sets +// and the id the posted result event references. +func (p pendingToolUse) id() string { + if p.custom { + return p.customToolUse.ID + } + return p.toolUse.ID +} + +// name returns the tool name to look up in the local registry. +func (p pendingToolUse) name() string { + if p.custom { + return p.customToolUse.Name + } + return p.toolUse.Name +} + +// input returns the raw tool input the agent supplied. +func (p pendingToolUse) input() map[string]any { + if p.custom { + return p.customToolUse.Input + } + return p.toolUse.Input +} + +// idleClock is the idle stop-countdown state. idleWatchdog reads it and +// stops the runner once armedAt + maxIdle has elapsed. +// +// It also owns the deferral of that countdown: gated tool work registered via +// block — a call held for user confirmation, or a user-approved call still +// dispatching — keeps an arm pending until unblock retires the last blocker. +// The server can report an end_turn idle while a call is held (a legacy +// v1beta idle is up-converted with stop_reason "end_turn" unconditionally), so +// the countdown must never run over gated work: stopping then would drop the +// held call when its verdict later arrives, or cut the runner off before a +// released call's result can drive the next turn. +// +// Every transition runs under mu, so a disarm racing the pending-arm apply +// cannot be overwritten and resurrect a cancelled countdown. +type idleClock struct { + maxIdle time.Duration + + wake chan struct{} // cap-1; nudges idleWatchdog to re-read the state + + mu sync.Mutex + armedAt time.Time // zero when disarmed + // armPending is set when an arm found blockers outstanding; the unblock + // retiring the last blocker applies it. Cleared by any disarm. While it is + // set — and, more generally, while blockers is non-empty — armedAt is zero. + armPending bool + blockers map[string]struct{} +} + +func newIdleClock(maxIdle time.Duration) *idleClock { + return &idleClock{maxIdle: maxIdle, wake: make(chan struct{}, 1), blockers: map[string]struct{}{}} +} + +// noteEvent arms on session.status_idle with stop_reason "end_turn"; +// disarms on anything else. +// +// user.tool_confirmation is neutral: it signals neither agent activity nor an +// idle, and its effect on the clock flows through block/unblock instead — +// disarming here would discard the pending arm the verdict is about to settle. +func (c *idleClock) noteEvent(eventType, stopReason string) { + if eventType == "user.tool_confirmation" { + return + } + if eventType == string(BetaManagedAgentsSessionStatusIdleEventTypeSessionStatusIdle) && + stopReason == string(BetaManagedAgentsSessionEndTurnTypeEndTurn) { + c.arm() + } else { + c.disarm() + } +} + +// arm (re)starts the countdown from now and wakes the watchdog — or, while +// blockers are outstanding, holds the arm pending instead. +func (c *idleClock) arm() { + if c.maxIdle <= 0 { + return + } + c.mu.Lock() + if len(c.blockers) > 0 { + // Any running countdown is stale: the arm defers because gated work is + // outstanding, so the session is not idly waiting to stop. + c.armPending = true + was := !c.armedAt.IsZero() + c.armedAt = time.Time{} + c.mu.Unlock() + if was { + c.signal() + } + return + } + c.armPending = false + c.armedAt = time.Now() + c.mu.Unlock() + c.signal() +} + +// disarm cancels the countdown and any pending arm. Blockers persist — they +// track real outstanding work, retired only by unblock. +func (c *idleClock) disarm() { + c.mu.Lock() + c.armPending = false + was := !c.armedAt.IsZero() + c.armedAt = time.Time{} + c.mu.Unlock() + if was { + c.signal() + } +} + +// block registers gated work that must finish before an idle countdown starts. +func (c *idleClock) block(id string) { + c.mu.Lock() + c.blockers[id] = struct{}{} + // Defensive: a blocker taken while the countdown runs converts it into a + // pending arm, so a stale end_turn cannot stop the runner mid-gate. + was := !c.armedAt.IsZero() + if was { + c.armPending = true + c.armedAt = time.Time{} + } + c.mu.Unlock() + if was { + c.signal() + } +} + +// unblock retires gated work (a no-op for ids never blocked) and applies a +// pending arm once the last blocker retires — the countdown then runs a full +// fresh window from now. The apply happens inside the critical section: +// deciding under the lock but stamping after releasing it would let a +// concurrent disarm (a new stream event — the session is not idle) land in the +// gap and be overwritten, resurrecting a cancelled countdown. +func (c *idleClock) unblock(id string) { + c.mu.Lock() + delete(c.blockers, id) + fire := len(c.blockers) == 0 && c.armPending + if fire { + c.armPending = false + c.armedAt = time.Now() + } + c.mu.Unlock() + if fire { + c.signal() + } +} + +func (c *idleClock) signal() { + select { + case c.wake <- struct{}{}: + default: + } +} + +// snapshot returns the current arm timestamp for the watchdog. +func (c *idleClock) snapshot() time.Time { + c.mu.Lock() + defer c.mu.Unlock() + return c.armedAt +} + +// streamLoop tails the live SSE stream with reconnect backoff. On each +// (re)connect it opens the stream FIRST and only then reconciles full history, +// so a tool_use the server emits during the reconcile window lands on the +// stream rather than in the gap between the two; the per-event seen/answered +// sets dedup events both passes observe. Both agent.tool_use and +// agent.custom_tool_use are dispatched; agent.mcp_tool_use is ignored (MCP +// tools run server-side). Closes toolUseQ on exit so dispatchLoop can return. +func (r *SessionToolRunner) streamLoop(ctx context.Context, out chan<- pendingToolUse) error { + defer close(out) + + backoff := sessionRunnerStreamBackoffStart + for { + if ctx.Err() != nil { + return nil + } + + // Open the live stream before reconciling history: StreamEvents makes + // its HTTP request eagerly, so once it returns the connection is + // established and no event emitted during reconcile can slip through + // the gap. seen/answered dedup whatever both passes pick up. + stream := r.eventService.StreamEvents( + ctx, + r.sessionID, + BetaSessionEventStreamParams{}, + r.reqOpts..., + ) + if err := r.reconcile(ctx, out); err != nil { + _ = stream.Close() + if errors.Is(err, ErrSessionTerminated) { + return err + } + if ctx.Err() != nil { + return nil + } + return err + } + if ctx.Err() != nil { + _ = stream.Close() + return nil + } + + // Reset backoff only once the connection has been healthy. + connectedAt := time.Now() + var sentinel error + for stream.Next() { + if time.Since(connectedAt) > sessionRunnerStreamHealthyAfter { + backoff = sessionRunnerStreamBackoffStart + } + ev := stream.Current() + r.idle.noteEvent(ev.Type, ev.StopReason.Type) + switch ev.Type { + case string(BetaManagedAgentsAgentToolUseEventTypeAgentToolUse): + if r.markSeen(ev.ID) { + r.routeToolEvent(ctx, out, pendingToolUse{toolUse: ev.AsAgentToolUse()}) + } + case string(BetaManagedAgentsAgentCustomToolUseEventTypeAgentCustomToolUse): + if r.markSeen(ev.ID) { + r.routeToolEvent(ctx, out, pendingToolUse{custom: true, customToolUse: ev.AsAgentCustomToolUse()}) + } + case "user.tool_confirmation": + r.noteConfirmation(ctx, out, ev.ToolUseID, string(ev.Result)) + case string(BetaManagedAgentsUserToolResultEventTypeUserToolResult): + r.markAnswered(ev.ToolUseID) + case string(BetaManagedAgentsUserCustomToolResultEventTypeUserCustomToolResult): + r.markAnswered(ev.CustomToolUseID) + case string(BetaManagedAgentsSessionStatusTerminatedEventTypeSessionStatusTerminated), + string(BetaManagedAgentsSessionDeletedEventTypeSessionDeleted): + r.log.Info("session terminated", slog.String("type", ev.Type)) + sentinel = ErrSessionTerminated + } + if sentinel != nil { + break + } + } + _ = stream.Close() + if sentinel != nil { + return sentinel + } + if err := stream.Err(); err != nil { + if ctx.Err() != nil { + return nil + } + if isFatal4xxStatus(err) { + r.log.Error("permanent stream failure", slog.Any("error", err)) + return fmt.Errorf("stream: %w", err) + } + r.log.Warn("stream disconnected; reconnecting", + slog.Any("error", err), slog.Duration("backoff", backoff)) + } + if ctx.Err() != nil { + return nil + } + // Jittered backoff so a fleet of runners reconnecting after the same + // blip don't synchronise into a thundering herd. + sleepCtx(ctx, jitterDuration(backoff)) + backoff = min(backoff*2, sessionRunnerStreamBackoffCap) + } +} + +// jitterDuration returns a random duration in [d/2, d) so concurrent runners +// spread their retries instead of synchronising. d <= 1 is returned unchanged. +func jitterDuration(d time.Duration) time.Duration { + if d <= 1 { + return d + } + half := d / 2 + return half + time.Duration(rand.Int64N(int64(d-half))) +} + +// reconcile lists full event history and emits any tool_use the runner has not +// already posted a result for. It pairs agent.tool_use with user.tool_result +// and agent.custom_tool_use with user.custom_tool_result when deciding what is +// still unanswered. +// +// Every tool-use event is collected — and marked seen so the concurrently +// running stream loop does not also enqueue it — but the enqueue decision is +// gated on `answered`, NOT `seen`: a tool_use whose result post previously +// FAILED was never marked answered, so it is re-dispatched on the next +// reconcile instead of being silently dropped. +// +// Returns ErrSessionTerminated if the listed history contains a +// session.status_terminated or session.deleted event — the live stream +// will never replay a terminate that fired before we attached, so without +// this check streamLoop would reconnect forever against a dead session. +func (r *SessionToolRunner) reconcile(ctx context.Context, out chan<- pendingToolUse) error { + var pending []pendingToolUse + lastWasEndTurn := false + pager := r.eventService.ListAutoPaging(ctx, r.sessionID, + BetaSessionEventListParams{ + Limit: param.NewOpt(int64(1000)), + // Reconcile assumes oldest-to-newest event order. + Order: BetaSessionEventListParamsOrderAsc, + }, + r.reqOpts...) + for pager.Next() { + ev := pager.Current() + switch ev.Type { + case string(BetaManagedAgentsAgentToolUseEventTypeAgentToolUse): + r.markSeen(ev.ID) + pending = append(pending, pendingToolUse{toolUse: ev.AsAgentToolUse()}) + case string(BetaManagedAgentsAgentCustomToolUseEventTypeAgentCustomToolUse): + r.markSeen(ev.ID) + pending = append(pending, pendingToolUse{custom: true, customToolUse: ev.AsAgentCustomToolUse()}) + case "user.tool_confirmation": + // Record the verdict only, before the routing pass below, so a + // tool call whose confirmation appears later in the same history + // is routed with its verdict already known. Skip already-answered + // calls so we don't re-record their verdict on every reconcile. + if !r.isAnswered(ev.ToolUseID) { + r.confirmationVerdicts[ev.ToolUseID] = string(ev.Result) + } + case string(BetaManagedAgentsUserToolResultEventTypeUserToolResult): + r.markAnswered(ev.ToolUseID) + case string(BetaManagedAgentsUserCustomToolResultEventTypeUserCustomToolResult): + r.markAnswered(ev.CustomToolUseID) + case string(BetaManagedAgentsSessionStatusTerminatedEventTypeSessionStatusTerminated), + string(BetaManagedAgentsSessionDeletedEventTypeSessionDeleted): + // The session is already over. Any pending tool_use we + // collected above can't be answered (the server won't accept + // results against a terminated session) and the live stream + // will never replay this event, so streamLoop must shut down. + r.log.Info("reconcile: session already terminated", slog.String("type", ev.Type)) + return ErrSessionTerminated + } + lastWasEndTurn = ev.Type == string(BetaManagedAgentsSessionStatusIdleEventTypeSessionStatusIdle) && + ev.StopReason.Type == string(BetaManagedAgentsSessionEndTurnTypeEndTurn) + } + if err := pager.Err(); err != nil { + r.log.Warn("reconcile list failed", slog.Any("error", err)) + return nil + } + var unanswered []pendingToolUse + for _, p := range pending { + if !r.isAnswered(p.id()) { + unanswered = append(unanswered, p) + } + } + // Disarm before routing: the routing pass can block on a full work queue + // while the clock is still armed from before the reconnect. + r.idle.disarm() + for _, p := range unanswered { + r.routeToolEvent(ctx, out, p) + } + // A held call's verdict is normally applied by the routing pass above; if + // its tool_use fell outside the listed window the pass never saw it, so + // apply the recorded verdict to the held copy here. + for id, held := range r.awaitingConfirmation { + if v, ok := r.confirmationVerdicts[id]; ok { + r.applyVerdict(ctx, out, held, v) + } + } + // Routing resolved denied calls in place (marking them answered) and held + // ask-gated calls for their verdict. If the last event in history is an + // end_turn idle and no tool work is outstanding, the session is done — arm + // the stop-countdown so the runner stops even if that end_turn arrived + // during a disconnect. A still-held call doesn't count as outstanding: the + // clock blocks on it, so the arm is held pending until its verdict lands. + if lastWasEndTurn && len(r.outstanding(unanswered)) == 0 { + r.idle.arm() + } + return nil +} + +// outstanding returns the reconciled tool calls that still owe the session a +// result: neither answered (a denial resolves a call in place) nor held +// awaiting a user confirmation. +func (r *SessionToolRunner) outstanding(unanswered []pendingToolUse) []pendingToolUse { + var out []pendingToolUse + for _, p := range unanswered { + id := p.id() + if _, held := r.awaitingConfirmation[id]; held { + continue + } + if r.isAnswered(id) { + continue + } + out = append(out, p) + } + return out +} + +// dispatchLoop reads tool-use events (agent.tool_use and agent.custom_tool_use) +// serially and executes each. The session contract guarantees one outstanding +// tool-use per session at a time, so serial execution is correct. Pushes the +// resulting DispatchedToolCall to r.results. +// +// Each call is unblocked once it is fully disposed of — executed, or moot +// because it was answered elsewhere — retiring the idle-clock blocker +// applyVerdict took on a user-approved call. unblock is a no-op for a call +// that was never gated. +func (r *SessionToolRunner) dispatchLoop(ctx context.Context, in <-chan pendingToolUse) error { + for { + select { + case <-ctx.Done(): + return nil + case p, ok := <-in: + if !ok { + return nil + } + // Retire the blocker only once the call is fully disposed of — + // executed and surfaced, or moot because it was answered + // elsewhere. Surfacing can block on a full results buffer, and + // the countdown must not start while the call is still queued. + func() { + defer r.idle.unblock(p.id()) + if r.isAnswered(p.id()) { + return + } + r.surfaceCall(ctx, r.execute(ctx, p)) + }() + } + } +} + +// maxIdle returns the configured idle-grace duration: DefaultMaxIdle when +// opts.MaxIdle is nil, otherwise the pointed-to value (<= 0 means disabled). +func (r *SessionToolRunner) maxIdle() time.Duration { + if r.opts.MaxIdle == nil { + return DefaultMaxIdle + } + return *r.opts.MaxIdle +} + +// toolTimeout returns the per-tool Execute deadline: opts.ToolTimeout when set +// to a positive value, otherwise defaultSessionRunnerToolTimeout. +func (r *SessionToolRunner) toolTimeout() time.Duration { + if r.opts.ToolTimeout > 0 { + return r.opts.ToolTimeout + } + return defaultSessionRunnerToolTimeout +} + +// sendTimeout returns the per-attempt tool-result send deadline: +// opts.SendTimeout when set to a positive value, otherwise +// defaultSessionRunnerSendTimeout. +func (r *SessionToolRunner) sendTimeout() time.Duration { + if r.opts.SendTimeout > 0 { + return r.opts.SendTimeout + } + return defaultSessionRunnerSendTimeout +} + +// sendRetryWindow returns how long a transiently failing tool-result send keeps +// retrying: the ctx-carried window when set, else defaultSessionRunnerSendRetryWindow. +func (r *SessionToolRunner) sendRetryWindow() time.Duration { + if d := r.sendWindow.Get(); d > 0 { + return d + } + return defaultSessionRunnerSendRetryWindow +} + +// drainTimeout returns how long Close waits for in-flight tools: opts.DrainTimeout +// when set to a positive value, otherwise defaultSessionRunnerDrainTimeout. +func (r *SessionToolRunner) drainTimeout() time.Duration { + if r.opts.DrainTimeout > 0 { + return r.opts.DrainTimeout + } + return defaultSessionRunnerDrainTimeout +} + +// idleWatchdog returns ErrIdleTimeout once the session has been idle past +// the bound matching its stop_reason. It is event-driven: the stream +// goroutine nudges idle.wake whenever it updates the clock, and the +// watchdog re-arms a single timer off that authoritative stamp — no +// polling ticker. +func (r *SessionToolRunner) idleWatchdog(ctx context.Context) error { + timer := time.NewTimer(time.Hour) + if !timer.Stop() { + <-timer.C + } + defer timer.Stop() + + rearm := func() { + if !timer.Stop() { + select { + case <-timer.C: + default: + } + } + if at := r.idle.snapshot(); !at.IsZero() { + remaining := r.idle.maxIdle - time.Since(at) + if remaining < time.Millisecond { + remaining = time.Millisecond + } + timer.Reset(remaining) + } + } + + for { + select { + case <-ctx.Done(): + return nil + case <-r.idle.wake: + rearm() + case <-timer.C: + at := r.idle.snapshot() + if !at.IsZero() && time.Since(at) >= r.idle.maxIdle { + r.log.Info("session idle after end_turn; stopping", + slog.Duration("max_idle", r.idle.maxIdle)) + return ErrIdleTimeout + } + rearm() + } + } +} + +// execute looks up the tool by name, runs it under a per-tool timeout, posts +// the matching result event (user.tool_result for an agent.tool_use, +// user.custom_tool_result for an agent.custom_tool_use), and returns the +// DispatchedToolCall to be yielded. +func (r *SessionToolRunner) execute(ctx context.Context, p pendingToolUse) DispatchedToolCall { + id, name := p.id(), p.name() + log := r.log.With( + slog.String("tool", name), + slog.String("tool_use_id", id), + slog.Bool("custom", p.custom), + ) + log.Info("executing tool") + + r.inFlight.Add(1) + defer r.inFlight.Done() + + call := DispatchedToolCall{ + Custom: p.custom, + ToolUse: p.toolUse, + CustomToolUse: p.customToolUse, + ToolUseID: id, + Name: name, + Confirmation: p.confirmation, + } + + rawInput, err := json.Marshal(p.input()) + if err != nil { + log.Warn("re-encoding tool input failed", slog.Any("error", err)) + call.IsError = true + return r.postCall(ctx, call, textOnlyResult(fmt.Sprintf("tool input could not be re-encoded: %v", err))) + } + + var blocks []BetaToolResultBlockParamContentUnion + tool, ok := r.byName[name] + if !ok { + // Skip (split-client partial fulfilment): a name this runner is not + // registered for belongs to the other client servicing this session + // (typically the customer's app backend handling custom tools). Post + // NO result, do not mark it answered, and leave the tool_use_id + // pending for its owner — claiming it would corrupt the conversation. + // Still yield the call so the caller can observe the unowned + // dispatch; nothing was sent, so Posted and IsError stay false and no + // result event is populated. The id remains unanswered, so reconcile + // keeps it out of the idle/end-turn accounting and re-surfaces it + // after a reconnect until its owner answers it. + log.Info("tool not owned by this runner; leaving the tool_use_id pending for its owner") + return call + } else { + // Derive the per-tool timeout from the runner ctx (not + // context.WithoutCancel) so cancelling the runner also aborts an + // in-flight tool instead of leaving it to run out the full timeout + // while teardown blocks on the drain. + toolTimeout := r.toolTimeout() + toolCtx, cancel := context.WithTimeout(ctx, toolTimeout) + out, runErr := tool.Execute(toolCtx, rawInput) + cancel() + switch { + case errors.Is(toolCtx.Err(), context.DeadlineExceeded): + call.IsError = true + blocks = textOnlyResult(fmt.Sprintf("tool %q timed out after %s", name, toolTimeout)) + case runErr != nil: + call.IsError = true + blocks = textOnlyResult(runErr.Error()) + default: + blocks = out + call.IsError = false + } + } + if len(blocks) == 0 { + blocks = textOnlyResult("(no output)") + } + return r.postCall(ctx, call, blocks) +} + +// textOnlyResult wraps s as a single text tool-result block. +func textOnlyResult(s string) []BetaToolResultBlockParamContentUnion { + return []BetaToolResultBlockParamContentUnion{{OfText: &BetaTextBlockParam{Text: s}}} +} + +// toToolResultContent converts tool result blocks for a user.tool_result event +// by JSON round-tripping each block into the event content union, falling back +// to a text block holding the raw JSON when the round-trip is incomplete. Empty +// text blocks are posted as "(no output)". +func toToolResultContent(blocks []BetaToolResultBlockParamContentUnion) []BetaManagedAgentsUserToolResultEventParamsContentUnion { + out := make([]BetaManagedAgentsUserToolResultEventParamsContentUnion, 0, len(blocks)) + for _, b := range blocks { + raw, err := json.Marshal(b) + if err != nil || len(raw) == 0 || string(raw) == "null" { + continue + } + var dst BetaManagedAgentsUserToolResultEventParamsContentUnion + if json.Unmarshal(raw, &dst) == nil && roundTripComplete(&dst) { + // The Sessions API rejects empty text blocks; a tool that + // succeeds silently must still produce a postable result. + if dst.OfText != nil && dst.OfText.Text == "" { + dst.OfText.Text = "(no output)" + } + out = append(out, dst) + continue + } + out = append(out, BetaManagedAgentsUserToolResultEventParamsContentUnion{ + OfText: &BetaManagedAgentsTextBlockParam{Text: string(raw)}, + }) + } + return out +} + +// roundTripComplete reports whether dst decoded into a variant whose required +// fields survived the JSON round-trip. +func roundTripComplete(dst *BetaManagedAgentsUserToolResultEventParamsContentUnion) bool { + switch { + case dst.OfText != nil: + return true + case dst.OfImage != nil: + return dst.OfImage.Source.asAny() != nil + case dst.OfDocument != nil: + return dst.OfDocument.Source.asAny() != nil + case dst.OfSearchResult != nil: + return dst.OfSearchResult.Source != "" && dst.OfSearchResult.Title != "" + default: + return false + } +} + +// toCustomToolResultContent converts tool result blocks for a +// user.custom_tool_result event using the same round-trip as toToolResultContent. +func toCustomToolResultContent(blocks []BetaToolResultBlockParamContentUnion) []BetaManagedAgentsUserCustomToolResultEventParamsContentUnion { + src := toToolResultContent(blocks) + out := make([]BetaManagedAgentsUserCustomToolResultEventParamsContentUnion, 0, len(src)) + for _, b := range src { + out = append(out, BetaManagedAgentsUserCustomToolResultEventParamsContentUnion{ + OfText: b.OfText, + OfImage: b.OfImage, + OfDocument: b.OfDocument, + OfSearchResult: b.OfSearchResult, + }) + } + return out +} + +// postCall builds the matching result event for call — user.custom_tool_result +// when call.Custom, otherwise user.tool_result — from the tool's result blocks, +// sends it, and records the event on call.Result / call.CustomResult and the +// send outcome on call.Posted. The tool-use id is marked answered ONLY when +// the result post actually succeeds: a failed post leaves the call unanswered +// so the next reconcile re-dispatches it instead of silently dropping it. +func (r *SessionToolRunner) postCall(ctx context.Context, call DispatchedToolCall, blocks []BetaToolResultBlockParamContentUnion) DispatchedToolCall { + var event BetaManagedAgentsEventParamsUnion + if call.Custom { + call.CustomResult = BetaManagedAgentsUserCustomToolResultEventParams{ + CustomToolUseID: call.ToolUseID, + Type: BetaManagedAgentsUserCustomToolResultEventParamsTypeUserCustomToolResult, + IsError: param.NewOpt(call.IsError), + Content: toCustomToolResultContent(blocks), + } + event = BetaManagedAgentsEventParamsUnion{OfUserCustomToolResult: &call.CustomResult} + } else { + call.Result = BetaManagedAgentsUserToolResultEventParams{ + ToolUseID: call.ToolUseID, + Type: BetaManagedAgentsUserToolResultEventParamsTypeUserToolResult, + IsError: param.NewOpt(call.IsError), + Content: toToolResultContent(blocks), + } + event = BetaManagedAgentsEventParamsUnion{OfUserToolResult: &call.Result} + } + call.Posted = r.sendResult(ctx, event, call.ToolUseID) + if call.Posted { + r.markAnswered(call.ToolUseID) + } + return call +} + +// sendResult posts a tool-result event (user.tool_result or +// user.custom_tool_result). Returns true on success. Transient failures are +// retried with jittered exponential backoff until sendRetryWindow (re-read on +// each failure, so a lease TTL learned mid-retry applies) has elapsed since the +// first attempt; a permanent 4xx or ctx cancellation short-circuits and returns +// false. +func (r *SessionToolRunner) sendResult(ctx context.Context, event BetaManagedAgentsEventParamsUnion, toolUseID string) bool { + params := BetaSessionEventSendParams{ + Events: []BetaManagedAgentsEventParamsUnion{event}, + } + start := time.Now() + backoff := sessionRunnerSendBackoffStart + for attempt := 1; ; attempt++ { + sendCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), r.sendTimeout()) + _, err := r.eventService.Send(sendCtx, r.sessionID, params, r.reqOpts...) + cancel() + if err == nil { + return true + } + if isFatal4xxStatus(err) { + r.log.Error("tool result send hit permanent 4xx; not retrying", + slog.String("tool_use_id", toolUseID), slog.Any("error", err)) + return false + } + if ctx.Err() != nil { + r.log.Debug("tool result send abandoned: ctx cancelled", + slog.String("tool_use_id", toolUseID)) + return false + } + remaining := r.sendRetryWindow() - time.Since(start) + if remaining <= 0 { + r.log.Error("tool result send failed; retry window exhausted", + slog.String("tool_use_id", toolUseID), + slog.Int("attempts", attempt), + slog.Any("error", err)) + return false + } + wait := min(jitterDuration(backoff), remaining) + r.log.Warn("tool result send failed; retrying", + slog.String("tool_use_id", toolUseID), + slog.Int("attempt", attempt), + slog.Duration("backoff", wait), + slog.Any("error", err)) + sleepCtx(ctx, wait) + backoff = min(backoff*2, sessionRunnerSendBackoffCap) + } +} + +func (r *SessionToolRunner) markSeen(id string) bool { + r.mu.Lock() + defer r.mu.Unlock() + if _, ok := r.seen[id]; ok { + return false + } + r.seen[id] = struct{}{} + return true +} + +func (r *SessionToolRunner) markAnswered(id string) { + r.mu.Lock() + r.answered[id] = struct{}{} + r.mu.Unlock() +} + +func (r *SessionToolRunner) isAnswered(id string) bool { + r.mu.Lock() + defer r.mu.Unlock() + _, ok := r.answered[id] + return ok +} + +// routeToolEvent enqueues p for dispatch, honoring its evaluated permission. +// A call the server gated with "ask" (or any unrecognized permission — fail +// closed) is held until its user.tool_confirmation arrives; a call already +// evaluated to "deny" is resolved as denied regardless of any recorded verdict. +func (r *SessionToolRunner) routeToolEvent(ctx context.Context, out chan<- pendingToolUse, p pendingToolUse) { + id := p.id() + // Only builtin agent.tool_use carries evaluated_permission today; if the + // field ever lands on agent.custom_tool_use the gate must keep failing + // closed rather than dispatch a gated call by event type. + perm := "" + if !p.custom { + perm = string(p.toolUse.EvaluatedPermission) + } + // Comma-ok, not the zero value: a verdict this SDK doesn't recognise — + // including an empty one — must reach applyVerdict and fail closed, not + // read as "no verdict yet" and dispatch. + verdict, hasVerdict := r.confirmationVerdicts[id] + if perm == "deny" { + // A server-side deny overrides any (stray) recorded verdict. + verdict, hasVerdict = "deny", true + } + if !hasVerdict { + if perm == "" || perm == "allow" { + select { + case <-ctx.Done(): + case out <- p: + } + } else if _, held := r.awaitingConfirmation[id]; !held { + // "ask" — or a permission this SDK doesn't recognise — waits for + // the user's verdict. (Already held: a reconcile after a reconnect + // re-routes the call; keep the existing hold.) + r.log.Info("tool call awaiting confirmation; holding", + slog.String("tool", p.name()), slog.String("tool_use_id", id)) + r.awaitingConfirmation[id] = p + r.idle.block(id) + } + return + } + r.applyVerdict(ctx, out, p, verdict) +} + +// noteConfirmation records an allow/deny verdict and releases the held call it +// gates, if any. A verdict for a call this runner has not seen yet (or one it +// never gates, e.g. an agent.mcp_tool_use) is kept in confirmationVerdicts so +// a later route of that call resolves instantly. +func (r *SessionToolRunner) noteConfirmation(ctx context.Context, out chan<- pendingToolUse, toolUseID, result string) { + r.confirmationVerdicts[toolUseID] = result + if held, ok := r.awaitingConfirmation[toolUseID]; ok { + r.applyVerdict(ctx, out, held, result) + } +} + +// applyVerdict dispatches or resolves a gated call according to its verdict. +// Only an explicit "allow" releases the call to execute; anything else fails +// closed as a denial. A denied call is marked answered and yielded directly +// (nothing ran, nothing posted) — it never reaches the dispatch queue. +// +// The idle-clock blocker accounting lives here: a denial retires the held +// call's blocker, while an allow keeps one on the call — taking it now if the +// verdict was already known when the call was routed, so no hold was ever +// taken — until the dispatch loop has finished with it. The countdown must not +// run over gated work that is still in flight. +func (r *SessionToolRunner) applyVerdict(ctx context.Context, out chan<- pendingToolUse, p pendingToolUse, verdict string) { + id := p.id() + _, wasHeld := r.awaitingConfirmation[id] + delete(r.awaitingConfirmation, id) + if verdict == "allow" { + r.log.Info("tool call confirmed", slog.String("tool", p.name()), slog.String("tool_use_id", id)) + if !wasHeld { + r.idle.block(id) + } + p.confirmation = "allow" + select { + case <-ctx.Done(): + case out <- p: + } + return + } + if wasHeld { + r.idle.unblock(id) + } + r.markAnswered(id) + r.log.Info("tool call denied; not executing", slog.String("tool", p.name()), slog.String("tool_use_id", id)) + r.surfaceCall(ctx, DispatchedToolCall{ + Custom: p.custom, + ToolUse: p.toolUse, + CustomToolUse: p.customToolUse, + ToolUseID: id, + Name: p.name(), + IsError: false, + Posted: false, + Confirmation: "deny", + }) +} + +// surfaceCall yields call to the consumer, tolerating a consumer that left +// early (ctx cancelled). The underlying work already happened; only the +// observability event is lost. +func (r *SessionToolRunner) surfaceCall(ctx context.Context, call DispatchedToolCall) { + select { + case <-ctx.Done(): + case r.results <- call: + } +} + +// sleepCtx sleeps for d or until ctx is done, whichever comes first. +func sleepCtx(ctx context.Context, d time.Duration) { + t := time.NewTimer(d) + defer t.Stop() + select { + case <-ctx.Done(): + case <-t.C: + } +} + +// isFatal4xxStatus reports whether err is a client error that will not succeed +// on retry. 408 (timeout), 409 (conflict) and 429 (rate-limited) are excluded +// so callers back off rather than tear down, mirroring the statuses the core +// client itself retries (internal/requestconfig). Keep in step with +// lib/environments.isFatal4xx, the environment worker's copy. +func isFatal4xxStatus(err error) bool { + var apiErr *Error + if !errors.As(err, &apiErr) { + return false + } + c := apiErr.StatusCode + return c >= 400 && c < 500 && c != 408 && c != 409 && c != 429 +} diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/betasessionutil.go b/vendor/github.com/anthropics/anthropic-sdk-go/betasessionutil.go new file mode 100644 index 000000000..5f69e2ef9 --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/betasessionutil.go @@ -0,0 +1,82 @@ +package anthropic + +import "strings" + +// BetaManagedAgentsEventAccumulator folds event_start / event_delta preview +// events into per-event-id agent.message snapshots. The zero value is ready +// to use. +// +// var previews anthropic.BetaManagedAgentsEventAccumulator +// for stream.Next() { +// event := stream.Current() +// previews.Accumulate(event) +// +// if event.Type == "event_delta" { +// fmt.Print(previews.AgentMessageText(event.EventID)) +// } +// } +type BetaManagedAgentsEventAccumulator struct { + // AgentMessages holds one snapshot per event id. Reconciled canonical + // agent.message events persist across model requests; unreconciled previews + // are dropped at span.model_request_end because the server will never + // complete them. The buffered event stream is the authoritative transcript. + AgentMessages map[string]BetaManagedAgentsAgentMessageEvent +} + +func (acc *BetaManagedAgentsEventAccumulator) Accumulate(event BetaManagedAgentsStreamSessionEventsUnion) { + if acc == nil { + return + } + if acc.AgentMessages == nil { + acc.AgentMessages = map[string]BetaManagedAgentsAgentMessageEvent{} + } + + switch event.Type { + case "event_start": + if event.Event.Type == "agent.message" { + acc.AgentMessages[event.Event.ID] = BetaManagedAgentsAgentMessageEvent{ + ID: event.Event.ID, + Type: BetaManagedAgentsAgentMessageEventTypeAgentMessage, + } + } + + case "event_delta": + msg, ok := acc.AgentMessages[event.EventID] + if !ok || msg.JSON.ProcessedAt.Valid() { + return + } + idx := int(event.Delta.Index) + if idx < 0 || idx > len(msg.Content) { + return + } + if idx == len(msg.Content) { + var block BetaManagedAgentsAgentMessageEventContentUnion + _ = block.UnmarshalJSON([]byte(event.Delta.Content.RawJSON())) + msg.Content = append(msg.Content, block) + } else { + msg.Content[idx].Text += event.Delta.Content.Text + } + acc.AgentMessages[event.EventID] = msg + + case "agent.message": + acc.AgentMessages[event.ID] = event.AsAgentMessage() + + case "span.model_request_end": + for id, msg := range acc.AgentMessages { + if !msg.JSON.ProcessedAt.Valid() { + delete(acc.AgentMessages, id) + } + } + } +} + +func (acc *BetaManagedAgentsEventAccumulator) AgentMessageText(eventID string) string { + if acc == nil { + return "" + } + var b strings.Builder + for _, block := range acc.AgentMessages[eventID].Content { + b.WriteString(block.Text) + } + return b.String() +} diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/betaskill.go b/vendor/github.com/anthropics/anthropic-sdk-go/betaskill.go index 1dd9dc9cd..c4d809604 100644 --- a/vendor/github.com/anthropics/anthropic-sdk-go/betaskill.go +++ b/vendor/github.com/anthropics/anthropic-sdk-go/betaskill.go @@ -286,16 +286,16 @@ func (r *BetaSkillDeleteResponse) UnmarshalJSON(data []byte) error { } type BetaSkillNewParams struct { + // Files to upload for the skill. + // + // All files must be in the same top-level directory and must include a SKILL.md + // file at the root of that directory. + Files []io.Reader `json:"files,omitzero" api:"required" format:"binary"` // Display title for the skill. // // This is a human-readable label that is not included in the prompt sent to the // model. DisplayTitle param.Opt[string] `json:"display_title,omitzero"` - // Files to upload for the skill. - // - // All files must be in the same top-level directory and must include a SKILL.md - // file at the root of that directory. - Files []io.Reader `json:"files,omitzero" format:"binary"` // Optional header to specify the beta version(s) you want to use. Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` paramObj @@ -350,7 +350,7 @@ type BetaSkillListParams struct { // URLQuery serializes [BetaSkillListParams]'s query parameters as `url.Values`. func (r BetaSkillListParams) URLQuery() (v url.Values, err error) { return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ - ArrayFormat: apiquery.ArrayQueryFormatComma, + ArrayFormat: apiquery.ArrayQueryFormatBrackets, NestedFormat: apiquery.NestedQueryFormatBrackets, }) } diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/betaskillversion.go b/vendor/github.com/anthropics/anthropic-sdk-go/betaskillversion.go index dabce4f15..501a55aaa 100644 --- a/vendor/github.com/anthropics/anthropic-sdk-go/betaskillversion.go +++ b/vendor/github.com/anthropics/anthropic-sdk-go/betaskillversion.go @@ -128,6 +128,26 @@ func (r *BetaSkillVersionService) Delete(ctx context.Context, version string, pa return res, err } +// Download a skill version's content as a zip archive. +func (r *BetaSkillVersionService) Download(ctx context.Context, version string, params BetaSkillVersionDownloadParams, opts ...option.RequestOption) (res *http.Response, err error) { + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "skills-2025-10-02"), option.WithHeader("Accept", "application/binary")}, opts...) + if params.SkillID == "" { + err = errors.New("missing required skill_id parameter") + return nil, err + } + if version == "" { + err = errors.New("missing required version parameter") + return nil, err + } + path := fmt.Sprintf("v1/skills/%s/versions/%s/content?beta=true", params.SkillID, version) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...) + return res, err +} + type BetaSkillVersionNewResponse struct { // Unique identifier for the skill version. // @@ -307,7 +327,7 @@ type BetaSkillVersionNewParams struct { // // All files must be in the same top-level directory and must include a SKILL.md // file at the root of that directory. - Files []io.Reader `json:"files,omitzero" format:"binary"` + Files []io.Reader `json:"files,omitzero" api:"required" format:"binary"` // Optional header to specify the beta version(s) you want to use. Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` paramObj @@ -357,7 +377,7 @@ type BetaSkillVersionListParams struct { // `url.Values`. func (r BetaSkillVersionListParams) URLQuery() (v url.Values, err error) { return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ - ArrayFormat: apiquery.ArrayQueryFormatComma, + ArrayFormat: apiquery.ArrayQueryFormatBrackets, NestedFormat: apiquery.NestedQueryFormatBrackets, }) } @@ -371,3 +391,13 @@ type BetaSkillVersionDeleteParams struct { Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` paramObj } + +type BetaSkillVersionDownloadParams struct { + // Unique identifier for the skill. + // + // The format and length of IDs may change over time. + SkillID string `path:"skill_id" api:"required" json:"-"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/betatoolrunner.go b/vendor/github.com/anthropics/anthropic-sdk-go/betatoolrunner.go index d4f547f3c..5e693fb6b 100644 --- a/vendor/github.com/anthropics/anthropic-sdk-go/betatoolrunner.go +++ b/vendor/github.com/anthropics/anthropic-sdk-go/betatoolrunner.go @@ -6,6 +6,7 @@ import ( "fmt" "iter" + "github.com/anthropics/anthropic-sdk-go/internal/stainlessheader" "github.com/anthropics/anthropic-sdk-go/option" "golang.org/x/sync/errgroup" ) @@ -63,6 +64,8 @@ func newBetaToolRunnerBase(messageService *BetaMessageService, tools []BetaTool, params.BetaMessageNewParams.Tools = apiTools params.Messages = append([]BetaMessageParam{}, params.Messages...) + opts = append([]option.RequestOption{stainlessheader.With(stainlessheader.BetaToolRunner)}, opts...) + return betaToolRunnerBase{ messageService: messageService, Params: params, @@ -111,17 +114,98 @@ func (b *betaToolRunnerBase) Err() error { return b.err } +// adoptContainer carries the container the last turn ran in onto the next +// request: container-bound server tools reject a follow-up that omits it, so +// its id is forwarded unless the caller pinned one themselves. +func (b *betaToolRunnerBase) adoptContainer(message *BetaMessage) { + id := message.Container.ID + if id == "" { + return + } + container := &b.Params.Container + switch { + case container.OfContainers != nil: + if !container.OfContainers.ID.Valid() { + pinned := *container.OfContainers + pinned.ID = String(id) + container.OfContainers = &pinned + } + case !container.OfString.Valid(): + container.OfString = String(id) + } +} + +// toolRunnerStep is what the runner does with a turn, decided by its stop reason. +type toolRunnerStep int + +const ( + // stepRunTools answers the turn's client tool calls and continues, or stops + // when there are none. + stepRunTools toolRunnerStep = iota + // stepResume sends the unfinished turn back unchanged, without executing + // any tool calls it carries, so the server continues it. + stepResume + // stepStop ends the conversation with the turn as the final message, + // without executing its tool calls. + stepStop +) + +// determineNextStepFromStopReason classifies every generated stop reason +// explicitly so a new one has to be placed in a bucket here; values unknown at +// runtime stop like end_turn rather than erroring. +func determineNextStepFromStopReason(reason BetaStopReason) toolRunnerStep { + switch reason { + case BetaStopReasonToolUse: + return stepRunTools + case BetaStopReasonPauseTurn: + // A long-running server tool paused the turn; sending it back unchanged + // resumes it. + return stepResume + case BetaStopReasonCompaction: + // pause_after_compaction hands the turn back before the model answers; + // sending it back unchanged continues it. + return stepResume + case BetaStopReasonRefusal: + // A refusal-terminated turn is terminal: its tool calls belong to a dead + // conversation — executing them fires side effects the caller never + // confirmed and produces tool_results that cannot be coherently replayed. + return stepStop + case BetaStopReasonMaxTokens, BetaStopReasonModelContextWindowExceeded: + // A cut-off turn left its last call's arguments incomplete. + return stepStop + case BetaStopReasonEndTurn, BetaStopReasonStopSequence: + return stepStop + default: + // An unrecognized stop reason stops like end_turn. + return stepStop + } +} + // executeTools processes any tool use blocks in the given message and returns a tool result message. // Returns: // - (result, nil) if tools executed successfully -// - (nil, nil) if no tools to execute +// - (nil, nil) if the turn did not stop for tool use or has no client tool calls // - (nil, ctx.Err()) if context was cancelled func (b *betaToolRunnerBase) executeTools(ctx context.Context, message *BetaMessage) (*BetaMessageParam, error) { + if determineNextStepFromStopReason(message.StopReason) != stepRunTools { + return nil, nil + } + + // Tool calls before the last fallback block belong to the attempt that + // refused; the fallback middleware strips them from replayed history, so + // answering them would orphan the tool_result. + seam := -1 + for i, block := range message.Content { + if block.Type == "fallback" { + seam = i + } + } + var toolUseBlocks []BetaToolUseBlock // Find all tool use blocks in the message - for _, block := range message.Content { - if block.Type == "tool_use" { + for i, block := range message.Content { + if i > seam && block.Type == "tool_use" { toolUseBlocks = append(toolUseBlocks, block.AsToolUse()) } } @@ -132,6 +216,7 @@ func (b *betaToolRunnerBase) executeTools(ctx context.Context, message *BetaMess // Execute all tools in parallel using errgroup for proper cancellation handling results := make([]BetaContentBlockParamUnion, len(toolUseBlocks)) + available := b.availableToolNames() g, gctx := errgroup.WithContext(ctx) for i, toolUse := range toolUseBlocks { @@ -142,7 +227,7 @@ func (b *betaToolRunnerBase) executeTools(ctx context.Context, message *BetaMess return gctx.Err() default: } - result := b.executeToolUse(gctx, toolUse) + result := b.executeToolUse(gctx, toolUse, available) results[i] = BetaContentBlockParamUnion{OfToolResult: &result} return nil // tool errors become result content, not Go errors }) @@ -161,10 +246,73 @@ func newBetaToolResultErrorBlockParam(toolUseID string, errorText string) BetaTo return NewBetaToolResultTextBlockParam(toolUseID, errorText, true) } +// availableToolNames returns the tool names currently offered to the model: +// every registered tool, minus names dropped by tool_removal blocks in +// role "system" messages, plus names re-enabled by later tool_addition +// blocks. Removal is only a hint — the model can still call a removed tool — +// so a removed tool must resolve to the same not-found result as one that +// was never registered. +func (b *betaToolRunnerBase) availableToolNames() map[string]struct{} { + available := make(map[string]struct{}, len(b.toolMap)) + for name := range b.toolMap { + available[name] = struct{}{} + } + for _, message := range b.Params.Messages { + if message.Role != BetaMessageParamRoleSystem { + continue + } + for _, block := range message.Content { + applyToolChange(block, available) + } + } + return available +} + +// applyToolChange folds one system-message content block into the available +// tool-name set. The populated Of* variant is the discriminator; every other +// block type, including ones added after this SDK was generated, leaves the +// set untouched. +func applyToolChange(block BetaContentBlockParamUnion, available map[string]struct{}) { + switch { + case block.OfToolRemoval != nil: + if name, ok := removalRefName(block.OfToolRemoval.Tool); ok { + delete(available, name) + } + case block.OfToolAddition != nil: + if name, ok := additionRefName(block.OfToolAddition.Tool); ok { + available[name] = struct{}{} + } + } +} + +// additionRefName and removalRefName resolve the referenced tool's name across +// the generated addition/removal tool unions. Only a tool_reference names a +// locally runnable tool; MCP references run server-side and unknown variants +// are ignored. +func additionRefName(u BetaRequestToolAdditionBlockToolUnionParam) (string, bool) { + switch { + case u.OfToolReference != nil: + return u.OfToolReference.Name, u.OfToolReference.Name != "" + default: + return "", false + } +} + +func removalRefName(u BetaRequestToolRemovalBlockToolUnionParam) (string, bool) { + switch { + case u.OfToolReference != nil: + return u.OfToolReference.Name, u.OfToolReference.Name != "" + default: + return "", false + } +} + // executeToolUse executes a single tool use block and returns the result. -func (b *betaToolRunnerBase) executeToolUse(ctx context.Context, toolUse BetaToolUseBlock) BetaToolResultBlockParam { +// available is the current set of offered tool names (see availableToolNames). +func (b *betaToolRunnerBase) executeToolUse(ctx context.Context, toolUse BetaToolUseBlock, available map[string]struct{}) BetaToolResultBlockParam { + _, allowed := available[toolUse.Name] tool, exists := b.toolMap[toolUse.Name] - if !exists { + if !exists || !allowed { return newBetaToolResultErrorBlockParam( toolUse.ID, fmt.Sprintf("Error: Tool '%s' not found", toolUse.Name), @@ -231,7 +379,7 @@ func (r *BetaToolRunner) NextMessage(ctx context.Context) (*BetaMessage, error) // Check iteration limit if r.Params.MaxIterations > 0 && r.iterationCount >= r.Params.MaxIterations { r.completed = true - return r.lastMessage, nil + return nil, nil } // Execute any pending tool calls from the last message @@ -241,12 +389,12 @@ func (r *BetaToolRunner) NextMessage(ctx context.Context) (*BetaMessage, error) r.err = err return nil, err } - if toolMessage == nil { - // No tools to execute, conversation is complete + if toolMessage != nil { + r.Params.Messages = append(r.Params.Messages, *toolMessage) + } else if determineNextStepFromStopReason(r.lastMessage.StopReason) != stepResume { r.completed = true - return r.lastMessage, nil + return nil, nil } - r.Params.Messages = append(r.Params.Messages, *toolMessage) } // Make API call @@ -262,6 +410,7 @@ func (r *BetaToolRunner) NextMessage(ctx context.Context) (*BetaMessage, error) r.lastMessage = message r.Params.Messages = append(r.Params.Messages, message.ToParam()) + r.adoptContainer(message) return message, nil } @@ -362,12 +511,12 @@ func (r *BetaToolRunnerStreaming) NextStreaming(ctx context.Context) iter.Seq2[B yield(BetaRawMessageStreamEventUnion{}, err) return } - if toolMessage == nil { - // No tools to execute, conversation is complete + if toolMessage != nil { + r.Params.Messages = append(r.Params.Messages, *toolMessage) + } else if determineNextStepFromStopReason(r.lastMessage.StopReason) != stepResume { r.completed = true return } - r.Params.Messages = append(r.Params.Messages, *toolMessage) } // Make streaming API call @@ -403,6 +552,7 @@ func (r *BetaToolRunnerStreaming) NextStreaming(ctx context.Context) iter.Seq2[B r.lastMessage = finalMessage r.Params.Messages = append(r.Params.Messages, finalMessage.ToParam()) + r.adoptContainer(finalMessage) } } diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/betatunnel.go b/vendor/github.com/anthropics/anthropic-sdk-go/betatunnel.go new file mode 100644 index 000000000..eb3363964 --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/betatunnel.go @@ -0,0 +1,320 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +package anthropic + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "slices" + "time" + + "github.com/anthropics/anthropic-sdk-go/internal/apijson" + "github.com/anthropics/anthropic-sdk-go/internal/apiquery" + "github.com/anthropics/anthropic-sdk-go/internal/requestconfig" + "github.com/anthropics/anthropic-sdk-go/option" + "github.com/anthropics/anthropic-sdk-go/packages/pagination" + "github.com/anthropics/anthropic-sdk-go/packages/param" + "github.com/anthropics/anthropic-sdk-go/packages/respjson" + "github.com/anthropics/anthropic-sdk-go/shared/constant" +) + +// BetaTunnelService contains methods and other services that help with interacting +// with the anthropic API. +// +// Note, unlike clients, this service does not read variables from the environment +// automatically. You should not instantiate this service directly, and instead use +// the [NewBetaTunnelService] method instead. +type BetaTunnelService struct { + Options []option.RequestOption + Certificates BetaTunnelCertificateService +} + +// NewBetaTunnelService generates a new service that applies the given options to +// each request. These options are applied after the parent client's options (if +// there is one), and before any request-specific options. +func NewBetaTunnelService(opts ...option.RequestOption) (r BetaTunnelService) { + r = BetaTunnelService{} + r.Options = opts + r.Certificates = NewBetaTunnelCertificateService(opts...) + return +} + +// The Tunnels API is in research preview. It requires the +// `anthropic-beta: mcp-tunnels-2026-06-22` header and may change without a +// deprecation period. It supersedes the Admin API endpoints at +// `/v1/organizations/tunnels`, which remain available during a migration window. +// +// Creates a tunnel. Creation allocates a fresh hostname and provisions the tunnel; +// it is not idempotent. The new tunnel rejects MCP traffic until at least one CA +// certificate is added. +func (r *BetaTunnelService) New(ctx context.Context, params BetaTunnelNewParams, opts ...option.RequestOption) (res *BetaTunnel, err error) { + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "mcp-tunnels-2026-06-22")}, opts...) + path := "v1/tunnels?beta=true" + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, params, &res, opts...) + return res, err +} + +// The Tunnels API is in research preview. It requires the +// `anthropic-beta: mcp-tunnels-2026-06-22` header and may change without a +// deprecation period. It supersedes the Admin API endpoints at +// `/v1/organizations/tunnels`, which remain available during a migration window. +// +// Fetches a tunnel by ID. +func (r *BetaTunnelService) Get(ctx context.Context, tunnelID string, query BetaTunnelGetParams, opts ...option.RequestOption) (res *BetaTunnel, err error) { + for _, v := range query.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "mcp-tunnels-2026-06-22")}, opts...) + if tunnelID == "" { + err = errors.New("missing required tunnel_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/tunnels/%s?beta=true", tunnelID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...) + return res, err +} + +// The Tunnels API is in research preview. It requires the +// `anthropic-beta: mcp-tunnels-2026-06-22` header and may change without a +// deprecation period. It supersedes the Admin API endpoints at +// `/v1/organizations/tunnels`, which remain available during a migration window. +// +// Lists tunnels. Results are ordered by creation time, newest first; archived +// tunnels are excluded unless include_archived is set. +func (r *BetaTunnelService) List(ctx context.Context, params BetaTunnelListParams, opts ...option.RequestOption) (res *pagination.PageCursor[BetaTunnel], err error) { + var raw *http.Response + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "mcp-tunnels-2026-06-22"), option.WithResponseInto(&raw)}, opts...) + path := "v1/tunnels?beta=true" + cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, params, &res, opts...) + if err != nil { + return nil, err + } + err = cfg.Execute() + if err != nil { + return nil, err + } + res.SetPageConfig(cfg, raw) + return res, nil +} + +// The Tunnels API is in research preview. It requires the +// `anthropic-beta: mcp-tunnels-2026-06-22` header and may change without a +// deprecation period. It supersedes the Admin API endpoints at +// `/v1/organizations/tunnels`, which remain available during a migration window. +// +// Lists tunnels. Results are ordered by creation time, newest first; archived +// tunnels are excluded unless include_archived is set. +func (r *BetaTunnelService) ListAutoPaging(ctx context.Context, params BetaTunnelListParams, opts ...option.RequestOption) *pagination.PageCursorAutoPager[BetaTunnel] { + return pagination.NewPageCursorAutoPager(r.List(ctx, params, opts...)) +} + +// The Tunnels API is in research preview. It requires the +// `anthropic-beta: mcp-tunnels-2026-06-22` header and may change without a +// deprecation period. It supersedes the Admin API endpoints at +// `/v1/organizations/tunnels`, which remain available during a migration window. +// +// Archives a tunnel. Archival is irreversible: every non-archived certificate on +// the tunnel is archived in the same operation, the hostname is retired and never +// re-allocated, and the tunnel token is invalidated. Retrying against an +// already-archived tunnel returns the existing record unchanged. +func (r *BetaTunnelService) Archive(ctx context.Context, tunnelID string, body BetaTunnelArchiveParams, opts ...option.RequestOption) (res *BetaTunnel, err error) { + for _, v := range body.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "mcp-tunnels-2026-06-22")}, opts...) + if tunnelID == "" { + err = errors.New("missing required tunnel_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/tunnels/%s/archive?beta=true", tunnelID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, nil, &res, opts...) + return res, err +} + +// The Tunnels API is in research preview. It requires the +// `anthropic-beta: mcp-tunnels-2026-06-22` header and may change without a +// deprecation period. It supersedes the Admin API endpoints at +// `/v1/organizations/tunnels`, which remain available during a migration window. +// +// Reveals a tunnel's connector token. The value is fetched live on each call; +// Anthropic does not store it. Repeated calls return the same value until the +// token is rotated. Exposed as POST so the token does not appear in intermediary +// access logs. +func (r *BetaTunnelService) RevealToken(ctx context.Context, tunnelID string, body BetaTunnelRevealTokenParams, opts ...option.RequestOption) (res *BetaTunnelToken, err error) { + for _, v := range body.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "mcp-tunnels-2026-06-22")}, opts...) + if tunnelID == "" { + err = errors.New("missing required tunnel_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/tunnels/%s/reveal_token?beta=true", tunnelID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, nil, &res, opts...) + return res, err +} + +// The Tunnels API is in research preview. It requires the +// `anthropic-beta: mcp-tunnels-2026-06-22` header and may change without a +// deprecation period. It supersedes the Admin API endpoints at +// `/v1/organizations/tunnels`, which remain available during a migration window. +// +// Rotates a tunnel's connector token. Rotation invalidates the current token for +// new connections and returns a fresh value; established connections are not +// severed. A connector restarted after rotation must use the new value. +func (r *BetaTunnelService) RotateToken(ctx context.Context, tunnelID string, params BetaTunnelRotateTokenParams, opts ...option.RequestOption) (res *BetaTunnelToken, err error) { + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "mcp-tunnels-2026-06-22")}, opts...) + if tunnelID == "" { + err = errors.New("missing required tunnel_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/tunnels/%s/rotate_token?beta=true", tunnelID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, params, &res, opts...) + return res, err +} + +// An MCP tunnel. +type BetaTunnel struct { + // Unique identifier for the tunnel, prefixed with `tnl_`. + ID string `json:"id" api:"required"` + // A timestamp in RFC 3339 format + ArchivedAt time.Time `json:"archived_at" api:"required" format:"date-time"` + // A timestamp in RFC 3339 format + CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"` + // Human-readable name for the tunnel (1-255 characters). Null if unset. + DisplayName string `json:"display_name" api:"required"` + // Anthropic-assigned hostname for the tunnel. MCP server URLs whose host is a + // subdomain of this value are routed through the tunnel. Globally unique and never + // reused, even after the tunnel is archived. + Domain string `json:"domain" api:"required"` + Type constant.Tunnel `json:"type" default:"tunnel"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + ArchivedAt respjson.Field + CreatedAt respjson.Field + DisplayName respjson.Field + Domain respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaTunnel) RawJSON() string { return r.JSON.raw } +func (r *BetaTunnel) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// A tunnel's connector token. +type BetaTunnelToken struct { + // Stable identifier for the current token value. Changes when the token is + // rotated. + ID string `json:"id" api:"required"` + // The connector token used to run the tunnel. Treat as a credential. + TunnelToken string `json:"tunnel_token" api:"required"` + Type constant.TunnelToken `json:"type" default:"tunnel_token"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + TunnelToken respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaTunnelToken) RawJSON() string { return r.JSON.raw } +func (r *BetaTunnelToken) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaTunnelNewParams struct { + // Optional human-readable name for the tunnel (1-255 characters). + DisplayName param.Opt[string] `json:"display_name,omitzero"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +func (r BetaTunnelNewParams) MarshalJSON() (data []byte, err error) { + type shadow BetaTunnelNewParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaTunnelNewParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaTunnelGetParams struct { + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +type BetaTunnelListParams struct { + // Whether to include archived tunnels in the results. Defaults to false. + IncludeArchived param.Opt[bool] `query:"include_archived,omitzero" json:"-"` + // Maximum number of tunnels to return per page. Defaults to 20, maximum 1000. + Limit param.Opt[int64] `query:"limit,omitzero" json:"-"` + // Opaque pagination cursor from a previous `list_tunnels` response. + Page param.Opt[string] `query:"page,omitzero" json:"-"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +// URLQuery serializes [BetaTunnelListParams]'s query parameters as `url.Values`. +func (r BetaTunnelListParams) URLQuery() (v url.Values, err error) { + return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ + ArrayFormat: apiquery.ArrayQueryFormatBrackets, + NestedFormat: apiquery.NestedQueryFormatBrackets, + }) +} + +type BetaTunnelArchiveParams struct { + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +type BetaTunnelRevealTokenParams struct { + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +type BetaTunnelRotateTokenParams struct { + // Optional free-text reason for the rotation, recorded for audit. + Reason param.Opt[string] `json:"reason,omitzero"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +func (r BetaTunnelRotateTokenParams) MarshalJSON() (data []byte, err error) { + type shadow BetaTunnelRotateTokenParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaTunnelRotateTokenParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/betatunnelcertificate.go b/vendor/github.com/anthropics/anthropic-sdk-go/betatunnelcertificate.go new file mode 100644 index 000000000..e0c24fdc3 --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/betatunnelcertificate.go @@ -0,0 +1,246 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +package anthropic + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "slices" + "time" + + "github.com/anthropics/anthropic-sdk-go/internal/apijson" + "github.com/anthropics/anthropic-sdk-go/internal/apiquery" + "github.com/anthropics/anthropic-sdk-go/internal/requestconfig" + "github.com/anthropics/anthropic-sdk-go/option" + "github.com/anthropics/anthropic-sdk-go/packages/pagination" + "github.com/anthropics/anthropic-sdk-go/packages/param" + "github.com/anthropics/anthropic-sdk-go/packages/respjson" + "github.com/anthropics/anthropic-sdk-go/shared/constant" +) + +// BetaTunnelCertificateService contains methods and other services that help with +// interacting with the anthropic API. +// +// Note, unlike clients, this service does not read variables from the environment +// automatically. You should not instantiate this service directly, and instead use +// the [NewBetaTunnelCertificateService] method instead. +type BetaTunnelCertificateService struct { + Options []option.RequestOption +} + +// NewBetaTunnelCertificateService generates a new service that applies the given +// options to each request. These options are applied after the parent client's +// options (if there is one), and before any request-specific options. +func NewBetaTunnelCertificateService(opts ...option.RequestOption) (r BetaTunnelCertificateService) { + r = BetaTunnelCertificateService{} + r.Options = opts + return +} + +// The Tunnels API is in research preview. It requires the +// `anthropic-beta: mcp-tunnels-2026-06-22` header and may change without a +// deprecation period. It supersedes the Admin API endpoints at +// `/v1/organizations/tunnels`, which remain available during a migration window. +// +// Registers a public CA certificate on a tunnel. Anthropic verifies the gateway's +// server certificate against this CA when it terminates the inner TLS session. A +// tunnel holds at most two non-archived certificates. +func (r *BetaTunnelCertificateService) New(ctx context.Context, tunnelID string, params BetaTunnelCertificateNewParams, opts ...option.RequestOption) (res *BetaTunnelCertificate, err error) { + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "mcp-tunnels-2026-06-22")}, opts...) + if tunnelID == "" { + err = errors.New("missing required tunnel_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/tunnels/%s/certificates?beta=true", tunnelID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, params, &res, opts...) + return res, err +} + +// The Tunnels API is in research preview. It requires the +// `anthropic-beta: mcp-tunnels-2026-06-22` header and may change without a +// deprecation period. It supersedes the Admin API endpoints at +// `/v1/organizations/tunnels`, which remain available during a migration window. +// +// Fetches a tunnel certificate by ID. +func (r *BetaTunnelCertificateService) Get(ctx context.Context, certificateID string, params BetaTunnelCertificateGetParams, opts ...option.RequestOption) (res *BetaTunnelCertificate, err error) { + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "mcp-tunnels-2026-06-22")}, opts...) + if params.TunnelID == "" { + err = errors.New("missing required tunnel_id parameter") + return nil, err + } + if certificateID == "" { + err = errors.New("missing required certificate_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/tunnels/%s/certificates/%s?beta=true", params.TunnelID, certificateID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...) + return res, err +} + +// The Tunnels API is in research preview. It requires the +// `anthropic-beta: mcp-tunnels-2026-06-22` header and may change without a +// deprecation period. It supersedes the Admin API endpoints at +// `/v1/organizations/tunnels`, which remain available during a migration window. +// +// Lists the certificates registered on a tunnel. Archived certificates are +// excluded unless include_archived is set. +func (r *BetaTunnelCertificateService) List(ctx context.Context, tunnelID string, params BetaTunnelCertificateListParams, opts ...option.RequestOption) (res *pagination.PageCursor[BetaTunnelCertificate], err error) { + var raw *http.Response + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "mcp-tunnels-2026-06-22"), option.WithResponseInto(&raw)}, opts...) + if tunnelID == "" { + err = errors.New("missing required tunnel_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/tunnels/%s/certificates?beta=true", tunnelID) + cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, params, &res, opts...) + if err != nil { + return nil, err + } + err = cfg.Execute() + if err != nil { + return nil, err + } + res.SetPageConfig(cfg, raw) + return res, nil +} + +// The Tunnels API is in research preview. It requires the +// `anthropic-beta: mcp-tunnels-2026-06-22` header and may change without a +// deprecation period. It supersedes the Admin API endpoints at +// `/v1/organizations/tunnels`, which remain available during a migration window. +// +// Lists the certificates registered on a tunnel. Archived certificates are +// excluded unless include_archived is set. +func (r *BetaTunnelCertificateService) ListAutoPaging(ctx context.Context, tunnelID string, params BetaTunnelCertificateListParams, opts ...option.RequestOption) *pagination.PageCursorAutoPager[BetaTunnelCertificate] { + return pagination.NewPageCursorAutoPager(r.List(ctx, tunnelID, params, opts...)) +} + +// The Tunnels API is in research preview. It requires the +// `anthropic-beta: mcp-tunnels-2026-06-22` header and may change without a +// deprecation period. It supersedes the Admin API endpoints at +// `/v1/organizations/tunnels`, which remain available during a migration window. +// +// Archives a tunnel certificate, removing it from the set Anthropic trusts for the +// tunnel. The certificate record is retained. Archiving the last non-archived +// certificate is permitted; the tunnel rejects MCP traffic until a new certificate +// is added. +func (r *BetaTunnelCertificateService) Archive(ctx context.Context, certificateID string, params BetaTunnelCertificateArchiveParams, opts ...option.RequestOption) (res *BetaTunnelCertificate, err error) { + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "mcp-tunnels-2026-06-22")}, opts...) + if params.TunnelID == "" { + err = errors.New("missing required tunnel_id parameter") + return nil, err + } + if certificateID == "" { + err = errors.New("missing required certificate_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/tunnels/%s/certificates/%s/archive?beta=true", params.TunnelID, certificateID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, nil, &res, opts...) + return res, err +} + +// A CA certificate attached to a tunnel. +type BetaTunnelCertificate struct { + // Unique identifier for the certificate, prefixed with `tcrt_`. + ID string `json:"id" api:"required"` + // A timestamp in RFC 3339 format + ArchivedAt time.Time `json:"archived_at" api:"required" format:"date-time"` + // A timestamp in RFC 3339 format + CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"` + // A timestamp in RFC 3339 format + ExpiresAt time.Time `json:"expires_at" api:"required" format:"date-time"` + // Lowercase hex SHA-256 fingerprint of the certificate's DER encoding. + Fingerprint string `json:"fingerprint" api:"required"` + // ID of the tunnel the certificate is registered against. + TunnelID string `json:"tunnel_id" api:"required"` + Type constant.TunnelCertificate `json:"type" default:"tunnel_certificate"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + ArchivedAt respjson.Field + CreatedAt respjson.Field + ExpiresAt respjson.Field + Fingerprint respjson.Field + TunnelID respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaTunnelCertificate) RawJSON() string { return r.JSON.raw } +func (r *BetaTunnelCertificate) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaTunnelCertificateNewParams struct { + // PEM-encoded X.509 CA certificate. Must contain exactly one certificate and no + // private-key material. Maximum 8KB. + CACertificatePEM string `json:"ca_certificate_pem" api:"required"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +func (r BetaTunnelCertificateNewParams) MarshalJSON() (data []byte, err error) { + type shadow BetaTunnelCertificateNewParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaTunnelCertificateNewParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaTunnelCertificateGetParams struct { + TunnelID string `path:"tunnel_id" api:"required" json:"-"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +type BetaTunnelCertificateListParams struct { + // Whether to include archived certificates in the results. Defaults to false. + IncludeArchived param.Opt[bool] `query:"include_archived,omitzero" json:"-"` + // Maximum number of certificates to return per page. Defaults to 20, maximum 1000. + Limit param.Opt[int64] `query:"limit,omitzero" json:"-"` + // Opaque pagination cursor from a previous `list_tunnel_certificates` response. + Page param.Opt[string] `query:"page,omitzero" json:"-"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} + +// URLQuery serializes [BetaTunnelCertificateListParams]'s query parameters as +// `url.Values`. +func (r BetaTunnelCertificateListParams) URLQuery() (v url.Values, err error) { + return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ + ArrayFormat: apiquery.ArrayQueryFormatBrackets, + NestedFormat: apiquery.NestedQueryFormatBrackets, + }) +} + +type BetaTunnelCertificateArchiveParams struct { + TunnelID string `path:"tunnel_id" api:"required" json:"-"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/betauserprofile.go b/vendor/github.com/anthropics/anthropic-sdk-go/betauserprofile.go index e7412b798..98397a9a6 100644 --- a/vendor/github.com/anthropics/anthropic-sdk-go/betauserprofile.go +++ b/vendor/github.com/anthropics/anthropic-sdk-go/betauserprofile.go @@ -45,7 +45,7 @@ func (r *BetaUserProfileService) New(ctx context.Context, params BetaUserProfile opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) } opts = slices.Concat(r.Options, opts) - opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "user-profiles-2026-03-24")}, opts...) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "user-profiles-2026-08-18")}, opts...) path := "v1/user_profiles?beta=true" err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, params, &res, opts...) return res, err @@ -57,7 +57,7 @@ func (r *BetaUserProfileService) Get(ctx context.Context, userProfileID string, opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) } opts = slices.Concat(r.Options, opts) - opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "user-profiles-2026-03-24")}, opts...) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "user-profiles-2026-08-18")}, opts...) if userProfileID == "" { err = errors.New("missing required user_profile_id parameter") return nil, err @@ -73,7 +73,7 @@ func (r *BetaUserProfileService) Update(ctx context.Context, userProfileID strin opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) } opts = slices.Concat(r.Options, opts) - opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "user-profiles-2026-03-24")}, opts...) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "user-profiles-2026-08-18")}, opts...) if userProfileID == "" { err = errors.New("missing required user_profile_id parameter") return nil, err @@ -90,7 +90,7 @@ func (r *BetaUserProfileService) List(ctx context.Context, params BetaUserProfil opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) } opts = slices.Concat(r.Options, opts) - opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "user-profiles-2026-03-24"), option.WithResponseInto(&raw)}, opts...) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "user-profiles-2026-08-18"), option.WithResponseInto(&raw)}, opts...) path := "v1/user_profiles?beta=true" cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, params, &res, opts...) if err != nil { @@ -115,7 +115,7 @@ func (r *BetaUserProfileService) NewEnrollmentURL(ctx context.Context, userProfi opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) } opts = slices.Concat(r.Options, opts) - opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "user-profiles-2026-03-24")}, opts...) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "user-profiles-2026-08-18")}, opts...) if userProfileID == "" { err = errors.New("missing required user_profile_id parameter") return nil, err @@ -142,19 +142,40 @@ type BetaUserProfile struct { Type BetaUserProfileType `json:"type" api:"required"` // A timestamp in RFC 3339 format UpdatedAt time.Time `json:"updated_at" api:"required" format:"date-time"` + // How the platform uses the API on behalf of the entity this profile represents. + // `application`: the platform sells a product that uses the API behind the scenes, + // and the profile represents an individual end-user of that product. + // `passthrough`: the platform resells raw inference, and the profile identifies + // the resold-to company. + // + // Any of "application", "passthrough". + AccessType BetaUserProfileAccessType `json:"access_type"` // Platform's own identifier for this user. Not enforced unique. ExternalID string `json:"external_id" api:"nullable"` + // Real-world name of the entity this profile represents (company or individual). + // For a resold-to company (`access_type` `passthrough`, or `relationship` `resold` + // under the `user-profiles-2026-03-24` header) this is that company's name. + Name string `json:"name" api:"nullable"` + // How the entity behind a user profile relates to the platform that owns the API + // key. `external`: an individual end-user of the platform. `resold`: a company the + // platform resells Claude access to. `internal`: the platform's own usage. + // + // Any of "external", "resold", "internal". + Relationship BetaUserProfileRelationship `json:"relationship"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { - ID respjson.Field - CreatedAt respjson.Field - Metadata respjson.Field - TrustGrants respjson.Field - Type respjson.Field - UpdatedAt respjson.Field - ExternalID respjson.Field - ExtraFields map[string]respjson.Field - raw string + ID respjson.Field + CreatedAt respjson.Field + Metadata respjson.Field + TrustGrants respjson.Field + Type respjson.Field + UpdatedAt respjson.Field + AccessType respjson.Field + ExternalID respjson.Field + Name respjson.Field + Relationship respjson.Field + ExtraFields map[string]respjson.Field + raw string } `json:"-"` } @@ -171,6 +192,29 @@ const ( BetaUserProfileTypeUserProfile BetaUserProfileType = "user_profile" ) +// How the platform uses the API on behalf of the entity this profile represents. +// `application`: the platform sells a product that uses the API behind the scenes, +// and the profile represents an individual end-user of that product. +// `passthrough`: the platform resells raw inference, and the profile identifies +// the resold-to company. +type BetaUserProfileAccessType string + +const ( + BetaUserProfileAccessTypeApplication BetaUserProfileAccessType = "application" + BetaUserProfileAccessTypePassthrough BetaUserProfileAccessType = "passthrough" +) + +// How the entity behind a user profile relates to the platform that owns the API +// key. `external`: an individual end-user of the platform. `resold`: a company the +// platform resells Claude access to. `internal`: the platform's own usage. +type BetaUserProfileRelationship string + +const ( + BetaUserProfileRelationshipExternal BetaUserProfileRelationship = "external" + BetaUserProfileRelationshipResold BetaUserProfileRelationship = "resold" + BetaUserProfileRelationshipInternal BetaUserProfileRelationship = "internal" +) + type BetaUserProfileEnrollmentURL struct { // A timestamp in RFC 3339 format ExpiresAt time.Time `json:"expires_at" api:"required" format:"date-time"` @@ -235,10 +279,29 @@ type BetaUserProfileNewParams struct { // Platform's own identifier for this user. Not enforced unique. Maximum 255 // characters. ExternalID param.Opt[string] `json:"external_id,omitzero"` + // Optional for all profiles. Real-world name of the entity this profile represents + // (company or individual); for a resold-to company (`relationship` `resold` / + // `access_type` `passthrough`), that company's name where known. Maximum 255 + // characters. + Name param.Opt[string] `json:"name,omitzero"` + // How the platform uses the API on behalf of the entity this profile represents. + // `application`: the platform sells a product that uses the API behind the scenes, + // and the profile represents an individual end-user of that product. + // `passthrough`: the platform resells raw inference, and the profile identifies + // the resold-to company. + // + // Any of "application", "passthrough". + AccessType BetaUserProfileNewParamsAccessType `json:"access_type,omitzero"` // Free-form key-value data to attach to this user profile. Maximum 16 keys, with // keys up to 64 characters and values up to 512 characters. Values must be // non-empty strings. Metadata map[string]string `json:"metadata,omitzero"` + // How the entity behind a user profile relates to the platform that owns the API + // key. `external`: an individual end-user of the platform. `resold`: a company the + // platform resells Claude access to. `internal`: the platform's own usage. + // + // Any of "external", "resold", "internal". + Relationship BetaUserProfileNewParamsRelationship `json:"relationship,omitzero"` // Optional header to specify the beta version(s) you want to use. Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` paramObj @@ -252,6 +315,29 @@ func (r *BetaUserProfileNewParams) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } +// How the platform uses the API on behalf of the entity this profile represents. +// `application`: the platform sells a product that uses the API behind the scenes, +// and the profile represents an individual end-user of that product. +// `passthrough`: the platform resells raw inference, and the profile identifies +// the resold-to company. +type BetaUserProfileNewParamsAccessType string + +const ( + BetaUserProfileNewParamsAccessTypeApplication BetaUserProfileNewParamsAccessType = "application" + BetaUserProfileNewParamsAccessTypePassthrough BetaUserProfileNewParamsAccessType = "passthrough" +) + +// How the entity behind a user profile relates to the platform that owns the API +// key. `external`: an individual end-user of the platform. `resold`: a company the +// platform resells Claude access to. `internal`: the platform's own usage. +type BetaUserProfileNewParamsRelationship string + +const ( + BetaUserProfileNewParamsRelationshipExternal BetaUserProfileNewParamsRelationship = "external" + BetaUserProfileNewParamsRelationshipResold BetaUserProfileNewParamsRelationship = "resold" + BetaUserProfileNewParamsRelationshipInternal BetaUserProfileNewParamsRelationship = "internal" +) + type BetaUserProfileGetParams struct { // Optional header to specify the beta version(s) you want to use. Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` @@ -262,6 +348,23 @@ type BetaUserProfileUpdateParams struct { // If present, replaces the stored external_id. Omit to leave unchanged. Maximum // 255 characters. ExternalID param.Opt[string] `json:"external_id,omitzero"` + // If present, replaces the stored name. Omit to leave unchanged. Maximum 255 + // characters. + Name param.Opt[string] `json:"name,omitzero"` + // How the platform uses the API on behalf of the entity this profile represents. + // `application`: the platform sells a product that uses the API behind the scenes, + // and the profile represents an individual end-user of that product. + // `passthrough`: the platform resells raw inference, and the profile identifies + // the resold-to company. + // + // Any of "application", "passthrough". + AccessType BetaUserProfileUpdateParamsAccessType `json:"access_type,omitzero"` + // How the entity behind a user profile relates to the platform that owns the API + // key. `external`: an individual end-user of the platform. `resold`: a company the + // platform resells Claude access to. `internal`: the platform's own usage. + // + // Any of "external", "resold", "internal". + Relationship BetaUserProfileUpdateParamsRelationship `json:"relationship,omitzero"` // Key-value pairs to merge into the stored metadata. Keys provided overwrite // existing values. To remove a key, set its value to an empty string. Keys not // provided are left unchanged. Maximum 16 keys, with keys up to 64 characters and @@ -280,6 +383,29 @@ func (r *BetaUserProfileUpdateParams) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } +// How the platform uses the API on behalf of the entity this profile represents. +// `application`: the platform sells a product that uses the API behind the scenes, +// and the profile represents an individual end-user of that product. +// `passthrough`: the platform resells raw inference, and the profile identifies +// the resold-to company. +type BetaUserProfileUpdateParamsAccessType string + +const ( + BetaUserProfileUpdateParamsAccessTypeApplication BetaUserProfileUpdateParamsAccessType = "application" + BetaUserProfileUpdateParamsAccessTypePassthrough BetaUserProfileUpdateParamsAccessType = "passthrough" +) + +// How the entity behind a user profile relates to the platform that owns the API +// key. `external`: an individual end-user of the platform. `resold`: a company the +// platform resells Claude access to. `internal`: the platform's own usage. +type BetaUserProfileUpdateParamsRelationship string + +const ( + BetaUserProfileUpdateParamsRelationshipExternal BetaUserProfileUpdateParamsRelationship = "external" + BetaUserProfileUpdateParamsRelationshipResold BetaUserProfileUpdateParamsRelationship = "resold" + BetaUserProfileUpdateParamsRelationshipInternal BetaUserProfileUpdateParamsRelationship = "internal" +) + type BetaUserProfileListParams struct { // Query parameter for limit Limit param.Opt[int64] `query:"limit,omitzero" json:"-"` @@ -298,7 +424,7 @@ type BetaUserProfileListParams struct { // `url.Values`. func (r BetaUserProfileListParams) URLQuery() (v url.Values, err error) { return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ - ArrayFormat: apiquery.ArrayQueryFormatComma, + ArrayFormat: apiquery.ArrayQueryFormatBrackets, NestedFormat: apiquery.NestedQueryFormatBrackets, }) } diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/betavault.go b/vendor/github.com/anthropics/anthropic-sdk-go/betavault.go index f6f02d2e3..dfa484aac 100644 --- a/vendor/github.com/anthropics/anthropic-sdk-go/betavault.go +++ b/vendor/github.com/anthropics/anthropic-sdk-go/betavault.go @@ -271,7 +271,7 @@ type BetaVaultListParams struct { // URLQuery serializes [BetaVaultListParams]'s query parameters as `url.Values`. func (r BetaVaultListParams) URLQuery() (v url.Values, err error) { return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ - ArrayFormat: apiquery.ArrayQueryFormatComma, + ArrayFormat: apiquery.ArrayQueryFormatBrackets, NestedFormat: apiquery.NestedQueryFormatBrackets, }) } diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/betavaultcredential.go b/vendor/github.com/anthropics/anthropic-sdk-go/betavaultcredential.go index 85685fa17..b2415aa53 100644 --- a/vendor/github.com/anthropics/anthropic-sdk-go/betavaultcredential.go +++ b/vendor/github.com/anthropics/anthropic-sdk-go/betavaultcredential.go @@ -166,6 +166,26 @@ func (r *BetaVaultCredentialService) Archive(ctx context.Context, credentialID s return res, err } +// Validate Credential +func (r *BetaVaultCredentialService) MCPOAuthValidate(ctx context.Context, credentialID string, params BetaVaultCredentialMCPOAuthValidateParams, opts ...option.RequestOption) (res *BetaManagedAgentsCredentialValidation, err error) { + for _, v := range params.Betas { + opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) + } + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("anthropic-beta", "managed-agents-2026-04-01")}, opts...) + if params.VaultID == "" { + err = errors.New("missing required vault_id parameter") + return nil, err + } + if credentialID == "" { + err = errors.New("missing required credential_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/vaults/%s/credentials/%s/mcp_oauth_validate?beta=true", params.VaultID, credentialID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, nil, &res, opts...) + return res, err +} + // A credential stored in a vault. Sensitive fields are never returned in // responses. type BetaManagedAgentsCredential struct { @@ -211,7 +231,8 @@ func (r *BetaManagedAgentsCredential) UnmarshalJSON(data []byte) error { // BetaManagedAgentsCredentialAuthUnion contains all possible properties and values // from [BetaManagedAgentsMCPOAuthAuthResponse], -// [BetaManagedAgentsStaticBearerAuthResponse]. +// [BetaManagedAgentsStaticBearerAuthResponse], +// [BetaManagedAgentsEnvironmentVariableAuthResponse]. // // Use the [BetaManagedAgentsCredentialAuthUnion.AsAny] method to switch on the // variant. @@ -219,18 +240,27 @@ func (r *BetaManagedAgentsCredential) UnmarshalJSON(data []byte) error { // Use the methods beginning with 'As' to cast the union to one of its variants. type BetaManagedAgentsCredentialAuthUnion struct { MCPServerURL string `json:"mcp_server_url"` - // Any of "mcp_oauth", "static_bearer". + // Any of "mcp_oauth", "static_bearer", "environment_variable". Type string `json:"type"` // This field is from variant [BetaManagedAgentsMCPOAuthAuthResponse]. ExpiresAt time.Time `json:"expires_at"` // This field is from variant [BetaManagedAgentsMCPOAuthAuthResponse]. Refresh BetaManagedAgentsMCPOAuthRefreshResponse `json:"refresh"` - JSON struct { - MCPServerURL respjson.Field - Type respjson.Field - ExpiresAt respjson.Field - Refresh respjson.Field - raw string + // This field is from variant [BetaManagedAgentsEnvironmentVariableAuthResponse]. + InjectionLocation BetaManagedAgentsInjectionLocationResponse `json:"injection_location"` + // This field is from variant [BetaManagedAgentsEnvironmentVariableAuthResponse]. + Networking BetaManagedAgentsEnvironmentVariableAuthResponseNetworkingUnion `json:"networking"` + // This field is from variant [BetaManagedAgentsEnvironmentVariableAuthResponse]. + SecretName string `json:"secret_name"` + JSON struct { + MCPServerURL respjson.Field + Type respjson.Field + ExpiresAt respjson.Field + Refresh respjson.Field + InjectionLocation respjson.Field + Networking respjson.Field + SecretName respjson.Field + raw string } `json:"-"` } @@ -241,14 +271,16 @@ type anyBetaManagedAgentsCredentialAuth interface { implBetaManagedAgentsCredentialAuthUnion() } -func (BetaManagedAgentsMCPOAuthAuthResponse) implBetaManagedAgentsCredentialAuthUnion() {} -func (BetaManagedAgentsStaticBearerAuthResponse) implBetaManagedAgentsCredentialAuthUnion() {} +func (BetaManagedAgentsMCPOAuthAuthResponse) implBetaManagedAgentsCredentialAuthUnion() {} +func (BetaManagedAgentsStaticBearerAuthResponse) implBetaManagedAgentsCredentialAuthUnion() {} +func (BetaManagedAgentsEnvironmentVariableAuthResponse) implBetaManagedAgentsCredentialAuthUnion() {} // Use the following switch statement to find the correct variant // // switch variant := BetaManagedAgentsCredentialAuthUnion.AsAny().(type) { // case anthropic.BetaManagedAgentsMCPOAuthAuthResponse: // case anthropic.BetaManagedAgentsStaticBearerAuthResponse: +// case anthropic.BetaManagedAgentsEnvironmentVariableAuthResponse: // default: // fmt.Errorf("no variant present") // } @@ -258,6 +290,8 @@ func (u BetaManagedAgentsCredentialAuthUnion) AsAny() anyBetaManagedAgentsCreden return u.AsMCPOAuth() case "static_bearer": return u.AsStaticBearer() + case "environment_variable": + return u.AsEnvironmentVariable() } return nil } @@ -272,6 +306,11 @@ func (u BetaManagedAgentsCredentialAuthUnion) AsStaticBearer() (v BetaManagedAge return } +func (u BetaManagedAgentsCredentialAuthUnion) AsEnvironmentVariable() (v BetaManagedAgentsEnvironmentVariableAuthResponse) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + // Returns the unmodified JSON received from the API func (u BetaManagedAgentsCredentialAuthUnion) RawJSON() string { return u.JSON.raw } @@ -285,6 +324,125 @@ const ( BetaManagedAgentsCredentialTypeVaultCredential BetaManagedAgentsCredentialType = "vault_credential" ) +func BetaManagedAgentsCredentialNetworkingParamsOfUnrestricted(type_ BetaManagedAgentsUnrestrictedCredentialNetworkingParamsType) BetaManagedAgentsCredentialNetworkingParamsUnion { + var unrestricted BetaManagedAgentsUnrestrictedCredentialNetworkingParams + unrestricted.Type = type_ + return BetaManagedAgentsCredentialNetworkingParamsUnion{OfUnrestricted: &unrestricted} +} + +func BetaManagedAgentsCredentialNetworkingParamsOfLimited(allowedHosts []string) BetaManagedAgentsCredentialNetworkingParamsUnion { + var limited BetaManagedAgentsLimitedCredentialNetworkingParams + limited.AllowedHosts = allowedHosts + return BetaManagedAgentsCredentialNetworkingParamsUnion{OfLimited: &limited} +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type BetaManagedAgentsCredentialNetworkingParamsUnion struct { + OfUnrestricted *BetaManagedAgentsUnrestrictedCredentialNetworkingParams `json:",omitzero,inline"` + OfLimited *BetaManagedAgentsLimitedCredentialNetworkingParams `json:",omitzero,inline"` + paramUnion +} + +func (u BetaManagedAgentsCredentialNetworkingParamsUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfUnrestricted, u.OfLimited) +} +func (u *BetaManagedAgentsCredentialNetworkingParamsUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *BetaManagedAgentsCredentialNetworkingParamsUnion) asAny() any { + if !param.IsOmitted(u.OfUnrestricted) { + return u.OfUnrestricted + } else if !param.IsOmitted(u.OfLimited) { + return u.OfLimited + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaManagedAgentsCredentialNetworkingParamsUnion) GetAllowedHosts() []string { + if vt := u.OfLimited; vt != nil { + return vt.AllowedHosts + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaManagedAgentsCredentialNetworkingParamsUnion) GetType() *string { + if vt := u.OfUnrestricted; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfLimited; vt != nil { + return (*string)(&vt.Type) + } + return nil +} + +func init() { + apijson.RegisterUnion[BetaManagedAgentsCredentialNetworkingParamsUnion]( + "type", + apijson.Discriminator[BetaManagedAgentsUnrestrictedCredentialNetworkingParams]("unrestricted"), + apijson.Discriminator[BetaManagedAgentsLimitedCredentialNetworkingParams]("limited"), + ) +} + +// Result of live-probing a credential against its configured MCP server. +type BetaManagedAgentsCredentialValidation struct { + // Unique identifier of the credential that was validated. + CredentialID string `json:"credential_id" api:"required"` + // Whether the credential has a refresh token configured. + HasRefreshToken bool `json:"has_refresh_token" api:"required"` + // The failing step of an MCP validation probe. + MCPProbe BetaManagedAgentsMCPProbe `json:"mcp_probe" api:"required"` + // Outcome of a refresh-token exchange attempted during credential validation. + Refresh BetaManagedAgentsRefreshObject `json:"refresh" api:"required"` + // Overall verdict of a credential validation probe. + // + // Any of "valid", "invalid", "unknown". + Status BetaManagedAgentsCredentialValidationStatus `json:"status" api:"required"` + // Any of "vault_credential_validation". + Type BetaManagedAgentsCredentialValidationType `json:"type" api:"required"` + // A timestamp in RFC 3339 format + ValidatedAt time.Time `json:"validated_at" api:"required" format:"date-time"` + // Identifier of the vault containing the credential. + VaultID string `json:"vault_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + CredentialID respjson.Field + HasRefreshToken respjson.Field + MCPProbe respjson.Field + Refresh respjson.Field + Status respjson.Field + Type respjson.Field + ValidatedAt respjson.Field + VaultID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsCredentialValidation) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsCredentialValidation) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsCredentialValidationType string + +const ( + BetaManagedAgentsCredentialValidationTypeVaultCredentialValidation BetaManagedAgentsCredentialValidationType = "vault_credential_validation" +) + +// Overall verdict of a credential validation probe. +type BetaManagedAgentsCredentialValidationStatus string + +const ( + BetaManagedAgentsCredentialValidationStatusValid BetaManagedAgentsCredentialValidationStatus = "valid" + BetaManagedAgentsCredentialValidationStatusInvalid BetaManagedAgentsCredentialValidationStatus = "invalid" + BetaManagedAgentsCredentialValidationStatusUnknown BetaManagedAgentsCredentialValidationStatus = "unknown" +) + // Confirmation of a deleted credential. type BetaManagedAgentsDeletedCredential struct { // Unique identifier of the deleted credential. @@ -312,6 +470,285 @@ const ( BetaManagedAgentsDeletedCredentialTypeVaultCredentialDeleted BetaManagedAgentsDeletedCredentialType = "vault_credential_deleted" ) +// Environment variable credential details. The secret value is never returned. +type BetaManagedAgentsEnvironmentVariableAuthResponse struct { + // Where in the outbound request the secret value is substituted. + InjectionLocation BetaManagedAgentsInjectionLocationResponse `json:"injection_location" api:"required"` + // Outbound hosts the secret value is substituted on. + Networking BetaManagedAgentsEnvironmentVariableAuthResponseNetworkingUnion `json:"networking" api:"required"` + // Name of the environment variable. + SecretName string `json:"secret_name" api:"required"` + // Any of "environment_variable". + Type BetaManagedAgentsEnvironmentVariableAuthResponseType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + InjectionLocation respjson.Field + Networking respjson.Field + SecretName respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsEnvironmentVariableAuthResponse) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsEnvironmentVariableAuthResponse) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaManagedAgentsEnvironmentVariableAuthResponseNetworkingUnion contains all +// possible properties and values from +// [BetaManagedAgentsUnrestrictedCredentialNetworkingResponse], +// [BetaManagedAgentsLimitedCredentialNetworkingResponse]. +// +// Use the [BetaManagedAgentsEnvironmentVariableAuthResponseNetworkingUnion.AsAny] +// method to switch on the variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaManagedAgentsEnvironmentVariableAuthResponseNetworkingUnion struct { + // Any of "unrestricted", "limited". + Type string `json:"type"` + // This field is from variant + // [BetaManagedAgentsLimitedCredentialNetworkingResponse]. + AllowedHosts []string `json:"allowed_hosts"` + JSON struct { + Type respjson.Field + AllowedHosts respjson.Field + raw string + } `json:"-"` +} + +// anyBetaManagedAgentsEnvironmentVariableAuthResponseNetworking is implemented by +// each variant of +// [BetaManagedAgentsEnvironmentVariableAuthResponseNetworkingUnion] to add type +// safety for the return type of +// [BetaManagedAgentsEnvironmentVariableAuthResponseNetworkingUnion.AsAny] +type anyBetaManagedAgentsEnvironmentVariableAuthResponseNetworking interface { + implBetaManagedAgentsEnvironmentVariableAuthResponseNetworkingUnion() +} + +func (BetaManagedAgentsUnrestrictedCredentialNetworkingResponse) implBetaManagedAgentsEnvironmentVariableAuthResponseNetworkingUnion() { +} +func (BetaManagedAgentsLimitedCredentialNetworkingResponse) implBetaManagedAgentsEnvironmentVariableAuthResponseNetworkingUnion() { +} + +// Use the following switch statement to find the correct variant +// +// switch variant := BetaManagedAgentsEnvironmentVariableAuthResponseNetworkingUnion.AsAny().(type) { +// case anthropic.BetaManagedAgentsUnrestrictedCredentialNetworkingResponse: +// case anthropic.BetaManagedAgentsLimitedCredentialNetworkingResponse: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaManagedAgentsEnvironmentVariableAuthResponseNetworkingUnion) AsAny() anyBetaManagedAgentsEnvironmentVariableAuthResponseNetworking { + switch u.Type { + case "unrestricted": + return u.AsUnrestricted() + case "limited": + return u.AsLimited() + } + return nil +} + +func (u BetaManagedAgentsEnvironmentVariableAuthResponseNetworkingUnion) AsUnrestricted() (v BetaManagedAgentsUnrestrictedCredentialNetworkingResponse) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaManagedAgentsEnvironmentVariableAuthResponseNetworkingUnion) AsLimited() (v BetaManagedAgentsLimitedCredentialNetworkingResponse) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u BetaManagedAgentsEnvironmentVariableAuthResponseNetworkingUnion) RawJSON() string { + return u.JSON.raw +} + +func (r *BetaManagedAgentsEnvironmentVariableAuthResponseNetworkingUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsEnvironmentVariableAuthResponseType string + +const ( + BetaManagedAgentsEnvironmentVariableAuthResponseTypeEnvironmentVariable BetaManagedAgentsEnvironmentVariableAuthResponseType = "environment_variable" +) + +// Parameters for creating an environment variable credential. +// +// The properties Networking, SecretName, SecretValue, Type are required. +type BetaManagedAgentsEnvironmentVariableCreateParams struct { + // Outbound hosts the secret value is substituted on. + Networking BetaManagedAgentsCredentialNetworkingParamsUnion `json:"networking,omitzero" api:"required"` + // Name of the environment variable. Immutable after create. + SecretName string `json:"secret_name" api:"required"` + // Secret value. Write-only; never returned in responses. + SecretValue string `json:"secret_value" api:"required"` + // Any of "environment_variable". + Type BetaManagedAgentsEnvironmentVariableCreateParamsType `json:"type,omitzero" api:"required"` + // Where in the outbound request the secret value may be substituted. + InjectionLocation BetaManagedAgentsInjectionLocationParams `json:"injection_location,omitzero"` + paramObj +} + +func (r BetaManagedAgentsEnvironmentVariableCreateParams) MarshalJSON() (data []byte, err error) { + type shadow BetaManagedAgentsEnvironmentVariableCreateParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaManagedAgentsEnvironmentVariableCreateParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsEnvironmentVariableCreateParamsType string + +const ( + BetaManagedAgentsEnvironmentVariableCreateParamsTypeEnvironmentVariable BetaManagedAgentsEnvironmentVariableCreateParamsType = "environment_variable" +) + +// Parameters for updating an environment variable credential. `secret_name` is +// immutable. +// +// The property Type is required. +type BetaManagedAgentsEnvironmentVariableUpdateParams struct { + // Any of "environment_variable". + Type BetaManagedAgentsEnvironmentVariableUpdateParamsType `json:"type,omitzero" api:"required"` + // Updated secret value. + SecretValue param.Opt[string] `json:"secret_value,omitzero"` + // Updated injection location. + InjectionLocation BetaManagedAgentsInjectionLocationUpdateParams `json:"injection_location,omitzero"` + // Updated networking scope. Full replacement. + Networking BetaManagedAgentsCredentialNetworkingParamsUnion `json:"networking,omitzero"` + paramObj +} + +func (r BetaManagedAgentsEnvironmentVariableUpdateParams) MarshalJSON() (data []byte, err error) { + type shadow BetaManagedAgentsEnvironmentVariableUpdateParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaManagedAgentsEnvironmentVariableUpdateParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsEnvironmentVariableUpdateParamsType string + +const ( + BetaManagedAgentsEnvironmentVariableUpdateParamsTypeEnvironmentVariable BetaManagedAgentsEnvironmentVariableUpdateParamsType = "environment_variable" +) + +// Where in the outbound request the secret value may be substituted. +type BetaManagedAgentsInjectionLocationParams struct { + // Substitute when the placeholder appears in the request body. + Body param.Opt[bool] `json:"body,omitzero"` + // Substitute when the placeholder appears in a request header value. + Header param.Opt[bool] `json:"header,omitzero"` + paramObj +} + +func (r BetaManagedAgentsInjectionLocationParams) MarshalJSON() (data []byte, err error) { + type shadow BetaManagedAgentsInjectionLocationParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaManagedAgentsInjectionLocationParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Where in the outbound request the secret value is substituted. +type BetaManagedAgentsInjectionLocationResponse struct { + // Whether the placeholder is substituted in the request body. + Body bool `json:"body" api:"required"` + // Whether the placeholder is substituted in request header values. + Header bool `json:"header" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Body respjson.Field + Header respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsInjectionLocationResponse) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsInjectionLocationResponse) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Updated injection location. +type BetaManagedAgentsInjectionLocationUpdateParams struct { + // Substitute when the placeholder appears in the request body. + Body param.Opt[bool] `json:"body,omitzero"` + // Substitute when the placeholder appears in a request header value. + Header param.Opt[bool] `json:"header,omitzero"` + paramObj +} + +func (r BetaManagedAgentsInjectionLocationUpdateParams) MarshalJSON() (data []byte, err error) { + type shadow BetaManagedAgentsInjectionLocationUpdateParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaManagedAgentsInjectionLocationUpdateParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Substitute the secret only on requests to the listed hosts. +// +// The properties AllowedHosts, Type are required. +type BetaManagedAgentsLimitedCredentialNetworkingParams struct { + // Hostnames on which the secret will be substituted. Each entry is a bare hostname + // (`api.example.com`), an IPv4 address (`192.0.2.1`), or a `*.`-prefixed wildcard + // (`*.example.com`). URLs, ports, paths, and IPv6 addresses are not accepted. At + // most 16 entries. + AllowedHosts []string `json:"allowed_hosts,omitzero" api:"required"` + // Any of "limited". + Type BetaManagedAgentsLimitedCredentialNetworkingParamsType `json:"type,omitzero" api:"required"` + paramObj +} + +func (r BetaManagedAgentsLimitedCredentialNetworkingParams) MarshalJSON() (data []byte, err error) { + type shadow BetaManagedAgentsLimitedCredentialNetworkingParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaManagedAgentsLimitedCredentialNetworkingParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsLimitedCredentialNetworkingParamsType string + +const ( + BetaManagedAgentsLimitedCredentialNetworkingParamsTypeLimited BetaManagedAgentsLimitedCredentialNetworkingParamsType = "limited" +) + +// The secret is substituted only on requests to the listed hosts. +type BetaManagedAgentsLimitedCredentialNetworkingResponse struct { + // Hostnames on which the secret will be substituted. An entry matches the request + // host exactly; a `*.`-prefixed entry matches any subdomain of the named domain + // but not the domain itself. + AllowedHosts []string `json:"allowed_hosts" api:"required"` + // Any of "limited". + Type BetaManagedAgentsLimitedCredentialNetworkingResponseType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + AllowedHosts respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsLimitedCredentialNetworkingResponse) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsLimitedCredentialNetworkingResponse) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsLimitedCredentialNetworkingResponseType string + +const ( + BetaManagedAgentsLimitedCredentialNetworkingResponseTypeLimited BetaManagedAgentsLimitedCredentialNetworkingResponseType = "limited" +) + // OAuth credential details for an MCP server. type BetaManagedAgentsMCPOAuthAuthResponse struct { // URL of the MCP server this credential authenticates against. @@ -674,6 +1111,87 @@ const ( BetaManagedAgentsMCPOAuthUpdateParamsTypeMCPOAuth BetaManagedAgentsMCPOAuthUpdateParamsType = "mcp_oauth" ) +// The failing step of an MCP validation probe. +type BetaManagedAgentsMCPProbe struct { + // An HTTP response captured during a credential validation probe. + HTTPResponse BetaManagedAgentsRefreshHTTPResponse `json:"http_response" api:"required"` + // The MCP method that failed (for example `initialize` or `tools/list`). + Method string `json:"method" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + HTTPResponse respjson.Field + Method respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsMCPProbe) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsMCPProbe) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// An HTTP response captured during a credential validation probe. +type BetaManagedAgentsRefreshHTTPResponse struct { + // Response body. May be truncated and has sensitive values scrubbed. + Body string `json:"body" api:"required"` + // Whether `body` was truncated. + BodyTruncated bool `json:"body_truncated" api:"required"` + // Value of the `Content-Type` response header. + ContentType string `json:"content_type" api:"required"` + // HTTP status code. + StatusCode int64 `json:"status_code" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Body respjson.Field + BodyTruncated respjson.Field + ContentType respjson.Field + StatusCode respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsRefreshHTTPResponse) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsRefreshHTTPResponse) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Outcome of a refresh-token exchange attempted during credential validation. +type BetaManagedAgentsRefreshObject struct { + // An HTTP response captured during a credential validation probe. + HTTPResponse BetaManagedAgentsRefreshHTTPResponse `json:"http_response" api:"required"` + // Outcome of a refresh-token exchange attempted during credential validation. + // + // Any of "succeeded", "failed", "connect_error", "no_refresh_token". + Status BetaManagedAgentsRefreshObjectStatus `json:"status" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + HTTPResponse respjson.Field + Status respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsRefreshObject) RawJSON() string { return r.JSON.raw } +func (r *BetaManagedAgentsRefreshObject) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Outcome of a refresh-token exchange attempted during credential validation. +type BetaManagedAgentsRefreshObjectStatus string + +const ( + BetaManagedAgentsRefreshObjectStatusSucceeded BetaManagedAgentsRefreshObjectStatus = "succeeded" + BetaManagedAgentsRefreshObjectStatusFailed BetaManagedAgentsRefreshObjectStatus = "failed" + BetaManagedAgentsRefreshObjectStatusConnectError BetaManagedAgentsRefreshObjectStatus = "connect_error" + BetaManagedAgentsRefreshObjectStatusNoRefreshToken BetaManagedAgentsRefreshObjectStatus = "no_refresh_token" +) + // Static bearer token credential details for an MCP server. type BetaManagedAgentsStaticBearerAuthResponse struct { // URL of the MCP server this credential authenticates against. @@ -949,6 +1467,58 @@ const ( BetaManagedAgentsTokenEndpointAuthPostUpdateParamTypeClientSecretPost BetaManagedAgentsTokenEndpointAuthPostUpdateParamType = "client_secret_post" ) +// Substitute the secret on any host the session's Environment network policy +// permits egress to. The Environment's network policy is the only boundary on +// where the secret can reach. +// +// The property Type is required. +type BetaManagedAgentsUnrestrictedCredentialNetworkingParams struct { + // Any of "unrestricted". + Type BetaManagedAgentsUnrestrictedCredentialNetworkingParamsType `json:"type,omitzero" api:"required"` + paramObj +} + +func (r BetaManagedAgentsUnrestrictedCredentialNetworkingParams) MarshalJSON() (data []byte, err error) { + type shadow BetaManagedAgentsUnrestrictedCredentialNetworkingParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BetaManagedAgentsUnrestrictedCredentialNetworkingParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsUnrestrictedCredentialNetworkingParamsType string + +const ( + BetaManagedAgentsUnrestrictedCredentialNetworkingParamsTypeUnrestricted BetaManagedAgentsUnrestrictedCredentialNetworkingParamsType = "unrestricted" +) + +// The secret is substituted on any host the session's Environment network policy +// permits egress to. +type BetaManagedAgentsUnrestrictedCredentialNetworkingResponse struct { + // Any of "unrestricted". + Type BetaManagedAgentsUnrestrictedCredentialNetworkingResponseType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaManagedAgentsUnrestrictedCredentialNetworkingResponse) RawJSON() string { + return r.JSON.raw +} +func (r *BetaManagedAgentsUnrestrictedCredentialNetworkingResponse) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaManagedAgentsUnrestrictedCredentialNetworkingResponseType string + +const ( + BetaManagedAgentsUnrestrictedCredentialNetworkingResponseTypeUnrestricted BetaManagedAgentsUnrestrictedCredentialNetworkingResponseType = "unrestricted" +) + type BetaVaultCredentialNewParams struct { // Authentication details for creating a credential. Auth BetaVaultCredentialNewParamsAuthUnion `json:"auth,omitzero" api:"required"` @@ -974,13 +1544,14 @@ func (r *BetaVaultCredentialNewParams) UnmarshalJSON(data []byte) error { // // Use [param.IsOmitted] to confirm if a field is set. type BetaVaultCredentialNewParamsAuthUnion struct { - OfMCPOAuth *BetaManagedAgentsMCPOAuthCreateParams `json:",omitzero,inline"` - OfStaticBearer *BetaManagedAgentsStaticBearerCreateParams `json:",omitzero,inline"` + OfMCPOAuth *BetaManagedAgentsMCPOAuthCreateParams `json:",omitzero,inline"` + OfStaticBearer *BetaManagedAgentsStaticBearerCreateParams `json:",omitzero,inline"` + OfEnvironmentVariable *BetaManagedAgentsEnvironmentVariableCreateParams `json:",omitzero,inline"` paramUnion } func (u BetaVaultCredentialNewParamsAuthUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfMCPOAuth, u.OfStaticBearer) + return param.MarshalUnion(u, u.OfMCPOAuth, u.OfStaticBearer, u.OfEnvironmentVariable) } func (u *BetaVaultCredentialNewParamsAuthUnion) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, u) @@ -991,6 +1562,8 @@ func (u *BetaVaultCredentialNewParamsAuthUnion) asAny() any { return u.OfMCPOAuth } else if !param.IsOmitted(u.OfStaticBearer) { return u.OfStaticBearer + } else if !param.IsOmitted(u.OfEnvironmentVariable) { + return u.OfEnvironmentVariable } return nil } @@ -1027,6 +1600,38 @@ func (u BetaVaultCredentialNewParamsAuthUnion) GetToken() *string { return nil } +// Returns a pointer to the underlying variant's property, if present. +func (u BetaVaultCredentialNewParamsAuthUnion) GetNetworking() *BetaManagedAgentsCredentialNetworkingParamsUnion { + if vt := u.OfEnvironmentVariable; vt != nil { + return &vt.Networking + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaVaultCredentialNewParamsAuthUnion) GetSecretName() *string { + if vt := u.OfEnvironmentVariable; vt != nil { + return &vt.SecretName + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaVaultCredentialNewParamsAuthUnion) GetSecretValue() *string { + if vt := u.OfEnvironmentVariable; vt != nil { + return &vt.SecretValue + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaVaultCredentialNewParamsAuthUnion) GetInjectionLocation() *BetaManagedAgentsInjectionLocationParams { + if vt := u.OfEnvironmentVariable; vt != nil { + return &vt.InjectionLocation + } + return nil +} + // Returns a pointer to the underlying variant's property, if present. func (u BetaVaultCredentialNewParamsAuthUnion) GetMCPServerURL() *string { if vt := u.OfMCPOAuth; vt != nil { @@ -1043,6 +1648,8 @@ func (u BetaVaultCredentialNewParamsAuthUnion) GetType() *string { return (*string)(&vt.Type) } else if vt := u.OfStaticBearer; vt != nil { return (*string)(&vt.Type) + } else if vt := u.OfEnvironmentVariable; vt != nil { + return (*string)(&vt.Type) } return nil } @@ -1052,6 +1659,7 @@ func init() { "type", apijson.Discriminator[BetaManagedAgentsMCPOAuthCreateParams]("mcp_oauth"), apijson.Discriminator[BetaManagedAgentsStaticBearerCreateParams]("static_bearer"), + apijson.Discriminator[BetaManagedAgentsEnvironmentVariableCreateParams]("environment_variable"), ) } @@ -1088,13 +1696,14 @@ func (r *BetaVaultCredentialUpdateParams) UnmarshalJSON(data []byte) error { // // Use [param.IsOmitted] to confirm if a field is set. type BetaVaultCredentialUpdateParamsAuthUnion struct { - OfMCPOAuth *BetaManagedAgentsMCPOAuthUpdateParams `json:",omitzero,inline"` - OfStaticBearer *BetaManagedAgentsStaticBearerUpdateParams `json:",omitzero,inline"` + OfMCPOAuth *BetaManagedAgentsMCPOAuthUpdateParams `json:",omitzero,inline"` + OfStaticBearer *BetaManagedAgentsStaticBearerUpdateParams `json:",omitzero,inline"` + OfEnvironmentVariable *BetaManagedAgentsEnvironmentVariableUpdateParams `json:",omitzero,inline"` paramUnion } func (u BetaVaultCredentialUpdateParamsAuthUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfMCPOAuth, u.OfStaticBearer) + return param.MarshalUnion(u, u.OfMCPOAuth, u.OfStaticBearer, u.OfEnvironmentVariable) } func (u *BetaVaultCredentialUpdateParamsAuthUnion) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, u) @@ -1105,6 +1714,8 @@ func (u *BetaVaultCredentialUpdateParamsAuthUnion) asAny() any { return u.OfMCPOAuth } else if !param.IsOmitted(u.OfStaticBearer) { return u.OfStaticBearer + } else if !param.IsOmitted(u.OfEnvironmentVariable) { + return u.OfEnvironmentVariable } return nil } @@ -1141,12 +1752,38 @@ func (u BetaVaultCredentialUpdateParamsAuthUnion) GetToken() *string { return nil } +// Returns a pointer to the underlying variant's property, if present. +func (u BetaVaultCredentialUpdateParamsAuthUnion) GetInjectionLocation() *BetaManagedAgentsInjectionLocationUpdateParams { + if vt := u.OfEnvironmentVariable; vt != nil { + return &vt.InjectionLocation + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaVaultCredentialUpdateParamsAuthUnion) GetNetworking() *BetaManagedAgentsCredentialNetworkingParamsUnion { + if vt := u.OfEnvironmentVariable; vt != nil { + return &vt.Networking + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u BetaVaultCredentialUpdateParamsAuthUnion) GetSecretValue() *string { + if vt := u.OfEnvironmentVariable; vt != nil && vt.SecretValue.Valid() { + return &vt.SecretValue.Value + } + return nil +} + // Returns a pointer to the underlying variant's property, if present. func (u BetaVaultCredentialUpdateParamsAuthUnion) GetType() *string { if vt := u.OfMCPOAuth; vt != nil { return (*string)(&vt.Type) } else if vt := u.OfStaticBearer; vt != nil { return (*string)(&vt.Type) + } else if vt := u.OfEnvironmentVariable; vt != nil { + return (*string)(&vt.Type) } return nil } @@ -1156,6 +1793,7 @@ func init() { "type", apijson.Discriminator[BetaManagedAgentsMCPOAuthUpdateParams]("mcp_oauth"), apijson.Discriminator[BetaManagedAgentsStaticBearerUpdateParams]("static_bearer"), + apijson.Discriminator[BetaManagedAgentsEnvironmentVariableUpdateParams]("environment_variable"), ) } @@ -1175,7 +1813,7 @@ type BetaVaultCredentialListParams struct { // `url.Values`. func (r BetaVaultCredentialListParams) URLQuery() (v url.Values, err error) { return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ - ArrayFormat: apiquery.ArrayQueryFormatComma, + ArrayFormat: apiquery.ArrayQueryFormatBrackets, NestedFormat: apiquery.NestedQueryFormatBrackets, }) } @@ -1193,3 +1831,10 @@ type BetaVaultCredentialArchiveParams struct { Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` paramObj } + +type BetaVaultCredentialMCPOAuthValidateParams struct { + VaultID string `path:"vault_id" api:"required" json:"-"` + // Optional header to specify the beta version(s) you want to use. + Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` + paramObj +} diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/betawebhook.go b/vendor/github.com/anthropics/anthropic-sdk-go/betawebhook.go new file mode 100644 index 000000000..f0649f833 --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/betawebhook.go @@ -0,0 +1,1619 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +package anthropic + +import ( + "encoding/json" + "errors" + "net/http" + "slices" + "time" + + "github.com/anthropics/anthropic-sdk-go/internal/apijson" + "github.com/anthropics/anthropic-sdk-go/internal/requestconfig" + "github.com/anthropics/anthropic-sdk-go/option" + "github.com/anthropics/anthropic-sdk-go/packages/respjson" + "github.com/anthropics/anthropic-sdk-go/shared/constant" + standardwebhooks "github.com/standard-webhooks/standard-webhooks/libraries/go" +) + +// BetaWebhookService contains methods and other services that help with +// interacting with the anthropic API. +// +// Note, unlike clients, this service does not read variables from the environment +// automatically. You should not instantiate this service directly, and instead use +// the [NewBetaWebhookService] method instead. +type BetaWebhookService struct { + Options []option.RequestOption +} + +// NewBetaWebhookService generates a new service that applies the given options to +// each request. These options are applied after the parent client's options (if +// there is one), and before any request-specific options. +func NewBetaWebhookService(opts ...option.RequestOption) (r BetaWebhookService) { + r = BetaWebhookService{} + r.Options = opts + return +} + +func (r *BetaWebhookService) Unwrap(payload []byte, headers http.Header, opts ...option.RequestOption) (*UnwrapWebhookEvent, error) { + opts = slices.Concat(r.Options, opts) + cfg, err := requestconfig.PreRequestOptions(opts...) + if err != nil { + return nil, err + } + key := cfg.WebhookKey + if key == "" { + return nil, errors.New("The WebhookKey option must be set in order to verify webhook headers") + } + wh, err := standardwebhooks.NewWebhook(key) + if err != nil { + return nil, err + } + err = wh.Verify(payload, headers) + if err != nil { + return nil, err + } + res := &UnwrapWebhookEvent{} + err = res.UnmarshalJSON(payload) + if err != nil { + return res, err + } + return res, nil +} + +type BetaWebhookAgentArchivedEventData struct { + // ID of the agent that triggered the event. + ID string `json:"id" api:"required"` + OrganizationID string `json:"organization_id" api:"required"` + Type constant.AgentArchived `json:"type" default:"agent.archived"` + WorkspaceID string `json:"workspace_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + OrganizationID respjson.Field + Type respjson.Field + WorkspaceID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaWebhookAgentArchivedEventData) RawJSON() string { return r.JSON.raw } +func (r *BetaWebhookAgentArchivedEventData) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaWebhookAgentCreatedEventData struct { + // ID of the agent that triggered the event. + ID string `json:"id" api:"required"` + OrganizationID string `json:"organization_id" api:"required"` + Type constant.AgentCreated `json:"type" default:"agent.created"` + WorkspaceID string `json:"workspace_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + OrganizationID respjson.Field + Type respjson.Field + WorkspaceID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaWebhookAgentCreatedEventData) RawJSON() string { return r.JSON.raw } +func (r *BetaWebhookAgentCreatedEventData) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaWebhookAgentDeletedEventData struct { + // ID of the agent that triggered the event. + ID string `json:"id" api:"required"` + OrganizationID string `json:"organization_id" api:"required"` + Type constant.AgentDeleted `json:"type" default:"agent.deleted"` + WorkspaceID string `json:"workspace_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + OrganizationID respjson.Field + Type respjson.Field + WorkspaceID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaWebhookAgentDeletedEventData) RawJSON() string { return r.JSON.raw } +func (r *BetaWebhookAgentDeletedEventData) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaWebhookAgentUpdatedEventData struct { + // ID of the agent that triggered the event. + ID string `json:"id" api:"required"` + OrganizationID string `json:"organization_id" api:"required"` + Type constant.AgentUpdated `json:"type" default:"agent.updated"` + WorkspaceID string `json:"workspace_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + OrganizationID respjson.Field + Type respjson.Field + WorkspaceID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaWebhookAgentUpdatedEventData) RawJSON() string { return r.JSON.raw } +func (r *BetaWebhookAgentUpdatedEventData) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaWebhookDeploymentArchivedEventData struct { + // ID of the deployment that triggered the event. + ID string `json:"id" api:"required"` + OrganizationID string `json:"organization_id" api:"required"` + Type constant.DeploymentArchived `json:"type" default:"deployment.archived"` + WorkspaceID string `json:"workspace_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + OrganizationID respjson.Field + Type respjson.Field + WorkspaceID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaWebhookDeploymentArchivedEventData) RawJSON() string { return r.JSON.raw } +func (r *BetaWebhookDeploymentArchivedEventData) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaWebhookDeploymentCreatedEventData struct { + // ID of the deployment that triggered the event. + ID string `json:"id" api:"required"` + OrganizationID string `json:"organization_id" api:"required"` + Type constant.DeploymentCreated `json:"type" default:"deployment.created"` + WorkspaceID string `json:"workspace_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + OrganizationID respjson.Field + Type respjson.Field + WorkspaceID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaWebhookDeploymentCreatedEventData) RawJSON() string { return r.JSON.raw } +func (r *BetaWebhookDeploymentCreatedEventData) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaWebhookDeploymentDeletedEventData struct { + // ID of the deployment that triggered the event. + ID string `json:"id" api:"required"` + OrganizationID string `json:"organization_id" api:"required"` + Type constant.DeploymentDeleted `json:"type" default:"deployment.deleted"` + WorkspaceID string `json:"workspace_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + OrganizationID respjson.Field + Type respjson.Field + WorkspaceID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaWebhookDeploymentDeletedEventData) RawJSON() string { return r.JSON.raw } +func (r *BetaWebhookDeploymentDeletedEventData) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaWebhookDeploymentPausedEventData struct { + // ID of the deployment that triggered the event. + ID string `json:"id" api:"required"` + OrganizationID string `json:"organization_id" api:"required"` + Type constant.DeploymentPaused `json:"type" default:"deployment.paused"` + WorkspaceID string `json:"workspace_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + OrganizationID respjson.Field + Type respjson.Field + WorkspaceID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaWebhookDeploymentPausedEventData) RawJSON() string { return r.JSON.raw } +func (r *BetaWebhookDeploymentPausedEventData) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaWebhookDeploymentRunFailedEventData struct { + // ID of the deployment run that triggered the event. + ID string `json:"id" api:"required"` + OrganizationID string `json:"organization_id" api:"required"` + Type constant.DeploymentRunFailed `json:"type" default:"deployment_run.failed"` + WorkspaceID string `json:"workspace_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + OrganizationID respjson.Field + Type respjson.Field + WorkspaceID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaWebhookDeploymentRunFailedEventData) RawJSON() string { return r.JSON.raw } +func (r *BetaWebhookDeploymentRunFailedEventData) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaWebhookDeploymentRunStartedEventData struct { + // ID of the deployment run that triggered the event. + ID string `json:"id" api:"required"` + OrganizationID string `json:"organization_id" api:"required"` + Type constant.DeploymentRunStarted `json:"type" default:"deployment_run.started"` + WorkspaceID string `json:"workspace_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + OrganizationID respjson.Field + Type respjson.Field + WorkspaceID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaWebhookDeploymentRunStartedEventData) RawJSON() string { return r.JSON.raw } +func (r *BetaWebhookDeploymentRunStartedEventData) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaWebhookDeploymentRunSucceededEventData struct { + // ID of the deployment run that triggered the event. + ID string `json:"id" api:"required"` + OrganizationID string `json:"organization_id" api:"required"` + Type constant.DeploymentRunSucceeded `json:"type" default:"deployment_run.succeeded"` + WorkspaceID string `json:"workspace_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + OrganizationID respjson.Field + Type respjson.Field + WorkspaceID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaWebhookDeploymentRunSucceededEventData) RawJSON() string { return r.JSON.raw } +func (r *BetaWebhookDeploymentRunSucceededEventData) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaWebhookDeploymentUnpausedEventData struct { + // ID of the deployment that triggered the event. + ID string `json:"id" api:"required"` + OrganizationID string `json:"organization_id" api:"required"` + Type constant.DeploymentUnpaused `json:"type" default:"deployment.unpaused"` + WorkspaceID string `json:"workspace_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + OrganizationID respjson.Field + Type respjson.Field + WorkspaceID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaWebhookDeploymentUnpausedEventData) RawJSON() string { return r.JSON.raw } +func (r *BetaWebhookDeploymentUnpausedEventData) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaWebhookDeploymentUpdatedEventData struct { + // ID of the deployment that triggered the event. + ID string `json:"id" api:"required"` + OrganizationID string `json:"organization_id" api:"required"` + Type constant.DeploymentUpdated `json:"type" default:"deployment.updated"` + WorkspaceID string `json:"workspace_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + OrganizationID respjson.Field + Type respjson.Field + WorkspaceID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaWebhookDeploymentUpdatedEventData) RawJSON() string { return r.JSON.raw } +func (r *BetaWebhookDeploymentUpdatedEventData) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaWebhookEnvironmentArchivedEventData struct { + // ID of the environment that triggered the event. + ID string `json:"id" api:"required"` + OrganizationID string `json:"organization_id" api:"required"` + Type constant.EnvironmentArchived `json:"type" default:"environment.archived"` + WorkspaceID string `json:"workspace_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + OrganizationID respjson.Field + Type respjson.Field + WorkspaceID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaWebhookEnvironmentArchivedEventData) RawJSON() string { return r.JSON.raw } +func (r *BetaWebhookEnvironmentArchivedEventData) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaWebhookEnvironmentCreatedEventData struct { + // ID of the environment that triggered the event. + ID string `json:"id" api:"required"` + OrganizationID string `json:"organization_id" api:"required"` + Type constant.EnvironmentCreated `json:"type" default:"environment.created"` + WorkspaceID string `json:"workspace_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + OrganizationID respjson.Field + Type respjson.Field + WorkspaceID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaWebhookEnvironmentCreatedEventData) RawJSON() string { return r.JSON.raw } +func (r *BetaWebhookEnvironmentCreatedEventData) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaWebhookEnvironmentDeletedEventData struct { + // ID of the environment that triggered the event. + ID string `json:"id" api:"required"` + OrganizationID string `json:"organization_id" api:"required"` + Type constant.EnvironmentDeleted `json:"type" default:"environment.deleted"` + WorkspaceID string `json:"workspace_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + OrganizationID respjson.Field + Type respjson.Field + WorkspaceID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaWebhookEnvironmentDeletedEventData) RawJSON() string { return r.JSON.raw } +func (r *BetaWebhookEnvironmentDeletedEventData) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaWebhookEnvironmentUpdatedEventData struct { + // ID of the environment that triggered the event. + ID string `json:"id" api:"required"` + OrganizationID string `json:"organization_id" api:"required"` + Type constant.EnvironmentUpdated `json:"type" default:"environment.updated"` + WorkspaceID string `json:"workspace_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + OrganizationID respjson.Field + Type respjson.Field + WorkspaceID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaWebhookEnvironmentUpdatedEventData) RawJSON() string { return r.JSON.raw } +func (r *BetaWebhookEnvironmentUpdatedEventData) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// BetaWebhookEventDataUnion contains all possible properties and values from +// [BetaWebhookSessionCreatedEventData], [BetaWebhookSessionPendingEventData], +// [BetaWebhookSessionRunningEventData], [BetaWebhookSessionIdledEventData], +// [BetaWebhookSessionRequiresActionEventData], +// [BetaWebhookSessionArchivedEventData], [BetaWebhookSessionDeletedEventData], +// [BetaWebhookSessionStatusRescheduledEventData], +// [BetaWebhookSessionStatusRunStartedEventData], +// [BetaWebhookSessionStatusIdledEventData], +// [BetaWebhookSessionStatusTerminatedEventData], +// [BetaWebhookSessionThreadCreatedEventData], +// [BetaWebhookSessionThreadIdledEventData], +// [BetaWebhookSessionThreadTerminatedEventData], +// [BetaWebhookSessionOutcomeEvaluationEndedEventData], +// [BetaWebhookVaultCreatedEventData], [BetaWebhookVaultArchivedEventData], +// [BetaWebhookVaultDeletedEventData], +// [BetaWebhookVaultCredentialCreatedEventData], +// [BetaWebhookVaultCredentialArchivedEventData], +// [BetaWebhookVaultCredentialDeletedEventData], +// [BetaWebhookVaultCredentialRefreshFailedEventData], +// [BetaWebhookSessionUpdatedEventData], [BetaWebhookAgentCreatedEventData], +// [BetaWebhookAgentArchivedEventData], [BetaWebhookAgentDeletedEventData], +// [BetaWebhookDeploymentPausedEventData], +// [BetaWebhookDeploymentRunFailedEventData], +// [BetaWebhookDeploymentCreatedEventData], +// [BetaWebhookDeploymentUpdatedEventData], +// [BetaWebhookDeploymentUnpausedEventData], [BetaWebhookAgentUpdatedEventData], +// [BetaWebhookDeploymentArchivedEventData], +// [BetaWebhookDeploymentRunStartedEventData], +// [BetaWebhookDeploymentDeletedEventData], +// [BetaWebhookDeploymentRunSucceededEventData], +// [BetaWebhookEnvironmentCreatedEventData], +// [BetaWebhookEnvironmentUpdatedEventData], +// [BetaWebhookEnvironmentArchivedEventData], +// [BetaWebhookEnvironmentDeletedEventData], +// [BetaWebhookMemoryStoreCreatedEventData], +// [BetaWebhookMemoryStoreArchivedEventData], +// [BetaWebhookMemoryStoreDeletedEventData], +// [BetaWebhookSessionBudgetReachedEventData]. +// +// Use the [BetaWebhookEventDataUnion.AsAny] method to switch on the variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type BetaWebhookEventDataUnion struct { + ID string `json:"id"` + OrganizationID string `json:"organization_id"` + // Any of "session.created", "session.pending", "session.running", "session.idled", + // "session.requires_action", "session.archived", "session.deleted", + // "session.status_rescheduled", "session.status_run_started", + // "session.status_idled", "session.status_terminated", "session.thread_created", + // "session.thread_idled", "session.thread_terminated", + // "session.outcome_evaluation_ended", "vault.created", "vault.archived", + // "vault.deleted", "vault_credential.created", "vault_credential.archived", + // "vault_credential.deleted", "vault_credential.refresh_failed", + // "session.updated", "agent.created", "agent.archived", "agent.deleted", + // "deployment.paused", "deployment_run.failed", "deployment.created", + // "deployment.updated", "deployment.unpaused", "agent.updated", + // "deployment.archived", "deployment_run.started", "deployment.deleted", + // "deployment_run.succeeded", "environment.created", "environment.updated", + // "environment.archived", "environment.deleted", "memory_store.created", + // "memory_store.archived", "memory_store.deleted", "session.budget_reached". + Type string `json:"type"` + WorkspaceID string `json:"workspace_id"` + SessionThreadID string `json:"session_thread_id"` + VaultID string `json:"vault_id"` + JSON struct { + ID respjson.Field + OrganizationID respjson.Field + Type respjson.Field + WorkspaceID respjson.Field + SessionThreadID respjson.Field + VaultID respjson.Field + raw string + } `json:"-"` +} + +// anyBetaWebhookEventData is implemented by each variant of +// [BetaWebhookEventDataUnion] to add type safety for the return type of +// [BetaWebhookEventDataUnion.AsAny] +type anyBetaWebhookEventData interface { + implBetaWebhookEventDataUnion() +} + +func (BetaWebhookSessionCreatedEventData) implBetaWebhookEventDataUnion() {} +func (BetaWebhookSessionPendingEventData) implBetaWebhookEventDataUnion() {} +func (BetaWebhookSessionRunningEventData) implBetaWebhookEventDataUnion() {} +func (BetaWebhookSessionIdledEventData) implBetaWebhookEventDataUnion() {} +func (BetaWebhookSessionRequiresActionEventData) implBetaWebhookEventDataUnion() {} +func (BetaWebhookSessionArchivedEventData) implBetaWebhookEventDataUnion() {} +func (BetaWebhookSessionDeletedEventData) implBetaWebhookEventDataUnion() {} +func (BetaWebhookSessionStatusRescheduledEventData) implBetaWebhookEventDataUnion() {} +func (BetaWebhookSessionStatusRunStartedEventData) implBetaWebhookEventDataUnion() {} +func (BetaWebhookSessionStatusIdledEventData) implBetaWebhookEventDataUnion() {} +func (BetaWebhookSessionStatusTerminatedEventData) implBetaWebhookEventDataUnion() {} +func (BetaWebhookSessionThreadCreatedEventData) implBetaWebhookEventDataUnion() {} +func (BetaWebhookSessionThreadIdledEventData) implBetaWebhookEventDataUnion() {} +func (BetaWebhookSessionThreadTerminatedEventData) implBetaWebhookEventDataUnion() {} +func (BetaWebhookSessionOutcomeEvaluationEndedEventData) implBetaWebhookEventDataUnion() {} +func (BetaWebhookVaultCreatedEventData) implBetaWebhookEventDataUnion() {} +func (BetaWebhookVaultArchivedEventData) implBetaWebhookEventDataUnion() {} +func (BetaWebhookVaultDeletedEventData) implBetaWebhookEventDataUnion() {} +func (BetaWebhookVaultCredentialCreatedEventData) implBetaWebhookEventDataUnion() {} +func (BetaWebhookVaultCredentialArchivedEventData) implBetaWebhookEventDataUnion() {} +func (BetaWebhookVaultCredentialDeletedEventData) implBetaWebhookEventDataUnion() {} +func (BetaWebhookVaultCredentialRefreshFailedEventData) implBetaWebhookEventDataUnion() {} +func (BetaWebhookSessionUpdatedEventData) implBetaWebhookEventDataUnion() {} +func (BetaWebhookAgentCreatedEventData) implBetaWebhookEventDataUnion() {} +func (BetaWebhookAgentArchivedEventData) implBetaWebhookEventDataUnion() {} +func (BetaWebhookAgentDeletedEventData) implBetaWebhookEventDataUnion() {} +func (BetaWebhookDeploymentPausedEventData) implBetaWebhookEventDataUnion() {} +func (BetaWebhookDeploymentRunFailedEventData) implBetaWebhookEventDataUnion() {} +func (BetaWebhookDeploymentCreatedEventData) implBetaWebhookEventDataUnion() {} +func (BetaWebhookDeploymentUpdatedEventData) implBetaWebhookEventDataUnion() {} +func (BetaWebhookDeploymentUnpausedEventData) implBetaWebhookEventDataUnion() {} +func (BetaWebhookAgentUpdatedEventData) implBetaWebhookEventDataUnion() {} +func (BetaWebhookDeploymentArchivedEventData) implBetaWebhookEventDataUnion() {} +func (BetaWebhookDeploymentRunStartedEventData) implBetaWebhookEventDataUnion() {} +func (BetaWebhookDeploymentDeletedEventData) implBetaWebhookEventDataUnion() {} +func (BetaWebhookDeploymentRunSucceededEventData) implBetaWebhookEventDataUnion() {} +func (BetaWebhookEnvironmentCreatedEventData) implBetaWebhookEventDataUnion() {} +func (BetaWebhookEnvironmentUpdatedEventData) implBetaWebhookEventDataUnion() {} +func (BetaWebhookEnvironmentArchivedEventData) implBetaWebhookEventDataUnion() {} +func (BetaWebhookEnvironmentDeletedEventData) implBetaWebhookEventDataUnion() {} +func (BetaWebhookMemoryStoreCreatedEventData) implBetaWebhookEventDataUnion() {} +func (BetaWebhookMemoryStoreArchivedEventData) implBetaWebhookEventDataUnion() {} +func (BetaWebhookMemoryStoreDeletedEventData) implBetaWebhookEventDataUnion() {} +func (BetaWebhookSessionBudgetReachedEventData) implBetaWebhookEventDataUnion() {} + +// Use the following switch statement to find the correct variant +// +// switch variant := BetaWebhookEventDataUnion.AsAny().(type) { +// case anthropic.BetaWebhookSessionCreatedEventData: +// case anthropic.BetaWebhookSessionPendingEventData: +// case anthropic.BetaWebhookSessionRunningEventData: +// case anthropic.BetaWebhookSessionIdledEventData: +// case anthropic.BetaWebhookSessionRequiresActionEventData: +// case anthropic.BetaWebhookSessionArchivedEventData: +// case anthropic.BetaWebhookSessionDeletedEventData: +// case anthropic.BetaWebhookSessionStatusRescheduledEventData: +// case anthropic.BetaWebhookSessionStatusRunStartedEventData: +// case anthropic.BetaWebhookSessionStatusIdledEventData: +// case anthropic.BetaWebhookSessionStatusTerminatedEventData: +// case anthropic.BetaWebhookSessionThreadCreatedEventData: +// case anthropic.BetaWebhookSessionThreadIdledEventData: +// case anthropic.BetaWebhookSessionThreadTerminatedEventData: +// case anthropic.BetaWebhookSessionOutcomeEvaluationEndedEventData: +// case anthropic.BetaWebhookVaultCreatedEventData: +// case anthropic.BetaWebhookVaultArchivedEventData: +// case anthropic.BetaWebhookVaultDeletedEventData: +// case anthropic.BetaWebhookVaultCredentialCreatedEventData: +// case anthropic.BetaWebhookVaultCredentialArchivedEventData: +// case anthropic.BetaWebhookVaultCredentialDeletedEventData: +// case anthropic.BetaWebhookVaultCredentialRefreshFailedEventData: +// case anthropic.BetaWebhookSessionUpdatedEventData: +// case anthropic.BetaWebhookAgentCreatedEventData: +// case anthropic.BetaWebhookAgentArchivedEventData: +// case anthropic.BetaWebhookAgentDeletedEventData: +// case anthropic.BetaWebhookDeploymentPausedEventData: +// case anthropic.BetaWebhookDeploymentRunFailedEventData: +// case anthropic.BetaWebhookDeploymentCreatedEventData: +// case anthropic.BetaWebhookDeploymentUpdatedEventData: +// case anthropic.BetaWebhookDeploymentUnpausedEventData: +// case anthropic.BetaWebhookAgentUpdatedEventData: +// case anthropic.BetaWebhookDeploymentArchivedEventData: +// case anthropic.BetaWebhookDeploymentRunStartedEventData: +// case anthropic.BetaWebhookDeploymentDeletedEventData: +// case anthropic.BetaWebhookDeploymentRunSucceededEventData: +// case anthropic.BetaWebhookEnvironmentCreatedEventData: +// case anthropic.BetaWebhookEnvironmentUpdatedEventData: +// case anthropic.BetaWebhookEnvironmentArchivedEventData: +// case anthropic.BetaWebhookEnvironmentDeletedEventData: +// case anthropic.BetaWebhookMemoryStoreCreatedEventData: +// case anthropic.BetaWebhookMemoryStoreArchivedEventData: +// case anthropic.BetaWebhookMemoryStoreDeletedEventData: +// case anthropic.BetaWebhookSessionBudgetReachedEventData: +// default: +// fmt.Errorf("no variant present") +// } +func (u BetaWebhookEventDataUnion) AsAny() anyBetaWebhookEventData { + switch u.Type { + case "session.created": + return u.AsSessionCreated() + case "session.pending": + return u.AsSessionPending() + case "session.running": + return u.AsSessionRunning() + case "session.idled": + return u.AsSessionIdled() + case "session.requires_action": + return u.AsSessionRequiresAction() + case "session.archived": + return u.AsSessionArchived() + case "session.deleted": + return u.AsSessionDeleted() + case "session.status_rescheduled": + return u.AsSessionStatusRescheduled() + case "session.status_run_started": + return u.AsSessionStatusRunStarted() + case "session.status_idled": + return u.AsSessionStatusIdled() + case "session.status_terminated": + return u.AsSessionStatusTerminated() + case "session.thread_created": + return u.AsSessionThreadCreated() + case "session.thread_idled": + return u.AsSessionThreadIdled() + case "session.thread_terminated": + return u.AsSessionThreadTerminated() + case "session.outcome_evaluation_ended": + return u.AsSessionOutcomeEvaluationEnded() + case "vault.created": + return u.AsVaultCreated() + case "vault.archived": + return u.AsVaultArchived() + case "vault.deleted": + return u.AsVaultDeleted() + case "vault_credential.created": + return u.AsVaultCredentialCreated() + case "vault_credential.archived": + return u.AsVaultCredentialArchived() + case "vault_credential.deleted": + return u.AsVaultCredentialDeleted() + case "vault_credential.refresh_failed": + return u.AsVaultCredentialRefreshFailed() + case "session.updated": + return u.AsSessionUpdated() + case "agent.created": + return u.AsAgentCreated() + case "agent.archived": + return u.AsAgentArchived() + case "agent.deleted": + return u.AsAgentDeleted() + case "deployment.paused": + return u.AsDeploymentPaused() + case "deployment_run.failed": + return u.AsDeploymentRunFailed() + case "deployment.created": + return u.AsDeploymentCreated() + case "deployment.updated": + return u.AsDeploymentUpdated() + case "deployment.unpaused": + return u.AsDeploymentUnpaused() + case "agent.updated": + return u.AsAgentUpdated() + case "deployment.archived": + return u.AsDeploymentArchived() + case "deployment_run.started": + return u.AsDeploymentRunStarted() + case "deployment.deleted": + return u.AsDeploymentDeleted() + case "deployment_run.succeeded": + return u.AsDeploymentRunSucceeded() + case "environment.created": + return u.AsEnvironmentCreated() + case "environment.updated": + return u.AsEnvironmentUpdated() + case "environment.archived": + return u.AsEnvironmentArchived() + case "environment.deleted": + return u.AsEnvironmentDeleted() + case "memory_store.created": + return u.AsMemoryStoreCreated() + case "memory_store.archived": + return u.AsMemoryStoreArchived() + case "memory_store.deleted": + return u.AsMemoryStoreDeleted() + case "session.budget_reached": + return u.AsSessionBudgetReached() + } + return nil +} + +func (u BetaWebhookEventDataUnion) AsSessionCreated() (v BetaWebhookSessionCreatedEventData) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaWebhookEventDataUnion) AsSessionPending() (v BetaWebhookSessionPendingEventData) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaWebhookEventDataUnion) AsSessionRunning() (v BetaWebhookSessionRunningEventData) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaWebhookEventDataUnion) AsSessionIdled() (v BetaWebhookSessionIdledEventData) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaWebhookEventDataUnion) AsSessionRequiresAction() (v BetaWebhookSessionRequiresActionEventData) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaWebhookEventDataUnion) AsSessionArchived() (v BetaWebhookSessionArchivedEventData) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaWebhookEventDataUnion) AsSessionDeleted() (v BetaWebhookSessionDeletedEventData) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaWebhookEventDataUnion) AsSessionStatusRescheduled() (v BetaWebhookSessionStatusRescheduledEventData) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaWebhookEventDataUnion) AsSessionStatusRunStarted() (v BetaWebhookSessionStatusRunStartedEventData) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaWebhookEventDataUnion) AsSessionStatusIdled() (v BetaWebhookSessionStatusIdledEventData) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaWebhookEventDataUnion) AsSessionStatusTerminated() (v BetaWebhookSessionStatusTerminatedEventData) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaWebhookEventDataUnion) AsSessionThreadCreated() (v BetaWebhookSessionThreadCreatedEventData) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaWebhookEventDataUnion) AsSessionThreadIdled() (v BetaWebhookSessionThreadIdledEventData) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaWebhookEventDataUnion) AsSessionThreadTerminated() (v BetaWebhookSessionThreadTerminatedEventData) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaWebhookEventDataUnion) AsSessionOutcomeEvaluationEnded() (v BetaWebhookSessionOutcomeEvaluationEndedEventData) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaWebhookEventDataUnion) AsVaultCreated() (v BetaWebhookVaultCreatedEventData) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaWebhookEventDataUnion) AsVaultArchived() (v BetaWebhookVaultArchivedEventData) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaWebhookEventDataUnion) AsVaultDeleted() (v BetaWebhookVaultDeletedEventData) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaWebhookEventDataUnion) AsVaultCredentialCreated() (v BetaWebhookVaultCredentialCreatedEventData) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaWebhookEventDataUnion) AsVaultCredentialArchived() (v BetaWebhookVaultCredentialArchivedEventData) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaWebhookEventDataUnion) AsVaultCredentialDeleted() (v BetaWebhookVaultCredentialDeletedEventData) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaWebhookEventDataUnion) AsVaultCredentialRefreshFailed() (v BetaWebhookVaultCredentialRefreshFailedEventData) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaWebhookEventDataUnion) AsSessionUpdated() (v BetaWebhookSessionUpdatedEventData) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaWebhookEventDataUnion) AsAgentCreated() (v BetaWebhookAgentCreatedEventData) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaWebhookEventDataUnion) AsAgentArchived() (v BetaWebhookAgentArchivedEventData) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaWebhookEventDataUnion) AsAgentDeleted() (v BetaWebhookAgentDeletedEventData) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaWebhookEventDataUnion) AsDeploymentPaused() (v BetaWebhookDeploymentPausedEventData) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaWebhookEventDataUnion) AsDeploymentRunFailed() (v BetaWebhookDeploymentRunFailedEventData) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaWebhookEventDataUnion) AsDeploymentCreated() (v BetaWebhookDeploymentCreatedEventData) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaWebhookEventDataUnion) AsDeploymentUpdated() (v BetaWebhookDeploymentUpdatedEventData) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaWebhookEventDataUnion) AsDeploymentUnpaused() (v BetaWebhookDeploymentUnpausedEventData) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaWebhookEventDataUnion) AsAgentUpdated() (v BetaWebhookAgentUpdatedEventData) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaWebhookEventDataUnion) AsDeploymentArchived() (v BetaWebhookDeploymentArchivedEventData) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaWebhookEventDataUnion) AsDeploymentRunStarted() (v BetaWebhookDeploymentRunStartedEventData) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaWebhookEventDataUnion) AsDeploymentDeleted() (v BetaWebhookDeploymentDeletedEventData) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaWebhookEventDataUnion) AsDeploymentRunSucceeded() (v BetaWebhookDeploymentRunSucceededEventData) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaWebhookEventDataUnion) AsEnvironmentCreated() (v BetaWebhookEnvironmentCreatedEventData) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaWebhookEventDataUnion) AsEnvironmentUpdated() (v BetaWebhookEnvironmentUpdatedEventData) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaWebhookEventDataUnion) AsEnvironmentArchived() (v BetaWebhookEnvironmentArchivedEventData) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaWebhookEventDataUnion) AsEnvironmentDeleted() (v BetaWebhookEnvironmentDeletedEventData) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaWebhookEventDataUnion) AsMemoryStoreCreated() (v BetaWebhookMemoryStoreCreatedEventData) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaWebhookEventDataUnion) AsMemoryStoreArchived() (v BetaWebhookMemoryStoreArchivedEventData) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaWebhookEventDataUnion) AsMemoryStoreDeleted() (v BetaWebhookMemoryStoreDeletedEventData) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u BetaWebhookEventDataUnion) AsSessionBudgetReached() (v BetaWebhookSessionBudgetReachedEventData) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u BetaWebhookEventDataUnion) RawJSON() string { return u.JSON.raw } + +func (r *BetaWebhookEventDataUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaWebhookMemoryStoreArchivedEventData struct { + // ID of the memory store that triggered the event. + ID string `json:"id" api:"required"` + OrganizationID string `json:"organization_id" api:"required"` + Type constant.MemoryStoreArchived `json:"type" default:"memory_store.archived"` + WorkspaceID string `json:"workspace_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + OrganizationID respjson.Field + Type respjson.Field + WorkspaceID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaWebhookMemoryStoreArchivedEventData) RawJSON() string { return r.JSON.raw } +func (r *BetaWebhookMemoryStoreArchivedEventData) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaWebhookMemoryStoreCreatedEventData struct { + // ID of the memory store that triggered the event. + ID string `json:"id" api:"required"` + OrganizationID string `json:"organization_id" api:"required"` + Type constant.MemoryStoreCreated `json:"type" default:"memory_store.created"` + WorkspaceID string `json:"workspace_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + OrganizationID respjson.Field + Type respjson.Field + WorkspaceID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaWebhookMemoryStoreCreatedEventData) RawJSON() string { return r.JSON.raw } +func (r *BetaWebhookMemoryStoreCreatedEventData) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaWebhookMemoryStoreDeletedEventData struct { + // ID of the memory store that triggered the event. + ID string `json:"id" api:"required"` + OrganizationID string `json:"organization_id" api:"required"` + Type constant.MemoryStoreDeleted `json:"type" default:"memory_store.deleted"` + WorkspaceID string `json:"workspace_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + OrganizationID respjson.Field + Type respjson.Field + WorkspaceID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaWebhookMemoryStoreDeletedEventData) RawJSON() string { return r.JSON.raw } +func (r *BetaWebhookMemoryStoreDeletedEventData) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaWebhookSessionArchivedEventData struct { + // ID of the session that triggered the event. + ID string `json:"id" api:"required"` + OrganizationID string `json:"organization_id" api:"required"` + Type constant.SessionArchived `json:"type" default:"session.archived"` + WorkspaceID string `json:"workspace_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + OrganizationID respjson.Field + Type respjson.Field + WorkspaceID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaWebhookSessionArchivedEventData) RawJSON() string { return r.JSON.raw } +func (r *BetaWebhookSessionArchivedEventData) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaWebhookSessionBudgetReachedEventData struct { + // ID of the session that triggered the event. + ID string `json:"id" api:"required"` + OrganizationID string `json:"organization_id" api:"required"` + Type constant.SessionBudgetReached `json:"type" default:"session.budget_reached"` + WorkspaceID string `json:"workspace_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + OrganizationID respjson.Field + Type respjson.Field + WorkspaceID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaWebhookSessionBudgetReachedEventData) RawJSON() string { return r.JSON.raw } +func (r *BetaWebhookSessionBudgetReachedEventData) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaWebhookSessionCreatedEventData struct { + // ID of the session that triggered the event. + ID string `json:"id" api:"required"` + OrganizationID string `json:"organization_id" api:"required"` + Type constant.SessionCreated `json:"type" default:"session.created"` + WorkspaceID string `json:"workspace_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + OrganizationID respjson.Field + Type respjson.Field + WorkspaceID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaWebhookSessionCreatedEventData) RawJSON() string { return r.JSON.raw } +func (r *BetaWebhookSessionCreatedEventData) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaWebhookSessionDeletedEventData struct { + // ID of the session that triggered the event. + ID string `json:"id" api:"required"` + OrganizationID string `json:"organization_id" api:"required"` + Type constant.SessionDeleted `json:"type" default:"session.deleted"` + WorkspaceID string `json:"workspace_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + OrganizationID respjson.Field + Type respjson.Field + WorkspaceID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaWebhookSessionDeletedEventData) RawJSON() string { return r.JSON.raw } +func (r *BetaWebhookSessionDeletedEventData) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaWebhookSessionIdledEventData struct { + // ID of the session that triggered the event. + ID string `json:"id" api:"required"` + OrganizationID string `json:"organization_id" api:"required"` + Type constant.SessionIdled `json:"type" default:"session.idled"` + WorkspaceID string `json:"workspace_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + OrganizationID respjson.Field + Type respjson.Field + WorkspaceID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaWebhookSessionIdledEventData) RawJSON() string { return r.JSON.raw } +func (r *BetaWebhookSessionIdledEventData) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaWebhookSessionOutcomeEvaluationEndedEventData struct { + // ID of the session that triggered the event. + ID string `json:"id" api:"required"` + OrganizationID string `json:"organization_id" api:"required"` + Type constant.SessionOutcomeEvaluationEnded `json:"type" default:"session.outcome_evaluation_ended"` + WorkspaceID string `json:"workspace_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + OrganizationID respjson.Field + Type respjson.Field + WorkspaceID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaWebhookSessionOutcomeEvaluationEndedEventData) RawJSON() string { return r.JSON.raw } +func (r *BetaWebhookSessionOutcomeEvaluationEndedEventData) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaWebhookSessionPendingEventData struct { + // ID of the session that triggered the event. + ID string `json:"id" api:"required"` + OrganizationID string `json:"organization_id" api:"required"` + Type constant.SessionPending `json:"type" default:"session.pending"` + WorkspaceID string `json:"workspace_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + OrganizationID respjson.Field + Type respjson.Field + WorkspaceID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaWebhookSessionPendingEventData) RawJSON() string { return r.JSON.raw } +func (r *BetaWebhookSessionPendingEventData) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaWebhookSessionRequiresActionEventData struct { + // ID of the session that triggered the event. + ID string `json:"id" api:"required"` + OrganizationID string `json:"organization_id" api:"required"` + Type constant.SessionRequiresAction `json:"type" default:"session.requires_action"` + WorkspaceID string `json:"workspace_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + OrganizationID respjson.Field + Type respjson.Field + WorkspaceID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaWebhookSessionRequiresActionEventData) RawJSON() string { return r.JSON.raw } +func (r *BetaWebhookSessionRequiresActionEventData) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaWebhookSessionRunningEventData struct { + // ID of the session that triggered the event. + ID string `json:"id" api:"required"` + OrganizationID string `json:"organization_id" api:"required"` + Type constant.SessionRunning `json:"type" default:"session.running"` + WorkspaceID string `json:"workspace_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + OrganizationID respjson.Field + Type respjson.Field + WorkspaceID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaWebhookSessionRunningEventData) RawJSON() string { return r.JSON.raw } +func (r *BetaWebhookSessionRunningEventData) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaWebhookSessionStatusIdledEventData struct { + // ID of the session that triggered the event. + ID string `json:"id" api:"required"` + OrganizationID string `json:"organization_id" api:"required"` + Type constant.SessionStatusIdled `json:"type" default:"session.status_idled"` + WorkspaceID string `json:"workspace_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + OrganizationID respjson.Field + Type respjson.Field + WorkspaceID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaWebhookSessionStatusIdledEventData) RawJSON() string { return r.JSON.raw } +func (r *BetaWebhookSessionStatusIdledEventData) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaWebhookSessionStatusRescheduledEventData struct { + // ID of the session that triggered the event. + ID string `json:"id" api:"required"` + OrganizationID string `json:"organization_id" api:"required"` + Type constant.SessionStatusRescheduled `json:"type" default:"session.status_rescheduled"` + WorkspaceID string `json:"workspace_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + OrganizationID respjson.Field + Type respjson.Field + WorkspaceID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaWebhookSessionStatusRescheduledEventData) RawJSON() string { return r.JSON.raw } +func (r *BetaWebhookSessionStatusRescheduledEventData) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaWebhookSessionStatusRunStartedEventData struct { + // ID of the session that triggered the event. + ID string `json:"id" api:"required"` + OrganizationID string `json:"organization_id" api:"required"` + Type constant.SessionStatusRunStarted `json:"type" default:"session.status_run_started"` + WorkspaceID string `json:"workspace_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + OrganizationID respjson.Field + Type respjson.Field + WorkspaceID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaWebhookSessionStatusRunStartedEventData) RawJSON() string { return r.JSON.raw } +func (r *BetaWebhookSessionStatusRunStartedEventData) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaWebhookSessionStatusTerminatedEventData struct { + // ID of the session that triggered the event. + ID string `json:"id" api:"required"` + OrganizationID string `json:"organization_id" api:"required"` + Type constant.SessionStatusTerminated `json:"type" default:"session.status_terminated"` + WorkspaceID string `json:"workspace_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + OrganizationID respjson.Field + Type respjson.Field + WorkspaceID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaWebhookSessionStatusTerminatedEventData) RawJSON() string { return r.JSON.raw } +func (r *BetaWebhookSessionStatusTerminatedEventData) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaWebhookSessionThreadCreatedEventData struct { + // ID of the session that triggered the event. + ID string `json:"id" api:"required"` + OrganizationID string `json:"organization_id" api:"required"` + // ID of the session thread this event refers to. + SessionThreadID string `json:"session_thread_id" api:"required"` + Type constant.SessionThreadCreated `json:"type" default:"session.thread_created"` + WorkspaceID string `json:"workspace_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + OrganizationID respjson.Field + SessionThreadID respjson.Field + Type respjson.Field + WorkspaceID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaWebhookSessionThreadCreatedEventData) RawJSON() string { return r.JSON.raw } +func (r *BetaWebhookSessionThreadCreatedEventData) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaWebhookSessionThreadIdledEventData struct { + // ID of the session that triggered the event. + ID string `json:"id" api:"required"` + OrganizationID string `json:"organization_id" api:"required"` + // ID of the session thread this event refers to. + SessionThreadID string `json:"session_thread_id" api:"required"` + Type constant.SessionThreadIdled `json:"type" default:"session.thread_idled"` + WorkspaceID string `json:"workspace_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + OrganizationID respjson.Field + SessionThreadID respjson.Field + Type respjson.Field + WorkspaceID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaWebhookSessionThreadIdledEventData) RawJSON() string { return r.JSON.raw } +func (r *BetaWebhookSessionThreadIdledEventData) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaWebhookSessionThreadTerminatedEventData struct { + // ID of the session that triggered the event. + ID string `json:"id" api:"required"` + OrganizationID string `json:"organization_id" api:"required"` + // ID of the session thread this event refers to. + SessionThreadID string `json:"session_thread_id" api:"required"` + Type constant.SessionThreadTerminated `json:"type" default:"session.thread_terminated"` + WorkspaceID string `json:"workspace_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + OrganizationID respjson.Field + SessionThreadID respjson.Field + Type respjson.Field + WorkspaceID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaWebhookSessionThreadTerminatedEventData) RawJSON() string { return r.JSON.raw } +func (r *BetaWebhookSessionThreadTerminatedEventData) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaWebhookSessionUpdatedEventData struct { + // ID of the session that triggered the event. + ID string `json:"id" api:"required"` + OrganizationID string `json:"organization_id" api:"required"` + Type constant.SessionUpdated `json:"type" default:"session.updated"` + WorkspaceID string `json:"workspace_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + OrganizationID respjson.Field + Type respjson.Field + WorkspaceID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaWebhookSessionUpdatedEventData) RawJSON() string { return r.JSON.raw } +func (r *BetaWebhookSessionUpdatedEventData) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaWebhookVaultArchivedEventData struct { + // ID of the vault that triggered the event. + ID string `json:"id" api:"required"` + OrganizationID string `json:"organization_id" api:"required"` + Type constant.VaultArchived `json:"type" default:"vault.archived"` + WorkspaceID string `json:"workspace_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + OrganizationID respjson.Field + Type respjson.Field + WorkspaceID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaWebhookVaultArchivedEventData) RawJSON() string { return r.JSON.raw } +func (r *BetaWebhookVaultArchivedEventData) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaWebhookVaultCreatedEventData struct { + // ID of the vault that triggered the event. + ID string `json:"id" api:"required"` + OrganizationID string `json:"organization_id" api:"required"` + Type constant.VaultCreated `json:"type" default:"vault.created"` + WorkspaceID string `json:"workspace_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + OrganizationID respjson.Field + Type respjson.Field + WorkspaceID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaWebhookVaultCreatedEventData) RawJSON() string { return r.JSON.raw } +func (r *BetaWebhookVaultCreatedEventData) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaWebhookVaultCredentialArchivedEventData struct { + // ID of the vault credential that triggered the event. + ID string `json:"id" api:"required"` + OrganizationID string `json:"organization_id" api:"required"` + Type constant.VaultCredentialArchived `json:"type" default:"vault_credential.archived"` + // ID of the vault that owns this credential. + VaultID string `json:"vault_id" api:"required"` + WorkspaceID string `json:"workspace_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + OrganizationID respjson.Field + Type respjson.Field + VaultID respjson.Field + WorkspaceID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaWebhookVaultCredentialArchivedEventData) RawJSON() string { return r.JSON.raw } +func (r *BetaWebhookVaultCredentialArchivedEventData) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaWebhookVaultCredentialCreatedEventData struct { + // ID of the vault credential that triggered the event. + ID string `json:"id" api:"required"` + OrganizationID string `json:"organization_id" api:"required"` + Type constant.VaultCredentialCreated `json:"type" default:"vault_credential.created"` + // ID of the vault that owns this credential. + VaultID string `json:"vault_id" api:"required"` + WorkspaceID string `json:"workspace_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + OrganizationID respjson.Field + Type respjson.Field + VaultID respjson.Field + WorkspaceID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaWebhookVaultCredentialCreatedEventData) RawJSON() string { return r.JSON.raw } +func (r *BetaWebhookVaultCredentialCreatedEventData) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaWebhookVaultCredentialDeletedEventData struct { + // ID of the vault credential that triggered the event. + ID string `json:"id" api:"required"` + OrganizationID string `json:"organization_id" api:"required"` + Type constant.VaultCredentialDeleted `json:"type" default:"vault_credential.deleted"` + // ID of the vault that owns this credential. + VaultID string `json:"vault_id" api:"required"` + WorkspaceID string `json:"workspace_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + OrganizationID respjson.Field + Type respjson.Field + VaultID respjson.Field + WorkspaceID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaWebhookVaultCredentialDeletedEventData) RawJSON() string { return r.JSON.raw } +func (r *BetaWebhookVaultCredentialDeletedEventData) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaWebhookVaultCredentialRefreshFailedEventData struct { + // ID of the vault credential that triggered the event. + ID string `json:"id" api:"required"` + OrganizationID string `json:"organization_id" api:"required"` + Type constant.VaultCredentialRefreshFailed `json:"type" default:"vault_credential.refresh_failed"` + // ID of the vault that owns this credential. + VaultID string `json:"vault_id" api:"required"` + WorkspaceID string `json:"workspace_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + OrganizationID respjson.Field + Type respjson.Field + VaultID respjson.Field + WorkspaceID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaWebhookVaultCredentialRefreshFailedEventData) RawJSON() string { return r.JSON.raw } +func (r *BetaWebhookVaultCredentialRefreshFailedEventData) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type BetaWebhookVaultDeletedEventData struct { + // ID of the vault that triggered the event. + ID string `json:"id" api:"required"` + OrganizationID string `json:"organization_id" api:"required"` + Type constant.VaultDeleted `json:"type" default:"vault.deleted"` + WorkspaceID string `json:"workspace_id" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + OrganizationID respjson.Field + Type respjson.Field + WorkspaceID respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r BetaWebhookVaultDeletedEventData) RawJSON() string { return r.JSON.raw } +func (r *BetaWebhookVaultDeletedEventData) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type UnwrapWebhookEvent struct { + // Unique event identifier for idempotency. + ID string `json:"id" api:"required"` + // RFC 3339 timestamp when the event occurred. + CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"` + Data BetaWebhookEventDataUnion `json:"data" api:"required"` + // Object type. Always `event` for webhook payloads. + Type constant.Event `json:"type" default:"event"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + CreatedAt respjson.Field + Data respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r UnwrapWebhookEvent) RawJSON() string { return r.JSON.raw } +func (r *UnwrapWebhookEvent) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/client.go b/vendor/github.com/anthropics/anthropic-sdk-go/client.go index 3755f4a04..74c4da8aa 100644 --- a/vendor/github.com/anthropics/anthropic-sdk-go/client.go +++ b/vendor/github.com/anthropics/anthropic-sdk-go/client.go @@ -4,12 +4,16 @@ package anthropic import ( "context" + "errors" "fmt" "net/http" "os" "slices" + "strings" "time" + "github.com/anthropics/anthropic-sdk-go/config" + "github.com/anthropics/anthropic-sdk-go/internal/auth" "github.com/anthropics/anthropic-sdk-go/internal/requestconfig" "github.com/anthropics/anthropic-sdk-go/option" "github.com/anthropics/anthropic-sdk-go/shared/constant" @@ -23,38 +27,201 @@ type Client struct { Completions CompletionService Messages MessageService Models ModelService + Files FileService + Skills SkillService Beta BetaService } -// DefaultClientOptions read from the environment (ANTHROPIC_API_KEY, -// ANTHROPIC_AUTH_TOKEN, ANTHROPIC_BASE_URL). This should be used to initialize new -// clients. +// DefaultClientOptions walks the default credential chain per the +// cross-SDK credential precedence spec: +// +// 1. ANTHROPIC_API_KEY +// 2. ANTHROPIC_AUTH_TOKEN +// 3. Explicit profile via ANTHROPIC_PROFILE (surfaces the error if the +// named profile is missing — the user explicitly selected it) +// 4. Env-var federation (ANTHROPIC_FEDERATION_RULE_ID + +// ANTHROPIC_ORGANIZATION_ID + ANTHROPIC_IDENTITY_TOKEN_FILE / _TOKEN) +// 5. Fallback profile (active_config file or literal "default" — a +// quiet miss when absent, so a WIF-configured machine with a +// leftover default profile still uses WIF) +// +// When no source produces a credential, the first request fails with an +// [auth.NoCredentialsError]. If ANTHROPIC_PROFILE points at a missing or +// invalid profile, the first request instead fails with a wrapped +// profile-load error naming the profile. An explicit credential option +// passed to [NewClient] (e.g. [option.WithAPIKey] or [option.WithAuthToken]) +// suppresses both paths. Also honors ANTHROPIC_BASE_URL. func DefaultClientOptions() []option.RequestOption { - defaults := []option.RequestOption{option.WithEnvironmentProduction()} + defaults := []option.RequestOption{ + option.WithHTTPClient(defaultHTTPClient()), + option.WithEnvironmentProduction(), + } if o, ok := os.LookupEnv("ANTHROPIC_BASE_URL"); ok { defaults = append(defaults, option.WithBaseURL(o)) } - if o, ok := os.LookupEnv("ANTHROPIC_API_KEY"); ok { - defaults = append(defaults, option.WithAPIKey(o)) + + statuses := []auth.CredentialSourceStatus{} + + if v, ok := os.LookupEnv("ANTHROPIC_API_KEY"); ok && v != "" { + defaults = append(defaults, option.WithAPIKey(v)) + return defaults + } + statuses = append(statuses, auth.CredentialSourceStatus{ + Name: "ANTHROPIC_API_KEY env var", + State: auth.CredentialSourceNotSet, + }) + + if v, ok := os.LookupEnv("ANTHROPIC_AUTH_TOKEN"); ok && v != "" { + defaults = append(defaults, option.WithAuthToken(v)) + return defaults + } + statuses = append(statuses, auth.CredentialSourceStatus{ + Name: "ANTHROPIC_AUTH_TOKEN env var", + State: auth.CredentialSourceNotSet, + }) + + // Step 3: explicit profile via ANTHROPIC_PROFILE. The user named a + // specific profile, so a load failure is surfaced immediately — do + // not fall through to env federation or the fallback profile. + if profile, ok := os.LookupEnv("ANTHROPIC_PROFILE"); ok && profile != "" { + cfg, err := config.LoadProfile(config.DefaultDir(), profile) + if err != nil { + return append(defaults, explicitProfileErrorOption(profile, err)) + } + return append(defaults, option.WithConfig(cfg)) + } + + // Step 4: env-var federation. Beats the fallback profile so a + // WIF-configured machine with a leftover default profile file still + // uses WIF. + envResult, envDetail, envState := auth.EnvCredentials() + if envResult != nil { + defaults = append(defaults, auth.WithAuthMiddleware(envResult.Provider)) + return defaults + } + envFederationStatus := auth.CredentialSourceStatus{ + Name: "env federation (ANTHROPIC_FEDERATION_RULE_ID + ANTHROPIC_ORGANIZATION_ID + ANTHROPIC_IDENTITY_TOKEN_FILE)", + State: envState, + Detail: envDetail, + } + + // Step 5: fallback profile (active_config or literal "default"). A + // missing profile here is a quiet miss — fall through to the no- + // credentials aggregate. + fallbackStatus, fallbackOpt := tryLoadFallbackProfile() + if fallbackOpt != nil { + return append(defaults, fallbackOpt) + } + if o, ok := os.LookupEnv("ANTHROPIC_WEBHOOK_SIGNING_KEY"); ok { + defaults = append(defaults, option.WithWebhookKey(o)) } - if o, ok := os.LookupEnv("ANTHROPIC_AUTH_TOKEN"); ok { - defaults = append(defaults, option.WithAuthToken(o)) + if o, ok := os.LookupEnv("ANTHROPIC_CUSTOM_HEADERS"); ok { + for _, line := range strings.Split(o, "\n") { + colon := strings.Index(line, ":") + if colon >= 0 { + defaults = append(defaults, option.WithHeader(strings.TrimSpace(line[:colon]), strings.TrimSpace(line[colon+1:]))) + } + } } + + statuses = append(statuses, envFederationStatus, fallbackStatus) + defaults = append(defaults, noCredentialsSentinel(statuses)) return defaults } +// tryLoadFallbackProfile attempts the step-5 fallback profile lookup: +// active_config file, otherwise literal "default". A missing profile is +// reported as a silent-miss status (the caller will fall through to the +// no-credentials aggregate); any other load error is reported as a +// load-failure status so the user sees the specific OS error. +func tryLoadFallbackProfile() (auth.CredentialSourceStatus, option.RequestOption) { + cfg, err := config.LoadConfig() + if err != nil { + if errors.Is(err, os.ErrNotExist) { + return auth.CredentialSourceStatus{ + Name: "profile config file", + State: auth.CredentialSourceNotFound, + Detail: "run `ant auth login` to create one", + }, nil + } + return auth.CredentialSourceStatus{ + Name: "profile config file", + State: auth.CredentialSourceLoadFailed, + Detail: err.Error(), + }, nil + } + return auth.CredentialSourceStatus{Name: "profile config file"}, option.WithConfig(cfg) +} + +// explicitProfileErrorOption installs a middleware that fails the request +// with the underlying load error, unless a caller-supplied credential +// option preempts the profile. Used when ANTHROPIC_PROFILE names a profile +// whose config file cannot be loaded. +func explicitProfileErrorOption(profile string, loadErr error) option.RequestOption { + profileErr := fmt.Errorf("ANTHROPIC_PROFILE=%q: %w", profile, loadErr) + return requestconfig.RequestOptionFunc(func(r *requestconfig.RequestConfig) error { + cfg := r + check := func(req *http.Request, next func(*http.Request) (*http.Response, error)) (*http.Response, error) { + if cfg.APIKey != "" || cfg.AuthToken != "" { + return next(req) + } + if req.Header.Get("Authorization") != "" || req.Header.Get("X-Api-Key") != "" { + return next(req) + } + return nil, profileErr + } + r.Middlewares = append(r.Middlewares, check) + return nil + }) +} + +func noCredentialsSentinel(statuses []auth.CredentialSourceStatus) option.RequestOption { + preBuiltErr := &auth.NoCredentialsError{Sources: statuses} + return requestconfig.RequestOptionFunc(func(r *requestconfig.RequestConfig) error { + cfg := r + check := func(req *http.Request, next func(*http.Request) (*http.Response, error)) (*http.Response, error) { + if cfg.APIKey != "" || cfg.AuthToken != "" { + return next(req) + } + if len(cfg.Middlewares) > 1 { + return next(req) + } + if req.Header.Get("Authorization") != "" || req.Header.Get("X-Api-Key") != "" { + return next(req) + } + return nil, preBuiltErr + } + r.Middlewares = append(r.Middlewares, check) + return nil + }) +} + // NewClient generates a new client with the default option read from the -// environment (ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN, ANTHROPIC_BASE_URL). The -// option passed in as arguments are applied after these default arguments, and all -// option will be passed down to the services and requests that this client makes. +// environment (ANTHROPIC_API_KEY, ANTHROPIC_WEBHOOK_SIGNING_KEY, ANTHROPIC_AUTH_TOKEN, +// ANTHROPIC_BASE_URL). The option passed in as arguments are applied after these +// default arguments, and all option will be passed down to the services and requests +// that this client makes. +// +// Pass [option.WithoutEnvironmentDefaults] to skip the environment-based +// credential autoload entirely (only the hardcoded production base-URL +// default is kept). Use this when the caller does its own credential +// resolution and wants the SDK to contribute nothing from the environment. func NewClient(opts ...option.RequestOption) (r Client) { - opts = append(DefaultClientOptions(), opts...) + var defaults []option.RequestOption + if option.HasWithoutEnvironmentDefaults(opts) { + defaults = []option.RequestOption{option.WithEnvironmentProduction()} + } else { + defaults = DefaultClientOptions() + } + opts = append(defaults, opts...) r = Client{Options: opts} r.Completions = NewCompletionService(opts...) r.Messages = NewMessageService(opts...) r.Models = NewModelService(opts...) + r.Files = NewFileService(opts...) + r.Skills = NewSkillService(opts...) r.Beta = NewBetaService(opts...) return diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/completion.go b/vendor/github.com/anthropics/anthropic-sdk-go/completion.go index 9bbb9269c..443669d35 100644 --- a/vendor/github.com/anthropics/anthropic-sdk-go/completion.go +++ b/vendor/github.com/anthropics/anthropic-sdk-go/completion.go @@ -39,10 +39,10 @@ func NewCompletionService(opts ...option.RequestOption) (r CompletionService) { // [Legacy] Create a Text Completion. // // The Text Completions API is a legacy API. We recommend using the -// [Messages API](https://docs.claude.com/en/api/messages) going forward. +// [Messages API](https://platform.claude.com/docs/en/api/messages) going forward. // // Future models and features will not be compatible with Text Completions. See our -// [migration guide](https://docs.claude.com/en/api/migrating-from-text-completions-to-messages) +// [migration guide](https://platform.claude.com/docs/en/build-with-claude/working-with-messages) // for guidance in migrating from Text Completions to Messages. // // Note: If you choose to set a timeout for this request, we recommend 10 minutes. @@ -59,10 +59,10 @@ func (r *CompletionService) New(ctx context.Context, params CompletionNewParams, // [Legacy] Create a Text Completion. // // The Text Completions API is a legacy API. We recommend using the -// [Messages API](https://docs.claude.com/en/api/messages) going forward. +// [Messages API](https://platform.claude.com/docs/en/api/messages) going forward. // // Future models and features will not be compatible with Text Completions. See our -// [migration guide](https://docs.claude.com/en/api/migrating-from-text-completions-to-messages) +// [migration guide](https://platform.claude.com/docs/en/build-with-claude/working-with-messages) // for guidance in migrating from Text Completions to Messages. // // Note: If you choose to set a timeout for this request, we recommend 10 minutes. @@ -88,8 +88,9 @@ type Completion struct { ID string `json:"id" api:"required"` // The resulting completion up to and excluding the stop sequences. Completion string `json:"completion" api:"required"` - // The model that will complete your prompt.\n\nSee - // [models](https://docs.anthropic.com/en/docs/models-overview) for additional + // The model that will complete your prompt. + // + // See [models](https://docs.anthropic.com/en/docs/models-overview) for additional // details and options. Model Model `json:"model" api:"required"` // The reason that we stopped. @@ -128,8 +129,9 @@ type CompletionNewParams struct { // Note that our models may stop _before_ reaching this maximum. This parameter // only specifies the absolute maximum number of tokens to generate. MaxTokensToSample int64 `json:"max_tokens_to_sample" api:"required"` - // The model that will complete your prompt.\n\nSee - // [models](https://docs.anthropic.com/en/docs/models-overview) for additional + // The model that will complete your prompt. + // + // See [models](https://docs.anthropic.com/en/docs/models-overview) for additional // details and options. Model Model `json:"model,omitzero" api:"required"` // The prompt that you want Claude to complete. @@ -141,8 +143,10 @@ type CompletionNewParams struct { // "\n\nHuman: {userQuestion}\n\nAssistant:" // ``` // - // See [prompt validation](https://docs.claude.com/en/api/prompt-validation) and - // our guide to [prompt design](https://docs.claude.com/en/docs/intro-to-prompting) + // See + // [prompt validation](https://platform.claude.com/docs/en/build-with-claude/working-with-messages) + // and our guide to + // [prompt design](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/overview) // for more details. Prompt string `json:"prompt" api:"required"` // Amount of randomness injected into the response. @@ -159,18 +163,15 @@ type CompletionNewParams struct { // Used to remove "long tail" low probability responses. // [Learn more technical details here](https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277). // - // Recommended for advanced use cases only. You usually only need to use - // `temperature`. + // Recommended for advanced use cases only. TopK param.Opt[int64] `json:"top_k,omitzero"` // Use nucleus sampling. // // In nucleus sampling, we compute the cumulative distribution over all the options // for each subsequent token in decreasing probability order and cut it off once it - // reaches a particular probability specified by `top_p`. You should either alter - // `temperature` or `top_p`, but not both. + // reaches a particular probability specified by `top_p`. // - // Recommended for advanced use cases only. You usually only need to use - // `temperature`. + // Recommended for advanced use cases only. TopP param.Opt[float64] `json:"top_p,omitzero"` // An object describing metadata about the request. Metadata MetadataParam `json:"metadata,omitzero"` diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/config/config.go b/vendor/github.com/anthropics/anthropic-sdk-go/config/config.go new file mode 100644 index 000000000..1470ab429 --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/config/config.go @@ -0,0 +1,592 @@ +package config + +import ( + "encoding/json" + "fmt" + "log" + "os" + "path/filepath" + "regexp" + "runtime" + "strings" + "sync" +) + +// ConfigFileVersion is the version written to configs/.json. Absent +// on read implies "1.0". Two-part major.minor: bump major on backwards- +// incompatible shape changes (readers can reject), minor on additive +// changes that older readers can tolerate. +const ConfigFileVersion = "1.0" + +// profileNamePattern restricts config profile names to characters that can +// never escape the configs/ directory (no path separators, no "..") and +// keeps the name shell-safe. +var profileNamePattern = regexp.MustCompile(`^[A-Za-z0-9_.-]+$`) + +func validateProfileName(name string) error { + if name == "" { + return fmt.Errorf("profile name is empty") + } + if name == "." || name == ".." { + return fmt.Errorf("profile name %q is not allowed", name) + } + if strings.ContainsAny(name, `/\`) { + return fmt.Errorf("profile name %q must not contain path separators", name) + } + if !profileNamePattern.MatchString(name) { + return fmt.Errorf("profile name %q contains disallowed characters (allowed: letters, digits, '_', '.', '-')", name) + } + return nil +} + +// Config holds the raw configuration for authenticating with the Anthropic +// API. It mirrors the data stored in config files (configs/.json) +// and can be constructed manually or loaded from disk with [LoadConfig]. +// +// Authentication-mode-specific fields live inside [AuthenticationInfo], a +// tagged union discriminated on [AuthenticationInfo.Type]. Top-level fields +// apply to every profile regardless of authentication mode. +type Config struct { + // Version is the file-format version. Set to [ConfigFileVersion] by + // [SaveProfile] on every write; absent on disk implies "1.0". + Version string `json:"version,omitempty"` + + // AuthenticationInfo describes how this profile authenticates. Required. + AuthenticationInfo *AuthenticationInfo `json:"authentication"` + + // BaseURL overrides the default API base URL. Optional. + BaseURL string `json:"base_url,omitempty"` + + // OrganizationID is the Anthropic organization the profile targets. + OrganizationID string `json:"organization_id,omitempty"` + + // WorkspaceID scopes requests to a specific workspace. For non-federation + // profiles it is sent as the anthropic-workspace-id request header; for + // oidc_federation profiles it is sent as workspace_id in the jwt-bearer + // exchange body instead (the minted token is already workspace-scoped). + WorkspaceID string `json:"workspace_id,omitempty"` +} + +// AuthenticationType is the discriminator for [AuthenticationInfo]. +type AuthenticationType string + +const ( + // AuthenticationTypeOIDCFederation exchanges a third-party OIDC JWT + // ("identity token") for a short-lived Anthropic access token via the + // jwt-bearer grant on /v1/oauth/token. + AuthenticationTypeOIDCFederation AuthenticationType = "oidc_federation" + + // AuthenticationTypeUserOAuth authenticates with an access token minted + // through a user-interactive OAuth flow (e.g. `ant auth login`), with + // optional refresh-token rotation when a ClientID is configured. + AuthenticationTypeUserOAuth AuthenticationType = "user_oauth" +) + +// AuthenticationInfo is a tagged union discriminated on [AuthenticationInfo.Type]. +// On the wire it is flat: the top-level JSON object holds `type`, the shared +// `credentials_path`, and the variant-specific fields all at the same level. +// In Go, the variant-specific fields are grouped into strongly-typed sub-structs +// ([OIDCFederation], [UserOAuth]) so callers get type safety and a clean +// non-nil check per variant. Exactly one sub-struct pointer is populated, and +// it must match [AuthenticationInfo.Type]. +// +// Because the wire shape is flat, all variant field names share a single +// namespace at the JSON layer — new variants must pick field names that do +// not collide with shared fields or with each other. +// +// [AuthenticationInfo.UnmarshalJSON] silently ignores unknown fields at the +// JSON layer (per the credentials-file-format spec: "SDKs MUST silently +// ignore unrecognized top-level keys in both config and credentials files" +// — the same tolerance rule applies to the nested authentication object). +// Unknown authentication types still fail loud because the SDK has no way +// to meaningfully resolve credentials for an unknown variant. +type AuthenticationInfo struct { + Type AuthenticationType `json:"-"` + + // CredentialsPath is the path to the credentials JSON file that stores + // access / refresh tokens on disk. Leave empty to use the default path + // (credentials/.json under the config directory). Shared across + // all authentication types. + CredentialsPath string `json:"-"` + + // OIDCFederation holds the fields for Type == AuthenticationTypeOIDCFederation. + // Populated by UnmarshalJSON and inlined by MarshalJSON; never appears as + // a nested JSON object. + OIDCFederation *OIDCFederation `json:"-"` + + // UserOAuth holds the fields for Type == AuthenticationTypeUserOAuth. + // Populated by UnmarshalJSON and inlined by MarshalJSON; never appears as + // a nested JSON object. + UserOAuth *UserOAuth `json:"-"` +} + +// OIDCFederation configures a profile that authenticates by exchanging a +// third-party OIDC identity token for an Anthropic access token. Its fields +// are inlined into the parent [AuthenticationInfo] on the wire. +type OIDCFederation struct { + // FederationRuleID is the tagged ID ("fdrl_...") of the OidcFederationRule + // that governs the exchange. Required. + FederationRuleID string `json:"federation_rule_id"` + + // ServiceAccountID is an optional expected-target check for federation + // rules with target_type=SERVICE_ACCOUNT. Must be a "svac_..." tagged ID. + // Omit for target_type=USER rules, where the principal is derived from + // the JWT claims. + ServiceAccountID string `json:"service_account_id,omitempty"` + + // IdentityToken describes how to obtain the OIDC assertion this profile + // presents at token-exchange time. + IdentityToken *IdentityTokenConfig `json:"identity_token,omitempty"` + + // Scope is the OAuth scope string (RFC 6749 §3.3 space-delimited form) + // the profile expects to be granted. It is stored on the profile for + // display and configuration purposes only — the SDK does NOT send it + // on the jwt-bearer exchange. The granted scope is determined by the + // federation rule on the server; IssueOAuthTokenRequest has no scope + // field, and the REST gateway's alias transformation strips unknown + // keys, so any attempt to wire this through to the exchange body + // would be silently dropped. The granted scope appears on the token + // response's `scope` field, but the SDK does not currently surface + // it to callers. + Scope string `json:"scope,omitempty"` +} + +// UserOAuth configures a profile authenticated via a user-interactive OAuth +// flow. The access and (optional) refresh tokens live on disk under the +// profile's [AuthenticationInfo.CredentialsPath]. Its fields are inlined +// into the parent [AuthenticationInfo] on the wire. +type UserOAuth struct { + // ClientID is the OAuth client ID used for refresh-token exchange. When + // empty, the access token is treated as static (no refresh) and the + // profile fails once it expires. + ClientID string `json:"client_id,omitempty"` + + // Scope is the OAuth scope string (RFC 6749 §3.3 space-delimited form) + // the profile was granted, captured at login time. The SDK does not + // consult this on refresh — the oauth-server preserves the original + // scope set when the refresh request omits scope — but `ant auth status` + // and similar tools display it. + Scope string `json:"scope,omitempty"` + + // ConsoleURL is the base URL of the OAuth /authorize page for + // interactive login. The SDK does not consult it; it's CLI-only state + // (the `ant auth login` target) that lives on the shared schema so + // SaveProfile/LoadProfile round-trip it without triggering the + // unknown-field warning. + ConsoleURL string `json:"console_url,omitempty"` +} + +// IdentityTokenSource is the source kind for an OIDC identity token. +type IdentityTokenSource string + +const ( + // IdentityTokenSourceFile reads the token from a file on every exchange, + // which supports rotated tokens (e.g. Kubernetes projected service + // account tokens). + IdentityTokenSourceFile IdentityTokenSource = "file" +) + +// IdentityTokenConfig specifies how to obtain an OIDC identity token for +// federation exchange. +type IdentityTokenConfig struct { + Source IdentityTokenSource `json:"source"` + Path string `json:"path,omitempty"` +} + +// NewUserOAuthAuthentication returns a populated [AuthenticationInfo] for +// the user_oauth variant. Pass an empty clientID to describe a profile whose +// access token is static (no refresh). +func NewUserOAuthAuthentication(clientID string) *AuthenticationInfo { + return &AuthenticationInfo{ + Type: AuthenticationTypeUserOAuth, + UserOAuth: &UserOAuth{ClientID: clientID}, + } +} + +// NewOIDCFederationAuthentication builds an [AuthenticationInfo] for the +// oidc_federation variant. +func NewOIDCFederationAuthentication(oidc OIDCFederation) *AuthenticationInfo { + return &AuthenticationInfo{ + Type: AuthenticationTypeOIDCFederation, + OIDCFederation: &oidc, + } +} + +// sharedAuthFields are the fields present on every authentication variant. +// The discriminator read uses a tolerant decoder (unknown fields allowed) +// because the variant decode in the second pass is what rejects typos. +type sharedAuthFields struct { + Type AuthenticationType `json:"type"` + CredentialsPath string `json:"credentials_path,omitempty"` +} + +// oidcFederationWire is the flat wire shape for oidc_federation: shared +// fields + inlined OIDCFederation fields. Unknown fields are tolerated +// per the credentials-file-format spec so forward-compatible additions +// and cross-SDK-written files don't fail loud. +type oidcFederationWire struct { + sharedAuthFields + FederationRuleID string `json:"federation_rule_id"` + ServiceAccountID string `json:"service_account_id,omitempty"` + IdentityToken *IdentityTokenConfig `json:"identity_token,omitempty"` + Scope string `json:"scope,omitempty"` +} + +// userOAuthWire is the flat wire shape for user_oauth: shared fields + +// inlined UserOAuth fields. +type userOAuthWire struct { + sharedAuthFields + ClientID string `json:"client_id,omitempty"` + Scope string `json:"scope,omitempty"` + ConsoleURL string `json:"console_url,omitempty"` +} + +// UnmarshalJSON decodes the flat tagged-union wire shape into the nested +// Go representation. Unknown fields are silently tolerated per the +// credentials-file-format spec but are also logged (warn-once) so a +// user who typo'd a field name at least sees that it was ignored. +// Unknown authentication types still fail loud. +func (a *AuthenticationInfo) UnmarshalJSON(data []byte) error { + var raw map[string]json.RawMessage + if err := json.Unmarshal(data, &raw); err != nil { + return err + } + var authType AuthenticationType + if b, ok := raw["type"]; ok { + if err := json.Unmarshal(b, &authType); err != nil { + return err + } + } + + switch authType { + case "": + return fmt.Errorf("authentication.type is required") + case AuthenticationTypeOIDCFederation: + var w oidcFederationWire + if err := json.Unmarshal(data, &w); err != nil { + return fmt.Errorf("authentication.type %q: %w", authType, err) + } + unknown := unknownRawKeys(raw, knownOIDCFederationFields) + *a = AuthenticationInfo{ + Type: w.Type, + CredentialsPath: w.CredentialsPath, + OIDCFederation: &OIDCFederation{ + FederationRuleID: w.FederationRuleID, + ServiceAccountID: w.ServiceAccountID, + IdentityToken: w.IdentityToken, + Scope: w.Scope, + }, + } + warnUnknownAuthFields(string(authType), unknown) + return nil + case AuthenticationTypeUserOAuth: + var w userOAuthWire + if err := json.Unmarshal(data, &w); err != nil { + return fmt.Errorf("authentication.type %q: %w", authType, err) + } + unknown := unknownRawKeys(raw, knownUserOAuthFields) + *a = AuthenticationInfo{ + Type: w.Type, + CredentialsPath: w.CredentialsPath, + UserOAuth: &UserOAuth{ + ClientID: w.ClientID, + Scope: w.Scope, + ConsoleURL: w.ConsoleURL, + }, + } + warnUnknownAuthFields(string(authType), unknown) + return nil + default: + return fmt.Errorf("authentication.type %q is not a known authentication type", authType) + } +} + +func unknownRawKeys(raw map[string]json.RawMessage, known map[string]struct{}) []string { + var unknown []string + for k := range raw { + if _, ok := known[k]; ok { + continue + } + unknown = append(unknown, k) + } + return unknown +} + +// Keep in sync with [oidcFederationWire] and [userOAuthWire]. +var ( + knownOIDCFederationFields = map[string]struct{}{ + "type": {}, + "credentials_path": {}, + "federation_rule_id": {}, + "service_account_id": {}, + "identity_token": {}, + "scope": {}, + } + knownUserOAuthFields = map[string]struct{}{ + "type": {}, + "credentials_path": {}, + "client_id": {}, + "scope": {}, + "console_url": {}, + } +) + +var ( + configWarnOnceMu sync.Mutex + configWarnOnceSet = map[string]bool{} +) + +func configWarnOnce(key, format string, args ...any) { + configWarnOnceMu.Lock() + already := configWarnOnceSet[key] + configWarnOnceSet[key] = true + configWarnOnceMu.Unlock() + if already { + return + } + log.Printf("anthropic-sdk-go/config: "+format, args...) +} + +func warnUnknownAuthFields(authType string, fields []string) { + for _, f := range fields { + configWarnOnce( + "unknown-auth-field:"+authType+":"+f, + "profile authentication.%s: unknown field %q (ignored)", + authType, f, + ) + } +} + +// ResetConfigWarnOnceForTest clears the warn-once dedupe state so tests +// can observe a warning a prior test may already have triggered. +func ResetConfigWarnOnceForTest() { + configWarnOnceMu.Lock() + configWarnOnceSet = map[string]bool{} + configWarnOnceMu.Unlock() +} + +// MarshalJSON emits the flat tagged-union wire shape: shared fields, then +// the matching variant's fields inlined at the same level. Returns an error +// when the in-memory state is inconsistent (Type mismatches the populated +// sub-struct, or neither/both are set). +func (a AuthenticationInfo) MarshalJSON() ([]byte, error) { + switch a.Type { + case "": + return nil, fmt.Errorf("AuthenticationInfo.Type is required") + case AuthenticationTypeOIDCFederation: + if a.OIDCFederation == nil { + return nil, fmt.Errorf("AuthenticationInfo.Type=%q requires OIDCFederation", a.Type) + } + if a.UserOAuth != nil { + return nil, fmt.Errorf("AuthenticationInfo.Type=%q must not set UserOAuth", a.Type) + } + return json.Marshal(oidcFederationWire{ + sharedAuthFields: sharedAuthFields{Type: a.Type, CredentialsPath: a.CredentialsPath}, + FederationRuleID: a.OIDCFederation.FederationRuleID, + ServiceAccountID: a.OIDCFederation.ServiceAccountID, + IdentityToken: a.OIDCFederation.IdentityToken, + Scope: a.OIDCFederation.Scope, + }) + case AuthenticationTypeUserOAuth: + if a.UserOAuth == nil { + return nil, fmt.Errorf("AuthenticationInfo.Type=%q requires UserOAuth", a.Type) + } + if a.OIDCFederation != nil { + return nil, fmt.Errorf("AuthenticationInfo.Type=%q must not set OIDCFederation", a.Type) + } + return json.Marshal(userOAuthWire{ + sharedAuthFields: sharedAuthFields{Type: a.Type, CredentialsPath: a.CredentialsPath}, + ClientID: a.UserOAuth.ClientID, + Scope: a.UserOAuth.Scope, + ConsoleURL: a.UserOAuth.ConsoleURL, + }) + default: + return nil, fmt.Errorf("AuthenticationInfo.Type %q is not a known authentication type", a.Type) + } +} + +// defaultConfigDir returns the platform-specific base directory for Anthropic +// config and credentials. It checks ANTHROPIC_CONFIG_DIR first, then falls +// back to the platform default. On non-Windows platforms XDG_CONFIG_HOME is +// honored per the XDG Base Directory spec before the $HOME/.config fallback. +// Returns an empty string when the platform home directory cannot be +// resolved (e.g., $HOME unset in a minimal container), so callers don't +// silently read/write to a CWD-relative path. +func defaultConfigDir() string { + if dir, ok := os.LookupEnv("ANTHROPIC_CONFIG_DIR"); ok { + return dir + } + if runtime.GOOS == "windows" { + if appdata := os.Getenv("APPDATA"); appdata != "" { + return filepath.Join(appdata, "Anthropic") + } + return "" + } + if xdg := os.Getenv("XDG_CONFIG_HOME"); xdg != "" { + return filepath.Join(xdg, "anthropic") + } + home, err := os.UserHomeDir() + if err != nil || home == "" { + return "" + } + return filepath.Join(home, ".config", "anthropic") +} + +// resolveProfile determines the active profile name. +// Resolution order: ANTHROPIC_PROFILE env -> active_config file -> "default". +func resolveProfile(configDir string) string { + if profile, ok := os.LookupEnv("ANTHROPIC_PROFILE"); ok { + return profile + } + data, err := os.ReadFile(filepath.Join(configDir, "active_config")) + if err == nil { + if name := strings.TrimSpace(string(data)); name != "" { + return name + } + } + return "default" +} + +// loadProfile reads the config file for a specific profile and returns the +// parsed [Config]. The [Config.CredentialsPath] is defaulted to +// credentials/.json under configDir if not already set. +func loadProfile(configDir, profile string) (*Config, error) { + if err := validateProfileName(profile); err != nil { + return nil, fmt.Errorf("invalid profile %q: %w", profile, err) + } + configPath := filepath.Join(configDir, "configs", profile+".json") + data, err := os.ReadFile(configPath) + if err != nil { + return nil, fmt.Errorf("failed to read config file %q: %w", configPath, err) + } + + var cfg Config + if err := json.Unmarshal(data, &cfg); err != nil { + return nil, fmt.Errorf("failed to parse config file %q: %w", configPath, err) + } + + if cfg.AuthenticationInfo == nil { + return nil, fmt.Errorf("config file %q is missing authentication", configPath) + } + + if cfg.AuthenticationInfo.CredentialsPath == "" { + cfg.AuthenticationInfo.CredentialsPath = filepath.Join(configDir, "credentials", profile+".json") + } + + fillMissingFromEnv(&cfg) + + return &cfg, nil +} + +const ( + envBaseURL = "ANTHROPIC_BASE_URL" + envOrganizationID = "ANTHROPIC_ORGANIZATION_ID" + envWorkspaceID = "ANTHROPIC_WORKSPACE_ID" + envFederationRuleID = "ANTHROPIC_FEDERATION_RULE_ID" + envServiceAccountID = "ANTHROPIC_SERVICE_ACCOUNT_ID" + envScope = "ANTHROPIC_SCOPE" + envIdentityTokenFile = "ANTHROPIC_IDENTITY_TOKEN_FILE" +) + +// fillMissingFromEnv populates cfg fields from ANTHROPIC_* environment +// variables, but only when the corresponding field is empty in the loaded +// profile. Contract lives in the cross-SDK credential precedence spec +// (sdk_credential_precedence.md, section 1 interaction rules): "env vars +// fill in fields omitted from a profile file, but never override present +// ones." This keeps an explicit profile authoritative on a machine that +// also happens to have WIF env vars exported (e.g., a prod profile is +// not silently replaced by a leftover dev federation_rule_id env var). +// +// Empty env values are treated as unset rather than "clear the field" so +// an accidentally-blanked env var can't silently strip a required field. +func fillMissingFromEnv(cfg *Config) { + if cfg.BaseURL == "" { + if v, ok := lookupNonEmpty(envBaseURL); ok { + cfg.BaseURL = v + } + } + if cfg.OrganizationID == "" { + if v, ok := lookupNonEmpty(envOrganizationID); ok { + cfg.OrganizationID = v + } + } + if cfg.WorkspaceID == "" { + if v, ok := lookupNonEmpty(envWorkspaceID); ok { + cfg.WorkspaceID = v + } + } + + switch cfg.AuthenticationInfo.Type { + case AuthenticationTypeOIDCFederation: + oidc := cfg.AuthenticationInfo.OIDCFederation + if oidc == nil { + return + } + if oidc.FederationRuleID == "" { + if v, ok := lookupNonEmpty(envFederationRuleID); ok { + oidc.FederationRuleID = v + } + } + if oidc.ServiceAccountID == "" { + if v, ok := lookupNonEmpty(envServiceAccountID); ok { + oidc.ServiceAccountID = v + } + } + if oidc.Scope == "" { + if v, ok := lookupNonEmpty(envScope); ok { + oidc.Scope = v + } + } + if oidc.IdentityToken == nil { + if v, ok := lookupNonEmpty(envIdentityTokenFile); ok { + oidc.IdentityToken = &IdentityTokenConfig{ + Source: IdentityTokenSourceFile, + Path: v, + } + } + } + case AuthenticationTypeUserOAuth: + if cfg.AuthenticationInfo.UserOAuth == nil { + return + } + if cfg.AuthenticationInfo.UserOAuth.Scope == "" { + if v, ok := lookupNonEmpty(envScope); ok { + cfg.AuthenticationInfo.UserOAuth.Scope = v + } + } + } +} + +// lookupNonEmpty returns the env var's value and true only when it is set +// and non-empty. An empty value is reported as unset. +func lookupNonEmpty(key string) (string, bool) { + v, ok := os.LookupEnv(key) + if !ok || v == "" { + return "", false + } + return v, true +} + +// LoadProfile loads the config for the named profile from the given config +// directory, bypassing ANTHROPIC_PROFILE / active_config resolution. Use +// [DefaultDir] for the standard location. This is the building block CLIs use +// to inspect or operate on a profile other than the currently-active one. +func LoadProfile(dir, profile string) (*Config, error) { + return loadProfile(dir, profile) +} + +// LoadConfig reads the raw configuration from the Anthropic config file system +// (configs/.json) and returns it without resolving credentials. +// Credential resolution is deferred until the config is passed to +// [option.WithConfig]. +// +// The config directory and profile are resolved using the standard resolution +// order (ANTHROPIC_CONFIG_DIR, ANTHROPIC_PROFILE, active_config file, defaults). +func LoadConfig() (*Config, error) { + configDir := defaultConfigDir() + profile := resolveProfile(configDir) + if err := validateProfileName(profile); err != nil { + return nil, fmt.Errorf("invalid profile name from resolution: %w", err) + } + return loadProfile(configDir, profile) +} diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/config/federation.go b/vendor/github.com/anthropics/anthropic-sdk-go/config/federation.go new file mode 100644 index 000000000..a370a5e78 --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/config/federation.go @@ -0,0 +1,235 @@ +package config + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "strings" + "time" + + "github.com/anthropics/anthropic-sdk-go/internal" +) + +// OAuth 2.0 wire-contract constants. These are the authoritative +// definitions; internal/auth re-exports them as local aliases so that +// in-tree auth code can reference them without importing config and +// forming a cycle. +const ( + // TokenEndpoint is the path of the Anthropic OAuth 2.0 token + // endpoint — the destination for jwt-bearer exchanges, + // refresh_token grants, and (future) authorization_code grants. + TokenEndpoint = "/v1/oauth/token" + + // GrantTypeJWTBearer is the RFC 7523 grant type string used for + // OIDC federation exchanges. + GrantTypeJWTBearer = "urn:ietf:params:oauth:grant-type:jwt-bearer" + + // GrantTypeRefreshToken is the RFC 6749 §6 grant type string used + // for rotating user_oauth access tokens. + GrantTypeRefreshToken = "refresh_token" + + // OAuthAPIBetaHeader is the anthropic-beta value required on + // authenticated API requests using an OAuth bearer token, and on + // refresh_token grants against the token endpoint. + OAuthAPIBetaHeader = "oauth-2025-04-20" + + // FederationBetaHeader is the anthropic-beta value required on + // jwt-bearer exchanges against the token endpoint. It routes the + // request to the Go userauth service; it must NOT be sent on + // refresh_token grants, which are gateway-routed to the Python + // oauth-server. + FederationBetaHeader = "oidc-federation-2026-04-01" +) + +const ( + defaultAPIBaseURL = "https://api.anthropic.com" + // federationExchangeBetaValue is the combined anthropic-beta value + // for jwt-bearer exchanges: oauth-2025-04-20 unlocks the oauth/token + // endpoint family, and oidc-federation-2026-04-01 routes jwt-bearer + // to the federation service. + federationExchangeBetaValue = OAuthAPIBetaHeader + "," + FederationBetaHeader +) + +// FederationExchangeParams captures the inputs needed to exchange a signed +// third-party assertion (GitHub OIDC, Kubernetes service account token, +// etc.) for a short-lived Anthropic access token via the jwt-bearer grant. +type FederationExchangeParams struct { + // Assertion is the signed JWT presented to the token endpoint. Required. + Assertion string + + // FederationRuleID is the tagged ID ("fdrl_...") of the OidcFederationRule + // that governs the exchange. Required. + FederationRuleID string + + // OrganizationID is the tagged ID of the Anthropic organization whose + // credentials the exchange should mint. Required. + OrganizationID string + + // ServiceAccountID is an optional "svac_..." target check for + // federation rules with target_type=SERVICE_ACCOUNT. Leave empty for + // user-targeted rules. + ServiceAccountID string + + // WorkspaceID is an optional `wrkspc_*` tagged ID, or the literal + // "default" to scope the token to the organization's default workspace. + // When omitted the server picks the rule's sole enabled workspace, else + // the org default if the rule covers it. Required when the rule enables + // more than one non-default workspace, or to target a specific workspace + // other than the one the server would pick. The minted token is + // workspace-scoped: per-request workspace selection (the + // anthropic-workspace-id header) is not supported for federation + // tokens — switching workspaces requires a new token exchange with a + // different WorkspaceID. + WorkspaceID string + + // BaseURL overrides the Anthropic API base URL. Defaults to + // https://api.anthropic.com. A trailing slash is tolerated. + BaseURL string + + // HTTPClient overrides the default HTTP client used for the exchange. + // When nil, a client with a 30s timeout is used. + HTTPClient *http.Client + + // UserAgent overrides the outgoing User-Agent header. When empty, the + // helper sends "anthropic-sdk-go/ ExchangeFederationAssertion" + // so the token endpoint's access logs identify the caller for + // incident triage. Callers with their own tooling (e.g. `ant-cli/1.2.3`) + // should set this so support tickets can point at the real binary. + UserAgent string +} + +// federationExchangeRequest mirrors the JSON body the server's token +// endpoint accepts. The REST gateway's AliasTransformation strips any +// field not in this exact set, so each JSON tag is load-bearing — sending +// "federation_rule" or "organization" (without "_id") causes the gateway +// to drop the value and the Connect handler to fail with an empty +// federation_rule_id error. Keep in sync with +// internal/auth/workload.go:tokenExchangeRequest. +type federationExchangeRequest struct { + GrantType string `json:"grant_type"` + Assertion string `json:"assertion"` + FederationRuleID string `json:"federation_rule_id"` + OrganizationID string `json:"organization_id"` + ServiceAccountID string `json:"service_account_id,omitempty"` + WorkspaceID string `json:"workspace_id,omitempty"` +} + +// FederationExchangeError is returned by [ExchangeFederationAssertion] when +// the token endpoint responds with a non-2xx status. The server body is +// kept verbatim so the caller can surface the exact upstream message; the +// Request-Id header is captured separately so support tickets can include +// a correlation identifier. +type FederationExchangeError struct { + StatusCode int + Body string + RequestID string +} + +func (e *FederationExchangeError) Error() string { + redacted := RedactOAuthErrorBody(e.Body) + if e.RequestID != "" { + return fmt.Sprintf("federation exchange failed (status %d, request-id %s): %s", + e.StatusCode, e.RequestID, redacted) + } + return fmt.Sprintf("federation exchange failed (status %d): %s", e.StatusCode, redacted) +} + +// ExchangeFederationAssertion performs an OAuth 2.0 jwt-bearer exchange +// against the Anthropic token endpoint and returns the minted credentials. +// +// Federation grants do not return a refresh token — callers re-exchange +// their assertion on expiry. The returned [*Credentials] therefore has an +// empty RefreshToken but a populated ExpiresAt whenever the server returns +// an expires_in field. +// +// On non-2xx responses the returned error is a [*FederationExchangeError] +// carrying the server body and the Request-Id response header. +func ExchangeFederationAssertion(ctx context.Context, params FederationExchangeParams) (*Credentials, error) { + if params.Assertion == "" { + return nil, errors.New("ExchangeFederationAssertion: Assertion is required") + } + if params.FederationRuleID == "" { + return nil, errors.New("ExchangeFederationAssertion: FederationRuleID is required") + } + if params.OrganizationID == "" { + return nil, errors.New("ExchangeFederationAssertion: OrganizationID is required") + } + + base := strings.TrimRight(params.BaseURL, "/") + if base == "" { + base = defaultAPIBaseURL + } + + bodyJSON, err := json.Marshal(federationExchangeRequest{ + GrantType: GrantTypeJWTBearer, + Assertion: params.Assertion, + FederationRuleID: params.FederationRuleID, + OrganizationID: params.OrganizationID, + ServiceAccountID: params.ServiceAccountID, + WorkspaceID: params.WorkspaceID, + }) + if err != nil { + return nil, fmt.Errorf("ExchangeFederationAssertion: marshal body: %w", err) + } + + req, err := http.NewRequestWithContext(ctx, http.MethodPost, base+TokenEndpoint, bytes.NewReader(bodyJSON)) + if err != nil { + return nil, fmt.Errorf("ExchangeFederationAssertion: build request: %w", err) + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("anthropic-beta", federationExchangeBetaValue) + ua := params.UserAgent + if ua == "" { + ua = "anthropic-sdk-go/" + internal.PackageVersion + " ExchangeFederationAssertion" + } + req.Header.Set("User-Agent", ua) + + client := params.HTTPClient + if client == nil { + client = &http.Client{Timeout: 30 * time.Second} + } + resp, err := client.Do(req) + if err != nil { + return nil, fmt.Errorf("ExchangeFederationAssertion: post: %w", err) + } + defer resp.Body.Close() + + body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + if err != nil { + return nil, fmt.Errorf("ExchangeFederationAssertion: read response: %w", err) + } + + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + return nil, &FederationExchangeError{ + StatusCode: resp.StatusCode, + Body: string(body), + RequestID: resp.Header.Get("Request-Id"), + } + } + + var parsed struct { + AccessToken string `json:"access_token"` + TokenType string `json:"token_type,omitempty"` + ExpiresIn *int `json:"expires_in,omitempty"` + } + if err := json.Unmarshal(body, &parsed); err != nil { + return nil, fmt.Errorf("ExchangeFederationAssertion: parse response: %w", err) + } + if parsed.AccessToken == "" { + return nil, errors.New("ExchangeFederationAssertion: response missing access_token") + } + if parsed.TokenType != "" && !strings.EqualFold(parsed.TokenType, "Bearer") { + return nil, fmt.Errorf("ExchangeFederationAssertion: unsupported token_type %q (want Bearer)", parsed.TokenType) + } + + creds := &Credentials{AccessToken: parsed.AccessToken} + if parsed.ExpiresIn != nil { + exp := time.Now().Add(time.Duration(*parsed.ExpiresIn) * time.Second) + creds.ExpiresAt = &exp + } + return creds, nil +} diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/config/oautherr.go b/vendor/github.com/anthropics/anthropic-sdk-go/config/oautherr.go new file mode 100644 index 000000000..d67e7762e --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/config/oautherr.go @@ -0,0 +1,46 @@ +package config + +import "encoding/json" + +// OAuthErrorBodyMaxLen caps the error body length embedded in OAuth-endpoint +// failure error messages. Token-endpoint responses are untrusted and are +// routinely captured in logs; the cap covers identity-provider proxies that +// concatenate upstream messages into error_description. +const OAuthErrorBodyMaxLen = 2000 + +// oauthErrorAllowedKeys is the RFC 6749 §5.2 allowlist surfaced in +// user-facing errors. Any other key is dropped — providers have been seen +// to echo back the assertion JWT or a partially-minted token, neither of +// which may appear in logs. error_description is attacker-controllable +// free-form text; callers must treat redacted output as untrusted. +var oauthErrorAllowedKeys = []string{ + "error", + "error_description", + "error_uri", +} + +// RedactOAuthErrorBody returns a safe-to-log form of an OAuth token endpoint +// failure body. If the body parses as a JSON object, only the RFC 6749 §5.2 +// allowed keys are kept. Non-JSON bodies are replaced with a redaction +// placeholder. Either way the result is truncated to [OAuthErrorBodyMaxLen]. +func RedactOAuthErrorBody(body string) string { + var obj map[string]any + // err only — Unmarshal("null") sets obj=nil with no error; nil filters to {}. + if err := json.Unmarshal([]byte(body), &obj); err == nil { + filtered := make(map[string]any, len(oauthErrorAllowedKeys)) + for _, k := range oauthErrorAllowedKeys { + if v, present := obj[k]; present { + filtered[k] = v + } + } + if b, err := json.Marshal(filtered); err == nil { + body = string(b) + } + } else { + body = "[redacted; not a JSON error response]" + } + if len(body) > OAuthErrorBodyMaxLen { + body = body[:OAuthErrorBodyMaxLen] + "...[truncated]" + } + return body +} diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/config/writers.go b/vendor/github.com/anthropics/anthropic-sdk-go/config/writers.go new file mode 100644 index 000000000..3da22b564 --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/config/writers.go @@ -0,0 +1,376 @@ +package config + +import ( + "encoding/json" + "fmt" + "io/fs" + "os" + "path/filepath" + "sort" + "strings" + "time" +) + +const credentialsTypeOAuthToken = "oauth_token" + +// CredentialsFileVersion is the version written to credentials/.json. +// Absent on read implies "1.0". Major.minor format: bump major on +// backwards-incompatible shape changes, minor on additive changes. +const CredentialsFileVersion = "1.0" + +// Credentials is the in-memory form of a credentials/.json file. +// Not every field is populated for every authentication variant: federation +// grants, for example, do not return a refresh token. +type Credentials struct { + AccessToken string + RefreshToken string + // ExpiresAt is the absolute expiry time of AccessToken. Nil means the + // token's lifetime is unknown to the SDK (treated as non-expiring by + // the in-memory cache). + ExpiresAt *time.Time + + // Scope, OrganizationUUID, OrganizationName, and AccountEmail record + // what the current AccessToken was actually granted/minted for. They are + // written on every login and reflect the token's view of the world at + // mint time. This is distinct from [Config.OrganizationID] on the profile + // config side, which is the user's intended target org; the two may + // diverge if the user is reassigned or the token was minted before the + // profile was edited. + Scope string + OrganizationUUID string + OrganizationName string + // AccountEmail is the email of the account that minted the token, taken + // from the /v1/oauth/token response's account.email_address. + AccountEmail string + // WorkspaceID and WorkspaceName record the workspace the token was + // bound to at mint time (when the authorization carried one). Stored + // as the tagged `wrkspc_...` form — the same format the CLI flag, + // profile config, and anthropic-workspace-id header accept. Sourced + // from the /v1/oauth/token response's workspace.id. Empty for tokens + // that aren't workspace-scoped. + WorkspaceID string + WorkspaceName string +} + +type credentialsWireShape struct { + Version string `json:"version,omitempty"` + Type string `json:"type"` + AccessToken string `json:"access_token"` + ExpiresAt *int64 `json:"expires_at,omitempty"` + RefreshToken string `json:"refresh_token,omitempty"` + Scope string `json:"scope,omitempty"` + OrganizationUUID string `json:"organization_uuid,omitempty"` + OrganizationName string `json:"organization_name,omitempty"` + AccountEmail string `json:"account_email,omitempty"` + WorkspaceID string `json:"workspace_id,omitempty"` + WorkspaceName string `json:"workspace_name,omitempty"` +} + +func (c Credentials) MarshalJSON() ([]byte, error) { + w := credentialsWireShape{ + Version: CredentialsFileVersion, + Type: credentialsTypeOAuthToken, + AccessToken: c.AccessToken, + RefreshToken: c.RefreshToken, + Scope: c.Scope, + OrganizationUUID: c.OrganizationUUID, + OrganizationName: c.OrganizationName, + AccountEmail: c.AccountEmail, + WorkspaceID: c.WorkspaceID, + WorkspaceName: c.WorkspaceName, + } + if c.ExpiresAt != nil { + exp := c.ExpiresAt.Unix() + w.ExpiresAt = &exp + } + return json.Marshal(w) +} + +// UnmarshalJSON decodes a credentials/.json file. Unknown fields +// are silently tolerated per the credentials-file-format spec. A missing +// "type" is treated as equivalent to "oauth_token" — this is a concession +// to interop with external tooling (credential daemons, sidecars) that +// may write plain bearer-token blobs without the discriminator. Every +// SDK writer emits "type" on write, so missing-type files can only come +// from outside the SDK; rejecting them would break valid integrations. +// A type that is set but not "oauth_token" still fails loud. +func (c *Credentials) UnmarshalJSON(data []byte) error { + var w credentialsWireShape + if err := json.Unmarshal(data, &w); err != nil { + return err + } + if w.Type != "" && w.Type != credentialsTypeOAuthToken { + return fmt.Errorf("credentials: unknown type %q", w.Type) + } + c.AccessToken = w.AccessToken + c.RefreshToken = w.RefreshToken + c.Scope = w.Scope + c.OrganizationUUID = w.OrganizationUUID + c.OrganizationName = w.OrganizationName + c.AccountEmail = w.AccountEmail + c.WorkspaceID = w.WorkspaceID + c.WorkspaceName = w.WorkspaceName + c.ExpiresAt = nil + if w.ExpiresAt != nil { + exp := time.Unix(*w.ExpiresAt, 0) + c.ExpiresAt = &exp + } + return nil +} + +// DefaultDir returns the SDK's default configuration directory (the same +// one [LoadConfig] reads from when ANTHROPIC_CONFIG_DIR is unset). Returns +// an empty string if the platform home directory cannot be resolved — the +// writers in this package surface that as an explicit error. +func DefaultDir() string { return defaultConfigDir() } + +// configsSubdir and credentialsSubdir are the directories under the config +// root that hold one JSON file per profile. Defined once here so the layout +// has a single source of truth across path helpers and [ListProfiles]. +const ( + configsSubdir = "configs" + credentialsSubdir = "credentials" +) + +// ProfilesDir returns the directory containing profile config JSON files. +func ProfilesDir(dir string) string { return filepath.Join(dir, configsSubdir) } + +// CredentialsDir returns the directory containing per-profile credentials files. +func CredentialsDir(dir string) string { return filepath.Join(dir, credentialsSubdir) } + +// ProfilePath returns the path to configs/.json under dir. +func ProfilePath(dir, profile string) string { + return filepath.Join(ProfilesDir(dir), profile+".json") +} + +// ProfileCredentialsPath returns the path to credentials/.json under dir. +func ProfileCredentialsPath(dir, profile string) string { + return filepath.Join(CredentialsDir(dir), profile+".json") +} + +// ActiveConfigPath returns the path to the active_config pointer file under dir. +func ActiveConfigPath(dir string) string { + return filepath.Join(dir, "active_config") +} + +// ListProfiles returns the names of all profiles stored under dir's configs +// subdirectory, sorted for stable output. A missing configs directory is +// treated as "no profiles" and returns a nil slice with no error, so callers +// can enumerate a fresh config root without special-casing first run. +func ListProfiles(dir string) ([]string, error) { + entries, err := os.ReadDir(ProfilesDir(dir)) + if err != nil { + if os.IsNotExist(err) { + return nil, nil + } + return nil, err + } + var names []string + for _, e := range entries { + if e.IsDir() { + continue + } + name, ok := strings.CutSuffix(e.Name(), ".json") + if !ok || name == "" { + continue + } + names = append(names, name) + } + sort.Strings(names) + return names, nil +} + +// Profile filesystem modes. Configs are non-secret and use the "public" +// mode so another UID on the same host (e.g. a sidecar, or `ant profile +// list` running as a different user inside a pod) can read them; +// credentials are secret and use the tighter mode. +// +// These track the credentials-file-format spec's split rationale: +// configs/ (0755 dirs, 0644 files — checkin-safe) vs credentials/ +// (0700 dirs, 0600 files — secrets). +const ( + publicDirMode os.FileMode = 0755 + publicFileMode os.FileMode = 0644 + secretDirMode os.FileMode = 0700 + secretFileMode os.FileMode = 0600 +) + +// writeFileAtomic writes to a unique sibling tmp file then renames onto +// the target (last-writer-wins). Tmp name is unique per write so +// concurrent writers don't collide on the temp; mode is Chmod'd +// explicitly so umask can't loosen secrets; tmp and parent dir are +// fsync'd for crash durability; tmp is removed on any failure. +func writeFileAtomic(path string, data []byte, dirMode, fileMode os.FileMode) error { + dir := filepath.Dir(path) + if err := os.MkdirAll(dir, dirMode); err != nil { + return err + } + + // Base prefix is for debuggability (which target a leftover tmp belongs to). + f, err := os.CreateTemp(dir, filepath.Base(path)+".*.tmp") + if err != nil { + return err + } + tmpPath := f.Name() + // From here on, any failure must remove the tmp file. + cleanup := func(err error) error { + os.Remove(tmpPath) + return err + } + if _, err := f.Write(data); err != nil { + f.Close() + return cleanup(err) + } + // CreateTemp defaults to 0600; Chmod enforces fileMode for both paths. + if err := f.Chmod(fileMode); err != nil { + f.Close() + return cleanup(err) + } + if err := f.Sync(); err != nil { + f.Close() + return cleanup(err) + } + if err := f.Close(); err != nil { + return cleanup(err) + } + // Refuse a pre-planted symlink at the target — would let an attacker + // redirect the bearer-token write to a path of their choosing. + if fi, err := os.Lstat(path); err == nil && fi.Mode()&fs.ModeSymlink != 0 { + return cleanup(fmt.Errorf("refusing to write %s: target is a symlink", path)) + } + if err := os.Rename(tmpPath, path); err != nil { + return cleanup(err) + } + // fsync the parent directory so the rename is durable across a crash. + // On Windows this is a no-op / unsupported — the Sync() call may + // return an error, which we swallow because the rename itself is + // already visible to other processes. + if d, err := os.Open(dir); err == nil { + _ = d.Sync() + d.Close() + } + return nil +} + +// validateDirAndProfile rejects empty dirs and unsafe profile names so +// callers that pass zero values or untrusted input get a clean error +// instead of a path-traversal. +func validateDirAndProfile(dir, profile string) error { + if dir == "" { + return fmt.Errorf("config dir is empty (DefaultDir returned empty; set ANTHROPIC_CONFIG_DIR)") + } + if err := validateProfileName(profile); err != nil { + return err + } + return nil +} + +// SaveProfile persists cfg to configs/.json under dir. The write +// is atomic (.tmp sibling + rename); the target file is mode 0644 and the +// configs/ parent is 0755, matching the spec's "non-secret, checkin-safe" +// positioning for config files (other UIDs on the host — a sidecar, or +// the CLI running under a different user inside a pod — must be able to +// read them). +// +// If cfg.AuthenticationInfo.CredentialsPath exactly matches the default +// resolved path for this profile (i.e. it was populated by LoadConfig +// defaulting the value, not set explicitly by the caller), it is cleared +// on write. Otherwise a load → save round-trip would pin the profile +// config file to the current $HOME via an absolute path, breaking the +// "checkin-safe, relocatable" design goal. +func SaveProfile(dir, profile string, cfg *Config) error { + if err := validateDirAndProfile(dir, profile); err != nil { + return fmt.Errorf("SaveProfile: %w", err) + } + if cfg == nil { + return fmt.Errorf("SaveProfile: cfg is nil") + } + if cfg.AuthenticationInfo == nil { + return fmt.Errorf("SaveProfile: cfg.AuthenticationInfo is required") + } + + toWrite := *cfg + toWrite.Version = ConfigFileVersion + authCopy := *cfg.AuthenticationInfo + toWrite.AuthenticationInfo = &authCopy + if authCopy.CredentialsPath == ProfileCredentialsPath(dir, profile) { + authCopy.CredentialsPath = "" + } + + body, err := json.MarshalIndent(&toWrite, "", " ") + if err != nil { + return fmt.Errorf("SaveProfile: marshal: %w", err) + } + target := ProfilePath(dir, profile) + if err := writeFileAtomic(target, body, publicDirMode, publicFileMode); err != nil { + return fmt.Errorf("SaveProfile: write %q: %w", target, err) + } + return nil +} + +// WriteCredentials persists creds to path atomically. The target file is +// mode 0600 and the parent directory 0700. Callers typically build path +// with [ProfileCredentialsPath]; the signature takes a raw path so tests +// and non-profile layouts can target arbitrary locations. +func WriteCredentials(path string, creds Credentials) error { + if path == "" { + return fmt.Errorf("WriteCredentials: path is empty") + } + body, err := json.MarshalIndent(creds, "", " ") + if err != nil { + return fmt.Errorf("WriteCredentials: marshal: %w", err) + } + if err := writeFileAtomic(path, body, secretDirMode, secretFileMode); err != nil { + return fmt.Errorf("WriteCredentials: write %q: %w", path, err) + } + return nil +} + +// SetActiveProfile writes the active_config pointer under dir so that +// subsequent [LoadConfig] calls (without ANTHROPIC_PROFILE set) resolve +// to profile. The pointer file sits next to configs/ and is written with +// the "public" config modes. +func SetActiveProfile(dir, profile string) error { + if err := validateDirAndProfile(dir, profile); err != nil { + return fmt.Errorf("SetActiveProfile: %w", err) + } + target := ActiveConfigPath(dir) + if err := writeFileAtomic(target, []byte(profile+"\n"), publicDirMode, publicFileMode); err != nil { + return fmt.Errorf("SetActiveProfile: write %q: %w", target, err) + } + return nil +} + +// DeleteProfile removes configs/.json and credentials/.json +// under dir. If active_config currently points at profile, the pointer file +// is also cleared so the next [LoadConfig] call falls back to "default". +// Missing files are not an error — DeleteProfile is idempotent. +func DeleteProfile(dir, profile string) error { + if err := validateDirAndProfile(dir, profile); err != nil { + return fmt.Errorf("DeleteProfile: %w", err) + } + + for _, p := range []string{ + ProfilePath(dir, profile), + ProfileCredentialsPath(dir, profile), + } { + if err := os.Remove(p); err != nil && !os.IsNotExist(err) { + return fmt.Errorf("DeleteProfile: remove %q: %w", p, err) + } + } + + if readActiveConfigPointer(dir) == profile { + if err := os.Remove(ActiveConfigPath(dir)); err != nil && !os.IsNotExist(err) { + return fmt.Errorf("DeleteProfile: clear active_config: %w", err) + } + } + return nil +} + +func readActiveConfigPointer(dir string) string { + data, err := os.ReadFile(ActiveConfigPath(dir)) + if err != nil { + return "" + } + return strings.TrimSpace(string(data)) +} diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/default_http_client.go b/vendor/github.com/anthropics/anthropic-sdk-go/default_http_client.go new file mode 100644 index 000000000..c0d483930 --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/default_http_client.go @@ -0,0 +1,30 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +package anthropic + +import ( + "net/http" + "time" +) + +// defaultResponseHeaderTimeout bounds the time between a fully written request +// and the server's response headers. It does not apply to the response body, +// so long-running streams are unaffected. Without this, a server that accepts +// the connection but never responds would hang the request indefinitely. +const defaultResponseHeaderTimeout = 10 * time.Minute + +// defaultHTTPClient returns an [*http.Client] used when the caller does not +// supply one via [option.WithHTTPClient]. When [http.DefaultTransport] is the +// stdlib [*http.Transport], it is cloned and a [http.Transport.ResponseHeaderTimeout] +// is set so stuck connections fail fast instead of compounding across retries. +// If [http.DefaultTransport] has been wrapped (for example by otelhttp for +// distributed tracing), the wrapping is preserved and the header timeout is +// skipped. +func defaultHTTPClient() *http.Client { + if t, ok := http.DefaultTransport.(*http.Transport); ok { + t = t.Clone() + t.ResponseHeaderTimeout = defaultResponseHeaderTimeout + return &http.Client{Transport: t} + } + return &http.Client{Transport: http.DefaultTransport} +} diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/file.go b/vendor/github.com/anthropics/anthropic-sdk-go/file.go new file mode 100644 index 000000000..fa753eacb --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/file.go @@ -0,0 +1,242 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +package anthropic + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "mime/multipart" + "net/http" + "net/url" + "slices" + "time" + + "github.com/anthropics/anthropic-sdk-go/internal/apiform" + "github.com/anthropics/anthropic-sdk-go/internal/apijson" + "github.com/anthropics/anthropic-sdk-go/internal/apiquery" + "github.com/anthropics/anthropic-sdk-go/internal/requestconfig" + "github.com/anthropics/anthropic-sdk-go/option" + "github.com/anthropics/anthropic-sdk-go/packages/pagination" + "github.com/anthropics/anthropic-sdk-go/packages/param" + "github.com/anthropics/anthropic-sdk-go/packages/respjson" + "github.com/anthropics/anthropic-sdk-go/shared/constant" +) + +// FileService contains methods and other services that help with interacting with +// the anthropic API. +// +// Note, unlike clients, this service does not read variables from the environment +// automatically. You should not instantiate this service directly, and instead use +// the [NewFileService] method instead. +type FileService struct { + Options []option.RequestOption +} + +// NewFileService generates a new service that applies the given options to each +// request. These options are applied after the parent client's options (if there +// is one), and before any request-specific options. +func NewFileService(opts ...option.RequestOption) (r FileService) { + r = FileService{} + r.Options = opts + return +} + +// List Files +func (r *FileService) List(ctx context.Context, query FileListParams, opts ...option.RequestOption) (res *pagination.PageCursor[FileMetadata], err error) { + var raw *http.Response + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithResponseInto(&raw)}, opts...) + path := "v1/files" + cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, query, &res, opts...) + if err != nil { + return nil, err + } + err = cfg.Execute() + if err != nil { + return nil, err + } + res.SetPageConfig(cfg, raw) + return res, nil +} + +// List Files +func (r *FileService) ListAutoPaging(ctx context.Context, query FileListParams, opts ...option.RequestOption) *pagination.PageCursorAutoPager[FileMetadata] { + return pagination.NewPageCursorAutoPager(r.List(ctx, query, opts...)) +} + +// Delete File +func (r *FileService) Delete(ctx context.Context, fileID string, opts ...option.RequestOption) (res *DeletedFile, err error) { + opts = slices.Concat(r.Options, opts) + if fileID == "" { + err = errors.New("missing required file_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/files/%s", fileID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodDelete, path, nil, &res, opts...) + return res, err +} + +// Download File +func (r *FileService) Download(ctx context.Context, fileID string, opts ...option.RequestOption) (res *http.Response, err error) { + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithHeader("Accept", "application/binary")}, opts...) + if fileID == "" { + err = errors.New("missing required file_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/files/%s/content", fileID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...) + return res, err +} + +// Get File Metadata +func (r *FileService) GetMetadata(ctx context.Context, fileID string, opts ...option.RequestOption) (res *FileMetadata, err error) { + opts = slices.Concat(r.Options, opts) + if fileID == "" { + err = errors.New("missing required file_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/files/%s", fileID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...) + return res, err +} + +// Upload File +func (r *FileService) Upload(ctx context.Context, body FileUploadParams, opts ...option.RequestOption) (res *FileMetadata, err error) { + opts = slices.Concat(r.Options, opts) + path := "v1/files" + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...) + return res, err +} + +type DeletedFile struct { + // ID of the deleted file. + ID string `json:"id" api:"required"` + // Deleted object type. + // + // For file deletion, this is always `"file_deleted"`. + // + // Any of "file_deleted". + Type DeletedFileType `json:"type"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r DeletedFile) RawJSON() string { return r.JSON.raw } +func (r *DeletedFile) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Deleted object type. +// +// For file deletion, this is always `"file_deleted"`. +type DeletedFileType string + +const ( + DeletedFileTypeFileDeleted DeletedFileType = "file_deleted" +) + +type FileMetadata struct { + // Unique object identifier. + // + // The format and length of IDs may change over time. + ID string `json:"id" api:"required"` + // RFC 3339 datetime string representing when the file was created. + CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"` + // Original filename of the uploaded file. + Filename string `json:"filename" api:"required"` + // MIME type of the file. + MimeType string `json:"mime_type" api:"required"` + // Size of the file in bytes. + SizeBytes int64 `json:"size_bytes" api:"required"` + // Object type. + // + // For files, this is always `"file"`. + Type constant.File `json:"type" default:"file"` + // Whether the file can be downloaded. + Downloadable bool `json:"downloadable"` + // RFC 3339 datetime string representing when the file will expire and become + // unavailable for download. Null if the file does not expire. For files uploaded + // with `expires_in_seconds`, this is the upload time plus that value. + ExpiresAt time.Time `json:"expires_at" api:"nullable" format:"date-time"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + CreatedAt respjson.Field + Filename respjson.Field + MimeType respjson.Field + SizeBytes respjson.Field + Type respjson.Field + Downloadable respjson.Field + ExpiresAt respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r FileMetadata) RawJSON() string { return r.JSON.raw } +func (r *FileMetadata) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type FileListParams struct { + // Opaque page cursor returned in a prior list response's `next_page`. Prefixed + // `page_`. + Page param.Opt[string] `query:"page,omitzero" json:"-"` + // Number of items to return per page. + // + // Defaults to `20`. Ranges from `1` to `1000`. + Limit param.Opt[int64] `query:"limit,omitzero" json:"-"` + // Restrict the result set to Files whose `id` is in this list. At most 100 entries + // (after de-duplication). Mutually exclusive with `page` and `limit`. When + // supplied, the response is always a single page (`next_page` is null). IDs that + // do not resolve to a visible File — including deleted Files — are silently + // omitted. + IDs []string `query:"ids,omitzero" json:"-"` + paramObj +} + +// URLQuery serializes [FileListParams]'s query parameters as `url.Values`. +func (r FileListParams) URLQuery() (v url.Values, err error) { + return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ + ArrayFormat: apiquery.ArrayQueryFormatBrackets, + NestedFormat: apiquery.NestedQueryFormatBrackets, + }) +} + +type FileUploadParams struct { + // The file to upload + File io.Reader `json:"file,omitzero" api:"required" format:"binary"` + // Seconds from upload until the file expires and its bytes become permanently + // unavailable. Must be between 3600 (one hour) and 7776000 (ninety days). + ExpiresInSeconds param.Opt[int64] `json:"expires_in_seconds,omitzero"` + paramObj +} + +func (r FileUploadParams) MarshalMultipart() (data []byte, contentType string, err error) { + buf := bytes.NewBuffer(nil) + writer := multipart.NewWriter(buf) + err = apiform.MarshalRoot(r, writer) + if err == nil { + err = apiform.WriteExtras(writer, r.ExtraFields()) + } + if err != nil { + writer.Close() + return nil, "", err + } + err = writer.Close() + if err != nil { + return nil, "", err + } + return buf.Bytes(), writer.FormDataContentType(), nil +} diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/internal/apierror/apierror.go b/vendor/github.com/anthropics/anthropic-sdk-go/internal/apierror/apierror.go index a18934b46..e7d442d58 100644 --- a/vendor/github.com/anthropics/anthropic-sdk-go/internal/apierror/apierror.go +++ b/vendor/github.com/anthropics/anthropic-sdk-go/internal/apierror/apierror.go @@ -3,12 +3,14 @@ package apierror import ( + "encoding/json" "fmt" "net/http" "net/http/httputil" "github.com/anthropics/anthropic-sdk-go/internal/apijson" "github.com/anthropics/anthropic-sdk-go/packages/respjson" + "github.com/anthropics/anthropic-sdk-go/shared" ) // Error represents an error that originates from the API, i.e. when a request is @@ -20,18 +22,43 @@ type Error struct { ExtraFields map[string]respjson.Field raw string } `json:"-"` - StatusCode int - Request *http.Request - Response *http.Response - RequestID string + StatusCode int + Request *http.Request + Response *http.Response + RequestID string + WorkspaceID string + + errorType shared.ErrorType } +// Type returns the error type from the API response body, e.g. +// "rate_limit_error" or "overloaded_error". Returns "" if the +// response body did not contain a recognized error type. +func (r *Error) Type() shared.ErrorType { return r.errorType } + // Returns the unmodified JSON received from the API func (r Error) RawJSON() string { return r.JSON.raw } + func (r *Error) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) + if err := apijson.UnmarshalRoot(data, r); err != nil { + return err + } + // Extract error type from the standard {"error":{"type":"..."}} envelope. + var envelope struct { + Error struct { + Type shared.ErrorType `json:"type"` + } `json:"error"` + } + if json.Unmarshal(data, &envelope) == nil { + r.errorType = envelope.Error.Type + } + return nil } +// UnmarshalAPIJSON marks Error as not apijson-native. See +// [apijson.CustomUnmarshaler]. +func (r *Error) UnmarshalAPIJSON(data []byte) error { return r.UnmarshalJSON(data) } + func (r *Error) Error() string { // Attempt to re-populate the response body statusInfo := fmt.Sprintf("%s %q: %d %s", r.Request.Method, r.Request.URL, r.Response.StatusCode, http.StatusText(r.Response.StatusCode)) @@ -39,6 +66,9 @@ func (r *Error) Error() string { if r.RequestID != "" { statusInfo += fmt.Sprintf(" (Request-ID: %s)", r.RequestID) } + if r.WorkspaceID != "" { + statusInfo += fmt.Sprintf(" (Workspace-ID: %s)", r.WorkspaceID) + } return fmt.Sprintf("%s %s", statusInfo, r.JSON.raw) } diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/internal/apiform/encoder.go b/vendor/github.com/anthropics/anthropic-sdk-go/internal/apiform/encoder.go index 2d8e3d08f..bccaab42f 100644 --- a/vendor/github.com/anthropics/anthropic-sdk-go/internal/apiform/encoder.go +++ b/vendor/github.com/anthropics/anthropic-sdk-go/internal/apiform/encoder.go @@ -58,7 +58,7 @@ type encoderField struct { } type encoderEntry struct { - reflect.Type + typ reflect.Type dateFormat string arrayFmt string root bool @@ -76,7 +76,7 @@ func (e *encoder) marshal(value any, writer *multipart.Writer) error { func (e *encoder) typeEncoder(t reflect.Type) encoderFunc { entry := encoderEntry{ - Type: t, + typ: t, dateFormat: e.dateFormat, arrayFmt: e.arrayFmt, root: e.root, diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/internal/apijson/decoder.go b/vendor/github.com/anthropics/anthropic-sdk-go/internal/apijson/decoder.go index 26d15b246..ad4a67d4d 100644 --- a/vendor/github.com/anthropics/anthropic-sdk-go/internal/apijson/decoder.go +++ b/vendor/github.com/anthropics/anthropic-sdk-go/internal/apijson/decoder.go @@ -7,13 +7,14 @@ package apijson import ( "encoding/json" "fmt" - "github.com/anthropics/anthropic-sdk-go/packages/param" "reflect" "strconv" "sync" "time" "unsafe" + "github.com/anthropics/anthropic-sdk-go/packages/param" + "github.com/tidwall/gjson" ) @@ -53,23 +54,6 @@ type decoderState struct { validator *validationEntry } -// Exactness refers to how close to the type the result was if deserialization -// was successful. This is useful in deserializing unions, where you want to try -// each entry, first with strict, then with looser validation, without actually -// having to do a lot of redundant work by marshalling twice (or maybe even more -// times). -type exactness int8 - -const ( - // Some values had to fudged a bit, for example by converting a string to an - // int, or an enum with extra values. - loose exactness = iota - // There are some extra arguments, but other wise it matches the union. - extras - // Exactly right. - exact -) - type decoderFunc func(node gjson.Result, value reflect.Value, state *decoderState) error type decoderField struct { @@ -80,7 +64,7 @@ type decoderField struct { } type decoderEntry struct { - reflect.Type + typ reflect.Type dateFormat string root bool } @@ -89,9 +73,9 @@ func (d *decoderBuilder) unmarshal(raw []byte, to any) error { value := reflect.ValueOf(to).Elem() result := gjson.ParseBytes(raw) if !value.IsValid() { - return fmt.Errorf("apijson: cannot marshal into invalid value") + return fmt.Errorf("apijson: cannot unmarshal into invalid value") } - return d.typeDecoder(value.Type())(result, value, &decoderState{strict: false, exactness: exact}) + return d.typeDecoder(value.Type())(result, value, &decoderState{}) } // unmarshalWithExactness is used for internal testing purposes. @@ -99,16 +83,16 @@ func (d *decoderBuilder) unmarshalWithExactness(raw []byte, to any) (exactness, value := reflect.ValueOf(to).Elem() result := gjson.ParseBytes(raw) if !value.IsValid() { - return 0, fmt.Errorf("apijson: cannot marshal into invalid value") + return exactness{}, fmt.Errorf("apijson: cannot marshal into invalid value") } - state := decoderState{strict: false, exactness: exact} + var state decoderState err := d.typeDecoder(value.Type())(result, value, &state) return state.exactness, err } func (d *decoderBuilder) typeDecoder(t reflect.Type) decoderFunc { entry := decoderEntry{ - Type: t, + typ: t, dateFormat: d.dateFormat, root: d.root, } @@ -163,6 +147,16 @@ func indirectUnmarshalerDecoder(n gjson.Result, v reflect.Value, state *decoderS return v.Addr().Interface().(json.Unmarshaler).UnmarshalJSON([]byte(n.Raw)) } +func customUnmarshalerDecoder(n gjson.Result, v reflect.Value, state *decoderState) error { + if v.Kind() == reflect.Pointer && v.CanSet() { + v.Set(reflect.New(v.Type().Elem())) + } + if u, ok := v.Interface().(CustomUnmarshaler); ok { + return u.UnmarshalAPIJSON([]byte(n.Raw)) + } + return v.Addr().Interface().(CustomUnmarshaler).UnmarshalAPIJSON([]byte(n.Raw)) +} + func unmarshalerDecoder(n gjson.Result, v reflect.Value, state *decoderState) error { if v.Kind() == reflect.Pointer && v.CanSet() { v.Set(reflect.New(v.Type().Elem())) @@ -196,10 +190,15 @@ func (d *decoderBuilder) newDefaultTypeDecoder(t reflect.Type) decoderFunc { return d.newOptTypeDecoder(t) } - if !d.root && t.Implements(reflect.TypeOf((*json.Unmarshaler)(nil)).Elem()) { + if !d.root && implementsCustomUnmarshaler(t) { + return customUnmarshalerDecoder + } + + // apijson-native types are decoded directly; see [isApijsonNative]. + if !d.root && !isApijsonNative(t) && t.Implements(reflect.TypeOf((*json.Unmarshaler)(nil)).Elem()) { return unmarshalerDecoder } - if !d.root && reflect.PointerTo(t).Implements(reflect.TypeOf((*json.Unmarshaler)(nil)).Elem()) { + if !d.root && !isApijsonNative(t) && reflect.PointerTo(t).Implements(reflect.TypeOf((*json.Unmarshaler)(nil)).Elem()) { if _, ok := unionVariants[t]; !ok { return indirectUnmarshalerDecoder } @@ -334,6 +333,10 @@ func (d *decoderBuilder) newStructTypeDecoder(t reflect.Type) decoderFunc { extraDecoder := (*decoderField)(nil) var inlineDecoders []decoderField + // Missing api:"required" fields lower a param variant's rank. + isParam := isParamStruct(t) + requiredCount := 0 + validationEntries := validationRegistry[t] for i := 0; i < t.NumField(); i++ { @@ -392,10 +395,13 @@ func (d *decoderBuilder) newStructTypeDecoder(t reflect.Type) decoderFunc { } } - decoderFields[ptag.name] = decoderField{ - ptag, - d.validatedTypeDecoder(field.Type, validator), - idx, field.Name, + fn := d.validatedTypeDecoder(field.Type, validator) + if def, ok := ptag.defaultValue.(string); ok && field.Type.Kind() == reflect.String { + fn = constantFieldDecoder(fn, def) + } + decoderFields[ptag.name] = decoderField{ptag, fn, idx, field.Name} + if isParam && ptag.required { + requiredCount++ } d.dateFormat = oldFormat @@ -452,6 +458,7 @@ func (d *decoderBuilder) newStructTypeDecoder(t reflect.Type) decoderFunc { typedExtraFields = reflect.MakeMap(typedExtraType) } untypedExtraFields := map[string]Field{} + seenRequired := 0 for fieldName, itemNode := range node.Map() { df, explicit := decoderFields[fieldName] @@ -469,18 +476,26 @@ func (d *decoderBuilder) newStructTypeDecoder(t reflect.Type) decoderFunc { fn = extraDecoder.fn } + // Handle null [param.Opt] + if itemNode.Type == gjson.Null && dest.IsValid() && dest.Type().Implements(reflect.TypeOf((*param.Optional)(nil)).Elem()) { + _ = dest.Addr().Interface().(json.Unmarshaler).UnmarshalJSON([]byte(itemNode.Raw)) + if explicit && df.tag.required { + seenRequired++ + } + continue + } + isValid := false if dest.IsValid() && itemNode.Type != gjson.Null { err = fn(itemNode, dest, state) if err == nil { isValid = true + } else { + state.exactness.noteFieldError() } } - - // Handle null [param.Opt] - if itemNode.Type == gjson.Null && dest.IsValid() && dest.Type().Implements(reflect.TypeOf((*param.Optional)(nil)).Elem()) { - _ = dest.Addr().Interface().(json.Unmarshaler).UnmarshalJSON([]byte(itemNode.Raw)) - continue + if explicit && df.tag.required && isValid { + seenRequired++ } if itemNode.Type == gjson.Null { @@ -515,12 +530,12 @@ func (d *decoderBuilder) newStructTypeDecoder(t reflect.Type) decoderFunc { value.FieldByIndex(extraDecoder.idx).Set(typedExtraFields) } - // Set exactness to 'extras' if there are untyped, extra fields. - if len(untypedExtraFields) > 0 && state.exactness > extras { - state.exactness = extras + if seenRequired < requiredCount { + state.exactness.noteRequiredMissing(requiredCount - seenRequired) } if len(untypedExtraFields) > 0 { + state.exactness.noteExtras() setMetadataExtraFields(value, []int{-1}, "ExtraFields", untypedExtraFields) } return nil @@ -683,7 +698,7 @@ func guardStrict(state *decoderState, cond bool) bool { return true } - state.exactness = loose + state.exactness.noteCoercion() return false } @@ -692,14 +707,25 @@ func canParseAsNumber(str string) bool { return err == nil } -var stringType = reflect.TypeOf(string("")) - func guardUnknown(state *decoderState, v reflect.Value) bool { - if have, ok := v.Interface().(interface{ IsKnown() bool }); guardStrict(state, ok && !have.IsKnown()) { - return true + if have, ok := v.Interface().(interface{ IsKnown() bool }); ok && !have.IsKnown() { + state.exactness.noteCoercion() } + return false +} - constantString, ok := v.Interface().(interface{ Default() string }) - named := v.Type() != stringType - return guardStrict(state, ok && named && v.Equal(reflect.ValueOf(constantString.Default()))) +// To feed union variant selection, record whether a constant field +// matched its default. +func constantFieldDecoder(inner decoderFunc, def string) decoderFunc { + return func(n gjson.Result, v reflect.Value, state *decoderState) error { + if err := inner(n, v, state); err != nil { + return err + } + if v.String() == def { + state.exactness.noteConstMatch() + } else { + state.exactness.noteConstMismatch() + } + return nil + } } diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/internal/apijson/encoder.go b/vendor/github.com/anthropics/anthropic-sdk-go/internal/apijson/encoder.go index 3d8b198b9..25262ea55 100644 --- a/vendor/github.com/anthropics/anthropic-sdk-go/internal/apijson/encoder.go +++ b/vendor/github.com/anthropics/anthropic-sdk-go/internal/apijson/encoder.go @@ -46,7 +46,7 @@ type encoderField struct { } type encoderEntry struct { - reflect.Type + typ reflect.Type dateFormat string root bool } @@ -63,7 +63,7 @@ func (e *encoder) marshal(value any) ([]byte, error) { func (e *encoder) typeEncoder(t reflect.Type) encoderFunc { entry := encoderEntry{ - Type: t, + typ: t, dateFormat: e.dateFormat, root: e.root, } diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/internal/apijson/enum.go b/vendor/github.com/anthropics/anthropic-sdk-go/internal/apijson/enum.go index a1626a574..5bf77521d 100644 --- a/vendor/github.com/anthropics/anthropic-sdk-go/internal/apijson/enum.go +++ b/vendor/github.com/anthropics/anthropic-sdk-go/internal/apijson/enum.go @@ -88,7 +88,7 @@ func (state *decoderState) validateString(v reflect.Value) { return } if !slices.Contains(state.validator.legalValues.strings, v.String()) { - state.exactness = loose + state.exactness.noteCoercion() } } @@ -97,7 +97,7 @@ func (state *decoderState) validateInt(v reflect.Value) { return } if !slices.Contains(state.validator.legalValues.ints, v.Int()) { - state.exactness = loose + state.exactness.noteCoercion() } } @@ -107,21 +107,21 @@ func (state *decoderState) validateBool(v reflect.Value) { } b := v.Bool() if state.validator.legalValues.bools == 1 && !b { - state.exactness = loose + state.exactness.noteCoercion() } else if state.validator.legalValues.bools == 0 && b { - state.exactness = loose + state.exactness.noteCoercion() } } func (state *decoderState) validateOptKind(node gjson.Result, t reflect.Type) { switch node.Type { case gjson.JSON: - state.exactness = loose + state.exactness.noteCoercion() case gjson.Null: return case gjson.False, gjson.True: if t.Kind() != reflect.Bool { - state.exactness = loose + state.exactness.noteCoercion() } case gjson.Number: switch t.Kind() { @@ -130,11 +130,11 @@ func (state *decoderState) validateOptKind(node gjson.Result, t reflect.Type) { reflect.Float32, reflect.Float64: return default: - state.exactness = loose + state.exactness.noteCoercion() } case gjson.String: if t.Kind() != reflect.String { - state.exactness = loose + state.exactness.noteCoercion() } } } diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/internal/apijson/exactness.go b/vendor/github.com/anthropics/anthropic-sdk-go/internal/apijson/exactness.go new file mode 100644 index 000000000..37a01d623 --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/internal/apijson/exactness.go @@ -0,0 +1,66 @@ +package apijson + +// exactness ranks union variants by how well the input fit. A variant +// whose constants all match (constHit) is picked outright; among the +// rest, structural fit decides. +type exactness struct { + constMatch uint32 + constMismatch uint32 + + requiredMissing uint32 + fieldErrors uint32 + coercions uint32 + extras fitExtra +} + +type fitExtra uint8 + +const ( + noExtras fitExtra = iota + hasExtras +) + +func (e *exactness) noteConstMatch() { e.constMatch++ } +func (e *exactness) noteConstMismatch() { e.constMismatch++ } +func (e *exactness) noteRequiredMissing(n int) { e.requiredMissing += uint32(n) } +func (e *exactness) noteFieldError() { e.fieldErrors++ } +func (e *exactness) noteCoercion() { e.coercions++ } +func (e *exactness) noteExtras() { e.extras = hasExtras } + +func (e exactness) constHit() bool { + return e.constMismatch == 0 && e.constMatch > 0 +} + +func (e exactness) perfect() bool { + e.constMatch = 0 + return e == exactness{} +} + +func (e exactness) betterThan(o exactness) bool { + if h, oh := e.constHit(), o.constHit(); h != oh { + return h + } + if e.constMatch != o.constMatch { + return e.constMatch > o.constMatch + } + if e.requiredMissing != o.requiredMissing { + return e.requiredMissing < o.requiredMissing + } + if e.fieldErrors != o.fieldErrors { + return e.fieldErrors < o.fieldErrors + } + if e.coercions != o.coercions { + return e.coercions < o.coercions + } + return e.extras < o.extras +} + +// absorb folds a child union's fit into its parent. +func (e *exactness) absorb(o exactness) { + e.requiredMissing += o.requiredMissing + e.fieldErrors += o.fieldErrors + e.coercions += o.coercions + if o.extras > e.extras { + e.extras = o.extras + } +} diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/internal/apijson/union.go b/vendor/github.com/anthropics/anthropic-sdk-go/internal/apijson/union.go index 78ed921f8..2da5d9841 100644 --- a/vendor/github.com/anthropics/anthropic-sdk-go/internal/apijson/union.go +++ b/vendor/github.com/anthropics/anthropic-sdk-go/internal/apijson/union.go @@ -2,13 +2,93 @@ package apijson import ( "errors" - "github.com/anthropics/anthropic-sdk-go/packages/param" "reflect" + "sync" + + "github.com/anthropics/anthropic-sdk-go/packages/param" "github.com/tidwall/gjson" ) var apiUnionType = reflect.TypeOf(param.APIUnion{}) +var apiObjectType = reflect.TypeOf(param.APIObject{}) + +var nativeTypeCache sync.Map // map[reflect.Type]bool + +// CustomUnmarshaler indicates that a type is not "apijson native". +// apijson native types use the custom [json.Unmarshaler] only as an entry +// point, and therefore are skipped when nested. +type CustomUnmarshaler interface { + UnmarshalAPIJSON([]byte) error +} + +var customUnmarshalerType = reflect.TypeOf((*CustomUnmarshaler)(nil)).Elem() + +func implementsCustomUnmarshaler(t reflect.Type) bool { + return t.Implements(customUnmarshalerType) || reflect.PointerTo(t).Implements(customUnmarshalerType) +} + +// isApijsonNative reports whether t is a generated struct whose +// UnmarshalJSON is the trivial delegation to [UnmarshalRoot], therefore +// the UnmarshalJSON function can be skipped for nested values. +func isApijsonNative(t reflect.Type) bool { + if cached, ok := nativeTypeCache.Load(t); ok { + return cached.(bool) + } + native := computeApijsonNative(t) + nativeTypeCache.Store(t, native) + return native +} + +func computeApijsonNative(t reflect.Type) bool { + for t.Kind() == reflect.Pointer { + t = t.Elem() + } + if t.Kind() != reflect.Struct { + return false + } + if implementsCustomUnmarshaler(t) { + return false + } + if isParamStruct(t) || isStructUnion(t) { + return true + } + if f, ok := t.FieldByName("JSON"); ok && f.Type.Kind() == reflect.Struct { + if _, ok := f.Type.FieldByName("raw"); ok { + return true + } + } + return false +} + +var paramObjectIdxCache sync.Map // map[reflect.Type]int + +func paramObjectIndex(t reflect.Type) int { + return paramEmbedIndex(t, apiObjectType, ¶mObjectIdxCache) +} + +func paramEmbedIndex(t reflect.Type, embed reflect.Type, cache *sync.Map) int { + if cached, ok := cache.Load(t); ok { + return cached.(int) + } + idx := -1 + if t.Kind() == reflect.Struct { + for i := 0; i < t.NumField(); i++ { + f := t.Field(i) + if f.Anonymous && f.Type == embed { + idx = i + break + } + } + } + cache.Store(t, idx) + return idx +} + +// isParamStruct reports whether t is a generated request param struct. +func isParamStruct(t reflect.Type) bool { + return paramObjectIndex(t) >= 0 +} func isStructUnion(t reflect.Type) bool { if t.Kind() != reflect.Struct { @@ -37,26 +117,74 @@ func RegisterDiscriminatedUnion[T any](key string, mappings map[string]reflect.T unionRegistry[reflect.TypeOf(t)] = entry } +// deriveDiscriminator picks the `default:`-tagged field whose values +// route the most variants uniquely, and returns that field's JSON +// name plus a value→variant-index map. +func deriveDiscriminator(variants []reflect.StructField) (key string, index map[string]int) { + byKey := map[string]map[string]int{} + for idx, v := range variants { + t := v.Type + for t.Kind() == reflect.Ptr { + t = t.Elem() + } + if t.Kind() != reflect.Struct { + continue + } + for i := 0; i < t.NumField(); i++ { + ptag, ok := parseJSONStructTag(t.Field(i)) + if !ok { + continue + } + def, ok := ptag.defaultValue.(string) + if !ok { + continue + } + m := byKey[ptag.name] + if m == nil { + m = map[string]int{} + byKey[ptag.name] = m + } + if _, dup := m[def]; dup { + m[def] = -1 + } else { + m[def] = idx + } + } + } + for k, m := range byKey { + usable := map[string]int{} + for v, idx := range m { + if idx >= 0 { + usable[v] = idx + } + } + if len(usable) > len(index) || (len(usable) == len(index) && k < key) { + key, index = k, usable + } + } + return key, index +} + func (d *decoderBuilder) newStructUnionDecoder(t reflect.Type) decoderFunc { type variantDecoder struct { decoder decoderFunc field reflect.StructField } - decoders := []variantDecoder{} + var decoders []variantDecoder + var fields []reflect.StructField for i := 0; i < t.NumField(); i++ { field := t.Field(i) - if field.Anonymous && field.Type == apiUnionType { continue } - - decoder := d.typeDecoder(field.Type) - decoders = append(decoders, variantDecoder{ - decoder: decoder, - field: field, - }) + decoders = append(decoders, variantDecoder{d.typeDecoder(field.Type), field}) + fields = append(fields, field) } + // To more performantly pick the correct variant, derive a + // discriminator from the `default:` tags. + discrimKey, discrimIndex := deriveDiscriminator(fields) + type discriminatedDecoder struct { variantDecoder discriminator any @@ -88,8 +216,19 @@ func (d *decoderBuilder) newStructUnionDecoder(t reflect.Type) decoderFunc { return errors.New("apijson: was not able to find discriminated union variant") } - // Set bestExactness to worse than loose - bestExactness := loose - 1 + scanned := discrimKey != "" && n.Type == gjson.JSON + if scanned { + if i, ok := discrimIndex[n.Get(EscapeSJSONKey(discrimKey)).String()]; ok { + sub := decoderState{strict: state.strict} + inner := v.FieldByIndex(decoders[i].field.Index) + if decoders[i].decoder(n, inner, &sub) == nil { + state.exactness.absorb(sub.exactness) + return nil + } + } + } + + var best exactness bestVariant := -1 for i, decoder := range decoders { // Pointers are used to discern JSON object variants from value variants @@ -97,30 +236,29 @@ func (d *decoderBuilder) newStructUnionDecoder(t reflect.Type) decoderFunc { continue } - sub := decoderState{strict: state.strict, exactness: exact} + sub := decoderState{strict: state.strict} inner := v.FieldByIndex(decoder.field.Index) - err := decoder.decoder(n, inner, &sub) - if err != nil { + if err := decoder.decoder(n, inner, &sub); err != nil { continue } - if sub.exactness == exact { - bestExactness = exact - bestVariant = i - break - } - if sub.exactness > bestExactness { - bestExactness = sub.exactness - bestVariant = i + if bestVariant < 0 || sub.exactness.betterThan(best) { + best, bestVariant = sub.exactness, i + // A perfect fit cannot be beaten once the discriminator + // scan (or the fit itself) has ruled out a later hit. + if best.perfect() && (scanned || best.constHit()) { + break + } } } - if bestExactness < loose { + if bestVariant < 0 { return errors.New("apijson: was not able to coerce type as union") } - if guardStrict(state, bestExactness != exact) { + if state.strict && !best.perfect() { return errors.New("apijson: was not able to coerce type as union strictly") } + state.exactness.absorb(best) for i := 0; i < len(decoders); i++ { if i == bestVariant { @@ -172,36 +310,37 @@ func (d *decoderBuilder) newUnionDecoder(t reflect.Type) decoderFunc { } } - // Set bestExactness to worse than loose - bestExactness := loose - 1 + var bestExactness exactness + found := false for idx, variant := range unionEntry.variants { decoder := decoders[idx] if variant.TypeFilter != n.Type { continue } - sub := decoderState{strict: state.strict, exactness: exact} + sub := decoderState{strict: state.strict} inner := reflect.New(variant.Type).Elem() err := decoder(n, inner, &sub) if err != nil { continue } - if sub.exactness == exact { - v.Set(inner) - return nil - } - if sub.exactness > bestExactness { + if !found || sub.exactness.betterThan(bestExactness) { v.Set(inner) bestExactness = sub.exactness + found = true + if bestExactness.constHit() && bestExactness.perfect() { + return nil + } } } - if bestExactness < loose { + if !found { return errors.New("apijson: was not able to coerce type as union") } - if guardStrict(state, bestExactness != exact) { + if state.strict && !bestExactness.perfect() { return errors.New("apijson: was not able to coerce type as union strictly") } + state.exactness.absorb(bestExactness) return nil } diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/internal/apiquery/encoder.go b/vendor/github.com/anthropics/anthropic-sdk-go/internal/apiquery/encoder.go index d04379078..7cbb5dd6d 100644 --- a/vendor/github.com/anthropics/anthropic-sdk-go/internal/apiquery/encoder.go +++ b/vendor/github.com/anthropics/anthropic-sdk-go/internal/apiquery/encoder.go @@ -29,7 +29,7 @@ type encoderField struct { } type encoderEntry struct { - reflect.Type + typ reflect.Type dateFormat string root bool settings QuerySettings @@ -42,7 +42,7 @@ type Pair struct { func (e *encoder) typeEncoder(t reflect.Type) encoderFunc { entry := encoderEntry{ - Type: t, + typ: t, dateFormat: e.dateFormat, root: e.root, settings: e.settings, diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/internal/auth/cache.go b/vendor/github.com/anthropics/anthropic-sdk-go/internal/auth/cache.go new file mode 100644 index 000000000..708d61e23 --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/internal/auth/cache.go @@ -0,0 +1,227 @@ +package auth + +import ( + "context" + "net/http" + "sync" + "time" +) + +// advisoryRefreshBackoff caps how often a failed background refresh will +// re-run in the advisory window. Without this, a token endpoint that is +// down during the advisory window would be re-hit at request rate until +// the mandatory threshold is crossed. +const advisoryRefreshBackoff = 5 * time.Second + +// TokenCache wraps a [TokenProvider] with two-tier proactive refresh and +// thread-safe caching. +// +// Refresh tiers: +// - No cached token: fetch synchronously +// - ExpiresAt == nil: cache forever +// - More than [AdvisoryRefreshThreshold] remaining: return cached +// - Between mandatory and advisory thresholds: try background refresh; +// on failure, return the stale token +// - Less than [MandatoryRefreshThreshold] remaining or expired: refresh +// synchronously; on failure, return the error +// +// A cached token is scoped to the baseURL it was minted for: if a caller +// passes a different baseURL to a subsequent [TokenCache.Token] call, the +// cached token is discarded so a token issued by one environment can never +// be served for a request going to another. +type TokenCache struct { + provider TokenProvider + httpHandler func(*http.Request) (*http.Response, error) + + mu sync.Mutex + cached *AccessToken + cachedBaseURL string + refresh *refreshState + lastAdvisoryError time.Time +} + +type refreshState struct { + done chan struct{} + token *AccessToken + err error +} + +// NewTokenCache returns a [TokenCache] that delegates to the given provider. +// The handler is passed through to the provider on every fetch; the base URL +// to exchange at is supplied per call to [TokenCache.Token]. +func NewTokenCache(provider TokenProvider, handler func(*http.Request) (*http.Response, error)) *TokenCache { + return &TokenCache{provider: provider, httpHandler: handler} +} + +// Token returns a valid access token, fetching or refreshing via the provider +// if necessary. baseURL is forwarded to the provider for token-exchange / +// refresh HTTP calls; a fresh cached token bypasses the provider entirely. +func (cache *TokenCache) Token(ctx context.Context, baseURL string) (string, error) { + if ok, token := cache.check(ctx, baseURL); ok { + return token, nil + } + return cache.fetch(ctx, baseURL) +} + +// ForceToken is like [TokenCache.Token] but signals token providers that +// maintain their own caches (e.g., file-backed credential loaders) to bypass +// them and re-exchange the underlying credential. Call this after a 401 has +// invalidated the in-memory cache, so a stale on-disk token can't re-surface +// for the retry. +func (cache *TokenCache) ForceToken(ctx context.Context, baseURL string) (string, error) { + return cache.Token(withForceRefresh(ctx), baseURL) +} + +// Invalidate drops the in-memory cache so the next call to [TokenCache.Token] +// re-enters the provider. Pair with [TokenCache.ForceToken] on the retry path +// to also bypass provider-side caches. Returns true if there was a cached +// token to drop. +func (cache *TokenCache) Invalidate() bool { + cache.mu.Lock() + defer cache.mu.Unlock() + if cache.cached == nil { + return false + } + cache.cached = nil + cache.cachedBaseURL = "" + return true +} + +// check inspects the cached token under the lock and returns whether +// the caller can use it directly or must fetch a new one. +func (cache *TokenCache) check(ctx context.Context, baseURL string) (bool, string) { + cache.mu.Lock() + defer cache.mu.Unlock() + + if cache.cached == nil { + return false, "" + } + + // Scope cached tokens to the baseURL they were minted for. + if cache.cachedBaseURL != baseURL { + cache.cached = nil + cache.cachedBaseURL = "" + return false, "" + } + + if cache.cached.ExpiresAt == nil { + // No expiry. Cache forever. + return true, cache.cached.Token + } + + remaining := time.Until(*cache.cached.ExpiresAt) + + if remaining > AdvisoryRefreshThreshold { + // Fresh enough. Use the cached token. + return true, cache.cached.Token + } + + if remaining > MandatoryRefreshThreshold { + // Advisory window. Kick off background refresh (subject to backoff + // on repeated failure), return stale. + if time.Since(cache.lastAdvisoryError) >= advisoryRefreshBackoff { + cache.startBackgroundRefresh(ctx, baseURL) + } + return true, cache.cached.Token + } + + // Mandatory window or expired. + return false, "" +} + +// fetch performs a synchronous token fetch. If another goroutine is already +// fetching, it waits for that result instead of starting a duplicate. Callers +// in the mandatory window (the only callers that reach fetch) never receive +// a stale token: if the refresh fails, the error propagates. +func (cache *TokenCache) fetch(ctx context.Context, baseURL string) (string, error) { + isFetcher, refresh := cache.getOrStartRefresh() + if !isFetcher { + return awaitRefresh(ctx, refresh) + } + + token, err := cache.provider(ctx, baseURL, cache.httpHandler) + cache.completeRefresh(refresh, baseURL, token, err, false) + if err != nil { + return "", err + } + return token.Token, nil +} + +// getOrStartRefresh returns the in-flight refresh if one exists, or starts a +// new one. The bool indicates whether the caller is the fetcher. +func (cache *TokenCache) getOrStartRefresh() (bool, *refreshState) { + cache.mu.Lock() + defer cache.mu.Unlock() + + if refresh := cache.refresh; refresh != nil { + return false, refresh + } + + refresh := &refreshState{done: make(chan struct{})} + cache.refresh = refresh + return true, refresh +} + +// awaitRefresh blocks until the in-flight refresh completes and returns its +// result. Piggy-backing callers never receive a stale token on failure; they +// are by construction in the mandatory window, where stale is unacceptable. +func awaitRefresh(ctx context.Context, refresh *refreshState) (string, error) { + select { + case <-refresh.done: + case <-ctx.Done(): + return "", ctx.Err() + } + if refresh.err != nil { + return "", refresh.err + } + return refresh.token.Token, nil +} + +// completeRefresh records the result of a fetch, updates the cache, and +// signals all waiters. advisory indicates whether this refresh ran in the +// advisory (background) window — on failure, advisory refreshes arm the +// backoff instead of propagating the error. +func (cache *TokenCache) completeRefresh(refresh *refreshState, baseURL string, token *AccessToken, err error, advisory bool) { + cache.mu.Lock() + defer cache.mu.Unlock() + refresh.token = token + refresh.err = err + if err == nil { + cache.cached = token + cache.cachedBaseURL = baseURL + cache.lastAdvisoryError = time.Time{} + } else if advisory { + cache.lastAdvisoryError = time.Now() + } + cache.refresh = nil + close(refresh.done) +} + +// startBackgroundRefresh kicks off an advisory background refresh if one isn't +// already in-flight. Must be called with mu held. +func (cache *TokenCache) startBackgroundRefresh(ctx context.Context, baseURL string) { + if cache.refresh != nil { + return + } + + refresh := &refreshState{done: make(chan struct{})} + cache.refresh = refresh + + go func() { + token, err := cache.provider(context.WithoutCancel(ctx), baseURL, cache.httpHandler) + cache.completeRefresh(refresh, baseURL, token, err, true) + }() +} + +type forceRefreshKey struct{} + +func withForceRefresh(ctx context.Context) context.Context { + return context.WithValue(ctx, forceRefreshKey{}, true) +} + +// isForceRefresh reports whether ctx carries a force-refresh signal. Token +// providers that maintain their own caches should skip them when true. +func isForceRefresh(ctx context.Context) bool { + v, _ := ctx.Value(forceRefreshKey{}).(bool) + return v +} diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/internal/auth/constants.go b/vendor/github.com/anthropics/anthropic-sdk-go/internal/auth/constants.go new file mode 100644 index 000000000..7adbfa060 --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/internal/auth/constants.go @@ -0,0 +1,38 @@ +package auth + +import ( + "time" + + "github.com/anthropics/anthropic-sdk-go/config" +) + +// OAuth wire-contract constants live in the public config package so the +// SDK has a single source of truth. Re-exported here as local aliases so +// auth code can reference them without a package qualifier. +const ( + GrantTypeJWTBearer = config.GrantTypeJWTBearer + GrantTypeRefreshToken = config.GrantTypeRefreshToken + + TokenEndpoint = config.TokenEndpoint + + // FederationBetaHeader is sent on requests to the oauth/token endpoint + // during federation token exchange. + FederationBetaHeader = config.FederationBetaHeader + + // OAuthAPIBetaHeader is sent on authenticated API requests that use a + // bearer token obtained via OAuth/federation, and on refresh_token + // grants against the token endpoint. + OAuthAPIBetaHeader = config.OAuthAPIBetaHeader +) + +const ( + AdvisoryRefreshThreshold = 120 * time.Second + MandatoryRefreshThreshold = 30 * time.Second + + EnvIdentityToken = "ANTHROPIC_IDENTITY_TOKEN" + EnvIdentityTokenFile = "ANTHROPIC_IDENTITY_TOKEN_FILE" + EnvFederationRuleID = "ANTHROPIC_FEDERATION_RULE_ID" + EnvOrganizationID = "ANTHROPIC_ORGANIZATION_ID" + EnvServiceAccountID = "ANTHROPIC_SERVICE_ACCOUNT_ID" + EnvWorkspaceID = "ANTHROPIC_WORKSPACE_ID" +) diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/internal/auth/credentials_file.go b/vendor/github.com/anthropics/anthropic-sdk-go/internal/auth/credentials_file.go new file mode 100644 index 000000000..1eb768c61 --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/internal/auth/credentials_file.go @@ -0,0 +1,363 @@ +package auth + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "io/fs" + "net/http" + "os" + "runtime" + "strings" + "time" + + "github.com/anthropics/anthropic-sdk-go/config" + "github.com/anthropics/anthropic-sdk-go/internal" +) + +// Credentials file schema — credentials/.json. Reads only; all writes +// go through config.WriteCredentials for a single-source-of-truth on the +// atomic + fsync + Chmod guarantees. +type credentialsTokenData struct { + Type string `json:"type"` + AccessToken string `json:"access_token"` + ExpiresAt *int64 `json:"expires_at,omitempty"` + RefreshToken string `json:"refresh_token,omitempty"` +} + +func readCredentialsFile(path string) (*credentialsTokenData, error) { + if err := checkCredentialsFileSafety(path); err != nil { + return nil, err + } + data, err := os.ReadFile(path) + if err != nil { + return nil, err + } + var cred credentialsTokenData + if err := json.Unmarshal(data, &cred); err != nil { + return nil, err + } + return &cred, nil +} + +// checkCredentialsFileSafety refuses credentials files exposed to other +// UIDs on the host. Symlinks could redirect a refresh-token write; any +// mode&0o077 bit lets another UID read or inject a token. Mode bits are +// not meaningful on Windows, so that check is skipped there. +func checkCredentialsFileSafety(path string) error { + info, err := os.Lstat(path) + if err != nil { + return err + } + if info.Mode().Type()&fs.ModeSymlink != 0 { + return fmt.Errorf("credentials file %q is a symlink; refusing to read (set ANTHROPIC_CREDENTIALS_PATH to the real file)", path) + } + if runtime.GOOS == "windows" { + return nil + } + mode := info.Mode().Perm() + if mode&0o077 != 0 { + return fmt.Errorf("credentials file %q has unsafe permissions %#o; refusing to read (must not be accessible by group or other; chmod 600 %s)", path, mode, path) + } + return nil +} + +// freshAccessToken returns a non-nil [AccessToken] only when the credentials +// contain a non-empty token that won't expire within [MandatoryRefreshThreshold]. +// If ExpiresAt is nil the token is treated as non-expiring. +func (cred *credentialsTokenData) freshAccessToken() *AccessToken { + if cred.AccessToken == "" { + return nil + } + if cred.ExpiresAt != nil { + exp := time.Unix(*cred.ExpiresAt, 0) + if time.Until(exp) <= MandatoryRefreshThreshold { + return nil + } + return &AccessToken{Token: cred.AccessToken, ExpiresAt: &exp} + } + return &AccessToken{Token: cred.AccessToken} +} + +// ResolveCredentials builds a [CredentialsResult] from a [config.Config]. +// The [AuthenticationInfo.CredentialsPath] must already be resolved to an +// absolute path (or left empty if credentials are not file-based). +func ResolveCredentials(cfg *config.Config) (*CredentialsResult, error) { + if cfg.AuthenticationInfo == nil { + return nil, &CredentialResolutionError{ + Message: "config is missing authentication", + } + } + switch cfg.AuthenticationInfo.Type { + case config.AuthenticationTypeOIDCFederation: + return loadOIDCFederationProfile(cfg) + case config.AuthenticationTypeUserOAuth: + return loadUserOAuthProfile(cfg) + default: + return nil, &CredentialResolutionError{ + Message: fmt.Sprintf("unknown authentication.type %q", cfg.AuthenticationInfo.Type), + } + } +} + +func loadOIDCFederationProfile(cfg *config.Config) (*CredentialsResult, error) { + oidc := cfg.AuthenticationInfo.OIDCFederation + if oidc == nil { + return nil, &CredentialResolutionError{ + Message: "oidc_federation config missing oidc_federation sub-object", + } + } + if oidc.FederationRuleID == "" || cfg.OrganizationID == "" { + return nil, &CredentialResolutionError{ + Message: "oidc_federation config missing federation_rule_id or organization_id", + } + } + + var identityProvider IdentityTokenProvider + switch { + case oidc.IdentityToken != nil: + if oidc.IdentityToken.Source != config.IdentityTokenSourceFile { + return nil, &CredentialResolutionError{ + Message: fmt.Sprintf("oidc_federation identity_token.source %q is not supported (only %q)", oidc.IdentityToken.Source, config.IdentityTokenSourceFile), + } + } + if oidc.IdentityToken.Path == "" { + return nil, &CredentialResolutionError{ + Message: fmt.Sprintf("oidc_federation identity_token.source %q requires a non-empty path", config.IdentityTokenSourceFile), + } + } + identityProvider = &IdentityTokenFile{Path: oidc.IdentityToken.Path} + default: + identityProvider = identityProviderFromEnv() + if identityProvider == nil { + return nil, &CredentialResolutionError{ + Message: fmt.Sprintf("oidc_federation config requires identity_token with source %q, or %s / %s environment variable", config.IdentityTokenSourceFile, EnvIdentityTokenFile, EnvIdentityToken), + } + } + } + + exchangeProvider := NewOIDCFederationCredentials(OIDCFederationConfig{ + IdentityProvider: identityProvider, + FederationRuleID: oidc.FederationRuleID, + OrganizationID: cfg.OrganizationID, + ServiceAccountID: oidc.ServiceAccountID, + WorkspaceID: cfg.WorkspaceID, + BaseURL: cfg.BaseURL, + }) + + credPath := cfg.AuthenticationInfo.CredentialsPath + + // Wrap with cache-aware provider that checks the credentials file first. + provider := func(ctx context.Context, baseURL string, handler func(*http.Request) (*http.Response, error)) (*AccessToken, error) { + // Try cached credentials file, unless the caller signaled a force- + // refresh (e.g. after a 401 invalidation in the auth middleware). + if !isForceRefresh(ctx) { + if cred, err := readCredentialsFile(credPath); err == nil { + if token := cred.freshAccessToken(); token != nil { + return token, nil + } + } else if !os.IsNotExist(err) { + warnOnce("workload-cache-read:"+credPath, + "failed to read workload-identity token cache %q: %v (continuing with fresh exchange)", credPath, err) + } + } + + // Exchange for a new token. + token, err := exchangeProvider(ctx, baseURL, handler) + if err != nil { + return nil, err + } + + // Write cache back (best-effort; log once on failure so a misconfigured + // cache directory does not cause a silent exchange-per-request loop). + if token.ExpiresAt != nil { + cacheData := config.Credentials{ + AccessToken: token.Token, + ExpiresAt: token.ExpiresAt, + } + if writeErr := config.WriteCredentials(credPath, cacheData); writeErr != nil { + warnOnce("workload-cache-write:"+credPath, + "failed to write workload-identity token cache %q: %v", credPath, writeErr) + } + } + + return token, nil + } + + // For federation profiles workspace_id is sent in the jwt-bearer + // exchange body, not as a request header (the minted token is already + // workspace-scoped, so the header would be ignored). WorkspaceID is + // therefore intentionally omitted from the CredentialsResult here. + return &CredentialsResult{ + Provider: provider, + BaseURL: cfg.BaseURL, + }, nil +} + +func loadUserOAuthProfile(cfg *config.Config) (*CredentialsResult, error) { + userOAuth := cfg.AuthenticationInfo.UserOAuth + if userOAuth == nil { + return nil, &CredentialResolutionError{ + Message: "user_oauth config missing user_oauth sub-object", + } + } + + credPath := cfg.AuthenticationInfo.CredentialsPath + cred, err := readCredentialsFile(credPath) + if err != nil { + return nil, &CredentialResolutionError{ + Message: fmt.Sprintf("failed to read credentials file %q", credPath), + Err: err, + } + } + + if cred.AccessToken == "" { + return nil, &CredentialResolutionError{ + Message: fmt.Sprintf("user_oauth credentials in %q missing access_token", credPath), + } + } + + if userOAuth.ClientID == "" { + // Without a client_id we cannot refresh. Fail fast on an already- + // expired token so callers get a clean error instead of a 401-retry + // loop until maxRetries on a silently stale bearer. + if cred.freshAccessToken() == nil { + return nil, &CredentialResolutionError{ + Message: fmt.Sprintf("user_oauth credentials in %q: access_token is expired or missing and no refresh is available (client_id is empty)", credPath), + } + } + // Re-read on every call so externally-rotated tokens (e.g. from a + // credential daemon) are picked up. + staticProvider := func(_ context.Context, _ string, _ func(*http.Request) (*http.Response, error)) (*AccessToken, error) { + current, err := readCredentialsFile(credPath) + if err != nil { + return nil, fmt.Errorf("failed to read credentials file %q: %w", credPath, err) + } + token := current.freshAccessToken() + if token == nil { + return nil, fmt.Errorf("user_oauth credentials in %q: access_token is expired or missing and no refresh is available (client_id is empty)", credPath) + } + return token, nil + } + return &CredentialsResult{ + Provider: staticProvider, + BaseURL: cfg.BaseURL, + WorkspaceID: cfg.WorkspaceID, + }, nil + } + + if cred.RefreshToken == "" { + return nil, &CredentialResolutionError{ + Message: fmt.Sprintf("user_oauth credentials in %q has client_id in config but missing refresh_token", credPath), + } + } + + provider := func(ctx context.Context, baseURL string, handler func(*http.Request) (*http.Response, error)) (*AccessToken, error) { + base := strings.TrimRight(cfg.BaseURL, "/") + if base == "" { + base = strings.TrimRight(baseURL, "/") + } + if err := requireSecureTokenEndpoint(base); err != nil { + return nil, err + } + // Re-read credentials file to check if token is still fresh. Skip + // the freshness shortcut when force-refresh is signaled (e.g. after + // a 401 in the auth middleware). + current, err := readCredentialsFile(credPath) + if err != nil { + return nil, fmt.Errorf("failed to read credentials file %q: %w", credPath, err) + } + if !isForceRefresh(ctx) { + if token := current.freshAccessToken(); token != nil { + return token, nil + } + } + + // Refresh the token. `scope` is intentionally omitted: the Python + // oauth-server preserves the original token's full scope set when + // scope is absent on the request (see the early-return in + // api/api/oauth_server/oauth/grants/refresh_token_grant.py). + refreshReq := map[string]string{ + "grant_type": GrantTypeRefreshToken, + "refresh_token": current.RefreshToken, + "client_id": userOAuth.ClientID, + } + refreshBody, _ := json.Marshal(refreshReq) + + endpoint := base + TokenEndpoint + req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(refreshBody)) + if err != nil { + return nil, fmt.Errorf("failed to create refresh request: %w", err) + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("User-Agent", "anthropic-sdk-go/"+internal.PackageVersion+" (user-oauth-refresh)") + // The oauth-2025-04-20 beta is required by the Python oauth-server + // to accept refresh-token grants for user_oauth credentials. + // + // Do NOT add FederationBetaHeader here. POST /v1/oauth/token is + // gateway-routed: with oidc-federation-2026-04-01 present it goes + // to the Go userauth service, which only handles the jwt-bearer + // grant. Refresh-token grants must fall through to the Python + // oauth-server, where the federation beta must be absent. + req.Header.Set("anthropic-beta", OAuthAPIBetaHeader) + + resp, err := handler(req) + if err != nil { + return nil, fmt.Errorf("refresh request failed: %w", err) + } + defer resp.Body.Close() + + respBody, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + if err != nil { + return nil, fmt.Errorf("failed to read refresh response: %w", err) + } + + if resp.StatusCode != http.StatusOK { + return nil, &OAuthTokenError{ + StatusCode: resp.StatusCode, + Body: string(respBody), + RequestID: resp.Header.Get("Request-Id"), + } + } + + var result struct { + AccessToken string `json:"access_token"` + TokenType string `json:"token_type,omitempty"` + RefreshToken string `json:"refresh_token"` + ExpiresIn *int `json:"expires_in,omitempty"` + } + if err := json.Unmarshal(respBody, &result); err != nil { + return nil, fmt.Errorf("failed to parse refresh response: %w", err) + } + if result.TokenType != "" && !strings.EqualFold(result.TokenType, "Bearer") { + return nil, fmt.Errorf("refresh response: unsupported token_type %q (want Bearer)", result.TokenType) + } + + updated := config.Credentials{ + AccessToken: result.AccessToken, + RefreshToken: current.RefreshToken, + } + if result.RefreshToken != "" { + updated.RefreshToken = result.RefreshToken + } + token := &AccessToken{Token: result.AccessToken} + if result.ExpiresIn != nil { + exp := time.Now().Add(time.Duration(*result.ExpiresIn) * time.Second) + updated.ExpiresAt = &exp + token.ExpiresAt = &exp + } + + if err := config.WriteCredentials(credPath, updated); err != nil { + return nil, fmt.Errorf("failed to write updated credentials: %w", err) + } + return token, nil + } + + return &CredentialsResult{ + Provider: provider, + BaseURL: cfg.BaseURL, + WorkspaceID: cfg.WorkspaceID, + }, nil +} diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/internal/auth/default.go b/vendor/github.com/anthropics/anthropic-sdk-go/internal/auth/default.go new file mode 100644 index 000000000..b61a611ec --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/internal/auth/default.go @@ -0,0 +1,71 @@ +package auth + +import ( + "os" + "strings" +) + +// identityProviderFromEnv resolves an [IdentityTokenProvider] from env vars, +// preferring ANTHROPIC_IDENTITY_TOKEN_FILE (rotation-safe) over the literal +// ANTHROPIC_IDENTITY_TOKEN. Returns nil when neither is set. +func identityProviderFromEnv() IdentityTokenProvider { + if path, ok := os.LookupEnv(EnvIdentityTokenFile); ok { + return &IdentityTokenFile{Path: path} + } + if token, ok := os.LookupEnv(EnvIdentityToken); ok { + return &IdentityTokenValue{Token: token} + } + return nil +} + +// EnvCredentials resolves OIDC-federation credentials from environment +// variables. Returns a usable result when the three required vars are all +// set. Otherwise returns nil plus a detail + state enum: NotSet when +// nothing is configured, Partial with a "missing: ..." detail otherwise. +func EnvCredentials() (*CredentialsResult, string, CredentialSourceState) { + federationRuleID, hasFedRule := os.LookupEnv(EnvFederationRuleID) + _, hasOrgID := os.LookupEnv(EnvOrganizationID) + hasTokenFile := os.Getenv(EnvIdentityTokenFile) != "" + hasTokenLiteral := os.Getenv(EnvIdentityToken) != "" + hasToken := hasTokenFile || hasTokenLiteral + + if !hasFedRule && !hasOrgID && !hasToken { + return nil, "", CredentialSourceNotSet + } + + if !hasFedRule || !hasOrgID || !hasToken { + var missing []string + if !hasFedRule { + missing = append(missing, EnvFederationRuleID) + } + if !hasOrgID { + missing = append(missing, EnvOrganizationID) + } + if !hasToken { + missing = append(missing, EnvIdentityTokenFile+" (or "+EnvIdentityToken+")") + } + return nil, "partial configuration, missing: " + strings.Join(missing, ", "), CredentialSourcePartial + } + + orgID := os.Getenv(EnvOrganizationID) + identityProvider := identityProviderFromEnv() + cfg := OIDCFederationConfig{ + IdentityProvider: identityProvider, + FederationRuleID: federationRuleID, + OrganizationID: orgID, + } + if sa, ok := os.LookupEnv(EnvServiceAccountID); ok { + cfg.ServiceAccountID = sa + } + if ws, ok := os.LookupEnv(EnvWorkspaceID); ok { + // An empty ANTHROPIC_WORKSPACE_ID (a defaulted-but-empty CI variable) + // is treated as unset: WorkspaceID stays "" and the wire field has + // json:"workspace_id,omitempty", so `"workspace_id": ""` is never + // serialized. No coercion needed — Go's Getenv + omitempty handle it. + cfg.WorkspaceID = ws + } + + return &CredentialsResult{ + Provider: NewOIDCFederationCredentials(cfg), + }, "", CredentialSourceNotSet +} diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/internal/auth/error.go b/vendor/github.com/anthropics/anthropic-sdk-go/internal/auth/error.go new file mode 100644 index 000000000..e5760edc2 --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/internal/auth/error.go @@ -0,0 +1,166 @@ +package auth + +import ( + "encoding/json" + "errors" + "fmt" + "strings" + + "github.com/anthropics/anthropic-sdk-go/config" +) + +// ErrNoCredentials is the sentinel for the case where the default credential +// chain produced no usable credential. Every [NoCredentialsError] value +// matches this sentinel via [errors.Is], so callers can branch on the +// class of failure without a type assertion. +var ErrNoCredentials = errors.New("no Anthropic credentials found") + +// OAuthTokenError is returned when an OAuth token request (workload identity +// exchange or authorized_user refresh) fails with a non-200 status. +type OAuthTokenError struct { + StatusCode int + Body string + // RequestID is the value of the server's Request-Id response header, if + // any. Empty when the response had no such header. Included in the + // formatted error so support can correlate user reports with server logs. + RequestID string + // Hint is an optional caller-supplied diagnostic appended verbatim to + // the error message. Callers gate it on the response status and their + // own state — Error does not inspect StatusCode or Body to decide + // whether to include it. + Hint string + // WorkloadIdentity is set by the OIDC federation (jwt-bearer) flow to + // suppress the "re-run `ant auth login`" remediation suffix. + // That suffix only makes sense for the interactive user_oauth flow; + // machine credentials have no browser login to re-run, and suggesting + // one sends operators down the wrong path. The zero value keeps the + // suffix so the user_oauth flow needs no change at its call site. + WorkloadIdentity bool +} + +// rfc6749ErrorBody is the subset of the RFC 6749 OAuth error response the SDK +// surfaces in user-facing error messages. Extra fields are ignored. +type rfc6749ErrorBody struct { + Error string `json:"error"` + ErrorDescription string `json:"error_description"` +} + +func (e *OAuthTokenError) Error() string { + parts := []string{fmt.Sprintf("oauth token request failed (status %d)", e.StatusCode)} + if e.RequestID != "" { + parts = append(parts, fmt.Sprintf("request id %s", e.RequestID)) + } + + var parsed rfc6749ErrorBody + if err := json.Unmarshal([]byte(e.Body), &parsed); err == nil && parsed.Error != "" { + if parsed.ErrorDescription != "" { + parts = append(parts, fmt.Sprintf("%s: %s", parsed.Error, parsed.ErrorDescription)) + } else { + parts = append(parts, parsed.Error) + } + } else { + parts = append(parts, config.RedactOAuthErrorBody(e.Body)) + } + + msg := strings.Join(parts, "; ") + if !e.WorkloadIdentity && shouldSuggestRelogin(e.StatusCode, parsed.Error) { + msg += " — re-run `ant auth login` to re-authenticate" + } + if e.Hint != "" { + msg += ". " + e.Hint + } + return msg +} + +// shouldSuggestRelogin returns true when a token-endpoint failure is most +// likely caused by an expired or revoked refresh credential. 5xx is treated +// as transient; blaming the user's credentials on a server outage is wrong. +func shouldSuggestRelogin(status int, rfcCode string) bool { + if rfcCode == "invalid_grant" { + return true + } + return status == 400 || status == 401 || status == 403 +} + +// CredentialSourceState categorizes the outcome of one entry in the default +// credential chain when no source produced a usable credential. +type CredentialSourceState int + +const ( + CredentialSourceNotSet CredentialSourceState = iota + CredentialSourceNotFound + CredentialSourceLoadFailed + CredentialSourcePartial +) + +// CredentialSourceStatus records what the default resolution chain observed +// for one credential source when all sources failed. Detail is the load +// error for [CredentialSourceLoadFailed], the remediation hint for +// [CredentialSourceNotFound], or the missing-var list for +// [CredentialSourcePartial]; it is empty for [CredentialSourceNotSet]. +type CredentialSourceStatus struct { + Name string + State CredentialSourceState + Detail string +} + +// NoCredentialsError is returned by the default credential chain when no +// source produced a usable credential. Its Error method renders every +// source the SDK tried and a brief remediation hint. +type NoCredentialsError struct { + Sources []CredentialSourceStatus +} + +// Is reports whether target is [ErrNoCredentials]. Enables callers to +// detect the no-credentials class with [errors.Is] in addition to +// [errors.As] against the concrete type. +func (e *NoCredentialsError) Is(target error) bool { + return target == ErrNoCredentials +} + +func (e *NoCredentialsError) Error() string { + var b strings.Builder + b.WriteString("no Anthropic credentials found. The SDK tried these sources in order:") + for i, s := range e.Sources { + fmt.Fprintf(&b, "\n %d. %s: %s", i+1, s.Name, formatSourceState(s)) + } + b.WriteString("\nTo fix:") + b.WriteString("\n - run `ant auth login` to interactively authenticate, or") + b.WriteString("\n - set ANTHROPIC_API_KEY, or") + b.WriteString("\n - configure workload identity federation with ANTHROPIC_FEDERATION_RULE_ID, ANTHROPIC_ORGANIZATION_ID, and ANTHROPIC_IDENTITY_TOKEN_FILE") + return b.String() +} + +func formatSourceState(s CredentialSourceStatus) string { + switch s.State { + case CredentialSourceNotFound: + if s.Detail != "" { + return "not found (" + s.Detail + ")" + } + return "not found" + case CredentialSourceLoadFailed: + return "load failed: " + s.Detail + case CredentialSourcePartial: + return s.Detail + default: + return "not set" + } +} + +// CredentialResolutionError is returned when a credential provider cannot be +// constructed from the available configuration. +type CredentialResolutionError struct { + Message string + Err error +} + +func (e *CredentialResolutionError) Error() string { + if e.Err != nil { + return fmt.Sprintf("credential resolution error: %s: %v", e.Message, e.Err) + } + return fmt.Sprintf("credential resolution error: %s", e.Message) +} + +func (e *CredentialResolutionError) Unwrap() error { + return e.Err +} diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/internal/auth/https.go b/vendor/github.com/anthropics/anthropic-sdk-go/internal/auth/https.go new file mode 100644 index 000000000..2dfdabcee --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/internal/auth/https.go @@ -0,0 +1,32 @@ +package auth + +import ( + "fmt" + "net/url" + "strings" +) + +// requireSecureTokenEndpoint rejects base URLs that would cause a JWT +// assertion or refresh token to be sent over cleartext HTTP. Local +// development hosts (localhost, 127.0.0.1, ::1) are allowed. +func requireSecureTokenEndpoint(base string) error { + if base == "" { + return nil + } + u, err := url.Parse(base) + if err != nil { + return fmt.Errorf("invalid token endpoint base URL %q: %w", base, err) + } + if u.Scheme == "https" { + return nil + } + if u.Scheme == "http" && isLoopbackHost(u.Hostname()) { + return nil + } + return fmt.Errorf("refusing to send credential over non-https token endpoint %q", base) +} + +func isLoopbackHost(host string) bool { + host = strings.ToLower(host) + return host == "localhost" || host == "127.0.0.1" || host == "::1" +} diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/internal/auth/identity.go b/vendor/github.com/anthropics/anthropic-sdk-go/internal/auth/identity.go new file mode 100644 index 000000000..9d8fe5c0d --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/internal/auth/identity.go @@ -0,0 +1,41 @@ +package auth + +import ( + "context" + "fmt" + "os" + "strings" +) + +// IdentityTokenFile reads a JWT from a file on each call, supporting +// automatic rotation (e.g. Kubernetes projected service account tokens). +type IdentityTokenFile struct { + Path string +} + +func (p *IdentityTokenFile) GetIdentityToken(_ context.Context) (string, error) { + if p.Path == "" { + return "", fmt.Errorf("identity token file path is empty") + } + data, err := os.ReadFile(p.Path) + if err != nil { + return "", fmt.Errorf("failed to read identity token file %q: %w", p.Path, err) + } + token := strings.TrimSpace(string(data)) + if token == "" { + return "", fmt.Errorf("identity token file %q is empty", p.Path) + } + return token, nil +} + +// IdentityTokenValue wraps a static JWT string as an [IdentityTokenProvider]. +type IdentityTokenValue struct { + Token string +} + +func (p *IdentityTokenValue) GetIdentityToken(_ context.Context) (string, error) { + if p.Token == "" { + return "", fmt.Errorf("identity token value is empty") + } + return p.Token, nil +} diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/internal/auth/logging.go b/vendor/github.com/anthropics/anthropic-sdk-go/internal/auth/logging.go new file mode 100644 index 000000000..f5c9d94d4 --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/internal/auth/logging.go @@ -0,0 +1,73 @@ +package auth + +import ( + "log" + "sync" +) + +// warnOnce emits a log line for an error category exactly once per process. +// Used for best-effort failures that should not surface as request errors +// but also must not be swallowed silently (e.g. a permissions problem on +// the credentials cache would otherwise cause a fresh exchange on every +// request with no visible cause). +var ( + warnOnceMu sync.Mutex + warnOnceSet = map[string]bool{} +) + +func warnOnce(key, format string, args ...any) { + warnOnceMu.Lock() + already := warnOnceSet[key] + warnOnceSet[key] = true + warnOnceMu.Unlock() + if already { + return + } + log.Printf("anthropic-sdk-go/auth: "+format, args...) +} + +// ResetWarnOnceForTest clears the warnOnce dedupe set. Exported for test +// helpers in sibling packages (e.g. internal/auth integration tests in +// package auth_test) that need to observe a warning a prior test may +// already have triggered. +func ResetWarnOnceForTest() { + warnOnceMu.Lock() + warnOnceSet = map[string]bool{} + warnOnceMu.Unlock() +} + +// ConfigShadowSource describes where the static credential that is +// shadowing a profile came from. Used by [WarnConfigShadowed] to tailor +// the remediation hint. +type ConfigShadowSource int + +const ( + // ConfigShadowFromEnv means the static credential was picked up from + // ANTHROPIC_API_KEY or ANTHROPIC_AUTH_TOKEN by the env autoloader. + // Remediation: unset the env var. + ConfigShadowFromEnv ConfigShadowSource = iota + // ConfigShadowFromOption means the static credential was passed + // explicitly via option.WithAPIKey / option.WithAuthToken. + // Remediation: remove the option. + ConfigShadowFromOption +) + +// WarnConfigShadowed warns once when a static credential is present +// alongside a profile config. Per the documented precedence, the static +// credential wins, which silently disables the profile's auth. Source +// determines whether the remediation points at an env var or an explicit +// option call. +func WarnConfigShadowed(name string, source ConfigShadowSource) { + var remediation string + switch source { + case ConfigShadowFromOption: + remediation = "remove the explicit option" + default: + remediation = "unset " + name + " (and remove any explicit WithAPIKey/WithAuthToken calls if present)" + } + warnOnce( + "config-shadowed-by-"+name, + "%s is set and takes precedence over the profile configuration passed via WithConfig; to use the profile, %s", + name, remediation, + ) +} diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/internal/auth/middleware.go b/vendor/github.com/anthropics/anthropic-sdk-go/internal/auth/middleware.go new file mode 100644 index 000000000..503ea472e --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/internal/auth/middleware.go @@ -0,0 +1,153 @@ +package auth + +import ( + "errors" + "fmt" + "net/http" + "net/url" + "strings" + "sync" + + "github.com/anthropics/anthropic-sdk-go/internal/requestconfig" +) + +// applyBearerAuth sets the Authorization and anthropic-beta headers for +// OAuth/bearer-based credentials on outgoing API requests. +func applyBearerAuth(req *http.Request, token string) { + req.Header.Set("Authorization", "Bearer "+token) + existing := req.Header.Get("anthropic-beta") + switch { + case existing == "": + req.Header.Set("anthropic-beta", OAuthAPIBetaHeader) + case !strings.Contains(existing, OAuthAPIBetaHeader): + req.Header.Set("anthropic-beta", existing+","+OAuthAPIBetaHeader) + } +} + +type authMiddlewareFunc func(*http.Request, func(*http.Request) (*http.Response, error)) (*http.Response, error) + +// NewMiddleware returns bearer-auth middleware serving tokens from cache. +// Tokens are exchanged at, and only attached to requests for, cfg.BaseURL — +// a request path may be an absolute URL for some other host. +func NewMiddleware(cache *TokenCache, cfg *requestconfig.RequestConfig) authMiddlewareFunc { + return func(req *http.Request, next func(*http.Request) (*http.Response, error)) (*http.Response, error) { + // Skip if static auth headers are already set. + if req.Header.Get("X-Api-Key") != "" || req.Header.Get("Authorization") != "" { + return next(req) + } + + if cfg.BaseURL == nil { + return nil, errors.New("cannot resolve credentials: client base URL is not set") + } + if !sameOrigin(req.URL, cfg.BaseURL) { + return next(req) + } + baseURL := cfg.BaseURL.Scheme + "://" + cfg.BaseURL.Host + + token, err := cache.Token(req.Context(), baseURL) + if err != nil { + return nil, fmt.Errorf("failed to get credentials token: %w", err) + } + applyBearerAuth(req, token) + + resp, err := next(req) + if err != nil { + return resp, err + } + + if resp.StatusCode != http.StatusUnauthorized { + return resp, nil + } + + if !cache.Invalidate() { + return resp, nil + } + + if req.GetBody == nil && req.Body != nil { + warnOnce( + "401-retry-unreplayable-body", + "401 response; request body cannot be replayed (no GetBody), skipping credential refresh retry. Use a buffered body or fix credentials.", + ) + return resp, nil + } + + token, tokenErr := cache.ForceToken(req.Context(), baseURL) + if tokenErr != nil { + warnOnce( + "401-retry-refresh-failed", + "401 response; credential refresh also failed, returning original 401: %v", + tokenErr, + ) + return resp, nil + } + applyBearerAuth(req, token) + + if req.GetBody != nil { + newBody, bodyErr := req.GetBody() + if bodyErr != nil { + resp.Body.Close() + return nil, bodyErr + } + req.Body = newBody + } + + resp.Body.Close() + return next(req) + } +} + +func sameOrigin(u, base *url.URL) bool { + return strings.EqualFold(u.Scheme, base.Scheme) && strings.EqualFold(u.Host, base.Host) +} + +// clientKey identifies the HTTP transport a [TokenCache] should bind to. +// Keying the per-option cache map on this struct ensures two clients that +// share the same [WithAuthMiddleware] option value each get their own cache +// bound to their own transport, rather than the second client silently +// reusing the first client's transport for token exchange. +type clientKey struct { + httpClient *http.Client + customDoer requestconfig.HTTPDoer +} + +// WithAuthMiddleware returns a [requestconfig.RequestOptionFunc] that appends +// HTTP middleware which authenticates requests using a cached bearer token. +// +// A separate [TokenCache] is lazily constructed per distinct HTTP transport +// (the combination of [requestconfig.RequestConfig.HTTPClient] and +// [requestconfig.RequestConfig.CustomHTTPDoer]) that applies this option, so +// the same option value can safely be shared across multiple clients built +// with different transports. Within one client, the cache is constructed +// exactly once and reused for every request so its in-memory token, refresh +// state, and 401 invalidation signal are preserved. +// +// The base URL is read at request time, so this option can be listed in any +// order relative to [option.WithBaseURL] / [option.WithEnvironmentProduction]. +// +// If the request already has an X-Api-Key or Authorization header set +// (e.g. via [option.WithAPIKey] or [option.WithAuthToken]), the middleware +// is a no-op pass-through. +func WithAuthMiddleware(provider TokenProvider) requestconfig.RequestOptionFunc { + var ( + mu sync.Mutex + byKey = map[clientKey]*TokenCache{} + ) + return func(r *requestconfig.RequestConfig) error { + key := clientKey{httpClient: r.HTTPClient, customDoer: r.CustomHTTPDoer} + + mu.Lock() + cache, ok := byKey[key] + if !ok { + handler := r.HTTPClient.Do + if r.CustomHTTPDoer != nil { + handler = r.CustomHTTPDoer.Do + } + cache = NewTokenCache(provider, handler) + byKey[key] = cache + } + mu.Unlock() + + r.Middlewares = append(r.Middlewares, NewMiddleware(cache, r)) + return nil + } +} diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/internal/auth/types.go b/vendor/github.com/anthropics/anthropic-sdk-go/internal/auth/types.go new file mode 100644 index 000000000..655993750 --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/internal/auth/types.go @@ -0,0 +1,40 @@ +package auth + +import ( + "context" + "net/http" + "time" +) + +// AccessToken represents an access token with an optional expiry time. +type AccessToken struct { + Token string + ExpiresAt *time.Time // nil means no expiry (cache forever) +} + +// TokenProvider fetches a fresh [AccessToken], potentially performing network calls. +// The handler parameter is the resolved HTTP transport from [requestconfig.RequestConfig] +// (CustomHTTPDoer ?? HTTPClient). +// +// Implementations must be safe for concurrent use because [TokenCache] may +// invoke the provider from a background goroutine while another call is +// in-flight on the main request path. +type TokenProvider func(ctx context.Context, baseURL string, handler func(*http.Request) (*http.Response, error)) (*AccessToken, error) + +// IdentityTokenProvider provides a JWT identity token for federation. +type IdentityTokenProvider interface { + GetIdentityToken(ctx context.Context) (string, error) +} + +// CredentialsResult bundles a [TokenProvider] with config-level metadata that +// needs to be propagated to the client (e.g. base_url, workspace_id). +// +// OrganizationID is intentionally absent: the server exposes the caller's +// organization only as the anthropic-organization-id *response* header, not +// as a request header, so there is no way for the SDK to act on a +// config-level organization ID today. +type CredentialsResult struct { + Provider TokenProvider + BaseURL string // from config file; empty if not set + WorkspaceID string +} diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/internal/auth/workload.go b/vendor/github.com/anthropics/anthropic-sdk-go/internal/auth/workload.go new file mode 100644 index 000000000..2dc05a25f --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/internal/auth/workload.go @@ -0,0 +1,165 @@ +package auth + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "strings" + "time" + + "github.com/anthropics/anthropic-sdk-go/internal" +) + +// MaxAssertionSize bounds the JWT sent to /v1/oauth/token. Honest OIDC +// tokens are well under 16 KiB; reject larger inputs before shipping them +// at request rate. +const MaxAssertionSize = 16384 + +// OIDCFederationConfig configures an OIDC-federation [TokenProvider] that +// exchanges a third-party JWT for an Anthropic access token. +type OIDCFederationConfig struct { + IdentityProvider IdentityTokenProvider + FederationRuleID string + OrganizationID string + ServiceAccountID string // optional + // WorkspaceID is an optional `wrkspc_*` tagged ID, or the literal + // "default" to scope the token to the organization's default workspace. + // When omitted the server picks the rule's sole enabled workspace, else + // the org default if the rule covers it. Required when the rule enables + // more than one non-default workspace, or to target a specific workspace + // other than the one the server would pick. The minted token is + // workspace-scoped: per-request workspace selection (the + // anthropic-workspace-id header) is not supported for federation + // tokens — switching workspaces requires a new token exchange with a + // different WorkspaceID. + WorkspaceID string + BaseURL string // optional override; if empty, uses baseURL from TokenCache +} + +type tokenExchangeRequest struct { + GrantType string `json:"grant_type"` + Assertion string `json:"assertion"` + FederationRuleID string `json:"federation_rule_id"` + OrganizationID string `json:"organization_id"` + ServiceAccountID string `json:"service_account_id,omitempty"` + WorkspaceID string `json:"workspace_id,omitempty"` +} + +type tokenExchangeResponse struct { + AccessToken string `json:"access_token"` + TokenType string `json:"token_type,omitempty"` + ExpiresIn *int `json:"expires_in,omitempty"` +} + +// NewOIDCFederationCredentials returns a [TokenProvider] that exchanges an +// OIDC identity token for a short-lived Anthropic access token via the OAuth +// token endpoint. +func NewOIDCFederationCredentials(cfg OIDCFederationConfig) TokenProvider { + return func(ctx context.Context, baseURL string, handler func(*http.Request) (*http.Response, error)) (*AccessToken, error) { + effectiveBase := strings.TrimRight(cfg.BaseURL, "/") + if effectiveBase == "" { + effectiveBase = strings.TrimRight(baseURL, "/") + } + if err := requireSecureTokenEndpoint(effectiveBase); err != nil { + return nil, err + } + jwt, err := cfg.IdentityProvider.GetIdentityToken(ctx) + if err != nil { + return nil, fmt.Errorf("failed to get identity token: %w", err) + } + // post-fetch: bounds wire size, not allocation + if len(jwt) > MaxAssertionSize { + return nil, fmt.Errorf("identity token exceeds %d-byte limit (got %d bytes)", MaxAssertionSize, len(jwt)) + } + + body := tokenExchangeRequest{ + GrantType: GrantTypeJWTBearer, + Assertion: jwt, + FederationRuleID: cfg.FederationRuleID, + OrganizationID: cfg.OrganizationID, + ServiceAccountID: cfg.ServiceAccountID, + WorkspaceID: cfg.WorkspaceID, + } + bodyJSON, err := json.Marshal(body) + if err != nil { + return nil, fmt.Errorf("failed to marshal token exchange request: %w", err) + } + + endpoint := effectiveBase + TokenEndpoint + req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(bodyJSON)) + if err != nil { + return nil, fmt.Errorf("failed to create token exchange request: %w", err) + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("User-Agent", "anthropic-sdk-go/"+internal.PackageVersion+" (oidc-federation)") + // oauth-2025-04-20 unlocks the oauth/token endpoint family and is + // required alongside the federation beta for jwt-bearer grants. + req.Header.Set("anthropic-beta", OAuthAPIBetaHeader+","+FederationBetaHeader) + + resp, err := handler(req) + if err != nil { + return nil, fmt.Errorf("token exchange request failed: %w", err) + } + defer resp.Body.Close() + + respBody, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + if err != nil { + return nil, fmt.Errorf("failed to read token exchange response: %w", err) + } + + if resp.StatusCode != http.StatusOK { + // A 401 is the auth-failure case worth a hint: point the operator + // at the federation rule and the authentication-events log in + // Claude Console. When no WorkspaceID is configured, also surface + // the most common ambiguous-401 cause — a federation rule spanning + // multiple workspaces — so the operator doesn't have to dig + // through docs. Other statuses (5xx, non-401 4xx) get no hint: + // they don't indicate a config problem this guidance would fix. + var hint string + if resp.StatusCode == http.StatusUnauthorized { + hintParts := []string{ + "Ensure your federation rule matches your identity token", + } + if cfg.WorkspaceID == "" { + hintParts = append(hintParts, + "If your federation rule is scoped to multiple workspaces, set the "+ + "ANTHROPIC_WORKSPACE_ID environment variable, the 'workspace_id' "+ + "config key, or the WorkspaceID field on option.FederationOptions") + } + hintParts = append(hintParts, + "View your authentication events in the Workload identity page of "+ + "Claude Console for more details") + hint = strings.Join(hintParts, ". ") + "." + } + return nil, &OAuthTokenError{ + StatusCode: resp.StatusCode, + Body: string(respBody), + RequestID: resp.Header.Get("Request-Id"), + Hint: hint, + WorkloadIdentity: true, + } + } + + var result tokenExchangeResponse + if err := json.Unmarshal(respBody, &result); err != nil { + return nil, fmt.Errorf("failed to parse token exchange response: %w", err) + } + + if result.AccessToken == "" { + return nil, fmt.Errorf("token exchange response missing access_token") + } + if result.TokenType != "" && !strings.EqualFold(result.TokenType, "Bearer") { + return nil, fmt.Errorf("token exchange response: unsupported token_type %q (want Bearer)", result.TokenType) + } + + token := &AccessToken{Token: result.AccessToken} + if result.ExpiresIn != nil { + exp := time.Now().Add(time.Duration(*result.ExpiresIn) * time.Second) + token.ExpiresAt = &exp + } + return token, nil + } +} diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/internal/encoding/json/encode.go b/vendor/github.com/anthropics/anthropic-sdk-go/internal/encoding/json/encode.go index 643d50779..6ad6b0276 100644 --- a/vendor/github.com/anthropics/anthropic-sdk-go/internal/encoding/json/encode.go +++ b/vendor/github.com/anthropics/anthropic-sdk-go/internal/encoding/json/encode.go @@ -173,15 +173,21 @@ import ( // JSON cannot represent cyclic data structures and Marshal does not // handle them. Passing cyclic structures to Marshal will result in // an error. -func Marshal(v any) ([]byte, error) { +// EDIT(begin): add optimization options +func Marshal(v any, opts ...Option) ([]byte, error) { + // EDIT(end): add optimization options e := newEncodeState() defer encodeStatePool.Put(e) - // SHIM(begin): don't escape HTML by default - err := e.marshal(v, encOpts{escapeHTML: shims.EscapeHTMLByDefault}) + // EDIT(begin): don't escape HTML by default, and apply options + encOpts := encOpts{escapeHTML: shims.EscapeHTMLByDefault} + if opts != nil { + encOpts = encOpts.apply(opts...) + } + err := e.marshal(v, encOpts) // ORIGINAL: // err := e.marshal(v, encOpts{escapeHTML: true}) - // SHIM(end) + // EDIT(end) if err != nil { return nil, err } @@ -352,6 +358,9 @@ type encOpts struct { // EDIT(begin): save the timefmt timefmt string // EDIT(end) + // EDIT(begin): add optimization to skip compaction + skipCompaction bool + // EDIT(end) } type encoderFunc func(e *encodeState, v reflect.Value, opts encOpts) @@ -410,6 +419,14 @@ func newTypeEncoder(t reflect.Type, allowAddr bool) encoderFunc { } // EDIT(end) + // EDIT(begin): json.RawMessage carries caller-supplied bytes; never skip its scanning pass. + // The Implements guard keeps named pointer types (empty method set) on the + // regular pointer-encoder path. + if t == rawMessageType || (t.Kind() == reflect.Pointer && t.Elem() == rawMessageType && t.Implements(marshalerType)) { + return rawMessageEncoder + } + // EDIT(end) + // If we have a non-pointer value whose type implements // Marshaler with a value receiver, then we're better off taking // the address of the value - otherwise we end up with an @@ -483,7 +500,7 @@ func marshalerEncoder(e *encodeState, v reflect.Value, opts encOpts) { if err == nil { e.Grow(len(b)) out := e.AvailableBuffer() - out, err = appendCompact(out, b, opts.escapeHTML) + out, err = appendCompact(out, b, opts) e.Buffer.Write(out) } if err != nil { @@ -509,7 +526,7 @@ func addrMarshalerEncoder(e *encodeState, v reflect.Value, opts encOpts) { if err == nil { e.Grow(len(b)) out := e.AvailableBuffer() - out, err = appendCompact(out, b, opts.escapeHTML) + out, err = appendCompact(out, b, opts) e.Buffer.Write(out) } if err != nil { diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/internal/encoding/json/indent.go b/vendor/github.com/anthropics/anthropic-sdk-go/internal/encoding/json/indent.go index 01bfdf65e..c9d6ca5b1 100644 --- a/vendor/github.com/anthropics/anthropic-sdk-go/internal/encoding/json/indent.go +++ b/vendor/github.com/anthropics/anthropic-sdk-go/internal/encoding/json/indent.go @@ -4,7 +4,9 @@ package json -import "bytes" +import ( + "bytes" +) // HTMLEscape appends to dst the JSON-encoded src with <, >, &, U+2028 and U+2029 // characters inside string literals changed to \u003c, \u003e, \u0026, \u2028, \u2029 @@ -41,12 +43,21 @@ func appendHTMLEscape(dst, src []byte) []byte { func Compact(dst *bytes.Buffer, src []byte) error { dst.Grow(len(src)) b := dst.AvailableBuffer() - b, err := appendCompact(b, src, false) + b, err := appendCompact(b, src, encOpts{}) dst.Write(b) return err } -func appendCompact(dst, src []byte, escape bool) ([]byte, error) { +func appendCompact(dst, src []byte, opts encOpts) ([]byte, error) { + // EDIT(begin): optimize for skipCompaction + if opts.skipCompaction { + dst = append(dst, src...) + return dst, nil + } + + escape := opts.escapeHTML + // EDIT(end) + origLen := len(dst) scan := newScanner() defer freeScanner(scan) diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/internal/encoding/json/opt.go b/vendor/github.com/anthropics/anthropic-sdk-go/internal/encoding/json/opt.go new file mode 100644 index 000000000..eedc37f19 --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/internal/encoding/json/opt.go @@ -0,0 +1,41 @@ +// EDIT(begin): add custom options for JSON encoding +package json + +import ( + stdjson "encoding/json" + "reflect" + + "github.com/anthropics/anthropic-sdk-go/internal/encoding/json/shims" +) + +type Option func(*encOpts) + +// Every time a sub-type of [json.Marshaler] is encountered, +// skip a redundant and costly compaction step, trust it to self-compact. +// +// This is a divergence from the standard library behavior, and is only guaranteed +// safe with SDK types. +func WithSkipCompaction(b bool) Option { + return func(eos *encOpts) { + eos.skipCompaction = true + } +} + +func (eos encOpts) apply(opts ...Option) encOpts { + for _, opt := range opts { + opt(&eos) + } + return eos +} + +var rawMessageType = shims.TypeFor[stdjson.RawMessage]() + +// rawMessageEncoder is marshalerEncoder minus the [WithSkipCompaction] trust: +// a json.RawMessage returns caller-supplied bytes verbatim, so they always get +// the scanning pass, which compacts, HTML-escapes, and rejects invalid JSON. +func rawMessageEncoder(e *encodeState, v reflect.Value, opts encOpts) { + opts.skipCompaction = false + marshalerEncoder(e, v, opts) +} + +// EDIT(end) diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/internal/encoding/json/stream.go b/vendor/github.com/anthropics/anthropic-sdk-go/internal/encoding/json/stream.go index e2d9470bc..652522c3a 100644 --- a/vendor/github.com/anthropics/anthropic-sdk-go/internal/encoding/json/stream.go +++ b/vendor/github.com/anthropics/anthropic-sdk-go/internal/encoding/json/stream.go @@ -6,7 +6,6 @@ package json import ( "bytes" - "errors" "io" ) @@ -253,30 +252,34 @@ func (enc *Encoder) SetEscapeHTML(on bool) { enc.escapeHTML = on } -// RawMessage is a raw encoded JSON value. -// It implements [Marshaler] and [Unmarshaler] and can -// be used to delay JSON decoding or precompute a JSON encoding. -type RawMessage []byte - -// MarshalJSON returns m as the JSON encoding of m. -func (m RawMessage) MarshalJSON() ([]byte, error) { - if m == nil { - return []byte("null"), nil - } - return m, nil -} - -// UnmarshalJSON sets *m to a copy of data. -func (m *RawMessage) UnmarshalJSON(data []byte) error { - if m == nil { - return errors.New("json.RawMessage: UnmarshalJSON on nil pointer") - } - *m = append((*m)[0:0], data...) - return nil -} - -var _ Marshaler = (*RawMessage)(nil) -var _ Unmarshaler = (*RawMessage)(nil) +// EDIT(begin): remove RawMessage +// +// // RawMessage is a raw encoded JSON value. +// // It implements [Marshaler] and [Unmarshaler] and can +// // be used to delay JSON decoding or precompute a JSON encoding. +// type RawMessage []byte +// +// // MarshalJSON returns m as the JSON encoding of m. +// func (m RawMessage) MarshalJSON() ([]byte, error) { +// if m == nil { +// return []byte("null"), nil +// } +// return m, nil +// } +// +// // UnmarshalJSON sets *m to a copy of data. +// func (m *RawMessage) UnmarshalJSON(data []byte) error { +// if m == nil { +// return errors.New("json.RawMessage: UnmarshalJSON on nil pointer") +// } +// *m = append((*m)[0:0], data...) +// return nil +// } +// +// var _ Marshaler = (*RawMessage)(nil) +// var _ Unmarshaler = (*RawMessage)(nil) +// +// EDIT(end) // A Token holds a value of one of these types: // diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/internal/encoding/json/time.go b/vendor/github.com/anthropics/anthropic-sdk-go/internal/encoding/json/time.go index 3db94be18..27008f388 100644 --- a/vendor/github.com/anthropics/anthropic-sdk-go/internal/encoding/json/time.go +++ b/vendor/github.com/anthropics/anthropic-sdk-go/internal/encoding/json/time.go @@ -50,7 +50,7 @@ func timeMarshalEncoder(e *encodeState, v reflect.Value, opts encOpts) bool { if b != nil { e.Grow(len(b)) out := e.AvailableBuffer() - out, _ = appendCompact(out, b, opts.escapeHTML) + out, _ = appendCompact(out, b, opts) e.Buffer.Write(out) return true } diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/internal/requestconfig/requestconfig.go b/vendor/github.com/anthropics/anthropic-sdk-go/internal/requestconfig/requestconfig.go index aba8afefd..b5339ebbc 100644 --- a/vendor/github.com/anthropics/anthropic-sdk-go/internal/requestconfig/requestconfig.go +++ b/vendor/github.com/anthropics/anthropic-sdk-go/internal/requestconfig/requestconfig.go @@ -220,6 +220,7 @@ type RequestConfig struct { Middlewares []middleware APIKey string AuthToken string + WebhookKey string // If ResponseBodyInto not nil, then we will attempt to deserialize into // ResponseBodyInto. If Destination is a []byte, then it will return the body as // is. @@ -506,7 +507,7 @@ func (cfg *RequestConfig) Execute() (err error) { res.Body = io.NopCloser(bytes.NewBuffer(contents)) // Load the contents into the error format if it is provided. - aerr := apierror.Error{Request: cfg.Request, Response: res, StatusCode: res.StatusCode, RequestID: res.Header.Get("request-id")} + aerr := apierror.Error{Request: cfg.Request, Response: res, StatusCode: res.StatusCode, RequestID: res.Header.Get("request-id"), WorkspaceID: res.Header.Get("anthropic-workspace-id")} err = aerr.UnmarshalJSON(contents) if err != nil { return err @@ -595,6 +596,7 @@ func (cfg *RequestConfig) Clone(ctx context.Context) *RequestConfig { Middlewares: cfg.Middlewares, APIKey: cfg.APIKey, AuthToken: cfg.AuthToken, + WebhookKey: cfg.WebhookKey, } return new diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/internal/sendwindow/sendwindow.go b/vendor/github.com/anthropics/anthropic-sdk-go/internal/sendwindow/sendwindow.go new file mode 100644 index 000000000..02789af3d --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/internal/sendwindow/sendwindow.go @@ -0,0 +1,40 @@ +// Package sendwindow carries the tool-result send retry window from +// lib/environments.EnvironmentWorker (which learns the work-item lease TTL from +// each heartbeat) to anthropic.SessionToolRunner (which bounds its send retries +// by it) without putting the plumbing on either package's public API. +package sendwindow + +import ( + "context" + "sync/atomic" + "time" +) + +// Window is a duration that one goroutine updates while another reads it. The +// zero value, and a nil *Window, report 0, meaning "use the default". +type Window struct{ nanos atomic.Int64 } + +// Set stores d. +func (w *Window) Set(d time.Duration) { w.nanos.Store(int64(d)) } + +// Get returns the last Set value, or 0. +func (w *Window) Get() time.Duration { + if w == nil { + return 0 + } + return time.Duration(w.nanos.Load()) +} + +type ctxKey struct{} + +// NewContext returns a child of ctx carrying w. A SessionToolRunner constructed +// on the returned context re-reads w before every send retry. +func NewContext(ctx context.Context, w *Window) context.Context { + return context.WithValue(ctx, ctxKey{}, w) +} + +// FromContext returns the Window carried by ctx, or nil. +func FromContext(ctx context.Context) *Window { + w, _ := ctx.Value(ctxKey{}).(*Window) + return w +} diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/internal/stainlessheader/stainlessheader.go b/vendor/github.com/anthropics/anthropic-sdk-go/internal/stainlessheader/stainlessheader.go new file mode 100644 index 000000000..46a55c156 --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/internal/stainlessheader/stainlessheader.go @@ -0,0 +1,71 @@ +// Package stainlessheader is the single source of truth for the +// x-stainless-helper telemetry header — the key, the closed set of tag +// values shared across SDKs, and the append-don't-clobber request option. +package stainlessheader + +import ( + "net/http" + "strings" + + "github.com/anthropics/anthropic-sdk-go/internal/requestconfig" +) + +// Header is the helper-telemetry header key. Always this lowercase form; +// http.Header is case-insensitive but a single canonical casing keeps every +// call site greppable. +const Header = "x-stainless-helper" + +// Value is the closed set of helper-telemetry tags, shared verbatim across +// SDKs. A typo at a call site is caught by the unused-const check rather than +// silently mistagged. Existing values keep their original spellings — telemetry +// consumers match on them, so renames lose history. New tags are hyphenated +// lowercase; add them here (and to the matching set in every other SDK) before +// using them. +type Value string + +const ( + BetaToolRunner Value = "BetaToolRunner" + Compaction Value = "compaction" + EnvironmentsWorkPoller Value = "environments-work-poller" + EnvironmentsWorker Value = "environments-worker" + FallbackRefusalMiddleware Value = "fallback-refusal-middleware" + SessionToolRunner Value = "session-tool-runner" +) + +// With returns a request option (assignable to [option.RequestOption]) that +// appends value to the x-stainless-helper header rather than replacing it — +// the backend logs the header as one opaque string, so a second header line or +// a clobbered value loses data. Existing tags keep their position; the new tag +// appends at the end; duplicates are dropped. +func With(value Value) requestconfig.RequestOption { + return requestconfig.RequestOptionFunc(func(r *requestconfig.RequestConfig) error { + AppendHeaderValue(r.Request.Header, value) + return nil + }) +} + +// AppendHeaderValue appends value to h's x-stainless-helper entry in place, +// collapsing any existing values (under any casing, across multiple lines) +// into one comma-joined deduplicated string. Exposed for code paths that hold +// a [*http.Request] rather than a request option chain (e.g. middleware). +func AppendHeaderValue(h http.Header, value Value) { + var tokens []string + seen := map[string]struct{}{} + add := func(tok string) { + if tok == "" { + return + } + if _, ok := seen[tok]; ok { + return + } + seen[tok] = struct{}{} + tokens = append(tokens, tok) + } + for _, existing := range h.Values(Header) { + for _, tok := range strings.Split(existing, ",") { + add(strings.TrimSpace(tok)) + } + } + add(string(value)) + h.Set(Header, strings.Join(tokens, ", ")) +} diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/internal/version.go b/vendor/github.com/anthropics/anthropic-sdk-go/internal/version.go index 5549d4bed..1d722d7bc 100644 --- a/vendor/github.com/anthropics/anthropic-sdk-go/internal/version.go +++ b/vendor/github.com/anthropics/anthropic-sdk-go/internal/version.go @@ -2,4 +2,4 @@ package internal -const PackageVersion = "1.37.0" // x-release-please-version +const PackageVersion = "1.67.0" // x-release-please-version diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/message.go b/vendor/github.com/anthropics/anthropic-sdk-go/message.go index 70fdc3cc3..0208d5c25 100644 --- a/vendor/github.com/anthropics/anthropic-sdk-go/message.go +++ b/vendor/github.com/anthropics/anthropic-sdk-go/message.go @@ -5,6 +5,7 @@ package anthropic import ( "context" "encoding/json" + "fmt" "net/http" "reflect" "slices" @@ -49,23 +50,26 @@ func NewMessageService(opts ...option.RequestOption) (r MessageService) { // conversations. // // Learn more about the Messages API in our -// [user guide](https://docs.claude.com/en/docs/initial-setup) +// [user guide](https://platform.claude.com/docs/en/get-started) // // Note: If you choose to set a timeout for this request, we recommend 10 minutes. -func (r *MessageService) New(ctx context.Context, body MessageNewParams, opts ...option.RequestOption) (res *Message, err error) { +func (r *MessageService) New(ctx context.Context, params MessageNewParams, opts ...option.RequestOption) (res *Message, err error) { + if !param.IsOmitted(params.UserProfileID) { + opts = append(opts, option.WithHeader("anthropic-user-profile-id", fmt.Sprintf("%v", params.UserProfileID.Value))) + } opts = slices.Concat(r.Options, opts) - warnIfThinkingEnabled(body.Model, body.Thinking.OfEnabled != nil) + warnIfThinkingEnabled(params.Model, params.Thinking.OfEnabled != nil) // For non-streaming requests, calculate the appropriate timeout based on maxTokens // and check against model-specific limits - timeout, timeoutErr := CalculateNonStreamingTimeout(int(body.MaxTokens), body.Model, opts) + timeout, timeoutErr := CalculateNonStreamingTimeout(int(params.MaxTokens), params.Model, opts) if timeoutErr != nil { return nil, timeoutErr } opts = append(opts, option.WithRequestTimeout(timeout)) path := "v1/messages" - err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, params, &res, opts...) return res, err } @@ -76,19 +80,22 @@ func (r *MessageService) New(ctx context.Context, body MessageNewParams, opts .. // conversations. // // Learn more about the Messages API in our -// [user guide](https://docs.claude.com/en/docs/initial-setup) +// [user guide](https://platform.claude.com/docs/en/get-started) // // Note: If you choose to set a timeout for this request, we recommend 10 minutes. -func (r *MessageService) NewStreaming(ctx context.Context, body MessageNewParams, opts ...option.RequestOption) (stream *ssestream.Stream[MessageStreamEventUnion]) { +func (r *MessageService) NewStreaming(ctx context.Context, params MessageNewParams, opts ...option.RequestOption) (stream *ssestream.Stream[MessageStreamEventUnion]) { var ( raw *http.Response err error ) + if !param.IsOmitted(params.UserProfileID) { + opts = append(opts, option.WithHeader("anthropic-user-profile-id", fmt.Sprintf("%v", params.UserProfileID.Value))) + } opts = slices.Concat(r.Options, opts) - warnIfThinkingEnabled(body.Model, body.Thinking.OfEnabled != nil) + warnIfThinkingEnabled(params.Model, params.Thinking.OfEnabled != nil) opts = append(opts, option.WithJSONSet("stream", true)) path := "v1/messages" - err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &raw, opts...) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, params, &raw, opts...) return ssestream.NewStream[MessageStreamEventUnion](ssestream.NewDecoder(raw), err) } @@ -98,11 +105,14 @@ func (r *MessageService) NewStreaming(ctx context.Context, body MessageNewParams // including tools, images, and documents, without creating it. // // Learn more about token counting in our -// [user guide](https://docs.claude.com/en/docs/build-with-claude/token-counting) -func (r *MessageService) CountTokens(ctx context.Context, body MessageCountTokensParams, opts ...option.RequestOption) (res *MessageTokensCount, err error) { +// [user guide](https://platform.claude.com/docs/en/build-with-claude/token-counting) +func (r *MessageService) CountTokens(ctx context.Context, params MessageCountTokensParams, opts ...option.RequestOption) (res *MessageTokensCount, err error) { + if !param.IsOmitted(params.UserProfileID) { + opts = append(opts, option.WithHeader("anthropic-user-profile-id", fmt.Sprintf("%v", params.UserProfileID.Value))) + } opts = slices.Concat(r.Options, opts) path := "v1/messages/count_tokens" - err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, params, &res, opts...) return res, err } @@ -468,3044 +478,4825 @@ func (r *BashCodeExecutionToolResultErrorParam) UnmarshalJSON(data []byte) error return apijson.UnmarshalRoot(data, r) } -func NewCacheControlEphemeralParam() CacheControlEphemeralParam { - return CacheControlEphemeralParam{ - Type: "ephemeral", - } -} - -// This struct has a constant value, construct it with -// [NewCacheControlEphemeralParam]. -type CacheControlEphemeralParam struct { - // The time-to-live for the cache control breakpoint. - // - // This may be one the following values: - // - // - `5m`: 5 minutes - // - `1h`: 1 hour - // - // Defaults to `5m`. - // - // Any of "5m", "1h". - TTL CacheControlEphemeralTTL `json:"ttl,omitzero"` - Type constant.Ephemeral `json:"type" default:"ephemeral"` +// `close_tab`'s config overrides. +type BrowserCloseTabConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` paramObj } -func (r CacheControlEphemeralParam) MarshalJSON() (data []byte, err error) { - type shadow CacheControlEphemeralParam +func (r BrowserCloseTabConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BrowserCloseTabConfigParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *CacheControlEphemeralParam) UnmarshalJSON(data []byte) error { +func (r *BrowserCloseTabConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The time-to-live for the cache control breakpoint. -// -// This may be one the following values: -// -// - `5m`: 5 minutes -// - `1h`: 1 hour -// -// Defaults to `5m`. -type CacheControlEphemeralTTL string +// `double_click`'s config overrides. +type BrowserDoubleClickConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj +} -const ( - CacheControlEphemeralTTLTTL5m CacheControlEphemeralTTL = "5m" - CacheControlEphemeralTTLTTL1h CacheControlEphemeralTTL = "1h" -) +func (r BrowserDoubleClickConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BrowserDoubleClickConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BrowserDoubleClickConfigParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} -type CacheCreation struct { - // The number of input tokens used to create the 1 hour cache entry. - Ephemeral1hInputTokens int64 `json:"ephemeral_1h_input_tokens" api:"required"` - // The number of input tokens used to create the 5 minute cache entry. - Ephemeral5mInputTokens int64 `json:"ephemeral_5m_input_tokens" api:"required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Ephemeral1hInputTokens respjson.Field - Ephemeral5mInputTokens respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +// `file_upload`'s config overrides. +type BrowserFileUploadConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -// Returns the unmodified JSON received from the API -func (r CacheCreation) RawJSON() string { return r.JSON.raw } -func (r *CacheCreation) UnmarshalJSON(data []byte) error { +func (r BrowserFileUploadConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BrowserFileUploadConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BrowserFileUploadConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type CitationCharLocation struct { - CitedText string `json:"cited_text" api:"required"` - DocumentIndex int64 `json:"document_index" api:"required"` - DocumentTitle string `json:"document_title" api:"required"` - EndCharIndex int64 `json:"end_char_index" api:"required"` - FileID string `json:"file_id" api:"required"` - StartCharIndex int64 `json:"start_char_index" api:"required"` - Type constant.CharLocation `json:"type" default:"char_location"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - CitedText respjson.Field - DocumentIndex respjson.Field - DocumentTitle respjson.Field - EndCharIndex respjson.Field - FileID respjson.Field - StartCharIndex respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +// `find`'s config overrides. +type BrowserFindConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -// Returns the unmodified JSON received from the API -func (r CitationCharLocation) RawJSON() string { return r.JSON.raw } -func (r *CitationCharLocation) UnmarshalJSON(data []byte) error { +func (r BrowserFindConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BrowserFindConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BrowserFindConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The properties CitedText, DocumentIndex, DocumentTitle, EndCharIndex, -// StartCharIndex, Type are required. -type CitationCharLocationParam struct { - DocumentTitle param.Opt[string] `json:"document_title,omitzero" api:"required"` - CitedText string `json:"cited_text" api:"required"` - DocumentIndex int64 `json:"document_index" api:"required"` - EndCharIndex int64 `json:"end_char_index" api:"required"` - StartCharIndex int64 `json:"start_char_index" api:"required"` - // This field can be elided, and will marshal its zero value as "char_location". - Type constant.CharLocation `json:"type" default:"char_location"` +// `form_input`'s config overrides. +type BrowserFormInputConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` paramObj } -func (r CitationCharLocationParam) MarshalJSON() (data []byte, err error) { - type shadow CitationCharLocationParam +func (r BrowserFormInputConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BrowserFormInputConfigParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *CitationCharLocationParam) UnmarshalJSON(data []byte) error { +func (r *BrowserFormInputConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type CitationContentBlockLocation struct { - CitedText string `json:"cited_text" api:"required"` - DocumentIndex int64 `json:"document_index" api:"required"` - DocumentTitle string `json:"document_title" api:"required"` - EndBlockIndex int64 `json:"end_block_index" api:"required"` - FileID string `json:"file_id" api:"required"` - StartBlockIndex int64 `json:"start_block_index" api:"required"` - Type constant.ContentBlockLocation `json:"type" default:"content_block_location"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - CitedText respjson.Field - DocumentIndex respjson.Field - DocumentTitle respjson.Field - EndBlockIndex respjson.Field - FileID respjson.Field - StartBlockIndex respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +// `get_page_text`'s config overrides. +type BrowserGetPageTextConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -// Returns the unmodified JSON received from the API -func (r CitationContentBlockLocation) RawJSON() string { return r.JSON.raw } -func (r *CitationContentBlockLocation) UnmarshalJSON(data []byte) error { +func (r BrowserGetPageTextConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BrowserGetPageTextConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BrowserGetPageTextConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The properties CitedText, DocumentIndex, DocumentTitle, EndBlockIndex, -// StartBlockIndex, Type are required. -type CitationContentBlockLocationParam struct { - DocumentTitle param.Opt[string] `json:"document_title,omitzero" api:"required"` - CitedText string `json:"cited_text" api:"required"` - DocumentIndex int64 `json:"document_index" api:"required"` - EndBlockIndex int64 `json:"end_block_index" api:"required"` - StartBlockIndex int64 `json:"start_block_index" api:"required"` - // This field can be elided, and will marshal its zero value as - // "content_block_location". - Type constant.ContentBlockLocation `json:"type" default:"content_block_location"` +// `hold_key`'s config overrides. +type BrowserHoldKeyConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` paramObj } -func (r CitationContentBlockLocationParam) MarshalJSON() (data []byte, err error) { - type shadow CitationContentBlockLocationParam +func (r BrowserHoldKeyConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BrowserHoldKeyConfigParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *CitationContentBlockLocationParam) UnmarshalJSON(data []byte) error { +func (r *BrowserHoldKeyConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type CitationPageLocation struct { - CitedText string `json:"cited_text" api:"required"` - DocumentIndex int64 `json:"document_index" api:"required"` - DocumentTitle string `json:"document_title" api:"required"` - EndPageNumber int64 `json:"end_page_number" api:"required"` - FileID string `json:"file_id" api:"required"` - StartPageNumber int64 `json:"start_page_number" api:"required"` - Type constant.PageLocation `json:"type" default:"page_location"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - CitedText respjson.Field - DocumentIndex respjson.Field - DocumentTitle respjson.Field - EndPageNumber respjson.Field - FileID respjson.Field - StartPageNumber respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +// `hover`'s config overrides. +type BrowserHoverConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -// Returns the unmodified JSON received from the API -func (r CitationPageLocation) RawJSON() string { return r.JSON.raw } -func (r *CitationPageLocation) UnmarshalJSON(data []byte) error { +func (r BrowserHoverConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BrowserHoverConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BrowserHoverConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The properties CitedText, DocumentIndex, DocumentTitle, EndPageNumber, -// StartPageNumber, Type are required. -type CitationPageLocationParam struct { - DocumentTitle param.Opt[string] `json:"document_title,omitzero" api:"required"` - CitedText string `json:"cited_text" api:"required"` - DocumentIndex int64 `json:"document_index" api:"required"` - EndPageNumber int64 `json:"end_page_number" api:"required"` - StartPageNumber int64 `json:"start_page_number" api:"required"` - // This field can be elided, and will marshal its zero value as "page_location". - Type constant.PageLocation `json:"type" default:"page_location"` +// `javascript_exec`'s config overrides. +type BrowserJavascriptExecConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` paramObj } -func (r CitationPageLocationParam) MarshalJSON() (data []byte, err error) { - type shadow CitationPageLocationParam +func (r BrowserJavascriptExecConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BrowserJavascriptExecConfigParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *CitationPageLocationParam) UnmarshalJSON(data []byte) error { +func (r *BrowserJavascriptExecConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The properties CitedText, EndBlockIndex, SearchResultIndex, Source, -// StartBlockIndex, Title, Type are required. -type CitationSearchResultLocationParam struct { - Title param.Opt[string] `json:"title,omitzero" api:"required"` - CitedText string `json:"cited_text" api:"required"` - EndBlockIndex int64 `json:"end_block_index" api:"required"` - SearchResultIndex int64 `json:"search_result_index" api:"required"` - Source string `json:"source" api:"required"` - StartBlockIndex int64 `json:"start_block_index" api:"required"` - // This field can be elided, and will marshal its zero value as - // "search_result_location". - Type constant.SearchResultLocation `json:"type" default:"search_result_location"` +// `key`'s config overrides. +type BrowserKeyConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` paramObj } -func (r CitationSearchResultLocationParam) MarshalJSON() (data []byte, err error) { - type shadow CitationSearchResultLocationParam +func (r BrowserKeyConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BrowserKeyConfigParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *CitationSearchResultLocationParam) UnmarshalJSON(data []byte) error { +func (r *BrowserKeyConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The properties CitedText, EncryptedIndex, Title, Type, URL are required. -type CitationWebSearchResultLocationParam struct { - Title param.Opt[string] `json:"title,omitzero" api:"required"` - CitedText string `json:"cited_text" api:"required"` - EncryptedIndex string `json:"encrypted_index" api:"required"` - URL string `json:"url" api:"required"` - // This field can be elided, and will marshal its zero value as - // "web_search_result_location". - Type constant.WebSearchResultLocation `json:"type" default:"web_search_result_location"` +// `left_click`'s config overrides. +type BrowserLeftClickConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` paramObj } -func (r CitationWebSearchResultLocationParam) MarshalJSON() (data []byte, err error) { - type shadow CitationWebSearchResultLocationParam +func (r BrowserLeftClickConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BrowserLeftClickConfigParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *CitationWebSearchResultLocationParam) UnmarshalJSON(data []byte) error { +func (r *BrowserLeftClickConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type CitationsConfig struct { - Enabled bool `json:"enabled" api:"required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Enabled respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +// `left_click_drag`'s config overrides. +type BrowserLeftClickDragConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -// Returns the unmodified JSON received from the API -func (r CitationsConfig) RawJSON() string { return r.JSON.raw } -func (r *CitationsConfig) UnmarshalJSON(data []byte) error { +func (r BrowserLeftClickDragConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BrowserLeftClickDragConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BrowserLeftClickDragConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type CitationsConfigParam struct { +// `left_mouse_down`'s config overrides. +type BrowserLeftMouseDownConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. Enabled param.Opt[bool] `json:"enabled,omitzero"` paramObj } -func (r CitationsConfigParam) MarshalJSON() (data []byte, err error) { - type shadow CitationsConfigParam +func (r BrowserLeftMouseDownConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BrowserLeftMouseDownConfigParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *CitationsConfigParam) UnmarshalJSON(data []byte) error { +func (r *BrowserLeftMouseDownConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type CitationsDelta struct { - Citation CitationsDeltaCitationUnion `json:"citation" api:"required"` - Type constant.CitationsDelta `json:"type" default:"citations_delta"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Citation respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +// `left_mouse_up`'s config overrides. +type BrowserLeftMouseUpConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -// Returns the unmodified JSON received from the API -func (r CitationsDelta) RawJSON() string { return r.JSON.raw } -func (r *CitationsDelta) UnmarshalJSON(data []byte) error { +func (r BrowserLeftMouseUpConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BrowserLeftMouseUpConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BrowserLeftMouseUpConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// CitationsDeltaCitationUnion contains all possible properties and values from -// [CitationCharLocation], [CitationPageLocation], [CitationContentBlockLocation], -// [CitationsWebSearchResultLocation], [CitationsSearchResultLocation]. -// -// Use the [CitationsDeltaCitationUnion.AsAny] method to switch on the variant. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -type CitationsDeltaCitationUnion struct { - CitedText string `json:"cited_text"` - DocumentIndex int64 `json:"document_index"` - DocumentTitle string `json:"document_title"` - // This field is from variant [CitationCharLocation]. - EndCharIndex int64 `json:"end_char_index"` - FileID string `json:"file_id"` - // This field is from variant [CitationCharLocation]. - StartCharIndex int64 `json:"start_char_index"` - // Any of "char_location", "page_location", "content_block_location", - // "web_search_result_location", "search_result_location". - Type string `json:"type"` - // This field is from variant [CitationPageLocation]. - EndPageNumber int64 `json:"end_page_number"` - // This field is from variant [CitationPageLocation]. - StartPageNumber int64 `json:"start_page_number"` - EndBlockIndex int64 `json:"end_block_index"` - StartBlockIndex int64 `json:"start_block_index"` - // This field is from variant [CitationsWebSearchResultLocation]. - EncryptedIndex string `json:"encrypted_index"` - Title string `json:"title"` - // This field is from variant [CitationsWebSearchResultLocation]. - URL string `json:"url"` - // This field is from variant [CitationsSearchResultLocation]. - SearchResultIndex int64 `json:"search_result_index"` - // This field is from variant [CitationsSearchResultLocation]. - Source string `json:"source"` - JSON struct { - CitedText respjson.Field - DocumentIndex respjson.Field - DocumentTitle respjson.Field - EndCharIndex respjson.Field - FileID respjson.Field - StartCharIndex respjson.Field - Type respjson.Field - EndPageNumber respjson.Field - StartPageNumber respjson.Field - EndBlockIndex respjson.Field - StartBlockIndex respjson.Field - EncryptedIndex respjson.Field - Title respjson.Field - URL respjson.Field - SearchResultIndex respjson.Field - Source respjson.Field - raw string - } `json:"-"` +// `list_tabs`'s config overrides. +type BrowserListTabsConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -// anyCitationsDeltaCitation is implemented by each variant of -// [CitationsDeltaCitationUnion] to add type safety for the return type of -// [CitationsDeltaCitationUnion.AsAny] -type anyCitationsDeltaCitation interface { - implCitationsDeltaCitationUnion() +func (r BrowserListTabsConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BrowserListTabsConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BrowserListTabsConfigParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func (CitationCharLocation) implCitationsDeltaCitationUnion() {} -func (CitationPageLocation) implCitationsDeltaCitationUnion() {} -func (CitationContentBlockLocation) implCitationsDeltaCitationUnion() {} -func (CitationsWebSearchResultLocation) implCitationsDeltaCitationUnion() {} -func (CitationsSearchResultLocation) implCitationsDeltaCitationUnion() {} - -// Use the following switch statement to find the correct variant -// -// switch variant := CitationsDeltaCitationUnion.AsAny().(type) { -// case anthropic.CitationCharLocation: -// case anthropic.CitationPageLocation: -// case anthropic.CitationContentBlockLocation: -// case anthropic.CitationsWebSearchResultLocation: -// case anthropic.CitationsSearchResultLocation: -// default: -// fmt.Errorf("no variant present") -// } -func (u CitationsDeltaCitationUnion) AsAny() anyCitationsDeltaCitation { - switch u.Type { - case "char_location": - return u.AsCharLocation() - case "page_location": - return u.AsPageLocation() - case "content_block_location": - return u.AsContentBlockLocation() - case "web_search_result_location": - return u.AsWebSearchResultLocation() - case "search_result_location": - return u.AsSearchResultLocation() - } - return nil +// `middle_click`'s config overrides. +type BrowserMiddleClickConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -func (u CitationsDeltaCitationUnion) AsCharLocation() (v CitationCharLocation) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +func (r BrowserMiddleClickConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BrowserMiddleClickConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BrowserMiddleClickConfigParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func (u CitationsDeltaCitationUnion) AsPageLocation() (v CitationPageLocation) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +// `mouse_move`'s config overrides. +type BrowserMouseMoveConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -func (u CitationsDeltaCitationUnion) AsContentBlockLocation() (v CitationContentBlockLocation) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +func (r BrowserMouseMoveConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BrowserMouseMoveConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BrowserMouseMoveConfigParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func (u CitationsDeltaCitationUnion) AsWebSearchResultLocation() (v CitationsWebSearchResultLocation) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +// `navigate`'s config overrides. +type BrowserNavigateConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -func (u CitationsDeltaCitationUnion) AsSearchResultLocation() (v CitationsSearchResultLocation) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +func (r BrowserNavigateConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BrowserNavigateConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BrowserNavigateConfigParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns the unmodified JSON received from the API -func (u CitationsDeltaCitationUnion) RawJSON() string { return u.JSON.raw } +// `new_tab`'s config overrides. +type BrowserNewTabConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj +} -func (r *CitationsDeltaCitationUnion) UnmarshalJSON(data []byte) error { +func (r BrowserNewTabConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BrowserNewTabConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BrowserNewTabConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type CitationsSearchResultLocation struct { - CitedText string `json:"cited_text" api:"required"` - EndBlockIndex int64 `json:"end_block_index" api:"required"` - SearchResultIndex int64 `json:"search_result_index" api:"required"` - Source string `json:"source" api:"required"` - StartBlockIndex int64 `json:"start_block_index" api:"required"` - Title string `json:"title" api:"required"` - Type constant.SearchResultLocation `json:"type" default:"search_result_location"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - CitedText respjson.Field - EndBlockIndex respjson.Field - SearchResultIndex respjson.Field - Source respjson.Field - StartBlockIndex respjson.Field - Title respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +// `read_console`'s config overrides. +type BrowserReadConsoleConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -// Returns the unmodified JSON received from the API -func (r CitationsSearchResultLocation) RawJSON() string { return r.JSON.raw } -func (r *CitationsSearchResultLocation) UnmarshalJSON(data []byte) error { +func (r BrowserReadConsoleConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BrowserReadConsoleConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BrowserReadConsoleConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type CitationsWebSearchResultLocation struct { - CitedText string `json:"cited_text" api:"required"` - EncryptedIndex string `json:"encrypted_index" api:"required"` - Title string `json:"title" api:"required"` - Type constant.WebSearchResultLocation `json:"type" default:"web_search_result_location"` - URL string `json:"url" api:"required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - CitedText respjson.Field - EncryptedIndex respjson.Field - Title respjson.Field - Type respjson.Field - URL respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +// `read_network`'s config overrides. +type BrowserReadNetworkConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -// Returns the unmodified JSON received from the API -func (r CitationsWebSearchResultLocation) RawJSON() string { return r.JSON.raw } -func (r *CitationsWebSearchResultLocation) UnmarshalJSON(data []byte) error { +func (r BrowserReadNetworkConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BrowserReadNetworkConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BrowserReadNetworkConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type CodeExecutionOutputBlock struct { - FileID string `json:"file_id" api:"required"` - Type constant.CodeExecutionOutput `json:"type" default:"code_execution_output"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - FileID respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +// `read_page`'s config overrides. +type BrowserReadPageConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -// Returns the unmodified JSON received from the API -func (r CodeExecutionOutputBlock) RawJSON() string { return r.JSON.raw } -func (r *CodeExecutionOutputBlock) UnmarshalJSON(data []byte) error { +func (r BrowserReadPageConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BrowserReadPageConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BrowserReadPageConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The properties FileID, Type are required. -type CodeExecutionOutputBlockParam struct { - FileID string `json:"file_id" api:"required"` - // This field can be elided, and will marshal its zero value as - // "code_execution_output". - Type constant.CodeExecutionOutput `json:"type" default:"code_execution_output"` +// `right_click`'s config overrides. +type BrowserRightClickConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` paramObj } -func (r CodeExecutionOutputBlockParam) MarshalJSON() (data []byte, err error) { - type shadow CodeExecutionOutputBlockParam +func (r BrowserRightClickConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BrowserRightClickConfigParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *CodeExecutionOutputBlockParam) UnmarshalJSON(data []byte) error { +func (r *BrowserRightClickConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type CodeExecutionResultBlock struct { - Content []CodeExecutionOutputBlock `json:"content" api:"required"` - ReturnCode int64 `json:"return_code" api:"required"` - Stderr string `json:"stderr" api:"required"` - Stdout string `json:"stdout" api:"required"` - Type constant.CodeExecutionResult `json:"type" default:"code_execution_result"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Content respjson.Field - ReturnCode respjson.Field - Stderr respjson.Field - Stdout respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +// `screenshot`'s config overrides. +type BrowserScreenshotConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -// Returns the unmodified JSON received from the API -func (r CodeExecutionResultBlock) RawJSON() string { return r.JSON.raw } -func (r *CodeExecutionResultBlock) UnmarshalJSON(data []byte) error { +func (r BrowserScreenshotConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BrowserScreenshotConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BrowserScreenshotConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The properties Content, ReturnCode, Stderr, Stdout, Type are required. -type CodeExecutionResultBlockParam struct { - Content []CodeExecutionOutputBlockParam `json:"content,omitzero" api:"required"` - ReturnCode int64 `json:"return_code" api:"required"` - Stderr string `json:"stderr" api:"required"` - Stdout string `json:"stdout" api:"required"` - // This field can be elided, and will marshal its zero value as - // "code_execution_result". - Type constant.CodeExecutionResult `json:"type" default:"code_execution_result"` +// `scroll`'s config overrides. +type BrowserScrollConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` paramObj } -func (r CodeExecutionResultBlockParam) MarshalJSON() (data []byte, err error) { - type shadow CodeExecutionResultBlockParam +func (r BrowserScrollConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BrowserScrollConfigParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *CodeExecutionResultBlockParam) UnmarshalJSON(data []byte) error { +func (r *BrowserScrollConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The properties Name, Type are required. -type CodeExecutionTool20250522Param struct { - // If true, tool will not be included in initial system prompt. Only loaded when - // returned via tool_reference from tool search. +// `scroll_to`'s config overrides. +type BrowserScrollToConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` - // When true, guarantees schema validation on tool names and inputs - Strict param.Opt[bool] `json:"strict,omitzero"` - // Any of "direct", "code_execution_20250825", "code_execution_20260120". - AllowedCallers []string `json:"allowed_callers,omitzero"` - // Create a cache control breakpoint at this content block. - CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` - // Name of the tool. - // - // This is how the tool will be called by the model and in `tool_use` blocks. - // - // This field can be elided, and will marshal its zero value as "code_execution". - Name constant.CodeExecution `json:"name" default:"code_execution"` - // This field can be elided, and will marshal its zero value as - // "code_execution_20250522". - Type constant.CodeExecution20250522 `json:"type" default:"code_execution_20250522"` - paramObj -} - -func (r CodeExecutionTool20250522Param) MarshalJSON() (data []byte, err error) { - type shadow CodeExecutionTool20250522Param - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *CodeExecutionTool20250522Param) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The properties Name, Type are required. -type CodeExecutionTool20250825Param struct { - // If true, tool will not be included in initial system prompt. Only loaded when - // returned via tool_reference from tool search. - DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` - // When true, guarantees schema validation on tool names and inputs - Strict param.Opt[bool] `json:"strict,omitzero"` - // Any of "direct", "code_execution_20250825", "code_execution_20260120". - AllowedCallers []string `json:"allowed_callers,omitzero"` - // Create a cache control breakpoint at this content block. - CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` - // Name of the tool. - // - // This is how the tool will be called by the model and in `tool_use` blocks. - // - // This field can be elided, and will marshal its zero value as "code_execution". - Name constant.CodeExecution `json:"name" default:"code_execution"` - // This field can be elided, and will marshal its zero value as - // "code_execution_20250825". - Type constant.CodeExecution20250825 `json:"type" default:"code_execution_20250825"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` paramObj } -func (r CodeExecutionTool20250825Param) MarshalJSON() (data []byte, err error) { - type shadow CodeExecutionTool20250825Param +func (r BrowserScrollToConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BrowserScrollToConfigParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *CodeExecutionTool20250825Param) UnmarshalJSON(data []byte) error { +func (r *BrowserScrollToConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// Code execution tool with REPL state persistence (daemon mode + gVisor -// checkpoint). +// The caller's browser state after a browser toolset member call — the full +// inventory of open tabs, which tab is active, and any side effects (tabs opened, +// download state changes) the call produced. // -// The properties Name, Type are required. -type CodeExecutionTool20260120Param struct { - // If true, tool will not be included in initial system prompt. Only loaded when - // returned via tool_reference from tool search. - DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` - // When true, guarantees schema validation on tool names and inputs - Strict param.Opt[bool] `json:"strict,omitzero"` - // Any of "direct", "code_execution_20250825", "code_execution_20260120". - AllowedCallers []string `json:"allowed_callers,omitzero"` +// At most one per `tool_result`, only on a non-error result answering a browser +// toolset member `tool_use`. The server renders the model-visible text from it; +// the model never sees the raw fields. +// +// The properties Tabs, Type are required. +type BrowserStateBlockParam struct { + // All tabs open in the browser after this call — the full inventory, not a delta. + // May be empty. Whenever non-empty, exactly one entry carries `active: true`. + Tabs []BrowserStateTabEntryParam `json:"tabs,omitzero" api:"required"` + // Tabs opened and download state changes during this call. "Nothing to report" is + // expressed by omitting the field, never by an empty list. + StateChanges []BrowserStateChangeUnionParam `json:"state_changes,omitzero"` // Create a cache control breakpoint at this content block. CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` - // Name of the tool. - // - // This is how the tool will be called by the model and in `tool_use` blocks. - // - // This field can be elided, and will marshal its zero value as "code_execution". - Name constant.CodeExecution `json:"name" default:"code_execution"` - // This field can be elided, and will marshal its zero value as - // "code_execution_20260120". - Type constant.CodeExecution20260120 `json:"type" default:"code_execution_20260120"` + // This field can be elided, and will marshal its zero value as "browser_state". + Type constant.BrowserState `json:"type" default:"browser_state"` paramObj } -func (r CodeExecutionTool20260120Param) MarshalJSON() (data []byte, err error) { - type shadow CodeExecutionTool20260120Param +func (r BrowserStateBlockParam) MarshalJSON() (data []byte, err error) { + type shadow BrowserStateBlockParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *CodeExecutionTool20260120Param) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type CodeExecutionToolResultBlock struct { - // Code execution result with encrypted stdout for PFC + web_search results. - Content CodeExecutionToolResultBlockContentUnion `json:"content" api:"required"` - ToolUseID string `json:"tool_use_id" api:"required"` - Type constant.CodeExecutionToolResult `json:"type" default:"code_execution_tool_result"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Content respjson.Field - ToolUseID respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r CodeExecutionToolResultBlock) RawJSON() string { return r.JSON.raw } -func (r *CodeExecutionToolResultBlock) UnmarshalJSON(data []byte) error { +func (r *BrowserStateBlockParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// CodeExecutionToolResultBlockContentUnion contains all possible properties and -// values from [CodeExecutionToolResultError], [CodeExecutionResultBlock], -// [EncryptedCodeExecutionResultBlock]. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -type CodeExecutionToolResultBlockContentUnion struct { - // This field is from variant [CodeExecutionToolResultError]. - ErrorCode CodeExecutionToolResultErrorCode `json:"error_code"` - Type string `json:"type"` - Content []CodeExecutionOutputBlock `json:"content"` - ReturnCode int64 `json:"return_code"` - Stderr string `json:"stderr"` - // This field is from variant [CodeExecutionResultBlock]. - Stdout string `json:"stdout"` - // This field is from variant [EncryptedCodeExecutionResultBlock]. - EncryptedStdout string `json:"encrypted_stdout"` - JSON struct { - ErrorCode respjson.Field - Type respjson.Field - Content respjson.Field - ReturnCode respjson.Field - Stderr respjson.Field - Stdout respjson.Field - EncryptedStdout respjson.Field - raw string - } `json:"-"` -} - -func (u CodeExecutionToolResultBlockContentUnion) AsResponseCodeExecutionToolResultError() (v CodeExecutionToolResultError) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u CodeExecutionToolResultBlockContentUnion) AsResponseCodeExecutionResultBlock() (v CodeExecutionResultBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u CodeExecutionToolResultBlockContentUnion) AsResponseEncryptedCodeExecutionResultBlock() (v EncryptedCodeExecutionResultBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -// Returns the unmodified JSON received from the API -func (u CodeExecutionToolResultBlockContentUnion) RawJSON() string { return u.JSON.raw } - -func (r *CodeExecutionToolResultBlockContentUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +func BrowserStateChangeParamOfTabOpened(tabID string) BrowserStateChangeUnionParam { + var tabOpened BrowserStateChangeTabOpenedParam + tabOpened.TabID = tabID + return BrowserStateChangeUnionParam{OfTabOpened: &tabOpened} } -// The properties Content, ToolUseID, Type are required. -type CodeExecutionToolResultBlockParam struct { - // Code execution result with encrypted stdout for PFC + web_search results. - Content CodeExecutionToolResultBlockParamContentUnion `json:"content,omitzero" api:"required"` - ToolUseID string `json:"tool_use_id" api:"required"` - // Create a cache control breakpoint at this content block. - CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` - // This field can be elided, and will marshal its zero value as - // "code_execution_tool_result". - Type constant.CodeExecutionToolResult `json:"type" default:"code_execution_tool_result"` - paramObj +func BrowserStateChangeParamOfDownloadStarted(downloadID string, url string) BrowserStateChangeUnionParam { + var downloadStarted BrowserStateChangeDownloadStartedParam + downloadStarted.DownloadID = downloadID + downloadStarted.URL = url + return BrowserStateChangeUnionParam{OfDownloadStarted: &downloadStarted} } -func (r CodeExecutionToolResultBlockParam) MarshalJSON() (data []byte, err error) { - type shadow CodeExecutionToolResultBlockParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *CodeExecutionToolResultBlockParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +func BrowserStateChangeParamOfDownloadCompleted(downloadID string, url string) BrowserStateChangeUnionParam { + var downloadCompleted BrowserStateChangeDownloadCompletedParam + downloadCompleted.DownloadID = downloadID + downloadCompleted.URL = url + return BrowserStateChangeUnionParam{OfDownloadCompleted: &downloadCompleted} } -func CodeExecutionToolResultBlockParamContentOfRequestCodeExecutionToolResultError(errorCode CodeExecutionToolResultErrorCode) CodeExecutionToolResultBlockParamContentUnion { - var variant CodeExecutionToolResultErrorParam - variant.ErrorCode = errorCode - return CodeExecutionToolResultBlockParamContentUnion{OfRequestCodeExecutionToolResultError: &variant} +func BrowserStateChangeParamOfDownloadFailed(downloadID string, url string) BrowserStateChangeUnionParam { + var downloadFailed BrowserStateChangeDownloadFailedParam + downloadFailed.DownloadID = downloadID + downloadFailed.URL = url + return BrowserStateChangeUnionParam{OfDownloadFailed: &downloadFailed} } // Only one field can be non-zero. // // Use [param.IsOmitted] to confirm if a field is set. -type CodeExecutionToolResultBlockParamContentUnion struct { - OfRequestCodeExecutionToolResultError *CodeExecutionToolResultErrorParam `json:",omitzero,inline"` - OfRequestCodeExecutionResultBlock *CodeExecutionResultBlockParam `json:",omitzero,inline"` - OfRequestEncryptedCodeExecutionResultBlock *EncryptedCodeExecutionResultBlockParam `json:",omitzero,inline"` +type BrowserStateChangeUnionParam struct { + OfTabOpened *BrowserStateChangeTabOpenedParam `json:",omitzero,inline"` + OfDownloadStarted *BrowserStateChangeDownloadStartedParam `json:",omitzero,inline"` + OfDownloadCompleted *BrowserStateChangeDownloadCompletedParam `json:",omitzero,inline"` + OfDownloadFailed *BrowserStateChangeDownloadFailedParam `json:",omitzero,inline"` paramUnion } -func (u CodeExecutionToolResultBlockParamContentUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfRequestCodeExecutionToolResultError, u.OfRequestCodeExecutionResultBlock, u.OfRequestEncryptedCodeExecutionResultBlock) +func (u BrowserStateChangeUnionParam) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfTabOpened, u.OfDownloadStarted, u.OfDownloadCompleted, u.OfDownloadFailed) } -func (u *CodeExecutionToolResultBlockParamContentUnion) UnmarshalJSON(data []byte) error { +func (u *BrowserStateChangeUnionParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, u) } -func (u *CodeExecutionToolResultBlockParamContentUnion) asAny() any { - if !param.IsOmitted(u.OfRequestCodeExecutionToolResultError) { - return u.OfRequestCodeExecutionToolResultError - } else if !param.IsOmitted(u.OfRequestCodeExecutionResultBlock) { - return u.OfRequestCodeExecutionResultBlock - } else if !param.IsOmitted(u.OfRequestEncryptedCodeExecutionResultBlock) { - return u.OfRequestEncryptedCodeExecutionResultBlock +func (u *BrowserStateChangeUnionParam) asAny() any { + if !param.IsOmitted(u.OfTabOpened) { + return u.OfTabOpened + } else if !param.IsOmitted(u.OfDownloadStarted) { + return u.OfDownloadStarted + } else if !param.IsOmitted(u.OfDownloadCompleted) { + return u.OfDownloadCompleted + } else if !param.IsOmitted(u.OfDownloadFailed) { + return u.OfDownloadFailed } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u CodeExecutionToolResultBlockParamContentUnion) GetErrorCode() *string { - if vt := u.OfRequestCodeExecutionToolResultError; vt != nil { - return (*string)(&vt.ErrorCode) +func (u BrowserStateChangeUnionParam) GetTabID() *string { + if vt := u.OfTabOpened; vt != nil { + return &vt.TabID } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u CodeExecutionToolResultBlockParamContentUnion) GetStdout() *string { - if vt := u.OfRequestCodeExecutionResultBlock; vt != nil { - return &vt.Stdout +func (u BrowserStateChangeUnionParam) GetPath() *string { + if vt := u.OfDownloadCompleted; vt != nil && vt.Path.Valid() { + return &vt.Path.Value } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u CodeExecutionToolResultBlockParamContentUnion) GetEncryptedStdout() *string { - if vt := u.OfRequestEncryptedCodeExecutionResultBlock; vt != nil { - return &vt.EncryptedStdout +func (u BrowserStateChangeUnionParam) GetSizeBytes() *int64 { + if vt := u.OfDownloadCompleted; vt != nil && vt.SizeBytes.Valid() { + return &vt.SizeBytes.Value } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u CodeExecutionToolResultBlockParamContentUnion) GetType() *string { - if vt := u.OfRequestCodeExecutionToolResultError; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfRequestCodeExecutionResultBlock; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfRequestEncryptedCodeExecutionResultBlock; vt != nil { - return (*string)(&vt.Type) +func (u BrowserStateChangeUnionParam) GetError() *string { + if vt := u.OfDownloadFailed; vt != nil && vt.Error.Valid() { + return &vt.Error.Value } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u CodeExecutionToolResultBlockParamContentUnion) GetReturnCode() *int64 { - if vt := u.OfRequestCodeExecutionResultBlock; vt != nil { - return (*int64)(&vt.ReturnCode) - } else if vt := u.OfRequestEncryptedCodeExecutionResultBlock; vt != nil { - return (*int64)(&vt.ReturnCode) +func (u BrowserStateChangeUnionParam) GetType() *string { + if vt := u.OfTabOpened; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfDownloadStarted; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfDownloadCompleted; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfDownloadFailed; vt != nil { + return (*string)(&vt.Type) } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u CodeExecutionToolResultBlockParamContentUnion) GetStderr() *string { - if vt := u.OfRequestCodeExecutionResultBlock; vt != nil { - return (*string)(&vt.Stderr) - } else if vt := u.OfRequestEncryptedCodeExecutionResultBlock; vt != nil { - return (*string)(&vt.Stderr) +func (u BrowserStateChangeUnionParam) GetDownloadID() *string { + if vt := u.OfDownloadStarted; vt != nil { + return (*string)(&vt.DownloadID) + } else if vt := u.OfDownloadCompleted; vt != nil { + return (*string)(&vt.DownloadID) + } else if vt := u.OfDownloadFailed; vt != nil { + return (*string)(&vt.DownloadID) } return nil } -// Returns a pointer to the underlying variant's Content property, if present. -func (u CodeExecutionToolResultBlockParamContentUnion) GetContent() []CodeExecutionOutputBlockParam { - if vt := u.OfRequestCodeExecutionResultBlock; vt != nil { - return vt.Content - } else if vt := u.OfRequestEncryptedCodeExecutionResultBlock; vt != nil { - return vt.Content +// Returns a pointer to the underlying variant's property, if present. +func (u BrowserStateChangeUnionParam) GetURL() *string { + if vt := u.OfDownloadStarted; vt != nil { + return (*string)(&vt.URL) + } else if vt := u.OfDownloadCompleted; vt != nil { + return (*string)(&vt.URL) + } else if vt := u.OfDownloadFailed; vt != nil { + return (*string)(&vt.URL) } return nil } -type CodeExecutionToolResultError struct { - // Any of "invalid_tool_input", "unavailable", "too_many_requests", - // "execution_time_exceeded". - ErrorCode CodeExecutionToolResultErrorCode `json:"error_code" api:"required"` - Type constant.CodeExecutionToolResultError `json:"type" default:"code_execution_tool_result_error"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ErrorCode respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r CodeExecutionToolResultError) RawJSON() string { return r.JSON.raw } -func (r *CodeExecutionToolResultError) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +func init() { + apijson.RegisterUnion[BrowserStateChangeUnionParam]( + "type", + apijson.Discriminator[BrowserStateChangeTabOpenedParam]("tab_opened"), + apijson.Discriminator[BrowserStateChangeDownloadStartedParam]("download_started"), + apijson.Discriminator[BrowserStateChangeDownloadCompletedParam]("download_completed"), + apijson.Discriminator[BrowserStateChangeDownloadFailedParam]("download_failed"), + ) } -type CodeExecutionToolResultErrorCode string - -const ( - CodeExecutionToolResultErrorCodeInvalidToolInput CodeExecutionToolResultErrorCode = "invalid_tool_input" - CodeExecutionToolResultErrorCodeUnavailable CodeExecutionToolResultErrorCode = "unavailable" - CodeExecutionToolResultErrorCodeTooManyRequests CodeExecutionToolResultErrorCode = "too_many_requests" - CodeExecutionToolResultErrorCodeExecutionTimeExceeded CodeExecutionToolResultErrorCode = "execution_time_exceeded" -) - -// The properties ErrorCode, Type are required. -type CodeExecutionToolResultErrorParam struct { - // Any of "invalid_tool_input", "unavailable", "too_many_requests", - // "execution_time_exceeded". - ErrorCode CodeExecutionToolResultErrorCode `json:"error_code,omitzero" api:"required"` +// A file download that finished during this call, reported with the same +// `download_id` as its `download_started` — or without a prior `download_started`, +// when the download finished during the call that started it (at most one state +// change per `download_id` per result). +// +// The properties DownloadID, Type, URL are required. +type BrowserStateChangeDownloadCompletedParam struct { + // The caller-assigned identifier for this download, stable across the state + // changes reporting it. + DownloadID string `json:"download_id" api:"required"` + // The final post-redirect URL the download was served from. + URL string `json:"url" api:"required"` + // Where the executor saved the file, on the executor's filesystem. Only included + // when another tool in the same environment can read the file at that path. + Path param.Opt[string] `json:"path,omitzero"` + // The completed download's size. + SizeBytes param.Opt[int64] `json:"size_bytes,omitzero"` // This field can be elided, and will marshal its zero value as - // "code_execution_tool_result_error". - Type constant.CodeExecutionToolResultError `json:"type" default:"code_execution_tool_result_error"` + // "download_completed". + Type constant.DownloadCompleted `json:"type" default:"download_completed"` paramObj } -func (r CodeExecutionToolResultErrorParam) MarshalJSON() (data []byte, err error) { - type shadow CodeExecutionToolResultErrorParam +func (r BrowserStateChangeDownloadCompletedParam) MarshalJSON() (data []byte, err error) { + type shadow BrowserStateChangeDownloadCompletedParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *CodeExecutionToolResultErrorParam) UnmarshalJSON(data []byte) error { +func (r *BrowserStateChangeDownloadCompletedParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// Information about the container used in the request (for the code execution -// tool) -type Container struct { - // Identifier for the container used in this request - ID string `json:"id" api:"required"` - // The time at which the container will expire. - ExpiresAt time.Time `json:"expires_at" api:"required" format:"date-time"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ID respjson.Field - ExpiresAt respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +// A file download that failed — or was cancelled — during this call. +// +// The properties DownloadID, Type, URL are required. +type BrowserStateChangeDownloadFailedParam struct { + // The caller-assigned identifier for this download, stable across the state + // changes reporting it. + DownloadID string `json:"download_id" api:"required"` + // The final post-redirect URL the download was served from. + URL string `json:"url" api:"required"` + // The failure or cancellation detail, when known. + Error param.Opt[string] `json:"error,omitzero"` + // This field can be elided, and will marshal its zero value as "download_failed". + Type constant.DownloadFailed `json:"type" default:"download_failed"` + paramObj } -// Returns the unmodified JSON received from the API -func (r Container) RawJSON() string { return r.JSON.raw } -func (r *Container) UnmarshalJSON(data []byte) error { +func (r BrowserStateChangeDownloadFailedParam) MarshalJSON() (data []byte, err error) { + type shadow BrowserStateChangeDownloadFailedParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BrowserStateChangeDownloadFailedParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// Response model for a file uploaded to the container. -type ContainerUploadBlock struct { - FileID string `json:"file_id" api:"required"` - Type constant.ContainerUpload `json:"type" default:"container_upload"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - FileID respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +// A file download that started during this call. +// +// The properties DownloadID, Type, URL are required. +type BrowserStateChangeDownloadStartedParam struct { + // The caller-assigned identifier for this download, stable across the state + // changes reporting it. + DownloadID string `json:"download_id" api:"required"` + // The final post-redirect URL the download was served from. + URL string `json:"url" api:"required"` + // This field can be elided, and will marshal its zero value as "download_started". + Type constant.DownloadStarted `json:"type" default:"download_started"` + paramObj } -// Returns the unmodified JSON received from the API -func (r ContainerUploadBlock) RawJSON() string { return r.JSON.raw } -func (r *ContainerUploadBlock) UnmarshalJSON(data []byte) error { +func (r BrowserStateChangeDownloadStartedParam) MarshalJSON() (data []byte, err error) { + type shadow BrowserStateChangeDownloadStartedParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BrowserStateChangeDownloadStartedParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// A content block that represents a file to be uploaded to the container Files -// uploaded via this block will be available in the container's input directory. +// A tab this call's execution opened that remains open at its end — the creation +// delta of the `tabs` inventory, not an event log. // -// The properties FileID, Type are required. -type ContainerUploadBlockParam struct { - FileID string `json:"file_id" api:"required"` - // Create a cache control breakpoint at this content block. - CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` - // This field can be elided, and will marshal its zero value as "container_upload". - Type constant.ContainerUpload `json:"type" default:"container_upload"` +// Carries only the `tab_id`; the tab's `title` and `url` live on its `tabs` entry, +// which must include the same `tab_id`. A tab opened during a failed call gets no +// deferred `tab_opened`; it simply appears in the next result's `tabs` inventory. +// +// The properties TabID, Type are required. +type BrowserStateChangeTabOpenedParam struct { + // The `tab_id` of the opened tab, present in `tabs`. + TabID string `json:"tab_id" api:"required"` + // This field can be elided, and will marshal its zero value as "tab_opened". + Type constant.TabOpened `json:"type" default:"tab_opened"` paramObj } -func (r ContainerUploadBlockParam) MarshalJSON() (data []byte, err error) { - type shadow ContainerUploadBlockParam +func (r BrowserStateChangeTabOpenedParam) MarshalJSON() (data []byte, err error) { + type shadow BrowserStateChangeTabOpenedParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *ContainerUploadBlockParam) UnmarshalJSON(data []byte) error { +func (r *BrowserStateChangeTabOpenedParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// ContentBlockUnion contains all possible properties and values from [TextBlock], -// [ThinkingBlock], [RedactedThinkingBlock], [ToolUseBlock], [ServerToolUseBlock], -// [WebSearchToolResultBlock], [WebFetchToolResultBlock], -// [CodeExecutionToolResultBlock], [BashCodeExecutionToolResultBlock], -// [TextEditorCodeExecutionToolResultBlock], [ToolSearchToolResultBlock], -// [ContainerUploadBlock]. +// One open browser tab reported in a `browser_state` block's `tabs` inventory. // -// Use the [ContentBlockUnion.AsAny] method to switch on the variant. +// `tab_id` is the caller-assigned identifier for the tab; `title` and `url` +// describe the page the tab is currently showing and may be empty strings (a blank +// tab legitimately has both empty). `active` marks the tab that is active after +// this call; whenever `tabs` is non-empty, exactly one entry is marked. // -// Use the methods beginning with 'As' to cast the union to one of its variants. -type ContentBlockUnion struct { - // This field is from variant [TextBlock]. - Citations []TextCitationUnion `json:"citations"` - // This field is from variant [TextBlock]. - Text string `json:"text"` - // Any of "text", "thinking", "redacted_thinking", "tool_use", "server_tool_use", - // "web_search_tool_result", "web_fetch_tool_result", "code_execution_tool_result", - // "bash_code_execution_tool_result", "text_editor_code_execution_tool_result", - // "tool_search_tool_result", "container_upload". - Type string `json:"type"` - // This field is from variant [ThinkingBlock]. - Signature string `json:"signature"` - // This field is from variant [ThinkingBlock]. - Thinking string `json:"thinking"` - // This field is from variant [RedactedThinkingBlock]. - Data string `json:"data"` - ID string `json:"id"` - // necessary custom code modification - Input json.RawMessage `json:"input"` - Name string `json:"name"` - // This field is from variant [WebSearchToolResultBlock]. - Content WebSearchToolResultBlockContentUnion `json:"content"` - // This field is from variant [WebSearchToolResultBlock]. - ToolUseID string `json:"tool_use_id"` - JSON struct { - Citations respjson.Field - Text respjson.Field - Type respjson.Field - Signature respjson.Field - Thinking respjson.Field - Data respjson.Field - ID respjson.Field - Caller respjson.Field - Input respjson.Field - Name respjson.Field - Content respjson.Field - ToolUseID respjson.Field - FileID respjson.Field - raw string - } `json:"-"` +// The properties TabID, Title, URL are required. +type BrowserStateTabEntryParam struct { + // The caller-assigned identifier for this tab, unique within the inventory. + TabID string `json:"tab_id" api:"required"` + // The title of the page the tab is showing. May be empty. + Title string `json:"title" api:"required"` + // The URL of the page the tab is showing. May be empty. + URL string `json:"url" api:"required"` + // Whether this tab is the active tab after this call. Whenever `tabs` is + // non-empty, exactly one entry is marked `active: true`. + Active param.Opt[bool] `json:"active,omitzero"` + paramObj } -// anyContentBlock is implemented by each variant of [ContentBlockUnion] to add -// type safety for the return type of [ContentBlockUnion.AsAny] -type anyContentBlock interface { - implContentBlockUnion() - toParamUnion() ContentBlockParamUnion +func (r BrowserStateTabEntryParam) MarshalJSON() (data []byte, err error) { + type shadow BrowserStateTabEntryParam + return param.MarshalObject(r, (*shadow)(&r)) } - -func (TextBlock) implContentBlockUnion() {} -func (ThinkingBlock) implContentBlockUnion() {} -func (RedactedThinkingBlock) implContentBlockUnion() {} -func (ToolUseBlock) implContentBlockUnion() {} -func (ServerToolUseBlock) implContentBlockUnion() {} -func (WebSearchToolResultBlock) implContentBlockUnion() {} -func (WebFetchToolResultBlock) implContentBlockUnion() {} -func (CodeExecutionToolResultBlock) implContentBlockUnion() {} -func (BashCodeExecutionToolResultBlock) implContentBlockUnion() {} -func (TextEditorCodeExecutionToolResultBlock) implContentBlockUnion() {} -func (ToolSearchToolResultBlock) implContentBlockUnion() {} -func (ContainerUploadBlock) implContentBlockUnion() {} - -// Use the following switch statement to find the correct variant -// -// switch variant := ContentBlockUnion.AsAny().(type) { -// case anthropic.TextBlock: -// case anthropic.ThinkingBlock: -// case anthropic.RedactedThinkingBlock: -// case anthropic.ToolUseBlock: -// case anthropic.ServerToolUseBlock: -// case anthropic.WebSearchToolResultBlock: -// case anthropic.WebFetchToolResultBlock: -// case anthropic.CodeExecutionToolResultBlock: -// case anthropic.BashCodeExecutionToolResultBlock: -// case anthropic.TextEditorCodeExecutionToolResultBlock: -// case anthropic.ToolSearchToolResultBlock: -// case anthropic.ContainerUploadBlock: -// default: -// fmt.Errorf("no variant present") -// } -func (u ContentBlockUnion) AsAny() anyContentBlock { - switch u.Type { - case "text": - return u.AsText() - case "thinking": - return u.AsThinking() - case "redacted_thinking": - return u.AsRedactedThinking() - case "tool_use": - return u.AsToolUse() - case "server_tool_use": - return u.AsServerToolUse() - case "web_search_tool_result": - return u.AsWebSearchToolResult() - case "web_fetch_tool_result": - return u.AsWebFetchToolResult() - case "code_execution_tool_result": - return u.AsCodeExecutionToolResult() - case "bash_code_execution_tool_result": - return u.AsBashCodeExecutionToolResult() - case "text_editor_code_execution_tool_result": - return u.AsTextEditorCodeExecutionToolResult() - case "tool_search_tool_result": - return u.AsToolSearchToolResult() - case "container_upload": - return u.AsContainerUpload() - } - return nil +func (r *BrowserStateTabEntryParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func (u ContentBlockUnion) AsText() (v TextBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +// `switch_tab`'s config overrides. +type BrowserSwitchTabConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -func (u ContentBlockUnion) AsThinking() (v ThinkingBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +func (r BrowserSwitchTabConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BrowserSwitchTabConfigParam + return param.MarshalObject(r, (*shadow)(&r)) } - -func (u ContentBlockUnion) AsRedactedThinking() (v RedactedThinkingBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +func (r *BrowserSwitchTabConfigParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func (u ContentBlockUnion) AsToolUse() (v ToolUseBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +// The browser toolset: a single `tools[]` entry (carrying no `name`) that declares +// the browser tool family. The model is served the family's tool with any members +// disabled via `configs` removed from its schema. +// +// The property Type is required. +type BrowserToolset20260801Param struct { + // Any of "direct", "code_execution_20250825", "code_execution_20260120", + // "code_execution_20260521". + AllowedCallers []string `json:"allowed_callers,omitzero"` + // Create a cache control breakpoint at this content block. + CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` + // Per-member configuration for `browser_toolset_20260801`: one optional field per + // member tool, keyed by the member name — the same name the member's `tool_use` + // blocks carry. Every member is an accepted key, and a member's defaults apply + // wherever its key is absent. Unknown keys are rejected: the field set is this + // toolset version's complete member set. + Configs BrowserToolsetConfigsParam `json:"configs,omitzero"` + // This field can be elided, and will marshal its zero value as + // "browser_toolset_20260801". + Type constant.BrowserToolset20260801 `json:"type" default:"browser_toolset_20260801"` + paramObj } -func (u ContentBlockUnion) AsServerToolUse() (v ServerToolUseBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +func (r BrowserToolset20260801Param) MarshalJSON() (data []byte, err error) { + type shadow BrowserToolset20260801Param + return param.MarshalObject(r, (*shadow)(&r)) } - -func (u ContentBlockUnion) AsWebSearchToolResult() (v WebSearchToolResultBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +func (r *BrowserToolset20260801Param) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Per-member configuration for `browser_toolset_20260801`: one optional field per +// member tool, keyed by the member name — the same name the member's `tool_use` +// blocks carry. Every member is an accepted key, and a member's defaults apply +// wherever its key is absent. Unknown keys are rejected: the field set is this +// toolset version's complete member set. +type BrowserToolsetConfigsParam struct { + // `close_tab`'s config overrides. + CloseTab BrowserCloseTabConfigParam `json:"close_tab,omitzero"` + // `double_click`'s config overrides. + DoubleClick BrowserDoubleClickConfigParam `json:"double_click,omitzero"` + // `file_upload`'s config overrides. + FileUpload BrowserFileUploadConfigParam `json:"file_upload,omitzero"` + // `find`'s config overrides. + Find BrowserFindConfigParam `json:"find,omitzero"` + // `form_input`'s config overrides. + FormInput BrowserFormInputConfigParam `json:"form_input,omitzero"` + // `get_page_text`'s config overrides. + GetPageText BrowserGetPageTextConfigParam `json:"get_page_text,omitzero"` + // `hold_key`'s config overrides. + HoldKey BrowserHoldKeyConfigParam `json:"hold_key,omitzero"` + // `hover`'s config overrides. + Hover BrowserHoverConfigParam `json:"hover,omitzero"` + // `javascript_exec`'s config overrides. + JavascriptExec BrowserJavascriptExecConfigParam `json:"javascript_exec,omitzero"` + // `key`'s config overrides. + Key BrowserKeyConfigParam `json:"key,omitzero"` + // `left_click`'s config overrides. + LeftClick BrowserLeftClickConfigParam `json:"left_click,omitzero"` + // `left_click_drag`'s config overrides. + LeftClickDrag BrowserLeftClickDragConfigParam `json:"left_click_drag,omitzero"` + // `left_mouse_down`'s config overrides. + LeftMouseDown BrowserLeftMouseDownConfigParam `json:"left_mouse_down,omitzero"` + // `left_mouse_up`'s config overrides. + LeftMouseUp BrowserLeftMouseUpConfigParam `json:"left_mouse_up,omitzero"` + // `list_tabs`'s config overrides. + ListTabs BrowserListTabsConfigParam `json:"list_tabs,omitzero"` + // `middle_click`'s config overrides. + MiddleClick BrowserMiddleClickConfigParam `json:"middle_click,omitzero"` + // `mouse_move`'s config overrides. + MouseMove BrowserMouseMoveConfigParam `json:"mouse_move,omitzero"` + // `navigate`'s config overrides. + Navigate BrowserNavigateConfigParam `json:"navigate,omitzero"` + // `new_tab`'s config overrides. + NewTab BrowserNewTabConfigParam `json:"new_tab,omitzero"` + // `read_console`'s config overrides. + ReadConsole BrowserReadConsoleConfigParam `json:"read_console,omitzero"` + // `read_network`'s config overrides. + ReadNetwork BrowserReadNetworkConfigParam `json:"read_network,omitzero"` + // `read_page`'s config overrides. + ReadPage BrowserReadPageConfigParam `json:"read_page,omitzero"` + // `right_click`'s config overrides. + RightClick BrowserRightClickConfigParam `json:"right_click,omitzero"` + // `screenshot`'s config overrides. + Screenshot BrowserScreenshotConfigParam `json:"screenshot,omitzero"` + // `scroll`'s config overrides. + Scroll BrowserScrollConfigParam `json:"scroll,omitzero"` + // `scroll_to`'s config overrides. + ScrollTo BrowserScrollToConfigParam `json:"scroll_to,omitzero"` + // `switch_tab`'s config overrides. + SwitchTab BrowserSwitchTabConfigParam `json:"switch_tab,omitzero"` + // `triple_click`'s config overrides. + TripleClick BrowserTripleClickConfigParam `json:"triple_click,omitzero"` + // `type`'s config overrides. + Type BrowserTypeConfigParam `json:"type,omitzero"` + // `wait`'s config overrides. + Wait BrowserWaitConfigParam `json:"wait,omitzero"` + // `zoom`'s config overrides. + Zoom BrowserZoomConfigParam `json:"zoom,omitzero"` + paramObj } -func (u ContentBlockUnion) AsWebFetchToolResult() (v WebFetchToolResultBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +func (r BrowserToolsetConfigsParam) MarshalJSON() (data []byte, err error) { + type shadow BrowserToolsetConfigsParam + return param.MarshalObject(r, (*shadow)(&r)) } - -func (u ContentBlockUnion) AsCodeExecutionToolResult() (v CodeExecutionToolResultBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +func (r *BrowserToolsetConfigsParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func (u ContentBlockUnion) AsBashCodeExecutionToolResult() (v BashCodeExecutionToolResultBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +// `triple_click`'s config overrides. +type BrowserTripleClickConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -func (u ContentBlockUnion) AsTextEditorCodeExecutionToolResult() (v TextEditorCodeExecutionToolResultBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +func (r BrowserTripleClickConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BrowserTripleClickConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BrowserTripleClickConfigParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func (u ContentBlockUnion) AsToolSearchToolResult() (v ToolSearchToolResultBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +// `type`'s config overrides. +type BrowserTypeConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -func (u ContentBlockUnion) AsContainerUpload() (v ContainerUploadBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +func (r BrowserTypeConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BrowserTypeConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BrowserTypeConfigParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns the unmodified JSON received from the API -func (u ContentBlockUnion) RawJSON() string { return u.JSON.raw } +// `wait`'s config overrides. +type BrowserWaitConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj +} -func (r *ContentBlockUnion) UnmarshalJSON(data []byte) error { +func (r BrowserWaitConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BrowserWaitConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BrowserWaitConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// ContentBlockUnionCaller is an implicit subunion of [ContentBlockUnion]. -// ContentBlockUnionCaller provides convenient access to the sub-properties of the -// union. -// -// For type safety it is recommended to directly use a variant of the -// [ContentBlockUnion]. -type ContentBlockUnionCaller struct { - Type string `json:"type"` - ToolID string `json:"tool_id"` - JSON struct { - Type respjson.Field - ToolID respjson.Field - raw string - } `json:"-"` +// `zoom`'s config overrides. +type BrowserZoomConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -func (r *ContentBlockUnionCaller) UnmarshalJSON(data []byte) error { +func (r BrowserZoomConfigParam) MarshalJSON() (data []byte, err error) { + type shadow BrowserZoomConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *BrowserZoomConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// ContentBlockUnionContent is an implicit subunion of [ContentBlockUnion]. -// ContentBlockUnionContent provides convenient access to the sub-properties of the -// union. -// -// For type safety it is recommended to directly use a variant of the -// [ContentBlockUnion]. -// -// If the underlying value is not a json object, one of the following properties -// will be valid: OfWebSearchResultBlockArray] -type ContentBlockUnionContent struct { - // This field will be present if the value is a [[]WebSearchResultBlock] instead of - // an object. - OfWebSearchResultBlockArray []WebSearchResultBlock `json:",inline"` - ErrorCode string `json:"error_code"` - Type string `json:"type"` - // This field is a union of [DocumentBlock], [[]CodeExecutionOutputBlock], - // [[]CodeExecutionOutputBlock], [[]BashCodeExecutionOutputBlock], [string] - Content ContentBlockUnionContentContent `json:"content"` - // This field is from variant [WebFetchToolResultBlockContentUnion]. - RetrievedAt string `json:"retrieved_at"` - // This field is from variant [WebFetchToolResultBlockContentUnion]. - URL string `json:"url"` - ReturnCode int64 `json:"return_code"` - Stderr string `json:"stderr"` - Stdout string `json:"stdout"` - // This field is from variant [CodeExecutionToolResultBlockContentUnion]. - EncryptedStdout string `json:"encrypted_stdout"` - ErrorMessage string `json:"error_message"` - // This field is from variant [TextEditorCodeExecutionToolResultBlockContentUnion]. - FileType TextEditorCodeExecutionViewResultBlockFileType `json:"file_type"` - // This field is from variant [TextEditorCodeExecutionToolResultBlockContentUnion]. - NumLines int64 `json:"num_lines"` - // This field is from variant [TextEditorCodeExecutionToolResultBlockContentUnion]. - StartLine int64 `json:"start_line"` - // This field is from variant [TextEditorCodeExecutionToolResultBlockContentUnion]. - TotalLines int64 `json:"total_lines"` - // This field is from variant [TextEditorCodeExecutionToolResultBlockContentUnion]. - IsFileUpdate bool `json:"is_file_update"` - // This field is from variant [TextEditorCodeExecutionToolResultBlockContentUnion]. - Lines []string `json:"lines"` - // This field is from variant [TextEditorCodeExecutionToolResultBlockContentUnion]. - NewLines int64 `json:"new_lines"` - // This field is from variant [TextEditorCodeExecutionToolResultBlockContentUnion]. - NewStart int64 `json:"new_start"` - // This field is from variant [TextEditorCodeExecutionToolResultBlockContentUnion]. - OldLines int64 `json:"old_lines"` - // This field is from variant [TextEditorCodeExecutionToolResultBlockContentUnion]. - OldStart int64 `json:"old_start"` - // This field is from variant [ToolSearchToolResultBlockContentUnion]. - ToolReferences []ToolReferenceBlock `json:"tool_references"` - JSON struct { - OfWebSearchResultBlockArray respjson.Field - ErrorCode respjson.Field - Type respjson.Field - Content respjson.Field - RetrievedAt respjson.Field - URL respjson.Field - ReturnCode respjson.Field - Stderr respjson.Field - Stdout respjson.Field - EncryptedStdout respjson.Field - ErrorMessage respjson.Field - FileType respjson.Field - NumLines respjson.Field - StartLine respjson.Field - TotalLines respjson.Field - IsFileUpdate respjson.Field - Lines respjson.Field - NewLines respjson.Field - NewStart respjson.Field - OldLines respjson.Field - OldStart respjson.Field - ToolReferences respjson.Field - raw string - } `json:"-"` +func NewCacheControlEphemeralParam() CacheControlEphemeralParam { + return CacheControlEphemeralParam{ + Type: "ephemeral", + } } -func (r *ContentBlockUnionContent) UnmarshalJSON(data []byte) error { +// This struct has a constant value, construct it with +// [NewCacheControlEphemeralParam]. +type CacheControlEphemeralParam struct { + // The time-to-live for the cache control breakpoint. + // + // This may be one the following values: + // + // - `5m`: 5 minutes + // - `1h`: 1 hour + // + // Defaults to `5m`. See + // [prompt caching pricing](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) + // for details. + // + // Any of "5m", "1h". + TTL CacheControlEphemeralTTL `json:"ttl,omitzero"` + Type constant.Ephemeral `json:"type" default:"ephemeral"` + paramObj +} + +func (r CacheControlEphemeralParam) MarshalJSON() (data []byte, err error) { + type shadow CacheControlEphemeralParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *CacheControlEphemeralParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// ContentBlockUnionContentContent is an implicit subunion of [ContentBlockUnion]. -// ContentBlockUnionContentContent provides convenient access to the sub-properties -// of the union. +// The time-to-live for the cache control breakpoint. // -// For type safety it is recommended to directly use a variant of the -// [ContentBlockUnion]. +// This may be one the following values: // -// If the underlying value is not a json object, one of the following properties -// will be valid: OfContent OfString] -type ContentBlockUnionContentContent struct { - // This field will be present if the value is a [[]CodeExecutionOutputBlock] - // instead of an object. - OfContent []CodeExecutionOutputBlock `json:",inline"` - // This field will be present if the value is a [string] instead of an object. - OfString string `json:",inline"` - // This field is from variant [DocumentBlock]. - Citations CitationsConfig `json:"citations"` - // This field is from variant [DocumentBlock]. - Source DocumentBlockSourceUnion `json:"source"` - // This field is from variant [DocumentBlock]. - Title string `json:"title"` - // This field is from variant [DocumentBlock]. - Type constant.Document `json:"type"` +// - `5m`: 5 minutes +// - `1h`: 1 hour +// +// Defaults to `5m`. See +// [prompt caching pricing](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) +// for details. +type CacheControlEphemeralTTL string + +const ( + CacheControlEphemeralTTLTTL5m CacheControlEphemeralTTL = "5m" + CacheControlEphemeralTTLTTL1h CacheControlEphemeralTTL = "1h" +) + +type CacheCreation struct { + // The number of input tokens used to create the 1 hour cache entry. + Ephemeral1hInputTokens int64 `json:"ephemeral_1h_input_tokens" api:"required"` + // The number of input tokens used to create the 5 minute cache entry. + Ephemeral5mInputTokens int64 `json:"ephemeral_5m_input_tokens" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { - OfContent respjson.Field - OfString respjson.Field - Citations respjson.Field - Source respjson.Field - Title respjson.Field - Type respjson.Field - raw string + Ephemeral1hInputTokens respjson.Field + Ephemeral5mInputTokens respjson.Field + ExtraFields map[string]respjson.Field + raw string } `json:"-"` } -func (r *ContentBlockUnionContentContent) UnmarshalJSON(data []byte) error { +// Returns the unmodified JSON received from the API +func (r CacheCreation) RawJSON() string { return r.JSON.raw } +func (r *CacheCreation) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -func NewTextBlock(text string) ContentBlockParamUnion { - var variant TextBlockParam - variant.Text = text - return ContentBlockParamUnion{OfText: &variant} +type CitationCharLocation struct { + CitedText string `json:"cited_text" api:"required"` + DocumentIndex int64 `json:"document_index" api:"required"` + DocumentTitle string `json:"document_title" api:"required"` + EndCharIndex int64 `json:"end_char_index" api:"required"` + FileID string `json:"file_id" api:"required"` + StartCharIndex int64 `json:"start_char_index" api:"required"` + Type constant.CharLocation `json:"type" default:"char_location"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + CitedText respjson.Field + DocumentIndex respjson.Field + DocumentTitle respjson.Field + EndCharIndex respjson.Field + FileID respjson.Field + StartCharIndex respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` } -func NewImageBlock[T Base64ImageSourceParam | URLImageSourceParam](source T) ContentBlockParamUnion { - var image ImageBlockParam - switch v := any(source).(type) { - case Base64ImageSourceParam: - image.Source.OfBase64 = &v - case URLImageSourceParam: - image.Source.OfURL = &v - } - return ContentBlockParamUnion{OfImage: &image} +// Returns the unmodified JSON received from the API +func (r CitationCharLocation) RawJSON() string { return r.JSON.raw } +func (r *CitationCharLocation) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func NewImageBlockBase64(mediaType string, encodedData string) ContentBlockParamUnion { - return ContentBlockParamUnion{ - OfImage: &ImageBlockParam{ - Source: ImageBlockParamSourceUnion{ - OfBase64: &Base64ImageSourceParam{ - Data: encodedData, - MediaType: Base64ImageSourceMediaType(mediaType), - }, - }, - }, - } +// The properties CitedText, DocumentIndex, DocumentTitle, EndCharIndex, +// StartCharIndex, Type are required. +type CitationCharLocationParam struct { + DocumentTitle param.Opt[string] `json:"document_title,omitzero" api:"required"` + CitedText string `json:"cited_text" api:"required"` + DocumentIndex int64 `json:"document_index" api:"required"` + EndCharIndex int64 `json:"end_char_index" api:"required"` + StartCharIndex int64 `json:"start_char_index" api:"required"` + // This field can be elided, and will marshal its zero value as "char_location". + Type constant.CharLocation `json:"type" default:"char_location"` + paramObj } -func NewDocumentBlock[ - T Base64PDFSourceParam | PlainTextSourceParam | ContentBlockSourceParam | URLPDFSourceParam, -](source T) ContentBlockParamUnion { - var document DocumentBlockParam - switch v := any(source).(type) { - case Base64PDFSourceParam: - document.Source.OfBase64 = &v - case PlainTextSourceParam: - document.Source.OfText = &v - case ContentBlockSourceParam: - document.Source.OfContent = &v - case URLPDFSourceParam: - document.Source.OfURL = &v - } - return ContentBlockParamUnion{OfDocument: &document} +func (r CitationCharLocationParam) MarshalJSON() (data []byte, err error) { + type shadow CitationCharLocationParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *CitationCharLocationParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func NewSearchResultBlock(content []TextBlockParam, source string, title string) ContentBlockParamUnion { - var searchResult SearchResultBlockParam - searchResult.Content = content - searchResult.Source = source - searchResult.Title = title - return ContentBlockParamUnion{OfSearchResult: &searchResult} +type CitationContentBlockLocation struct { + // The full text of the cited block range, concatenated. + // + // Always equals the contents of `content[start_block_index:end_block_index]` + // joined together. The text block is the minimal citable unit; this field is never + // a substring of a single block. Not counted toward output tokens, and not counted + // toward input tokens when sent back in subsequent turns. + CitedText string `json:"cited_text" api:"required"` + DocumentIndex int64 `json:"document_index" api:"required"` + DocumentTitle string `json:"document_title" api:"required"` + // Exclusive 0-based end index of the cited block range in the source's `content` + // array. + // + // Always greater than `start_block_index`; a single-block citation has + // `end_block_index = start_block_index + 1`. + EndBlockIndex int64 `json:"end_block_index" api:"required"` + FileID string `json:"file_id" api:"required"` + // 0-based index of the first cited block in the source's `content` array. + StartBlockIndex int64 `json:"start_block_index" api:"required"` + Type constant.ContentBlockLocation `json:"type" default:"content_block_location"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + CitedText respjson.Field + DocumentIndex respjson.Field + DocumentTitle respjson.Field + EndBlockIndex respjson.Field + FileID respjson.Field + StartBlockIndex respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` } -func NewThinkingBlock(signature string, thinking string) ContentBlockParamUnion { - var variant ThinkingBlockParam - variant.Signature = signature - variant.Thinking = thinking - return ContentBlockParamUnion{OfThinking: &variant} +// Returns the unmodified JSON received from the API +func (r CitationContentBlockLocation) RawJSON() string { return r.JSON.raw } +func (r *CitationContentBlockLocation) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func NewRedactedThinkingBlock(data string) ContentBlockParamUnion { - var redactedThinking RedactedThinkingBlockParam - redactedThinking.Data = data - return ContentBlockParamUnion{OfRedactedThinking: &redactedThinking} +// The properties CitedText, DocumentIndex, DocumentTitle, EndBlockIndex, +// StartBlockIndex, Type are required. +type CitationContentBlockLocationParam struct { + DocumentTitle param.Opt[string] `json:"document_title,omitzero" api:"required"` + // The full text of the cited block range, concatenated. + // + // Always equals the contents of `content[start_block_index:end_block_index]` + // joined together. The text block is the minimal citable unit; this field is never + // a substring of a single block. Not counted toward output tokens, and not counted + // toward input tokens when sent back in subsequent turns. + CitedText string `json:"cited_text" api:"required"` + DocumentIndex int64 `json:"document_index" api:"required"` + // Exclusive 0-based end index of the cited block range in the source's `content` + // array. + // + // Always greater than `start_block_index`; a single-block citation has + // `end_block_index = start_block_index + 1`. + EndBlockIndex int64 `json:"end_block_index" api:"required"` + // 0-based index of the first cited block in the source's `content` array. + StartBlockIndex int64 `json:"start_block_index" api:"required"` + // This field can be elided, and will marshal its zero value as + // "content_block_location". + Type constant.ContentBlockLocation `json:"type" default:"content_block_location"` + paramObj } -func NewToolUseBlock(id string, input any, name string) ContentBlockParamUnion { - var toolUse ToolUseBlockParam - toolUse.ID = id - toolUse.Input = input - toolUse.Name = name - return ContentBlockParamUnion{OfToolUse: &toolUse} +func (r CitationContentBlockLocationParam) MarshalJSON() (data []byte, err error) { + type shadow CitationContentBlockLocationParam + return param.MarshalObject(r, (*shadow)(&r)) } - -func NewToolResultBlock(toolUseID string, content string, isError bool) ContentBlockParamUnion { - toolBlock := ToolResultBlockParam{ - ToolUseID: toolUseID, - Content: []ToolResultBlockParamContentUnion{ - {OfText: &TextBlockParam{Text: content}}, - }, - IsError: Bool(isError), - } - return ContentBlockParamUnion{OfToolResult: &toolBlock} +func (r *CitationContentBlockLocationParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func NewServerToolUseBlock(id string, input any, name ServerToolUseBlockParamName) ContentBlockParamUnion { - var serverToolUse ServerToolUseBlockParam - serverToolUse.ID = id - serverToolUse.Input = input - serverToolUse.Name = name - return ContentBlockParamUnion{OfServerToolUse: &serverToolUse} +type CitationPageLocation struct { + CitedText string `json:"cited_text" api:"required"` + DocumentIndex int64 `json:"document_index" api:"required"` + DocumentTitle string `json:"document_title" api:"required"` + EndPageNumber int64 `json:"end_page_number" api:"required"` + FileID string `json:"file_id" api:"required"` + StartPageNumber int64 `json:"start_page_number" api:"required"` + Type constant.PageLocation `json:"type" default:"page_location"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + CitedText respjson.Field + DocumentIndex respjson.Field + DocumentTitle respjson.Field + EndPageNumber respjson.Field + FileID respjson.Field + StartPageNumber respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` } -func NewWebSearchToolResultBlock[ - T []WebSearchResultBlockParam | WebSearchToolRequestErrorParam, -](content T, toolUseID string) ContentBlockParamUnion { - var webSearchToolResult WebSearchToolResultBlockParam - switch v := any(content).(type) { - case []WebSearchResultBlockParam: - webSearchToolResult.Content.OfWebSearchToolResultBlockItem = v - case WebSearchToolRequestErrorParam: - webSearchToolResult.Content.OfRequestWebSearchToolResultError = &v - } - webSearchToolResult.ToolUseID = toolUseID - return ContentBlockParamUnion{OfWebSearchToolResult: &webSearchToolResult} +// Returns the unmodified JSON received from the API +func (r CitationPageLocation) RawJSON() string { return r.JSON.raw } +func (r *CitationPageLocation) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func NewWebFetchToolResultBlock[ - T WebFetchToolResultErrorBlockParam | WebFetchBlockParam, -](content T, toolUseID string) ContentBlockParamUnion { - var webFetchToolResult WebFetchToolResultBlockParam - switch v := any(content).(type) { - case WebFetchToolResultErrorBlockParam: - webFetchToolResult.Content.OfRequestWebFetchToolResultError = &v - case WebFetchBlockParam: - webFetchToolResult.Content.OfRequestWebFetchResultBlock = &v - } - webFetchToolResult.ToolUseID = toolUseID - return ContentBlockParamUnion{OfWebFetchToolResult: &webFetchToolResult} +// The properties CitedText, DocumentIndex, DocumentTitle, EndPageNumber, +// StartPageNumber, Type are required. +type CitationPageLocationParam struct { + DocumentTitle param.Opt[string] `json:"document_title,omitzero" api:"required"` + CitedText string `json:"cited_text" api:"required"` + DocumentIndex int64 `json:"document_index" api:"required"` + EndPageNumber int64 `json:"end_page_number" api:"required"` + StartPageNumber int64 `json:"start_page_number" api:"required"` + // This field can be elided, and will marshal its zero value as "page_location". + Type constant.PageLocation `json:"type" default:"page_location"` + paramObj } -func NewCodeExecutionToolResultBlock[ - T CodeExecutionToolResultErrorParam | CodeExecutionResultBlockParam | EncryptedCodeExecutionResultBlockParam, -](content T, toolUseID string) ContentBlockParamUnion { - var codeExecutionToolResult CodeExecutionToolResultBlockParam - switch v := any(content).(type) { - case CodeExecutionToolResultErrorParam: - codeExecutionToolResult.Content.OfRequestCodeExecutionToolResultError = &v - case CodeExecutionResultBlockParam: - codeExecutionToolResult.Content.OfRequestCodeExecutionResultBlock = &v - case EncryptedCodeExecutionResultBlockParam: - codeExecutionToolResult.Content.OfRequestEncryptedCodeExecutionResultBlock = &v - } - codeExecutionToolResult.ToolUseID = toolUseID - return ContentBlockParamUnion{OfCodeExecutionToolResult: &codeExecutionToolResult} +func (r CitationPageLocationParam) MarshalJSON() (data []byte, err error) { + type shadow CitationPageLocationParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *CitationPageLocationParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func NewBashCodeExecutionToolResultBlock[ - T BashCodeExecutionToolResultErrorParam | BashCodeExecutionResultBlockParam, -](content T, toolUseID string) ContentBlockParamUnion { - var bashCodeExecutionToolResult BashCodeExecutionToolResultBlockParam - switch v := any(content).(type) { - case BashCodeExecutionToolResultErrorParam: - bashCodeExecutionToolResult.Content.OfRequestBashCodeExecutionToolResultError = &v - case BashCodeExecutionResultBlockParam: - bashCodeExecutionToolResult.Content.OfRequestBashCodeExecutionResultBlock = &v - } - bashCodeExecutionToolResult.ToolUseID = toolUseID - return ContentBlockParamUnion{OfBashCodeExecutionToolResult: &bashCodeExecutionToolResult} +// The properties CitedText, EndBlockIndex, SearchResultIndex, Source, +// StartBlockIndex, Title, Type are required. +type CitationSearchResultLocationParam struct { + Title param.Opt[string] `json:"title,omitzero" api:"required"` + // The full text of the cited block range, concatenated. + // + // Always equals the contents of `content[start_block_index:end_block_index]` + // joined together. The text block is the minimal citable unit; this field is never + // a substring of a single block. Not counted toward output tokens, and not counted + // toward input tokens when sent back in subsequent turns. + CitedText string `json:"cited_text" api:"required"` + // Exclusive 0-based end index of the cited block range in the source's `content` + // array. + // + // Always greater than `start_block_index`; a single-block citation has + // `end_block_index = start_block_index + 1`. + EndBlockIndex int64 `json:"end_block_index" api:"required"` + // 0-based index of the cited search result among all `search_result` content + // blocks in the request, in the order they appear across messages and tool + // results. + // + // Counted separately from `document_index`; server-side web search results are not + // included in this count. + SearchResultIndex int64 `json:"search_result_index" api:"required"` + Source string `json:"source" api:"required"` + // 0-based index of the first cited block in the source's `content` array. + StartBlockIndex int64 `json:"start_block_index" api:"required"` + // This field can be elided, and will marshal its zero value as + // "search_result_location". + Type constant.SearchResultLocation `json:"type" default:"search_result_location"` + paramObj } -func NewTextEditorCodeExecutionToolResultBlock[ - T TextEditorCodeExecutionToolResultErrorParam | TextEditorCodeExecutionViewResultBlockParam | TextEditorCodeExecutionCreateResultBlockParam | TextEditorCodeExecutionStrReplaceResultBlockParam, -](content T, toolUseID string) ContentBlockParamUnion { - var textEditorCodeExecutionToolResult TextEditorCodeExecutionToolResultBlockParam - switch v := any(content).(type) { - case TextEditorCodeExecutionToolResultErrorParam: - textEditorCodeExecutionToolResult.Content.OfRequestTextEditorCodeExecutionToolResultError = &v - case TextEditorCodeExecutionViewResultBlockParam: - textEditorCodeExecutionToolResult.Content.OfRequestTextEditorCodeExecutionViewResultBlock = &v - case TextEditorCodeExecutionCreateResultBlockParam: - textEditorCodeExecutionToolResult.Content.OfRequestTextEditorCodeExecutionCreateResultBlock = &v - case TextEditorCodeExecutionStrReplaceResultBlockParam: - textEditorCodeExecutionToolResult.Content.OfRequestTextEditorCodeExecutionStrReplaceResultBlock = &v - } - textEditorCodeExecutionToolResult.ToolUseID = toolUseID - return ContentBlockParamUnion{OfTextEditorCodeExecutionToolResult: &textEditorCodeExecutionToolResult} +func (r CitationSearchResultLocationParam) MarshalJSON() (data []byte, err error) { + type shadow CitationSearchResultLocationParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *CitationSearchResultLocationParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func NewToolSearchToolResultBlock[ - T ToolSearchToolResultErrorParam | ToolSearchToolSearchResultBlockParam, -](content T, toolUseID string) ContentBlockParamUnion { - var toolSearchToolResult ToolSearchToolResultBlockParam - switch v := any(content).(type) { - case ToolSearchToolResultErrorParam: - toolSearchToolResult.Content.OfRequestToolSearchToolResultError = &v - case ToolSearchToolSearchResultBlockParam: - toolSearchToolResult.Content.OfRequestToolSearchToolSearchResultBlock = &v - } - toolSearchToolResult.ToolUseID = toolUseID - return ContentBlockParamUnion{OfToolSearchToolResult: &toolSearchToolResult} +// The properties CitedText, EncryptedIndex, Title, Type, URL are required. +type CitationWebSearchResultLocationParam struct { + Title param.Opt[string] `json:"title,omitzero" api:"required"` + CitedText string `json:"cited_text" api:"required"` + EncryptedIndex string `json:"encrypted_index" api:"required"` + URL string `json:"url" api:"required"` + // This field can be elided, and will marshal its zero value as + // "web_search_result_location". + Type constant.WebSearchResultLocation `json:"type" default:"web_search_result_location"` + paramObj } -func NewContainerUploadBlock(fileID string) ContentBlockParamUnion { - var containerUpload ContainerUploadBlockParam - containerUpload.FileID = fileID - return ContentBlockParamUnion{OfContainerUpload: &containerUpload} +func (r CitationWebSearchResultLocationParam) MarshalJSON() (data []byte, err error) { + type shadow CitationWebSearchResultLocationParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *CitationWebSearchResultLocationParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type ContentBlockParamUnion struct { - OfText *TextBlockParam `json:",omitzero,inline"` - OfImage *ImageBlockParam `json:",omitzero,inline"` - OfDocument *DocumentBlockParam `json:",omitzero,inline"` - OfSearchResult *SearchResultBlockParam `json:",omitzero,inline"` - OfThinking *ThinkingBlockParam `json:",omitzero,inline"` - OfRedactedThinking *RedactedThinkingBlockParam `json:",omitzero,inline"` - OfToolUse *ToolUseBlockParam `json:",omitzero,inline"` - OfToolResult *ToolResultBlockParam `json:",omitzero,inline"` - OfServerToolUse *ServerToolUseBlockParam `json:",omitzero,inline"` - OfWebSearchToolResult *WebSearchToolResultBlockParam `json:",omitzero,inline"` - OfWebFetchToolResult *WebFetchToolResultBlockParam `json:",omitzero,inline"` - OfCodeExecutionToolResult *CodeExecutionToolResultBlockParam `json:",omitzero,inline"` - OfBashCodeExecutionToolResult *BashCodeExecutionToolResultBlockParam `json:",omitzero,inline"` - OfTextEditorCodeExecutionToolResult *TextEditorCodeExecutionToolResultBlockParam `json:",omitzero,inline"` - OfToolSearchToolResult *ToolSearchToolResultBlockParam `json:",omitzero,inline"` - OfContainerUpload *ContainerUploadBlockParam `json:",omitzero,inline"` - paramUnion +type CitationsConfig struct { + Enabled bool `json:"enabled" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Enabled respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` } -func (u ContentBlockParamUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfText, - u.OfImage, - u.OfDocument, - u.OfSearchResult, - u.OfThinking, - u.OfRedactedThinking, - u.OfToolUse, - u.OfToolResult, - u.OfServerToolUse, - u.OfWebSearchToolResult, - u.OfWebFetchToolResult, - u.OfCodeExecutionToolResult, - u.OfBashCodeExecutionToolResult, - u.OfTextEditorCodeExecutionToolResult, - u.OfToolSearchToolResult, - u.OfContainerUpload) +// Returns the unmodified JSON received from the API +func (r CitationsConfig) RawJSON() string { return r.JSON.raw } +func (r *CitationsConfig) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func (u *ContentBlockParamUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) + +type CitationsConfigParam struct { + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -func (u *ContentBlockParamUnion) asAny() any { - if !param.IsOmitted(u.OfText) { - return u.OfText - } else if !param.IsOmitted(u.OfImage) { - return u.OfImage - } else if !param.IsOmitted(u.OfDocument) { - return u.OfDocument - } else if !param.IsOmitted(u.OfSearchResult) { - return u.OfSearchResult - } else if !param.IsOmitted(u.OfThinking) { - return u.OfThinking - } else if !param.IsOmitted(u.OfRedactedThinking) { - return u.OfRedactedThinking - } else if !param.IsOmitted(u.OfToolUse) { - return u.OfToolUse - } else if !param.IsOmitted(u.OfToolResult) { - return u.OfToolResult - } else if !param.IsOmitted(u.OfServerToolUse) { - return u.OfServerToolUse - } else if !param.IsOmitted(u.OfWebSearchToolResult) { - return u.OfWebSearchToolResult - } else if !param.IsOmitted(u.OfWebFetchToolResult) { - return u.OfWebFetchToolResult - } else if !param.IsOmitted(u.OfCodeExecutionToolResult) { - return u.OfCodeExecutionToolResult - } else if !param.IsOmitted(u.OfBashCodeExecutionToolResult) { - return u.OfBashCodeExecutionToolResult - } else if !param.IsOmitted(u.OfTextEditorCodeExecutionToolResult) { - return u.OfTextEditorCodeExecutionToolResult - } else if !param.IsOmitted(u.OfToolSearchToolResult) { - return u.OfToolSearchToolResult - } else if !param.IsOmitted(u.OfContainerUpload) { - return u.OfContainerUpload - } - return nil +func (r CitationsConfigParam) MarshalJSON() (data []byte, err error) { + type shadow CitationsConfigParam + return param.MarshalObject(r, (*shadow)(&r)) } - -// Returns a pointer to the underlying variant's property, if present. -func (u ContentBlockParamUnion) GetText() *string { - if vt := u.OfText; vt != nil { - return &vt.Text - } - return nil +func (r *CitationsConfigParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns a pointer to the underlying variant's property, if present. -func (u ContentBlockParamUnion) GetContext() *string { - if vt := u.OfDocument; vt != nil && vt.Context.Valid() { - return &vt.Context.Value - } - return nil +type CitationsDelta struct { + Citation CitationsDeltaCitationUnion `json:"citation" api:"required"` + Type constant.CitationsDelta `json:"type" default:"citations_delta"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Citation respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` } -// Returns a pointer to the underlying variant's property, if present. -func (u ContentBlockParamUnion) GetSignature() *string { - if vt := u.OfThinking; vt != nil { - return &vt.Signature - } - return nil +// Returns the unmodified JSON received from the API +func (r CitationsDelta) RawJSON() string { return r.JSON.raw } +func (r *CitationsDelta) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns a pointer to the underlying variant's property, if present. -func (u ContentBlockParamUnion) GetThinking() *string { - if vt := u.OfThinking; vt != nil { - return &vt.Thinking - } - return nil +// CitationsDeltaCitationUnion contains all possible properties and values from +// [CitationCharLocation], [CitationPageLocation], [CitationContentBlockLocation], +// [CitationsWebSearchResultLocation], [CitationsSearchResultLocation]. +// +// Use the [CitationsDeltaCitationUnion.AsAny] method to switch on the variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type CitationsDeltaCitationUnion struct { + CitedText string `json:"cited_text"` + DocumentIndex int64 `json:"document_index"` + DocumentTitle string `json:"document_title"` + // This field is from variant [CitationCharLocation]. + EndCharIndex int64 `json:"end_char_index"` + FileID string `json:"file_id"` + // This field is from variant [CitationCharLocation]. + StartCharIndex int64 `json:"start_char_index"` + // Any of "char_location", "page_location", "content_block_location", + // "web_search_result_location", "search_result_location". + Type string `json:"type"` + // This field is from variant [CitationPageLocation]. + EndPageNumber int64 `json:"end_page_number"` + // This field is from variant [CitationPageLocation]. + StartPageNumber int64 `json:"start_page_number"` + EndBlockIndex int64 `json:"end_block_index"` + StartBlockIndex int64 `json:"start_block_index"` + // This field is from variant [CitationsWebSearchResultLocation]. + EncryptedIndex string `json:"encrypted_index"` + Title string `json:"title"` + // This field is from variant [CitationsWebSearchResultLocation]. + URL string `json:"url"` + // This field is from variant [CitationsSearchResultLocation]. + SearchResultIndex int64 `json:"search_result_index"` + // This field is from variant [CitationsSearchResultLocation]. + Source string `json:"source"` + JSON struct { + CitedText respjson.Field + DocumentIndex respjson.Field + DocumentTitle respjson.Field + EndCharIndex respjson.Field + FileID respjson.Field + StartCharIndex respjson.Field + Type respjson.Field + EndPageNumber respjson.Field + StartPageNumber respjson.Field + EndBlockIndex respjson.Field + StartBlockIndex respjson.Field + EncryptedIndex respjson.Field + Title respjson.Field + URL respjson.Field + SearchResultIndex respjson.Field + Source respjson.Field + raw string + } `json:"-"` } -// Returns a pointer to the underlying variant's property, if present. -func (u ContentBlockParamUnion) GetData() *string { - if vt := u.OfRedactedThinking; vt != nil { - return &vt.Data - } - return nil +// anyCitationsDeltaCitation is implemented by each variant of +// [CitationsDeltaCitationUnion] to add type safety for the return type of +// [CitationsDeltaCitationUnion.AsAny] +type anyCitationsDeltaCitation interface { + implCitationsDeltaCitationUnion() } -// Returns a pointer to the underlying variant's property, if present. -func (u ContentBlockParamUnion) GetIsError() *bool { - if vt := u.OfToolResult; vt != nil && vt.IsError.Valid() { - return &vt.IsError.Value +func (CitationCharLocation) implCitationsDeltaCitationUnion() {} +func (CitationPageLocation) implCitationsDeltaCitationUnion() {} +func (CitationContentBlockLocation) implCitationsDeltaCitationUnion() {} +func (CitationsWebSearchResultLocation) implCitationsDeltaCitationUnion() {} +func (CitationsSearchResultLocation) implCitationsDeltaCitationUnion() {} + +// Use the following switch statement to find the correct variant +// +// switch variant := CitationsDeltaCitationUnion.AsAny().(type) { +// case anthropic.CitationCharLocation: +// case anthropic.CitationPageLocation: +// case anthropic.CitationContentBlockLocation: +// case anthropic.CitationsWebSearchResultLocation: +// case anthropic.CitationsSearchResultLocation: +// default: +// fmt.Errorf("no variant present") +// } +func (u CitationsDeltaCitationUnion) AsAny() anyCitationsDeltaCitation { + switch u.Type { + case "char_location": + return u.AsCharLocation() + case "page_location": + return u.AsPageLocation() + case "content_block_location": + return u.AsContentBlockLocation() + case "web_search_result_location": + return u.AsWebSearchResultLocation() + case "search_result_location": + return u.AsSearchResultLocation() } return nil } -// Returns a pointer to the underlying variant's property, if present. -func (u ContentBlockParamUnion) GetFileID() *string { - if vt := u.OfContainerUpload; vt != nil { - return &vt.FileID - } - return nil +func (u CitationsDeltaCitationUnion) AsCharLocation() (v CitationCharLocation) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -// Returns a pointer to the underlying variant's property, if present. -func (u ContentBlockParamUnion) GetType() *string { - if vt := u.OfText; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfImage; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfDocument; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfSearchResult; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfThinking; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfRedactedThinking; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfToolUse; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfToolResult; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfServerToolUse; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfWebSearchToolResult; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfWebFetchToolResult; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfCodeExecutionToolResult; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfBashCodeExecutionToolResult; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfTextEditorCodeExecutionToolResult; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfToolSearchToolResult; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfContainerUpload; vt != nil { - return (*string)(&vt.Type) - } - return nil +func (u CitationsDeltaCitationUnion) AsPageLocation() (v CitationPageLocation) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -// Returns a pointer to the underlying variant's property, if present. -func (u ContentBlockParamUnion) GetTitle() *string { - if vt := u.OfDocument; vt != nil && vt.Title.Valid() { - return &vt.Title.Value - } else if vt := u.OfSearchResult; vt != nil { - return (*string)(&vt.Title) - } - return nil +func (u CitationsDeltaCitationUnion) AsContentBlockLocation() (v CitationContentBlockLocation) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -// Returns a pointer to the underlying variant's property, if present. -func (u ContentBlockParamUnion) GetID() *string { - if vt := u.OfToolUse; vt != nil { - return (*string)(&vt.ID) - } else if vt := u.OfServerToolUse; vt != nil { - return (*string)(&vt.ID) - } - return nil +func (u CitationsDeltaCitationUnion) AsWebSearchResultLocation() (v CitationsWebSearchResultLocation) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -// Returns a pointer to the underlying variant's property, if present. -func (u ContentBlockParamUnion) GetName() *string { - if vt := u.OfToolUse; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfServerToolUse; vt != nil { - return (*string)(&vt.Name) - } - return nil +func (u CitationsDeltaCitationUnion) AsSearchResultLocation() (v CitationsSearchResultLocation) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -// Returns a pointer to the underlying variant's property, if present. -func (u ContentBlockParamUnion) GetToolUseID() *string { - if vt := u.OfToolResult; vt != nil { - return (*string)(&vt.ToolUseID) - } else if vt := u.OfWebSearchToolResult; vt != nil { - return (*string)(&vt.ToolUseID) - } else if vt := u.OfWebFetchToolResult; vt != nil { - return (*string)(&vt.ToolUseID) - } else if vt := u.OfCodeExecutionToolResult; vt != nil { - return (*string)(&vt.ToolUseID) - } else if vt := u.OfBashCodeExecutionToolResult; vt != nil { - return (*string)(&vt.ToolUseID) - } else if vt := u.OfTextEditorCodeExecutionToolResult; vt != nil { - return (*string)(&vt.ToolUseID) - } else if vt := u.OfToolSearchToolResult; vt != nil { - return (*string)(&vt.ToolUseID) - } - return nil +// Returns the unmodified JSON received from the API +func (u CitationsDeltaCitationUnion) RawJSON() string { return u.JSON.raw } + +func (r *CitationsDeltaCitationUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns a pointer to the underlying variant's CacheControl property, if present. -func (u ContentBlockParamUnion) GetCacheControl() *CacheControlEphemeralParam { - if vt := u.OfText; vt != nil { - return &vt.CacheControl - } else if vt := u.OfImage; vt != nil { - return &vt.CacheControl - } else if vt := u.OfDocument; vt != nil { - return &vt.CacheControl - } else if vt := u.OfSearchResult; vt != nil { - return &vt.CacheControl - } else if vt := u.OfToolUse; vt != nil { - return &vt.CacheControl - } else if vt := u.OfToolResult; vt != nil { - return &vt.CacheControl - } else if vt := u.OfServerToolUse; vt != nil { - return &vt.CacheControl - } else if vt := u.OfWebSearchToolResult; vt != nil { - return &vt.CacheControl - } else if vt := u.OfWebFetchToolResult; vt != nil { - return &vt.CacheControl - } else if vt := u.OfCodeExecutionToolResult; vt != nil { - return &vt.CacheControl - } else if vt := u.OfBashCodeExecutionToolResult; vt != nil { - return &vt.CacheControl - } else if vt := u.OfTextEditorCodeExecutionToolResult; vt != nil { - return &vt.CacheControl - } else if vt := u.OfToolSearchToolResult; vt != nil { - return &vt.CacheControl - } else if vt := u.OfContainerUpload; vt != nil { - return &vt.CacheControl - } - return nil +type CitationsSearchResultLocation struct { + // The full text of the cited block range, concatenated. + // + // Always equals the contents of `content[start_block_index:end_block_index]` + // joined together. The text block is the minimal citable unit; this field is never + // a substring of a single block. Not counted toward output tokens, and not counted + // toward input tokens when sent back in subsequent turns. + CitedText string `json:"cited_text" api:"required"` + // Exclusive 0-based end index of the cited block range in the source's `content` + // array. + // + // Always greater than `start_block_index`; a single-block citation has + // `end_block_index = start_block_index + 1`. + EndBlockIndex int64 `json:"end_block_index" api:"required"` + // 0-based index of the cited search result among all `search_result` content + // blocks in the request, in the order they appear across messages and tool + // results. + // + // Counted separately from `document_index`; server-side web search results are not + // included in this count. + SearchResultIndex int64 `json:"search_result_index" api:"required"` + Source string `json:"source" api:"required"` + // 0-based index of the first cited block in the source's `content` array. + StartBlockIndex int64 `json:"start_block_index" api:"required"` + Title string `json:"title" api:"required"` + Type constant.SearchResultLocation `json:"type" default:"search_result_location"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + CitedText respjson.Field + EndBlockIndex respjson.Field + SearchResultIndex respjson.Field + Source respjson.Field + StartBlockIndex respjson.Field + Title respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` } -// Returns a subunion which exports methods to access subproperties -// -// Or use AsAny() to get the underlying value -func (u ContentBlockParamUnion) GetCitations() (res contentBlockParamUnionCitations) { - if vt := u.OfText; vt != nil { - res.any = &vt.Citations - } else if vt := u.OfDocument; vt != nil { - res.any = &vt.Citations - } else if vt := u.OfSearchResult; vt != nil { - res.any = &vt.Citations - } - return +// Returns the unmodified JSON received from the API +func (r CitationsSearchResultLocation) RawJSON() string { return r.JSON.raw } +func (r *CitationsSearchResultLocation) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Can have the runtime types [*[]TextCitationParamUnion], [*CitationsConfigParam] -type contentBlockParamUnionCitations struct{ any } +type CitationsWebSearchResultLocation struct { + CitedText string `json:"cited_text" api:"required"` + EncryptedIndex string `json:"encrypted_index" api:"required"` + Title string `json:"title" api:"required"` + Type constant.WebSearchResultLocation `json:"type" default:"web_search_result_location"` + URL string `json:"url" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + CitedText respjson.Field + EncryptedIndex respjson.Field + Title respjson.Field + Type respjson.Field + URL respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} -// Use the following switch statement to get the type of the union: -// -// switch u.AsAny().(type) { -// case *[]anthropic.TextCitationParamUnion: -// case *anthropic.CitationsConfigParam: -// default: -// fmt.Errorf("not present") -// } -func (u contentBlockParamUnionCitations) AsAny() any { return u.any } +// Returns the unmodified JSON received from the API +func (r CitationsWebSearchResultLocation) RawJSON() string { return r.JSON.raw } +func (r *CitationsWebSearchResultLocation) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} -// Returns a pointer to the underlying variant's property, if present. -func (u contentBlockParamUnionCitations) GetEnabled() *bool { - switch vt := u.any.(type) { - case *CitationsConfigParam: - return paramutil.AddrIfPresent(vt.Enabled) - } - return nil +type CodeExecutionOutputBlock struct { + FileID string `json:"file_id" api:"required"` + Type constant.CodeExecutionOutput `json:"type" default:"code_execution_output"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + FileID respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` } -// Returns a subunion which exports methods to access subproperties -// -// Or use AsAny() to get the underlying value -func (u ContentBlockParamUnion) GetSource() (res contentBlockParamUnionSource) { - if vt := u.OfImage; vt != nil { - res.any = vt.Source.asAny() - } else if vt := u.OfDocument; vt != nil { - res.any = vt.Source.asAny() - } else if vt := u.OfSearchResult; vt != nil { - res.any = &vt.Source - } - return +// Returns the unmodified JSON received from the API +func (r CodeExecutionOutputBlock) RawJSON() string { return r.JSON.raw } +func (r *CodeExecutionOutputBlock) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Can have the runtime types [*Base64ImageSourceParam], [*URLImageSourceParam], -// [*Base64PDFSourceParam], [*PlainTextSourceParam], [*ContentBlockSourceParam], -// [*URLPDFSourceParam], [*string] -type contentBlockParamUnionSource struct{ any } +// The properties FileID, Type are required. +type CodeExecutionOutputBlockParam struct { + FileID string `json:"file_id" api:"required"` + // This field can be elided, and will marshal its zero value as + // "code_execution_output". + Type constant.CodeExecutionOutput `json:"type" default:"code_execution_output"` + paramObj +} -// Use the following switch statement to get the type of the union: -// -// switch u.AsAny().(type) { -// case *anthropic.Base64ImageSourceParam: -// case *anthropic.URLImageSourceParam: -// case *anthropic.Base64PDFSourceParam: -// case *anthropic.PlainTextSourceParam: -// case *anthropic.ContentBlockSourceParam: -// case *anthropic.URLPDFSourceParam: -// case *string: -// default: -// fmt.Errorf("not present") -// } -func (u contentBlockParamUnionSource) AsAny() any { return u.any } +func (r CodeExecutionOutputBlockParam) MarshalJSON() (data []byte, err error) { + type shadow CodeExecutionOutputBlockParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *CodeExecutionOutputBlockParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} -// Returns a pointer to the underlying variant's property, if present. -func (u contentBlockParamUnionSource) GetContent() *ContentBlockSourceContentUnionParam { - switch vt := u.any.(type) { - case *DocumentBlockParamSourceUnion: - return vt.GetContent() - } - return nil +type CodeExecutionResultBlock struct { + Content []CodeExecutionOutputBlock `json:"content" api:"required"` + ReturnCode int64 `json:"return_code" api:"required"` + Stderr string `json:"stderr" api:"required"` + Stdout string `json:"stdout" api:"required"` + Type constant.CodeExecutionResult `json:"type" default:"code_execution_result"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Content respjson.Field + ReturnCode respjson.Field + Stderr respjson.Field + Stdout respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` } -// Returns a pointer to the underlying variant's property, if present. -func (u contentBlockParamUnionSource) GetData() *string { - switch vt := u.any.(type) { - case *ImageBlockParamSourceUnion: - return vt.GetData() - case *DocumentBlockParamSourceUnion: - return vt.GetData() - } - return nil +// Returns the unmodified JSON received from the API +func (r CodeExecutionResultBlock) RawJSON() string { return r.JSON.raw } +func (r *CodeExecutionResultBlock) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns a pointer to the underlying variant's property, if present. -func (u contentBlockParamUnionSource) GetMediaType() *string { - switch vt := u.any.(type) { - case *ImageBlockParamSourceUnion: - return vt.GetMediaType() - case *DocumentBlockParamSourceUnion: - return vt.GetMediaType() - } - return nil +// The properties Content, ReturnCode, Stderr, Stdout, Type are required. +type CodeExecutionResultBlockParam struct { + Content []CodeExecutionOutputBlockParam `json:"content,omitzero" api:"required"` + ReturnCode int64 `json:"return_code" api:"required"` + Stderr string `json:"stderr" api:"required"` + Stdout string `json:"stdout" api:"required"` + // This field can be elided, and will marshal its zero value as + // "code_execution_result". + Type constant.CodeExecutionResult `json:"type" default:"code_execution_result"` + paramObj } -// Returns a pointer to the underlying variant's property, if present. -func (u contentBlockParamUnionSource) GetType() *string { - switch vt := u.any.(type) { - case *ImageBlockParamSourceUnion: - return vt.GetType() - case *DocumentBlockParamSourceUnion: - return vt.GetType() - } - return nil +func (r CodeExecutionResultBlockParam) MarshalJSON() (data []byte, err error) { + type shadow CodeExecutionResultBlockParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *CodeExecutionResultBlockParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns a pointer to the underlying variant's property, if present. -func (u contentBlockParamUnionSource) GetURL() *string { - switch vt := u.any.(type) { - case *ImageBlockParamSourceUnion: - return vt.GetURL() - case *DocumentBlockParamSourceUnion: - return vt.GetURL() - } - return nil +// The properties Name, Type are required. +type CodeExecutionTool20250522Param struct { + // If true, tool will not be included in initial system prompt. Only loaded when + // returned via tool_reference from tool search. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // When true, guarantees schema validation on tool names and inputs + Strict param.Opt[bool] `json:"strict,omitzero"` + // Any of "direct", "code_execution_20250825", "code_execution_20260120", + // "code_execution_20260521". + AllowedCallers []string `json:"allowed_callers,omitzero"` + // Create a cache control breakpoint at this content block. + CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` + // Name of the tool. + // + // This is how the tool will be called by the model and in `tool_use` blocks. + // + // This field can be elided, and will marshal its zero value as "code_execution". + Name constant.CodeExecution `json:"name" default:"code_execution"` + // This field can be elided, and will marshal its zero value as + // "code_execution_20250522". + Type constant.CodeExecution20250522 `json:"type" default:"code_execution_20250522"` + paramObj } -// Returns a subunion which exports methods to access subproperties -// -// Or use AsAny() to get the underlying value -func (u ContentBlockParamUnion) GetContent() (res contentBlockParamUnionContent) { - if vt := u.OfSearchResult; vt != nil { - res.any = &vt.Content - } else if vt := u.OfToolResult; vt != nil { - res.any = &vt.Content - } else if vt := u.OfWebSearchToolResult; vt != nil { - res.any = vt.Content.asAny() - } else if vt := u.OfWebFetchToolResult; vt != nil { - res.any = vt.Content.asAny() - } else if vt := u.OfCodeExecutionToolResult; vt != nil { - res.any = vt.Content.asAny() - } else if vt := u.OfBashCodeExecutionToolResult; vt != nil { - res.any = vt.Content.asAny() - } else if vt := u.OfTextEditorCodeExecutionToolResult; vt != nil { - res.any = vt.Content.asAny() - } else if vt := u.OfToolSearchToolResult; vt != nil { - res.any = vt.Content.asAny() - } - return +func (r CodeExecutionTool20250522Param) MarshalJSON() (data []byte, err error) { + type shadow CodeExecutionTool20250522Param + return param.MarshalObject(r, (*shadow)(&r)) } - -// Can have the runtime types [_[]TextBlockParam], -// [_[]ToolResultBlockParamContentUnion], [*[]WebSearchResultBlockParam], -// [*WebFetchToolResultErrorBlockParam], [*WebFetchBlockParam], -// [*CodeExecutionToolResultErrorParam], [*CodeExecutionResultBlockParam], -// [*EncryptedCodeExecutionResultBlockParam], -// [*BashCodeExecutionToolResultErrorParam], [*BashCodeExecutionResultBlockParam], -// [*TextEditorCodeExecutionToolResultErrorParam], -// [*TextEditorCodeExecutionViewResultBlockParam], -// [*TextEditorCodeExecutionCreateResultBlockParam], -// [*TextEditorCodeExecutionStrReplaceResultBlockParam], -// [*ToolSearchToolResultErrorParam], [*ToolSearchToolSearchResultBlockParam] -type contentBlockParamUnionContent struct{ any } - -// Use the following switch statement to get the type of the union: -// -// switch u.AsAny().(type) { -// case *[]anthropic.TextBlockParam: -// case *[]anthropic.ToolResultBlockParamContentUnion: -// case *[]anthropic.WebSearchResultBlockParam: -// case *anthropic.WebFetchToolResultErrorBlockParam: -// case *anthropic.WebFetchBlockParam: -// case *anthropic.CodeExecutionToolResultErrorParam: -// case *anthropic.CodeExecutionResultBlockParam: -// case *anthropic.EncryptedCodeExecutionResultBlockParam: -// case *anthropic.BashCodeExecutionToolResultErrorParam: -// case *anthropic.BashCodeExecutionResultBlockParam: -// case *anthropic.TextEditorCodeExecutionToolResultErrorParam: -// case *anthropic.TextEditorCodeExecutionViewResultBlockParam: -// case *anthropic.TextEditorCodeExecutionCreateResultBlockParam: -// case *anthropic.TextEditorCodeExecutionStrReplaceResultBlockParam: -// case *anthropic.ToolSearchToolResultErrorParam: -// case *anthropic.ToolSearchToolSearchResultBlockParam: -// default: -// fmt.Errorf("not present") -// } -func (u contentBlockParamUnionContent) AsAny() any { return u.any } - -// Returns a pointer to the underlying variant's property, if present. -func (u contentBlockParamUnionContent) GetURL() *string { - switch vt := u.any.(type) { - case *WebFetchToolResultBlockParamContentUnion: - return vt.GetURL() - } - return nil +func (r *CodeExecutionTool20250522Param) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns a pointer to the underlying variant's property, if present. -func (u contentBlockParamUnionContent) GetRetrievedAt() *string { - switch vt := u.any.(type) { - case *WebFetchToolResultBlockParamContentUnion: - return vt.GetRetrievedAt() - } - return nil +// The properties Name, Type are required. +type CodeExecutionTool20250825Param struct { + // If true, tool will not be included in initial system prompt. Only loaded when + // returned via tool_reference from tool search. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // When true, guarantees schema validation on tool names and inputs + Strict param.Opt[bool] `json:"strict,omitzero"` + // Any of "direct", "code_execution_20250825", "code_execution_20260120", + // "code_execution_20260521". + AllowedCallers []string `json:"allowed_callers,omitzero"` + // Create a cache control breakpoint at this content block. + CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` + // Name of the tool. + // + // This is how the tool will be called by the model and in `tool_use` blocks. + // + // This field can be elided, and will marshal its zero value as "code_execution". + Name constant.CodeExecution `json:"name" default:"code_execution"` + // This field can be elided, and will marshal its zero value as + // "code_execution_20250825". + Type constant.CodeExecution20250825 `json:"type" default:"code_execution_20250825"` + paramObj } -// Returns a pointer to the underlying variant's property, if present. -func (u contentBlockParamUnionContent) GetEncryptedStdout() *string { - switch vt := u.any.(type) { - case *CodeExecutionToolResultBlockParamContentUnion: - return vt.GetEncryptedStdout() - } - return nil +func (r CodeExecutionTool20250825Param) MarshalJSON() (data []byte, err error) { + type shadow CodeExecutionTool20250825Param + return param.MarshalObject(r, (*shadow)(&r)) } - -// Returns a pointer to the underlying variant's property, if present. -func (u contentBlockParamUnionContent) GetErrorMessage() *string { - switch vt := u.any.(type) { - case *TextEditorCodeExecutionToolResultBlockParamContentUnion: - return vt.GetErrorMessage() - } - return nil +func (r *CodeExecutionTool20250825Param) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns a pointer to the underlying variant's property, if present. -func (u contentBlockParamUnionContent) GetFileType() *string { - switch vt := u.any.(type) { - case *TextEditorCodeExecutionToolResultBlockParamContentUnion: - return vt.GetFileType() - } - return nil +// Code execution tool with REPL state persistence (daemon mode + gVisor +// checkpoint). +// +// The properties Name, Type are required. +type CodeExecutionTool20260120Param struct { + // If true, tool will not be included in initial system prompt. Only loaded when + // returned via tool_reference from tool search. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // When true, guarantees schema validation on tool names and inputs + Strict param.Opt[bool] `json:"strict,omitzero"` + // Any of "direct", "code_execution_20250825", "code_execution_20260120", + // "code_execution_20260521". + AllowedCallers []string `json:"allowed_callers,omitzero"` + // Create a cache control breakpoint at this content block. + CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` + // Name of the tool. + // + // This is how the tool will be called by the model and in `tool_use` blocks. + // + // This field can be elided, and will marshal its zero value as "code_execution". + Name constant.CodeExecution `json:"name" default:"code_execution"` + // This field can be elided, and will marshal its zero value as + // "code_execution_20260120". + Type constant.CodeExecution20260120 `json:"type" default:"code_execution_20260120"` + paramObj } -// Returns a pointer to the underlying variant's property, if present. -func (u contentBlockParamUnionContent) GetNumLines() *int64 { - switch vt := u.any.(type) { - case *TextEditorCodeExecutionToolResultBlockParamContentUnion: - return vt.GetNumLines() - } - return nil +func (r CodeExecutionTool20260120Param) MarshalJSON() (data []byte, err error) { + type shadow CodeExecutionTool20260120Param + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *CodeExecutionTool20260120Param) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns a pointer to the underlying variant's property, if present. -func (u contentBlockParamUnionContent) GetStartLine() *int64 { - switch vt := u.any.(type) { - case *TextEditorCodeExecutionToolResultBlockParamContentUnion: - return vt.GetStartLine() - } - return nil +// Code execution tool with REPL state persistence. +// +// The properties Name, Type are required. +type CodeExecutionTool20260521Param struct { + // If true, tool will not be included in initial system prompt. Only loaded when + // returned via tool_reference from tool search. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // When true, guarantees schema validation on tool names and inputs + Strict param.Opt[bool] `json:"strict,omitzero"` + // Any of "direct", "code_execution_20250825", "code_execution_20260120", + // "code_execution_20260521". + AllowedCallers []string `json:"allowed_callers,omitzero"` + // Create a cache control breakpoint at this content block. + CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` + // Name of the tool. + // + // This is how the tool will be called by the model and in `tool_use` blocks. + // + // This field can be elided, and will marshal its zero value as "code_execution". + Name constant.CodeExecution `json:"name" default:"code_execution"` + // This field can be elided, and will marshal its zero value as + // "code_execution_20260521". + Type constant.CodeExecution20260521 `json:"type" default:"code_execution_20260521"` + paramObj } -// Returns a pointer to the underlying variant's property, if present. -func (u contentBlockParamUnionContent) GetTotalLines() *int64 { - switch vt := u.any.(type) { - case *TextEditorCodeExecutionToolResultBlockParamContentUnion: - return vt.GetTotalLines() - } - return nil +func (r CodeExecutionTool20260521Param) MarshalJSON() (data []byte, err error) { + type shadow CodeExecutionTool20260521Param + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *CodeExecutionTool20260521Param) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns a pointer to the underlying variant's property, if present. -func (u contentBlockParamUnionContent) GetIsFileUpdate() *bool { - switch vt := u.any.(type) { - case *TextEditorCodeExecutionToolResultBlockParamContentUnion: - return vt.GetIsFileUpdate() - } - return nil +type CodeExecutionToolResultBlock struct { + // Code execution result with encrypted stdout for PFC + web_search results. + Content CodeExecutionToolResultBlockContentUnion `json:"content" api:"required"` + ToolUseID string `json:"tool_use_id" api:"required"` + Type constant.CodeExecutionToolResult `json:"type" default:"code_execution_tool_result"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Content respjson.Field + ToolUseID respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` } -// Returns a pointer to the underlying variant's property, if present. -func (u contentBlockParamUnionContent) GetLines() []string { - switch vt := u.any.(type) { - case *TextEditorCodeExecutionToolResultBlockParamContentUnion: - return vt.GetLines() - } - return nil +// Returns the unmodified JSON received from the API +func (r CodeExecutionToolResultBlock) RawJSON() string { return r.JSON.raw } +func (r *CodeExecutionToolResultBlock) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns a pointer to the underlying variant's property, if present. -func (u contentBlockParamUnionContent) GetNewLines() *int64 { - switch vt := u.any.(type) { - case *TextEditorCodeExecutionToolResultBlockParamContentUnion: - return vt.GetNewLines() - } - return nil +// CodeExecutionToolResultBlockContentUnion contains all possible properties and +// values from [CodeExecutionToolResultError], [CodeExecutionResultBlock], +// [EncryptedCodeExecutionResultBlock]. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type CodeExecutionToolResultBlockContentUnion struct { + // This field is from variant [CodeExecutionToolResultError]. + ErrorCode CodeExecutionToolResultErrorCode `json:"error_code"` + Type string `json:"type"` + Content []CodeExecutionOutputBlock `json:"content"` + ReturnCode int64 `json:"return_code"` + Stderr string `json:"stderr"` + // This field is from variant [CodeExecutionResultBlock]. + Stdout string `json:"stdout"` + // This field is from variant [EncryptedCodeExecutionResultBlock]. + EncryptedStdout string `json:"encrypted_stdout"` + JSON struct { + ErrorCode respjson.Field + Type respjson.Field + Content respjson.Field + ReturnCode respjson.Field + Stderr respjson.Field + Stdout respjson.Field + EncryptedStdout respjson.Field + raw string + } `json:"-"` } -// Returns a pointer to the underlying variant's property, if present. -func (u contentBlockParamUnionContent) GetNewStart() *int64 { - switch vt := u.any.(type) { - case *TextEditorCodeExecutionToolResultBlockParamContentUnion: - return vt.GetNewStart() - } - return nil +func (u CodeExecutionToolResultBlockContentUnion) AsResponseCodeExecutionToolResultError() (v CodeExecutionToolResultError) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -// Returns a pointer to the underlying variant's property, if present. -func (u contentBlockParamUnionContent) GetOldLines() *int64 { - switch vt := u.any.(type) { - case *TextEditorCodeExecutionToolResultBlockParamContentUnion: - return vt.GetOldLines() +func (u CodeExecutionToolResultBlockContentUnion) AsResponseCodeExecutionResultBlock() (v CodeExecutionResultBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u CodeExecutionToolResultBlockContentUnion) AsResponseEncryptedCodeExecutionResultBlock() (v EncryptedCodeExecutionResultBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u CodeExecutionToolResultBlockContentUnion) RawJSON() string { return u.JSON.raw } + +func (r *CodeExecutionToolResultBlockContentUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The properties Content, ToolUseID, Type are required. +type CodeExecutionToolResultBlockParam struct { + // Code execution result with encrypted stdout for PFC + web_search results. + Content CodeExecutionToolResultBlockParamContentUnion `json:"content,omitzero" api:"required"` + ToolUseID string `json:"tool_use_id" api:"required"` + // Create a cache control breakpoint at this content block. + CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` + // This field can be elided, and will marshal its zero value as + // "code_execution_tool_result". + Type constant.CodeExecutionToolResult `json:"type" default:"code_execution_tool_result"` + paramObj +} + +func (r CodeExecutionToolResultBlockParam) MarshalJSON() (data []byte, err error) { + type shadow CodeExecutionToolResultBlockParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *CodeExecutionToolResultBlockParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +func CodeExecutionToolResultBlockParamContentOfRequestCodeExecutionToolResultError(errorCode CodeExecutionToolResultErrorCode) CodeExecutionToolResultBlockParamContentUnion { + var variant CodeExecutionToolResultErrorParam + variant.ErrorCode = errorCode + return CodeExecutionToolResultBlockParamContentUnion{OfRequestCodeExecutionToolResultError: &variant} +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type CodeExecutionToolResultBlockParamContentUnion struct { + OfRequestCodeExecutionToolResultError *CodeExecutionToolResultErrorParam `json:",omitzero,inline"` + OfRequestCodeExecutionResultBlock *CodeExecutionResultBlockParam `json:",omitzero,inline"` + OfRequestEncryptedCodeExecutionResultBlock *EncryptedCodeExecutionResultBlockParam `json:",omitzero,inline"` + paramUnion +} + +func (u CodeExecutionToolResultBlockParamContentUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfRequestCodeExecutionToolResultError, u.OfRequestCodeExecutionResultBlock, u.OfRequestEncryptedCodeExecutionResultBlock) +} +func (u *CodeExecutionToolResultBlockParamContentUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *CodeExecutionToolResultBlockParamContentUnion) asAny() any { + if !param.IsOmitted(u.OfRequestCodeExecutionToolResultError) { + return u.OfRequestCodeExecutionToolResultError + } else if !param.IsOmitted(u.OfRequestCodeExecutionResultBlock) { + return u.OfRequestCodeExecutionResultBlock + } else if !param.IsOmitted(u.OfRequestEncryptedCodeExecutionResultBlock) { + return u.OfRequestEncryptedCodeExecutionResultBlock } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u contentBlockParamUnionContent) GetOldStart() *int64 { - switch vt := u.any.(type) { - case *TextEditorCodeExecutionToolResultBlockParamContentUnion: - return vt.GetOldStart() +func (u CodeExecutionToolResultBlockParamContentUnion) GetErrorCode() *string { + if vt := u.OfRequestCodeExecutionToolResultError; vt != nil { + return (*string)(&vt.ErrorCode) } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u contentBlockParamUnionContent) GetToolReferences() []ToolReferenceBlockParam { - switch vt := u.any.(type) { - case *ToolSearchToolResultBlockParamContentUnion: - return vt.GetToolReferences() +func (u CodeExecutionToolResultBlockParamContentUnion) GetStdout() *string { + if vt := u.OfRequestCodeExecutionResultBlock; vt != nil { + return &vt.Stdout } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u contentBlockParamUnionContent) GetErrorCode() *string { - switch vt := u.any.(type) { - case *WebSearchToolResultBlockParamContentUnion: - if vt.OfRequestWebSearchToolResultError != nil { - return (*string)(&vt.OfRequestWebSearchToolResultError.ErrorCode) - } - case *WebFetchToolResultBlockParamContentUnion: - return vt.GetErrorCode() - case *CodeExecutionToolResultBlockParamContentUnion: - return vt.GetErrorCode() - case *BashCodeExecutionToolResultBlockParamContentUnion: - return vt.GetErrorCode() - case *TextEditorCodeExecutionToolResultBlockParamContentUnion: - return vt.GetErrorCode() - case *ToolSearchToolResultBlockParamContentUnion: - return vt.GetErrorCode() +func (u CodeExecutionToolResultBlockParamContentUnion) GetEncryptedStdout() *string { + if vt := u.OfRequestEncryptedCodeExecutionResultBlock; vt != nil { + return &vt.EncryptedStdout } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u contentBlockParamUnionContent) GetType() *string { - switch vt := u.any.(type) { - case *WebSearchToolResultBlockParamContentUnion: - if vt.OfRequestWebSearchToolResultError != nil { - return (*string)(&vt.OfRequestWebSearchToolResultError.Type) - } - case *WebFetchToolResultBlockParamContentUnion: - return vt.GetType() - case *CodeExecutionToolResultBlockParamContentUnion: - return vt.GetType() - case *BashCodeExecutionToolResultBlockParamContentUnion: - return vt.GetType() - case *TextEditorCodeExecutionToolResultBlockParamContentUnion: - return vt.GetType() - case *ToolSearchToolResultBlockParamContentUnion: - return vt.GetType() +func (u CodeExecutionToolResultBlockParamContentUnion) GetType() *string { + if vt := u.OfRequestCodeExecutionToolResultError; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfRequestCodeExecutionResultBlock; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfRequestEncryptedCodeExecutionResultBlock; vt != nil { + return (*string)(&vt.Type) } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u contentBlockParamUnionContent) GetReturnCode() *int64 { - switch vt := u.any.(type) { - case *CodeExecutionToolResultBlockParamContentUnion: - return vt.GetReturnCode() - case *BashCodeExecutionToolResultBlockParamContentUnion: - return vt.GetReturnCode() +func (u CodeExecutionToolResultBlockParamContentUnion) GetReturnCode() *int64 { + if vt := u.OfRequestCodeExecutionResultBlock; vt != nil { + return (*int64)(&vt.ReturnCode) + } else if vt := u.OfRequestEncryptedCodeExecutionResultBlock; vt != nil { + return (*int64)(&vt.ReturnCode) } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u contentBlockParamUnionContent) GetStderr() *string { - switch vt := u.any.(type) { - case *CodeExecutionToolResultBlockParamContentUnion: - return vt.GetStderr() - case *BashCodeExecutionToolResultBlockParamContentUnion: - return vt.GetStderr() +func (u CodeExecutionToolResultBlockParamContentUnion) GetStderr() *string { + if vt := u.OfRequestCodeExecutionResultBlock; vt != nil { + return (*string)(&vt.Stderr) + } else if vt := u.OfRequestEncryptedCodeExecutionResultBlock; vt != nil { + return (*string)(&vt.Stderr) } return nil } -// Returns a pointer to the underlying variant's property, if present. -func (u contentBlockParamUnionContent) GetStdout() *string { - switch vt := u.any.(type) { - case *CodeExecutionToolResultBlockParamContentUnion: - return vt.GetStdout() - case *BashCodeExecutionToolResultBlockParamContentUnion: - return vt.GetStdout() +// Returns a pointer to the underlying variant's Content property, if present. +func (u CodeExecutionToolResultBlockParamContentUnion) GetContent() []CodeExecutionOutputBlockParam { + if vt := u.OfRequestCodeExecutionResultBlock; vt != nil { + return vt.Content + } else if vt := u.OfRequestEncryptedCodeExecutionResultBlock; vt != nil { + return vt.Content } return nil } -// Returns a subunion which exports methods to access subproperties -// -// Or use AsAny() to get the underlying value -func (u contentBlockParamUnionContent) GetContent() (res contentBlockParamUnionContentContent) { - switch vt := u.any.(type) { - case *WebFetchToolResultBlockParamContentUnion: - res.any = vt.GetContent() - case *CodeExecutionToolResultBlockParamContentUnion: - res.any = vt.GetContent() - case *BashCodeExecutionToolResultBlockParamContentUnion: - res.any = vt.GetContent() - case *TextEditorCodeExecutionToolResultBlockParamContentUnion: - res.any = vt.GetContent() - } - return res +type CodeExecutionToolResultError struct { + // Any of "invalid_tool_input", "unavailable", "too_many_requests", + // "execution_time_exceeded". + ErrorCode CodeExecutionToolResultErrorCode `json:"error_code" api:"required"` + Type constant.CodeExecutionToolResultError `json:"type" default:"code_execution_tool_result_error"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ErrorCode respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` } -// Can have the runtime types [*DocumentBlockParam], -// [_[]CodeExecutionOutputBlockParam], [_[]BashCodeExecutionOutputBlockParam], -// [*string] -type contentBlockParamUnionContentContent struct{ any } +// Returns the unmodified JSON received from the API +func (r CodeExecutionToolResultError) RawJSON() string { return r.JSON.raw } +func (r *CodeExecutionToolResultError) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} -// Use the following switch statement to get the type of the union: -// -// switch u.AsAny().(type) { -// case *anthropic.DocumentBlockParam: -// case *[]anthropic.CodeExecutionOutputBlockParam: -// case *[]anthropic.BashCodeExecutionOutputBlockParam: -// case *string: -// default: -// fmt.Errorf("not present") -// } -func (u contentBlockParamUnionContentContent) AsAny() any { return u.any } +type CodeExecutionToolResultErrorCode string -// Returns a pointer to the underlying variant's Input property, if present. -func (u ContentBlockParamUnion) GetInput() *any { - if vt := u.OfToolUse; vt != nil { - return &vt.Input - } else if vt := u.OfServerToolUse; vt != nil { - return &vt.Input - } - return nil -} +const ( + CodeExecutionToolResultErrorCodeInvalidToolInput CodeExecutionToolResultErrorCode = "invalid_tool_input" + CodeExecutionToolResultErrorCodeUnavailable CodeExecutionToolResultErrorCode = "unavailable" + CodeExecutionToolResultErrorCodeTooManyRequests CodeExecutionToolResultErrorCode = "too_many_requests" + CodeExecutionToolResultErrorCodeExecutionTimeExceeded CodeExecutionToolResultErrorCode = "execution_time_exceeded" +) -// Returns a subunion which exports methods to access subproperties -// -// Or use AsAny() to get the underlying value -func (u ContentBlockParamUnion) GetCaller() (res contentBlockParamUnionCaller) { - if vt := u.OfToolUse; vt != nil { - res.any = vt.Caller.asAny() - } else if vt := u.OfServerToolUse; vt != nil { - res.any = vt.Caller.asAny() - } else if vt := u.OfWebSearchToolResult; vt != nil { - res.any = vt.Caller.asAny() - } else if vt := u.OfWebFetchToolResult; vt != nil { - res.any = vt.Caller.asAny() - } - return +// The properties ErrorCode, Type are required. +type CodeExecutionToolResultErrorParam struct { + // Any of "invalid_tool_input", "unavailable", "too_many_requests", + // "execution_time_exceeded". + ErrorCode CodeExecutionToolResultErrorCode `json:"error_code,omitzero" api:"required"` + // This field can be elided, and will marshal its zero value as + // "code_execution_tool_result_error". + Type constant.CodeExecutionToolResultError `json:"type" default:"code_execution_tool_result_error"` + paramObj } -// Can have the runtime types [*DirectCallerParam], [*ServerToolCallerParam], -// [*ServerToolCaller20260120Param] -type contentBlockParamUnionCaller struct{ any } - -// Use the following switch statement to get the type of the union: -// -// switch u.AsAny().(type) { -// case *anthropic.DirectCallerParam: -// case *anthropic.ServerToolCallerParam: -// case *anthropic.ServerToolCaller20260120Param: -// default: -// fmt.Errorf("not present") -// } -func (u contentBlockParamUnionCaller) AsAny() any { return u.any } - -// Returns a pointer to the underlying variant's property, if present. -func (u contentBlockParamUnionCaller) GetType() *string { - switch vt := u.any.(type) { - case *ToolUseBlockParamCallerUnion: - return vt.GetType() - case *ServerToolUseBlockParamCallerUnion: - return vt.GetType() - case *WebSearchToolResultBlockParamCallerUnion: - return vt.GetType() - case *WebFetchToolResultBlockParamCallerUnion: - return vt.GetType() - } - return nil +func (r CodeExecutionToolResultErrorParam) MarshalJSON() (data []byte, err error) { + type shadow CodeExecutionToolResultErrorParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *CodeExecutionToolResultErrorParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns a pointer to the underlying variant's property, if present. -func (u contentBlockParamUnionCaller) GetToolID() *string { - switch vt := u.any.(type) { - case *ToolUseBlockParamCallerUnion: - return vt.GetToolID() - case *ServerToolUseBlockParamCallerUnion: - return vt.GetToolID() - case *WebSearchToolResultBlockParamCallerUnion: - return vt.GetToolID() - case *WebFetchToolResultBlockParamCallerUnion: - return vt.GetToolID() - } - return nil +// `cursor_position`'s config overrides. +type ComputerCursorPositionConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -func init() { - apijson.RegisterCustomDecoder[[]ContentBlockParamUnion](func(node gjson.Result, value reflect.Value, defaultDecoder func(gjson.Result, reflect.Value) error) error { - if node.Type == gjson.String { - textBlock := TextBlockParam{Text: node.String(), Type: "text"} - contentUnion := ContentBlockParamUnion{OfText: &textBlock} - arrayValue := reflect.MakeSlice(value.Type(), 1, 1) - arrayValue.Index(0).Set(reflect.ValueOf(contentUnion)) - value.Set(arrayValue) - return nil - } - return defaultDecoder(node, value) - }) +func (r ComputerCursorPositionConfigParam) MarshalJSON() (data []byte, err error) { + type shadow ComputerCursorPositionConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *ComputerCursorPositionConfigParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func init() { - apijson.RegisterCustomDecoder[[]ToolResultBlockParamContentUnion](func(node gjson.Result, value reflect.Value, defaultDecoder func(gjson.Result, reflect.Value) error) error { - if node.Type == gjson.String { - textBlock := TextBlockParam{Text: node.String(), Type: "text"} - contentUnion := ToolResultBlockParamContentUnion{OfText: &textBlock} - arrayValue := reflect.MakeSlice(value.Type(), 1, 1) - arrayValue.Index(0).Set(reflect.ValueOf(contentUnion)) - value.Set(arrayValue) - return nil - } - return defaultDecoder(node, value) - }) +// `double_click`'s config overrides. +type ComputerDoubleClickConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -func init() { - apijson.RegisterUnion[ContentBlockParamUnion]( - "type", - apijson.Discriminator[TextBlockParam]("text"), - apijson.Discriminator[ImageBlockParam]("image"), - apijson.Discriminator[DocumentBlockParam]("document"), - apijson.Discriminator[SearchResultBlockParam]("search_result"), - apijson.Discriminator[ThinkingBlockParam]("thinking"), - apijson.Discriminator[RedactedThinkingBlockParam]("redacted_thinking"), - apijson.Discriminator[ToolUseBlockParam]("tool_use"), - apijson.Discriminator[ToolResultBlockParam]("tool_result"), - apijson.Discriminator[ServerToolUseBlockParam]("server_tool_use"), - apijson.Discriminator[WebSearchToolResultBlockParam]("web_search_tool_result"), - apijson.Discriminator[WebFetchToolResultBlockParam]("web_fetch_tool_result"), - apijson.Discriminator[CodeExecutionToolResultBlockParam]("code_execution_tool_result"), - apijson.Discriminator[BashCodeExecutionToolResultBlockParam]("bash_code_execution_tool_result"), - apijson.Discriminator[TextEditorCodeExecutionToolResultBlockParam]("text_editor_code_execution_tool_result"), - apijson.Discriminator[ToolSearchToolResultBlockParam]("tool_search_tool_result"), - apijson.Discriminator[ContainerUploadBlockParam]("container_upload"), - ) +func (r ComputerDoubleClickConfigParam) MarshalJSON() (data []byte, err error) { + type shadow ComputerDoubleClickConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *ComputerDoubleClickConfigParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// The properties Content, Type are required. -type ContentBlockSourceParam struct { - Content ContentBlockSourceContentUnionParam `json:"content,omitzero" api:"required"` - // This field can be elided, and will marshal its zero value as "content". - Type constant.Content `json:"type" default:"content"` +// `hold_key`'s config overrides. +type ComputerHoldKeyConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` paramObj } -func (r ContentBlockSourceParam) MarshalJSON() (data []byte, err error) { - type shadow ContentBlockSourceParam +func (r ComputerHoldKeyConfigParam) MarshalJSON() (data []byte, err error) { + type shadow ComputerHoldKeyConfigParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *ContentBlockSourceParam) UnmarshalJSON(data []byte) error { +func (r *ComputerHoldKeyConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type ContentBlockSourceContentUnionParam struct { - OfString param.Opt[string] `json:",omitzero,inline"` - OfContentBlockSourceContent []ContentBlockSourceContentItemUnionParam `json:",omitzero,inline"` - paramUnion +// `key`'s config overrides. +type ComputerKeyConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -func (u ContentBlockSourceContentUnionParam) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfString, u.OfContentBlockSourceContent) +func (r ComputerKeyConfigParam) MarshalJSON() (data []byte, err error) { + type shadow ComputerKeyConfigParam + return param.MarshalObject(r, (*shadow)(&r)) } -func (u *ContentBlockSourceContentUnionParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) +func (r *ComputerKeyConfigParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func (u *ContentBlockSourceContentUnionParam) asAny() any { - if !param.IsOmitted(u.OfString) { - return &u.OfString.Value - } else if !param.IsOmitted(u.OfContentBlockSourceContent) { - return &u.OfContentBlockSourceContent - } - return nil +// `left_click`'s config overrides. +type ComputerLeftClickConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -func ContentBlockSourceContentItemParamOfText(text string) ContentBlockSourceContentItemUnionParam { - var variant TextBlockParam - variant.Text = text - return ContentBlockSourceContentItemUnionParam{OfText: &variant} +func (r ComputerLeftClickConfigParam) MarshalJSON() (data []byte, err error) { + type shadow ComputerLeftClickConfigParam + return param.MarshalObject(r, (*shadow)(&r)) } - -func ContentBlockSourceContentItemParamOfImage[T Base64ImageSourceParam | URLImageSourceParam](source T) ContentBlockSourceContentItemUnionParam { - var image ImageBlockParam - switch v := any(source).(type) { - case Base64ImageSourceParam: - image.Source.OfBase64 = &v - case URLImageSourceParam: - image.Source.OfURL = &v - } - return ContentBlockSourceContentItemUnionParam{OfImage: &image} +func (r *ComputerLeftClickConfigParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type ContentBlockSourceContentItemUnionParam struct { - OfText *TextBlockParam `json:",omitzero,inline"` - OfImage *ImageBlockParam `json:",omitzero,inline"` - paramUnion +// `left_click_drag`'s config overrides. +type ComputerLeftClickDragConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -func (u ContentBlockSourceContentItemUnionParam) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfText, u.OfImage) +func (r ComputerLeftClickDragConfigParam) MarshalJSON() (data []byte, err error) { + type shadow ComputerLeftClickDragConfigParam + return param.MarshalObject(r, (*shadow)(&r)) } -func (u *ContentBlockSourceContentItemUnionParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) +func (r *ComputerLeftClickDragConfigParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func (u *ContentBlockSourceContentItemUnionParam) asAny() any { - if !param.IsOmitted(u.OfText) { - return u.OfText - } else if !param.IsOmitted(u.OfImage) { - return u.OfImage - } - return nil +// `left_mouse_down`'s config overrides. +type ComputerLeftMouseDownConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -// Returns a pointer to the underlying variant's property, if present. -func (u ContentBlockSourceContentItemUnionParam) GetText() *string { - if vt := u.OfText; vt != nil { - return &vt.Text - } - return nil +func (r ComputerLeftMouseDownConfigParam) MarshalJSON() (data []byte, err error) { + type shadow ComputerLeftMouseDownConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *ComputerLeftMouseDownConfigParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns a pointer to the underlying variant's property, if present. -func (u ContentBlockSourceContentItemUnionParam) GetCitations() []TextCitationParamUnion { - if vt := u.OfText; vt != nil { - return vt.Citations - } - return nil +// `left_mouse_up`'s config overrides. +type ComputerLeftMouseUpConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -// Returns a pointer to the underlying variant's property, if present. -func (u ContentBlockSourceContentItemUnionParam) GetSource() *ImageBlockParamSourceUnion { - if vt := u.OfImage; vt != nil { - return &vt.Source - } - return nil +func (r ComputerLeftMouseUpConfigParam) MarshalJSON() (data []byte, err error) { + type shadow ComputerLeftMouseUpConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *ComputerLeftMouseUpConfigParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns a pointer to the underlying variant's property, if present. -func (u ContentBlockSourceContentItemUnionParam) GetType() *string { - if vt := u.OfText; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfImage; vt != nil { - return (*string)(&vt.Type) - } - return nil +// `middle_click`'s config overrides. +type ComputerMiddleClickConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -// Returns a pointer to the underlying variant's CacheControl property, if present. -func (u ContentBlockSourceContentItemUnionParam) GetCacheControl() *CacheControlEphemeralParam { - if vt := u.OfText; vt != nil { - return &vt.CacheControl - } else if vt := u.OfImage; vt != nil { - return &vt.CacheControl - } - return nil +func (r ComputerMiddleClickConfigParam) MarshalJSON() (data []byte, err error) { + type shadow ComputerMiddleClickConfigParam + return param.MarshalObject(r, (*shadow)(&r)) } - -func init() { - apijson.RegisterUnion[ContentBlockSourceContentItemUnionParam]( - "type", - apijson.Discriminator[TextBlockParam]("text"), - apijson.Discriminator[ImageBlockParam]("image"), - ) +func (r *ComputerMiddleClickConfigParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Tool invocation directly from the model. -type DirectCaller struct { - Type constant.Direct `json:"type" default:"direct"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +// `mouse_move`'s config overrides. +type ComputerMouseMoveConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -// Returns the unmodified JSON received from the API -func (r DirectCaller) RawJSON() string { return r.JSON.raw } -func (r *DirectCaller) UnmarshalJSON(data []byte) error { +func (r ComputerMouseMoveConfigParam) MarshalJSON() (data []byte, err error) { + type shadow ComputerMouseMoveConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *ComputerMouseMoveConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// ToParam converts this DirectCaller to a DirectCallerParam. -// -// Warning: the fields of the param type will not be present. ToParam should only -// be used at the last possible moment before sending a request. Test for this with -// DirectCallerParam.Overrides() -func (r DirectCaller) ToParam() DirectCallerParam { - return param.Override[DirectCallerParam](json.RawMessage(r.RawJSON())) +// `right_click`'s config overrides. +type ComputerRightClickConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -func NewDirectCallerParam() DirectCallerParam { - return DirectCallerParam{ - Type: "direct", - } +func (r ComputerRightClickConfigParam) MarshalJSON() (data []byte, err error) { + type shadow ComputerRightClickConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *ComputerRightClickConfigParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Tool invocation directly from the model. -// -// This struct has a constant value, construct it with [NewDirectCallerParam]. -type DirectCallerParam struct { - Type constant.Direct `json:"type" default:"direct"` +// `screenshot`'s config overrides. +type ComputerScreenshotConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` paramObj } -func (r DirectCallerParam) MarshalJSON() (data []byte, err error) { - type shadow DirectCallerParam +func (r ComputerScreenshotConfigParam) MarshalJSON() (data []byte, err error) { + type shadow ComputerScreenshotConfigParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *DirectCallerParam) UnmarshalJSON(data []byte) error { +func (r *ComputerScreenshotConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type DocumentBlock struct { - // Citation configuration for the document - Citations CitationsConfig `json:"citations" api:"required"` - Source DocumentBlockSourceUnion `json:"source" api:"required"` - // The title of the document - Title string `json:"title" api:"required"` - Type constant.Document `json:"type" default:"document"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Citations respjson.Field - Source respjson.Field - Title respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +// `scroll`'s config overrides. +type ComputerScrollConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -// Returns the unmodified JSON received from the API -func (r DocumentBlock) RawJSON() string { return r.JSON.raw } -func (r *DocumentBlock) UnmarshalJSON(data []byte) error { +func (r ComputerScrollConfigParam) MarshalJSON() (data []byte, err error) { + type shadow ComputerScrollConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *ComputerScrollConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// DocumentBlockSourceUnion contains all possible properties and values from -// [Base64PDFSource], [PlainTextSource]. -// -// Use the [DocumentBlockSourceUnion.AsAny] method to switch on the variant. +// The computer toolset: a single `tools[]` entry (carrying no `name`) that +// declares the computer tool family. The model is served the family's tool with +// any members disabled via `configs` removed from its schema. Every member is +// enabled by default, zoom included. The single-tool options `display_number` and +// `enable_zoom` are not fields of a toolset entry — it carries only `type`, +// `configs`, and `cache_control`; zoom is controlled via `configs.zoom.enabled`. // -// Use the methods beginning with 'As' to cast the union to one of its variants. -type DocumentBlockSourceUnion struct { - Data string `json:"data"` - MediaType string `json:"media_type"` - // Any of "base64", "text". - Type string `json:"type"` - JSON struct { - Data respjson.Field - MediaType respjson.Field - Type respjson.Field - raw string - } `json:"-"` +// The property Type is required. +type ComputerToolset20260801Param struct { + // Any of "direct", "code_execution_20250825", "code_execution_20260120", + // "code_execution_20260521". + AllowedCallers []string `json:"allowed_callers,omitzero"` + // Create a cache control breakpoint at this content block. + CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` + // Per-member configuration for `computer_toolset_20260801`: one optional field per + // member tool, keyed by the member name — the same name the member's `tool_use` + // blocks carry. Every member is an accepted key, and a member's defaults apply + // wherever its key is absent. Unknown keys are rejected: the field set is this + // toolset version's complete member set. + Configs ComputerToolsetConfigsParam `json:"configs,omitzero"` + // This field can be elided, and will marshal its zero value as + // "computer_toolset_20260801". + Type constant.ComputerToolset20260801 `json:"type" default:"computer_toolset_20260801"` + paramObj } -// anyDocumentBlockSource is implemented by each variant of -// [DocumentBlockSourceUnion] to add type safety for the return type of -// [DocumentBlockSourceUnion.AsAny] -type anyDocumentBlockSource interface { - implDocumentBlockSourceUnion() +func (r ComputerToolset20260801Param) MarshalJSON() (data []byte, err error) { + type shadow ComputerToolset20260801Param + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *ComputerToolset20260801Param) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Per-member configuration for `computer_toolset_20260801`: one optional field per +// member tool, keyed by the member name — the same name the member's `tool_use` +// blocks carry. Every member is an accepted key, and a member's defaults apply +// wherever its key is absent. Unknown keys are rejected: the field set is this +// toolset version's complete member set. +type ComputerToolsetConfigsParam struct { + // `cursor_position`'s config overrides. + CursorPosition ComputerCursorPositionConfigParam `json:"cursor_position,omitzero"` + // `double_click`'s config overrides. + DoubleClick ComputerDoubleClickConfigParam `json:"double_click,omitzero"` + // `hold_key`'s config overrides. + HoldKey ComputerHoldKeyConfigParam `json:"hold_key,omitzero"` + // `key`'s config overrides. + Key ComputerKeyConfigParam `json:"key,omitzero"` + // `left_click`'s config overrides. + LeftClick ComputerLeftClickConfigParam `json:"left_click,omitzero"` + // `left_click_drag`'s config overrides. + LeftClickDrag ComputerLeftClickDragConfigParam `json:"left_click_drag,omitzero"` + // `left_mouse_down`'s config overrides. + LeftMouseDown ComputerLeftMouseDownConfigParam `json:"left_mouse_down,omitzero"` + // `left_mouse_up`'s config overrides. + LeftMouseUp ComputerLeftMouseUpConfigParam `json:"left_mouse_up,omitzero"` + // `middle_click`'s config overrides. + MiddleClick ComputerMiddleClickConfigParam `json:"middle_click,omitzero"` + // `mouse_move`'s config overrides. + MouseMove ComputerMouseMoveConfigParam `json:"mouse_move,omitzero"` + // `right_click`'s config overrides. + RightClick ComputerRightClickConfigParam `json:"right_click,omitzero"` + // `screenshot`'s config overrides. + Screenshot ComputerScreenshotConfigParam `json:"screenshot,omitzero"` + // `scroll`'s config overrides. + Scroll ComputerScrollConfigParam `json:"scroll,omitzero"` + // `triple_click`'s config overrides. + TripleClick ComputerTripleClickConfigParam `json:"triple_click,omitzero"` + // `type`'s config overrides. + Type ComputerTypeConfigParam `json:"type,omitzero"` + // `wait`'s config overrides. + Wait ComputerWaitConfigParam `json:"wait,omitzero"` + // `zoom`'s config overrides. + Zoom ComputerZoomConfigParam `json:"zoom,omitzero"` + paramObj } -func (Base64PDFSource) implDocumentBlockSourceUnion() {} -func (PlainTextSource) implDocumentBlockSourceUnion() {} - -// Use the following switch statement to find the correct variant -// -// switch variant := DocumentBlockSourceUnion.AsAny().(type) { -// case anthropic.Base64PDFSource: -// case anthropic.PlainTextSource: -// default: -// fmt.Errorf("no variant present") -// } -func (u DocumentBlockSourceUnion) AsAny() anyDocumentBlockSource { - switch u.Type { - case "base64": - return u.AsBase64() - case "text": - return u.AsText() - } - return nil +func (r ComputerToolsetConfigsParam) MarshalJSON() (data []byte, err error) { + type shadow ComputerToolsetConfigsParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *ComputerToolsetConfigsParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func (u DocumentBlockSourceUnion) AsBase64() (v Base64PDFSource) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +// `triple_click`'s config overrides. +type ComputerTripleClickConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -func (u DocumentBlockSourceUnion) AsText() (v PlainTextSource) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +func (r ComputerTripleClickConfigParam) MarshalJSON() (data []byte, err error) { + type shadow ComputerTripleClickConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *ComputerTripleClickConfigParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns the unmodified JSON received from the API -func (u DocumentBlockSourceUnion) RawJSON() string { return u.JSON.raw } +// `type`'s config overrides. +type ComputerTypeConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj +} -func (r *DocumentBlockSourceUnion) UnmarshalJSON(data []byte) error { +func (r ComputerTypeConfigParam) MarshalJSON() (data []byte, err error) { + type shadow ComputerTypeConfigParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *ComputerTypeConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The properties Source, Type are required. -type DocumentBlockParam struct { - Source DocumentBlockParamSourceUnion `json:"source,omitzero" api:"required"` - Context param.Opt[string] `json:"context,omitzero"` - Title param.Opt[string] `json:"title,omitzero"` - // Create a cache control breakpoint at this content block. - CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` - Citations CitationsConfigParam `json:"citations,omitzero"` - // This field can be elided, and will marshal its zero value as "document". - Type constant.Document `json:"type" default:"document"` +// `wait`'s config overrides. +type ComputerWaitConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` paramObj } -func (r DocumentBlockParam) MarshalJSON() (data []byte, err error) { - type shadow DocumentBlockParam +func (r ComputerWaitConfigParam) MarshalJSON() (data []byte, err error) { + type shadow ComputerWaitConfigParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *DocumentBlockParam) UnmarshalJSON(data []byte) error { +func (r *ComputerWaitConfigParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type DocumentBlockParamSourceUnion struct { - OfBase64 *Base64PDFSourceParam `json:",omitzero,inline"` - OfText *PlainTextSourceParam `json:",omitzero,inline"` - OfContent *ContentBlockSourceParam `json:",omitzero,inline"` - OfURL *URLPDFSourceParam `json:",omitzero,inline"` - paramUnion +// `zoom`'s config overrides. +type ComputerZoomConfigParam struct { + // Defer loading for this member. Must resolve to the same value on every enabled + // member of the toolset. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Whether this member is offered to the model. Default is per member, per the + // toolset's documentation. A member whose enabled resolves false is withheld from + // the served schema. + Enabled param.Opt[bool] `json:"enabled,omitzero"` + paramObj } -func (u DocumentBlockParamSourceUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfBase64, u.OfText, u.OfContent, u.OfURL) +func (r ComputerZoomConfigParam) MarshalJSON() (data []byte, err error) { + type shadow ComputerZoomConfigParam + return param.MarshalObject(r, (*shadow)(&r)) } -func (u *DocumentBlockParamSourceUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) +func (r *ComputerZoomConfigParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func (u *DocumentBlockParamSourceUnion) asAny() any { - if !param.IsOmitted(u.OfBase64) { - return u.OfBase64 - } else if !param.IsOmitted(u.OfText) { - return u.OfText - } else if !param.IsOmitted(u.OfContent) { - return u.OfContent - } else if !param.IsOmitted(u.OfURL) { - return u.OfURL - } - return nil +// Information about the container used in the request (for the code execution +// tool) +type Container struct { + // Identifier for the container used in this request + ID string `json:"id" api:"required"` + // The time at which the container will expire. + ExpiresAt time.Time `json:"expires_at" api:"required" format:"date-time"` + // Skills loaded in the container + Skills []ContainerSkill `json:"skills" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + ExpiresAt respjson.Field + Skills respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` } -// Returns a pointer to the underlying variant's property, if present. -func (u DocumentBlockParamSourceUnion) GetContent() *ContentBlockSourceContentUnionParam { - if vt := u.OfContent; vt != nil { - return &vt.Content - } - return nil +// Returns the unmodified JSON received from the API +func (r Container) RawJSON() string { return r.JSON.raw } +func (r *Container) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns a pointer to the underlying variant's property, if present. -func (u DocumentBlockParamSourceUnion) GetURL() *string { - if vt := u.OfURL; vt != nil { - return &vt.URL - } - return nil +// Container parameters with skills to be loaded. +type ContainerParams struct { + // Container id + ID param.Opt[string] `json:"id,omitzero"` + // List of skills to load in the container + Skills []SkillParams `json:"skills,omitzero"` + paramObj } -// Returns a pointer to the underlying variant's property, if present. -func (u DocumentBlockParamSourceUnion) GetData() *string { - if vt := u.OfBase64; vt != nil { - return (*string)(&vt.Data) - } else if vt := u.OfText; vt != nil { - return (*string)(&vt.Data) - } - return nil +func (r ContainerParams) MarshalJSON() (data []byte, err error) { + type shadow ContainerParams + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *ContainerParams) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns a pointer to the underlying variant's property, if present. -func (u DocumentBlockParamSourceUnion) GetMediaType() *string { - if vt := u.OfBase64; vt != nil { - return (*string)(&vt.MediaType) - } else if vt := u.OfText; vt != nil { - return (*string)(&vt.MediaType) - } - return nil +// A skill that was loaded in a container (response model). +type ContainerSkill struct { + // Skill ID + SkillID string `json:"skill_id" api:"required"` + // Type of skill - either 'anthropic' (built-in) or 'custom' (user-defined) + // + // Any of "anthropic", "custom". + Type ContainerSkillType `json:"type" api:"required"` + // The resolved version: a skill version ID for custom skills. + Version string `json:"version" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + SkillID respjson.Field + Type respjson.Field + Version respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` } -// Returns a pointer to the underlying variant's property, if present. -func (u DocumentBlockParamSourceUnion) GetType() *string { - if vt := u.OfBase64; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfText; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfContent; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfURL; vt != nil { - return (*string)(&vt.Type) - } - return nil +// Returns the unmodified JSON received from the API +func (r ContainerSkill) RawJSON() string { return r.JSON.raw } +func (r *ContainerSkill) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func init() { - apijson.RegisterUnion[DocumentBlockParamSourceUnion]( - "type", - apijson.Discriminator[Base64PDFSourceParam]("base64"), - apijson.Discriminator[PlainTextSourceParam]("text"), - apijson.Discriminator[ContentBlockSourceParam]("content"), - apijson.Discriminator[URLPDFSourceParam]("url"), - ) -} +// Type of skill - either 'anthropic' (built-in) or 'custom' (user-defined) +type ContainerSkillType string -// Code execution result with encrypted stdout for PFC + web_search results. -type EncryptedCodeExecutionResultBlock struct { - Content []CodeExecutionOutputBlock `json:"content" api:"required"` - EncryptedStdout string `json:"encrypted_stdout" api:"required"` - ReturnCode int64 `json:"return_code" api:"required"` - Stderr string `json:"stderr" api:"required"` - Type constant.EncryptedCodeExecutionResult `json:"type" default:"encrypted_code_execution_result"` +const ( + ContainerSkillTypeAnthropic ContainerSkillType = "anthropic" + ContainerSkillTypeCustom ContainerSkillType = "custom" +) + +// Response model for a file uploaded to the container. +type ContainerUploadBlock struct { + FileID string `json:"file_id" api:"required"` + Type constant.ContainerUpload `json:"type" default:"container_upload"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { - Content respjson.Field - EncryptedStdout respjson.Field - ReturnCode respjson.Field - Stderr respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string + FileID respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string } `json:"-"` } // Returns the unmodified JSON received from the API -func (r EncryptedCodeExecutionResultBlock) RawJSON() string { return r.JSON.raw } -func (r *EncryptedCodeExecutionResultBlock) UnmarshalJSON(data []byte) error { +func (r ContainerUploadBlock) RawJSON() string { return r.JSON.raw } +func (r *ContainerUploadBlock) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// Code execution result with encrypted stdout for PFC + web_search results. +// A content block that represents a file to be uploaded to the container Files +// uploaded via this block will be available in the container's input directory. // -// The properties Content, EncryptedStdout, ReturnCode, Stderr, Type are required. -type EncryptedCodeExecutionResultBlockParam struct { - Content []CodeExecutionOutputBlockParam `json:"content,omitzero" api:"required"` - EncryptedStdout string `json:"encrypted_stdout" api:"required"` - ReturnCode int64 `json:"return_code" api:"required"` - Stderr string `json:"stderr" api:"required"` - // This field can be elided, and will marshal its zero value as - // "encrypted_code_execution_result". - Type constant.EncryptedCodeExecutionResult `json:"type" default:"encrypted_code_execution_result"` - paramObj -} - -func (r EncryptedCodeExecutionResultBlockParam) MarshalJSON() (data []byte, err error) { - type shadow EncryptedCodeExecutionResultBlockParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *EncryptedCodeExecutionResultBlockParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The properties Source, Type are required. -type ImageBlockParam struct { - Source ImageBlockParamSourceUnion `json:"source,omitzero" api:"required"` +// The properties FileID, Type are required. +type ContainerUploadBlockParam struct { + FileID string `json:"file_id" api:"required"` // Create a cache control breakpoint at this content block. CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` - // This field can be elided, and will marshal its zero value as "image". - Type constant.Image `json:"type" default:"image"` + // This field can be elided, and will marshal its zero value as "container_upload". + Type constant.ContainerUpload `json:"type" default:"container_upload"` paramObj } -func (r ImageBlockParam) MarshalJSON() (data []byte, err error) { - type shadow ImageBlockParam +func (r ContainerUploadBlockParam) MarshalJSON() (data []byte, err error) { + type shadow ContainerUploadBlockParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *ImageBlockParam) UnmarshalJSON(data []byte) error { +func (r *ContainerUploadBlockParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// Only one field can be non-zero. +// ContentBlockUnion contains all possible properties and values from [TextBlock], +// [ThinkingBlock], [RedactedThinkingBlock], [ToolUseBlock], [ServerToolUseBlock], +// [WebSearchToolResultBlock], [WebFetchToolResultBlock], +// [CodeExecutionToolResultBlock], [BashCodeExecutionToolResultBlock], +// [TextEditorCodeExecutionToolResultBlock], [ToolSearchToolResultBlock], +// [ContainerUploadBlock]. // -// Use [param.IsOmitted] to confirm if a field is set. -type ImageBlockParamSourceUnion struct { - OfBase64 *Base64ImageSourceParam `json:",omitzero,inline"` - OfURL *URLImageSourceParam `json:",omitzero,inline"` - paramUnion +// Use the [ContentBlockUnion.AsAny] method to switch on the variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type ContentBlockUnion struct { + // This field is from variant [TextBlock]. + Citations []TextCitationUnion `json:"citations"` + // This field is from variant [TextBlock]. + Text string `json:"text"` + // Any of "text", "thinking", "redacted_thinking", "tool_use", "server_tool_use", + // "web_search_tool_result", "web_fetch_tool_result", "code_execution_tool_result", + // "bash_code_execution_tool_result", "text_editor_code_execution_tool_result", + // "tool_search_tool_result", "container_upload". + Type string `json:"type"` + // This field is from variant [ThinkingBlock]. + Signature string `json:"signature"` + // This field is from variant [ThinkingBlock]. + Thinking string `json:"thinking"` + // This field is from variant [RedactedThinkingBlock]. + Data string `json:"data"` + ID string `json:"id"` + // necessary custom code modification + Input json.RawMessage `json:"input"` + Name string `json:"name"` + // This field is from variant [ToolUseBlock]. + ToolsetName string `json:"toolset_name"` + // This field is from variant [WebSearchToolResultBlock]. + Content WebSearchToolResultBlockContentUnion `json:"content"` + // This field is from variant [WebSearchToolResultBlock]. + ToolUseID string `json:"tool_use_id"` + JSON struct { + Citations respjson.Field + Text respjson.Field + Type respjson.Field + Signature respjson.Field + Thinking respjson.Field + Data respjson.Field + ID respjson.Field + Caller respjson.Field + Input respjson.Field + Name respjson.Field + ToolsetName respjson.Field + Content respjson.Field + ToolUseID respjson.Field + FileID respjson.Field + raw string + } `json:"-"` } -func (u ImageBlockParamSourceUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfBase64, u.OfURL) -} -func (u *ImageBlockParamSourceUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) +// anyContentBlock is implemented by each variant of [ContentBlockUnion] to add +// type safety for the return type of [ContentBlockUnion.AsAny] +type anyContentBlock interface { + implContentBlockUnion() + toParamUnion() ContentBlockParamUnion } -func (u *ImageBlockParamSourceUnion) asAny() any { - if !param.IsOmitted(u.OfBase64) { - return u.OfBase64 - } else if !param.IsOmitted(u.OfURL) { - return u.OfURL +func (TextBlock) implContentBlockUnion() {} +func (ThinkingBlock) implContentBlockUnion() {} +func (RedactedThinkingBlock) implContentBlockUnion() {} +func (ToolUseBlock) implContentBlockUnion() {} +func (ServerToolUseBlock) implContentBlockUnion() {} +func (WebSearchToolResultBlock) implContentBlockUnion() {} +func (WebFetchToolResultBlock) implContentBlockUnion() {} +func (CodeExecutionToolResultBlock) implContentBlockUnion() {} +func (BashCodeExecutionToolResultBlock) implContentBlockUnion() {} +func (TextEditorCodeExecutionToolResultBlock) implContentBlockUnion() {} +func (ToolSearchToolResultBlock) implContentBlockUnion() {} +func (ContainerUploadBlock) implContentBlockUnion() {} + +// Use the following switch statement to find the correct variant +// +// switch variant := ContentBlockUnion.AsAny().(type) { +// case anthropic.TextBlock: +// case anthropic.ThinkingBlock: +// case anthropic.RedactedThinkingBlock: +// case anthropic.ToolUseBlock: +// case anthropic.ServerToolUseBlock: +// case anthropic.WebSearchToolResultBlock: +// case anthropic.WebFetchToolResultBlock: +// case anthropic.CodeExecutionToolResultBlock: +// case anthropic.BashCodeExecutionToolResultBlock: +// case anthropic.TextEditorCodeExecutionToolResultBlock: +// case anthropic.ToolSearchToolResultBlock: +// case anthropic.ContainerUploadBlock: +// default: +// fmt.Errorf("no variant present") +// } +func (u ContentBlockUnion) AsAny() anyContentBlock { + switch u.Type { + case "text": + return u.AsText() + case "thinking": + return u.AsThinking() + case "redacted_thinking": + return u.AsRedactedThinking() + case "tool_use": + return u.AsToolUse() + case "server_tool_use": + return u.AsServerToolUse() + case "web_search_tool_result": + return u.AsWebSearchToolResult() + case "web_fetch_tool_result": + return u.AsWebFetchToolResult() + case "code_execution_tool_result": + return u.AsCodeExecutionToolResult() + case "bash_code_execution_tool_result": + return u.AsBashCodeExecutionToolResult() + case "text_editor_code_execution_tool_result": + return u.AsTextEditorCodeExecutionToolResult() + case "tool_search_tool_result": + return u.AsToolSearchToolResult() + case "container_upload": + return u.AsContainerUpload() } return nil } -// Returns a pointer to the underlying variant's property, if present. -func (u ImageBlockParamSourceUnion) GetData() *string { - if vt := u.OfBase64; vt != nil { - return &vt.Data - } - return nil +func (u ContentBlockUnion) AsText() (v TextBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -// Returns a pointer to the underlying variant's property, if present. -func (u ImageBlockParamSourceUnion) GetMediaType() *string { - if vt := u.OfBase64; vt != nil { - return (*string)(&vt.MediaType) - } - return nil +func (u ContentBlockUnion) AsThinking() (v ThinkingBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -// Returns a pointer to the underlying variant's property, if present. -func (u ImageBlockParamSourceUnion) GetURL() *string { - if vt := u.OfURL; vt != nil { - return &vt.URL - } - return nil +func (u ContentBlockUnion) AsRedactedThinking() (v RedactedThinkingBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -// Returns a pointer to the underlying variant's property, if present. -func (u ImageBlockParamSourceUnion) GetType() *string { - if vt := u.OfBase64; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfURL; vt != nil { - return (*string)(&vt.Type) - } - return nil +func (u ContentBlockUnion) AsToolUse() (v ToolUseBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -func init() { - apijson.RegisterUnion[ImageBlockParamSourceUnion]( - "type", - apijson.Discriminator[Base64ImageSourceParam]("base64"), - apijson.Discriminator[URLImageSourceParam]("url"), - ) +func (u ContentBlockUnion) AsServerToolUse() (v ServerToolUseBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -type InputJSONDelta struct { - PartialJSON string `json:"partial_json" api:"required"` - Type constant.InputJSONDelta `json:"type" default:"input_json_delta"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - PartialJSON respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +func (u ContentBlockUnion) AsWebSearchToolResult() (v WebSearchToolResultBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -// Returns the unmodified JSON received from the API -func (r InputJSONDelta) RawJSON() string { return r.JSON.raw } -func (r *InputJSONDelta) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +func (u ContentBlockUnion) AsWebFetchToolResult() (v WebFetchToolResultBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -// The properties Schema, Type are required. -type JSONOutputFormatParam struct { - // The JSON schema of the format - Schema map[string]any `json:"schema,omitzero" api:"required"` - // This field can be elided, and will marshal its zero value as "json_schema". - Type constant.JSONSchema `json:"type" default:"json_schema"` - paramObj +func (u ContentBlockUnion) AsCodeExecutionToolResult() (v CodeExecutionToolResultBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -func (r JSONOutputFormatParam) MarshalJSON() (data []byte, err error) { - type shadow JSONOutputFormatParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *JSONOutputFormatParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +func (u ContentBlockUnion) AsBashCodeExecutionToolResult() (v BashCodeExecutionToolResultBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -// The properties Name, Type are required. -type MemoryTool20250818Param struct { - // If true, tool will not be included in initial system prompt. Only loaded when - // returned via tool_reference from tool search. - DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` - // When true, guarantees schema validation on tool names and inputs - Strict param.Opt[bool] `json:"strict,omitzero"` - // Any of "direct", "code_execution_20250825", "code_execution_20260120". - AllowedCallers []string `json:"allowed_callers,omitzero"` - // Create a cache control breakpoint at this content block. - CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` - InputExamples []map[string]any `json:"input_examples,omitzero"` - // Name of the tool. - // - // This is how the tool will be called by the model and in `tool_use` blocks. - // - // This field can be elided, and will marshal its zero value as "memory". - Name constant.Memory `json:"name" default:"memory"` - // This field can be elided, and will marshal its zero value as "memory_20250818". - Type constant.Memory20250818 `json:"type" default:"memory_20250818"` - paramObj +func (u ContentBlockUnion) AsTextEditorCodeExecutionToolResult() (v TextEditorCodeExecutionToolResultBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -func (r MemoryTool20250818Param) MarshalJSON() (data []byte, err error) { - type shadow MemoryTool20250818Param - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *MemoryTool20250818Param) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +func (u ContentBlockUnion) AsToolSearchToolResult() (v ToolSearchToolResultBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -type Message struct { - // Unique object identifier. - // - // The format and length of IDs may change over time. - ID string `json:"id" api:"required"` - // Information about the container used in the request (for the code execution - // tool) - Container Container `json:"container" api:"required"` - // Content generated by the model. - // - // This is an array of content blocks, each of which has a `type` that determines - // its shape. - // - // Example: - // - // ```json - // [{ "type": "text", "text": "Hi, I'm Claude." }] - // ``` - // - // If the request input `messages` ended with an `assistant` turn, then the - // response `content` will continue directly from that last turn. You can use this - // to constrain the model's output. - // - // For example, if the input `messages` were: - // - // ```json - // [ - // - // { - // "role": "user", - // "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun" - // }, - // { "role": "assistant", "content": "The best answer is (" } - // - // ] - // ``` - // - // Then the response `content` might be: - // - // ```json - // [{ "type": "text", "text": "B)" }] - // ``` - Content []ContentBlockUnion `json:"content" api:"required"` - // The model that will complete your prompt.\n\nSee - // [models](https://docs.anthropic.com/en/docs/models-overview) for additional - // details and options. - Model Model `json:"model" api:"required"` - // Conversational role of the generated message. - // - // This will always be `"assistant"`. - Role constant.Assistant `json:"role" default:"assistant"` - // Structured information about a refusal. - StopDetails RefusalStopDetails `json:"stop_details" api:"required"` - // The reason that we stopped. - // - // This may be one the following values: - // - // - `"end_turn"`: the model reached a natural stopping point - // - `"max_tokens"`: we exceeded the requested `max_tokens` or the model's maximum - // - `"stop_sequence"`: one of your provided custom `stop_sequences` was generated - // - `"tool_use"`: the model invoked one or more tools - // - `"pause_turn"`: we paused a long-running turn. You may provide the response - // back as-is in a subsequent request to let the model continue. - // - `"refusal"`: when streaming classifiers intervene to handle potential policy - // violations - // - // In non-streaming mode this value is always non-null. In streaming mode, it is - // null in the `message_start` event and non-null otherwise. - // - // Any of "end_turn", "max_tokens", "stop_sequence", "tool_use", "pause_turn", - // "refusal". - StopReason StopReason `json:"stop_reason" api:"required"` - // Which custom stop sequence was generated, if any. - // - // This value will be a non-null string if one of your custom stop sequences was - // generated. - StopSequence string `json:"stop_sequence" api:"required"` - // Object type. - // - // For Messages, this is always `"message"`. - Type constant.Message `json:"type" default:"message"` - // Billing and rate-limit usage. - // - // Anthropic's API bills and rate-limits by token counts, as tokens represent the - // underlying cost to our systems. - // - // Under the hood, the API transforms requests into a format suitable for the - // model. The model's output then goes through a parsing stage before becoming an - // API response. As a result, the token counts in `usage` will not match one-to-one - // with the exact visible content of an API request or response. - // - // For example, `output_tokens` will be non-zero, even for an empty string response - // from Claude. - // - // Total input tokens in a request is the summation of `input_tokens`, - // `cache_creation_input_tokens`, and `cache_read_input_tokens`. - Usage Usage `json:"usage" api:"required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ID respjson.Field - Container respjson.Field - Content respjson.Field - Model respjson.Field - Role respjson.Field - StopDetails respjson.Field - StopReason respjson.Field - StopSequence respjson.Field - Type respjson.Field - Usage respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +func (u ContentBlockUnion) AsContainerUpload() (v ContainerUploadBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } // Returns the unmodified JSON received from the API -func (r Message) RawJSON() string { return r.JSON.raw } -func (r *Message) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - +func (u ContentBlockUnion) RawJSON() string { return u.JSON.raw } -func MessageCountTokensToolParamOfTool(inputSchema ToolInputSchemaParam, name string) MessageCountTokensToolUnionParam { - var variant ToolParam - variant.InputSchema = inputSchema - variant.Name = name - return MessageCountTokensToolUnionParam{OfTool: &variant} +func (r *ContentBlockUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func MessageCountTokensToolParamOfToolSearchToolBm25_20251119(type_ ToolSearchToolBm25_20251119Type) MessageCountTokensToolUnionParam { - var variant ToolSearchToolBm25_20251119Param - variant.Type = type_ - return MessageCountTokensToolUnionParam{OfToolSearchToolBm25_20251119: &variant} +// ContentBlockUnionCaller is an implicit subunion of [ContentBlockUnion]. +// ContentBlockUnionCaller provides convenient access to the sub-properties of the +// union. +// +// For type safety it is recommended to directly use a variant of the +// [ContentBlockUnion]. +type ContentBlockUnionCaller struct { + Type string `json:"type"` + ToolID string `json:"tool_id"` + JSON struct { + Type respjson.Field + ToolID respjson.Field + raw string + } `json:"-"` } -func MessageCountTokensToolParamOfToolSearchToolRegex20251119(type_ ToolSearchToolRegex20251119Type) MessageCountTokensToolUnionParam { - var variant ToolSearchToolRegex20251119Param - variant.Type = type_ - return MessageCountTokensToolUnionParam{OfToolSearchToolRegex20251119: &variant} +func (r *ContentBlockUnionCaller) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Only one field can be non-zero. +// ContentBlockUnionContent is an implicit subunion of [ContentBlockUnion]. +// ContentBlockUnionContent provides convenient access to the sub-properties of the +// union. // -// Use [param.IsOmitted] to confirm if a field is set. -type MessageCountTokensToolUnionParam struct { - OfTool *ToolParam `json:",omitzero,inline"` - OfBashTool20250124 *ToolBash20250124Param `json:",omitzero,inline"` - OfCodeExecutionTool20250522 *CodeExecutionTool20250522Param `json:",omitzero,inline"` - OfCodeExecutionTool20250825 *CodeExecutionTool20250825Param `json:",omitzero,inline"` - OfCodeExecutionTool20260120 *CodeExecutionTool20260120Param `json:",omitzero,inline"` - OfMemoryTool20250818 *MemoryTool20250818Param `json:",omitzero,inline"` - OfTextEditor20250124 *ToolTextEditor20250124Param `json:",omitzero,inline"` - OfTextEditor20250429 *ToolTextEditor20250429Param `json:",omitzero,inline"` - OfTextEditor20250728 *ToolTextEditor20250728Param `json:",omitzero,inline"` - OfWebSearchTool20250305 *WebSearchTool20250305Param `json:",omitzero,inline"` - OfWebFetchTool20250910 *WebFetchTool20250910Param `json:",omitzero,inline"` - OfWebSearchTool20260209 *WebSearchTool20260209Param `json:",omitzero,inline"` - OfWebFetchTool20260209 *WebFetchTool20260209Param `json:",omitzero,inline"` - OfWebFetchTool20260309 *WebFetchTool20260309Param `json:",omitzero,inline"` - OfToolSearchToolBm25_20251119 *ToolSearchToolBm25_20251119Param `json:",omitzero,inline"` - OfToolSearchToolRegex20251119 *ToolSearchToolRegex20251119Param `json:",omitzero,inline"` - paramUnion -} - -func (u MessageCountTokensToolUnionParam) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfTool, +// For type safety it is recommended to directly use a variant of the +// [ContentBlockUnion]. +// +// If the underlying value is not a json object, one of the following properties +// will be valid: OfWebSearchResultBlockArray] +type ContentBlockUnionContent struct { + // This field will be present if the value is a [[]WebSearchResultBlock] instead of + // an object. + OfWebSearchResultBlockArray []WebSearchResultBlock `json:",inline"` + ErrorCode string `json:"error_code"` + Type string `json:"type"` + // This field is a union of [DocumentBlock], [[]CodeExecutionOutputBlock], + // [[]CodeExecutionOutputBlock], [[]BashCodeExecutionOutputBlock], [string] + Content ContentBlockUnionContentContent `json:"content"` + // This field is from variant [WebFetchToolResultBlockContentUnion]. + RetrievedAt string `json:"retrieved_at"` + // This field is from variant [WebFetchToolResultBlockContentUnion]. + URL string `json:"url"` + ReturnCode int64 `json:"return_code"` + Stderr string `json:"stderr"` + Stdout string `json:"stdout"` + // This field is from variant [CodeExecutionToolResultBlockContentUnion]. + EncryptedStdout string `json:"encrypted_stdout"` + ErrorMessage string `json:"error_message"` + // This field is from variant [TextEditorCodeExecutionToolResultBlockContentUnion]. + FileType TextEditorCodeExecutionViewResultBlockFileType `json:"file_type"` + // This field is from variant [TextEditorCodeExecutionToolResultBlockContentUnion]. + NumLines int64 `json:"num_lines"` + // This field is from variant [TextEditorCodeExecutionToolResultBlockContentUnion]. + StartLine int64 `json:"start_line"` + // This field is from variant [TextEditorCodeExecutionToolResultBlockContentUnion]. + TotalLines int64 `json:"total_lines"` + // This field is from variant [TextEditorCodeExecutionToolResultBlockContentUnion]. + IsFileUpdate bool `json:"is_file_update"` + // This field is from variant [TextEditorCodeExecutionToolResultBlockContentUnion]. + Lines []string `json:"lines"` + // This field is from variant [TextEditorCodeExecutionToolResultBlockContentUnion]. + NewLines int64 `json:"new_lines"` + // This field is from variant [TextEditorCodeExecutionToolResultBlockContentUnion]. + NewStart int64 `json:"new_start"` + // This field is from variant [TextEditorCodeExecutionToolResultBlockContentUnion]. + OldLines int64 `json:"old_lines"` + // This field is from variant [TextEditorCodeExecutionToolResultBlockContentUnion]. + OldStart int64 `json:"old_start"` + // This field is from variant [ToolSearchToolResultBlockContentUnion]. + ToolReferences []ToolReferenceBlock `json:"tool_references"` + JSON struct { + OfWebSearchResultBlockArray respjson.Field + ErrorCode respjson.Field + Type respjson.Field + Content respjson.Field + RetrievedAt respjson.Field + URL respjson.Field + ReturnCode respjson.Field + Stderr respjson.Field + Stdout respjson.Field + EncryptedStdout respjson.Field + ErrorMessage respjson.Field + FileType respjson.Field + NumLines respjson.Field + StartLine respjson.Field + TotalLines respjson.Field + IsFileUpdate respjson.Field + Lines respjson.Field + NewLines respjson.Field + NewStart respjson.Field + OldLines respjson.Field + OldStart respjson.Field + ToolReferences respjson.Field + raw string + } `json:"-"` +} + +func (r *ContentBlockUnionContent) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// ContentBlockUnionContentContent is an implicit subunion of [ContentBlockUnion]. +// ContentBlockUnionContentContent provides convenient access to the sub-properties +// of the union. +// +// For type safety it is recommended to directly use a variant of the +// [ContentBlockUnion]. +// +// If the underlying value is not a json object, one of the following properties +// will be valid: OfContent OfString] +type ContentBlockUnionContentContent struct { + // This field will be present if the value is a [[]CodeExecutionOutputBlock] + // instead of an object. + OfContent []CodeExecutionOutputBlock `json:",inline"` + // This field will be present if the value is a [string] instead of an object. + OfString string `json:",inline"` + // This field is from variant [DocumentBlock]. + Citations CitationsConfig `json:"citations"` + // This field is from variant [DocumentBlock]. + Source DocumentBlockSourceUnion `json:"source"` + // This field is from variant [DocumentBlock]. + Title string `json:"title"` + // This field is from variant [DocumentBlock]. + Type constant.Document `json:"type"` + JSON struct { + OfContent respjson.Field + OfString respjson.Field + Citations respjson.Field + Source respjson.Field + Title respjson.Field + Type respjson.Field + raw string + } `json:"-"` +} + +func (r *ContentBlockUnionContentContent) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +func NewTextBlock(text string) ContentBlockParamUnion { + var variant TextBlockParam + variant.Text = text + return ContentBlockParamUnion{OfText: &variant} +} + +func NewImageBlock[ + T Base64ImageSourceParam | URLImageSourceParam | FileImageSourceParam, +](source T) ContentBlockParamUnion { + var image ImageBlockParam + switch v := any(source).(type) { + case Base64ImageSourceParam: + image.Source.OfBase64 = &v + case URLImageSourceParam: + image.Source.OfURL = &v + case FileImageSourceParam: + image.Source.OfFile = &v + } + return ContentBlockParamUnion{OfImage: &image} +} + +func NewImageBlockBase64(mediaType string, encodedData string) ContentBlockParamUnion { + return ContentBlockParamUnion{ + OfImage: &ImageBlockParam{ + Source: ImageBlockParamSourceUnion{ + OfBase64: &Base64ImageSourceParam{ + Data: encodedData, + MediaType: Base64ImageSourceMediaType(mediaType), + }, + }, + }, + } +} + +func NewDocumentBlock[ + T Base64PDFSourceParam | PlainTextSourceParam | ContentBlockSourceParam | URLPDFSourceParam | FileDocumentSourceParam, +](source T) ContentBlockParamUnion { + var document DocumentBlockParam + switch v := any(source).(type) { + case Base64PDFSourceParam: + document.Source.OfBase64 = &v + case PlainTextSourceParam: + document.Source.OfText = &v + case ContentBlockSourceParam: + document.Source.OfContent = &v + case URLPDFSourceParam: + document.Source.OfURL = &v + case FileDocumentSourceParam: + document.Source.OfFile = &v + } + return ContentBlockParamUnion{OfDocument: &document} +} + +func NewSearchResultBlock(content []TextBlockParam, source string, title string) ContentBlockParamUnion { + var searchResult SearchResultBlockParam + searchResult.Content = content + searchResult.Source = source + searchResult.Title = title + return ContentBlockParamUnion{OfSearchResult: &searchResult} +} + +func NewThinkingBlock(signature string, thinking string) ContentBlockParamUnion { + var variant ThinkingBlockParam + variant.Signature = signature + variant.Thinking = thinking + return ContentBlockParamUnion{OfThinking: &variant} +} + +func NewRedactedThinkingBlock(data string) ContentBlockParamUnion { + var redactedThinking RedactedThinkingBlockParam + redactedThinking.Data = data + return ContentBlockParamUnion{OfRedactedThinking: &redactedThinking} +} + +func NewToolUseBlock(id string, input any, name string) ContentBlockParamUnion { + var toolUse ToolUseBlockParam + toolUse.ID = id + toolUse.Input = input + toolUse.Name = name + return ContentBlockParamUnion{OfToolUse: &toolUse} +} + +func NewToolResultBlock(toolUseID string, content string, isError bool) ContentBlockParamUnion { + toolBlock := ToolResultBlockParam{ + ToolUseID: toolUseID, + Content: []ToolResultBlockParamContentUnion{ + {OfText: &TextBlockParam{Text: content}}, + }, + IsError: Bool(isError), + } + return ContentBlockParamUnion{OfToolResult: &toolBlock} +} + +func NewServerToolUseBlock(id string, input any, name ServerToolUseBlockParamName) ContentBlockParamUnion { + var serverToolUse ServerToolUseBlockParam + serverToolUse.ID = id + serverToolUse.Input = input + serverToolUse.Name = name + return ContentBlockParamUnion{OfServerToolUse: &serverToolUse} +} + +func NewWebSearchToolResultBlock[ + T []WebSearchResultBlockParam | WebSearchToolRequestErrorParam, +](content T, toolUseID string) ContentBlockParamUnion { + var webSearchToolResult WebSearchToolResultBlockParam + switch v := any(content).(type) { + case []WebSearchResultBlockParam: + webSearchToolResult.Content.OfWebSearchToolResultBlockItem = v + case WebSearchToolRequestErrorParam: + webSearchToolResult.Content.OfRequestWebSearchToolResultError = &v + } + webSearchToolResult.ToolUseID = toolUseID + return ContentBlockParamUnion{OfWebSearchToolResult: &webSearchToolResult} +} + +func NewWebFetchToolResultBlock[ + T WebFetchToolResultErrorBlockParam | WebFetchBlockParam, +](content T, toolUseID string) ContentBlockParamUnion { + var webFetchToolResult WebFetchToolResultBlockParam + switch v := any(content).(type) { + case WebFetchToolResultErrorBlockParam: + webFetchToolResult.Content.OfRequestWebFetchToolResultError = &v + case WebFetchBlockParam: + webFetchToolResult.Content.OfRequestWebFetchResultBlock = &v + } + webFetchToolResult.ToolUseID = toolUseID + return ContentBlockParamUnion{OfWebFetchToolResult: &webFetchToolResult} +} + +func NewCodeExecutionToolResultBlock[ + T CodeExecutionToolResultErrorParam | CodeExecutionResultBlockParam | EncryptedCodeExecutionResultBlockParam, +](content T, toolUseID string) ContentBlockParamUnion { + var codeExecutionToolResult CodeExecutionToolResultBlockParam + switch v := any(content).(type) { + case CodeExecutionToolResultErrorParam: + codeExecutionToolResult.Content.OfRequestCodeExecutionToolResultError = &v + case CodeExecutionResultBlockParam: + codeExecutionToolResult.Content.OfRequestCodeExecutionResultBlock = &v + case EncryptedCodeExecutionResultBlockParam: + codeExecutionToolResult.Content.OfRequestEncryptedCodeExecutionResultBlock = &v + } + codeExecutionToolResult.ToolUseID = toolUseID + return ContentBlockParamUnion{OfCodeExecutionToolResult: &codeExecutionToolResult} +} + +func NewBashCodeExecutionToolResultBlock[ + T BashCodeExecutionToolResultErrorParam | BashCodeExecutionResultBlockParam, +](content T, toolUseID string) ContentBlockParamUnion { + var bashCodeExecutionToolResult BashCodeExecutionToolResultBlockParam + switch v := any(content).(type) { + case BashCodeExecutionToolResultErrorParam: + bashCodeExecutionToolResult.Content.OfRequestBashCodeExecutionToolResultError = &v + case BashCodeExecutionResultBlockParam: + bashCodeExecutionToolResult.Content.OfRequestBashCodeExecutionResultBlock = &v + } + bashCodeExecutionToolResult.ToolUseID = toolUseID + return ContentBlockParamUnion{OfBashCodeExecutionToolResult: &bashCodeExecutionToolResult} +} + +func NewTextEditorCodeExecutionToolResultBlock[ + T TextEditorCodeExecutionToolResultErrorParam | TextEditorCodeExecutionViewResultBlockParam | TextEditorCodeExecutionCreateResultBlockParam | TextEditorCodeExecutionStrReplaceResultBlockParam, +](content T, toolUseID string) ContentBlockParamUnion { + var textEditorCodeExecutionToolResult TextEditorCodeExecutionToolResultBlockParam + switch v := any(content).(type) { + case TextEditorCodeExecutionToolResultErrorParam: + textEditorCodeExecutionToolResult.Content.OfRequestTextEditorCodeExecutionToolResultError = &v + case TextEditorCodeExecutionViewResultBlockParam: + textEditorCodeExecutionToolResult.Content.OfRequestTextEditorCodeExecutionViewResultBlock = &v + case TextEditorCodeExecutionCreateResultBlockParam: + textEditorCodeExecutionToolResult.Content.OfRequestTextEditorCodeExecutionCreateResultBlock = &v + case TextEditorCodeExecutionStrReplaceResultBlockParam: + textEditorCodeExecutionToolResult.Content.OfRequestTextEditorCodeExecutionStrReplaceResultBlock = &v + } + textEditorCodeExecutionToolResult.ToolUseID = toolUseID + return ContentBlockParamUnion{OfTextEditorCodeExecutionToolResult: &textEditorCodeExecutionToolResult} +} + +func NewToolSearchToolResultBlock[ + T ToolSearchToolResultErrorParam | ToolSearchToolSearchResultBlockParam, +](content T, toolUseID string) ContentBlockParamUnion { + var toolSearchToolResult ToolSearchToolResultBlockParam + switch v := any(content).(type) { + case ToolSearchToolResultErrorParam: + toolSearchToolResult.Content.OfRequestToolSearchToolResultError = &v + case ToolSearchToolSearchResultBlockParam: + toolSearchToolResult.Content.OfRequestToolSearchToolSearchResultBlock = &v + } + toolSearchToolResult.ToolUseID = toolUseID + return ContentBlockParamUnion{OfToolSearchToolResult: &toolSearchToolResult} +} + +func NewContainerUploadBlock(fileID string) ContentBlockParamUnion { + var containerUpload ContainerUploadBlockParam + containerUpload.FileID = fileID + return ContentBlockParamUnion{OfContainerUpload: &containerUpload} +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type ContentBlockParamUnion struct { + OfText *TextBlockParam `json:",omitzero,inline"` + OfImage *ImageBlockParam `json:",omitzero,inline"` + OfDocument *DocumentBlockParam `json:",omitzero,inline"` + OfSearchResult *SearchResultBlockParam `json:",omitzero,inline"` + OfThinking *ThinkingBlockParam `json:",omitzero,inline"` + OfRedactedThinking *RedactedThinkingBlockParam `json:",omitzero,inline"` + OfToolUse *ToolUseBlockParam `json:",omitzero,inline"` + OfToolResult *ToolResultBlockParam `json:",omitzero,inline"` + OfServerToolUse *ServerToolUseBlockParam `json:",omitzero,inline"` + OfWebSearchToolResult *WebSearchToolResultBlockParam `json:",omitzero,inline"` + OfWebFetchToolResult *WebFetchToolResultBlockParam `json:",omitzero,inline"` + OfCodeExecutionToolResult *CodeExecutionToolResultBlockParam `json:",omitzero,inline"` + OfBashCodeExecutionToolResult *BashCodeExecutionToolResultBlockParam `json:",omitzero,inline"` + OfTextEditorCodeExecutionToolResult *TextEditorCodeExecutionToolResultBlockParam `json:",omitzero,inline"` + OfToolSearchToolResult *ToolSearchToolResultBlockParam `json:",omitzero,inline"` + OfContainerUpload *ContainerUploadBlockParam `json:",omitzero,inline"` + paramUnion +} + +func (u ContentBlockParamUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfText, + u.OfImage, + u.OfDocument, + u.OfSearchResult, + u.OfThinking, + u.OfRedactedThinking, + u.OfToolUse, + u.OfToolResult, + u.OfServerToolUse, + u.OfWebSearchToolResult, + u.OfWebFetchToolResult, + u.OfCodeExecutionToolResult, + u.OfBashCodeExecutionToolResult, + u.OfTextEditorCodeExecutionToolResult, + u.OfToolSearchToolResult, + u.OfContainerUpload) +} +func (u *ContentBlockParamUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *ContentBlockParamUnion) asAny() any { + if !param.IsOmitted(u.OfText) { + return u.OfText + } else if !param.IsOmitted(u.OfImage) { + return u.OfImage + } else if !param.IsOmitted(u.OfDocument) { + return u.OfDocument + } else if !param.IsOmitted(u.OfSearchResult) { + return u.OfSearchResult + } else if !param.IsOmitted(u.OfThinking) { + return u.OfThinking + } else if !param.IsOmitted(u.OfRedactedThinking) { + return u.OfRedactedThinking + } else if !param.IsOmitted(u.OfToolUse) { + return u.OfToolUse + } else if !param.IsOmitted(u.OfToolResult) { + return u.OfToolResult + } else if !param.IsOmitted(u.OfServerToolUse) { + return u.OfServerToolUse + } else if !param.IsOmitted(u.OfWebSearchToolResult) { + return u.OfWebSearchToolResult + } else if !param.IsOmitted(u.OfWebFetchToolResult) { + return u.OfWebFetchToolResult + } else if !param.IsOmitted(u.OfCodeExecutionToolResult) { + return u.OfCodeExecutionToolResult + } else if !param.IsOmitted(u.OfBashCodeExecutionToolResult) { + return u.OfBashCodeExecutionToolResult + } else if !param.IsOmitted(u.OfTextEditorCodeExecutionToolResult) { + return u.OfTextEditorCodeExecutionToolResult + } else if !param.IsOmitted(u.OfToolSearchToolResult) { + return u.OfToolSearchToolResult + } else if !param.IsOmitted(u.OfContainerUpload) { + return u.OfContainerUpload + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u ContentBlockParamUnion) GetText() *string { + if vt := u.OfText; vt != nil { + return &vt.Text + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u ContentBlockParamUnion) GetTransformations() *ImageTransformationsParam { + if vt := u.OfImage; vt != nil { + return &vt.Transformations + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u ContentBlockParamUnion) GetContext() *string { + if vt := u.OfDocument; vt != nil && vt.Context.Valid() { + return &vt.Context.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u ContentBlockParamUnion) GetSignature() *string { + if vt := u.OfThinking; vt != nil { + return &vt.Signature + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u ContentBlockParamUnion) GetThinking() *string { + if vt := u.OfThinking; vt != nil { + return &vt.Thinking + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u ContentBlockParamUnion) GetData() *string { + if vt := u.OfRedactedThinking; vt != nil { + return &vt.Data + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u ContentBlockParamUnion) GetIsError() *bool { + if vt := u.OfToolResult; vt != nil && vt.IsError.Valid() { + return &vt.IsError.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u ContentBlockParamUnion) GetFileID() *string { + if vt := u.OfContainerUpload; vt != nil { + return &vt.FileID + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u ContentBlockParamUnion) GetType() *string { + if vt := u.OfText; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfImage; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfDocument; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfSearchResult; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfThinking; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfRedactedThinking; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfToolUse; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfToolResult; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfServerToolUse; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfWebSearchToolResult; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfWebFetchToolResult; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfCodeExecutionToolResult; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfBashCodeExecutionToolResult; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfTextEditorCodeExecutionToolResult; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfToolSearchToolResult; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfContainerUpload; vt != nil { + return (*string)(&vt.Type) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u ContentBlockParamUnion) GetTitle() *string { + if vt := u.OfDocument; vt != nil && vt.Title.Valid() { + return &vt.Title.Value + } else if vt := u.OfSearchResult; vt != nil { + return (*string)(&vt.Title) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u ContentBlockParamUnion) GetID() *string { + if vt := u.OfToolUse; vt != nil { + return (*string)(&vt.ID) + } else if vt := u.OfServerToolUse; vt != nil { + return (*string)(&vt.ID) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u ContentBlockParamUnion) GetName() *string { + if vt := u.OfToolUse; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfServerToolUse; vt != nil { + return (*string)(&vt.Name) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u ContentBlockParamUnion) GetToolsetName() *string { + if vt := u.OfToolUse; vt != nil && vt.ToolsetName.Valid() { + return &vt.ToolsetName.Value + } else if vt := u.OfToolResult; vt != nil && vt.ToolsetName.Valid() { + return &vt.ToolsetName.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u ContentBlockParamUnion) GetToolUseID() *string { + if vt := u.OfToolResult; vt != nil { + return (*string)(&vt.ToolUseID) + } else if vt := u.OfWebSearchToolResult; vt != nil { + return (*string)(&vt.ToolUseID) + } else if vt := u.OfWebFetchToolResult; vt != nil { + return (*string)(&vt.ToolUseID) + } else if vt := u.OfCodeExecutionToolResult; vt != nil { + return (*string)(&vt.ToolUseID) + } else if vt := u.OfBashCodeExecutionToolResult; vt != nil { + return (*string)(&vt.ToolUseID) + } else if vt := u.OfTextEditorCodeExecutionToolResult; vt != nil { + return (*string)(&vt.ToolUseID) + } else if vt := u.OfToolSearchToolResult; vt != nil { + return (*string)(&vt.ToolUseID) + } + return nil +} + +// Returns a pointer to the underlying variant's CacheControl property, if present. +func (u ContentBlockParamUnion) GetCacheControl() *CacheControlEphemeralParam { + if vt := u.OfText; vt != nil { + return &vt.CacheControl + } else if vt := u.OfImage; vt != nil { + return &vt.CacheControl + } else if vt := u.OfDocument; vt != nil { + return &vt.CacheControl + } else if vt := u.OfSearchResult; vt != nil { + return &vt.CacheControl + } else if vt := u.OfToolUse; vt != nil { + return &vt.CacheControl + } else if vt := u.OfToolResult; vt != nil { + return &vt.CacheControl + } else if vt := u.OfServerToolUse; vt != nil { + return &vt.CacheControl + } else if vt := u.OfWebSearchToolResult; vt != nil { + return &vt.CacheControl + } else if vt := u.OfWebFetchToolResult; vt != nil { + return &vt.CacheControl + } else if vt := u.OfCodeExecutionToolResult; vt != nil { + return &vt.CacheControl + } else if vt := u.OfBashCodeExecutionToolResult; vt != nil { + return &vt.CacheControl + } else if vt := u.OfTextEditorCodeExecutionToolResult; vt != nil { + return &vt.CacheControl + } else if vt := u.OfToolSearchToolResult; vt != nil { + return &vt.CacheControl + } else if vt := u.OfContainerUpload; vt != nil { + return &vt.CacheControl + } + return nil +} + +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u ContentBlockParamUnion) GetCitations() (res contentBlockParamUnionCitations) { + if vt := u.OfText; vt != nil { + res.any = &vt.Citations + } else if vt := u.OfDocument; vt != nil { + res.any = &vt.Citations + } else if vt := u.OfSearchResult; vt != nil { + res.any = &vt.Citations + } + return +} + +// Can have the runtime types [*[]TextCitationParamUnion], [*CitationsConfigParam] +type contentBlockParamUnionCitations struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *[]anthropic.TextCitationParamUnion: +// case *anthropic.CitationsConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u contentBlockParamUnionCitations) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u contentBlockParamUnionCitations) GetEnabled() *bool { + switch vt := u.any.(type) { + case *CitationsConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + } + return nil +} + +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u ContentBlockParamUnion) GetSource() (res contentBlockParamUnionSource) { + if vt := u.OfImage; vt != nil { + res.any = vt.Source.asAny() + } else if vt := u.OfDocument; vt != nil { + res.any = vt.Source.asAny() + } else if vt := u.OfSearchResult; vt != nil { + res.any = &vt.Source + } + return +} + +// Can have the runtime types [*Base64ImageSourceParam], [*URLImageSourceParam], +// [*FileImageSourceParam], [*Base64PDFSourceParam], [*PlainTextSourceParam], +// [*ContentBlockSourceParam], [*URLPDFSourceParam], [*FileDocumentSourceParam], +// [*string] +type contentBlockParamUnionSource struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.Base64ImageSourceParam: +// case *anthropic.URLImageSourceParam: +// case *anthropic.FileImageSourceParam: +// case *anthropic.Base64PDFSourceParam: +// case *anthropic.PlainTextSourceParam: +// case *anthropic.ContentBlockSourceParam: +// case *anthropic.URLPDFSourceParam: +// case *anthropic.FileDocumentSourceParam: +// case *string: +// default: +// fmt.Errorf("not present") +// } +func (u contentBlockParamUnionSource) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u contentBlockParamUnionSource) GetContent() *ContentBlockSourceContentUnionParam { + switch vt := u.any.(type) { + case *DocumentBlockParamSourceUnion: + return vt.GetContent() + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u contentBlockParamUnionSource) GetData() *string { + switch vt := u.any.(type) { + case *ImageBlockParamSourceUnion: + return vt.GetData() + case *DocumentBlockParamSourceUnion: + return vt.GetData() + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u contentBlockParamUnionSource) GetMediaType() *string { + switch vt := u.any.(type) { + case *ImageBlockParamSourceUnion: + return vt.GetMediaType() + case *DocumentBlockParamSourceUnion: + return vt.GetMediaType() + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u contentBlockParamUnionSource) GetType() *string { + switch vt := u.any.(type) { + case *ImageBlockParamSourceUnion: + return vt.GetType() + case *DocumentBlockParamSourceUnion: + return vt.GetType() + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u contentBlockParamUnionSource) GetURL() *string { + switch vt := u.any.(type) { + case *ImageBlockParamSourceUnion: + return vt.GetURL() + case *DocumentBlockParamSourceUnion: + return vt.GetURL() + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u contentBlockParamUnionSource) GetFileID() *string { + switch vt := u.any.(type) { + case *ImageBlockParamSourceUnion: + return vt.GetFileID() + case *DocumentBlockParamSourceUnion: + return vt.GetFileID() + } + return nil +} + +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u ContentBlockParamUnion) GetContent() (res contentBlockParamUnionContent) { + if vt := u.OfSearchResult; vt != nil { + res.any = &vt.Content + } else if vt := u.OfToolResult; vt != nil { + res.any = &vt.Content + } else if vt := u.OfWebSearchToolResult; vt != nil { + res.any = vt.Content.asAny() + } else if vt := u.OfWebFetchToolResult; vt != nil { + res.any = vt.Content.asAny() + } else if vt := u.OfCodeExecutionToolResult; vt != nil { + res.any = vt.Content.asAny() + } else if vt := u.OfBashCodeExecutionToolResult; vt != nil { + res.any = vt.Content.asAny() + } else if vt := u.OfTextEditorCodeExecutionToolResult; vt != nil { + res.any = vt.Content.asAny() + } else if vt := u.OfToolSearchToolResult; vt != nil { + res.any = vt.Content.asAny() + } + return +} + +// Can have the runtime types [_[]TextBlockParam], +// [_[]ToolResultBlockParamContentUnion], [*[]WebSearchResultBlockParam], +// [*WebFetchToolResultErrorBlockParam], [*WebFetchBlockParam], +// [*CodeExecutionToolResultErrorParam], [*CodeExecutionResultBlockParam], +// [*EncryptedCodeExecutionResultBlockParam], +// [*BashCodeExecutionToolResultErrorParam], [*BashCodeExecutionResultBlockParam], +// [*TextEditorCodeExecutionToolResultErrorParam], +// [*TextEditorCodeExecutionViewResultBlockParam], +// [*TextEditorCodeExecutionCreateResultBlockParam], +// [*TextEditorCodeExecutionStrReplaceResultBlockParam], +// [*ToolSearchToolResultErrorParam], [*ToolSearchToolSearchResultBlockParam] +type contentBlockParamUnionContent struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *[]anthropic.TextBlockParam: +// case *[]anthropic.ToolResultBlockParamContentUnion: +// case *[]anthropic.WebSearchResultBlockParam: +// case *anthropic.WebFetchToolResultErrorBlockParam: +// case *anthropic.WebFetchBlockParam: +// case *anthropic.CodeExecutionToolResultErrorParam: +// case *anthropic.CodeExecutionResultBlockParam: +// case *anthropic.EncryptedCodeExecutionResultBlockParam: +// case *anthropic.BashCodeExecutionToolResultErrorParam: +// case *anthropic.BashCodeExecutionResultBlockParam: +// case *anthropic.TextEditorCodeExecutionToolResultErrorParam: +// case *anthropic.TextEditorCodeExecutionViewResultBlockParam: +// case *anthropic.TextEditorCodeExecutionCreateResultBlockParam: +// case *anthropic.TextEditorCodeExecutionStrReplaceResultBlockParam: +// case *anthropic.ToolSearchToolResultErrorParam: +// case *anthropic.ToolSearchToolSearchResultBlockParam: +// default: +// fmt.Errorf("not present") +// } +func (u contentBlockParamUnionContent) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u contentBlockParamUnionContent) GetURL() *string { + switch vt := u.any.(type) { + case *WebFetchToolResultBlockParamContentUnion: + return vt.GetURL() + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u contentBlockParamUnionContent) GetRetrievedAt() *string { + switch vt := u.any.(type) { + case *WebFetchToolResultBlockParamContentUnion: + return vt.GetRetrievedAt() + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u contentBlockParamUnionContent) GetEncryptedStdout() *string { + switch vt := u.any.(type) { + case *CodeExecutionToolResultBlockParamContentUnion: + return vt.GetEncryptedStdout() + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u contentBlockParamUnionContent) GetFileType() *string { + switch vt := u.any.(type) { + case *TextEditorCodeExecutionToolResultBlockParamContentUnion: + return vt.GetFileType() + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u contentBlockParamUnionContent) GetNumLines() *int64 { + switch vt := u.any.(type) { + case *TextEditorCodeExecutionToolResultBlockParamContentUnion: + return vt.GetNumLines() + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u contentBlockParamUnionContent) GetStartLine() *int64 { + switch vt := u.any.(type) { + case *TextEditorCodeExecutionToolResultBlockParamContentUnion: + return vt.GetStartLine() + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u contentBlockParamUnionContent) GetTotalLines() *int64 { + switch vt := u.any.(type) { + case *TextEditorCodeExecutionToolResultBlockParamContentUnion: + return vt.GetTotalLines() + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u contentBlockParamUnionContent) GetIsFileUpdate() *bool { + switch vt := u.any.(type) { + case *TextEditorCodeExecutionToolResultBlockParamContentUnion: + return vt.GetIsFileUpdate() + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u contentBlockParamUnionContent) GetLines() []string { + switch vt := u.any.(type) { + case *TextEditorCodeExecutionToolResultBlockParamContentUnion: + return vt.GetLines() + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u contentBlockParamUnionContent) GetNewLines() *int64 { + switch vt := u.any.(type) { + case *TextEditorCodeExecutionToolResultBlockParamContentUnion: + return vt.GetNewLines() + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u contentBlockParamUnionContent) GetNewStart() *int64 { + switch vt := u.any.(type) { + case *TextEditorCodeExecutionToolResultBlockParamContentUnion: + return vt.GetNewStart() + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u contentBlockParamUnionContent) GetOldLines() *int64 { + switch vt := u.any.(type) { + case *TextEditorCodeExecutionToolResultBlockParamContentUnion: + return vt.GetOldLines() + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u contentBlockParamUnionContent) GetOldStart() *int64 { + switch vt := u.any.(type) { + case *TextEditorCodeExecutionToolResultBlockParamContentUnion: + return vt.GetOldStart() + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u contentBlockParamUnionContent) GetToolReferences() []ToolReferenceBlockParam { + switch vt := u.any.(type) { + case *ToolSearchToolResultBlockParamContentUnion: + return vt.GetToolReferences() + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u contentBlockParamUnionContent) GetErrorCode() *string { + switch vt := u.any.(type) { + case *WebSearchToolResultBlockParamContentUnion: + if vt.OfRequestWebSearchToolResultError != nil { + return (*string)(&vt.OfRequestWebSearchToolResultError.ErrorCode) + } + case *WebFetchToolResultBlockParamContentUnion: + return vt.GetErrorCode() + case *CodeExecutionToolResultBlockParamContentUnion: + return vt.GetErrorCode() + case *BashCodeExecutionToolResultBlockParamContentUnion: + return vt.GetErrorCode() + case *TextEditorCodeExecutionToolResultBlockParamContentUnion: + return vt.GetErrorCode() + case *ToolSearchToolResultBlockParamContentUnion: + return vt.GetErrorCode() + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u contentBlockParamUnionContent) GetType() *string { + switch vt := u.any.(type) { + case *WebSearchToolResultBlockParamContentUnion: + if vt.OfRequestWebSearchToolResultError != nil { + return (*string)(&vt.OfRequestWebSearchToolResultError.Type) + } + case *WebFetchToolResultBlockParamContentUnion: + return vt.GetType() + case *CodeExecutionToolResultBlockParamContentUnion: + return vt.GetType() + case *BashCodeExecutionToolResultBlockParamContentUnion: + return vt.GetType() + case *TextEditorCodeExecutionToolResultBlockParamContentUnion: + return vt.GetType() + case *ToolSearchToolResultBlockParamContentUnion: + return vt.GetType() + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u contentBlockParamUnionContent) GetReturnCode() *int64 { + switch vt := u.any.(type) { + case *CodeExecutionToolResultBlockParamContentUnion: + return vt.GetReturnCode() + case *BashCodeExecutionToolResultBlockParamContentUnion: + return vt.GetReturnCode() + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u contentBlockParamUnionContent) GetStderr() *string { + switch vt := u.any.(type) { + case *CodeExecutionToolResultBlockParamContentUnion: + return vt.GetStderr() + case *BashCodeExecutionToolResultBlockParamContentUnion: + return vt.GetStderr() + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u contentBlockParamUnionContent) GetStdout() *string { + switch vt := u.any.(type) { + case *CodeExecutionToolResultBlockParamContentUnion: + return vt.GetStdout() + case *BashCodeExecutionToolResultBlockParamContentUnion: + return vt.GetStdout() + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u contentBlockParamUnionContent) GetErrorMessage() *string { + switch vt := u.any.(type) { + case *TextEditorCodeExecutionToolResultBlockParamContentUnion: + return vt.GetErrorMessage() + case *ToolSearchToolResultBlockParamContentUnion: + return vt.GetErrorMessage() + } + return nil +} + +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u contentBlockParamUnionContent) GetContent() (res contentBlockParamUnionContentContent) { + switch vt := u.any.(type) { + case *WebFetchToolResultBlockParamContentUnion: + res.any = vt.GetContent() + case *CodeExecutionToolResultBlockParamContentUnion: + res.any = vt.GetContent() + case *BashCodeExecutionToolResultBlockParamContentUnion: + res.any = vt.GetContent() + case *TextEditorCodeExecutionToolResultBlockParamContentUnion: + res.any = vt.GetContent() + } + return res +} + +// Can have the runtime types [*DocumentBlockParam], +// [_[]CodeExecutionOutputBlockParam], [_[]BashCodeExecutionOutputBlockParam], +// [*string] +type contentBlockParamUnionContentContent struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.DocumentBlockParam: +// case *[]anthropic.CodeExecutionOutputBlockParam: +// case *[]anthropic.BashCodeExecutionOutputBlockParam: +// case *string: +// default: +// fmt.Errorf("not present") +// } +func (u contentBlockParamUnionContentContent) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's Input property, if present. +func (u ContentBlockParamUnion) GetInput() *any { + if vt := u.OfToolUse; vt != nil { + return &vt.Input + } else if vt := u.OfServerToolUse; vt != nil { + return &vt.Input + } + return nil +} + +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u ContentBlockParamUnion) GetCaller() (res contentBlockParamUnionCaller) { + if vt := u.OfToolUse; vt != nil { + res.any = vt.Caller.asAny() + } else if vt := u.OfServerToolUse; vt != nil { + res.any = vt.Caller.asAny() + } else if vt := u.OfWebSearchToolResult; vt != nil { + res.any = vt.Caller.asAny() + } else if vt := u.OfWebFetchToolResult; vt != nil { + res.any = vt.Caller.asAny() + } + return +} + +// Can have the runtime types [*DirectCallerParam], [*ServerToolCallerParam], +// [*ServerToolCaller20260120Param] +type contentBlockParamUnionCaller struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.DirectCallerParam: +// case *anthropic.ServerToolCallerParam: +// case *anthropic.ServerToolCaller20260120Param: +// default: +// fmt.Errorf("not present") +// } +func (u contentBlockParamUnionCaller) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u contentBlockParamUnionCaller) GetType() *string { + switch vt := u.any.(type) { + case *ToolUseBlockParamCallerUnion: + return vt.GetType() + case *ServerToolUseBlockParamCallerUnion: + return vt.GetType() + case *WebSearchToolResultBlockParamCallerUnion: + return vt.GetType() + case *WebFetchToolResultBlockParamCallerUnion: + return vt.GetType() + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u contentBlockParamUnionCaller) GetToolID() *string { + switch vt := u.any.(type) { + case *ToolUseBlockParamCallerUnion: + return vt.GetToolID() + case *ServerToolUseBlockParamCallerUnion: + return vt.GetToolID() + case *WebSearchToolResultBlockParamCallerUnion: + return vt.GetToolID() + case *WebFetchToolResultBlockParamCallerUnion: + return vt.GetToolID() + } + return nil +} + +func init() { + apijson.RegisterCustomDecoder[[]ContentBlockParamUnion](func(node gjson.Result, value reflect.Value, defaultDecoder func(gjson.Result, reflect.Value) error) error { + if node.Type == gjson.String { + textBlock := TextBlockParam{Text: node.String(), Type: "text"} + contentUnion := ContentBlockParamUnion{OfText: &textBlock} + arrayValue := reflect.MakeSlice(value.Type(), 1, 1) + arrayValue.Index(0).Set(reflect.ValueOf(contentUnion)) + value.Set(arrayValue) + return nil + } + return defaultDecoder(node, value) + }) +} + +func init() { + apijson.RegisterCustomDecoder[[]ToolResultBlockParamContentUnion](func(node gjson.Result, value reflect.Value, defaultDecoder func(gjson.Result, reflect.Value) error) error { + if node.Type == gjson.String { + textBlock := TextBlockParam{Text: node.String(), Type: "text"} + contentUnion := ToolResultBlockParamContentUnion{OfText: &textBlock} + arrayValue := reflect.MakeSlice(value.Type(), 1, 1) + arrayValue.Index(0).Set(reflect.ValueOf(contentUnion)) + value.Set(arrayValue) + return nil + } + return defaultDecoder(node, value) + }) +} + +func init() { + apijson.RegisterUnion[ContentBlockParamUnion]( + "type", + apijson.Discriminator[TextBlockParam]("text"), + apijson.Discriminator[ImageBlockParam]("image"), + apijson.Discriminator[DocumentBlockParam]("document"), + apijson.Discriminator[SearchResultBlockParam]("search_result"), + apijson.Discriminator[ThinkingBlockParam]("thinking"), + apijson.Discriminator[RedactedThinkingBlockParam]("redacted_thinking"), + apijson.Discriminator[ToolUseBlockParam]("tool_use"), + apijson.Discriminator[ToolResultBlockParam]("tool_result"), + apijson.Discriminator[ServerToolUseBlockParam]("server_tool_use"), + apijson.Discriminator[WebSearchToolResultBlockParam]("web_search_tool_result"), + apijson.Discriminator[WebFetchToolResultBlockParam]("web_fetch_tool_result"), + apijson.Discriminator[CodeExecutionToolResultBlockParam]("code_execution_tool_result"), + apijson.Discriminator[BashCodeExecutionToolResultBlockParam]("bash_code_execution_tool_result"), + apijson.Discriminator[TextEditorCodeExecutionToolResultBlockParam]("text_editor_code_execution_tool_result"), + apijson.Discriminator[ToolSearchToolResultBlockParam]("tool_search_tool_result"), + apijson.Discriminator[ContainerUploadBlockParam]("container_upload"), + ) +} + +// The properties Content, Type are required. +type ContentBlockSourceParam struct { + Content ContentBlockSourceContentUnionParam `json:"content,omitzero" api:"required"` + // This field can be elided, and will marshal its zero value as "content". + Type constant.Content `json:"type" default:"content"` + paramObj +} + +func (r ContentBlockSourceParam) MarshalJSON() (data []byte, err error) { + type shadow ContentBlockSourceParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *ContentBlockSourceParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type ContentBlockSourceContentUnionParam struct { + OfString param.Opt[string] `json:",omitzero,inline"` + OfContentBlockSourceContent []ContentBlockSourceContentItemUnionParam `json:",omitzero,inline"` + paramUnion +} + +func (u ContentBlockSourceContentUnionParam) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfString, u.OfContentBlockSourceContent) +} +func (u *ContentBlockSourceContentUnionParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *ContentBlockSourceContentUnionParam) asAny() any { + if !param.IsOmitted(u.OfString) { + return &u.OfString.Value + } else if !param.IsOmitted(u.OfContentBlockSourceContent) { + return &u.OfContentBlockSourceContent + } + return nil +} + +func ContentBlockSourceContentItemParamOfText(text string) ContentBlockSourceContentItemUnionParam { + var variant TextBlockParam + variant.Text = text + return ContentBlockSourceContentItemUnionParam{OfText: &variant} +} + +func ContentBlockSourceContentItemParamOfImage[ + T Base64ImageSourceParam | URLImageSourceParam | FileImageSourceParam, +](source T) ContentBlockSourceContentItemUnionParam { + var image ImageBlockParam + switch v := any(source).(type) { + case Base64ImageSourceParam: + image.Source.OfBase64 = &v + case URLImageSourceParam: + image.Source.OfURL = &v + case FileImageSourceParam: + image.Source.OfFile = &v + } + return ContentBlockSourceContentItemUnionParam{OfImage: &image} +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type ContentBlockSourceContentItemUnionParam struct { + OfText *TextBlockParam `json:",omitzero,inline"` + OfImage *ImageBlockParam `json:",omitzero,inline"` + paramUnion +} + +func (u ContentBlockSourceContentItemUnionParam) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfText, u.OfImage) +} +func (u *ContentBlockSourceContentItemUnionParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *ContentBlockSourceContentItemUnionParam) asAny() any { + if !param.IsOmitted(u.OfText) { + return u.OfText + } else if !param.IsOmitted(u.OfImage) { + return u.OfImage + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u ContentBlockSourceContentItemUnionParam) GetText() *string { + if vt := u.OfText; vt != nil { + return &vt.Text + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u ContentBlockSourceContentItemUnionParam) GetCitations() []TextCitationParamUnion { + if vt := u.OfText; vt != nil { + return vt.Citations + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u ContentBlockSourceContentItemUnionParam) GetSource() *ImageBlockParamSourceUnion { + if vt := u.OfImage; vt != nil { + return &vt.Source + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u ContentBlockSourceContentItemUnionParam) GetTransformations() *ImageTransformationsParam { + if vt := u.OfImage; vt != nil { + return &vt.Transformations + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u ContentBlockSourceContentItemUnionParam) GetType() *string { + if vt := u.OfText; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfImage; vt != nil { + return (*string)(&vt.Type) + } + return nil +} + +// Returns a pointer to the underlying variant's CacheControl property, if present. +func (u ContentBlockSourceContentItemUnionParam) GetCacheControl() *CacheControlEphemeralParam { + if vt := u.OfText; vt != nil { + return &vt.CacheControl + } else if vt := u.OfImage; vt != nil { + return &vt.CacheControl + } + return nil +} + +func init() { + apijson.RegisterUnion[ContentBlockSourceContentItemUnionParam]( + "type", + apijson.Discriminator[TextBlockParam]("text"), + apijson.Discriminator[ImageBlockParam]("image"), + ) +} + +// Tool invocation directly from the model. +type DirectCaller struct { + Type constant.Direct `json:"type" default:"direct"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r DirectCaller) RawJSON() string { return r.JSON.raw } +func (r *DirectCaller) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// ToParam converts this DirectCaller to a DirectCallerParam. +// +// Warning: the fields of the param type will not be present. ToParam should only +// be used at the last possible moment before sending a request. Test for this with +// DirectCallerParam.Overrides() +func (r DirectCaller) ToParam() DirectCallerParam { + return param.Override[DirectCallerParam](json.RawMessage(r.RawJSON())) +} + +func NewDirectCallerParam() DirectCallerParam { + return DirectCallerParam{ + Type: "direct", + } +} + +// Tool invocation directly from the model. +// +// This struct has a constant value, construct it with [NewDirectCallerParam]. +type DirectCallerParam struct { + Type constant.Direct `json:"type" default:"direct"` + paramObj +} + +func (r DirectCallerParam) MarshalJSON() (data []byte, err error) { + type shadow DirectCallerParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *DirectCallerParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type DocumentBlock struct { + // Citation configuration for the document + Citations CitationsConfig `json:"citations" api:"required"` + Source DocumentBlockSourceUnion `json:"source" api:"required"` + // The title of the document + Title string `json:"title" api:"required"` + Type constant.Document `json:"type" default:"document"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Citations respjson.Field + Source respjson.Field + Title respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r DocumentBlock) RawJSON() string { return r.JSON.raw } +func (r *DocumentBlock) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// DocumentBlockSourceUnion contains all possible properties and values from +// [Base64PDFSource], [PlainTextSource]. +// +// Use the [DocumentBlockSourceUnion.AsAny] method to switch on the variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type DocumentBlockSourceUnion struct { + Data string `json:"data"` + MediaType string `json:"media_type"` + // Any of "base64", "text". + Type string `json:"type"` + JSON struct { + Data respjson.Field + MediaType respjson.Field + Type respjson.Field + raw string + } `json:"-"` +} + +// anyDocumentBlockSource is implemented by each variant of +// [DocumentBlockSourceUnion] to add type safety for the return type of +// [DocumentBlockSourceUnion.AsAny] +type anyDocumentBlockSource interface { + implDocumentBlockSourceUnion() +} + +func (Base64PDFSource) implDocumentBlockSourceUnion() {} +func (PlainTextSource) implDocumentBlockSourceUnion() {} + +// Use the following switch statement to find the correct variant +// +// switch variant := DocumentBlockSourceUnion.AsAny().(type) { +// case anthropic.Base64PDFSource: +// case anthropic.PlainTextSource: +// default: +// fmt.Errorf("no variant present") +// } +func (u DocumentBlockSourceUnion) AsAny() anyDocumentBlockSource { + switch u.Type { + case "base64": + return u.AsBase64() + case "text": + return u.AsText() + } + return nil +} + +func (u DocumentBlockSourceUnion) AsBase64() (v Base64PDFSource) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u DocumentBlockSourceUnion) AsText() (v PlainTextSource) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u DocumentBlockSourceUnion) RawJSON() string { return u.JSON.raw } + +func (r *DocumentBlockSourceUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The properties Source, Type are required. +type DocumentBlockParam struct { + Source DocumentBlockParamSourceUnion `json:"source,omitzero" api:"required"` + Context param.Opt[string] `json:"context,omitzero"` + Title param.Opt[string] `json:"title,omitzero"` + // Create a cache control breakpoint at this content block. + CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` + Citations CitationsConfigParam `json:"citations,omitzero"` + // This field can be elided, and will marshal its zero value as "document". + Type constant.Document `json:"type" default:"document"` + paramObj +} + +func (r DocumentBlockParam) MarshalJSON() (data []byte, err error) { + type shadow DocumentBlockParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *DocumentBlockParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type DocumentBlockParamSourceUnion struct { + OfBase64 *Base64PDFSourceParam `json:",omitzero,inline"` + OfText *PlainTextSourceParam `json:",omitzero,inline"` + OfContent *ContentBlockSourceParam `json:",omitzero,inline"` + OfURL *URLPDFSourceParam `json:",omitzero,inline"` + OfFile *FileDocumentSourceParam `json:",omitzero,inline"` + paramUnion +} + +func (u DocumentBlockParamSourceUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfBase64, + u.OfText, + u.OfContent, + u.OfURL, + u.OfFile) +} +func (u *DocumentBlockParamSourceUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *DocumentBlockParamSourceUnion) asAny() any { + if !param.IsOmitted(u.OfBase64) { + return u.OfBase64 + } else if !param.IsOmitted(u.OfText) { + return u.OfText + } else if !param.IsOmitted(u.OfContent) { + return u.OfContent + } else if !param.IsOmitted(u.OfURL) { + return u.OfURL + } else if !param.IsOmitted(u.OfFile) { + return u.OfFile + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u DocumentBlockParamSourceUnion) GetContent() *ContentBlockSourceContentUnionParam { + if vt := u.OfContent; vt != nil { + return &vt.Content + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u DocumentBlockParamSourceUnion) GetURL() *string { + if vt := u.OfURL; vt != nil { + return &vt.URL + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u DocumentBlockParamSourceUnion) GetFileID() *string { + if vt := u.OfFile; vt != nil { + return &vt.FileID + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u DocumentBlockParamSourceUnion) GetData() *string { + if vt := u.OfBase64; vt != nil { + return (*string)(&vt.Data) + } else if vt := u.OfText; vt != nil { + return (*string)(&vt.Data) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u DocumentBlockParamSourceUnion) GetMediaType() *string { + if vt := u.OfBase64; vt != nil { + return (*string)(&vt.MediaType) + } else if vt := u.OfText; vt != nil { + return (*string)(&vt.MediaType) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u DocumentBlockParamSourceUnion) GetType() *string { + if vt := u.OfBase64; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfText; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfContent; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfURL; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfFile; vt != nil { + return (*string)(&vt.Type) + } + return nil +} + +func init() { + apijson.RegisterUnion[DocumentBlockParamSourceUnion]( + "type", + apijson.Discriminator[Base64PDFSourceParam]("base64"), + apijson.Discriminator[PlainTextSourceParam]("text"), + apijson.Discriminator[ContentBlockSourceParam]("content"), + apijson.Discriminator[URLPDFSourceParam]("url"), + apijson.Discriminator[FileDocumentSourceParam]("file"), + ) +} + +// Code execution result with encrypted stdout for PFC + web_search results. +type EncryptedCodeExecutionResultBlock struct { + Content []CodeExecutionOutputBlock `json:"content" api:"required"` + EncryptedStdout string `json:"encrypted_stdout" api:"required"` + ReturnCode int64 `json:"return_code" api:"required"` + Stderr string `json:"stderr" api:"required"` + Type constant.EncryptedCodeExecutionResult `json:"type" default:"encrypted_code_execution_result"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Content respjson.Field + EncryptedStdout respjson.Field + ReturnCode respjson.Field + Stderr respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r EncryptedCodeExecutionResultBlock) RawJSON() string { return r.JSON.raw } +func (r *EncryptedCodeExecutionResultBlock) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Code execution result with encrypted stdout for PFC + web_search results. +// +// The properties Content, EncryptedStdout, ReturnCode, Stderr, Type are required. +type EncryptedCodeExecutionResultBlockParam struct { + Content []CodeExecutionOutputBlockParam `json:"content,omitzero" api:"required"` + EncryptedStdout string `json:"encrypted_stdout" api:"required"` + ReturnCode int64 `json:"return_code" api:"required"` + Stderr string `json:"stderr" api:"required"` + // This field can be elided, and will marshal its zero value as + // "encrypted_code_execution_result". + Type constant.EncryptedCodeExecutionResult `json:"type" default:"encrypted_code_execution_result"` + paramObj +} + +func (r EncryptedCodeExecutionResultBlockParam) MarshalJSON() (data []byte, err error) { + type shadow EncryptedCodeExecutionResultBlockParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *EncryptedCodeExecutionResultBlockParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The properties FileID, Type are required. +type FileDocumentSourceParam struct { + FileID string `json:"file_id" api:"required"` + // This field can be elided, and will marshal its zero value as "file". + Type constant.File `json:"type" default:"file"` + paramObj +} + +func (r FileDocumentSourceParam) MarshalJSON() (data []byte, err error) { + type shadow FileDocumentSourceParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *FileDocumentSourceParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The properties FileID, Type are required. +type FileImageSourceParam struct { + FileID string `json:"file_id" api:"required"` + // This field can be elided, and will marshal its zero value as "file". + Type constant.File `json:"type" default:"file"` + paramObj +} + +func (r FileImageSourceParam) MarshalJSON() (data []byte, err error) { + type shadow FileImageSourceParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *FileImageSourceParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The properties Source, Type are required. +type ImageBlockParam struct { + Source ImageBlockParamSourceUnion `json:"source,omitzero" api:"required"` + // Create a cache control breakpoint at this content block. + CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` + // Configures the transformations the server applies to this image before the model + // observes it. Each key names a condition the server transforms images for; its + // value selects the transformation applied. Omitted keys keep their default + // behavior, and an empty object is equivalent to omitting the field. + Transformations ImageTransformationsParam `json:"transformations,omitzero"` + // This field can be elided, and will marshal its zero value as "image". + Type constant.Image `json:"type" default:"image"` + paramObj +} + +func (r ImageBlockParam) MarshalJSON() (data []byte, err error) { + type shadow ImageBlockParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *ImageBlockParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type ImageBlockParamSourceUnion struct { + OfBase64 *Base64ImageSourceParam `json:",omitzero,inline"` + OfURL *URLImageSourceParam `json:",omitzero,inline"` + OfFile *FileImageSourceParam `json:",omitzero,inline"` + paramUnion +} + +func (u ImageBlockParamSourceUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfBase64, u.OfURL, u.OfFile) +} +func (u *ImageBlockParamSourceUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *ImageBlockParamSourceUnion) asAny() any { + if !param.IsOmitted(u.OfBase64) { + return u.OfBase64 + } else if !param.IsOmitted(u.OfURL) { + return u.OfURL + } else if !param.IsOmitted(u.OfFile) { + return u.OfFile + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u ImageBlockParamSourceUnion) GetData() *string { + if vt := u.OfBase64; vt != nil { + return &vt.Data + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u ImageBlockParamSourceUnion) GetMediaType() *string { + if vt := u.OfBase64; vt != nil { + return (*string)(&vt.MediaType) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u ImageBlockParamSourceUnion) GetURL() *string { + if vt := u.OfURL; vt != nil { + return &vt.URL + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u ImageBlockParamSourceUnion) GetFileID() *string { + if vt := u.OfFile; vt != nil { + return &vt.FileID + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u ImageBlockParamSourceUnion) GetType() *string { + if vt := u.OfBase64; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfURL; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfFile; vt != nil { + return (*string)(&vt.Type) + } + return nil +} + +func init() { + apijson.RegisterUnion[ImageBlockParamSourceUnion]( + "type", + apijson.Discriminator[Base64ImageSourceParam]("base64"), + apijson.Discriminator[URLImageSourceParam]("url"), + apijson.Discriminator[FileImageSourceParam]("file"), + ) +} + +// Configures the transformations the server applies to this image before the model +// observes it. Each key names a condition the server transforms images for; its +// value selects the transformation applied. Omitted keys keep their default +// behavior, and an empty object is equivalent to omitting the field. +type ImageTransformationsParam struct { + // What the server does when this image exceeds the model's maximum image size. + // `"downsize"` (the default) scales the image down to fit, which changes the + // dimensions the model observes without telling you. `"error"` instead rejects the + // request with a 400 error naming the image's dimensions and the largest + // dimensions that fit, so you can scale the image deliberately — your image is + // never silently scaled down. + // + // Any of "downsize", "error". + OversizedImage ImageTransformationsParamOversizedImage `json:"oversized_image,omitzero"` + paramObj +} + +func (r ImageTransformationsParam) MarshalJSON() (data []byte, err error) { + type shadow ImageTransformationsParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *ImageTransformationsParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// What the server does when this image exceeds the model's maximum image size. +// `"downsize"` (the default) scales the image down to fit, which changes the +// dimensions the model observes without telling you. `"error"` instead rejects the +// request with a 400 error naming the image's dimensions and the largest +// dimensions that fit, so you can scale the image deliberately — your image is +// never silently scaled down. +type ImageTransformationsParamOversizedImage string + +const ( + ImageTransformationsParamOversizedImageDownsize ImageTransformationsParamOversizedImage = "downsize" + ImageTransformationsParamOversizedImageError ImageTransformationsParamOversizedImage = "error" +) + +type InputJSONDelta struct { + PartialJSON string `json:"partial_json" api:"required"` + Type constant.InputJSONDelta `json:"type" default:"input_json_delta"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + PartialJSON respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r InputJSONDelta) RawJSON() string { return r.JSON.raw } +func (r *InputJSONDelta) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The properties Schema, Type are required. +type JSONOutputFormatParam struct { + // The JSON schema of the format + Schema map[string]any `json:"schema,omitzero" api:"required"` + // This field can be elided, and will marshal its zero value as "json_schema". + Type constant.JSONSchema `json:"type" default:"json_schema"` + paramObj +} + +func (r JSONOutputFormatParam) MarshalJSON() (data []byte, err error) { + type shadow JSONOutputFormatParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *JSONOutputFormatParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The properties Name, Type are required. +type MemoryTool20250818Param struct { + // If true, tool will not be included in initial system prompt. Only loaded when + // returned via tool_reference from tool search. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // When true, guarantees schema validation on tool names and inputs + Strict param.Opt[bool] `json:"strict,omitzero"` + // Any of "direct", "code_execution_20250825", "code_execution_20260120", + // "code_execution_20260521". + AllowedCallers []string `json:"allowed_callers,omitzero"` + // Create a cache control breakpoint at this content block. + CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` + InputExamples []map[string]any `json:"input_examples,omitzero"` + // Name of the tool. + // + // This is how the tool will be called by the model and in `tool_use` blocks. + // + // This field can be elided, and will marshal its zero value as "memory". + Name constant.Memory `json:"name" default:"memory"` + // This field can be elided, and will marshal its zero value as "memory_20250818". + Type constant.Memory20250818 `json:"type" default:"memory_20250818"` + paramObj +} + +func (r MemoryTool20250818Param) MarshalJSON() (data []byte, err error) { + type shadow MemoryTool20250818Param + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *MemoryTool20250818Param) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type Message struct { + // Unique object identifier. + // + // The format and length of IDs may change over time. + ID string `json:"id" api:"required"` + // Information about the container used in the request (for the code execution + // tool) + Container Container `json:"container" api:"required"` + // Content generated by the model. + // + // This is an array of content blocks, each of which has a `type` that determines + // its shape. + // + // Example: + // + // ```json + // [{ "type": "text", "text": "Hi, I'm Claude." }] + // ``` + // + // If the request input `messages` ended with an `assistant` turn, then the + // response `content` will continue directly from that last turn. You can use this + // to constrain the model's output. + // + // For example, if the input `messages` were: + // + // ```json + // [ + // + // { + // "role": "user", + // "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun" + // }, + // { "role": "assistant", "content": "The best answer is (" } + // + // ] + // ``` + // + // Then the response `content` might be: + // + // ```json + // [{ "type": "text", "text": "B)" }] + // ``` + Content []ContentBlockUnion `json:"content" api:"required"` + // The model that will complete your prompt. + // + // See [models](https://docs.anthropic.com/en/docs/models-overview) for additional + // details and options. + Model Model `json:"model" api:"required"` + // Conversational role of the generated message. + // + // This will always be `"assistant"`. + Role constant.Assistant `json:"role" default:"assistant"` + // Structured information about a refusal. + StopDetails RefusalStopDetails `json:"stop_details" api:"required"` + // The reason that we stopped. + // + // This may be one the following values: + // + // - `"end_turn"`: the model reached a natural stopping point + // - `"max_tokens"`: we exceeded the requested `max_tokens` or the model's maximum + // - `"stop_sequence"`: one of your provided custom `stop_sequences` was generated + // - `"tool_use"`: the model invoked one or more tools + // - `"pause_turn"`: we paused a long-running turn. You may provide the response + // back as-is in a subsequent request to let the model continue. + // - `"refusal"`: when streaming classifiers intervene to handle potential policy + // violations + // - `"model_context_window_exceeded"`: we exceeded the model's context window + // + // In non-streaming mode this value is always non-null. In streaming mode, it is + // null in the `message_start` event and non-null otherwise. + // + // Any of "end_turn", "max_tokens", "stop_sequence", "tool_use", "pause_turn", + // "refusal", "model_context_window_exceeded". + StopReason StopReason `json:"stop_reason" api:"required"` + // Which custom stop sequence was generated, if any. + // + // This value will be a non-null string if one of your custom stop sequences was + // generated. + StopSequence string `json:"stop_sequence" api:"required"` + // Object type. + // + // For Messages, this is always `"message"`. + Type constant.Message `json:"type" default:"message"` + // Billing and rate-limit usage. + // + // Anthropic's API bills and rate-limits by token counts, as tokens represent the + // underlying cost to our systems. + // + // Under the hood, the API transforms requests into a format suitable for the + // model. The model's output then goes through a parsing stage before becoming an + // API response. As a result, the token counts in `usage` will not match one-to-one + // with the exact visible content of an API request or response. + // + // For example, `output_tokens` will be non-zero, even for an empty string response + // from Claude. + // + // Total input tokens in a request is the summation of `input_tokens`, + // `cache_creation_input_tokens`, and `cache_read_input_tokens`. + Usage Usage `json:"usage" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + Container respjson.Field + Content respjson.Field + Model respjson.Field + Role respjson.Field + StopDetails respjson.Field + StopReason respjson.Field + StopSequence respjson.Field + Type respjson.Field + Usage respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r Message) RawJSON() string { return r.JSON.raw } +func (r *Message) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +func MessageCountTokensToolParamOfTool(inputSchema ToolInputSchemaParam, name string) MessageCountTokensToolUnionParam { + var variant ToolParam + variant.InputSchema = inputSchema + variant.Name = name + return MessageCountTokensToolUnionParam{OfTool: &variant} +} + +func MessageCountTokensToolParamOfToolSearchToolBm25_20251119(type_ ToolSearchToolBm25_20251119Type) MessageCountTokensToolUnionParam { + var variant ToolSearchToolBm25_20251119Param + variant.Type = type_ + return MessageCountTokensToolUnionParam{OfToolSearchToolBm25_20251119: &variant} +} + +func MessageCountTokensToolParamOfToolSearchToolRegex20251119(type_ ToolSearchToolRegex20251119Type) MessageCountTokensToolUnionParam { + var variant ToolSearchToolRegex20251119Param + variant.Type = type_ + return MessageCountTokensToolUnionParam{OfToolSearchToolRegex20251119: &variant} +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type MessageCountTokensToolUnionParam struct { + OfTool *ToolParam `json:",omitzero,inline"` + OfBashTool20250124 *ToolBash20250124Param `json:",omitzero,inline"` + OfCodeExecutionTool20250522 *CodeExecutionTool20250522Param `json:",omitzero,inline"` + OfCodeExecutionTool20250825 *CodeExecutionTool20250825Param `json:",omitzero,inline"` + OfCodeExecutionTool20260120 *CodeExecutionTool20260120Param `json:",omitzero,inline"` + OfCodeExecutionTool20260521 *CodeExecutionTool20260521Param `json:",omitzero,inline"` + OfBrowserToolset20260801 *BrowserToolset20260801Param `json:",omitzero,inline"` + OfMemoryTool20250818 *MemoryTool20250818Param `json:",omitzero,inline"` + OfComputerToolset20260801 *ComputerToolset20260801Param `json:",omitzero,inline"` + OfTextEditor20250124 *ToolTextEditor20250124Param `json:",omitzero,inline"` + OfTextEditor20250429 *ToolTextEditor20250429Param `json:",omitzero,inline"` + OfTextEditor20250728 *ToolTextEditor20250728Param `json:",omitzero,inline"` + OfWebSearchTool20250305 *WebSearchTool20250305Param `json:",omitzero,inline"` + OfWebFetchTool20250910 *WebFetchTool20250910Param `json:",omitzero,inline"` + OfWebSearchTool20260209 *WebSearchTool20260209Param `json:",omitzero,inline"` + OfWebFetchTool20260209 *WebFetchTool20260209Param `json:",omitzero,inline"` + OfWebFetchTool20260309 *WebFetchTool20260309Param `json:",omitzero,inline"` + OfWebSearchTool20260318 *WebSearchTool20260318Param `json:",omitzero,inline"` + OfWebFetchTool20260318 *WebFetchTool20260318Param `json:",omitzero,inline"` + OfToolSearchToolBm25_20251119 *ToolSearchToolBm25_20251119Param `json:",omitzero,inline"` + OfToolSearchToolRegex20251119 *ToolSearchToolRegex20251119Param `json:",omitzero,inline"` + paramUnion +} + +func (u MessageCountTokensToolUnionParam) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfTool, u.OfBashTool20250124, u.OfCodeExecutionTool20250522, u.OfCodeExecutionTool20250825, u.OfCodeExecutionTool20260120, + u.OfCodeExecutionTool20260521, + u.OfBrowserToolset20260801, u.OfMemoryTool20250818, + u.OfComputerToolset20260801, u.OfTextEditor20250124, u.OfTextEditor20250429, u.OfTextEditor20250728, @@ -3514,362 +5305,1390 @@ func (u MessageCountTokensToolUnionParam) MarshalJSON() ([]byte, error) { u.OfWebSearchTool20260209, u.OfWebFetchTool20260209, u.OfWebFetchTool20260309, + u.OfWebSearchTool20260318, + u.OfWebFetchTool20260318, u.OfToolSearchToolBm25_20251119, u.OfToolSearchToolRegex20251119) } -func (u *MessageCountTokensToolUnionParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) +func (u *MessageCountTokensToolUnionParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *MessageCountTokensToolUnionParam) asAny() any { + if !param.IsOmitted(u.OfTool) { + return u.OfTool + } else if !param.IsOmitted(u.OfBashTool20250124) { + return u.OfBashTool20250124 + } else if !param.IsOmitted(u.OfCodeExecutionTool20250522) { + return u.OfCodeExecutionTool20250522 + } else if !param.IsOmitted(u.OfCodeExecutionTool20250825) { + return u.OfCodeExecutionTool20250825 + } else if !param.IsOmitted(u.OfCodeExecutionTool20260120) { + return u.OfCodeExecutionTool20260120 + } else if !param.IsOmitted(u.OfCodeExecutionTool20260521) { + return u.OfCodeExecutionTool20260521 + } else if !param.IsOmitted(u.OfBrowserToolset20260801) { + return u.OfBrowserToolset20260801 + } else if !param.IsOmitted(u.OfMemoryTool20250818) { + return u.OfMemoryTool20250818 + } else if !param.IsOmitted(u.OfComputerToolset20260801) { + return u.OfComputerToolset20260801 + } else if !param.IsOmitted(u.OfTextEditor20250124) { + return u.OfTextEditor20250124 + } else if !param.IsOmitted(u.OfTextEditor20250429) { + return u.OfTextEditor20250429 + } else if !param.IsOmitted(u.OfTextEditor20250728) { + return u.OfTextEditor20250728 + } else if !param.IsOmitted(u.OfWebSearchTool20250305) { + return u.OfWebSearchTool20250305 + } else if !param.IsOmitted(u.OfWebFetchTool20250910) { + return u.OfWebFetchTool20250910 + } else if !param.IsOmitted(u.OfWebSearchTool20260209) { + return u.OfWebSearchTool20260209 + } else if !param.IsOmitted(u.OfWebFetchTool20260209) { + return u.OfWebFetchTool20260209 + } else if !param.IsOmitted(u.OfWebFetchTool20260309) { + return u.OfWebFetchTool20260309 + } else if !param.IsOmitted(u.OfWebSearchTool20260318) { + return u.OfWebSearchTool20260318 + } else if !param.IsOmitted(u.OfWebFetchTool20260318) { + return u.OfWebFetchTool20260318 + } else if !param.IsOmitted(u.OfToolSearchToolBm25_20251119) { + return u.OfToolSearchToolBm25_20251119 + } else if !param.IsOmitted(u.OfToolSearchToolRegex20251119) { + return u.OfToolSearchToolRegex20251119 + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u MessageCountTokensToolUnionParam) GetInputSchema() *ToolInputSchemaParam { + if vt := u.OfTool; vt != nil { + return &vt.InputSchema + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u MessageCountTokensToolUnionParam) GetDescription() *string { + if vt := u.OfTool; vt != nil && vt.Description.Valid() { + return &vt.Description.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u MessageCountTokensToolUnionParam) GetEagerInputStreaming() *bool { + if vt := u.OfTool; vt != nil && vt.EagerInputStreaming.Valid() { + return &vt.EagerInputStreaming.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u MessageCountTokensToolUnionParam) GetMaxCharacters() *int64 { + if vt := u.OfTextEditor20250728; vt != nil && vt.MaxCharacters.Valid() { + return &vt.MaxCharacters.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u MessageCountTokensToolUnionParam) GetName() *string { + if vt := u.OfTool; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfBashTool20250124; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfCodeExecutionTool20250522; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfCodeExecutionTool20250825; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfCodeExecutionTool20260120; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfCodeExecutionTool20260521; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfMemoryTool20250818; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfTextEditor20250124; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfTextEditor20250429; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfTextEditor20250728; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfWebSearchTool20250305; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfWebFetchTool20250910; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfWebSearchTool20260209; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfWebFetchTool20260209; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfWebFetchTool20260309; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfWebSearchTool20260318; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfWebFetchTool20260318; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfToolSearchToolRegex20251119; vt != nil { + return (*string)(&vt.Name) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u MessageCountTokensToolUnionParam) GetDeferLoading() *bool { + if vt := u.OfTool; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfBashTool20250124; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfCodeExecutionTool20250522; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfCodeExecutionTool20250825; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfCodeExecutionTool20260120; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfCodeExecutionTool20260521; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfMemoryTool20250818; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfTextEditor20250124; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfTextEditor20250429; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfTextEditor20250728; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfWebSearchTool20250305; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfWebFetchTool20250910; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfWebSearchTool20260209; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfWebFetchTool20260209; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfWebFetchTool20260309; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfWebSearchTool20260318; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfWebFetchTool20260318; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfToolSearchToolRegex20251119; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u MessageCountTokensToolUnionParam) GetStrict() *bool { + if vt := u.OfTool; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfBashTool20250124; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfCodeExecutionTool20250522; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfCodeExecutionTool20250825; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfCodeExecutionTool20260120; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfCodeExecutionTool20260521; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfMemoryTool20250818; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfTextEditor20250124; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfTextEditor20250429; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfTextEditor20250728; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfWebSearchTool20250305; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfWebFetchTool20250910; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfWebSearchTool20260209; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfWebFetchTool20260209; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfWebFetchTool20260309; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfWebSearchTool20260318; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfWebFetchTool20260318; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfToolSearchToolRegex20251119; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u MessageCountTokensToolUnionParam) GetType() *string { + if vt := u.OfTool; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfBashTool20250124; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfCodeExecutionTool20250522; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfCodeExecutionTool20250825; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfCodeExecutionTool20260120; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfCodeExecutionTool20260521; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfBrowserToolset20260801; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfMemoryTool20250818; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfComputerToolset20260801; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfTextEditor20250124; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfTextEditor20250429; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfTextEditor20250728; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfWebSearchTool20250305; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfWebFetchTool20250910; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfWebSearchTool20260209; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfWebFetchTool20260209; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfWebFetchTool20260309; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfWebSearchTool20260318; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfWebFetchTool20260318; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfToolSearchToolRegex20251119; vt != nil { + return (*string)(&vt.Type) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u MessageCountTokensToolUnionParam) GetMaxUses() *int64 { + if vt := u.OfWebSearchTool20250305; vt != nil && vt.MaxUses.Valid() { + return &vt.MaxUses.Value + } else if vt := u.OfWebFetchTool20250910; vt != nil && vt.MaxUses.Valid() { + return &vt.MaxUses.Value + } else if vt := u.OfWebSearchTool20260209; vt != nil && vt.MaxUses.Valid() { + return &vt.MaxUses.Value + } else if vt := u.OfWebFetchTool20260209; vt != nil && vt.MaxUses.Valid() { + return &vt.MaxUses.Value + } else if vt := u.OfWebFetchTool20260309; vt != nil && vt.MaxUses.Valid() { + return &vt.MaxUses.Value + } else if vt := u.OfWebSearchTool20260318; vt != nil && vt.MaxUses.Valid() { + return &vt.MaxUses.Value + } else if vt := u.OfWebFetchTool20260318; vt != nil && vt.MaxUses.Valid() { + return &vt.MaxUses.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u MessageCountTokensToolUnionParam) GetMaxContentTokens() *int64 { + if vt := u.OfWebFetchTool20250910; vt != nil && vt.MaxContentTokens.Valid() { + return &vt.MaxContentTokens.Value + } else if vt := u.OfWebFetchTool20260209; vt != nil && vt.MaxContentTokens.Valid() { + return &vt.MaxContentTokens.Value + } else if vt := u.OfWebFetchTool20260309; vt != nil && vt.MaxContentTokens.Valid() { + return &vt.MaxContentTokens.Value + } else if vt := u.OfWebFetchTool20260318; vt != nil && vt.MaxContentTokens.Valid() { + return &vt.MaxContentTokens.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u MessageCountTokensToolUnionParam) GetUseCache() *bool { + if vt := u.OfWebFetchTool20260309; vt != nil && vt.UseCache.Valid() { + return &vt.UseCache.Value + } else if vt := u.OfWebFetchTool20260318; vt != nil && vt.UseCache.Valid() { + return &vt.UseCache.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u MessageCountTokensToolUnionParam) GetResponseInclusion() *string { + if vt := u.OfWebSearchTool20260318; vt != nil { + return (*string)(&vt.ResponseInclusion) + } else if vt := u.OfWebFetchTool20260318; vt != nil { + return (*string)(&vt.ResponseInclusion) + } + return nil +} + +// Returns a pointer to the underlying variant's AllowedCallers property, if +// present. +func (u MessageCountTokensToolUnionParam) GetAllowedCallers() []string { + if vt := u.OfTool; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfBashTool20250124; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfCodeExecutionTool20250522; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfCodeExecutionTool20250825; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfCodeExecutionTool20260120; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfCodeExecutionTool20260521; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfBrowserToolset20260801; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfMemoryTool20250818; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfComputerToolset20260801; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfTextEditor20250124; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfTextEditor20250429; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfTextEditor20250728; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfWebSearchTool20250305; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfWebFetchTool20250910; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfWebSearchTool20260209; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfWebFetchTool20260209; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfWebFetchTool20260309; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfWebSearchTool20260318; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfWebFetchTool20260318; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfToolSearchToolRegex20251119; vt != nil { + return vt.AllowedCallers + } + return nil +} + +// Returns a pointer to the underlying variant's CacheControl property, if present. +func (u MessageCountTokensToolUnionParam) GetCacheControl() *CacheControlEphemeralParam { + if vt := u.OfTool; vt != nil { + return &vt.CacheControl + } else if vt := u.OfBashTool20250124; vt != nil { + return &vt.CacheControl + } else if vt := u.OfCodeExecutionTool20250522; vt != nil { + return &vt.CacheControl + } else if vt := u.OfCodeExecutionTool20250825; vt != nil { + return &vt.CacheControl + } else if vt := u.OfCodeExecutionTool20260120; vt != nil { + return &vt.CacheControl + } else if vt := u.OfCodeExecutionTool20260521; vt != nil { + return &vt.CacheControl + } else if vt := u.OfBrowserToolset20260801; vt != nil { + return &vt.CacheControl + } else if vt := u.OfMemoryTool20250818; vt != nil { + return &vt.CacheControl + } else if vt := u.OfComputerToolset20260801; vt != nil { + return &vt.CacheControl + } else if vt := u.OfTextEditor20250124; vt != nil { + return &vt.CacheControl + } else if vt := u.OfTextEditor20250429; vt != nil { + return &vt.CacheControl + } else if vt := u.OfTextEditor20250728; vt != nil { + return &vt.CacheControl + } else if vt := u.OfWebSearchTool20250305; vt != nil { + return &vt.CacheControl + } else if vt := u.OfWebFetchTool20250910; vt != nil { + return &vt.CacheControl + } else if vt := u.OfWebSearchTool20260209; vt != nil { + return &vt.CacheControl + } else if vt := u.OfWebFetchTool20260209; vt != nil { + return &vt.CacheControl + } else if vt := u.OfWebFetchTool20260309; vt != nil { + return &vt.CacheControl + } else if vt := u.OfWebSearchTool20260318; vt != nil { + return &vt.CacheControl + } else if vt := u.OfWebFetchTool20260318; vt != nil { + return &vt.CacheControl + } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil { + return &vt.CacheControl + } else if vt := u.OfToolSearchToolRegex20251119; vt != nil { + return &vt.CacheControl + } + return nil +} + +// Returns a pointer to the underlying variant's InputExamples property, if +// present. +func (u MessageCountTokensToolUnionParam) GetInputExamples() []map[string]any { + if vt := u.OfTool; vt != nil { + return vt.InputExamples + } else if vt := u.OfBashTool20250124; vt != nil { + return vt.InputExamples + } else if vt := u.OfMemoryTool20250818; vt != nil { + return vt.InputExamples + } else if vt := u.OfTextEditor20250124; vt != nil { + return vt.InputExamples + } else if vt := u.OfTextEditor20250429; vt != nil { + return vt.InputExamples + } else if vt := u.OfTextEditor20250728; vt != nil { + return vt.InputExamples + } + return nil +} + +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u MessageCountTokensToolUnionParam) GetConfigs() (res messageCountTokensToolUnionParamConfigs) { + if vt := u.OfBrowserToolset20260801; vt != nil { + res.any = &vt.Configs + } else if vt := u.OfComputerToolset20260801; vt != nil { + res.any = &vt.Configs + } + return +} + +// Can have the runtime types [*BrowserToolsetConfigsParam], +// [*ComputerToolsetConfigsParam] +type messageCountTokensToolUnionParamConfigs struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BrowserToolsetConfigsParam: +// case *anthropic.ComputerToolsetConfigsParam: +// default: +// fmt.Errorf("not present") +// } +func (u messageCountTokensToolUnionParamConfigs) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u messageCountTokensToolUnionParamConfigs) GetCloseTab() *BrowserCloseTabConfigParam { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + return &vt.CloseTab + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u messageCountTokensToolUnionParamConfigs) GetFileUpload() *BrowserFileUploadConfigParam { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + return &vt.FileUpload + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u messageCountTokensToolUnionParamConfigs) GetFind() *BrowserFindConfigParam { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + return &vt.Find + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u messageCountTokensToolUnionParamConfigs) GetFormInput() *BrowserFormInputConfigParam { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + return &vt.FormInput + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u messageCountTokensToolUnionParamConfigs) GetGetPageText() *BrowserGetPageTextConfigParam { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + return &vt.GetPageText + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u messageCountTokensToolUnionParamConfigs) GetHover() *BrowserHoverConfigParam { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + return &vt.Hover + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u messageCountTokensToolUnionParamConfigs) GetJavascriptExec() *BrowserJavascriptExecConfigParam { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + return &vt.JavascriptExec + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u messageCountTokensToolUnionParamConfigs) GetListTabs() *BrowserListTabsConfigParam { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + return &vt.ListTabs + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u messageCountTokensToolUnionParamConfigs) GetNavigate() *BrowserNavigateConfigParam { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + return &vt.Navigate + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u messageCountTokensToolUnionParamConfigs) GetNewTab() *BrowserNewTabConfigParam { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + return &vt.NewTab + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u messageCountTokensToolUnionParamConfigs) GetReadConsole() *BrowserReadConsoleConfigParam { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + return &vt.ReadConsole + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u messageCountTokensToolUnionParamConfigs) GetReadNetwork() *BrowserReadNetworkConfigParam { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + return &vt.ReadNetwork + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u messageCountTokensToolUnionParamConfigs) GetReadPage() *BrowserReadPageConfigParam { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + return &vt.ReadPage + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u messageCountTokensToolUnionParamConfigs) GetScrollTo() *BrowserScrollToConfigParam { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + return &vt.ScrollTo + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u messageCountTokensToolUnionParamConfigs) GetSwitchTab() *BrowserSwitchTabConfigParam { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + return &vt.SwitchTab + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u messageCountTokensToolUnionParamConfigs) GetCursorPosition() *ComputerCursorPositionConfigParam { + switch vt := u.any.(type) { + case *ComputerToolsetConfigsParam: + return &vt.CursorPosition + } + return nil +} + +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u messageCountTokensToolUnionParamConfigs) GetDoubleClick() (res messageCountTokensToolUnionParamConfigsDoubleClick) { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + res.any = &vt.DoubleClick + case *ComputerToolsetConfigsParam: + res.any = &vt.DoubleClick + } + return res +} + +// Can have the runtime types [*BrowserDoubleClickConfigParam], +// [*ComputerDoubleClickConfigParam] +type messageCountTokensToolUnionParamConfigsDoubleClick struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BrowserDoubleClickConfigParam: +// case *anthropic.ComputerDoubleClickConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u messageCountTokensToolUnionParamConfigsDoubleClick) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u messageCountTokensToolUnionParamConfigsDoubleClick) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BrowserDoubleClickConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *ComputerDoubleClickConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u messageCountTokensToolUnionParamConfigsDoubleClick) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BrowserDoubleClickConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *ComputerDoubleClickConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + } + return nil +} + +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u messageCountTokensToolUnionParamConfigs) GetHoldKey() (res messageCountTokensToolUnionParamConfigsHoldKey) { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + res.any = &vt.HoldKey + case *ComputerToolsetConfigsParam: + res.any = &vt.HoldKey + } + return res +} + +// Can have the runtime types [*BrowserHoldKeyConfigParam], +// [*ComputerHoldKeyConfigParam] +type messageCountTokensToolUnionParamConfigsHoldKey struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BrowserHoldKeyConfigParam: +// case *anthropic.ComputerHoldKeyConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u messageCountTokensToolUnionParamConfigsHoldKey) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u messageCountTokensToolUnionParamConfigsHoldKey) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BrowserHoldKeyConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *ComputerHoldKeyConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u messageCountTokensToolUnionParamConfigsHoldKey) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BrowserHoldKeyConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *ComputerHoldKeyConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + } + return nil +} + +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u messageCountTokensToolUnionParamConfigs) GetKey() (res messageCountTokensToolUnionParamConfigsKey) { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + res.any = &vt.Key + case *ComputerToolsetConfigsParam: + res.any = &vt.Key + } + return res +} + +// Can have the runtime types [*BrowserKeyConfigParam], [*ComputerKeyConfigParam] +type messageCountTokensToolUnionParamConfigsKey struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BrowserKeyConfigParam: +// case *anthropic.ComputerKeyConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u messageCountTokensToolUnionParamConfigsKey) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u messageCountTokensToolUnionParamConfigsKey) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BrowserKeyConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *ComputerKeyConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u messageCountTokensToolUnionParamConfigsKey) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BrowserKeyConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *ComputerKeyConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + } + return nil +} + +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u messageCountTokensToolUnionParamConfigs) GetLeftClick() (res messageCountTokensToolUnionParamConfigsLeftClick) { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + res.any = &vt.LeftClick + case *ComputerToolsetConfigsParam: + res.any = &vt.LeftClick + } + return res +} + +// Can have the runtime types [*BrowserLeftClickConfigParam], +// [*ComputerLeftClickConfigParam] +type messageCountTokensToolUnionParamConfigsLeftClick struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BrowserLeftClickConfigParam: +// case *anthropic.ComputerLeftClickConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u messageCountTokensToolUnionParamConfigsLeftClick) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u messageCountTokensToolUnionParamConfigsLeftClick) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BrowserLeftClickConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *ComputerLeftClickConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u messageCountTokensToolUnionParamConfigsLeftClick) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BrowserLeftClickConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *ComputerLeftClickConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + } + return nil +} + +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u messageCountTokensToolUnionParamConfigs) GetLeftClickDrag() (res messageCountTokensToolUnionParamConfigsLeftClickDrag) { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + res.any = &vt.LeftClickDrag + case *ComputerToolsetConfigsParam: + res.any = &vt.LeftClickDrag + } + return res +} + +// Can have the runtime types [*BrowserLeftClickDragConfigParam], +// [*ComputerLeftClickDragConfigParam] +type messageCountTokensToolUnionParamConfigsLeftClickDrag struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BrowserLeftClickDragConfigParam: +// case *anthropic.ComputerLeftClickDragConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u messageCountTokensToolUnionParamConfigsLeftClickDrag) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u messageCountTokensToolUnionParamConfigsLeftClickDrag) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BrowserLeftClickDragConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *ComputerLeftClickDragConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u messageCountTokensToolUnionParamConfigsLeftClickDrag) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BrowserLeftClickDragConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *ComputerLeftClickDragConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + } + return nil +} + +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u messageCountTokensToolUnionParamConfigs) GetLeftMouseDown() (res messageCountTokensToolUnionParamConfigsLeftMouseDown) { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + res.any = &vt.LeftMouseDown + case *ComputerToolsetConfigsParam: + res.any = &vt.LeftMouseDown + } + return res +} + +// Can have the runtime types [*BrowserLeftMouseDownConfigParam], +// [*ComputerLeftMouseDownConfigParam] +type messageCountTokensToolUnionParamConfigsLeftMouseDown struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BrowserLeftMouseDownConfigParam: +// case *anthropic.ComputerLeftMouseDownConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u messageCountTokensToolUnionParamConfigsLeftMouseDown) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u messageCountTokensToolUnionParamConfigsLeftMouseDown) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BrowserLeftMouseDownConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *ComputerLeftMouseDownConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u messageCountTokensToolUnionParamConfigsLeftMouseDown) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BrowserLeftMouseDownConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *ComputerLeftMouseDownConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + } + return nil +} + +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u messageCountTokensToolUnionParamConfigs) GetLeftMouseUp() (res messageCountTokensToolUnionParamConfigsLeftMouseUp) { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + res.any = &vt.LeftMouseUp + case *ComputerToolsetConfigsParam: + res.any = &vt.LeftMouseUp + } + return res +} + +// Can have the runtime types [*BrowserLeftMouseUpConfigParam], +// [*ComputerLeftMouseUpConfigParam] +type messageCountTokensToolUnionParamConfigsLeftMouseUp struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BrowserLeftMouseUpConfigParam: +// case *anthropic.ComputerLeftMouseUpConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u messageCountTokensToolUnionParamConfigsLeftMouseUp) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u messageCountTokensToolUnionParamConfigsLeftMouseUp) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BrowserLeftMouseUpConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *ComputerLeftMouseUpConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u messageCountTokensToolUnionParamConfigsLeftMouseUp) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BrowserLeftMouseUpConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *ComputerLeftMouseUpConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + } + return nil +} + +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u messageCountTokensToolUnionParamConfigs) GetMiddleClick() (res messageCountTokensToolUnionParamConfigsMiddleClick) { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + res.any = &vt.MiddleClick + case *ComputerToolsetConfigsParam: + res.any = &vt.MiddleClick + } + return res +} + +// Can have the runtime types [*BrowserMiddleClickConfigParam], +// [*ComputerMiddleClickConfigParam] +type messageCountTokensToolUnionParamConfigsMiddleClick struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BrowserMiddleClickConfigParam: +// case *anthropic.ComputerMiddleClickConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u messageCountTokensToolUnionParamConfigsMiddleClick) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u messageCountTokensToolUnionParamConfigsMiddleClick) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BrowserMiddleClickConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *ComputerMiddleClickConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u messageCountTokensToolUnionParamConfigsMiddleClick) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BrowserMiddleClickConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *ComputerMiddleClickConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + } + return nil } -func (u *MessageCountTokensToolUnionParam) asAny() any { - if !param.IsOmitted(u.OfTool) { - return u.OfTool - } else if !param.IsOmitted(u.OfBashTool20250124) { - return u.OfBashTool20250124 - } else if !param.IsOmitted(u.OfCodeExecutionTool20250522) { - return u.OfCodeExecutionTool20250522 - } else if !param.IsOmitted(u.OfCodeExecutionTool20250825) { - return u.OfCodeExecutionTool20250825 - } else if !param.IsOmitted(u.OfCodeExecutionTool20260120) { - return u.OfCodeExecutionTool20260120 - } else if !param.IsOmitted(u.OfMemoryTool20250818) { - return u.OfMemoryTool20250818 - } else if !param.IsOmitted(u.OfTextEditor20250124) { - return u.OfTextEditor20250124 - } else if !param.IsOmitted(u.OfTextEditor20250429) { - return u.OfTextEditor20250429 - } else if !param.IsOmitted(u.OfTextEditor20250728) { - return u.OfTextEditor20250728 - } else if !param.IsOmitted(u.OfWebSearchTool20250305) { - return u.OfWebSearchTool20250305 - } else if !param.IsOmitted(u.OfWebFetchTool20250910) { - return u.OfWebFetchTool20250910 - } else if !param.IsOmitted(u.OfWebSearchTool20260209) { - return u.OfWebSearchTool20260209 - } else if !param.IsOmitted(u.OfWebFetchTool20260209) { - return u.OfWebFetchTool20260209 - } else if !param.IsOmitted(u.OfWebFetchTool20260309) { - return u.OfWebFetchTool20260309 - } else if !param.IsOmitted(u.OfToolSearchToolBm25_20251119) { - return u.OfToolSearchToolBm25_20251119 - } else if !param.IsOmitted(u.OfToolSearchToolRegex20251119) { - return u.OfToolSearchToolRegex20251119 +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u messageCountTokensToolUnionParamConfigs) GetMouseMove() (res messageCountTokensToolUnionParamConfigsMouseMove) { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + res.any = &vt.MouseMove + case *ComputerToolsetConfigsParam: + res.any = &vt.MouseMove + } + return res +} + +// Can have the runtime types [*BrowserMouseMoveConfigParam], +// [*ComputerMouseMoveConfigParam] +type messageCountTokensToolUnionParamConfigsMouseMove struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BrowserMouseMoveConfigParam: +// case *anthropic.ComputerMouseMoveConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u messageCountTokensToolUnionParamConfigsMouseMove) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u messageCountTokensToolUnionParamConfigsMouseMove) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BrowserMouseMoveConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *ComputerMouseMoveConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u MessageCountTokensToolUnionParam) GetInputSchema() *ToolInputSchemaParam { - if vt := u.OfTool; vt != nil { - return &vt.InputSchema +func (u messageCountTokensToolUnionParamConfigsMouseMove) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BrowserMouseMoveConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *ComputerMouseMoveConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) } return nil } +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u messageCountTokensToolUnionParamConfigs) GetRightClick() (res messageCountTokensToolUnionParamConfigsRightClick) { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + res.any = &vt.RightClick + case *ComputerToolsetConfigsParam: + res.any = &vt.RightClick + } + return res +} + +// Can have the runtime types [*BrowserRightClickConfigParam], +// [*ComputerRightClickConfigParam] +type messageCountTokensToolUnionParamConfigsRightClick struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BrowserRightClickConfigParam: +// case *anthropic.ComputerRightClickConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u messageCountTokensToolUnionParamConfigsRightClick) AsAny() any { return u.any } + // Returns a pointer to the underlying variant's property, if present. -func (u MessageCountTokensToolUnionParam) GetDescription() *string { - if vt := u.OfTool; vt != nil && vt.Description.Valid() { - return &vt.Description.Value +func (u messageCountTokensToolUnionParamConfigsRightClick) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BrowserRightClickConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *ComputerRightClickConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u MessageCountTokensToolUnionParam) GetEagerInputStreaming() *bool { - if vt := u.OfTool; vt != nil && vt.EagerInputStreaming.Valid() { - return &vt.EagerInputStreaming.Value +func (u messageCountTokensToolUnionParamConfigsRightClick) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BrowserRightClickConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *ComputerRightClickConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) } return nil } +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u messageCountTokensToolUnionParamConfigs) GetScreenshot() (res messageCountTokensToolUnionParamConfigsScreenshot) { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + res.any = &vt.Screenshot + case *ComputerToolsetConfigsParam: + res.any = &vt.Screenshot + } + return res +} + +// Can have the runtime types [*BrowserScreenshotConfigParam], +// [*ComputerScreenshotConfigParam] +type messageCountTokensToolUnionParamConfigsScreenshot struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BrowserScreenshotConfigParam: +// case *anthropic.ComputerScreenshotConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u messageCountTokensToolUnionParamConfigsScreenshot) AsAny() any { return u.any } + // Returns a pointer to the underlying variant's property, if present. -func (u MessageCountTokensToolUnionParam) GetMaxCharacters() *int64 { - if vt := u.OfTextEditor20250728; vt != nil && vt.MaxCharacters.Valid() { - return &vt.MaxCharacters.Value +func (u messageCountTokensToolUnionParamConfigsScreenshot) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BrowserScreenshotConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *ComputerScreenshotConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u MessageCountTokensToolUnionParam) GetUseCache() *bool { - if vt := u.OfWebFetchTool20260309; vt != nil && vt.UseCache.Valid() { - return &vt.UseCache.Value +func (u messageCountTokensToolUnionParamConfigsScreenshot) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BrowserScreenshotConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *ComputerScreenshotConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) } return nil } +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u messageCountTokensToolUnionParamConfigs) GetScroll() (res messageCountTokensToolUnionParamConfigsScroll) { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + res.any = &vt.Scroll + case *ComputerToolsetConfigsParam: + res.any = &vt.Scroll + } + return res +} + +// Can have the runtime types [*BrowserScrollConfigParam], +// [*ComputerScrollConfigParam] +type messageCountTokensToolUnionParamConfigsScroll struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BrowserScrollConfigParam: +// case *anthropic.ComputerScrollConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u messageCountTokensToolUnionParamConfigsScroll) AsAny() any { return u.any } + // Returns a pointer to the underlying variant's property, if present. -func (u MessageCountTokensToolUnionParam) GetName() *string { - if vt := u.OfTool; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfBashTool20250124; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfCodeExecutionTool20250522; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfCodeExecutionTool20250825; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfCodeExecutionTool20260120; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfMemoryTool20250818; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfTextEditor20250124; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfTextEditor20250429; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfTextEditor20250728; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfWebSearchTool20250305; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfWebFetchTool20250910; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfWebSearchTool20260209; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfWebFetchTool20260209; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfWebFetchTool20260309; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfToolSearchToolRegex20251119; vt != nil { - return (*string)(&vt.Name) +func (u messageCountTokensToolUnionParamConfigsScroll) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BrowserScrollConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *ComputerScrollConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u MessageCountTokensToolUnionParam) GetDeferLoading() *bool { - if vt := u.OfTool; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfBashTool20250124; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfCodeExecutionTool20250522; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfCodeExecutionTool20250825; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfCodeExecutionTool20260120; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfMemoryTool20250818; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfTextEditor20250124; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfTextEditor20250429; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfTextEditor20250728; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfWebSearchTool20250305; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfWebFetchTool20250910; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfWebSearchTool20260209; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfWebFetchTool20260209; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfWebFetchTool20260309; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfToolSearchToolRegex20251119; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value +func (u messageCountTokensToolUnionParamConfigsScroll) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BrowserScrollConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *ComputerScrollConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) } return nil } +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u messageCountTokensToolUnionParamConfigs) GetTripleClick() (res messageCountTokensToolUnionParamConfigsTripleClick) { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + res.any = &vt.TripleClick + case *ComputerToolsetConfigsParam: + res.any = &vt.TripleClick + } + return res +} + +// Can have the runtime types [*BrowserTripleClickConfigParam], +// [*ComputerTripleClickConfigParam] +type messageCountTokensToolUnionParamConfigsTripleClick struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BrowserTripleClickConfigParam: +// case *anthropic.ComputerTripleClickConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u messageCountTokensToolUnionParamConfigsTripleClick) AsAny() any { return u.any } + // Returns a pointer to the underlying variant's property, if present. -func (u MessageCountTokensToolUnionParam) GetStrict() *bool { - if vt := u.OfTool; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfBashTool20250124; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfCodeExecutionTool20250522; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfCodeExecutionTool20250825; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfCodeExecutionTool20260120; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfMemoryTool20250818; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfTextEditor20250124; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfTextEditor20250429; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfTextEditor20250728; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfWebSearchTool20250305; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfWebFetchTool20250910; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfWebSearchTool20260209; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfWebFetchTool20260209; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfWebFetchTool20260309; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfToolSearchToolRegex20251119; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value +func (u messageCountTokensToolUnionParamConfigsTripleClick) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BrowserTripleClickConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *ComputerTripleClickConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u MessageCountTokensToolUnionParam) GetType() *string { - if vt := u.OfTool; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfBashTool20250124; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfCodeExecutionTool20250522; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfCodeExecutionTool20250825; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfCodeExecutionTool20260120; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfMemoryTool20250818; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfTextEditor20250124; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfTextEditor20250429; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfTextEditor20250728; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfWebSearchTool20250305; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfWebFetchTool20250910; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfWebSearchTool20260209; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfWebFetchTool20260209; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfWebFetchTool20260309; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfToolSearchToolRegex20251119; vt != nil { - return (*string)(&vt.Type) +func (u messageCountTokensToolUnionParamConfigsTripleClick) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BrowserTripleClickConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *ComputerTripleClickConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) } return nil } +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u messageCountTokensToolUnionParamConfigs) GetType() (res messageCountTokensToolUnionParamConfigsType) { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + res.any = &vt.Type + case *ComputerToolsetConfigsParam: + res.any = &vt.Type + } + return res +} + +// Can have the runtime types [*BrowserTypeConfigParam], [*ComputerTypeConfigParam] +type messageCountTokensToolUnionParamConfigsType struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BrowserTypeConfigParam: +// case *anthropic.ComputerTypeConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u messageCountTokensToolUnionParamConfigsType) AsAny() any { return u.any } + // Returns a pointer to the underlying variant's property, if present. -func (u MessageCountTokensToolUnionParam) GetMaxUses() *int64 { - if vt := u.OfWebSearchTool20250305; vt != nil && vt.MaxUses.Valid() { - return &vt.MaxUses.Value - } else if vt := u.OfWebFetchTool20250910; vt != nil && vt.MaxUses.Valid() { - return &vt.MaxUses.Value - } else if vt := u.OfWebSearchTool20260209; vt != nil && vt.MaxUses.Valid() { - return &vt.MaxUses.Value - } else if vt := u.OfWebFetchTool20260209; vt != nil && vt.MaxUses.Valid() { - return &vt.MaxUses.Value - } else if vt := u.OfWebFetchTool20260309; vt != nil && vt.MaxUses.Valid() { - return &vt.MaxUses.Value +func (u messageCountTokensToolUnionParamConfigsType) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BrowserTypeConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *ComputerTypeConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u MessageCountTokensToolUnionParam) GetMaxContentTokens() *int64 { - if vt := u.OfWebFetchTool20250910; vt != nil && vt.MaxContentTokens.Valid() { - return &vt.MaxContentTokens.Value - } else if vt := u.OfWebFetchTool20260209; vt != nil && vt.MaxContentTokens.Valid() { - return &vt.MaxContentTokens.Value - } else if vt := u.OfWebFetchTool20260309; vt != nil && vt.MaxContentTokens.Valid() { - return &vt.MaxContentTokens.Value +func (u messageCountTokensToolUnionParamConfigsType) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BrowserTypeConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *ComputerTypeConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) } return nil } -// Returns a pointer to the underlying variant's AllowedCallers property, if -// present. -func (u MessageCountTokensToolUnionParam) GetAllowedCallers() []string { - if vt := u.OfTool; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfBashTool20250124; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfCodeExecutionTool20250522; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfCodeExecutionTool20250825; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfCodeExecutionTool20260120; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfMemoryTool20250818; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfTextEditor20250124; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfTextEditor20250429; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfTextEditor20250728; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfWebSearchTool20250305; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfWebFetchTool20250910; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfWebSearchTool20260209; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfWebFetchTool20260209; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfWebFetchTool20260309; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfToolSearchToolRegex20251119; vt != nil { - return vt.AllowedCallers +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u messageCountTokensToolUnionParamConfigs) GetWait() (res messageCountTokensToolUnionParamConfigsWait) { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + res.any = &vt.Wait + case *ComputerToolsetConfigsParam: + res.any = &vt.Wait + } + return res +} + +// Can have the runtime types [*BrowserWaitConfigParam], [*ComputerWaitConfigParam] +type messageCountTokensToolUnionParamConfigsWait struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BrowserWaitConfigParam: +// case *anthropic.ComputerWaitConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u messageCountTokensToolUnionParamConfigsWait) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u messageCountTokensToolUnionParamConfigsWait) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BrowserWaitConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *ComputerWaitConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) } return nil } -// Returns a pointer to the underlying variant's CacheControl property, if present. -func (u MessageCountTokensToolUnionParam) GetCacheControl() *CacheControlEphemeralParam { - if vt := u.OfTool; vt != nil { - return &vt.CacheControl - } else if vt := u.OfBashTool20250124; vt != nil { - return &vt.CacheControl - } else if vt := u.OfCodeExecutionTool20250522; vt != nil { - return &vt.CacheControl - } else if vt := u.OfCodeExecutionTool20250825; vt != nil { - return &vt.CacheControl - } else if vt := u.OfCodeExecutionTool20260120; vt != nil { - return &vt.CacheControl - } else if vt := u.OfMemoryTool20250818; vt != nil { - return &vt.CacheControl - } else if vt := u.OfTextEditor20250124; vt != nil { - return &vt.CacheControl - } else if vt := u.OfTextEditor20250429; vt != nil { - return &vt.CacheControl - } else if vt := u.OfTextEditor20250728; vt != nil { - return &vt.CacheControl - } else if vt := u.OfWebSearchTool20250305; vt != nil { - return &vt.CacheControl - } else if vt := u.OfWebFetchTool20250910; vt != nil { - return &vt.CacheControl - } else if vt := u.OfWebSearchTool20260209; vt != nil { - return &vt.CacheControl - } else if vt := u.OfWebFetchTool20260209; vt != nil { - return &vt.CacheControl - } else if vt := u.OfWebFetchTool20260309; vt != nil { - return &vt.CacheControl - } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil { - return &vt.CacheControl - } else if vt := u.OfToolSearchToolRegex20251119; vt != nil { - return &vt.CacheControl +// Returns a pointer to the underlying variant's property, if present. +func (u messageCountTokensToolUnionParamConfigsWait) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BrowserWaitConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *ComputerWaitConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) } return nil } -// Returns a pointer to the underlying variant's InputExamples property, if -// present. -func (u MessageCountTokensToolUnionParam) GetInputExamples() []map[string]any { - if vt := u.OfTool; vt != nil { - return vt.InputExamples - } else if vt := u.OfBashTool20250124; vt != nil { - return vt.InputExamples - } else if vt := u.OfMemoryTool20250818; vt != nil { - return vt.InputExamples - } else if vt := u.OfTextEditor20250124; vt != nil { - return vt.InputExamples - } else if vt := u.OfTextEditor20250429; vt != nil { - return vt.InputExamples - } else if vt := u.OfTextEditor20250728; vt != nil { - return vt.InputExamples +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u messageCountTokensToolUnionParamConfigs) GetZoom() (res messageCountTokensToolUnionParamConfigsZoom) { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + res.any = &vt.Zoom + case *ComputerToolsetConfigsParam: + res.any = &vt.Zoom + } + return res +} + +// Can have the runtime types [*BrowserZoomConfigParam], [*ComputerZoomConfigParam] +type messageCountTokensToolUnionParamConfigsZoom struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BrowserZoomConfigParam: +// case *anthropic.ComputerZoomConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u messageCountTokensToolUnionParamConfigsZoom) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u messageCountTokensToolUnionParamConfigsZoom) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BrowserZoomConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *ComputerZoomConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u messageCountTokensToolUnionParamConfigsZoom) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BrowserZoomConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *ComputerZoomConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) } return nil } @@ -3887,6 +6706,10 @@ func (u MessageCountTokensToolUnionParam) GetAllowedDomains() []string { return vt.AllowedDomains } else if vt := u.OfWebFetchTool20260309; vt != nil { return vt.AllowedDomains + } else if vt := u.OfWebSearchTool20260318; vt != nil { + return vt.AllowedDomains + } else if vt := u.OfWebFetchTool20260318; vt != nil { + return vt.AllowedDomains } return nil } @@ -3904,6 +6727,10 @@ func (u MessageCountTokensToolUnionParam) GetBlockedDomains() []string { return vt.BlockedDomains } else if vt := u.OfWebFetchTool20260309; vt != nil { return vt.BlockedDomains + } else if vt := u.OfWebSearchTool20260318; vt != nil { + return vt.BlockedDomains + } else if vt := u.OfWebFetchTool20260318; vt != nil { + return vt.BlockedDomains } return nil } @@ -3914,6 +6741,8 @@ func (u MessageCountTokensToolUnionParam) GetUserLocation() *UserLocationParam { return &vt.UserLocation } else if vt := u.OfWebSearchTool20260209; vt != nil { return &vt.UserLocation + } else if vt := u.OfWebSearchTool20260318; vt != nil { + return &vt.UserLocation } return nil } @@ -3926,6 +6755,33 @@ func (u MessageCountTokensToolUnionParam) GetCitations() *CitationsConfigParam { return &vt.Citations } else if vt := u.OfWebFetchTool20260309; vt != nil { return &vt.Citations + } else if vt := u.OfWebFetchTool20260318; vt != nil { + return &vt.Citations + } + return nil +} + +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type MessageCreateParamsContainerUnion struct { + OfContainers *ContainerParams `json:",omitzero,inline"` + OfString param.Opt[string] `json:",omitzero,inline"` + paramUnion +} + +func (u MessageCreateParamsContainerUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfContainers, u.OfString) +} +func (u *MessageCreateParamsContainerUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} + +func (u *MessageCreateParamsContainerUnion) asAny() any { + if !param.IsOmitted(u.OfContainers) { + return u.OfContainers + } else if !param.IsOmitted(u.OfString) { + return &u.OfString.Value } return nil } @@ -3939,6 +6795,13 @@ type MessageDeltaUsage struct { InputTokens int64 `json:"input_tokens" api:"required"` // The cumulative number of output tokens which were used. OutputTokens int64 `json:"output_tokens" api:"required"` + // Breakdown of output tokens by category. + // + // `output_tokens` remains the inclusive, authoritative total used for billing. + // This object provides a read-only decomposition for observability — for example, + // how many of the billed output tokens were spent on internal reasoning that may + // have been summarized before being returned to you. + OutputTokensDetails OutputTokensDetails `json:"output_tokens_details" api:"required"` // The number of server tool requests. ServerToolUse ServerToolUsage `json:"server_tool_use" api:"required"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. @@ -3947,6 +6810,7 @@ type MessageDeltaUsage struct { CacheReadInputTokens respjson.Field InputTokens respjson.Field OutputTokens respjson.Field + OutputTokensDetails respjson.Field ServerToolUse respjson.Field ExtraFields map[string]respjson.Field raw string @@ -3962,7 +6826,7 @@ func (r *MessageDeltaUsage) UnmarshalJSON(data []byte) error { // The properties Content, Role are required. type MessageParam struct { Content []ContentBlockParamUnion `json:"content,omitzero" api:"required"` - // Any of "user", "assistant". + // Any of "user", "assistant", "system". Role MessageParamRole `json:"role,omitzero" api:"required"` paramObj } @@ -3994,6 +6858,7 @@ type MessageParamRole string const ( MessageParamRoleUser MessageParamRole = "user" MessageParamRoleAssistant MessageParamRole = "assistant" + MessageParamRoleSystem MessageParamRole = "system" ) type MessageTokensCount struct { @@ -4032,13 +6897,23 @@ func (r *MetadataParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The model that will complete your prompt.\n\nSee -// [models](https://docs.anthropic.com/en/docs/models-overview) for additional +// The model that will complete your prompt. +// +// See [models](https://docs.anthropic.com/en/docs/models-overview) for additional // details and options. type Model = string const ( - ModelClaudeOpus4_7 Model = "claude-opus-4-7" + ModelClaudeSonnet5 Model = "claude-sonnet-5" + ModelClaudeFable5 Model = "claude-fable-5" + ModelClaudeMythos5 Model = "claude-mythos-5" + ModelClaudeOpus5 Model = "claude-opus-5" + ModelClaudeOpus4_8 Model = "claude-opus-4-8" + ModelClaudeOpus4_7 Model = "claude-opus-4-7" + // Deprecated: Will reach end-of-life on June 30, 2026. Please migrate to + // claude-mythos-5. Visit + // https://docs.anthropic.com/en/docs/resources/model-deprecations for more + // information. ModelClaudeMythosPreview Model = "claude-mythos-preview" ModelClaudeOpus4_6 Model = "claude-opus-4-6" ModelClaudeSonnet4_6 Model = "claude-sonnet-4-6" @@ -4048,29 +6923,6 @@ const ( ModelClaudeOpus4_5_20251101 Model = "claude-opus-4-5-20251101" ModelClaudeSonnet4_5 Model = "claude-sonnet-4-5" ModelClaudeSonnet4_5_20250929 Model = "claude-sonnet-4-5-20250929" - ModelClaudeOpus4_1 Model = "claude-opus-4-1" - ModelClaudeOpus4_1_20250805 Model = "claude-opus-4-1-20250805" - // Deprecated: Will reach end-of-life on June 15th, 2026. Please migrate to a newer - // model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for - // more information. - ModelClaudeOpus4_0 Model = "claude-opus-4-0" - // Deprecated: Will reach end-of-life on June 15th, 2026. Please migrate to a newer - // model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for - // more information. - ModelClaudeOpus4_20250514 Model = "claude-opus-4-20250514" - // Deprecated: Will reach end-of-life on June 15th, 2026. Please migrate to a newer - // model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for - // more information. - ModelClaudeSonnet4_0 Model = "claude-sonnet-4-0" - // Deprecated: Will reach end-of-life on June 15th, 2026. Please migrate to a newer - // model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for - // more information. - ModelClaudeSonnet4_20250514 Model = "claude-sonnet-4-20250514" - // Deprecated: Will reach end-of-life on April 20th, 2026. Please migrate to - // claude-haiku-4-5. Visit - // https://docs.anthropic.com/en/docs/resources/model-deprecations for more - // information. - ModelClaude_3_Haiku_20240307 Model = "claude-3-haiku-20240307" ) type OutputConfigParam struct { @@ -4103,6 +6955,30 @@ const ( OutputConfigEffortMax OutputConfigEffort = "max" ) +type OutputTokensDetails struct { + // Number of output tokens the model generated as internal reasoning, including the + // thinking-block delimiter tokens. + // + // Reflects the raw reasoning the model produced, not the (possibly shorter) + // summarized thinking text returned in the response body. Computed by + // re-tokenizing the raw reasoning text, so it may differ from the model's exact + // generation count by a small number of tokens. Always ≤ `output_tokens`; + // `output_tokens - thinking_tokens` approximates the non-reasoning output. + ThinkingTokens int64 `json:"thinking_tokens" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ThinkingTokens respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r OutputTokensDetails) RawJSON() string { return r.JSON.raw } +func (r *OutputTokensDetails) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + type PlainTextSource struct { Data string `json:"data" api:"required"` MediaType constant.TextPlain `json:"media_type" default:"text/plain"` @@ -4329,6 +7205,8 @@ type ContentBlockStartEventContentBlockUnion struct { Caller ContentBlockStartEventContentBlockUnionCaller `json:"caller"` Input any `json:"input"` Name string `json:"name"` + // This field is from variant [ToolUseBlock]. + ToolsetName string `json:"toolset_name"` // This field is a union of [WebSearchToolResultBlockContentUnion], // [WebFetchToolResultBlockContentUnion], // [CodeExecutionToolResultBlockContentUnion], @@ -4340,20 +7218,21 @@ type ContentBlockStartEventContentBlockUnion struct { // This field is from variant [ContainerUploadBlock]. FileID string `json:"file_id"` JSON struct { - Citations respjson.Field - Text respjson.Field - Type respjson.Field - Signature respjson.Field - Thinking respjson.Field - Data respjson.Field - ID respjson.Field - Caller respjson.Field - Input respjson.Field - Name respjson.Field - Content respjson.Field - ToolUseID respjson.Field - FileID respjson.Field - raw string + Citations respjson.Field + Text respjson.Field + Type respjson.Field + Signature respjson.Field + Thinking respjson.Field + Data respjson.Field + ID respjson.Field + Caller respjson.Field + Input respjson.Field + Name respjson.Field + ToolsetName respjson.Field + Content respjson.Field + ToolUseID respjson.Field + FileID respjson.Field + raw string } `json:"-"` } @@ -4630,16 +7509,297 @@ type ContentBlockStartEventContentBlockUnionContentContent struct { } `json:"-"` } -func (r *ContentBlockStartEventContentBlockUnionContentContent) UnmarshalJSON(data []byte) error { +func (r *ContentBlockStartEventContentBlockUnionContentContent) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type ContentBlockStopEvent struct { + Index int64 `json:"index" api:"required"` + Type constant.ContentBlockStop `json:"type" default:"content_block_stop"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Index respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r ContentBlockStopEvent) RawJSON() string { return r.JSON.raw } +func (r *ContentBlockStopEvent) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type MessageDeltaEvent struct { + Delta MessageDeltaEventDelta `json:"delta" api:"required"` + Type constant.MessageDelta `json:"type" default:"message_delta"` + // Billing and rate-limit usage. + // + // Anthropic's API bills and rate-limits by token counts, as tokens represent the + // underlying cost to our systems. + // + // Under the hood, the API transforms requests into a format suitable for the + // model. The model's output then goes through a parsing stage before becoming an + // API response. As a result, the token counts in `usage` will not match one-to-one + // with the exact visible content of an API request or response. + // + // For example, `output_tokens` will be non-zero, even for an empty string response + // from Claude. + // + // Total input tokens in a request is the summation of `input_tokens`, + // `cache_creation_input_tokens`, and `cache_read_input_tokens`. + Usage MessageDeltaUsage `json:"usage" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Delta respjson.Field + Type respjson.Field + Usage respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r MessageDeltaEvent) RawJSON() string { return r.JSON.raw } +func (r *MessageDeltaEvent) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type MessageDeltaEventDelta struct { + // Information about the container used in the request (for the code execution + // tool) + Container Container `json:"container" api:"required"` + // Structured information about a refusal. + StopDetails RefusalStopDetails `json:"stop_details" api:"required"` + // Any of "end_turn", "max_tokens", "stop_sequence", "tool_use", "pause_turn", + // "refusal", "model_context_window_exceeded". + StopReason StopReason `json:"stop_reason" api:"required"` + StopSequence string `json:"stop_sequence" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Container respjson.Field + StopDetails respjson.Field + StopReason respjson.Field + StopSequence respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r MessageDeltaEventDelta) RawJSON() string { return r.JSON.raw } +func (r *MessageDeltaEventDelta) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type MessageStartEvent struct { + Message Message `json:"message" api:"required"` + Type constant.MessageStart `json:"type" default:"message_start"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Message respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r MessageStartEvent) RawJSON() string { return r.JSON.raw } +func (r *MessageStartEvent) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type MessageStopEvent struct { + Type constant.MessageStop `json:"type" default:"message_stop"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r MessageStopEvent) RawJSON() string { return r.JSON.raw } +func (r *MessageStopEvent) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// MessageStreamEventUnion contains all possible properties and values from +// [MessageStartEvent], [MessageDeltaEvent], [MessageStopEvent], +// [ContentBlockStartEvent], [ContentBlockDeltaEvent], [ContentBlockStopEvent]. +// +// Use the [MessageStreamEventUnion.AsAny] method to switch on the variant. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type MessageStreamEventUnion struct { + // This field is from variant [MessageStartEvent]. + Message Message `json:"message"` + // Any of "message_start", "message_delta", "message_stop", "content_block_start", + // "content_block_delta", "content_block_stop". + Type string `json:"type"` + // This field is a union of [MessageDeltaEventDelta], [RawContentBlockDeltaUnion] + Delta MessageStreamEventUnionDelta `json:"delta"` + // This field is from variant [MessageDeltaEvent]. + Usage MessageDeltaUsage `json:"usage"` + // This field is from variant [ContentBlockStartEvent]. + ContentBlock ContentBlockStartEventContentBlockUnion `json:"content_block"` + Index int64 `json:"index"` + JSON struct { + Message respjson.Field + Type respjson.Field + Delta respjson.Field + Usage respjson.Field + ContentBlock respjson.Field + Index respjson.Field + raw string + } `json:"-"` +} + +// anyMessageStreamEvent is implemented by each variant of +// [MessageStreamEventUnion] to add type safety for the return type of +// [MessageStreamEventUnion.AsAny] +type anyMessageStreamEvent interface { + implMessageStreamEventUnion() +} + +func (MessageStartEvent) implMessageStreamEventUnion() {} +func (MessageDeltaEvent) implMessageStreamEventUnion() {} +func (MessageStopEvent) implMessageStreamEventUnion() {} +func (ContentBlockStartEvent) implMessageStreamEventUnion() {} +func (ContentBlockDeltaEvent) implMessageStreamEventUnion() {} +func (ContentBlockStopEvent) implMessageStreamEventUnion() {} + +// Use the following switch statement to find the correct variant +// +// switch variant := MessageStreamEventUnion.AsAny().(type) { +// case anthropic.MessageStartEvent: +// case anthropic.MessageDeltaEvent: +// case anthropic.MessageStopEvent: +// case anthropic.ContentBlockStartEvent: +// case anthropic.ContentBlockDeltaEvent: +// case anthropic.ContentBlockStopEvent: +// default: +// fmt.Errorf("no variant present") +// } +func (u MessageStreamEventUnion) AsAny() anyMessageStreamEvent { + switch u.Type { + case "message_start": + return u.AsMessageStart() + case "message_delta": + return u.AsMessageDelta() + case "message_stop": + return u.AsMessageStop() + case "content_block_start": + return u.AsContentBlockStart() + case "content_block_delta": + return u.AsContentBlockDelta() + case "content_block_stop": + return u.AsContentBlockStop() + } + return nil +} + +func (u MessageStreamEventUnion) AsMessageStart() (v MessageStartEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u MessageStreamEventUnion) AsMessageDelta() (v MessageDeltaEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u MessageStreamEventUnion) AsMessageStop() (v MessageStopEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u MessageStreamEventUnion) AsContentBlockStart() (v ContentBlockStartEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u MessageStreamEventUnion) AsContentBlockDelta() (v ContentBlockDeltaEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u MessageStreamEventUnion) AsContentBlockStop() (v ContentBlockStopEvent) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +// Returns the unmodified JSON received from the API +func (u MessageStreamEventUnion) RawJSON() string { return u.JSON.raw } + +func (r *MessageStreamEventUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// MessageStreamEventUnionDelta is an implicit subunion of +// [MessageStreamEventUnion]. MessageStreamEventUnionDelta provides convenient +// access to the sub-properties of the union. +// +// For type safety it is recommended to directly use a variant of the +// [MessageStreamEventUnion]. +type MessageStreamEventUnionDelta struct { + // This field is from variant [MessageDeltaEventDelta]. + Container Container `json:"container"` + // This field is from variant [MessageDeltaEventDelta]. + StopDetails RefusalStopDetails `json:"stop_details"` + // This field is from variant [MessageDeltaEventDelta]. + StopReason StopReason `json:"stop_reason"` + // This field is from variant [MessageDeltaEventDelta]. + StopSequence string `json:"stop_sequence"` + // This field is from variant [RawContentBlockDeltaUnion]. + Text string `json:"text"` + Type string `json:"type"` + // This field is from variant [RawContentBlockDeltaUnion]. + PartialJSON string `json:"partial_json"` + // This field is from variant [RawContentBlockDeltaUnion]. + Citation CitationsDeltaCitationUnion `json:"citation"` + // This field is from variant [RawContentBlockDeltaUnion]. + Thinking string `json:"thinking"` + // This field is from variant [RawContentBlockDeltaUnion]. + Signature string `json:"signature"` + JSON struct { + Container respjson.Field + StopDetails respjson.Field + StopReason respjson.Field + StopSequence respjson.Field + Text respjson.Field + Type respjson.Field + PartialJSON respjson.Field + Citation respjson.Field + Thinking respjson.Field + Signature respjson.Field + raw string + } `json:"-"` +} + +func (r *MessageStreamEventUnionDelta) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type ContentBlockStopEvent struct { - Index int64 `json:"index" api:"required"` - Type constant.ContentBlockStop `json:"type" default:"content_block_stop"` +type RedactedThinkingBlock struct { + // The contents of this redacted thinking block, returned when portions of the + // model's thinking were safety-redacted. This field is opaque and encrypted, with + // no readable content. + // + // Pass `redacted_thinking` blocks back to the API unchanged when continuing a + // multi-turn conversation. + // + // See + // [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking#redacted-thinking-blocks) + // for details. + Data string `json:"data" api:"required"` + Type constant.RedactedThinking `json:"type" default:"redacted_thinking"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { - Index respjson.Field + Data respjson.Field Type respjson.Field ExtraFields map[string]respjson.Field raw string @@ -4647,79 +7807,143 @@ type ContentBlockStopEvent struct { } // Returns the unmodified JSON received from the API -func (r ContentBlockStopEvent) RawJSON() string { return r.JSON.raw } -func (r *ContentBlockStopEvent) UnmarshalJSON(data []byte) error { +func (r RedactedThinkingBlock) RawJSON() string { return r.JSON.raw } +func (r *RedactedThinkingBlock) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type MessageDeltaEvent struct { - Delta MessageDeltaEventDelta `json:"delta" api:"required"` - Type constant.MessageDelta `json:"type" default:"message_delta"` - // Billing and rate-limit usage. - // - // Anthropic's API bills and rate-limits by token counts, as tokens represent the - // underlying cost to our systems. - // - // Under the hood, the API transforms requests into a format suitable for the - // model. The model's output then goes through a parsing stage before becoming an - // API response. As a result, the token counts in `usage` will not match one-to-one - // with the exact visible content of an API request or response. +// The properties Data, Type are required. +type RedactedThinkingBlockParam struct { + // The `data` value of this redacted thinking block, exactly as returned by the API + // in a previous response. Opaque and encrypted; pass it back unchanged. + Data string `json:"data" api:"required"` + // This field can be elided, and will marshal its zero value as + // "redacted_thinking". + Type constant.RedactedThinking `json:"type" default:"redacted_thinking"` + paramObj +} + +func (r RedactedThinkingBlockParam) MarshalJSON() (data []byte, err error) { + type shadow RedactedThinkingBlockParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *RedactedThinkingBlockParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Structured information about a refusal. +type RefusalStopDetails struct { + // The policy category that triggered a refusal. // - // For example, `output_tokens` will be non-zero, even for an empty string response - // from Claude. + // Any of "cyber", "bio", "frontier_llm", "reasoning_extraction", "general_harms". + Category RefusalStopDetailsCategory `json:"category" api:"required"` + // Human-readable explanation of the refusal. // - // Total input tokens in a request is the summation of `input_tokens`, - // `cache_creation_input_tokens`, and `cache_read_input_tokens`. - Usage MessageDeltaUsage `json:"usage" api:"required"` + // This text is not guaranteed to be stable. `null` when no explanation is + // available for the category. + Explanation string `json:"explanation" api:"required"` + Type constant.Refusal `json:"type" default:"refusal"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { - Delta respjson.Field + Category respjson.Field + Explanation respjson.Field Type respjson.Field - Usage respjson.Field ExtraFields map[string]respjson.Field raw string } `json:"-"` } // Returns the unmodified JSON received from the API -func (r MessageDeltaEvent) RawJSON() string { return r.JSON.raw } -func (r *MessageDeltaEvent) UnmarshalJSON(data []byte) error { +func (r RefusalStopDetails) RawJSON() string { return r.JSON.raw } +func (r *RefusalStopDetails) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type MessageDeltaEventDelta struct { - // Information about the container used in the request (for the code execution - // tool) - Container Container `json:"container" api:"required"` - // Structured information about a refusal. - StopDetails RefusalStopDetails `json:"stop_details" api:"required"` - // Any of "end_turn", "max_tokens", "stop_sequence", "tool_use", "pause_turn", - // "refusal". - StopReason StopReason `json:"stop_reason" api:"required"` - StopSequence string `json:"stop_sequence" api:"required"` +// The policy category that triggered a refusal. +type RefusalStopDetailsCategory string + +const ( + RefusalStopDetailsCategoryCyber RefusalStopDetailsCategory = "cyber" + RefusalStopDetailsCategoryBio RefusalStopDetailsCategory = "bio" + RefusalStopDetailsCategoryFrontierLLM RefusalStopDetailsCategory = "frontier_llm" + RefusalStopDetailsCategoryReasoningExtraction RefusalStopDetailsCategory = "reasoning_extraction" + RefusalStopDetailsCategoryGeneralHarms RefusalStopDetailsCategory = "general_harms" +) + +// The properties Content, Source, Title, Type are required. +type SearchResultBlockParam struct { + Content []TextBlockParam `json:"content,omitzero" api:"required"` + Source string `json:"source" api:"required"` + Title string `json:"title" api:"required"` + // Create a cache control breakpoint at this content block. + CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` + Citations CitationsConfigParam `json:"citations,omitzero"` + // This field can be elided, and will marshal its zero value as "search_result". + Type constant.SearchResult `json:"type" default:"search_result"` + paramObj +} + +func (r SearchResultBlockParam) MarshalJSON() (data []byte, err error) { + type shadow SearchResultBlockParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *SearchResultBlockParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Tool invocation generated by a server-side tool. +type ServerToolCaller struct { + ToolID string `json:"tool_id" api:"required"` + Type constant.CodeExecution20250825 `json:"type" default:"code_execution_20250825"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { - Container respjson.Field - StopDetails respjson.Field - StopReason respjson.Field - StopSequence respjson.Field - ExtraFields map[string]respjson.Field - raw string + ToolID respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string } `json:"-"` } // Returns the unmodified JSON received from the API -func (r MessageDeltaEventDelta) RawJSON() string { return r.JSON.raw } -func (r *MessageDeltaEventDelta) UnmarshalJSON(data []byte) error { +func (r ServerToolCaller) RawJSON() string { return r.JSON.raw } +func (r *ServerToolCaller) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type MessageStartEvent struct { - Message Message `json:"message" api:"required"` - Type constant.MessageStart `json:"type" default:"message_start"` +// ToParam converts this ServerToolCaller to a ServerToolCallerParam. +// +// Warning: the fields of the param type will not be present. ToParam should only +// be used at the last possible moment before sending a request. Test for this with +// ServerToolCallerParam.Overrides() +func (r ServerToolCaller) ToParam() ServerToolCallerParam { + return param.Override[ServerToolCallerParam](json.RawMessage(r.RawJSON())) +} + +// Tool invocation generated by a server-side tool. +// +// The properties ToolID, Type are required. +type ServerToolCallerParam struct { + ToolID string `json:"tool_id" api:"required"` + // This field can be elided, and will marshal its zero value as + // "code_execution_20250825". + Type constant.CodeExecution20250825 `json:"type" default:"code_execution_20250825"` + paramObj +} + +func (r ServerToolCallerParam) MarshalJSON() (data []byte, err error) { + type shadow ServerToolCallerParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *ServerToolCallerParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type ServerToolCaller20260120 struct { + ToolID string `json:"tool_id" api:"required"` + Type constant.CodeExecution20260120 `json:"type" default:"code_execution_20260120"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { - Message respjson.Field + ToolID respjson.Field Type respjson.Field ExtraFields map[string]respjson.Field raw string @@ -4727,15 +7951,73 @@ type MessageStartEvent struct { } // Returns the unmodified JSON received from the API -func (r MessageStartEvent) RawJSON() string { return r.JSON.raw } -func (r *MessageStartEvent) UnmarshalJSON(data []byte) error { +func (r ServerToolCaller20260120) RawJSON() string { return r.JSON.raw } +func (r *ServerToolCaller20260120) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type MessageStopEvent struct { - Type constant.MessageStop `json:"type" default:"message_stop"` +// ToParam converts this ServerToolCaller20260120 to a +// ServerToolCaller20260120Param. +// +// Warning: the fields of the param type will not be present. ToParam should only +// be used at the last possible moment before sending a request. Test for this with +// ServerToolCaller20260120Param.Overrides() +func (r ServerToolCaller20260120) ToParam() ServerToolCaller20260120Param { + return param.Override[ServerToolCaller20260120Param](json.RawMessage(r.RawJSON())) +} + +// The properties ToolID, Type are required. +type ServerToolCaller20260120Param struct { + ToolID string `json:"tool_id" api:"required"` + // This field can be elided, and will marshal its zero value as + // "code_execution_20260120". + Type constant.CodeExecution20260120 `json:"type" default:"code_execution_20260120"` + paramObj +} + +func (r ServerToolCaller20260120Param) MarshalJSON() (data []byte, err error) { + type shadow ServerToolCaller20260120Param + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *ServerToolCaller20260120Param) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type ServerToolUsage struct { + // The number of web fetch tool requests. + WebFetchRequests int64 `json:"web_fetch_requests" api:"required"` + // The number of web search tool requests. + WebSearchRequests int64 `json:"web_search_requests" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + WebFetchRequests respjson.Field + WebSearchRequests respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r ServerToolUsage) RawJSON() string { return r.JSON.raw } +func (r *ServerToolUsage) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type ServerToolUseBlock struct { + ID string `json:"id" api:"required"` + // Tool invocation directly from the model. + Caller ServerToolUseBlockCallerUnion `json:"caller" api:"required"` + Input any `json:"input" api:"required"` + // Any of "web_search", "web_fetch", "code_execution", "bash_code_execution", + // "text_editor_code_execution", "tool_search_tool_regex", "tool_search_tool_bm25". + Name ServerToolUseBlockName `json:"name" api:"required"` + Type constant.ServerToolUse `json:"type" default:"server_tool_use"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { + ID respjson.Field + Caller respjson.Field + Input respjson.Field + Name respjson.Field Type respjson.Field ExtraFields map[string]respjson.Field raw string @@ -4743,317 +8025,198 @@ type MessageStopEvent struct { } // Returns the unmodified JSON received from the API -func (r MessageStopEvent) RawJSON() string { return r.JSON.raw } -func (r *MessageStopEvent) UnmarshalJSON(data []byte) error { +func (r ServerToolUseBlock) RawJSON() string { return r.JSON.raw } +func (r *ServerToolUseBlock) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// MessageStreamEventUnion contains all possible properties and values from -// [MessageStartEvent], [MessageDeltaEvent], [MessageStopEvent], -// [ContentBlockStartEvent], [ContentBlockDeltaEvent], [ContentBlockStopEvent]. +// ServerToolUseBlockCallerUnion contains all possible properties and values from +// [DirectCaller], [ServerToolCaller], [ServerToolCaller20260120]. // -// Use the [MessageStreamEventUnion.AsAny] method to switch on the variant. +// Use the [ServerToolUseBlockCallerUnion.AsAny] method to switch on the variant. // // Use the methods beginning with 'As' to cast the union to one of its variants. -type MessageStreamEventUnion struct { - // This field is from variant [MessageStartEvent]. - Message Message `json:"message"` - // Any of "message_start", "message_delta", "message_stop", "content_block_start", - // "content_block_delta", "content_block_stop". - Type string `json:"type"` - // This field is a union of [MessageDeltaEventDelta], [RawContentBlockDeltaUnion] - Delta MessageStreamEventUnionDelta `json:"delta"` - // This field is from variant [MessageDeltaEvent]. - Usage MessageDeltaUsage `json:"usage"` - // This field is from variant [ContentBlockStartEvent]. - ContentBlock ContentBlockStartEventContentBlockUnion `json:"content_block"` - Index int64 `json:"index"` - JSON struct { - Message respjson.Field - Type respjson.Field - Delta respjson.Field - Usage respjson.Field - ContentBlock respjson.Field - Index respjson.Field - raw string +type ServerToolUseBlockCallerUnion struct { + // Any of "direct", "code_execution_20250825", "code_execution_20260120". + Type string `json:"type"` + ToolID string `json:"tool_id"` + JSON struct { + Type respjson.Field + ToolID respjson.Field + raw string } `json:"-"` } -// anyMessageStreamEvent is implemented by each variant of -// [MessageStreamEventUnion] to add type safety for the return type of -// [MessageStreamEventUnion.AsAny] -type anyMessageStreamEvent interface { - implMessageStreamEventUnion() +// anyServerToolUseBlockCaller is implemented by each variant of +// [ServerToolUseBlockCallerUnion] to add type safety for the return type of +// [ServerToolUseBlockCallerUnion.AsAny] +type anyServerToolUseBlockCaller interface { + implServerToolUseBlockCallerUnion() } -func (MessageStartEvent) implMessageStreamEventUnion() {} -func (MessageDeltaEvent) implMessageStreamEventUnion() {} -func (MessageStopEvent) implMessageStreamEventUnion() {} -func (ContentBlockStartEvent) implMessageStreamEventUnion() {} -func (ContentBlockDeltaEvent) implMessageStreamEventUnion() {} -func (ContentBlockStopEvent) implMessageStreamEventUnion() {} +func (DirectCaller) implServerToolUseBlockCallerUnion() {} +func (ServerToolCaller) implServerToolUseBlockCallerUnion() {} +func (ServerToolCaller20260120) implServerToolUseBlockCallerUnion() {} // Use the following switch statement to find the correct variant // -// switch variant := MessageStreamEventUnion.AsAny().(type) { -// case anthropic.MessageStartEvent: -// case anthropic.MessageDeltaEvent: -// case anthropic.MessageStopEvent: -// case anthropic.ContentBlockStartEvent: -// case anthropic.ContentBlockDeltaEvent: -// case anthropic.ContentBlockStopEvent: +// switch variant := ServerToolUseBlockCallerUnion.AsAny().(type) { +// case anthropic.DirectCaller: +// case anthropic.ServerToolCaller: +// case anthropic.ServerToolCaller20260120: // default: // fmt.Errorf("no variant present") // } -func (u MessageStreamEventUnion) AsAny() anyMessageStreamEvent { +func (u ServerToolUseBlockCallerUnion) AsAny() anyServerToolUseBlockCaller { switch u.Type { - case "message_start": - return u.AsMessageStart() - case "message_delta": - return u.AsMessageDelta() - case "message_stop": - return u.AsMessageStop() - case "content_block_start": - return u.AsContentBlockStart() - case "content_block_delta": - return u.AsContentBlockDelta() - case "content_block_stop": - return u.AsContentBlockStop() + case "direct": + return u.AsDirect() + case "code_execution_20250825": + return u.AsCodeExecution20250825() + case "code_execution_20260120": + return u.AsCodeExecution20260120() } return nil } -func (u MessageStreamEventUnion) AsMessageStart() (v MessageStartEvent) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u MessageStreamEventUnion) AsMessageDelta() (v MessageDeltaEvent) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u MessageStreamEventUnion) AsMessageStop() (v MessageStopEvent) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u MessageStreamEventUnion) AsContentBlockStart() (v ContentBlockStartEvent) { +func (u ServerToolUseBlockCallerUnion) AsDirect() (v DirectCaller) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return } -func (u MessageStreamEventUnion) AsContentBlockDelta() (v ContentBlockDeltaEvent) { +func (u ServerToolUseBlockCallerUnion) AsCodeExecution20250825() (v ServerToolCaller) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return } -func (u MessageStreamEventUnion) AsContentBlockStop() (v ContentBlockStopEvent) { +func (u ServerToolUseBlockCallerUnion) AsCodeExecution20260120() (v ServerToolCaller20260120) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return } // Returns the unmodified JSON received from the API -func (u MessageStreamEventUnion) RawJSON() string { return u.JSON.raw } - -func (r *MessageStreamEventUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// MessageStreamEventUnionDelta is an implicit subunion of -// [MessageStreamEventUnion]. MessageStreamEventUnionDelta provides convenient -// access to the sub-properties of the union. -// -// For type safety it is recommended to directly use a variant of the -// [MessageStreamEventUnion]. -type MessageStreamEventUnionDelta struct { - // This field is from variant [MessageDeltaEventDelta]. - Container Container `json:"container"` - // This field is from variant [MessageDeltaEventDelta]. - StopDetails RefusalStopDetails `json:"stop_details"` - // This field is from variant [MessageDeltaEventDelta]. - StopReason StopReason `json:"stop_reason"` - // This field is from variant [MessageDeltaEventDelta]. - StopSequence string `json:"stop_sequence"` - // This field is from variant [RawContentBlockDeltaUnion]. - Text string `json:"text"` - Type string `json:"type"` - // This field is from variant [RawContentBlockDeltaUnion]. - PartialJSON string `json:"partial_json"` - // This field is from variant [RawContentBlockDeltaUnion]. - Citation CitationsDeltaCitationUnion `json:"citation"` - // This field is from variant [RawContentBlockDeltaUnion]. - Thinking string `json:"thinking"` - // This field is from variant [RawContentBlockDeltaUnion]. - Signature string `json:"signature"` - JSON struct { - Container respjson.Field - StopDetails respjson.Field - StopReason respjson.Field - StopSequence respjson.Field - Text respjson.Field - Type respjson.Field - PartialJSON respjson.Field - Citation respjson.Field - Thinking respjson.Field - Signature respjson.Field - raw string - } `json:"-"` -} +func (u ServerToolUseBlockCallerUnion) RawJSON() string { return u.JSON.raw } -func (r *MessageStreamEventUnionDelta) UnmarshalJSON(data []byte) error { +func (r *ServerToolUseBlockCallerUnion) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type RedactedThinkingBlock struct { - Data string `json:"data" api:"required"` - Type constant.RedactedThinking `json:"type" default:"redacted_thinking"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Data respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} +type ServerToolUseBlockName string -// Returns the unmodified JSON received from the API -func (r RedactedThinkingBlock) RawJSON() string { return r.JSON.raw } -func (r *RedactedThinkingBlock) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} +const ( + ServerToolUseBlockNameWebSearch ServerToolUseBlockName = "web_search" + ServerToolUseBlockNameWebFetch ServerToolUseBlockName = "web_fetch" + ServerToolUseBlockNameCodeExecution ServerToolUseBlockName = "code_execution" + ServerToolUseBlockNameBashCodeExecution ServerToolUseBlockName = "bash_code_execution" + ServerToolUseBlockNameTextEditorCodeExecution ServerToolUseBlockName = "text_editor_code_execution" + ServerToolUseBlockNameToolSearchToolRegex ServerToolUseBlockName = "tool_search_tool_regex" + ServerToolUseBlockNameToolSearchToolBm25 ServerToolUseBlockName = "tool_search_tool_bm25" +) -// The properties Data, Type are required. -type RedactedThinkingBlockParam struct { - Data string `json:"data" api:"required"` - // This field can be elided, and will marshal its zero value as - // "redacted_thinking". - Type constant.RedactedThinking `json:"type" default:"redacted_thinking"` +// The properties ID, Input, Name, Type are required. +type ServerToolUseBlockParam struct { + ID string `json:"id" api:"required"` + Input any `json:"input,omitzero" api:"required"` + // Any of "web_search", "web_fetch", "code_execution", "bash_code_execution", + // "text_editor_code_execution", "tool_search_tool_regex", "tool_search_tool_bm25". + Name ServerToolUseBlockParamName `json:"name,omitzero" api:"required"` + // Create a cache control breakpoint at this content block. + CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` + // Tool invocation directly from the model. + Caller ServerToolUseBlockParamCallerUnion `json:"caller,omitzero"` + // This field can be elided, and will marshal its zero value as "server_tool_use". + Type constant.ServerToolUse `json:"type" default:"server_tool_use"` paramObj } -func (r RedactedThinkingBlockParam) MarshalJSON() (data []byte, err error) { - type shadow RedactedThinkingBlockParam +func (r ServerToolUseBlockParam) MarshalJSON() (data []byte, err error) { + type shadow ServerToolUseBlockParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *RedactedThinkingBlockParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Structured information about a refusal. -type RefusalStopDetails struct { - // The policy category that triggered the refusal. - // - // `null` when the refusal doesn't map to a named category. - // - // Any of "cyber", "bio". - Category RefusalStopDetailsCategory `json:"category" api:"required"` - // Human-readable explanation of the refusal. - // - // This text is not guaranteed to be stable. `null` when no explanation is - // available for the category. - Explanation string `json:"explanation" api:"required"` - Type constant.Refusal `json:"type" default:"refusal"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Category respjson.Field - Explanation respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r RefusalStopDetails) RawJSON() string { return r.JSON.raw } -func (r *RefusalStopDetails) UnmarshalJSON(data []byte) error { +func (r *ServerToolUseBlockParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The policy category that triggered the refusal. -// -// `null` when the refusal doesn't map to a named category. -type RefusalStopDetailsCategory string +type ServerToolUseBlockParamName string const ( - RefusalStopDetailsCategoryCyber RefusalStopDetailsCategory = "cyber" - RefusalStopDetailsCategoryBio RefusalStopDetailsCategory = "bio" + ServerToolUseBlockParamNameWebSearch ServerToolUseBlockParamName = "web_search" + ServerToolUseBlockParamNameWebFetch ServerToolUseBlockParamName = "web_fetch" + ServerToolUseBlockParamNameCodeExecution ServerToolUseBlockParamName = "code_execution" + ServerToolUseBlockParamNameBashCodeExecution ServerToolUseBlockParamName = "bash_code_execution" + ServerToolUseBlockParamNameTextEditorCodeExecution ServerToolUseBlockParamName = "text_editor_code_execution" + ServerToolUseBlockParamNameToolSearchToolRegex ServerToolUseBlockParamName = "tool_search_tool_regex" + ServerToolUseBlockParamNameToolSearchToolBm25 ServerToolUseBlockParamName = "tool_search_tool_bm25" ) -// The properties Content, Source, Title, Type are required. -type SearchResultBlockParam struct { - Content []TextBlockParam `json:"content,omitzero" api:"required"` - Source string `json:"source" api:"required"` - Title string `json:"title" api:"required"` - // Create a cache control breakpoint at this content block. - CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` - Citations CitationsConfigParam `json:"citations,omitzero"` - // This field can be elided, and will marshal its zero value as "search_result". - Type constant.SearchResult `json:"type" default:"search_result"` - paramObj +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type ServerToolUseBlockParamCallerUnion struct { + OfDirect *DirectCallerParam `json:",omitzero,inline"` + OfCodeExecution20250825 *ServerToolCallerParam `json:",omitzero,inline"` + OfCodeExecution20260120 *ServerToolCaller20260120Param `json:",omitzero,inline"` + paramUnion } -func (r SearchResultBlockParam) MarshalJSON() (data []byte, err error) { - type shadow SearchResultBlockParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *SearchResultBlockParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +func (u ServerToolUseBlockParamCallerUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfDirect, u.OfCodeExecution20250825, u.OfCodeExecution20260120) } - -// Tool invocation generated by a server-side tool. -type ServerToolCaller struct { - ToolID string `json:"tool_id" api:"required"` - Type constant.CodeExecution20250825 `json:"type" default:"code_execution_20250825"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ToolID respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +func (u *ServerToolUseBlockParamCallerUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) } -// Returns the unmodified JSON received from the API -func (r ServerToolCaller) RawJSON() string { return r.JSON.raw } -func (r *ServerToolCaller) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +func (u *ServerToolUseBlockParamCallerUnion) asAny() any { + if !param.IsOmitted(u.OfDirect) { + return u.OfDirect + } else if !param.IsOmitted(u.OfCodeExecution20250825) { + return u.OfCodeExecution20250825 + } else if !param.IsOmitted(u.OfCodeExecution20260120) { + return u.OfCodeExecution20260120 + } + return nil } -// ToParam converts this ServerToolCaller to a ServerToolCallerParam. -// -// Warning: the fields of the param type will not be present. ToParam should only -// be used at the last possible moment before sending a request. Test for this with -// ServerToolCallerParam.Overrides() -func (r ServerToolCaller) ToParam() ServerToolCallerParam { - return param.Override[ServerToolCallerParam](json.RawMessage(r.RawJSON())) +// Returns a pointer to the underlying variant's property, if present. +func (u ServerToolUseBlockParamCallerUnion) GetType() *string { + if vt := u.OfDirect; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfCodeExecution20250825; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfCodeExecution20260120; vt != nil { + return (*string)(&vt.Type) + } + return nil } -// Tool invocation generated by a server-side tool. -// -// The properties ToolID, Type are required. -type ServerToolCallerParam struct { - ToolID string `json:"tool_id" api:"required"` - // This field can be elided, and will marshal its zero value as - // "code_execution_20250825". - Type constant.CodeExecution20250825 `json:"type" default:"code_execution_20250825"` - paramObj +// Returns a pointer to the underlying variant's property, if present. +func (u ServerToolUseBlockParamCallerUnion) GetToolID() *string { + if vt := u.OfCodeExecution20250825; vt != nil { + return (*string)(&vt.ToolID) + } else if vt := u.OfCodeExecution20260120; vt != nil { + return (*string)(&vt.ToolID) + } + return nil } -func (r ServerToolCallerParam) MarshalJSON() (data []byte, err error) { - type shadow ServerToolCallerParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ServerToolCallerParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +func init() { + apijson.RegisterUnion[ServerToolUseBlockParamCallerUnion]( + "type", + apijson.Discriminator[DirectCallerParam]("direct"), + apijson.Discriminator[ServerToolCallerParam]("code_execution_20250825"), + apijson.Discriminator[ServerToolCaller20260120Param]("code_execution_20260120"), + ) } -type ServerToolCaller20260120 struct { - ToolID string `json:"tool_id" api:"required"` - Type constant.CodeExecution20260120 `json:"type" default:"code_execution_20260120"` +type SignatureDelta struct { + // The `signature` for this thinking block: an opaque value used to verify that the + // block was generated by Claude when it is passed back to the API. Delivered in a + // `signature_delta` event just before the block's `content_block_stop` event. + Signature string `json:"signature" api:"required"` + Type constant.SignatureDelta `json:"type" default:"signature_delta"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { - ToolID respjson.Field + Signature respjson.Field Type respjson.Field ExtraFields map[string]respjson.Field raw string @@ -5061,73 +8224,67 @@ type ServerToolCaller20260120 struct { } // Returns the unmodified JSON received from the API -func (r ServerToolCaller20260120) RawJSON() string { return r.JSON.raw } -func (r *ServerToolCaller20260120) UnmarshalJSON(data []byte) error { +func (r SignatureDelta) RawJSON() string { return r.JSON.raw } +func (r *SignatureDelta) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// ToParam converts this ServerToolCaller20260120 to a -// ServerToolCaller20260120Param. +// Specification for a skill to be loaded in a container (request model). // -// Warning: the fields of the param type will not be present. ToParam should only -// be used at the last possible moment before sending a request. Test for this with -// ServerToolCaller20260120Param.Overrides() -func (r ServerToolCaller20260120) ToParam() ServerToolCaller20260120Param { - return param.Override[ServerToolCaller20260120Param](json.RawMessage(r.RawJSON())) -} - -// The properties ToolID, Type are required. -type ServerToolCaller20260120Param struct { - ToolID string `json:"tool_id" api:"required"` - // This field can be elided, and will marshal its zero value as - // "code_execution_20260120". - Type constant.CodeExecution20260120 `json:"type" default:"code_execution_20260120"` +// The properties SkillID, Type are required. +type SkillParams struct { + // Skill ID + SkillID string `json:"skill_id" api:"required"` + // Type of skill - either 'anthropic' (built-in) or 'custom' (user-defined) + // + // Any of "anthropic", "custom". + Type SkillParamsType `json:"type,omitzero" api:"required"` + // Skill version or 'latest' for most recent version + Version param.Opt[string] `json:"version,omitzero"` paramObj } -func (r ServerToolCaller20260120Param) MarshalJSON() (data []byte, err error) { - type shadow ServerToolCaller20260120Param +func (r SkillParams) MarshalJSON() (data []byte, err error) { + type shadow SkillParams return param.MarshalObject(r, (*shadow)(&r)) } -func (r *ServerToolCaller20260120Param) UnmarshalJSON(data []byte) error { +func (r *SkillParams) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type ServerToolUsage struct { - // The number of web fetch tool requests. - WebFetchRequests int64 `json:"web_fetch_requests" api:"required"` - // The number of web search tool requests. - WebSearchRequests int64 `json:"web_search_requests" api:"required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - WebFetchRequests respjson.Field - WebSearchRequests respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} +// Type of skill - either 'anthropic' (built-in) or 'custom' (user-defined) +type SkillParamsType string -// Returns the unmodified JSON received from the API -func (r ServerToolUsage) RawJSON() string { return r.JSON.raw } -func (r *ServerToolUsage) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} +const ( + SkillParamsTypeAnthropic SkillParamsType = "anthropic" + SkillParamsTypeCustom SkillParamsType = "custom" +) -type ServerToolUseBlock struct { - ID string `json:"id" api:"required"` - // Tool invocation directly from the model. - Caller ServerToolUseBlockCallerUnion `json:"caller" api:"required"` - Input any `json:"input" api:"required"` - // Any of "web_search", "web_fetch", "code_execution", "bash_code_execution", - // "text_editor_code_execution", "tool_search_tool_regex", "tool_search_tool_bm25". - Name ServerToolUseBlockName `json:"name" api:"required"` - Type constant.ServerToolUse `json:"type" default:"server_tool_use"` +type StopReason string + +const ( + StopReasonEndTurn StopReason = "end_turn" + StopReasonMaxTokens StopReason = "max_tokens" + StopReasonStopSequence StopReason = "stop_sequence" + StopReasonToolUse StopReason = "tool_use" + StopReasonPauseTurn StopReason = "pause_turn" + StopReasonRefusal StopReason = "refusal" + StopReasonModelContextWindowExceeded StopReason = "model_context_window_exceeded" +) + +type TextBlock struct { + // Citations supporting the text block. + // + // The type of citation returned will depend on the type of document being cited. + // Citing a PDF results in `page_location`, plain text results in `char_location`, + // and content document results in `content_block_location`. + Citations []TextCitationUnion `json:"citations" api:"required"` + Text string `json:"text" api:"required"` + Type constant.Text `json:"type" default:"text"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { - ID respjson.Field - Caller respjson.Field - Input respjson.Field - Name respjson.Field + Citations respjson.Field + Text respjson.Field Type respjson.Field ExtraFields map[string]respjson.Field raw string @@ -5135,195 +8292,362 @@ type ServerToolUseBlock struct { } // Returns the unmodified JSON received from the API -func (r ServerToolUseBlock) RawJSON() string { return r.JSON.raw } -func (r *ServerToolUseBlock) UnmarshalJSON(data []byte) error { +func (r TextBlock) RawJSON() string { return r.JSON.raw } +func (r *TextBlock) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// ServerToolUseBlockCallerUnion contains all possible properties and values from -// [DirectCaller], [ServerToolCaller], [ServerToolCaller20260120]. +// The properties Text, Type are required. +type TextBlockParam struct { + Text string `json:"text" api:"required"` + Citations []TextCitationParamUnion `json:"citations,omitzero"` + // Create a cache control breakpoint at this content block. + CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` + // This field can be elided, and will marshal its zero value as "text". + Type constant.Text `json:"type" default:"text"` + paramObj +} + +func (r TextBlockParam) MarshalJSON() (data []byte, err error) { + type shadow TextBlockParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *TextBlockParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// TextCitationUnion contains all possible properties and values from +// [CitationCharLocation], [CitationPageLocation], [CitationContentBlockLocation], +// [CitationsWebSearchResultLocation], [CitationsSearchResultLocation]. // -// Use the [ServerToolUseBlockCallerUnion.AsAny] method to switch on the variant. +// Use the [TextCitationUnion.AsAny] method to switch on the variant. // // Use the methods beginning with 'As' to cast the union to one of its variants. -type ServerToolUseBlockCallerUnion struct { - // Any of "direct", "code_execution_20250825", "code_execution_20260120". - Type string `json:"type"` - ToolID string `json:"tool_id"` +type TextCitationUnion struct { + CitedText string `json:"cited_text"` + DocumentIndex int64 `json:"document_index"` + DocumentTitle string `json:"document_title"` + // This field is from variant [CitationCharLocation]. + EndCharIndex int64 `json:"end_char_index"` + FileID string `json:"file_id"` + // This field is from variant [CitationCharLocation]. + StartCharIndex int64 `json:"start_char_index"` + // Any of "char_location", "page_location", "content_block_location", + // "web_search_result_location", "search_result_location". + Type string `json:"type"` + // This field is from variant [CitationPageLocation]. + EndPageNumber int64 `json:"end_page_number"` + // This field is from variant [CitationPageLocation]. + StartPageNumber int64 `json:"start_page_number"` + EndBlockIndex int64 `json:"end_block_index"` + StartBlockIndex int64 `json:"start_block_index"` + // This field is from variant [CitationsWebSearchResultLocation]. + EncryptedIndex string `json:"encrypted_index"` + Title string `json:"title"` + // This field is from variant [CitationsWebSearchResultLocation]. + URL string `json:"url"` + // This field is from variant [CitationsSearchResultLocation]. + SearchResultIndex int64 `json:"search_result_index"` + // This field is from variant [CitationsSearchResultLocation]. + Source string `json:"source"` JSON struct { - Type respjson.Field - ToolID respjson.Field - raw string + CitedText respjson.Field + DocumentIndex respjson.Field + DocumentTitle respjson.Field + EndCharIndex respjson.Field + FileID respjson.Field + StartCharIndex respjson.Field + Type respjson.Field + EndPageNumber respjson.Field + StartPageNumber respjson.Field + EndBlockIndex respjson.Field + StartBlockIndex respjson.Field + EncryptedIndex respjson.Field + Title respjson.Field + URL respjson.Field + SearchResultIndex respjson.Field + Source respjson.Field + raw string } `json:"-"` } -// anyServerToolUseBlockCaller is implemented by each variant of -// [ServerToolUseBlockCallerUnion] to add type safety for the return type of -// [ServerToolUseBlockCallerUnion.AsAny] -type anyServerToolUseBlockCaller interface { - implServerToolUseBlockCallerUnion() +// anyTextCitation is implemented by each variant of [TextCitationUnion] to add +// type safety for the return type of [TextCitationUnion.AsAny] +type anyTextCitation interface { + implTextCitationUnion() + toParamUnion() TextCitationParamUnion } -func (DirectCaller) implServerToolUseBlockCallerUnion() {} -func (ServerToolCaller) implServerToolUseBlockCallerUnion() {} -func (ServerToolCaller20260120) implServerToolUseBlockCallerUnion() {} - +func (CitationCharLocation) implTextCitationUnion() {} +func (CitationPageLocation) implTextCitationUnion() {} +func (CitationContentBlockLocation) implTextCitationUnion() {} +func (CitationsWebSearchResultLocation) implTextCitationUnion() {} +func (CitationsSearchResultLocation) implTextCitationUnion() {} + // Use the following switch statement to find the correct variant // -// switch variant := ServerToolUseBlockCallerUnion.AsAny().(type) { -// case anthropic.DirectCaller: -// case anthropic.ServerToolCaller: -// case anthropic.ServerToolCaller20260120: +// switch variant := TextCitationUnion.AsAny().(type) { +// case anthropic.CitationCharLocation: +// case anthropic.CitationPageLocation: +// case anthropic.CitationContentBlockLocation: +// case anthropic.CitationsWebSearchResultLocation: +// case anthropic.CitationsSearchResultLocation: // default: // fmt.Errorf("no variant present") // } -func (u ServerToolUseBlockCallerUnion) AsAny() anyServerToolUseBlockCaller { +func (u TextCitationUnion) AsAny() anyTextCitation { switch u.Type { - case "direct": - return u.AsDirect() - case "code_execution_20250825": - return u.AsCodeExecution20250825() - case "code_execution_20260120": - return u.AsCodeExecution20260120() + case "char_location": + return u.AsCharLocation() + case "page_location": + return u.AsPageLocation() + case "content_block_location": + return u.AsContentBlockLocation() + case "web_search_result_location": + return u.AsWebSearchResultLocation() + case "search_result_location": + return u.AsSearchResultLocation() } return nil } -func (u ServerToolUseBlockCallerUnion) AsDirect() (v DirectCaller) { +func (u TextCitationUnion) AsCharLocation() (v CitationCharLocation) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return } -func (u ServerToolUseBlockCallerUnion) AsCodeExecution20250825() (v ServerToolCaller) { +func (u TextCitationUnion) AsPageLocation() (v CitationPageLocation) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return } -func (u ServerToolUseBlockCallerUnion) AsCodeExecution20260120() (v ServerToolCaller20260120) { +func (u TextCitationUnion) AsContentBlockLocation() (v CitationContentBlockLocation) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u TextCitationUnion) AsWebSearchResultLocation() (v CitationsWebSearchResultLocation) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return +} + +func (u TextCitationUnion) AsSearchResultLocation() (v CitationsSearchResultLocation) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return } // Returns the unmodified JSON received from the API -func (u ServerToolUseBlockCallerUnion) RawJSON() string { return u.JSON.raw } +func (u TextCitationUnion) RawJSON() string { return u.JSON.raw } -func (r *ServerToolUseBlockCallerUnion) UnmarshalJSON(data []byte) error { +func (r *TextCitationUnion) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type ServerToolUseBlockName string +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type TextCitationParamUnion struct { + OfCharLocation *CitationCharLocationParam `json:",omitzero,inline"` + OfPageLocation *CitationPageLocationParam `json:",omitzero,inline"` + OfContentBlockLocation *CitationContentBlockLocationParam `json:",omitzero,inline"` + OfWebSearchResultLocation *CitationWebSearchResultLocationParam `json:",omitzero,inline"` + OfSearchResultLocation *CitationSearchResultLocationParam `json:",omitzero,inline"` + paramUnion +} -const ( - ServerToolUseBlockNameWebSearch ServerToolUseBlockName = "web_search" - ServerToolUseBlockNameWebFetch ServerToolUseBlockName = "web_fetch" - ServerToolUseBlockNameCodeExecution ServerToolUseBlockName = "code_execution" - ServerToolUseBlockNameBashCodeExecution ServerToolUseBlockName = "bash_code_execution" - ServerToolUseBlockNameTextEditorCodeExecution ServerToolUseBlockName = "text_editor_code_execution" - ServerToolUseBlockNameToolSearchToolRegex ServerToolUseBlockName = "tool_search_tool_regex" - ServerToolUseBlockNameToolSearchToolBm25 ServerToolUseBlockName = "tool_search_tool_bm25" -) +func (u TextCitationParamUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfCharLocation, + u.OfPageLocation, + u.OfContentBlockLocation, + u.OfWebSearchResultLocation, + u.OfSearchResultLocation) +} +func (u *TextCitationParamUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} -// The properties ID, Input, Name, Type are required. -type ServerToolUseBlockParam struct { - ID string `json:"id" api:"required"` - Input any `json:"input,omitzero" api:"required"` - // Any of "web_search", "web_fetch", "code_execution", "bash_code_execution", - // "text_editor_code_execution", "tool_search_tool_regex", "tool_search_tool_bm25". - Name ServerToolUseBlockParamName `json:"name,omitzero" api:"required"` - // Create a cache control breakpoint at this content block. - CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` - // Tool invocation directly from the model. - Caller ServerToolUseBlockParamCallerUnion `json:"caller,omitzero"` - // This field can be elided, and will marshal its zero value as "server_tool_use". - Type constant.ServerToolUse `json:"type" default:"server_tool_use"` - paramObj +func (u *TextCitationParamUnion) asAny() any { + if !param.IsOmitted(u.OfCharLocation) { + return u.OfCharLocation + } else if !param.IsOmitted(u.OfPageLocation) { + return u.OfPageLocation + } else if !param.IsOmitted(u.OfContentBlockLocation) { + return u.OfContentBlockLocation + } else if !param.IsOmitted(u.OfWebSearchResultLocation) { + return u.OfWebSearchResultLocation + } else if !param.IsOmitted(u.OfSearchResultLocation) { + return u.OfSearchResultLocation + } + return nil } -func (r ServerToolUseBlockParam) MarshalJSON() (data []byte, err error) { - type shadow ServerToolUseBlockParam - return param.MarshalObject(r, (*shadow)(&r)) +// Returns a pointer to the underlying variant's property, if present. +func (u TextCitationParamUnion) GetEndCharIndex() *int64 { + if vt := u.OfCharLocation; vt != nil { + return &vt.EndCharIndex + } + return nil } -func (r *ServerToolUseBlockParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) + +// Returns a pointer to the underlying variant's property, if present. +func (u TextCitationParamUnion) GetStartCharIndex() *int64 { + if vt := u.OfCharLocation; vt != nil { + return &vt.StartCharIndex + } + return nil } -type ServerToolUseBlockParamName string +// Returns a pointer to the underlying variant's property, if present. +func (u TextCitationParamUnion) GetEndPageNumber() *int64 { + if vt := u.OfPageLocation; vt != nil { + return &vt.EndPageNumber + } + return nil +} -const ( - ServerToolUseBlockParamNameWebSearch ServerToolUseBlockParamName = "web_search" - ServerToolUseBlockParamNameWebFetch ServerToolUseBlockParamName = "web_fetch" - ServerToolUseBlockParamNameCodeExecution ServerToolUseBlockParamName = "code_execution" - ServerToolUseBlockParamNameBashCodeExecution ServerToolUseBlockParamName = "bash_code_execution" - ServerToolUseBlockParamNameTextEditorCodeExecution ServerToolUseBlockParamName = "text_editor_code_execution" - ServerToolUseBlockParamNameToolSearchToolRegex ServerToolUseBlockParamName = "tool_search_tool_regex" - ServerToolUseBlockParamNameToolSearchToolBm25 ServerToolUseBlockParamName = "tool_search_tool_bm25" -) +// Returns a pointer to the underlying variant's property, if present. +func (u TextCitationParamUnion) GetStartPageNumber() *int64 { + if vt := u.OfPageLocation; vt != nil { + return &vt.StartPageNumber + } + return nil +} -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type ServerToolUseBlockParamCallerUnion struct { - OfDirect *DirectCallerParam `json:",omitzero,inline"` - OfCodeExecution20250825 *ServerToolCallerParam `json:",omitzero,inline"` - OfCodeExecution20260120 *ServerToolCaller20260120Param `json:",omitzero,inline"` - paramUnion +// Returns a pointer to the underlying variant's property, if present. +func (u TextCitationParamUnion) GetEncryptedIndex() *string { + if vt := u.OfWebSearchResultLocation; vt != nil { + return &vt.EncryptedIndex + } + return nil } -func (u ServerToolUseBlockParamCallerUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfDirect, u.OfCodeExecution20250825, u.OfCodeExecution20260120) +// Returns a pointer to the underlying variant's property, if present. +func (u TextCitationParamUnion) GetURL() *string { + if vt := u.OfWebSearchResultLocation; vt != nil { + return &vt.URL + } + return nil } -func (u *ServerToolUseBlockParamCallerUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) + +// Returns a pointer to the underlying variant's property, if present. +func (u TextCitationParamUnion) GetSearchResultIndex() *int64 { + if vt := u.OfSearchResultLocation; vt != nil { + return &vt.SearchResultIndex + } + return nil } -func (u *ServerToolUseBlockParamCallerUnion) asAny() any { - if !param.IsOmitted(u.OfDirect) { - return u.OfDirect - } else if !param.IsOmitted(u.OfCodeExecution20250825) { - return u.OfCodeExecution20250825 - } else if !param.IsOmitted(u.OfCodeExecution20260120) { - return u.OfCodeExecution20260120 +// Returns a pointer to the underlying variant's property, if present. +func (u TextCitationParamUnion) GetSource() *string { + if vt := u.OfSearchResultLocation; vt != nil { + return &vt.Source } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u ServerToolUseBlockParamCallerUnion) GetType() *string { - if vt := u.OfDirect; vt != nil { +func (u TextCitationParamUnion) GetCitedText() *string { + if vt := u.OfCharLocation; vt != nil { + return (*string)(&vt.CitedText) + } else if vt := u.OfPageLocation; vt != nil { + return (*string)(&vt.CitedText) + } else if vt := u.OfContentBlockLocation; vt != nil { + return (*string)(&vt.CitedText) + } else if vt := u.OfWebSearchResultLocation; vt != nil { + return (*string)(&vt.CitedText) + } else if vt := u.OfSearchResultLocation; vt != nil { + return (*string)(&vt.CitedText) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u TextCitationParamUnion) GetDocumentIndex() *int64 { + if vt := u.OfCharLocation; vt != nil { + return (*int64)(&vt.DocumentIndex) + } else if vt := u.OfPageLocation; vt != nil { + return (*int64)(&vt.DocumentIndex) + } else if vt := u.OfContentBlockLocation; vt != nil { + return (*int64)(&vt.DocumentIndex) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u TextCitationParamUnion) GetDocumentTitle() *string { + if vt := u.OfCharLocation; vt != nil && vt.DocumentTitle.Valid() { + return &vt.DocumentTitle.Value + } else if vt := u.OfPageLocation; vt != nil && vt.DocumentTitle.Valid() { + return &vt.DocumentTitle.Value + } else if vt := u.OfContentBlockLocation; vt != nil && vt.DocumentTitle.Valid() { + return &vt.DocumentTitle.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u TextCitationParamUnion) GetType() *string { + if vt := u.OfCharLocation; vt != nil { return (*string)(&vt.Type) - } else if vt := u.OfCodeExecution20250825; vt != nil { + } else if vt := u.OfPageLocation; vt != nil { return (*string)(&vt.Type) - } else if vt := u.OfCodeExecution20260120; vt != nil { + } else if vt := u.OfContentBlockLocation; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfWebSearchResultLocation; vt != nil { return (*string)(&vt.Type) + } else if vt := u.OfSearchResultLocation; vt != nil { + return (*string)(&vt.Type) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u TextCitationParamUnion) GetEndBlockIndex() *int64 { + if vt := u.OfContentBlockLocation; vt != nil { + return (*int64)(&vt.EndBlockIndex) + } else if vt := u.OfSearchResultLocation; vt != nil { + return (*int64)(&vt.EndBlockIndex) } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u ServerToolUseBlockParamCallerUnion) GetToolID() *string { - if vt := u.OfCodeExecution20250825; vt != nil { - return (*string)(&vt.ToolID) - } else if vt := u.OfCodeExecution20260120; vt != nil { - return (*string)(&vt.ToolID) +func (u TextCitationParamUnion) GetStartBlockIndex() *int64 { + if vt := u.OfContentBlockLocation; vt != nil { + return (*int64)(&vt.StartBlockIndex) + } else if vt := u.OfSearchResultLocation; vt != nil { + return (*int64)(&vt.StartBlockIndex) + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u TextCitationParamUnion) GetTitle() *string { + if vt := u.OfWebSearchResultLocation; vt != nil && vt.Title.Valid() { + return &vt.Title.Value + } else if vt := u.OfSearchResultLocation; vt != nil && vt.Title.Valid() { + return &vt.Title.Value } return nil } func init() { - apijson.RegisterUnion[ServerToolUseBlockParamCallerUnion]( + apijson.RegisterUnion[TextCitationParamUnion]( "type", - apijson.Discriminator[DirectCallerParam]("direct"), - apijson.Discriminator[ServerToolCallerParam]("code_execution_20250825"), - apijson.Discriminator[ServerToolCaller20260120Param]("code_execution_20260120"), + apijson.Discriminator[CitationCharLocationParam]("char_location"), + apijson.Discriminator[CitationPageLocationParam]("page_location"), + apijson.Discriminator[CitationContentBlockLocationParam]("content_block_location"), + apijson.Discriminator[CitationWebSearchResultLocationParam]("web_search_result_location"), + apijson.Discriminator[CitationSearchResultLocationParam]("search_result_location"), ) } -type SignatureDelta struct { - Signature string `json:"signature" api:"required"` - Type constant.SignatureDelta `json:"type" default:"signature_delta"` +type TextDelta struct { + Text string `json:"text" api:"required"` + Type constant.TextDelta `json:"type" default:"text_delta"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { - Signature respjson.Field + Text respjson.Field Type respjson.Field ExtraFields map[string]respjson.Field raw string @@ -5331,35 +8655,60 @@ type SignatureDelta struct { } // Returns the unmodified JSON received from the API -func (r SignatureDelta) RawJSON() string { return r.JSON.raw } -func (r *SignatureDelta) UnmarshalJSON(data []byte) error { +func (r TextDelta) RawJSON() string { return r.JSON.raw } +func (r *TextDelta) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type StopReason string +type TextEditorCodeExecutionCreateResultBlock struct { + IsFileUpdate bool `json:"is_file_update" api:"required"` + Type constant.TextEditorCodeExecutionCreateResult `json:"type" default:"text_editor_code_execution_create_result"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + IsFileUpdate respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} -const ( - StopReasonEndTurn StopReason = "end_turn" - StopReasonMaxTokens StopReason = "max_tokens" - StopReasonStopSequence StopReason = "stop_sequence" - StopReasonToolUse StopReason = "tool_use" - StopReasonPauseTurn StopReason = "pause_turn" - StopReasonRefusal StopReason = "refusal" -) +// Returns the unmodified JSON received from the API +func (r TextEditorCodeExecutionCreateResultBlock) RawJSON() string { return r.JSON.raw } +func (r *TextEditorCodeExecutionCreateResultBlock) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} -type TextBlock struct { - // Citations supporting the text block. - // - // The type of citation returned will depend on the type of document being cited. - // Citing a PDF results in `page_location`, plain text results in `char_location`, - // and content document results in `content_block_location`. - Citations []TextCitationUnion `json:"citations" api:"required"` - Text string `json:"text" api:"required"` - Type constant.Text `json:"type" default:"text"` +// The properties IsFileUpdate, Type are required. +type TextEditorCodeExecutionCreateResultBlockParam struct { + IsFileUpdate bool `json:"is_file_update" api:"required"` + // This field can be elided, and will marshal its zero value as + // "text_editor_code_execution_create_result". + Type constant.TextEditorCodeExecutionCreateResult `json:"type" default:"text_editor_code_execution_create_result"` + paramObj +} + +func (r TextEditorCodeExecutionCreateResultBlockParam) MarshalJSON() (data []byte, err error) { + type shadow TextEditorCodeExecutionCreateResultBlockParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *TextEditorCodeExecutionCreateResultBlockParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type TextEditorCodeExecutionStrReplaceResultBlock struct { + Lines []string `json:"lines" api:"required"` + NewLines int64 `json:"new_lines" api:"required"` + NewStart int64 `json:"new_start" api:"required"` + OldLines int64 `json:"old_lines" api:"required"` + OldStart int64 `json:"old_start" api:"required"` + Type constant.TextEditorCodeExecutionStrReplaceResult `json:"type" default:"text_editor_code_execution_str_replace_result"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { - Citations respjson.Field - Text respjson.Field + Lines respjson.Field + NewLines respjson.Field + NewStart respjson.Field + OldLines respjson.Field + OldStart respjson.Field Type respjson.Field ExtraFields map[string]respjson.Field raw string @@ -5367,380 +8716,312 @@ type TextBlock struct { } // Returns the unmodified JSON received from the API -func (r TextBlock) RawJSON() string { return r.JSON.raw } -func (r *TextBlock) UnmarshalJSON(data []byte) error { +func (r TextEditorCodeExecutionStrReplaceResultBlock) RawJSON() string { return r.JSON.raw } +func (r *TextEditorCodeExecutionStrReplaceResultBlock) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The properties Text, Type are required. -type TextBlockParam struct { - Text string `json:"text" api:"required"` - Citations []TextCitationParamUnion `json:"citations,omitzero"` - // Create a cache control breakpoint at this content block. - CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` - // This field can be elided, and will marshal its zero value as "text". - Type constant.Text `json:"type" default:"text"` +// The property Type is required. +type TextEditorCodeExecutionStrReplaceResultBlockParam struct { + NewLines param.Opt[int64] `json:"new_lines,omitzero"` + NewStart param.Opt[int64] `json:"new_start,omitzero"` + OldLines param.Opt[int64] `json:"old_lines,omitzero"` + OldStart param.Opt[int64] `json:"old_start,omitzero"` + Lines []string `json:"lines,omitzero"` + // This field can be elided, and will marshal its zero value as + // "text_editor_code_execution_str_replace_result". + Type constant.TextEditorCodeExecutionStrReplaceResult `json:"type" default:"text_editor_code_execution_str_replace_result"` paramObj } -func (r TextBlockParam) MarshalJSON() (data []byte, err error) { - type shadow TextBlockParam +func (r TextEditorCodeExecutionStrReplaceResultBlockParam) MarshalJSON() (data []byte, err error) { + type shadow TextEditorCodeExecutionStrReplaceResultBlockParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *TextBlockParam) UnmarshalJSON(data []byte) error { +func (r *TextEditorCodeExecutionStrReplaceResultBlockParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// TextCitationUnion contains all possible properties and values from -// [CitationCharLocation], [CitationPageLocation], [CitationContentBlockLocation], -// [CitationsWebSearchResultLocation], [CitationsSearchResultLocation]. -// -// Use the [TextCitationUnion.AsAny] method to switch on the variant. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -type TextCitationUnion struct { - CitedText string `json:"cited_text"` - DocumentIndex int64 `json:"document_index"` - DocumentTitle string `json:"document_title"` - // This field is from variant [CitationCharLocation]. - EndCharIndex int64 `json:"end_char_index"` - FileID string `json:"file_id"` - // This field is from variant [CitationCharLocation]. - StartCharIndex int64 `json:"start_char_index"` - // Any of "char_location", "page_location", "content_block_location", - // "web_search_result_location", "search_result_location". - Type string `json:"type"` - // This field is from variant [CitationPageLocation]. - EndPageNumber int64 `json:"end_page_number"` - // This field is from variant [CitationPageLocation]. - StartPageNumber int64 `json:"start_page_number"` - EndBlockIndex int64 `json:"end_block_index"` - StartBlockIndex int64 `json:"start_block_index"` - // This field is from variant [CitationsWebSearchResultLocation]. - EncryptedIndex string `json:"encrypted_index"` - Title string `json:"title"` - // This field is from variant [CitationsWebSearchResultLocation]. - URL string `json:"url"` - // This field is from variant [CitationsSearchResultLocation]. - SearchResultIndex int64 `json:"search_result_index"` - // This field is from variant [CitationsSearchResultLocation]. - Source string `json:"source"` - JSON struct { - CitedText respjson.Field - DocumentIndex respjson.Field - DocumentTitle respjson.Field - EndCharIndex respjson.Field - FileID respjson.Field - StartCharIndex respjson.Field - Type respjson.Field - EndPageNumber respjson.Field - StartPageNumber respjson.Field - EndBlockIndex respjson.Field - StartBlockIndex respjson.Field - EncryptedIndex respjson.Field - Title respjson.Field - URL respjson.Field - SearchResultIndex respjson.Field - Source respjson.Field - raw string +type TextEditorCodeExecutionToolResultBlock struct { + Content TextEditorCodeExecutionToolResultBlockContentUnion `json:"content" api:"required"` + ToolUseID string `json:"tool_use_id" api:"required"` + Type constant.TextEditorCodeExecutionToolResult `json:"type" default:"text_editor_code_execution_tool_result"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Content respjson.Field + ToolUseID respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string } `json:"-"` } -// anyTextCitation is implemented by each variant of [TextCitationUnion] to add -// type safety for the return type of [TextCitationUnion.AsAny] -type anyTextCitation interface { - implTextCitationUnion() - toParamUnion() TextCitationParamUnion +// Returns the unmodified JSON received from the API +func (r TextEditorCodeExecutionToolResultBlock) RawJSON() string { return r.JSON.raw } +func (r *TextEditorCodeExecutionToolResultBlock) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func (CitationCharLocation) implTextCitationUnion() {} -func (CitationPageLocation) implTextCitationUnion() {} -func (CitationContentBlockLocation) implTextCitationUnion() {} -func (CitationsWebSearchResultLocation) implTextCitationUnion() {} -func (CitationsSearchResultLocation) implTextCitationUnion() {} - -// Use the following switch statement to find the correct variant +// TextEditorCodeExecutionToolResultBlockContentUnion contains all possible +// properties and values from [TextEditorCodeExecutionToolResultError], +// [TextEditorCodeExecutionViewResultBlock], +// [TextEditorCodeExecutionCreateResultBlock], +// [TextEditorCodeExecutionStrReplaceResultBlock]. // -// switch variant := TextCitationUnion.AsAny().(type) { -// case anthropic.CitationCharLocation: -// case anthropic.CitationPageLocation: -// case anthropic.CitationContentBlockLocation: -// case anthropic.CitationsWebSearchResultLocation: -// case anthropic.CitationsSearchResultLocation: -// default: -// fmt.Errorf("no variant present") -// } -func (u TextCitationUnion) AsAny() anyTextCitation { - switch u.Type { - case "char_location": - return u.AsCharLocation() - case "page_location": - return u.AsPageLocation() - case "content_block_location": - return u.AsContentBlockLocation() - case "web_search_result_location": - return u.AsWebSearchResultLocation() - case "search_result_location": - return u.AsSearchResultLocation() - } - return nil +// Use the methods beginning with 'As' to cast the union to one of its variants. +type TextEditorCodeExecutionToolResultBlockContentUnion struct { + // This field is from variant [TextEditorCodeExecutionToolResultError]. + ErrorCode TextEditorCodeExecutionToolResultErrorCode `json:"error_code"` + // This field is from variant [TextEditorCodeExecutionToolResultError]. + ErrorMessage string `json:"error_message"` + Type string `json:"type"` + // This field is from variant [TextEditorCodeExecutionViewResultBlock]. + Content string `json:"content"` + // This field is from variant [TextEditorCodeExecutionViewResultBlock]. + FileType TextEditorCodeExecutionViewResultBlockFileType `json:"file_type"` + // This field is from variant [TextEditorCodeExecutionViewResultBlock]. + NumLines int64 `json:"num_lines"` + // This field is from variant [TextEditorCodeExecutionViewResultBlock]. + StartLine int64 `json:"start_line"` + // This field is from variant [TextEditorCodeExecutionViewResultBlock]. + TotalLines int64 `json:"total_lines"` + // This field is from variant [TextEditorCodeExecutionCreateResultBlock]. + IsFileUpdate bool `json:"is_file_update"` + // This field is from variant [TextEditorCodeExecutionStrReplaceResultBlock]. + Lines []string `json:"lines"` + // This field is from variant [TextEditorCodeExecutionStrReplaceResultBlock]. + NewLines int64 `json:"new_lines"` + // This field is from variant [TextEditorCodeExecutionStrReplaceResultBlock]. + NewStart int64 `json:"new_start"` + // This field is from variant [TextEditorCodeExecutionStrReplaceResultBlock]. + OldLines int64 `json:"old_lines"` + // This field is from variant [TextEditorCodeExecutionStrReplaceResultBlock]. + OldStart int64 `json:"old_start"` + JSON struct { + ErrorCode respjson.Field + ErrorMessage respjson.Field + Type respjson.Field + Content respjson.Field + FileType respjson.Field + NumLines respjson.Field + StartLine respjson.Field + TotalLines respjson.Field + IsFileUpdate respjson.Field + Lines respjson.Field + NewLines respjson.Field + NewStart respjson.Field + OldLines respjson.Field + OldStart respjson.Field + raw string + } `json:"-"` } -func (u TextCitationUnion) AsCharLocation() (v CitationCharLocation) { +func (u TextEditorCodeExecutionToolResultBlockContentUnion) AsResponseTextEditorCodeExecutionToolResultError() (v TextEditorCodeExecutionToolResultError) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return } -func (u TextCitationUnion) AsPageLocation() (v CitationPageLocation) { +func (u TextEditorCodeExecutionToolResultBlockContentUnion) AsResponseTextEditorCodeExecutionViewResultBlock() (v TextEditorCodeExecutionViewResultBlock) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return } -func (u TextCitationUnion) AsContentBlockLocation() (v CitationContentBlockLocation) { +func (u TextEditorCodeExecutionToolResultBlockContentUnion) AsResponseTextEditorCodeExecutionCreateResultBlock() (v TextEditorCodeExecutionCreateResultBlock) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return } -func (u TextCitationUnion) AsWebSearchResultLocation() (v CitationsWebSearchResultLocation) { +func (u TextEditorCodeExecutionToolResultBlockContentUnion) AsResponseTextEditorCodeExecutionStrReplaceResultBlock() (v TextEditorCodeExecutionStrReplaceResultBlock) { apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) return } -func (u TextCitationUnion) AsSearchResultLocation() (v CitationsSearchResultLocation) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +// Returns the unmodified JSON received from the API +func (u TextEditorCodeExecutionToolResultBlockContentUnion) RawJSON() string { return u.JSON.raw } + +func (r *TextEditorCodeExecutionToolResultBlockContentUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns the unmodified JSON received from the API -func (u TextCitationUnion) RawJSON() string { return u.JSON.raw } +// The properties Content, ToolUseID, Type are required. +type TextEditorCodeExecutionToolResultBlockParam struct { + Content TextEditorCodeExecutionToolResultBlockParamContentUnion `json:"content,omitzero" api:"required"` + ToolUseID string `json:"tool_use_id" api:"required"` + // Create a cache control breakpoint at this content block. + CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` + // This field can be elided, and will marshal its zero value as + // "text_editor_code_execution_tool_result". + Type constant.TextEditorCodeExecutionToolResult `json:"type" default:"text_editor_code_execution_tool_result"` + paramObj +} -func (r *TextCitationUnion) UnmarshalJSON(data []byte) error { +func (r TextEditorCodeExecutionToolResultBlockParam) MarshalJSON() (data []byte, err error) { + type shadow TextEditorCodeExecutionToolResultBlockParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *TextEditorCodeExecutionToolResultBlockParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } // Only one field can be non-zero. // // Use [param.IsOmitted] to confirm if a field is set. -type TextCitationParamUnion struct { - OfCharLocation *CitationCharLocationParam `json:",omitzero,inline"` - OfPageLocation *CitationPageLocationParam `json:",omitzero,inline"` - OfContentBlockLocation *CitationContentBlockLocationParam `json:",omitzero,inline"` - OfWebSearchResultLocation *CitationWebSearchResultLocationParam `json:",omitzero,inline"` - OfSearchResultLocation *CitationSearchResultLocationParam `json:",omitzero,inline"` +type TextEditorCodeExecutionToolResultBlockParamContentUnion struct { + OfRequestTextEditorCodeExecutionToolResultError *TextEditorCodeExecutionToolResultErrorParam `json:",omitzero,inline"` + OfRequestTextEditorCodeExecutionViewResultBlock *TextEditorCodeExecutionViewResultBlockParam `json:",omitzero,inline"` + OfRequestTextEditorCodeExecutionCreateResultBlock *TextEditorCodeExecutionCreateResultBlockParam `json:",omitzero,inline"` + OfRequestTextEditorCodeExecutionStrReplaceResultBlock *TextEditorCodeExecutionStrReplaceResultBlockParam `json:",omitzero,inline"` paramUnion } -func (u TextCitationParamUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfCharLocation, - u.OfPageLocation, - u.OfContentBlockLocation, - u.OfWebSearchResultLocation, - u.OfSearchResultLocation) +func (u TextEditorCodeExecutionToolResultBlockParamContentUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfRequestTextEditorCodeExecutionToolResultError, u.OfRequestTextEditorCodeExecutionViewResultBlock, u.OfRequestTextEditorCodeExecutionCreateResultBlock, u.OfRequestTextEditorCodeExecutionStrReplaceResultBlock) } -func (u *TextCitationParamUnion) UnmarshalJSON(data []byte) error { +func (u *TextEditorCodeExecutionToolResultBlockParamContentUnion) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, u) } -func (u *TextCitationParamUnion) asAny() any { - if !param.IsOmitted(u.OfCharLocation) { - return u.OfCharLocation - } else if !param.IsOmitted(u.OfPageLocation) { - return u.OfPageLocation - } else if !param.IsOmitted(u.OfContentBlockLocation) { - return u.OfContentBlockLocation - } else if !param.IsOmitted(u.OfWebSearchResultLocation) { - return u.OfWebSearchResultLocation - } else if !param.IsOmitted(u.OfSearchResultLocation) { - return u.OfSearchResultLocation - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u TextCitationParamUnion) GetEndCharIndex() *int64 { - if vt := u.OfCharLocation; vt != nil { - return &vt.EndCharIndex - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u TextCitationParamUnion) GetStartCharIndex() *int64 { - if vt := u.OfCharLocation; vt != nil { - return &vt.StartCharIndex +func (u *TextEditorCodeExecutionToolResultBlockParamContentUnion) asAny() any { + if !param.IsOmitted(u.OfRequestTextEditorCodeExecutionToolResultError) { + return u.OfRequestTextEditorCodeExecutionToolResultError + } else if !param.IsOmitted(u.OfRequestTextEditorCodeExecutionViewResultBlock) { + return u.OfRequestTextEditorCodeExecutionViewResultBlock + } else if !param.IsOmitted(u.OfRequestTextEditorCodeExecutionCreateResultBlock) { + return u.OfRequestTextEditorCodeExecutionCreateResultBlock + } else if !param.IsOmitted(u.OfRequestTextEditorCodeExecutionStrReplaceResultBlock) { + return u.OfRequestTextEditorCodeExecutionStrReplaceResultBlock } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u TextCitationParamUnion) GetEndPageNumber() *int64 { - if vt := u.OfPageLocation; vt != nil { - return &vt.EndPageNumber +func (u TextEditorCodeExecutionToolResultBlockParamContentUnion) GetErrorCode() *string { + if vt := u.OfRequestTextEditorCodeExecutionToolResultError; vt != nil { + return (*string)(&vt.ErrorCode) } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u TextCitationParamUnion) GetStartPageNumber() *int64 { - if vt := u.OfPageLocation; vt != nil { - return &vt.StartPageNumber +func (u TextEditorCodeExecutionToolResultBlockParamContentUnion) GetErrorMessage() *string { + if vt := u.OfRequestTextEditorCodeExecutionToolResultError; vt != nil && vt.ErrorMessage.Valid() { + return &vt.ErrorMessage.Value } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u TextCitationParamUnion) GetEncryptedIndex() *string { - if vt := u.OfWebSearchResultLocation; vt != nil { - return &vt.EncryptedIndex +func (u TextEditorCodeExecutionToolResultBlockParamContentUnion) GetContent() *string { + if vt := u.OfRequestTextEditorCodeExecutionViewResultBlock; vt != nil { + return &vt.Content } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u TextCitationParamUnion) GetURL() *string { - if vt := u.OfWebSearchResultLocation; vt != nil { - return &vt.URL +func (u TextEditorCodeExecutionToolResultBlockParamContentUnion) GetFileType() *string { + if vt := u.OfRequestTextEditorCodeExecutionViewResultBlock; vt != nil { + return (*string)(&vt.FileType) } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u TextCitationParamUnion) GetSearchResultIndex() *int64 { - if vt := u.OfSearchResultLocation; vt != nil { - return &vt.SearchResultIndex +func (u TextEditorCodeExecutionToolResultBlockParamContentUnion) GetNumLines() *int64 { + if vt := u.OfRequestTextEditorCodeExecutionViewResultBlock; vt != nil && vt.NumLines.Valid() { + return &vt.NumLines.Value } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u TextCitationParamUnion) GetSource() *string { - if vt := u.OfSearchResultLocation; vt != nil { - return &vt.Source +func (u TextEditorCodeExecutionToolResultBlockParamContentUnion) GetStartLine() *int64 { + if vt := u.OfRequestTextEditorCodeExecutionViewResultBlock; vt != nil && vt.StartLine.Valid() { + return &vt.StartLine.Value } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u TextCitationParamUnion) GetCitedText() *string { - if vt := u.OfCharLocation; vt != nil { - return (*string)(&vt.CitedText) - } else if vt := u.OfPageLocation; vt != nil { - return (*string)(&vt.CitedText) - } else if vt := u.OfContentBlockLocation; vt != nil { - return (*string)(&vt.CitedText) - } else if vt := u.OfWebSearchResultLocation; vt != nil { - return (*string)(&vt.CitedText) - } else if vt := u.OfSearchResultLocation; vt != nil { - return (*string)(&vt.CitedText) +func (u TextEditorCodeExecutionToolResultBlockParamContentUnion) GetTotalLines() *int64 { + if vt := u.OfRequestTextEditorCodeExecutionViewResultBlock; vt != nil && vt.TotalLines.Valid() { + return &vt.TotalLines.Value } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u TextCitationParamUnion) GetDocumentIndex() *int64 { - if vt := u.OfCharLocation; vt != nil { - return (*int64)(&vt.DocumentIndex) - } else if vt := u.OfPageLocation; vt != nil { - return (*int64)(&vt.DocumentIndex) - } else if vt := u.OfContentBlockLocation; vt != nil { - return (*int64)(&vt.DocumentIndex) +func (u TextEditorCodeExecutionToolResultBlockParamContentUnion) GetIsFileUpdate() *bool { + if vt := u.OfRequestTextEditorCodeExecutionCreateResultBlock; vt != nil { + return &vt.IsFileUpdate } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u TextCitationParamUnion) GetDocumentTitle() *string { - if vt := u.OfCharLocation; vt != nil && vt.DocumentTitle.Valid() { - return &vt.DocumentTitle.Value - } else if vt := u.OfPageLocation; vt != nil && vt.DocumentTitle.Valid() { - return &vt.DocumentTitle.Value - } else if vt := u.OfContentBlockLocation; vt != nil && vt.DocumentTitle.Valid() { - return &vt.DocumentTitle.Value +func (u TextEditorCodeExecutionToolResultBlockParamContentUnion) GetLines() []string { + if vt := u.OfRequestTextEditorCodeExecutionStrReplaceResultBlock; vt != nil { + return vt.Lines } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u TextCitationParamUnion) GetType() *string { - if vt := u.OfCharLocation; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfPageLocation; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfContentBlockLocation; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfWebSearchResultLocation; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfSearchResultLocation; vt != nil { - return (*string)(&vt.Type) +func (u TextEditorCodeExecutionToolResultBlockParamContentUnion) GetNewLines() *int64 { + if vt := u.OfRequestTextEditorCodeExecutionStrReplaceResultBlock; vt != nil && vt.NewLines.Valid() { + return &vt.NewLines.Value } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u TextCitationParamUnion) GetEndBlockIndex() *int64 { - if vt := u.OfContentBlockLocation; vt != nil { - return (*int64)(&vt.EndBlockIndex) - } else if vt := u.OfSearchResultLocation; vt != nil { - return (*int64)(&vt.EndBlockIndex) +func (u TextEditorCodeExecutionToolResultBlockParamContentUnion) GetNewStart() *int64 { + if vt := u.OfRequestTextEditorCodeExecutionStrReplaceResultBlock; vt != nil && vt.NewStart.Valid() { + return &vt.NewStart.Value } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u TextCitationParamUnion) GetStartBlockIndex() *int64 { - if vt := u.OfContentBlockLocation; vt != nil { - return (*int64)(&vt.StartBlockIndex) - } else if vt := u.OfSearchResultLocation; vt != nil { - return (*int64)(&vt.StartBlockIndex) +func (u TextEditorCodeExecutionToolResultBlockParamContentUnion) GetOldLines() *int64 { + if vt := u.OfRequestTextEditorCodeExecutionStrReplaceResultBlock; vt != nil && vt.OldLines.Valid() { + return &vt.OldLines.Value } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u TextCitationParamUnion) GetTitle() *string { - if vt := u.OfWebSearchResultLocation; vt != nil && vt.Title.Valid() { - return &vt.Title.Value - } else if vt := u.OfSearchResultLocation; vt != nil && vt.Title.Valid() { - return &vt.Title.Value +func (u TextEditorCodeExecutionToolResultBlockParamContentUnion) GetOldStart() *int64 { + if vt := u.OfRequestTextEditorCodeExecutionStrReplaceResultBlock; vt != nil && vt.OldStart.Valid() { + return &vt.OldStart.Value } - return nil -} - -func init() { - apijson.RegisterUnion[TextCitationParamUnion]( - "type", - apijson.Discriminator[CitationCharLocationParam]("char_location"), - apijson.Discriminator[CitationPageLocationParam]("page_location"), - apijson.Discriminator[CitationContentBlockLocationParam]("content_block_location"), - apijson.Discriminator[CitationWebSearchResultLocationParam]("web_search_result_location"), - apijson.Discriminator[CitationSearchResultLocationParam]("search_result_location"), - ) -} - -type TextDelta struct { - Text string `json:"text" api:"required"` - Type constant.TextDelta `json:"type" default:"text_delta"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Text respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r TextDelta) RawJSON() string { return r.JSON.raw } -func (r *TextDelta) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) + return nil } -type TextEditorCodeExecutionCreateResultBlock struct { - IsFileUpdate bool `json:"is_file_update" api:"required"` - Type constant.TextEditorCodeExecutionCreateResult `json:"type" default:"text_editor_code_execution_create_result"` +// Returns a pointer to the underlying variant's property, if present. +func (u TextEditorCodeExecutionToolResultBlockParamContentUnion) GetType() *string { + if vt := u.OfRequestTextEditorCodeExecutionToolResultError; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfRequestTextEditorCodeExecutionViewResultBlock; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfRequestTextEditorCodeExecutionCreateResultBlock; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfRequestTextEditorCodeExecutionStrReplaceResultBlock; vt != nil { + return (*string)(&vt.Type) + } + return nil +} + +type TextEditorCodeExecutionToolResultError struct { + // Any of "invalid_tool_input", "unavailable", "too_many_requests", + // "execution_time_exceeded", "file_not_found". + ErrorCode TextEditorCodeExecutionToolResultErrorCode `json:"error_code" api:"required"` + ErrorMessage string `json:"error_message" api:"required"` + Type constant.TextEditorCodeExecutionToolResultError `json:"type" default:"text_editor_code_execution_tool_result_error"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { - IsFileUpdate respjson.Field + ErrorCode respjson.Field + ErrorMessage respjson.Field Type respjson.Field ExtraFields map[string]respjson.Field raw string @@ -5748,42 +9029,56 @@ type TextEditorCodeExecutionCreateResultBlock struct { } // Returns the unmodified JSON received from the API -func (r TextEditorCodeExecutionCreateResultBlock) RawJSON() string { return r.JSON.raw } -func (r *TextEditorCodeExecutionCreateResultBlock) UnmarshalJSON(data []byte) error { +func (r TextEditorCodeExecutionToolResultError) RawJSON() string { return r.JSON.raw } +func (r *TextEditorCodeExecutionToolResultError) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The properties IsFileUpdate, Type are required. -type TextEditorCodeExecutionCreateResultBlockParam struct { - IsFileUpdate bool `json:"is_file_update" api:"required"` +type TextEditorCodeExecutionToolResultErrorCode string + +const ( + TextEditorCodeExecutionToolResultErrorCodeInvalidToolInput TextEditorCodeExecutionToolResultErrorCode = "invalid_tool_input" + TextEditorCodeExecutionToolResultErrorCodeUnavailable TextEditorCodeExecutionToolResultErrorCode = "unavailable" + TextEditorCodeExecutionToolResultErrorCodeTooManyRequests TextEditorCodeExecutionToolResultErrorCode = "too_many_requests" + TextEditorCodeExecutionToolResultErrorCodeExecutionTimeExceeded TextEditorCodeExecutionToolResultErrorCode = "execution_time_exceeded" + TextEditorCodeExecutionToolResultErrorCodeFileNotFound TextEditorCodeExecutionToolResultErrorCode = "file_not_found" +) + +// The properties ErrorCode, Type are required. +type TextEditorCodeExecutionToolResultErrorParam struct { + // Any of "invalid_tool_input", "unavailable", "too_many_requests", + // "execution_time_exceeded", "file_not_found". + ErrorCode TextEditorCodeExecutionToolResultErrorCode `json:"error_code,omitzero" api:"required"` + ErrorMessage param.Opt[string] `json:"error_message,omitzero"` // This field can be elided, and will marshal its zero value as - // "text_editor_code_execution_create_result". - Type constant.TextEditorCodeExecutionCreateResult `json:"type" default:"text_editor_code_execution_create_result"` + // "text_editor_code_execution_tool_result_error". + Type constant.TextEditorCodeExecutionToolResultError `json:"type" default:"text_editor_code_execution_tool_result_error"` paramObj } -func (r TextEditorCodeExecutionCreateResultBlockParam) MarshalJSON() (data []byte, err error) { - type shadow TextEditorCodeExecutionCreateResultBlockParam +func (r TextEditorCodeExecutionToolResultErrorParam) MarshalJSON() (data []byte, err error) { + type shadow TextEditorCodeExecutionToolResultErrorParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *TextEditorCodeExecutionCreateResultBlockParam) UnmarshalJSON(data []byte) error { +func (r *TextEditorCodeExecutionToolResultErrorParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type TextEditorCodeExecutionStrReplaceResultBlock struct { - Lines []string `json:"lines" api:"required"` - NewLines int64 `json:"new_lines" api:"required"` - NewStart int64 `json:"new_start" api:"required"` - OldLines int64 `json:"old_lines" api:"required"` - OldStart int64 `json:"old_start" api:"required"` - Type constant.TextEditorCodeExecutionStrReplaceResult `json:"type" default:"text_editor_code_execution_str_replace_result"` +type TextEditorCodeExecutionViewResultBlock struct { + Content string `json:"content" api:"required"` + // Any of "text", "image", "pdf". + FileType TextEditorCodeExecutionViewResultBlockFileType `json:"file_type" api:"required"` + NumLines int64 `json:"num_lines" api:"required"` + StartLine int64 `json:"start_line" api:"required"` + TotalLines int64 `json:"total_lines" api:"required"` + Type constant.TextEditorCodeExecutionViewResult `json:"type" default:"text_editor_code_execution_view_result"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { - Lines respjson.Field - NewLines respjson.Field - NewStart respjson.Field - OldLines respjson.Field - OldStart respjson.Field + Content respjson.Field + FileType respjson.Field + NumLines respjson.Field + StartLine respjson.Field + TotalLines respjson.Field Type respjson.Field ExtraFields map[string]respjson.Field raw string @@ -5791,40 +9086,68 @@ type TextEditorCodeExecutionStrReplaceResultBlock struct { } // Returns the unmodified JSON received from the API -func (r TextEditorCodeExecutionStrReplaceResultBlock) RawJSON() string { return r.JSON.raw } -func (r *TextEditorCodeExecutionStrReplaceResultBlock) UnmarshalJSON(data []byte) error { +func (r TextEditorCodeExecutionViewResultBlock) RawJSON() string { return r.JSON.raw } +func (r *TextEditorCodeExecutionViewResultBlock) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The property Type is required. -type TextEditorCodeExecutionStrReplaceResultBlockParam struct { - NewLines param.Opt[int64] `json:"new_lines,omitzero"` - NewStart param.Opt[int64] `json:"new_start,omitzero"` - OldLines param.Opt[int64] `json:"old_lines,omitzero"` - OldStart param.Opt[int64] `json:"old_start,omitzero"` - Lines []string `json:"lines,omitzero"` +type TextEditorCodeExecutionViewResultBlockFileType string + +const ( + TextEditorCodeExecutionViewResultBlockFileTypeText TextEditorCodeExecutionViewResultBlockFileType = "text" + TextEditorCodeExecutionViewResultBlockFileTypeImage TextEditorCodeExecutionViewResultBlockFileType = "image" + TextEditorCodeExecutionViewResultBlockFileTypePDF TextEditorCodeExecutionViewResultBlockFileType = "pdf" +) + +// The properties Content, FileType, Type are required. +type TextEditorCodeExecutionViewResultBlockParam struct { + Content string `json:"content" api:"required"` + // Any of "text", "image", "pdf". + FileType TextEditorCodeExecutionViewResultBlockParamFileType `json:"file_type,omitzero" api:"required"` + NumLines param.Opt[int64] `json:"num_lines,omitzero"` + StartLine param.Opt[int64] `json:"start_line,omitzero"` + TotalLines param.Opt[int64] `json:"total_lines,omitzero"` // This field can be elided, and will marshal its zero value as - // "text_editor_code_execution_str_replace_result". - Type constant.TextEditorCodeExecutionStrReplaceResult `json:"type" default:"text_editor_code_execution_str_replace_result"` + // "text_editor_code_execution_view_result". + Type constant.TextEditorCodeExecutionViewResult `json:"type" default:"text_editor_code_execution_view_result"` paramObj } -func (r TextEditorCodeExecutionStrReplaceResultBlockParam) MarshalJSON() (data []byte, err error) { - type shadow TextEditorCodeExecutionStrReplaceResultBlockParam +func (r TextEditorCodeExecutionViewResultBlockParam) MarshalJSON() (data []byte, err error) { + type shadow TextEditorCodeExecutionViewResultBlockParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *TextEditorCodeExecutionStrReplaceResultBlockParam) UnmarshalJSON(data []byte) error { +func (r *TextEditorCodeExecutionViewResultBlockParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type TextEditorCodeExecutionToolResultBlock struct { - Content TextEditorCodeExecutionToolResultBlockContentUnion `json:"content" api:"required"` - ToolUseID string `json:"tool_use_id" api:"required"` - Type constant.TextEditorCodeExecutionToolResult `json:"type" default:"text_editor_code_execution_tool_result"` +type TextEditorCodeExecutionViewResultBlockParamFileType string + +const ( + TextEditorCodeExecutionViewResultBlockParamFileTypeText TextEditorCodeExecutionViewResultBlockParamFileType = "text" + TextEditorCodeExecutionViewResultBlockParamFileTypeImage TextEditorCodeExecutionViewResultBlockParamFileType = "image" + TextEditorCodeExecutionViewResultBlockParamFileTypePDF TextEditorCodeExecutionViewResultBlockParamFileType = "pdf" +) + +type ThinkingBlock struct { + // A value used to verify that this thinking block was generated by Claude when it + // is passed back to the API. + // + // This is an opaque field and should not be interpreted or parsed. When passing + // thinking blocks back to the API (required when using tools with extended + // thinking), pass them back exactly as received, with this field intact. + // + // See + // [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking) + // for details. + Signature string `json:"signature" api:"required"` + // The text of Claude's thinking process for this block. + Thinking string `json:"thinking" api:"required"` + Type constant.Thinking `json:"type" default:"thinking"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { - Content respjson.Field - ToolUseID respjson.Field + Signature respjson.Field + Thinking respjson.Field Type respjson.Field ExtraFields map[string]respjson.Field raw string @@ -5832,386 +9155,511 @@ type TextEditorCodeExecutionToolResultBlock struct { } // Returns the unmodified JSON received from the API -func (r TextEditorCodeExecutionToolResultBlock) RawJSON() string { return r.JSON.raw } -func (r *TextEditorCodeExecutionToolResultBlock) UnmarshalJSON(data []byte) error { +func (r ThinkingBlock) RawJSON() string { return r.JSON.raw } +func (r *ThinkingBlock) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// TextEditorCodeExecutionToolResultBlockContentUnion contains all possible -// properties and values from [TextEditorCodeExecutionToolResultError], -// [TextEditorCodeExecutionViewResultBlock], -// [TextEditorCodeExecutionCreateResultBlock], -// [TextEditorCodeExecutionStrReplaceResultBlock]. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -type TextEditorCodeExecutionToolResultBlockContentUnion struct { - // This field is from variant [TextEditorCodeExecutionToolResultError]. - ErrorCode TextEditorCodeExecutionToolResultErrorCode `json:"error_code"` - // This field is from variant [TextEditorCodeExecutionToolResultError]. - ErrorMessage string `json:"error_message"` - Type string `json:"type"` - // This field is from variant [TextEditorCodeExecutionViewResultBlock]. - Content string `json:"content"` - // This field is from variant [TextEditorCodeExecutionViewResultBlock]. - FileType TextEditorCodeExecutionViewResultBlockFileType `json:"file_type"` - // This field is from variant [TextEditorCodeExecutionViewResultBlock]. - NumLines int64 `json:"num_lines"` - // This field is from variant [TextEditorCodeExecutionViewResultBlock]. - StartLine int64 `json:"start_line"` - // This field is from variant [TextEditorCodeExecutionViewResultBlock]. - TotalLines int64 `json:"total_lines"` - // This field is from variant [TextEditorCodeExecutionCreateResultBlock]. - IsFileUpdate bool `json:"is_file_update"` - // This field is from variant [TextEditorCodeExecutionStrReplaceResultBlock]. - Lines []string `json:"lines"` - // This field is from variant [TextEditorCodeExecutionStrReplaceResultBlock]. - NewLines int64 `json:"new_lines"` - // This field is from variant [TextEditorCodeExecutionStrReplaceResultBlock]. - NewStart int64 `json:"new_start"` - // This field is from variant [TextEditorCodeExecutionStrReplaceResultBlock]. - OldLines int64 `json:"old_lines"` - // This field is from variant [TextEditorCodeExecutionStrReplaceResultBlock]. - OldStart int64 `json:"old_start"` - JSON struct { - ErrorCode respjson.Field - ErrorMessage respjson.Field - Type respjson.Field - Content respjson.Field - FileType respjson.Field - NumLines respjson.Field - StartLine respjson.Field - TotalLines respjson.Field - IsFileUpdate respjson.Field - Lines respjson.Field - NewLines respjson.Field - NewStart respjson.Field - OldLines respjson.Field - OldStart respjson.Field - raw string - } `json:"-"` +// The properties Signature, Thinking, Type are required. +type ThinkingBlockParam struct { + // The `signature` value of this thinking block, exactly as returned by the API in + // a previous response. Used to verify that the block was generated by Claude. + // + // Thinking blocks must be passed back unmodified and in their original order; a + // modified block results in a 400 `invalid_request_error`. + Signature string `json:"signature" api:"required"` + // The `thinking` text of this block as returned by the API. + Thinking string `json:"thinking" api:"required"` + // This field can be elided, and will marshal its zero value as "thinking". + Type constant.Thinking `json:"type" default:"thinking"` + paramObj } -func (u TextEditorCodeExecutionToolResultBlockContentUnion) AsResponseTextEditorCodeExecutionToolResultError() (v TextEditorCodeExecutionToolResultError) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +func (r ThinkingBlockParam) MarshalJSON() (data []byte, err error) { + type shadow ThinkingBlockParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *ThinkingBlockParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func (u TextEditorCodeExecutionToolResultBlockContentUnion) AsResponseTextEditorCodeExecutionViewResultBlock() (v TextEditorCodeExecutionViewResultBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +// The property Type is required. +type ThinkingConfigAdaptiveParam struct { + // Controls how thinking content appears in the response. When set to `summarized`, + // thinking is returned normally. When set to `omitted`, thinking content is + // redacted but a signature is returned for multi-turn continuity. Defaults to + // `summarized`. + // + // Any of "summarized", "omitted". + Display ThinkingConfigAdaptiveDisplay `json:"display,omitzero"` + // This field can be elided, and will marshal its zero value as "adaptive". + Type constant.Adaptive `json:"type" default:"adaptive"` + paramObj } -func (u TextEditorCodeExecutionToolResultBlockContentUnion) AsResponseTextEditorCodeExecutionCreateResultBlock() (v TextEditorCodeExecutionCreateResultBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +func (r ThinkingConfigAdaptiveParam) MarshalJSON() (data []byte, err error) { + type shadow ThinkingConfigAdaptiveParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *ThinkingConfigAdaptiveParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -func (u TextEditorCodeExecutionToolResultBlockContentUnion) AsResponseTextEditorCodeExecutionStrReplaceResultBlock() (v TextEditorCodeExecutionStrReplaceResultBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +// Controls how thinking content appears in the response. When set to `summarized`, +// thinking is returned normally. When set to `omitted`, thinking content is +// redacted but a signature is returned for multi-turn continuity. Defaults to +// `summarized`. +type ThinkingConfigAdaptiveDisplay string + +const ( + ThinkingConfigAdaptiveDisplaySummarized ThinkingConfigAdaptiveDisplay = "summarized" + ThinkingConfigAdaptiveDisplayOmitted ThinkingConfigAdaptiveDisplay = "omitted" +) + +func NewThinkingConfigDisabledParam() ThinkingConfigDisabledParam { + return ThinkingConfigDisabledParam{ + Type: "disabled", + } } -// Returns the unmodified JSON received from the API -func (u TextEditorCodeExecutionToolResultBlockContentUnion) RawJSON() string { return u.JSON.raw } +// This struct has a constant value, construct it with +// [NewThinkingConfigDisabledParam]. +type ThinkingConfigDisabledParam struct { + Type constant.Disabled `json:"type" default:"disabled"` + paramObj +} -func (r *TextEditorCodeExecutionToolResultBlockContentUnion) UnmarshalJSON(data []byte) error { +func (r ThinkingConfigDisabledParam) MarshalJSON() (data []byte, err error) { + type shadow ThinkingConfigDisabledParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *ThinkingConfigDisabledParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The properties Content, ToolUseID, Type are required. -type TextEditorCodeExecutionToolResultBlockParam struct { - Content TextEditorCodeExecutionToolResultBlockParamContentUnion `json:"content,omitzero" api:"required"` - ToolUseID string `json:"tool_use_id" api:"required"` - // Create a cache control breakpoint at this content block. - CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` - // This field can be elided, and will marshal its zero value as - // "text_editor_code_execution_tool_result". - Type constant.TextEditorCodeExecutionToolResult `json:"type" default:"text_editor_code_execution_tool_result"` +// The properties BudgetTokens, Type are required. +type ThinkingConfigEnabledParam struct { + // Determines how many tokens Claude can use for its internal reasoning process. + // Larger budgets can enable more thorough analysis for complex problems, improving + // response quality. + // + // Must be ≥1024 and less than `max_tokens`. + // + // See + // [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking) + // for details. + BudgetTokens int64 `json:"budget_tokens" api:"required"` + // Controls how thinking content appears in the response. When set to `summarized`, + // thinking is returned normally. When set to `omitted`, thinking content is + // redacted but a signature is returned for multi-turn continuity. Defaults to + // `summarized`. + // + // Any of "summarized", "omitted". + Display ThinkingConfigEnabledDisplay `json:"display,omitzero"` + // This field can be elided, and will marshal its zero value as "enabled". + Type constant.Enabled `json:"type" default:"enabled"` paramObj } -func (r TextEditorCodeExecutionToolResultBlockParam) MarshalJSON() (data []byte, err error) { - type shadow TextEditorCodeExecutionToolResultBlockParam +func (r ThinkingConfigEnabledParam) MarshalJSON() (data []byte, err error) { + type shadow ThinkingConfigEnabledParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *TextEditorCodeExecutionToolResultBlockParam) UnmarshalJSON(data []byte) error { +func (r *ThinkingConfigEnabledParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } +// Controls how thinking content appears in the response. When set to `summarized`, +// thinking is returned normally. When set to `omitted`, thinking content is +// redacted but a signature is returned for multi-turn continuity. Defaults to +// `summarized`. +type ThinkingConfigEnabledDisplay string + +const ( + ThinkingConfigEnabledDisplaySummarized ThinkingConfigEnabledDisplay = "summarized" + ThinkingConfigEnabledDisplayOmitted ThinkingConfigEnabledDisplay = "omitted" +) + +func ThinkingConfigParamOfEnabled(budgetTokens int64) ThinkingConfigParamUnion { + var enabled ThinkingConfigEnabledParam + enabled.BudgetTokens = budgetTokens + return ThinkingConfigParamUnion{OfEnabled: &enabled} +} + // Only one field can be non-zero. // // Use [param.IsOmitted] to confirm if a field is set. -type TextEditorCodeExecutionToolResultBlockParamContentUnion struct { - OfRequestTextEditorCodeExecutionToolResultError *TextEditorCodeExecutionToolResultErrorParam `json:",omitzero,inline"` - OfRequestTextEditorCodeExecutionViewResultBlock *TextEditorCodeExecutionViewResultBlockParam `json:",omitzero,inline"` - OfRequestTextEditorCodeExecutionCreateResultBlock *TextEditorCodeExecutionCreateResultBlockParam `json:",omitzero,inline"` - OfRequestTextEditorCodeExecutionStrReplaceResultBlock *TextEditorCodeExecutionStrReplaceResultBlockParam `json:",omitzero,inline"` +type ThinkingConfigParamUnion struct { + OfEnabled *ThinkingConfigEnabledParam `json:",omitzero,inline"` + OfDisabled *ThinkingConfigDisabledParam `json:",omitzero,inline"` + OfAdaptive *ThinkingConfigAdaptiveParam `json:",omitzero,inline"` paramUnion } -func (u TextEditorCodeExecutionToolResultBlockParamContentUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfRequestTextEditorCodeExecutionToolResultError, u.OfRequestTextEditorCodeExecutionViewResultBlock, u.OfRequestTextEditorCodeExecutionCreateResultBlock, u.OfRequestTextEditorCodeExecutionStrReplaceResultBlock) +func (u ThinkingConfigParamUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfEnabled, u.OfDisabled, u.OfAdaptive) } -func (u *TextEditorCodeExecutionToolResultBlockParamContentUnion) UnmarshalJSON(data []byte) error { +func (u *ThinkingConfigParamUnion) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, u) } -func (u *TextEditorCodeExecutionToolResultBlockParamContentUnion) asAny() any { - if !param.IsOmitted(u.OfRequestTextEditorCodeExecutionToolResultError) { - return u.OfRequestTextEditorCodeExecutionToolResultError - } else if !param.IsOmitted(u.OfRequestTextEditorCodeExecutionViewResultBlock) { - return u.OfRequestTextEditorCodeExecutionViewResultBlock - } else if !param.IsOmitted(u.OfRequestTextEditorCodeExecutionCreateResultBlock) { - return u.OfRequestTextEditorCodeExecutionCreateResultBlock - } else if !param.IsOmitted(u.OfRequestTextEditorCodeExecutionStrReplaceResultBlock) { - return u.OfRequestTextEditorCodeExecutionStrReplaceResultBlock +func (u *ThinkingConfigParamUnion) asAny() any { + if !param.IsOmitted(u.OfEnabled) { + return u.OfEnabled + } else if !param.IsOmitted(u.OfDisabled) { + return u.OfDisabled + } else if !param.IsOmitted(u.OfAdaptive) { + return u.OfAdaptive } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u TextEditorCodeExecutionToolResultBlockParamContentUnion) GetErrorCode() *string { - if vt := u.OfRequestTextEditorCodeExecutionToolResultError; vt != nil { - return (*string)(&vt.ErrorCode) +func (u ThinkingConfigParamUnion) GetBudgetTokens() *int64 { + if vt := u.OfEnabled; vt != nil { + return &vt.BudgetTokens } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u TextEditorCodeExecutionToolResultBlockParamContentUnion) GetErrorMessage() *string { - if vt := u.OfRequestTextEditorCodeExecutionToolResultError; vt != nil && vt.ErrorMessage.Valid() { - return &vt.ErrorMessage.Value +func (u ThinkingConfigParamUnion) GetType() *string { + if vt := u.OfEnabled; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfDisabled; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfAdaptive; vt != nil { + return (*string)(&vt.Type) } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u TextEditorCodeExecutionToolResultBlockParamContentUnion) GetContent() *string { - if vt := u.OfRequestTextEditorCodeExecutionViewResultBlock; vt != nil { - return &vt.Content +func (u ThinkingConfigParamUnion) GetDisplay() *string { + if vt := u.OfEnabled; vt != nil { + return (*string)(&vt.Display) + } else if vt := u.OfAdaptive; vt != nil { + return (*string)(&vt.Display) } return nil } -// Returns a pointer to the underlying variant's property, if present. -func (u TextEditorCodeExecutionToolResultBlockParamContentUnion) GetFileType() *string { - if vt := u.OfRequestTextEditorCodeExecutionViewResultBlock; vt != nil { - return (*string)(&vt.FileType) - } - return nil +func init() { + apijson.RegisterUnion[ThinkingConfigParamUnion]( + "type", + apijson.Discriminator[ThinkingConfigEnabledParam]("enabled"), + apijson.Discriminator[ThinkingConfigDisabledParam]("disabled"), + apijson.Discriminator[ThinkingConfigAdaptiveParam]("adaptive"), + ) } -// Returns a pointer to the underlying variant's property, if present. -func (u TextEditorCodeExecutionToolResultBlockParamContentUnion) GetNumLines() *int64 { - if vt := u.OfRequestTextEditorCodeExecutionViewResultBlock; vt != nil && vt.NumLines.Valid() { - return &vt.NumLines.Value - } - return nil +type ThinkingDelta struct { + // The incremental `thinking` text for this content block. Concatenate the + // `thinking` values of successive `thinking_delta` events to assemble the block's + // full `thinking` value. + Thinking string `json:"thinking" api:"required"` + Type constant.ThinkingDelta `json:"type" default:"thinking_delta"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Thinking respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` } -// Returns a pointer to the underlying variant's property, if present. -func (u TextEditorCodeExecutionToolResultBlockParamContentUnion) GetStartLine() *int64 { - if vt := u.OfRequestTextEditorCodeExecutionViewResultBlock; vt != nil && vt.StartLine.Valid() { - return &vt.StartLine.Value - } - return nil +// Returns the unmodified JSON received from the API +func (r ThinkingDelta) RawJSON() string { return r.JSON.raw } +func (r *ThinkingDelta) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The properties InputSchema, Name are required. +type ToolParam struct { + // [JSON schema](https://json-schema.org/draft/2020-12) for this tool's input. + // + // This defines the shape of the `input` that your tool accepts and that the model + // will produce. + InputSchema ToolInputSchemaParam `json:"input_schema,omitzero" api:"required"` + // Name of the tool. + // + // This is how the tool will be called by the model and in `tool_use` blocks. + Name string `json:"name" api:"required"` + // Enable eager input streaming for this tool. When true, tool input parameters + // will be streamed incrementally as they are generated, and types will be inferred + // on-the-fly rather than buffering the full JSON output. When false, streaming is + // disabled for this tool even if the fine-grained-tool-streaming beta is active. + // When null (default), uses the default behavior based on beta headers. + EagerInputStreaming param.Opt[bool] `json:"eager_input_streaming,omitzero"` + // If true, tool will not be included in initial system prompt. Only loaded when + // returned via tool_reference from tool search. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // Description of what this tool does. + // + // Tool descriptions should be as detailed as possible. The more information that + // the model has about what the tool is and how to use it, the better it will + // perform. You can use natural language descriptions to reinforce important + // aspects of the tool input JSON schema. + Description param.Opt[string] `json:"description,omitzero"` + // When true, guarantees schema validation on tool names and inputs + Strict param.Opt[bool] `json:"strict,omitzero"` + // Any of "custom". + Type ToolType `json:"type,omitzero"` + // Any of "direct", "code_execution_20250825", "code_execution_20260120", + // "code_execution_20260521". + AllowedCallers []string `json:"allowed_callers,omitzero"` + // Create a cache control breakpoint at this content block. + CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` + InputExamples []map[string]any `json:"input_examples,omitzero"` + paramObj +} + +func (r ToolParam) MarshalJSON() (data []byte, err error) { + type shadow ToolParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *ToolParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// [JSON schema](https://json-schema.org/draft/2020-12) for this tool's input. +// +// This defines the shape of the `input` that your tool accepts and that the model +// will produce. +// +// The property Type is required. +type ToolInputSchemaParam struct { + Properties any `json:"properties,omitzero"` + Required []string `json:"required,omitzero"` + // This field can be elided, and will marshal its zero value as "object". + Type constant.Object `json:"type" default:"object"` + ExtraFields map[string]any `json:"-"` + paramObj +} + +func (r ToolInputSchemaParam) MarshalJSON() (data []byte, err error) { + type shadow ToolInputSchemaParam + return param.MarshalWithExtras(r, (*shadow)(&r), r.ExtraFields) +} +func (r *ToolInputSchemaParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type ToolType string + +const ( + ToolTypeCustom ToolType = "custom" +) + +// The properties Name, Type are required. +type ToolBash20250124Param struct { + // If true, tool will not be included in initial system prompt. Only loaded when + // returned via tool_reference from tool search. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // When true, guarantees schema validation on tool names and inputs + Strict param.Opt[bool] `json:"strict,omitzero"` + // Any of "direct", "code_execution_20250825", "code_execution_20260120", + // "code_execution_20260521". + AllowedCallers []string `json:"allowed_callers,omitzero"` + // Create a cache control breakpoint at this content block. + CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` + InputExamples []map[string]any `json:"input_examples,omitzero"` + // Name of the tool. + // + // This is how the tool will be called by the model and in `tool_use` blocks. + // + // This field can be elided, and will marshal its zero value as "bash". + Name constant.Bash `json:"name" default:"bash"` + // This field can be elided, and will marshal its zero value as "bash_20250124". + Type constant.Bash20250124 `json:"type" default:"bash_20250124"` + paramObj } -// Returns a pointer to the underlying variant's property, if present. -func (u TextEditorCodeExecutionToolResultBlockParamContentUnion) GetTotalLines() *int64 { - if vt := u.OfRequestTextEditorCodeExecutionViewResultBlock; vt != nil && vt.TotalLines.Valid() { - return &vt.TotalLines.Value - } - return nil +func (r ToolBash20250124Param) MarshalJSON() (data []byte, err error) { + type shadow ToolBash20250124Param + return param.MarshalObject(r, (*shadow)(&r)) } - -// Returns a pointer to the underlying variant's property, if present. -func (u TextEditorCodeExecutionToolResultBlockParamContentUnion) GetIsFileUpdate() *bool { - if vt := u.OfRequestTextEditorCodeExecutionCreateResultBlock; vt != nil { - return &vt.IsFileUpdate - } - return nil +func (r *ToolBash20250124Param) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) } -// Returns a pointer to the underlying variant's property, if present. -func (u TextEditorCodeExecutionToolResultBlockParamContentUnion) GetLines() []string { - if vt := u.OfRequestTextEditorCodeExecutionStrReplaceResultBlock; vt != nil { - return vt.Lines - } - return nil +func ToolChoiceParamOfTool(name string) ToolChoiceUnionParam { + var tool ToolChoiceToolParam + tool.Name = name + return ToolChoiceUnionParam{OfTool: &tool} } -// Returns a pointer to the underlying variant's property, if present. -func (u TextEditorCodeExecutionToolResultBlockParamContentUnion) GetNewLines() *int64 { - if vt := u.OfRequestTextEditorCodeExecutionStrReplaceResultBlock; vt != nil && vt.NewLines.Valid() { - return &vt.NewLines.Value - } - return nil +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type ToolChoiceUnionParam struct { + OfAuto *ToolChoiceAutoParam `json:",omitzero,inline"` + OfAny *ToolChoiceAnyParam `json:",omitzero,inline"` + OfTool *ToolChoiceToolParam `json:",omitzero,inline"` + OfNone *ToolChoiceNoneParam `json:",omitzero,inline"` + paramUnion } -// Returns a pointer to the underlying variant's property, if present. -func (u TextEditorCodeExecutionToolResultBlockParamContentUnion) GetNewStart() *int64 { - if vt := u.OfRequestTextEditorCodeExecutionStrReplaceResultBlock; vt != nil && vt.NewStart.Valid() { - return &vt.NewStart.Value - } - return nil +func (u ToolChoiceUnionParam) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfAuto, u.OfAny, u.OfTool, u.OfNone) +} +func (u *ToolChoiceUnionParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) } -// Returns a pointer to the underlying variant's property, if present. -func (u TextEditorCodeExecutionToolResultBlockParamContentUnion) GetOldLines() *int64 { - if vt := u.OfRequestTextEditorCodeExecutionStrReplaceResultBlock; vt != nil && vt.OldLines.Valid() { - return &vt.OldLines.Value +func (u *ToolChoiceUnionParam) asAny() any { + if !param.IsOmitted(u.OfAuto) { + return u.OfAuto + } else if !param.IsOmitted(u.OfAny) { + return u.OfAny + } else if !param.IsOmitted(u.OfTool) { + return u.OfTool + } else if !param.IsOmitted(u.OfNone) { + return u.OfNone } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u TextEditorCodeExecutionToolResultBlockParamContentUnion) GetOldStart() *int64 { - if vt := u.OfRequestTextEditorCodeExecutionStrReplaceResultBlock; vt != nil && vt.OldStart.Valid() { - return &vt.OldStart.Value +func (u ToolChoiceUnionParam) GetName() *string { + if vt := u.OfTool; vt != nil { + return &vt.Name } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u TextEditorCodeExecutionToolResultBlockParamContentUnion) GetType() *string { - if vt := u.OfRequestTextEditorCodeExecutionToolResultError; vt != nil { +func (u ToolChoiceUnionParam) GetType() *string { + if vt := u.OfAuto; vt != nil { return (*string)(&vt.Type) - } else if vt := u.OfRequestTextEditorCodeExecutionViewResultBlock; vt != nil { + } else if vt := u.OfAny; vt != nil { return (*string)(&vt.Type) - } else if vt := u.OfRequestTextEditorCodeExecutionCreateResultBlock; vt != nil { + } else if vt := u.OfTool; vt != nil { return (*string)(&vt.Type) - } else if vt := u.OfRequestTextEditorCodeExecutionStrReplaceResultBlock; vt != nil { + } else if vt := u.OfNone; vt != nil { return (*string)(&vt.Type) } return nil } -type TextEditorCodeExecutionToolResultError struct { - // Any of "invalid_tool_input", "unavailable", "too_many_requests", - // "execution_time_exceeded", "file_not_found". - ErrorCode TextEditorCodeExecutionToolResultErrorCode `json:"error_code" api:"required"` - ErrorMessage string `json:"error_message" api:"required"` - Type constant.TextEditorCodeExecutionToolResultError `json:"type" default:"text_editor_code_execution_tool_result_error"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ErrorCode respjson.Field - ErrorMessage respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +// Returns a pointer to the underlying variant's property, if present. +func (u ToolChoiceUnionParam) GetDisableParallelToolUse() *bool { + if vt := u.OfAuto; vt != nil && vt.DisableParallelToolUse.Valid() { + return &vt.DisableParallelToolUse.Value + } else if vt := u.OfAny; vt != nil && vt.DisableParallelToolUse.Valid() { + return &vt.DisableParallelToolUse.Value + } else if vt := u.OfTool; vt != nil && vt.DisableParallelToolUse.Valid() { + return &vt.DisableParallelToolUse.Value + } + return nil } -// Returns the unmodified JSON received from the API -func (r TextEditorCodeExecutionToolResultError) RawJSON() string { return r.JSON.raw } -func (r *TextEditorCodeExecutionToolResultError) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +func init() { + apijson.RegisterUnion[ToolChoiceUnionParam]( + "type", + apijson.Discriminator[ToolChoiceAutoParam]("auto"), + apijson.Discriminator[ToolChoiceAnyParam]("any"), + apijson.Discriminator[ToolChoiceToolParam]("tool"), + apijson.Discriminator[ToolChoiceNoneParam]("none"), + ) } -type TextEditorCodeExecutionToolResultErrorCode string - -const ( - TextEditorCodeExecutionToolResultErrorCodeInvalidToolInput TextEditorCodeExecutionToolResultErrorCode = "invalid_tool_input" - TextEditorCodeExecutionToolResultErrorCodeUnavailable TextEditorCodeExecutionToolResultErrorCode = "unavailable" - TextEditorCodeExecutionToolResultErrorCodeTooManyRequests TextEditorCodeExecutionToolResultErrorCode = "too_many_requests" - TextEditorCodeExecutionToolResultErrorCodeExecutionTimeExceeded TextEditorCodeExecutionToolResultErrorCode = "execution_time_exceeded" - TextEditorCodeExecutionToolResultErrorCodeFileNotFound TextEditorCodeExecutionToolResultErrorCode = "file_not_found" -) - -// The properties ErrorCode, Type are required. -type TextEditorCodeExecutionToolResultErrorParam struct { - // Any of "invalid_tool_input", "unavailable", "too_many_requests", - // "execution_time_exceeded", "file_not_found". - ErrorCode TextEditorCodeExecutionToolResultErrorCode `json:"error_code,omitzero" api:"required"` - ErrorMessage param.Opt[string] `json:"error_message,omitzero"` - // This field can be elided, and will marshal its zero value as - // "text_editor_code_execution_tool_result_error". - Type constant.TextEditorCodeExecutionToolResultError `json:"type" default:"text_editor_code_execution_tool_result_error"` +// The model will use any available tools. +// +// The property Type is required. +type ToolChoiceAnyParam struct { + // Whether to disable parallel tool use. + // + // Defaults to `false`. If set to `true`, the model will output exactly one tool + // use. + DisableParallelToolUse param.Opt[bool] `json:"disable_parallel_tool_use,omitzero"` + // This field can be elided, and will marshal its zero value as "any". + Type constant.Any `json:"type" default:"any"` paramObj } -func (r TextEditorCodeExecutionToolResultErrorParam) MarshalJSON() (data []byte, err error) { - type shadow TextEditorCodeExecutionToolResultErrorParam +func (r ToolChoiceAnyParam) MarshalJSON() (data []byte, err error) { + type shadow ToolChoiceAnyParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *TextEditorCodeExecutionToolResultErrorParam) UnmarshalJSON(data []byte) error { +func (r *ToolChoiceAnyParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type TextEditorCodeExecutionViewResultBlock struct { - Content string `json:"content" api:"required"` - // Any of "text", "image", "pdf". - FileType TextEditorCodeExecutionViewResultBlockFileType `json:"file_type" api:"required"` - NumLines int64 `json:"num_lines" api:"required"` - StartLine int64 `json:"start_line" api:"required"` - TotalLines int64 `json:"total_lines" api:"required"` - Type constant.TextEditorCodeExecutionViewResult `json:"type" default:"text_editor_code_execution_view_result"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Content respjson.Field - FileType respjson.Field - NumLines respjson.Field - StartLine respjson.Field - TotalLines respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +// The model will automatically decide whether to use tools. +// +// The property Type is required. +type ToolChoiceAutoParam struct { + // Whether to disable parallel tool use. + // + // Defaults to `false`. If set to `true`, the model will output at most one tool + // use. + DisableParallelToolUse param.Opt[bool] `json:"disable_parallel_tool_use,omitzero"` + // This field can be elided, and will marshal its zero value as "auto". + Type constant.Auto `json:"type" default:"auto"` + paramObj } -// Returns the unmodified JSON received from the API -func (r TextEditorCodeExecutionViewResultBlock) RawJSON() string { return r.JSON.raw } -func (r *TextEditorCodeExecutionViewResultBlock) UnmarshalJSON(data []byte) error { +func (r ToolChoiceAutoParam) MarshalJSON() (data []byte, err error) { + type shadow ToolChoiceAutoParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *ToolChoiceAutoParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type TextEditorCodeExecutionViewResultBlockFileType string - -const ( - TextEditorCodeExecutionViewResultBlockFileTypeText TextEditorCodeExecutionViewResultBlockFileType = "text" - TextEditorCodeExecutionViewResultBlockFileTypeImage TextEditorCodeExecutionViewResultBlockFileType = "image" - TextEditorCodeExecutionViewResultBlockFileTypePDF TextEditorCodeExecutionViewResultBlockFileType = "pdf" -) +func NewToolChoiceNoneParam() ToolChoiceNoneParam { + return ToolChoiceNoneParam{ + Type: "none", + } +} -// The properties Content, FileType, Type are required. -type TextEditorCodeExecutionViewResultBlockParam struct { - Content string `json:"content" api:"required"` - // Any of "text", "image", "pdf". - FileType TextEditorCodeExecutionViewResultBlockParamFileType `json:"file_type,omitzero" api:"required"` - NumLines param.Opt[int64] `json:"num_lines,omitzero"` - StartLine param.Opt[int64] `json:"start_line,omitzero"` - TotalLines param.Opt[int64] `json:"total_lines,omitzero"` - // This field can be elided, and will marshal its zero value as - // "text_editor_code_execution_view_result". - Type constant.TextEditorCodeExecutionViewResult `json:"type" default:"text_editor_code_execution_view_result"` +// The model will not be allowed to use tools. +// +// This struct has a constant value, construct it with [NewToolChoiceNoneParam]. +type ToolChoiceNoneParam struct { + Type constant.None `json:"type" default:"none"` paramObj } -func (r TextEditorCodeExecutionViewResultBlockParam) MarshalJSON() (data []byte, err error) { - type shadow TextEditorCodeExecutionViewResultBlockParam +func (r ToolChoiceNoneParam) MarshalJSON() (data []byte, err error) { + type shadow ToolChoiceNoneParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *TextEditorCodeExecutionViewResultBlockParam) UnmarshalJSON(data []byte) error { +func (r *ToolChoiceNoneParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type TextEditorCodeExecutionViewResultBlockParamFileType string +// The model will use the specified tool with `tool_choice.name`. +// +// The properties Name, Type are required. +type ToolChoiceToolParam struct { + // The name of the tool to use. + Name string `json:"name" api:"required"` + // Whether to disable parallel tool use. + // + // Defaults to `false`. If set to `true`, the model will output exactly one tool + // use. + DisableParallelToolUse param.Opt[bool] `json:"disable_parallel_tool_use,omitzero"` + // This field can be elided, and will marshal its zero value as "tool". + Type constant.Tool `json:"type" default:"tool"` + paramObj +} -const ( - TextEditorCodeExecutionViewResultBlockParamFileTypeText TextEditorCodeExecutionViewResultBlockParamFileType = "text" - TextEditorCodeExecutionViewResultBlockParamFileTypeImage TextEditorCodeExecutionViewResultBlockParamFileType = "image" - TextEditorCodeExecutionViewResultBlockParamFileTypePDF TextEditorCodeExecutionViewResultBlockParamFileType = "pdf" -) +func (r ToolChoiceToolParam) MarshalJSON() (data []byte, err error) { + type shadow ToolChoiceToolParam + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *ToolChoiceToolParam) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} -type ThinkingBlock struct { - Signature string `json:"signature" api:"required"` - Thinking string `json:"thinking" api:"required"` - Type constant.Thinking `json:"type" default:"thinking"` +type ToolReferenceBlock struct { + ToolName string `json:"tool_name" api:"required"` + Type constant.ToolReference `json:"type" default:"tool_reference"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { - Signature respjson.Field - Thinking respjson.Field + ToolName respjson.Field Type respjson.Field ExtraFields map[string]respjson.Field raw string @@ -6219,660 +9667,1251 @@ type ThinkingBlock struct { } // Returns the unmodified JSON received from the API -func (r ThinkingBlock) RawJSON() string { return r.JSON.raw } -func (r *ThinkingBlock) UnmarshalJSON(data []byte) error { +func (r ToolReferenceBlock) RawJSON() string { return r.JSON.raw } +func (r *ToolReferenceBlock) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The properties Signature, Thinking, Type are required. -type ThinkingBlockParam struct { - Signature string `json:"signature" api:"required"` - Thinking string `json:"thinking" api:"required"` - // This field can be elided, and will marshal its zero value as "thinking". - Type constant.Thinking `json:"type" default:"thinking"` +// Tool reference block that can be included in tool_result content. +// +// The properties ToolName, Type are required. +type ToolReferenceBlockParam struct { + ToolName string `json:"tool_name" api:"required"` + // Create a cache control breakpoint at this content block. + CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` + // This field can be elided, and will marshal its zero value as "tool_reference". + Type constant.ToolReference `json:"type" default:"tool_reference"` paramObj } -func (r ThinkingBlockParam) MarshalJSON() (data []byte, err error) { - type shadow ThinkingBlockParam +func (r ToolReferenceBlockParam) MarshalJSON() (data []byte, err error) { + type shadow ToolReferenceBlockParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *ThinkingBlockParam) UnmarshalJSON(data []byte) error { +func (r *ToolReferenceBlockParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The property Type is required. -type ThinkingConfigAdaptiveParam struct { - // Controls how thinking content appears in the response. When set to `summarized`, - // thinking is returned normally. When set to `omitted`, thinking content is - // redacted but a signature is returned for multi-turn continuity. Defaults to - // `summarized`. - // - // Any of "summarized", "omitted". - Display ThinkingConfigAdaptiveDisplay `json:"display,omitzero"` - // This field can be elided, and will marshal its zero value as "adaptive". - Type constant.Adaptive `json:"type" default:"adaptive"` +// The properties ToolUseID, Type are required. +type ToolResultBlockParam struct { + ToolUseID string `json:"tool_use_id" api:"required"` + // For a toolset member tool_result, the toolset family of the paired tool_use. + ToolsetName param.Opt[string] `json:"toolset_name,omitzero"` + IsError param.Opt[bool] `json:"is_error,omitzero"` + // Create a cache control breakpoint at this content block. + CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` + Content []ToolResultBlockParamContentUnion `json:"content,omitzero"` + // This field can be elided, and will marshal its zero value as "tool_result". + Type constant.ToolResult `json:"type" default:"tool_result"` paramObj } -func (r ThinkingConfigAdaptiveParam) MarshalJSON() (data []byte, err error) { - type shadow ThinkingConfigAdaptiveParam +func (r ToolResultBlockParam) MarshalJSON() (data []byte, err error) { + type shadow ToolResultBlockParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *ThinkingConfigAdaptiveParam) UnmarshalJSON(data []byte) error { +func (r *ToolResultBlockParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// Controls how thinking content appears in the response. When set to `summarized`, -// thinking is returned normally. When set to `omitted`, thinking content is -// redacted but a signature is returned for multi-turn continuity. Defaults to -// `summarized`. -type ThinkingConfigAdaptiveDisplay string +// Only one field can be non-zero. +// +// Use [param.IsOmitted] to confirm if a field is set. +type ToolResultBlockParamContentUnion struct { + OfText *TextBlockParam `json:",omitzero,inline"` + OfImage *ImageBlockParam `json:",omitzero,inline"` + OfSearchResult *SearchResultBlockParam `json:",omitzero,inline"` + OfDocument *DocumentBlockParam `json:",omitzero,inline"` + OfToolReference *ToolReferenceBlockParam `json:",omitzero,inline"` + OfBrowserState *BrowserStateBlockParam `json:",omitzero,inline"` + paramUnion +} -const ( - ThinkingConfigAdaptiveDisplaySummarized ThinkingConfigAdaptiveDisplay = "summarized" - ThinkingConfigAdaptiveDisplayOmitted ThinkingConfigAdaptiveDisplay = "omitted" -) +func (u ToolResultBlockParamContentUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfText, + u.OfImage, + u.OfSearchResult, + u.OfDocument, + u.OfToolReference, + u.OfBrowserState) +} +func (u *ToolResultBlockParamContentUnion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, u) +} -func NewThinkingConfigDisabledParam() ThinkingConfigDisabledParam { - return ThinkingConfigDisabledParam{ - Type: "disabled", +func (u *ToolResultBlockParamContentUnion) asAny() any { + if !param.IsOmitted(u.OfText) { + return u.OfText + } else if !param.IsOmitted(u.OfImage) { + return u.OfImage + } else if !param.IsOmitted(u.OfSearchResult) { + return u.OfSearchResult + } else if !param.IsOmitted(u.OfDocument) { + return u.OfDocument + } else if !param.IsOmitted(u.OfToolReference) { + return u.OfToolReference + } else if !param.IsOmitted(u.OfBrowserState) { + return u.OfBrowserState } + return nil } -// This struct has a constant value, construct it with -// [NewThinkingConfigDisabledParam]. -type ThinkingConfigDisabledParam struct { - Type constant.Disabled `json:"type" default:"disabled"` - paramObj +// Returns a pointer to the underlying variant's property, if present. +func (u ToolResultBlockParamContentUnion) GetText() *string { + if vt := u.OfText; vt != nil { + return &vt.Text + } + return nil } -func (r ThinkingConfigDisabledParam) MarshalJSON() (data []byte, err error) { - type shadow ThinkingConfigDisabledParam - return param.MarshalObject(r, (*shadow)(&r)) +// Returns a pointer to the underlying variant's property, if present. +func (u ToolResultBlockParamContentUnion) GetTransformations() *ImageTransformationsParam { + if vt := u.OfImage; vt != nil { + return &vt.Transformations + } + return nil } -func (r *ThinkingConfigDisabledParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) + +// Returns a pointer to the underlying variant's property, if present. +func (u ToolResultBlockParamContentUnion) GetContent() []TextBlockParam { + if vt := u.OfSearchResult; vt != nil { + return vt.Content + } + return nil } -// The properties BudgetTokens, Type are required. -type ThinkingConfigEnabledParam struct { - // Determines how many tokens Claude can use for its internal reasoning process. - // Larger budgets can enable more thorough analysis for complex problems, improving - // response quality. - // - // Must be ≥1024 and less than `max_tokens`. - // - // See - // [extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking) - // for details. - BudgetTokens int64 `json:"budget_tokens" api:"required"` - // Controls how thinking content appears in the response. When set to `summarized`, - // thinking is returned normally. When set to `omitted`, thinking content is - // redacted but a signature is returned for multi-turn continuity. Defaults to - // `summarized`. - // - // Any of "summarized", "omitted". - Display ThinkingConfigEnabledDisplay `json:"display,omitzero"` - // This field can be elided, and will marshal its zero value as "enabled". - Type constant.Enabled `json:"type" default:"enabled"` - paramObj +// Returns a pointer to the underlying variant's property, if present. +func (u ToolResultBlockParamContentUnion) GetContext() *string { + if vt := u.OfDocument; vt != nil && vt.Context.Valid() { + return &vt.Context.Value + } + return nil } -func (r ThinkingConfigEnabledParam) MarshalJSON() (data []byte, err error) { - type shadow ThinkingConfigEnabledParam - return param.MarshalObject(r, (*shadow)(&r)) +// Returns a pointer to the underlying variant's property, if present. +func (u ToolResultBlockParamContentUnion) GetToolName() *string { + if vt := u.OfToolReference; vt != nil { + return &vt.ToolName + } + return nil } -func (r *ThinkingConfigEnabledParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) + +// Returns a pointer to the underlying variant's property, if present. +func (u ToolResultBlockParamContentUnion) GetTabs() []BrowserStateTabEntryParam { + if vt := u.OfBrowserState; vt != nil { + return vt.Tabs + } + return nil } -// Controls how thinking content appears in the response. When set to `summarized`, -// thinking is returned normally. When set to `omitted`, thinking content is -// redacted but a signature is returned for multi-turn continuity. Defaults to -// `summarized`. -type ThinkingConfigEnabledDisplay string +// Returns a pointer to the underlying variant's property, if present. +func (u ToolResultBlockParamContentUnion) GetStateChanges() []BrowserStateChangeUnionParam { + if vt := u.OfBrowserState; vt != nil { + return vt.StateChanges + } + return nil +} -const ( - ThinkingConfigEnabledDisplaySummarized ThinkingConfigEnabledDisplay = "summarized" - ThinkingConfigEnabledDisplayOmitted ThinkingConfigEnabledDisplay = "omitted" -) +// Returns a pointer to the underlying variant's property, if present. +func (u ToolResultBlockParamContentUnion) GetType() *string { + if vt := u.OfText; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfImage; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfSearchResult; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfDocument; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfToolReference; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfBrowserState; vt != nil { + return (*string)(&vt.Type) + } + return nil +} -func ThinkingConfigParamOfEnabled(budgetTokens int64) ThinkingConfigParamUnion { - var enabled ThinkingConfigEnabledParam - enabled.BudgetTokens = budgetTokens - return ThinkingConfigParamUnion{OfEnabled: &enabled} +// Returns a pointer to the underlying variant's property, if present. +func (u ToolResultBlockParamContentUnion) GetTitle() *string { + if vt := u.OfSearchResult; vt != nil { + return (*string)(&vt.Title) + } else if vt := u.OfDocument; vt != nil && vt.Title.Valid() { + return &vt.Title.Value + } + return nil +} + +// Returns a pointer to the underlying variant's CacheControl property, if present. +func (u ToolResultBlockParamContentUnion) GetCacheControl() *CacheControlEphemeralParam { + if vt := u.OfText; vt != nil { + return &vt.CacheControl + } else if vt := u.OfImage; vt != nil { + return &vt.CacheControl + } else if vt := u.OfSearchResult; vt != nil { + return &vt.CacheControl + } else if vt := u.OfDocument; vt != nil { + return &vt.CacheControl + } else if vt := u.OfToolReference; vt != nil { + return &vt.CacheControl + } else if vt := u.OfBrowserState; vt != nil { + return &vt.CacheControl + } + return nil +} + +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u ToolResultBlockParamContentUnion) GetCitations() (res toolResultBlockParamContentUnionCitations) { + if vt := u.OfText; vt != nil { + res.any = &vt.Citations + } else if vt := u.OfSearchResult; vt != nil { + res.any = &vt.Citations + } else if vt := u.OfDocument; vt != nil { + res.any = &vt.Citations + } + return +} + +// Can have the runtime types [*[]TextCitationParamUnion], [*CitationsConfigParam] +type toolResultBlockParamContentUnionCitations struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *[]anthropic.TextCitationParamUnion: +// case *anthropic.CitationsConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u toolResultBlockParamContentUnionCitations) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u toolResultBlockParamContentUnionCitations) GetEnabled() *bool { + switch vt := u.any.(type) { + case *CitationsConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + } + return nil } -// Only one field can be non-zero. +// Returns a subunion which exports methods to access subproperties // -// Use [param.IsOmitted] to confirm if a field is set. -type ThinkingConfigParamUnion struct { - OfEnabled *ThinkingConfigEnabledParam `json:",omitzero,inline"` - OfDisabled *ThinkingConfigDisabledParam `json:",omitzero,inline"` - OfAdaptive *ThinkingConfigAdaptiveParam `json:",omitzero,inline"` - paramUnion +// Or use AsAny() to get the underlying value +func (u ToolResultBlockParamContentUnion) GetSource() (res toolResultBlockParamContentUnionSource) { + if vt := u.OfImage; vt != nil { + res.any = vt.Source.asAny() + } else if vt := u.OfSearchResult; vt != nil { + res.any = &vt.Source + } else if vt := u.OfDocument; vt != nil { + res.any = vt.Source.asAny() + } + return } -func (u ThinkingConfigParamUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfEnabled, u.OfDisabled, u.OfAdaptive) +// Can have the runtime types [*Base64ImageSourceParam], [*URLImageSourceParam], +// [*FileImageSourceParam], [*string], [*Base64PDFSourceParam], +// [*PlainTextSourceParam], [*ContentBlockSourceParam], [*URLPDFSourceParam], +// [*FileDocumentSourceParam] +type toolResultBlockParamContentUnionSource struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.Base64ImageSourceParam: +// case *anthropic.URLImageSourceParam: +// case *anthropic.FileImageSourceParam: +// case *string: +// case *anthropic.Base64PDFSourceParam: +// case *anthropic.PlainTextSourceParam: +// case *anthropic.ContentBlockSourceParam: +// case *anthropic.URLPDFSourceParam: +// case *anthropic.FileDocumentSourceParam: +// default: +// fmt.Errorf("not present") +// } +func (u toolResultBlockParamContentUnionSource) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u toolResultBlockParamContentUnionSource) GetContent() *ContentBlockSourceContentUnionParam { + switch vt := u.any.(type) { + case *DocumentBlockParamSourceUnion: + return vt.GetContent() + } + return nil } -func (u *ThinkingConfigParamUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) + +// Returns a pointer to the underlying variant's property, if present. +func (u toolResultBlockParamContentUnionSource) GetData() *string { + switch vt := u.any.(type) { + case *ImageBlockParamSourceUnion: + return vt.GetData() + case *DocumentBlockParamSourceUnion: + return vt.GetData() + } + return nil } -func (u *ThinkingConfigParamUnion) asAny() any { - if !param.IsOmitted(u.OfEnabled) { - return u.OfEnabled - } else if !param.IsOmitted(u.OfDisabled) { - return u.OfDisabled - } else if !param.IsOmitted(u.OfAdaptive) { - return u.OfAdaptive +// Returns a pointer to the underlying variant's property, if present. +func (u toolResultBlockParamContentUnionSource) GetMediaType() *string { + switch vt := u.any.(type) { + case *ImageBlockParamSourceUnion: + return vt.GetMediaType() + case *DocumentBlockParamSourceUnion: + return vt.GetMediaType() } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u ThinkingConfigParamUnion) GetBudgetTokens() *int64 { - if vt := u.OfEnabled; vt != nil { - return &vt.BudgetTokens +func (u toolResultBlockParamContentUnionSource) GetType() *string { + switch vt := u.any.(type) { + case *ImageBlockParamSourceUnion: + return vt.GetType() + case *DocumentBlockParamSourceUnion: + return vt.GetType() } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u ThinkingConfigParamUnion) GetType() *string { - if vt := u.OfEnabled; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfDisabled; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfAdaptive; vt != nil { - return (*string)(&vt.Type) +func (u toolResultBlockParamContentUnionSource) GetURL() *string { + switch vt := u.any.(type) { + case *ImageBlockParamSourceUnion: + return vt.GetURL() + case *DocumentBlockParamSourceUnion: + return vt.GetURL() } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u ThinkingConfigParamUnion) GetDisplay() *string { - if vt := u.OfEnabled; vt != nil { - return (*string)(&vt.Display) - } else if vt := u.OfAdaptive; vt != nil { - return (*string)(&vt.Display) +func (u toolResultBlockParamContentUnionSource) GetFileID() *string { + switch vt := u.any.(type) { + case *ImageBlockParamSourceUnion: + return vt.GetFileID() + case *DocumentBlockParamSourceUnion: + return vt.GetFileID() } return nil } func init() { - apijson.RegisterUnion[ThinkingConfigParamUnion]( + apijson.RegisterUnion[ToolResultBlockParamContentUnion]( "type", - apijson.Discriminator[ThinkingConfigEnabledParam]("enabled"), - apijson.Discriminator[ThinkingConfigDisabledParam]("disabled"), - apijson.Discriminator[ThinkingConfigAdaptiveParam]("adaptive"), + apijson.Discriminator[TextBlockParam]("text"), + apijson.Discriminator[ImageBlockParam]("image"), + apijson.Discriminator[SearchResultBlockParam]("search_result"), + apijson.Discriminator[DocumentBlockParam]("document"), + apijson.Discriminator[ToolReferenceBlockParam]("tool_reference"), + apijson.Discriminator[BrowserStateBlockParam]("browser_state"), ) } -type ThinkingDelta struct { - Thinking string `json:"thinking" api:"required"` - Type constant.ThinkingDelta `json:"type" default:"thinking_delta"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Thinking respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +// The properties Name, Type are required. +type ToolSearchToolBm25_20251119Param struct { + // Any of "tool_search_tool_bm25_20251119", "tool_search_tool_bm25". + Type ToolSearchToolBm25_20251119Type `json:"type,omitzero" api:"required"` + // If true, tool will not be included in initial system prompt. Only loaded when + // returned via tool_reference from tool search. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // When true, guarantees schema validation on tool names and inputs + Strict param.Opt[bool] `json:"strict,omitzero"` + // Any of "direct", "code_execution_20250825", "code_execution_20260120", + // "code_execution_20260521". + AllowedCallers []string `json:"allowed_callers,omitzero"` + // Create a cache control breakpoint at this content block. + CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` + // Name of the tool. + // + // This is how the tool will be called by the model and in `tool_use` blocks. + // + // This field can be elided, and will marshal its zero value as + // "tool_search_tool_bm25". + Name constant.ToolSearchToolBm25 `json:"name" default:"tool_search_tool_bm25"` + paramObj } -// Returns the unmodified JSON received from the API -func (r ThinkingDelta) RawJSON() string { return r.JSON.raw } -func (r *ThinkingDelta) UnmarshalJSON(data []byte) error { +func (r ToolSearchToolBm25_20251119Param) MarshalJSON() (data []byte, err error) { + type shadow ToolSearchToolBm25_20251119Param + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *ToolSearchToolBm25_20251119Param) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The properties InputSchema, Name are required. -type ToolParam struct { - // [JSON schema](https://json-schema.org/draft/2020-12) for this tool's input. - // - // This defines the shape of the `input` that your tool accepts and that the model - // will produce. - InputSchema ToolInputSchemaParam `json:"input_schema,omitzero" api:"required"` - // Name of the tool. - // - // This is how the tool will be called by the model and in `tool_use` blocks. - Name string `json:"name" api:"required"` - // Enable eager input streaming for this tool. When true, tool input parameters - // will be streamed incrementally as they are generated, and types will be inferred - // on-the-fly rather than buffering the full JSON output. When false, streaming is - // disabled for this tool even if the fine-grained-tool-streaming beta is active. - // When null (default), uses the default behavior based on beta headers. - EagerInputStreaming param.Opt[bool] `json:"eager_input_streaming,omitzero"` +type ToolSearchToolBm25_20251119Type string + +const ( + ToolSearchToolBm25_20251119TypeToolSearchToolBm25_20251119 ToolSearchToolBm25_20251119Type = "tool_search_tool_bm25_20251119" + ToolSearchToolBm25_20251119TypeToolSearchToolBm25 ToolSearchToolBm25_20251119Type = "tool_search_tool_bm25" +) + +// The properties Name, Type are required. +type ToolSearchToolRegex20251119Param struct { + // Any of "tool_search_tool_regex_20251119", "tool_search_tool_regex". + Type ToolSearchToolRegex20251119Type `json:"type,omitzero" api:"required"` // If true, tool will not be included in initial system prompt. Only loaded when // returned via tool_reference from tool search. DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` - // Description of what this tool does. - // - // Tool descriptions should be as detailed as possible. The more information that - // the model has about what the tool is and how to use it, the better it will - // perform. You can use natural language descriptions to reinforce important - // aspects of the tool input JSON schema. - Description param.Opt[string] `json:"description,omitzero"` // When true, guarantees schema validation on tool names and inputs Strict param.Opt[bool] `json:"strict,omitzero"` - // Any of "custom". - Type ToolType `json:"type,omitzero"` - // Any of "direct", "code_execution_20250825", "code_execution_20260120". + // Any of "direct", "code_execution_20250825", "code_execution_20260120", + // "code_execution_20260521". AllowedCallers []string `json:"allowed_callers,omitzero"` // Create a cache control breakpoint at this content block. - CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` - InputExamples []map[string]any `json:"input_examples,omitzero"` + CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` + // Name of the tool. + // + // This is how the tool will be called by the model and in `tool_use` blocks. + // + // This field can be elided, and will marshal its zero value as + // "tool_search_tool_regex". + Name constant.ToolSearchToolRegex `json:"name" default:"tool_search_tool_regex"` paramObj } -func (r ToolParam) MarshalJSON() (data []byte, err error) { - type shadow ToolParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ToolParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +func (r ToolSearchToolRegex20251119Param) MarshalJSON() (data []byte, err error) { + type shadow ToolSearchToolRegex20251119Param + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *ToolSearchToolRegex20251119Param) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type ToolSearchToolRegex20251119Type string + +const ( + ToolSearchToolRegex20251119TypeToolSearchToolRegex20251119 ToolSearchToolRegex20251119Type = "tool_search_tool_regex_20251119" + ToolSearchToolRegex20251119TypeToolSearchToolRegex ToolSearchToolRegex20251119Type = "tool_search_tool_regex" +) + +type ToolSearchToolResultBlock struct { + Content ToolSearchToolResultBlockContentUnion `json:"content" api:"required"` + ToolUseID string `json:"tool_use_id" api:"required"` + Type constant.ToolSearchToolResult `json:"type" default:"tool_search_tool_result"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Content respjson.Field + ToolUseID respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r ToolSearchToolResultBlock) RawJSON() string { return r.JSON.raw } +func (r *ToolSearchToolResultBlock) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// ToolSearchToolResultBlockContentUnion contains all possible properties and +// values from [ToolSearchToolResultError], [ToolSearchToolSearchResultBlock]. +// +// Use the methods beginning with 'As' to cast the union to one of its variants. +type ToolSearchToolResultBlockContentUnion struct { + // This field is from variant [ToolSearchToolResultError]. + ErrorCode ToolSearchToolResultErrorCode `json:"error_code"` + // This field is from variant [ToolSearchToolResultError]. + ErrorMessage string `json:"error_message"` + Type string `json:"type"` + // This field is from variant [ToolSearchToolSearchResultBlock]. + ToolReferences []ToolReferenceBlock `json:"tool_references"` + JSON struct { + ErrorCode respjson.Field + ErrorMessage respjson.Field + Type respjson.Field + ToolReferences respjson.Field + raw string + } `json:"-"` +} + +func (u ToolSearchToolResultBlockContentUnion) AsResponseToolSearchToolResultError() (v ToolSearchToolResultError) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -// [JSON schema](https://json-schema.org/draft/2020-12) for this tool's input. -// -// This defines the shape of the `input` that your tool accepts and that the model -// will produce. -// -// The property Type is required. -type ToolInputSchemaParam struct { - Properties any `json:"properties,omitzero"` - Required []string `json:"required,omitzero"` - // This field can be elided, and will marshal its zero value as "object". - Type constant.Object `json:"type" default:"object"` - ExtraFields map[string]any `json:"-"` - paramObj +func (u ToolSearchToolResultBlockContentUnion) AsResponseToolSearchToolSearchResultBlock() (v ToolSearchToolSearchResultBlock) { + apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) + return } -func (r ToolInputSchemaParam) MarshalJSON() (data []byte, err error) { - type shadow ToolInputSchemaParam - return param.MarshalWithExtras(r, (*shadow)(&r), r.ExtraFields) -} -func (r *ToolInputSchemaParam) UnmarshalJSON(data []byte) error { +// Returns the unmodified JSON received from the API +func (u ToolSearchToolResultBlockContentUnion) RawJSON() string { return u.JSON.raw } + +func (r *ToolSearchToolResultBlockContentUnion) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type ToolType string - -const ( - ToolTypeCustom ToolType = "custom" -) - -// The properties Name, Type are required. -type ToolBash20250124Param struct { - // If true, tool will not be included in initial system prompt. Only loaded when - // returned via tool_reference from tool search. - DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` - // When true, guarantees schema validation on tool names and inputs - Strict param.Opt[bool] `json:"strict,omitzero"` - // Any of "direct", "code_execution_20250825", "code_execution_20260120". - AllowedCallers []string `json:"allowed_callers,omitzero"` +// The properties Content, ToolUseID, Type are required. +type ToolSearchToolResultBlockParam struct { + Content ToolSearchToolResultBlockParamContentUnion `json:"content,omitzero" api:"required"` + ToolUseID string `json:"tool_use_id" api:"required"` // Create a cache control breakpoint at this content block. - CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` - InputExamples []map[string]any `json:"input_examples,omitzero"` - // Name of the tool. - // - // This is how the tool will be called by the model and in `tool_use` blocks. - // - // This field can be elided, and will marshal its zero value as "bash". - Name constant.Bash `json:"name" default:"bash"` - // This field can be elided, and will marshal its zero value as "bash_20250124". - Type constant.Bash20250124 `json:"type" default:"bash_20250124"` + CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` + // This field can be elided, and will marshal its zero value as + // "tool_search_tool_result". + Type constant.ToolSearchToolResult `json:"type" default:"tool_search_tool_result"` paramObj } -func (r ToolBash20250124Param) MarshalJSON() (data []byte, err error) { - type shadow ToolBash20250124Param +func (r ToolSearchToolResultBlockParam) MarshalJSON() (data []byte, err error) { + type shadow ToolSearchToolResultBlockParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *ToolBash20250124Param) UnmarshalJSON(data []byte) error { +func (r *ToolSearchToolResultBlockParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -func ToolChoiceParamOfTool(name string) ToolChoiceUnionParam { - var tool ToolChoiceToolParam - tool.Name = name - return ToolChoiceUnionParam{OfTool: &tool} -} - // Only one field can be non-zero. // // Use [param.IsOmitted] to confirm if a field is set. -type ToolChoiceUnionParam struct { - OfAuto *ToolChoiceAutoParam `json:",omitzero,inline"` - OfAny *ToolChoiceAnyParam `json:",omitzero,inline"` - OfTool *ToolChoiceToolParam `json:",omitzero,inline"` - OfNone *ToolChoiceNoneParam `json:",omitzero,inline"` +type ToolSearchToolResultBlockParamContentUnion struct { + OfRequestToolSearchToolResultError *ToolSearchToolResultErrorParam `json:",omitzero,inline"` + OfRequestToolSearchToolSearchResultBlock *ToolSearchToolSearchResultBlockParam `json:",omitzero,inline"` paramUnion } -func (u ToolChoiceUnionParam) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfAuto, u.OfAny, u.OfTool, u.OfNone) +func (u ToolSearchToolResultBlockParamContentUnion) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfRequestToolSearchToolResultError, u.OfRequestToolSearchToolSearchResultBlock) } -func (u *ToolChoiceUnionParam) UnmarshalJSON(data []byte) error { +func (u *ToolSearchToolResultBlockParamContentUnion) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, u) } -func (u *ToolChoiceUnionParam) asAny() any { - if !param.IsOmitted(u.OfAuto) { - return u.OfAuto - } else if !param.IsOmitted(u.OfAny) { - return u.OfAny - } else if !param.IsOmitted(u.OfTool) { - return u.OfTool - } else if !param.IsOmitted(u.OfNone) { - return u.OfNone +func (u *ToolSearchToolResultBlockParamContentUnion) asAny() any { + if !param.IsOmitted(u.OfRequestToolSearchToolResultError) { + return u.OfRequestToolSearchToolResultError + } else if !param.IsOmitted(u.OfRequestToolSearchToolSearchResultBlock) { + return u.OfRequestToolSearchToolSearchResultBlock } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u ToolChoiceUnionParam) GetName() *string { - if vt := u.OfTool; vt != nil { - return &vt.Name +func (u ToolSearchToolResultBlockParamContentUnion) GetErrorCode() *string { + if vt := u.OfRequestToolSearchToolResultError; vt != nil { + return (*string)(&vt.ErrorCode) } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u ToolChoiceUnionParam) GetType() *string { - if vt := u.OfAuto; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfAny; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfTool; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfNone; vt != nil { - return (*string)(&vt.Type) +func (u ToolSearchToolResultBlockParamContentUnion) GetErrorMessage() *string { + if vt := u.OfRequestToolSearchToolResultError; vt != nil && vt.ErrorMessage.Valid() { + return &vt.ErrorMessage.Value } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u ToolChoiceUnionParam) GetDisableParallelToolUse() *bool { - if vt := u.OfAuto; vt != nil && vt.DisableParallelToolUse.Valid() { - return &vt.DisableParallelToolUse.Value - } else if vt := u.OfAny; vt != nil && vt.DisableParallelToolUse.Valid() { - return &vt.DisableParallelToolUse.Value - } else if vt := u.OfTool; vt != nil && vt.DisableParallelToolUse.Valid() { - return &vt.DisableParallelToolUse.Value +func (u ToolSearchToolResultBlockParamContentUnion) GetToolReferences() []ToolReferenceBlockParam { + if vt := u.OfRequestToolSearchToolSearchResultBlock; vt != nil { + return vt.ToolReferences } return nil } -func init() { - apijson.RegisterUnion[ToolChoiceUnionParam]( - "type", - apijson.Discriminator[ToolChoiceAutoParam]("auto"), - apijson.Discriminator[ToolChoiceAnyParam]("any"), - apijson.Discriminator[ToolChoiceToolParam]("tool"), - apijson.Discriminator[ToolChoiceNoneParam]("none"), - ) +// Returns a pointer to the underlying variant's property, if present. +func (u ToolSearchToolResultBlockParamContentUnion) GetType() *string { + if vt := u.OfRequestToolSearchToolResultError; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfRequestToolSearchToolSearchResultBlock; vt != nil { + return (*string)(&vt.Type) + } + return nil } -// The model will use any available tools. -// -// The property Type is required. -type ToolChoiceAnyParam struct { - // Whether to disable parallel tool use. - // - // Defaults to `false`. If set to `true`, the model will output exactly one tool - // use. - DisableParallelToolUse param.Opt[bool] `json:"disable_parallel_tool_use,omitzero"` - // This field can be elided, and will marshal its zero value as "any". - Type constant.Any `json:"type" default:"any"` - paramObj +type ToolSearchToolResultError struct { + // Any of "invalid_tool_input", "unavailable", "too_many_requests", + // "execution_time_exceeded". + ErrorCode ToolSearchToolResultErrorCode `json:"error_code" api:"required"` + ErrorMessage string `json:"error_message" api:"required"` + Type constant.ToolSearchToolResultError `json:"type" default:"tool_search_tool_result_error"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ErrorCode respjson.Field + ErrorMessage respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` } -func (r ToolChoiceAnyParam) MarshalJSON() (data []byte, err error) { - type shadow ToolChoiceAnyParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ToolChoiceAnyParam) UnmarshalJSON(data []byte) error { +// Returns the unmodified JSON received from the API +func (r ToolSearchToolResultError) RawJSON() string { return r.JSON.raw } +func (r *ToolSearchToolResultError) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The model will automatically decide whether to use tools. -// -// The property Type is required. -type ToolChoiceAutoParam struct { - // Whether to disable parallel tool use. - // - // Defaults to `false`. If set to `true`, the model will output at most one tool - // use. - DisableParallelToolUse param.Opt[bool] `json:"disable_parallel_tool_use,omitzero"` - // This field can be elided, and will marshal its zero value as "auto". - Type constant.Auto `json:"type" default:"auto"` +type ToolSearchToolResultErrorCode string + +const ( + ToolSearchToolResultErrorCodeInvalidToolInput ToolSearchToolResultErrorCode = "invalid_tool_input" + ToolSearchToolResultErrorCodeUnavailable ToolSearchToolResultErrorCode = "unavailable" + ToolSearchToolResultErrorCodeTooManyRequests ToolSearchToolResultErrorCode = "too_many_requests" + ToolSearchToolResultErrorCodeExecutionTimeExceeded ToolSearchToolResultErrorCode = "execution_time_exceeded" +) + +// The properties ErrorCode, Type are required. +type ToolSearchToolResultErrorParam struct { + // Any of "invalid_tool_input", "unavailable", "too_many_requests", + // "execution_time_exceeded". + ErrorCode ToolSearchToolResultErrorCode `json:"error_code,omitzero" api:"required"` + ErrorMessage param.Opt[string] `json:"error_message,omitzero"` + // This field can be elided, and will marshal its zero value as + // "tool_search_tool_result_error". + Type constant.ToolSearchToolResultError `json:"type" default:"tool_search_tool_result_error"` paramObj } -func (r ToolChoiceAutoParam) MarshalJSON() (data []byte, err error) { - type shadow ToolChoiceAutoParam +func (r ToolSearchToolResultErrorParam) MarshalJSON() (data []byte, err error) { + type shadow ToolSearchToolResultErrorParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *ToolChoiceAutoParam) UnmarshalJSON(data []byte) error { +func (r *ToolSearchToolResultErrorParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -func NewToolChoiceNoneParam() ToolChoiceNoneParam { - return ToolChoiceNoneParam{ - Type: "none", - } +type ToolSearchToolSearchResultBlock struct { + ToolReferences []ToolReferenceBlock `json:"tool_references" api:"required"` + Type constant.ToolSearchToolSearchResult `json:"type" default:"tool_search_tool_search_result"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ToolReferences respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` } -// The model will not be allowed to use tools. -// -// This struct has a constant value, construct it with [NewToolChoiceNoneParam]. -type ToolChoiceNoneParam struct { - Type constant.None `json:"type" default:"none"` +// Returns the unmodified JSON received from the API +func (r ToolSearchToolSearchResultBlock) RawJSON() string { return r.JSON.raw } +func (r *ToolSearchToolSearchResultBlock) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// The properties ToolReferences, Type are required. +type ToolSearchToolSearchResultBlockParam struct { + ToolReferences []ToolReferenceBlockParam `json:"tool_references,omitzero" api:"required"` + // This field can be elided, and will marshal its zero value as + // "tool_search_tool_search_result". + Type constant.ToolSearchToolSearchResult `json:"type" default:"tool_search_tool_search_result"` paramObj } -func (r ToolChoiceNoneParam) MarshalJSON() (data []byte, err error) { - type shadow ToolChoiceNoneParam +func (r ToolSearchToolSearchResultBlockParam) MarshalJSON() (data []byte, err error) { + type shadow ToolSearchToolSearchResultBlockParam return param.MarshalObject(r, (*shadow)(&r)) } -func (r *ToolChoiceNoneParam) UnmarshalJSON(data []byte) error { +func (r *ToolSearchToolSearchResultBlockParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The model will use the specified tool with `tool_choice.name`. -// // The properties Name, Type are required. -type ToolChoiceToolParam struct { - // The name of the tool to use. - Name string `json:"name" api:"required"` - // Whether to disable parallel tool use. +type ToolTextEditor20250124Param struct { + // If true, tool will not be included in initial system prompt. Only loaded when + // returned via tool_reference from tool search. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // When true, guarantees schema validation on tool names and inputs + Strict param.Opt[bool] `json:"strict,omitzero"` + // Any of "direct", "code_execution_20250825", "code_execution_20260120", + // "code_execution_20260521". + AllowedCallers []string `json:"allowed_callers,omitzero"` + // Create a cache control breakpoint at this content block. + CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` + InputExamples []map[string]any `json:"input_examples,omitzero"` + // Name of the tool. // - // Defaults to `false`. If set to `true`, the model will output exactly one tool - // use. - DisableParallelToolUse param.Opt[bool] `json:"disable_parallel_tool_use,omitzero"` - // This field can be elided, and will marshal its zero value as "tool". - Type constant.Tool `json:"type" default:"tool"` + // This is how the tool will be called by the model and in `tool_use` blocks. + // + // This field can be elided, and will marshal its zero value as + // "str_replace_editor". + Name constant.StrReplaceEditor `json:"name" default:"str_replace_editor"` + // This field can be elided, and will marshal its zero value as + // "text_editor_20250124". + Type constant.TextEditor20250124 `json:"type" default:"text_editor_20250124"` paramObj } -func (r ToolChoiceToolParam) MarshalJSON() (data []byte, err error) { - type shadow ToolChoiceToolParam +func (r ToolTextEditor20250124Param) MarshalJSON() (data []byte, err error) { + type shadow ToolTextEditor20250124Param return param.MarshalObject(r, (*shadow)(&r)) } -func (r *ToolChoiceToolParam) UnmarshalJSON(data []byte) error { +func (r *ToolTextEditor20250124Param) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -type ToolReferenceBlock struct { - ToolName string `json:"tool_name" api:"required"` - Type constant.ToolReference `json:"type" default:"tool_reference"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ToolName respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +// The properties Name, Type are required. +type ToolTextEditor20250429Param struct { + // If true, tool will not be included in initial system prompt. Only loaded when + // returned via tool_reference from tool search. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // When true, guarantees schema validation on tool names and inputs + Strict param.Opt[bool] `json:"strict,omitzero"` + // Any of "direct", "code_execution_20250825", "code_execution_20260120", + // "code_execution_20260521". + AllowedCallers []string `json:"allowed_callers,omitzero"` + // Create a cache control breakpoint at this content block. + CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` + InputExamples []map[string]any `json:"input_examples,omitzero"` + // Name of the tool. + // + // This is how the tool will be called by the model and in `tool_use` blocks. + // + // This field can be elided, and will marshal its zero value as + // "str_replace_based_edit_tool". + Name constant.StrReplaceBasedEditTool `json:"name" default:"str_replace_based_edit_tool"` + // This field can be elided, and will marshal its zero value as + // "text_editor_20250429". + Type constant.TextEditor20250429 `json:"type" default:"text_editor_20250429"` + paramObj } -// Returns the unmodified JSON received from the API -func (r ToolReferenceBlock) RawJSON() string { return r.JSON.raw } -func (r *ToolReferenceBlock) UnmarshalJSON(data []byte) error { +func (r ToolTextEditor20250429Param) MarshalJSON() (data []byte, err error) { + type shadow ToolTextEditor20250429Param + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *ToolTextEditor20250429Param) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// Tool reference block that can be included in tool_result content. -// -// The properties ToolName, Type are required. -type ToolReferenceBlockParam struct { - ToolName string `json:"tool_name" api:"required"` +// The properties Name, Type are required. +type ToolTextEditor20250728Param struct { + // Maximum number of characters to display when viewing a file. If not specified, + // defaults to displaying the full file. + MaxCharacters param.Opt[int64] `json:"max_characters,omitzero"` + // If true, tool will not be included in initial system prompt. Only loaded when + // returned via tool_reference from tool search. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // When true, guarantees schema validation on tool names and inputs + Strict param.Opt[bool] `json:"strict,omitzero"` + // Any of "direct", "code_execution_20250825", "code_execution_20260120", + // "code_execution_20260521". + AllowedCallers []string `json:"allowed_callers,omitzero"` // Create a cache control breakpoint at this content block. - CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` - // This field can be elided, and will marshal its zero value as "tool_reference". - Type constant.ToolReference `json:"type" default:"tool_reference"` + CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` + InputExamples []map[string]any `json:"input_examples,omitzero"` + // Name of the tool. + // + // This is how the tool will be called by the model and in `tool_use` blocks. + // + // This field can be elided, and will marshal its zero value as + // "str_replace_based_edit_tool". + Name constant.StrReplaceBasedEditTool `json:"name" default:"str_replace_based_edit_tool"` + // This field can be elided, and will marshal its zero value as + // "text_editor_20250728". + Type constant.TextEditor20250728 `json:"type" default:"text_editor_20250728"` paramObj } -func (r ToolReferenceBlockParam) MarshalJSON() (data []byte, err error) { - type shadow ToolReferenceBlockParam +func (r ToolTextEditor20250728Param) MarshalJSON() (data []byte, err error) { + type shadow ToolTextEditor20250728Param return param.MarshalObject(r, (*shadow)(&r)) } -func (r *ToolReferenceBlockParam) UnmarshalJSON(data []byte) error { +func (r *ToolTextEditor20250728Param) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } -// The properties ToolUseID, Type are required. -type ToolResultBlockParam struct { - ToolUseID string `json:"tool_use_id" api:"required"` - IsError param.Opt[bool] `json:"is_error,omitzero"` - // Create a cache control breakpoint at this content block. - CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` - Content []ToolResultBlockParamContentUnion `json:"content,omitzero"` - // This field can be elided, and will marshal its zero value as "tool_result". - Type constant.ToolResult `json:"type" default:"tool_result"` - paramObj +func ToolUnionParamOfTool(inputSchema ToolInputSchemaParam, name string) ToolUnionParam { + var variant ToolParam + variant.InputSchema = inputSchema + variant.Name = name + return ToolUnionParam{OfTool: &variant} } -func (r ToolResultBlockParam) MarshalJSON() (data []byte, err error) { - type shadow ToolResultBlockParam - return param.MarshalObject(r, (*shadow)(&r)) +func ToolUnionParamOfToolSearchToolBm25_20251119(type_ ToolSearchToolBm25_20251119Type) ToolUnionParam { + var variant ToolSearchToolBm25_20251119Param + variant.Type = type_ + return ToolUnionParam{OfToolSearchToolBm25_20251119: &variant} } -func (r *ToolResultBlockParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) + +func ToolUnionParamOfToolSearchToolRegex20251119(type_ ToolSearchToolRegex20251119Type) ToolUnionParam { + var variant ToolSearchToolRegex20251119Param + variant.Type = type_ + return ToolUnionParam{OfToolSearchToolRegex20251119: &variant} } // Only one field can be non-zero. // // Use [param.IsOmitted] to confirm if a field is set. -type ToolResultBlockParamContentUnion struct { - OfText *TextBlockParam `json:",omitzero,inline"` - OfImage *ImageBlockParam `json:",omitzero,inline"` - OfSearchResult *SearchResultBlockParam `json:",omitzero,inline"` - OfDocument *DocumentBlockParam `json:",omitzero,inline"` - OfToolReference *ToolReferenceBlockParam `json:",omitzero,inline"` +type ToolUnionParam struct { + OfTool *ToolParam `json:",omitzero,inline"` + OfBashTool20250124 *ToolBash20250124Param `json:",omitzero,inline"` + OfCodeExecutionTool20250522 *CodeExecutionTool20250522Param `json:",omitzero,inline"` + OfCodeExecutionTool20250825 *CodeExecutionTool20250825Param `json:",omitzero,inline"` + OfCodeExecutionTool20260120 *CodeExecutionTool20260120Param `json:",omitzero,inline"` + OfCodeExecutionTool20260521 *CodeExecutionTool20260521Param `json:",omitzero,inline"` + OfBrowserToolset20260801 *BrowserToolset20260801Param `json:",omitzero,inline"` + OfMemoryTool20250818 *MemoryTool20250818Param `json:",omitzero,inline"` + OfComputerToolset20260801 *ComputerToolset20260801Param `json:",omitzero,inline"` + OfTextEditor20250124 *ToolTextEditor20250124Param `json:",omitzero,inline"` + OfTextEditor20250429 *ToolTextEditor20250429Param `json:",omitzero,inline"` + OfTextEditor20250728 *ToolTextEditor20250728Param `json:",omitzero,inline"` + OfWebSearchTool20250305 *WebSearchTool20250305Param `json:",omitzero,inline"` + OfWebFetchTool20250910 *WebFetchTool20250910Param `json:",omitzero,inline"` + OfWebSearchTool20260209 *WebSearchTool20260209Param `json:",omitzero,inline"` + OfWebFetchTool20260209 *WebFetchTool20260209Param `json:",omitzero,inline"` + OfWebFetchTool20260309 *WebFetchTool20260309Param `json:",omitzero,inline"` + OfWebSearchTool20260318 *WebSearchTool20260318Param `json:",omitzero,inline"` + OfWebFetchTool20260318 *WebFetchTool20260318Param `json:",omitzero,inline"` + OfToolSearchToolBm25_20251119 *ToolSearchToolBm25_20251119Param `json:",omitzero,inline"` + OfToolSearchToolRegex20251119 *ToolSearchToolRegex20251119Param `json:",omitzero,inline"` paramUnion } -func (u ToolResultBlockParamContentUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfText, - u.OfImage, - u.OfSearchResult, - u.OfDocument, - u.OfToolReference) +func (u ToolUnionParam) MarshalJSON() ([]byte, error) { + return param.MarshalUnion(u, u.OfTool, + u.OfBashTool20250124, + u.OfCodeExecutionTool20250522, + u.OfCodeExecutionTool20250825, + u.OfCodeExecutionTool20260120, + u.OfCodeExecutionTool20260521, + u.OfBrowserToolset20260801, + u.OfMemoryTool20250818, + u.OfComputerToolset20260801, + u.OfTextEditor20250124, + u.OfTextEditor20250429, + u.OfTextEditor20250728, + u.OfWebSearchTool20250305, + u.OfWebFetchTool20250910, + u.OfWebSearchTool20260209, + u.OfWebFetchTool20260209, + u.OfWebFetchTool20260309, + u.OfWebSearchTool20260318, + u.OfWebFetchTool20260318, + u.OfToolSearchToolBm25_20251119, + u.OfToolSearchToolRegex20251119) } -func (u *ToolResultBlockParamContentUnion) UnmarshalJSON(data []byte) error { +func (u *ToolUnionParam) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, u) } -func (u *ToolResultBlockParamContentUnion) asAny() any { - if !param.IsOmitted(u.OfText) { - return u.OfText - } else if !param.IsOmitted(u.OfImage) { - return u.OfImage - } else if !param.IsOmitted(u.OfSearchResult) { - return u.OfSearchResult - } else if !param.IsOmitted(u.OfDocument) { - return u.OfDocument - } else if !param.IsOmitted(u.OfToolReference) { - return u.OfToolReference +func (u *ToolUnionParam) asAny() any { + if !param.IsOmitted(u.OfTool) { + return u.OfTool + } else if !param.IsOmitted(u.OfBashTool20250124) { + return u.OfBashTool20250124 + } else if !param.IsOmitted(u.OfCodeExecutionTool20250522) { + return u.OfCodeExecutionTool20250522 + } else if !param.IsOmitted(u.OfCodeExecutionTool20250825) { + return u.OfCodeExecutionTool20250825 + } else if !param.IsOmitted(u.OfCodeExecutionTool20260120) { + return u.OfCodeExecutionTool20260120 + } else if !param.IsOmitted(u.OfCodeExecutionTool20260521) { + return u.OfCodeExecutionTool20260521 + } else if !param.IsOmitted(u.OfBrowserToolset20260801) { + return u.OfBrowserToolset20260801 + } else if !param.IsOmitted(u.OfMemoryTool20250818) { + return u.OfMemoryTool20250818 + } else if !param.IsOmitted(u.OfComputerToolset20260801) { + return u.OfComputerToolset20260801 + } else if !param.IsOmitted(u.OfTextEditor20250124) { + return u.OfTextEditor20250124 + } else if !param.IsOmitted(u.OfTextEditor20250429) { + return u.OfTextEditor20250429 + } else if !param.IsOmitted(u.OfTextEditor20250728) { + return u.OfTextEditor20250728 + } else if !param.IsOmitted(u.OfWebSearchTool20250305) { + return u.OfWebSearchTool20250305 + } else if !param.IsOmitted(u.OfWebFetchTool20250910) { + return u.OfWebFetchTool20250910 + } else if !param.IsOmitted(u.OfWebSearchTool20260209) { + return u.OfWebSearchTool20260209 + } else if !param.IsOmitted(u.OfWebFetchTool20260209) { + return u.OfWebFetchTool20260209 + } else if !param.IsOmitted(u.OfWebFetchTool20260309) { + return u.OfWebFetchTool20260309 + } else if !param.IsOmitted(u.OfWebSearchTool20260318) { + return u.OfWebSearchTool20260318 + } else if !param.IsOmitted(u.OfWebFetchTool20260318) { + return u.OfWebFetchTool20260318 + } else if !param.IsOmitted(u.OfToolSearchToolBm25_20251119) { + return u.OfToolSearchToolBm25_20251119 + } else if !param.IsOmitted(u.OfToolSearchToolRegex20251119) { + return u.OfToolSearchToolRegex20251119 + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u ToolUnionParam) GetInputSchema() *ToolInputSchemaParam { + if vt := u.OfTool; vt != nil { + return &vt.InputSchema + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u ToolUnionParam) GetDescription() *string { + if vt := u.OfTool; vt != nil && vt.Description.Valid() { + return &vt.Description.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u ToolUnionParam) GetEagerInputStreaming() *bool { + if vt := u.OfTool; vt != nil && vt.EagerInputStreaming.Valid() { + return &vt.EagerInputStreaming.Value } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u ToolResultBlockParamContentUnion) GetText() *string { - if vt := u.OfText; vt != nil { - return &vt.Text +func (u ToolUnionParam) GetMaxCharacters() *int64 { + if vt := u.OfTextEditor20250728; vt != nil && vt.MaxCharacters.Valid() { + return &vt.MaxCharacters.Value } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u ToolResultBlockParamContentUnion) GetContent() []TextBlockParam { - if vt := u.OfSearchResult; vt != nil { - return vt.Content +func (u ToolUnionParam) GetName() *string { + if vt := u.OfTool; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfBashTool20250124; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfCodeExecutionTool20250522; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfCodeExecutionTool20250825; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfCodeExecutionTool20260120; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfCodeExecutionTool20260521; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfMemoryTool20250818; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfTextEditor20250124; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfTextEditor20250429; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfTextEditor20250728; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfWebSearchTool20250305; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfWebFetchTool20250910; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfWebSearchTool20260209; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfWebFetchTool20260209; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfWebFetchTool20260309; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfWebSearchTool20260318; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfWebFetchTool20260318; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil { + return (*string)(&vt.Name) + } else if vt := u.OfToolSearchToolRegex20251119; vt != nil { + return (*string)(&vt.Name) } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u ToolResultBlockParamContentUnion) GetContext() *string { - if vt := u.OfDocument; vt != nil && vt.Context.Valid() { - return &vt.Context.Value +func (u ToolUnionParam) GetDeferLoading() *bool { + if vt := u.OfTool; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfBashTool20250124; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfCodeExecutionTool20250522; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfCodeExecutionTool20250825; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfCodeExecutionTool20260120; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfCodeExecutionTool20260521; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfMemoryTool20250818; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfTextEditor20250124; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfTextEditor20250429; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfTextEditor20250728; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfWebSearchTool20250305; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfWebFetchTool20250910; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfWebSearchTool20260209; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfWebFetchTool20260209; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfWebFetchTool20260309; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfWebSearchTool20260318; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfWebFetchTool20260318; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value + } else if vt := u.OfToolSearchToolRegex20251119; vt != nil && vt.DeferLoading.Valid() { + return &vt.DeferLoading.Value } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u ToolResultBlockParamContentUnion) GetToolName() *string { - if vt := u.OfToolReference; vt != nil { - return &vt.ToolName +func (u ToolUnionParam) GetStrict() *bool { + if vt := u.OfTool; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfBashTool20250124; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfCodeExecutionTool20250522; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfCodeExecutionTool20250825; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfCodeExecutionTool20260120; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfCodeExecutionTool20260521; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfMemoryTool20250818; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfTextEditor20250124; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfTextEditor20250429; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfTextEditor20250728; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfWebSearchTool20250305; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfWebFetchTool20250910; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfWebSearchTool20260209; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfWebFetchTool20260209; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfWebFetchTool20260309; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfWebSearchTool20260318; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfWebFetchTool20260318; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value + } else if vt := u.OfToolSearchToolRegex20251119; vt != nil && vt.Strict.Valid() { + return &vt.Strict.Value } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u ToolResultBlockParamContentUnion) GetType() *string { - if vt := u.OfText; vt != nil { +func (u ToolUnionParam) GetType() *string { + if vt := u.OfTool; vt != nil { return (*string)(&vt.Type) - } else if vt := u.OfImage; vt != nil { + } else if vt := u.OfBashTool20250124; vt != nil { return (*string)(&vt.Type) - } else if vt := u.OfSearchResult; vt != nil { + } else if vt := u.OfCodeExecutionTool20250522; vt != nil { return (*string)(&vt.Type) - } else if vt := u.OfDocument; vt != nil { + } else if vt := u.OfCodeExecutionTool20250825; vt != nil { return (*string)(&vt.Type) - } else if vt := u.OfToolReference; vt != nil { + } else if vt := u.OfCodeExecutionTool20260120; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfCodeExecutionTool20260521; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfBrowserToolset20260801; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfMemoryTool20250818; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfComputerToolset20260801; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfTextEditor20250124; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfTextEditor20250429; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfTextEditor20250728; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfWebSearchTool20250305; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfWebFetchTool20250910; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfWebSearchTool20260209; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfWebFetchTool20260209; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfWebFetchTool20260309; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfWebSearchTool20260318; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfWebFetchTool20260318; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil { + return (*string)(&vt.Type) + } else if vt := u.OfToolSearchToolRegex20251119; vt != nil { return (*string)(&vt.Type) } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u ToolResultBlockParamContentUnion) GetTitle() *string { - if vt := u.OfSearchResult; vt != nil { - return (*string)(&vt.Title) - } else if vt := u.OfDocument; vt != nil && vt.Title.Valid() { - return &vt.Title.Value +func (u ToolUnionParam) GetMaxUses() *int64 { + if vt := u.OfWebSearchTool20250305; vt != nil && vt.MaxUses.Valid() { + return &vt.MaxUses.Value + } else if vt := u.OfWebFetchTool20250910; vt != nil && vt.MaxUses.Valid() { + return &vt.MaxUses.Value + } else if vt := u.OfWebSearchTool20260209; vt != nil && vt.MaxUses.Valid() { + return &vt.MaxUses.Value + } else if vt := u.OfWebFetchTool20260209; vt != nil && vt.MaxUses.Valid() { + return &vt.MaxUses.Value + } else if vt := u.OfWebFetchTool20260309; vt != nil && vt.MaxUses.Valid() { + return &vt.MaxUses.Value + } else if vt := u.OfWebSearchTool20260318; vt != nil && vt.MaxUses.Valid() { + return &vt.MaxUses.Value + } else if vt := u.OfWebFetchTool20260318; vt != nil && vt.MaxUses.Valid() { + return &vt.MaxUses.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u ToolUnionParam) GetMaxContentTokens() *int64 { + if vt := u.OfWebFetchTool20250910; vt != nil && vt.MaxContentTokens.Valid() { + return &vt.MaxContentTokens.Value + } else if vt := u.OfWebFetchTool20260209; vt != nil && vt.MaxContentTokens.Valid() { + return &vt.MaxContentTokens.Value + } else if vt := u.OfWebFetchTool20260309; vt != nil && vt.MaxContentTokens.Valid() { + return &vt.MaxContentTokens.Value + } else if vt := u.OfWebFetchTool20260318; vt != nil && vt.MaxContentTokens.Valid() { + return &vt.MaxContentTokens.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u ToolUnionParam) GetUseCache() *bool { + if vt := u.OfWebFetchTool20260309; vt != nil && vt.UseCache.Valid() { + return &vt.UseCache.Value + } else if vt := u.OfWebFetchTool20260318; vt != nil && vt.UseCache.Valid() { + return &vt.UseCache.Value + } + return nil +} + +// Returns a pointer to the underlying variant's property, if present. +func (u ToolUnionParam) GetResponseInclusion() *string { + if vt := u.OfWebSearchTool20260318; vt != nil { + return (*string)(&vt.ResponseInclusion) + } else if vt := u.OfWebFetchTool20260318; vt != nil { + return (*string)(&vt.ResponseInclusion) + } + return nil +} + +// Returns a pointer to the underlying variant's AllowedCallers property, if +// present. +func (u ToolUnionParam) GetAllowedCallers() []string { + if vt := u.OfTool; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfBashTool20250124; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfCodeExecutionTool20250522; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfCodeExecutionTool20250825; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfCodeExecutionTool20260120; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfCodeExecutionTool20260521; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfBrowserToolset20260801; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfMemoryTool20250818; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfComputerToolset20260801; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfTextEditor20250124; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfTextEditor20250429; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfTextEditor20250728; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfWebSearchTool20250305; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfWebFetchTool20250910; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfWebSearchTool20260209; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfWebFetchTool20260209; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfWebFetchTool20260309; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfWebSearchTool20260318; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfWebFetchTool20260318; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil { + return vt.AllowedCallers + } else if vt := u.OfToolSearchToolRegex20251119; vt != nil { + return vt.AllowedCallers } return nil } // Returns a pointer to the underlying variant's CacheControl property, if present. -func (u ToolResultBlockParamContentUnion) GetCacheControl() *CacheControlEphemeralParam { - if vt := u.OfText; vt != nil { +func (u ToolUnionParam) GetCacheControl() *CacheControlEphemeralParam { + if vt := u.OfTool; vt != nil { return &vt.CacheControl - } else if vt := u.OfImage; vt != nil { + } else if vt := u.OfBashTool20250124; vt != nil { return &vt.CacheControl - } else if vt := u.OfSearchResult; vt != nil { + } else if vt := u.OfCodeExecutionTool20250522; vt != nil { return &vt.CacheControl - } else if vt := u.OfDocument; vt != nil { + } else if vt := u.OfCodeExecutionTool20250825; vt != nil { return &vt.CacheControl - } else if vt := u.OfToolReference; vt != nil { + } else if vt := u.OfCodeExecutionTool20260120; vt != nil { + return &vt.CacheControl + } else if vt := u.OfCodeExecutionTool20260521; vt != nil { + return &vt.CacheControl + } else if vt := u.OfBrowserToolset20260801; vt != nil { + return &vt.CacheControl + } else if vt := u.OfMemoryTool20250818; vt != nil { + return &vt.CacheControl + } else if vt := u.OfComputerToolset20260801; vt != nil { + return &vt.CacheControl + } else if vt := u.OfTextEditor20250124; vt != nil { + return &vt.CacheControl + } else if vt := u.OfTextEditor20250429; vt != nil { + return &vt.CacheControl + } else if vt := u.OfTextEditor20250728; vt != nil { + return &vt.CacheControl + } else if vt := u.OfWebSearchTool20250305; vt != nil { + return &vt.CacheControl + } else if vt := u.OfWebFetchTool20250910; vt != nil { + return &vt.CacheControl + } else if vt := u.OfWebSearchTool20260209; vt != nil { + return &vt.CacheControl + } else if vt := u.OfWebFetchTool20260209; vt != nil { + return &vt.CacheControl + } else if vt := u.OfWebFetchTool20260309; vt != nil { + return &vt.CacheControl + } else if vt := u.OfWebSearchTool20260318; vt != nil { + return &vt.CacheControl + } else if vt := u.OfWebFetchTool20260318; vt != nil { return &vt.CacheControl + } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil { + return &vt.CacheControl + } else if vt := u.OfToolSearchToolRegex20251119; vt != nil { + return &vt.CacheControl + } + return nil +} + +// Returns a pointer to the underlying variant's InputExamples property, if +// present. +func (u ToolUnionParam) GetInputExamples() []map[string]any { + if vt := u.OfTool; vt != nil { + return vt.InputExamples + } else if vt := u.OfBashTool20250124; vt != nil { + return vt.InputExamples + } else if vt := u.OfMemoryTool20250818; vt != nil { + return vt.InputExamples + } else if vt := u.OfTextEditor20250124; vt != nil { + return vt.InputExamples + } else if vt := u.OfTextEditor20250429; vt != nil { + return vt.InputExamples + } else if vt := u.OfTextEditor20250728; vt != nil { + return vt.InputExamples } return nil } @@ -6880,942 +10919,949 @@ func (u ToolResultBlockParamContentUnion) GetCacheControl() *CacheControlEphemer // Returns a subunion which exports methods to access subproperties // // Or use AsAny() to get the underlying value -func (u ToolResultBlockParamContentUnion) GetCitations() (res toolResultBlockParamContentUnionCitations) { - if vt := u.OfText; vt != nil { - res.any = &vt.Citations - } else if vt := u.OfSearchResult; vt != nil { - res.any = &vt.Citations - } else if vt := u.OfDocument; vt != nil { - res.any = &vt.Citations +func (u ToolUnionParam) GetConfigs() (res toolUnionParamConfigs) { + if vt := u.OfBrowserToolset20260801; vt != nil { + res.any = &vt.Configs + } else if vt := u.OfComputerToolset20260801; vt != nil { + res.any = &vt.Configs } return } -// Can have the runtime types [*[]TextCitationParamUnion], [*CitationsConfigParam] -type toolResultBlockParamContentUnionCitations struct{ any } +// Can have the runtime types [*BrowserToolsetConfigsParam], +// [*ComputerToolsetConfigsParam] +type toolUnionParamConfigs struct{ any } // Use the following switch statement to get the type of the union: // // switch u.AsAny().(type) { -// case *[]anthropic.TextCitationParamUnion: -// case *anthropic.CitationsConfigParam: +// case *anthropic.BrowserToolsetConfigsParam: +// case *anthropic.ComputerToolsetConfigsParam: // default: // fmt.Errorf("not present") // } -func (u toolResultBlockParamContentUnionCitations) AsAny() any { return u.any } +func (u toolUnionParamConfigs) AsAny() any { return u.any } // Returns a pointer to the underlying variant's property, if present. -func (u toolResultBlockParamContentUnionCitations) GetEnabled() *bool { +func (u toolUnionParamConfigs) GetCloseTab() *BrowserCloseTabConfigParam { switch vt := u.any.(type) { - case *CitationsConfigParam: - return paramutil.AddrIfPresent(vt.Enabled) + case *BrowserToolsetConfigsParam: + return &vt.CloseTab } return nil } -// Returns a subunion which exports methods to access subproperties -// -// Or use AsAny() to get the underlying value -func (u ToolResultBlockParamContentUnion) GetSource() (res toolResultBlockParamContentUnionSource) { - if vt := u.OfImage; vt != nil { - res.any = vt.Source.asAny() - } else if vt := u.OfSearchResult; vt != nil { - res.any = &vt.Source - } else if vt := u.OfDocument; vt != nil { - res.any = vt.Source.asAny() +// Returns a pointer to the underlying variant's property, if present. +func (u toolUnionParamConfigs) GetFileUpload() *BrowserFileUploadConfigParam { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + return &vt.FileUpload } - return + return nil } -// Can have the runtime types [*Base64ImageSourceParam], [*URLImageSourceParam], -// [*string], [*Base64PDFSourceParam], [*PlainTextSourceParam], -// [*ContentBlockSourceParam], [*URLPDFSourceParam] -type toolResultBlockParamContentUnionSource struct{ any } - -// Use the following switch statement to get the type of the union: -// -// switch u.AsAny().(type) { -// case *anthropic.Base64ImageSourceParam: -// case *anthropic.URLImageSourceParam: -// case *string: -// case *anthropic.Base64PDFSourceParam: -// case *anthropic.PlainTextSourceParam: -// case *anthropic.ContentBlockSourceParam: -// case *anthropic.URLPDFSourceParam: -// default: -// fmt.Errorf("not present") -// } -func (u toolResultBlockParamContentUnionSource) AsAny() any { return u.any } - // Returns a pointer to the underlying variant's property, if present. -func (u toolResultBlockParamContentUnionSource) GetContent() *ContentBlockSourceContentUnionParam { +func (u toolUnionParamConfigs) GetFind() *BrowserFindConfigParam { switch vt := u.any.(type) { - case *DocumentBlockParamSourceUnion: - return vt.GetContent() + case *BrowserToolsetConfigsParam: + return &vt.Find } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u toolResultBlockParamContentUnionSource) GetData() *string { +func (u toolUnionParamConfigs) GetFormInput() *BrowserFormInputConfigParam { switch vt := u.any.(type) { - case *ImageBlockParamSourceUnion: - return vt.GetData() - case *DocumentBlockParamSourceUnion: - return vt.GetData() + case *BrowserToolsetConfigsParam: + return &vt.FormInput } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u toolResultBlockParamContentUnionSource) GetMediaType() *string { +func (u toolUnionParamConfigs) GetGetPageText() *BrowserGetPageTextConfigParam { switch vt := u.any.(type) { - case *ImageBlockParamSourceUnion: - return vt.GetMediaType() - case *DocumentBlockParamSourceUnion: - return vt.GetMediaType() + case *BrowserToolsetConfigsParam: + return &vt.GetPageText } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u toolResultBlockParamContentUnionSource) GetType() *string { +func (u toolUnionParamConfigs) GetHover() *BrowserHoverConfigParam { switch vt := u.any.(type) { - case *ImageBlockParamSourceUnion: - return vt.GetType() - case *DocumentBlockParamSourceUnion: - return vt.GetType() + case *BrowserToolsetConfigsParam: + return &vt.Hover } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u toolResultBlockParamContentUnionSource) GetURL() *string { +func (u toolUnionParamConfigs) GetJavascriptExec() *BrowserJavascriptExecConfigParam { switch vt := u.any.(type) { - case *ImageBlockParamSourceUnion: - return vt.GetURL() - case *DocumentBlockParamSourceUnion: - return vt.GetURL() + case *BrowserToolsetConfigsParam: + return &vt.JavascriptExec } return nil } -func init() { - apijson.RegisterUnion[ToolResultBlockParamContentUnion]( - "type", - apijson.Discriminator[TextBlockParam]("text"), - apijson.Discriminator[ImageBlockParam]("image"), - apijson.Discriminator[SearchResultBlockParam]("search_result"), - apijson.Discriminator[DocumentBlockParam]("document"), - apijson.Discriminator[ToolReferenceBlockParam]("tool_reference"), - ) -} - -// The properties Name, Type are required. -type ToolSearchToolBm25_20251119Param struct { - // Any of "tool_search_tool_bm25_20251119", "tool_search_tool_bm25". - Type ToolSearchToolBm25_20251119Type `json:"type,omitzero" api:"required"` - // If true, tool will not be included in initial system prompt. Only loaded when - // returned via tool_reference from tool search. - DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` - // When true, guarantees schema validation on tool names and inputs - Strict param.Opt[bool] `json:"strict,omitzero"` - // Any of "direct", "code_execution_20250825", "code_execution_20260120". - AllowedCallers []string `json:"allowed_callers,omitzero"` - // Create a cache control breakpoint at this content block. - CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` - // Name of the tool. - // - // This is how the tool will be called by the model and in `tool_use` blocks. - // - // This field can be elided, and will marshal its zero value as - // "tool_search_tool_bm25". - Name constant.ToolSearchToolBm25 `json:"name" default:"tool_search_tool_bm25"` - paramObj -} - -func (r ToolSearchToolBm25_20251119Param) MarshalJSON() (data []byte, err error) { - type shadow ToolSearchToolBm25_20251119Param - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ToolSearchToolBm25_20251119Param) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type ToolSearchToolBm25_20251119Type string - -const ( - ToolSearchToolBm25_20251119TypeToolSearchToolBm25_20251119 ToolSearchToolBm25_20251119Type = "tool_search_tool_bm25_20251119" - ToolSearchToolBm25_20251119TypeToolSearchToolBm25 ToolSearchToolBm25_20251119Type = "tool_search_tool_bm25" -) - -// The properties Name, Type are required. -type ToolSearchToolRegex20251119Param struct { - // Any of "tool_search_tool_regex_20251119", "tool_search_tool_regex". - Type ToolSearchToolRegex20251119Type `json:"type,omitzero" api:"required"` - // If true, tool will not be included in initial system prompt. Only loaded when - // returned via tool_reference from tool search. - DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` - // When true, guarantees schema validation on tool names and inputs - Strict param.Opt[bool] `json:"strict,omitzero"` - // Any of "direct", "code_execution_20250825", "code_execution_20260120". - AllowedCallers []string `json:"allowed_callers,omitzero"` - // Create a cache control breakpoint at this content block. - CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` - // Name of the tool. - // - // This is how the tool will be called by the model and in `tool_use` blocks. - // - // This field can be elided, and will marshal its zero value as - // "tool_search_tool_regex". - Name constant.ToolSearchToolRegex `json:"name" default:"tool_search_tool_regex"` - paramObj -} - -func (r ToolSearchToolRegex20251119Param) MarshalJSON() (data []byte, err error) { - type shadow ToolSearchToolRegex20251119Param - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ToolSearchToolRegex20251119Param) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type ToolSearchToolRegex20251119Type string - -const ( - ToolSearchToolRegex20251119TypeToolSearchToolRegex20251119 ToolSearchToolRegex20251119Type = "tool_search_tool_regex_20251119" - ToolSearchToolRegex20251119TypeToolSearchToolRegex ToolSearchToolRegex20251119Type = "tool_search_tool_regex" -) - -type ToolSearchToolResultBlock struct { - Content ToolSearchToolResultBlockContentUnion `json:"content" api:"required"` - ToolUseID string `json:"tool_use_id" api:"required"` - Type constant.ToolSearchToolResult `json:"type" default:"tool_search_tool_result"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Content respjson.Field - ToolUseID respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ToolSearchToolResultBlock) RawJSON() string { return r.JSON.raw } -func (r *ToolSearchToolResultBlock) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +// Returns a pointer to the underlying variant's property, if present. +func (u toolUnionParamConfigs) GetListTabs() *BrowserListTabsConfigParam { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + return &vt.ListTabs + } + return nil } -// ToolSearchToolResultBlockContentUnion contains all possible properties and -// values from [ToolSearchToolResultError], [ToolSearchToolSearchResultBlock]. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -type ToolSearchToolResultBlockContentUnion struct { - // This field is from variant [ToolSearchToolResultError]. - ErrorCode ToolSearchToolResultErrorCode `json:"error_code"` - // This field is from variant [ToolSearchToolResultError]. - ErrorMessage string `json:"error_message"` - Type string `json:"type"` - // This field is from variant [ToolSearchToolSearchResultBlock]. - ToolReferences []ToolReferenceBlock `json:"tool_references"` - JSON struct { - ErrorCode respjson.Field - ErrorMessage respjson.Field - Type respjson.Field - ToolReferences respjson.Field - raw string - } `json:"-"` +// Returns a pointer to the underlying variant's property, if present. +func (u toolUnionParamConfigs) GetNavigate() *BrowserNavigateConfigParam { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + return &vt.Navigate + } + return nil } -func (u ToolSearchToolResultBlockContentUnion) AsResponseToolSearchToolResultError() (v ToolSearchToolResultError) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +// Returns a pointer to the underlying variant's property, if present. +func (u toolUnionParamConfigs) GetNewTab() *BrowserNewTabConfigParam { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + return &vt.NewTab + } + return nil } -func (u ToolSearchToolResultBlockContentUnion) AsResponseToolSearchToolSearchResultBlock() (v ToolSearchToolSearchResultBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return +// Returns a pointer to the underlying variant's property, if present. +func (u toolUnionParamConfigs) GetReadConsole() *BrowserReadConsoleConfigParam { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + return &vt.ReadConsole + } + return nil } -// Returns the unmodified JSON received from the API -func (u ToolSearchToolResultBlockContentUnion) RawJSON() string { return u.JSON.raw } +// Returns a pointer to the underlying variant's property, if present. +func (u toolUnionParamConfigs) GetReadNetwork() *BrowserReadNetworkConfigParam { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + return &vt.ReadNetwork + } + return nil +} -func (r *ToolSearchToolResultBlockContentUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +// Returns a pointer to the underlying variant's property, if present. +func (u toolUnionParamConfigs) GetReadPage() *BrowserReadPageConfigParam { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + return &vt.ReadPage + } + return nil } -// The properties Content, ToolUseID, Type are required. -type ToolSearchToolResultBlockParam struct { - Content ToolSearchToolResultBlockParamContentUnion `json:"content,omitzero" api:"required"` - ToolUseID string `json:"tool_use_id" api:"required"` - // Create a cache control breakpoint at this content block. - CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` - // This field can be elided, and will marshal its zero value as - // "tool_search_tool_result". - Type constant.ToolSearchToolResult `json:"type" default:"tool_search_tool_result"` - paramObj +// Returns a pointer to the underlying variant's property, if present. +func (u toolUnionParamConfigs) GetScrollTo() *BrowserScrollToConfigParam { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + return &vt.ScrollTo + } + return nil } -func (r ToolSearchToolResultBlockParam) MarshalJSON() (data []byte, err error) { - type shadow ToolSearchToolResultBlockParam - return param.MarshalObject(r, (*shadow)(&r)) +// Returns a pointer to the underlying variant's property, if present. +func (u toolUnionParamConfigs) GetSwitchTab() *BrowserSwitchTabConfigParam { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + return &vt.SwitchTab + } + return nil } -func (r *ToolSearchToolResultBlockParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) + +// Returns a pointer to the underlying variant's property, if present. +func (u toolUnionParamConfigs) GetCursorPosition() *ComputerCursorPositionConfigParam { + switch vt := u.any.(type) { + case *ComputerToolsetConfigsParam: + return &vt.CursorPosition + } + return nil } -// Only one field can be non-zero. +// Returns a subunion which exports methods to access subproperties // -// Use [param.IsOmitted] to confirm if a field is set. -type ToolSearchToolResultBlockParamContentUnion struct { - OfRequestToolSearchToolResultError *ToolSearchToolResultErrorParam `json:",omitzero,inline"` - OfRequestToolSearchToolSearchResultBlock *ToolSearchToolSearchResultBlockParam `json:",omitzero,inline"` - paramUnion +// Or use AsAny() to get the underlying value +func (u toolUnionParamConfigs) GetDoubleClick() (res toolUnionParamConfigsDoubleClick) { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + res.any = &vt.DoubleClick + case *ComputerToolsetConfigsParam: + res.any = &vt.DoubleClick + } + return res } -func (u ToolSearchToolResultBlockParamContentUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfRequestToolSearchToolResultError, u.OfRequestToolSearchToolSearchResultBlock) -} -func (u *ToolSearchToolResultBlockParamContentUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} +// Can have the runtime types [*BrowserDoubleClickConfigParam], +// [*ComputerDoubleClickConfigParam] +type toolUnionParamConfigsDoubleClick struct{ any } -func (u *ToolSearchToolResultBlockParamContentUnion) asAny() any { - if !param.IsOmitted(u.OfRequestToolSearchToolResultError) { - return u.OfRequestToolSearchToolResultError - } else if !param.IsOmitted(u.OfRequestToolSearchToolSearchResultBlock) { - return u.OfRequestToolSearchToolSearchResultBlock +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BrowserDoubleClickConfigParam: +// case *anthropic.ComputerDoubleClickConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u toolUnionParamConfigsDoubleClick) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u toolUnionParamConfigsDoubleClick) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BrowserDoubleClickConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *ComputerDoubleClickConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u ToolSearchToolResultBlockParamContentUnion) GetErrorCode() *string { - if vt := u.OfRequestToolSearchToolResultError; vt != nil { - return (*string)(&vt.ErrorCode) +func (u toolUnionParamConfigsDoubleClick) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BrowserDoubleClickConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *ComputerDoubleClickConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) } return nil } -// Returns a pointer to the underlying variant's property, if present. -func (u ToolSearchToolResultBlockParamContentUnion) GetToolReferences() []ToolReferenceBlockParam { - if vt := u.OfRequestToolSearchToolSearchResultBlock; vt != nil { - return vt.ToolReferences +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u toolUnionParamConfigs) GetHoldKey() (res toolUnionParamConfigsHoldKey) { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + res.any = &vt.HoldKey + case *ComputerToolsetConfigsParam: + res.any = &vt.HoldKey } - return nil + return res } +// Can have the runtime types [*BrowserHoldKeyConfigParam], +// [*ComputerHoldKeyConfigParam] +type toolUnionParamConfigsHoldKey struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BrowserHoldKeyConfigParam: +// case *anthropic.ComputerHoldKeyConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u toolUnionParamConfigsHoldKey) AsAny() any { return u.any } + // Returns a pointer to the underlying variant's property, if present. -func (u ToolSearchToolResultBlockParamContentUnion) GetType() *string { - if vt := u.OfRequestToolSearchToolResultError; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfRequestToolSearchToolSearchResultBlock; vt != nil { - return (*string)(&vt.Type) +func (u toolUnionParamConfigsHoldKey) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BrowserHoldKeyConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *ComputerHoldKeyConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) } return nil } -type ToolSearchToolResultError struct { - // Any of "invalid_tool_input", "unavailable", "too_many_requests", - // "execution_time_exceeded". - ErrorCode ToolSearchToolResultErrorCode `json:"error_code" api:"required"` - ErrorMessage string `json:"error_message" api:"required"` - Type constant.ToolSearchToolResultError `json:"type" default:"tool_search_tool_result_error"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ErrorCode respjson.Field - ErrorMessage respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +// Returns a pointer to the underlying variant's property, if present. +func (u toolUnionParamConfigsHoldKey) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BrowserHoldKeyConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *ComputerHoldKeyConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + } + return nil } -// Returns the unmodified JSON received from the API -func (r ToolSearchToolResultError) RawJSON() string { return r.JSON.raw } -func (r *ToolSearchToolResultError) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u toolUnionParamConfigs) GetKey() (res toolUnionParamConfigsKey) { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + res.any = &vt.Key + case *ComputerToolsetConfigsParam: + res.any = &vt.Key + } + return res } -type ToolSearchToolResultErrorCode string +// Can have the runtime types [*BrowserKeyConfigParam], [*ComputerKeyConfigParam] +type toolUnionParamConfigsKey struct{ any } -const ( - ToolSearchToolResultErrorCodeInvalidToolInput ToolSearchToolResultErrorCode = "invalid_tool_input" - ToolSearchToolResultErrorCodeUnavailable ToolSearchToolResultErrorCode = "unavailable" - ToolSearchToolResultErrorCodeTooManyRequests ToolSearchToolResultErrorCode = "too_many_requests" - ToolSearchToolResultErrorCodeExecutionTimeExceeded ToolSearchToolResultErrorCode = "execution_time_exceeded" -) +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BrowserKeyConfigParam: +// case *anthropic.ComputerKeyConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u toolUnionParamConfigsKey) AsAny() any { return u.any } -// The properties ErrorCode, Type are required. -type ToolSearchToolResultErrorParam struct { - // Any of "invalid_tool_input", "unavailable", "too_many_requests", - // "execution_time_exceeded". - ErrorCode ToolSearchToolResultErrorCode `json:"error_code,omitzero" api:"required"` - // This field can be elided, and will marshal its zero value as - // "tool_search_tool_result_error". - Type constant.ToolSearchToolResultError `json:"type" default:"tool_search_tool_result_error"` - paramObj +// Returns a pointer to the underlying variant's property, if present. +func (u toolUnionParamConfigsKey) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BrowserKeyConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *ComputerKeyConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + } + return nil } -func (r ToolSearchToolResultErrorParam) MarshalJSON() (data []byte, err error) { - type shadow ToolSearchToolResultErrorParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ToolSearchToolResultErrorParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +// Returns a pointer to the underlying variant's property, if present. +func (u toolUnionParamConfigsKey) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BrowserKeyConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *ComputerKeyConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + } + return nil } -type ToolSearchToolSearchResultBlock struct { - ToolReferences []ToolReferenceBlock `json:"tool_references" api:"required"` - Type constant.ToolSearchToolSearchResult `json:"type" default:"tool_search_tool_search_result"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ToolReferences respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u toolUnionParamConfigs) GetLeftClick() (res toolUnionParamConfigsLeftClick) { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + res.any = &vt.LeftClick + case *ComputerToolsetConfigsParam: + res.any = &vt.LeftClick + } + return res } -// Returns the unmodified JSON received from the API -func (r ToolSearchToolSearchResultBlock) RawJSON() string { return r.JSON.raw } -func (r *ToolSearchToolSearchResultBlock) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} +// Can have the runtime types [*BrowserLeftClickConfigParam], +// [*ComputerLeftClickConfigParam] +type toolUnionParamConfigsLeftClick struct{ any } -// The properties ToolReferences, Type are required. -type ToolSearchToolSearchResultBlockParam struct { - ToolReferences []ToolReferenceBlockParam `json:"tool_references,omitzero" api:"required"` - // This field can be elided, and will marshal its zero value as - // "tool_search_tool_search_result". - Type constant.ToolSearchToolSearchResult `json:"type" default:"tool_search_tool_search_result"` - paramObj -} +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BrowserLeftClickConfigParam: +// case *anthropic.ComputerLeftClickConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u toolUnionParamConfigsLeftClick) AsAny() any { return u.any } -func (r ToolSearchToolSearchResultBlockParam) MarshalJSON() (data []byte, err error) { - type shadow ToolSearchToolSearchResultBlockParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ToolSearchToolSearchResultBlockParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +// Returns a pointer to the underlying variant's property, if present. +func (u toolUnionParamConfigsLeftClick) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BrowserLeftClickConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *ComputerLeftClickConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + } + return nil } -// The properties Name, Type are required. -type ToolTextEditor20250124Param struct { - // If true, tool will not be included in initial system prompt. Only loaded when - // returned via tool_reference from tool search. - DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` - // When true, guarantees schema validation on tool names and inputs - Strict param.Opt[bool] `json:"strict,omitzero"` - // Any of "direct", "code_execution_20250825", "code_execution_20260120". - AllowedCallers []string `json:"allowed_callers,omitzero"` - // Create a cache control breakpoint at this content block. - CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` - InputExamples []map[string]any `json:"input_examples,omitzero"` - // Name of the tool. - // - // This is how the tool will be called by the model and in `tool_use` blocks. - // - // This field can be elided, and will marshal its zero value as - // "str_replace_editor". - Name constant.StrReplaceEditor `json:"name" default:"str_replace_editor"` - // This field can be elided, and will marshal its zero value as - // "text_editor_20250124". - Type constant.TextEditor20250124 `json:"type" default:"text_editor_20250124"` - paramObj +// Returns a pointer to the underlying variant's property, if present. +func (u toolUnionParamConfigsLeftClick) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BrowserLeftClickConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *ComputerLeftClickConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + } + return nil } -func (r ToolTextEditor20250124Param) MarshalJSON() (data []byte, err error) { - type shadow ToolTextEditor20250124Param - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ToolTextEditor20250124Param) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u toolUnionParamConfigs) GetLeftClickDrag() (res toolUnionParamConfigsLeftClickDrag) { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + res.any = &vt.LeftClickDrag + case *ComputerToolsetConfigsParam: + res.any = &vt.LeftClickDrag + } + return res } -// The properties Name, Type are required. -type ToolTextEditor20250429Param struct { - // If true, tool will not be included in initial system prompt. Only loaded when - // returned via tool_reference from tool search. - DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` - // When true, guarantees schema validation on tool names and inputs - Strict param.Opt[bool] `json:"strict,omitzero"` - // Any of "direct", "code_execution_20250825", "code_execution_20260120". - AllowedCallers []string `json:"allowed_callers,omitzero"` - // Create a cache control breakpoint at this content block. - CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` - InputExamples []map[string]any `json:"input_examples,omitzero"` - // Name of the tool. - // - // This is how the tool will be called by the model and in `tool_use` blocks. - // - // This field can be elided, and will marshal its zero value as - // "str_replace_based_edit_tool". - Name constant.StrReplaceBasedEditTool `json:"name" default:"str_replace_based_edit_tool"` - // This field can be elided, and will marshal its zero value as - // "text_editor_20250429". - Type constant.TextEditor20250429 `json:"type" default:"text_editor_20250429"` - paramObj +// Can have the runtime types [*BrowserLeftClickDragConfigParam], +// [*ComputerLeftClickDragConfigParam] +type toolUnionParamConfigsLeftClickDrag struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BrowserLeftClickDragConfigParam: +// case *anthropic.ComputerLeftClickDragConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u toolUnionParamConfigsLeftClickDrag) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u toolUnionParamConfigsLeftClickDrag) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BrowserLeftClickDragConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *ComputerLeftClickDragConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + } + return nil } -func (r ToolTextEditor20250429Param) MarshalJSON() (data []byte, err error) { - type shadow ToolTextEditor20250429Param - return param.MarshalObject(r, (*shadow)(&r)) +// Returns a pointer to the underlying variant's property, if present. +func (u toolUnionParamConfigsLeftClickDrag) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BrowserLeftClickDragConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *ComputerLeftClickDragConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + } + return nil } -func (r *ToolTextEditor20250429Param) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) + +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u toolUnionParamConfigs) GetLeftMouseDown() (res toolUnionParamConfigsLeftMouseDown) { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + res.any = &vt.LeftMouseDown + case *ComputerToolsetConfigsParam: + res.any = &vt.LeftMouseDown + } + return res } -// The properties Name, Type are required. -type ToolTextEditor20250728Param struct { - // Maximum number of characters to display when viewing a file. If not specified, - // defaults to displaying the full file. - MaxCharacters param.Opt[int64] `json:"max_characters,omitzero"` - // If true, tool will not be included in initial system prompt. Only loaded when - // returned via tool_reference from tool search. - DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` - // When true, guarantees schema validation on tool names and inputs - Strict param.Opt[bool] `json:"strict,omitzero"` - // Any of "direct", "code_execution_20250825", "code_execution_20260120". - AllowedCallers []string `json:"allowed_callers,omitzero"` - // Create a cache control breakpoint at this content block. - CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` - InputExamples []map[string]any `json:"input_examples,omitzero"` - // Name of the tool. - // - // This is how the tool will be called by the model and in `tool_use` blocks. - // - // This field can be elided, and will marshal its zero value as - // "str_replace_based_edit_tool". - Name constant.StrReplaceBasedEditTool `json:"name" default:"str_replace_based_edit_tool"` - // This field can be elided, and will marshal its zero value as - // "text_editor_20250728". - Type constant.TextEditor20250728 `json:"type" default:"text_editor_20250728"` - paramObj +// Can have the runtime types [*BrowserLeftMouseDownConfigParam], +// [*ComputerLeftMouseDownConfigParam] +type toolUnionParamConfigsLeftMouseDown struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BrowserLeftMouseDownConfigParam: +// case *anthropic.ComputerLeftMouseDownConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u toolUnionParamConfigsLeftMouseDown) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u toolUnionParamConfigsLeftMouseDown) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BrowserLeftMouseDownConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *ComputerLeftMouseDownConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + } + return nil } -func (r ToolTextEditor20250728Param) MarshalJSON() (data []byte, err error) { - type shadow ToolTextEditor20250728Param - return param.MarshalObject(r, (*shadow)(&r)) +// Returns a pointer to the underlying variant's property, if present. +func (u toolUnionParamConfigsLeftMouseDown) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BrowserLeftMouseDownConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *ComputerLeftMouseDownConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + } + return nil } -func (r *ToolTextEditor20250728Param) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) + +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u toolUnionParamConfigs) GetLeftMouseUp() (res toolUnionParamConfigsLeftMouseUp) { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + res.any = &vt.LeftMouseUp + case *ComputerToolsetConfigsParam: + res.any = &vt.LeftMouseUp + } + return res } -func ToolUnionParamOfTool(inputSchema ToolInputSchemaParam, name string) ToolUnionParam { - var variant ToolParam - variant.InputSchema = inputSchema - variant.Name = name - return ToolUnionParam{OfTool: &variant} +// Can have the runtime types [*BrowserLeftMouseUpConfigParam], +// [*ComputerLeftMouseUpConfigParam] +type toolUnionParamConfigsLeftMouseUp struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BrowserLeftMouseUpConfigParam: +// case *anthropic.ComputerLeftMouseUpConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u toolUnionParamConfigsLeftMouseUp) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u toolUnionParamConfigsLeftMouseUp) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BrowserLeftMouseUpConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *ComputerLeftMouseUpConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + } + return nil } -func ToolUnionParamOfToolSearchToolBm25_20251119(type_ ToolSearchToolBm25_20251119Type) ToolUnionParam { - var variant ToolSearchToolBm25_20251119Param - variant.Type = type_ - return ToolUnionParam{OfToolSearchToolBm25_20251119: &variant} +// Returns a pointer to the underlying variant's property, if present. +func (u toolUnionParamConfigsLeftMouseUp) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BrowserLeftMouseUpConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *ComputerLeftMouseUpConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + } + return nil } -func ToolUnionParamOfToolSearchToolRegex20251119(type_ ToolSearchToolRegex20251119Type) ToolUnionParam { - var variant ToolSearchToolRegex20251119Param - variant.Type = type_ - return ToolUnionParam{OfToolSearchToolRegex20251119: &variant} +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u toolUnionParamConfigs) GetMiddleClick() (res toolUnionParamConfigsMiddleClick) { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + res.any = &vt.MiddleClick + case *ComputerToolsetConfigsParam: + res.any = &vt.MiddleClick + } + return res } -// Only one field can be non-zero. +// Can have the runtime types [*BrowserMiddleClickConfigParam], +// [*ComputerMiddleClickConfigParam] +type toolUnionParamConfigsMiddleClick struct{ any } + +// Use the following switch statement to get the type of the union: // -// Use [param.IsOmitted] to confirm if a field is set. -type ToolUnionParam struct { - OfTool *ToolParam `json:",omitzero,inline"` - OfBashTool20250124 *ToolBash20250124Param `json:",omitzero,inline"` - OfCodeExecutionTool20250522 *CodeExecutionTool20250522Param `json:",omitzero,inline"` - OfCodeExecutionTool20250825 *CodeExecutionTool20250825Param `json:",omitzero,inline"` - OfCodeExecutionTool20260120 *CodeExecutionTool20260120Param `json:",omitzero,inline"` - OfMemoryTool20250818 *MemoryTool20250818Param `json:",omitzero,inline"` - OfTextEditor20250124 *ToolTextEditor20250124Param `json:",omitzero,inline"` - OfTextEditor20250429 *ToolTextEditor20250429Param `json:",omitzero,inline"` - OfTextEditor20250728 *ToolTextEditor20250728Param `json:",omitzero,inline"` - OfWebSearchTool20250305 *WebSearchTool20250305Param `json:",omitzero,inline"` - OfWebFetchTool20250910 *WebFetchTool20250910Param `json:",omitzero,inline"` - OfWebSearchTool20260209 *WebSearchTool20260209Param `json:",omitzero,inline"` - OfWebFetchTool20260209 *WebFetchTool20260209Param `json:",omitzero,inline"` - OfWebFetchTool20260309 *WebFetchTool20260309Param `json:",omitzero,inline"` - OfToolSearchToolBm25_20251119 *ToolSearchToolBm25_20251119Param `json:",omitzero,inline"` - OfToolSearchToolRegex20251119 *ToolSearchToolRegex20251119Param `json:",omitzero,inline"` - paramUnion +// switch u.AsAny().(type) { +// case *anthropic.BrowserMiddleClickConfigParam: +// case *anthropic.ComputerMiddleClickConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u toolUnionParamConfigsMiddleClick) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u toolUnionParamConfigsMiddleClick) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BrowserMiddleClickConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *ComputerMiddleClickConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + } + return nil } -func (u ToolUnionParam) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfTool, - u.OfBashTool20250124, - u.OfCodeExecutionTool20250522, - u.OfCodeExecutionTool20250825, - u.OfCodeExecutionTool20260120, - u.OfMemoryTool20250818, - u.OfTextEditor20250124, - u.OfTextEditor20250429, - u.OfTextEditor20250728, - u.OfWebSearchTool20250305, - u.OfWebFetchTool20250910, - u.OfWebSearchTool20260209, - u.OfWebFetchTool20260209, - u.OfWebFetchTool20260309, - u.OfToolSearchToolBm25_20251119, - u.OfToolSearchToolRegex20251119) +// Returns a pointer to the underlying variant's property, if present. +func (u toolUnionParamConfigsMiddleClick) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BrowserMiddleClickConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *ComputerMiddleClickConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + } + return nil } -func (u *ToolUnionParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) + +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u toolUnionParamConfigs) GetMouseMove() (res toolUnionParamConfigsMouseMove) { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + res.any = &vt.MouseMove + case *ComputerToolsetConfigsParam: + res.any = &vt.MouseMove + } + return res } -func (u *ToolUnionParam) asAny() any { - if !param.IsOmitted(u.OfTool) { - return u.OfTool - } else if !param.IsOmitted(u.OfBashTool20250124) { - return u.OfBashTool20250124 - } else if !param.IsOmitted(u.OfCodeExecutionTool20250522) { - return u.OfCodeExecutionTool20250522 - } else if !param.IsOmitted(u.OfCodeExecutionTool20250825) { - return u.OfCodeExecutionTool20250825 - } else if !param.IsOmitted(u.OfCodeExecutionTool20260120) { - return u.OfCodeExecutionTool20260120 - } else if !param.IsOmitted(u.OfMemoryTool20250818) { - return u.OfMemoryTool20250818 - } else if !param.IsOmitted(u.OfTextEditor20250124) { - return u.OfTextEditor20250124 - } else if !param.IsOmitted(u.OfTextEditor20250429) { - return u.OfTextEditor20250429 - } else if !param.IsOmitted(u.OfTextEditor20250728) { - return u.OfTextEditor20250728 - } else if !param.IsOmitted(u.OfWebSearchTool20250305) { - return u.OfWebSearchTool20250305 - } else if !param.IsOmitted(u.OfWebFetchTool20250910) { - return u.OfWebFetchTool20250910 - } else if !param.IsOmitted(u.OfWebSearchTool20260209) { - return u.OfWebSearchTool20260209 - } else if !param.IsOmitted(u.OfWebFetchTool20260209) { - return u.OfWebFetchTool20260209 - } else if !param.IsOmitted(u.OfWebFetchTool20260309) { - return u.OfWebFetchTool20260309 - } else if !param.IsOmitted(u.OfToolSearchToolBm25_20251119) { - return u.OfToolSearchToolBm25_20251119 - } else if !param.IsOmitted(u.OfToolSearchToolRegex20251119) { - return u.OfToolSearchToolRegex20251119 +// Can have the runtime types [*BrowserMouseMoveConfigParam], +// [*ComputerMouseMoveConfigParam] +type toolUnionParamConfigsMouseMove struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BrowserMouseMoveConfigParam: +// case *anthropic.ComputerMouseMoveConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u toolUnionParamConfigsMouseMove) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u toolUnionParamConfigsMouseMove) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BrowserMouseMoveConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *ComputerMouseMoveConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u ToolUnionParam) GetInputSchema() *ToolInputSchemaParam { - if vt := u.OfTool; vt != nil { - return &vt.InputSchema +func (u toolUnionParamConfigsMouseMove) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BrowserMouseMoveConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *ComputerMouseMoveConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) } return nil } +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u toolUnionParamConfigs) GetRightClick() (res toolUnionParamConfigsRightClick) { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + res.any = &vt.RightClick + case *ComputerToolsetConfigsParam: + res.any = &vt.RightClick + } + return res +} + +// Can have the runtime types [*BrowserRightClickConfigParam], +// [*ComputerRightClickConfigParam] +type toolUnionParamConfigsRightClick struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BrowserRightClickConfigParam: +// case *anthropic.ComputerRightClickConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u toolUnionParamConfigsRightClick) AsAny() any { return u.any } + // Returns a pointer to the underlying variant's property, if present. -func (u ToolUnionParam) GetDescription() *string { - if vt := u.OfTool; vt != nil && vt.Description.Valid() { - return &vt.Description.Value +func (u toolUnionParamConfigsRightClick) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BrowserRightClickConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *ComputerRightClickConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u ToolUnionParam) GetEagerInputStreaming() *bool { - if vt := u.OfTool; vt != nil && vt.EagerInputStreaming.Valid() { - return &vt.EagerInputStreaming.Value +func (u toolUnionParamConfigsRightClick) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BrowserRightClickConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *ComputerRightClickConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) } return nil } +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u toolUnionParamConfigs) GetScreenshot() (res toolUnionParamConfigsScreenshot) { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + res.any = &vt.Screenshot + case *ComputerToolsetConfigsParam: + res.any = &vt.Screenshot + } + return res +} + +// Can have the runtime types [*BrowserScreenshotConfigParam], +// [*ComputerScreenshotConfigParam] +type toolUnionParamConfigsScreenshot struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BrowserScreenshotConfigParam: +// case *anthropic.ComputerScreenshotConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u toolUnionParamConfigsScreenshot) AsAny() any { return u.any } + // Returns a pointer to the underlying variant's property, if present. -func (u ToolUnionParam) GetMaxCharacters() *int64 { - if vt := u.OfTextEditor20250728; vt != nil && vt.MaxCharacters.Valid() { - return &vt.MaxCharacters.Value +func (u toolUnionParamConfigsScreenshot) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BrowserScreenshotConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *ComputerScreenshotConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u ToolUnionParam) GetUseCache() *bool { - if vt := u.OfWebFetchTool20260309; vt != nil && vt.UseCache.Valid() { - return &vt.UseCache.Value +func (u toolUnionParamConfigsScreenshot) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BrowserScreenshotConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *ComputerScreenshotConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) } return nil } +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u toolUnionParamConfigs) GetScroll() (res toolUnionParamConfigsScroll) { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + res.any = &vt.Scroll + case *ComputerToolsetConfigsParam: + res.any = &vt.Scroll + } + return res +} + +// Can have the runtime types [*BrowserScrollConfigParam], +// [*ComputerScrollConfigParam] +type toolUnionParamConfigsScroll struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BrowserScrollConfigParam: +// case *anthropic.ComputerScrollConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u toolUnionParamConfigsScroll) AsAny() any { return u.any } + // Returns a pointer to the underlying variant's property, if present. -func (u ToolUnionParam) GetName() *string { - if vt := u.OfTool; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfBashTool20250124; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfCodeExecutionTool20250522; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfCodeExecutionTool20250825; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfCodeExecutionTool20260120; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfMemoryTool20250818; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfTextEditor20250124; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfTextEditor20250429; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfTextEditor20250728; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfWebSearchTool20250305; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfWebFetchTool20250910; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfWebSearchTool20260209; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfWebFetchTool20260209; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfWebFetchTool20260309; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfToolSearchToolRegex20251119; vt != nil { - return (*string)(&vt.Name) +func (u toolUnionParamConfigsScroll) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BrowserScrollConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *ComputerScrollConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u ToolUnionParam) GetDeferLoading() *bool { - if vt := u.OfTool; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfBashTool20250124; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfCodeExecutionTool20250522; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfCodeExecutionTool20250825; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfCodeExecutionTool20260120; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfMemoryTool20250818; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfTextEditor20250124; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfTextEditor20250429; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfTextEditor20250728; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfWebSearchTool20250305; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfWebFetchTool20250910; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfWebSearchTool20260209; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfWebFetchTool20260209; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfWebFetchTool20260309; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value - } else if vt := u.OfToolSearchToolRegex20251119; vt != nil && vt.DeferLoading.Valid() { - return &vt.DeferLoading.Value +func (u toolUnionParamConfigsScroll) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BrowserScrollConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *ComputerScrollConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) } return nil } +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u toolUnionParamConfigs) GetTripleClick() (res toolUnionParamConfigsTripleClick) { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + res.any = &vt.TripleClick + case *ComputerToolsetConfigsParam: + res.any = &vt.TripleClick + } + return res +} + +// Can have the runtime types [*BrowserTripleClickConfigParam], +// [*ComputerTripleClickConfigParam] +type toolUnionParamConfigsTripleClick struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BrowserTripleClickConfigParam: +// case *anthropic.ComputerTripleClickConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u toolUnionParamConfigsTripleClick) AsAny() any { return u.any } + // Returns a pointer to the underlying variant's property, if present. -func (u ToolUnionParam) GetStrict() *bool { - if vt := u.OfTool; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfBashTool20250124; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfCodeExecutionTool20250522; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfCodeExecutionTool20250825; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfCodeExecutionTool20260120; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfMemoryTool20250818; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfTextEditor20250124; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfTextEditor20250429; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfTextEditor20250728; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfWebSearchTool20250305; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfWebFetchTool20250910; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfWebSearchTool20260209; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfWebFetchTool20260209; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfWebFetchTool20260309; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value - } else if vt := u.OfToolSearchToolRegex20251119; vt != nil && vt.Strict.Valid() { - return &vt.Strict.Value +func (u toolUnionParamConfigsTripleClick) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BrowserTripleClickConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *ComputerTripleClickConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u ToolUnionParam) GetType() *string { - if vt := u.OfTool; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfBashTool20250124; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfCodeExecutionTool20250522; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfCodeExecutionTool20250825; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfCodeExecutionTool20260120; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfMemoryTool20250818; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfTextEditor20250124; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfTextEditor20250429; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfTextEditor20250728; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfWebSearchTool20250305; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfWebFetchTool20250910; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfWebSearchTool20260209; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfWebFetchTool20260209; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfWebFetchTool20260309; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfToolSearchToolRegex20251119; vt != nil { - return (*string)(&vt.Type) +func (u toolUnionParamConfigsTripleClick) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BrowserTripleClickConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *ComputerTripleClickConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + } + return nil +} + +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u toolUnionParamConfigs) GetType() (res toolUnionParamConfigsType) { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + res.any = &vt.Type + case *ComputerToolsetConfigsParam: + res.any = &vt.Type + } + return res +} + +// Can have the runtime types [*BrowserTypeConfigParam], [*ComputerTypeConfigParam] +type toolUnionParamConfigsType struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BrowserTypeConfigParam: +// case *anthropic.ComputerTypeConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u toolUnionParamConfigsType) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u toolUnionParamConfigsType) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BrowserTypeConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *ComputerTypeConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) } return nil } // Returns a pointer to the underlying variant's property, if present. -func (u ToolUnionParam) GetMaxUses() *int64 { - if vt := u.OfWebSearchTool20250305; vt != nil && vt.MaxUses.Valid() { - return &vt.MaxUses.Value - } else if vt := u.OfWebFetchTool20250910; vt != nil && vt.MaxUses.Valid() { - return &vt.MaxUses.Value - } else if vt := u.OfWebSearchTool20260209; vt != nil && vt.MaxUses.Valid() { - return &vt.MaxUses.Value - } else if vt := u.OfWebFetchTool20260209; vt != nil && vt.MaxUses.Valid() { - return &vt.MaxUses.Value - } else if vt := u.OfWebFetchTool20260309; vt != nil && vt.MaxUses.Valid() { - return &vt.MaxUses.Value +func (u toolUnionParamConfigsType) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BrowserTypeConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *ComputerTypeConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) } return nil } +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u toolUnionParamConfigs) GetWait() (res toolUnionParamConfigsWait) { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + res.any = &vt.Wait + case *ComputerToolsetConfigsParam: + res.any = &vt.Wait + } + return res +} + +// Can have the runtime types [*BrowserWaitConfigParam], [*ComputerWaitConfigParam] +type toolUnionParamConfigsWait struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BrowserWaitConfigParam: +// case *anthropic.ComputerWaitConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u toolUnionParamConfigsWait) AsAny() any { return u.any } + // Returns a pointer to the underlying variant's property, if present. -func (u ToolUnionParam) GetMaxContentTokens() *int64 { - if vt := u.OfWebFetchTool20250910; vt != nil && vt.MaxContentTokens.Valid() { - return &vt.MaxContentTokens.Value - } else if vt := u.OfWebFetchTool20260209; vt != nil && vt.MaxContentTokens.Valid() { - return &vt.MaxContentTokens.Value - } else if vt := u.OfWebFetchTool20260309; vt != nil && vt.MaxContentTokens.Valid() { - return &vt.MaxContentTokens.Value +func (u toolUnionParamConfigsWait) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BrowserWaitConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *ComputerWaitConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) } return nil } -// Returns a pointer to the underlying variant's AllowedCallers property, if -// present. -func (u ToolUnionParam) GetAllowedCallers() []string { - if vt := u.OfTool; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfBashTool20250124; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfCodeExecutionTool20250522; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfCodeExecutionTool20250825; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfCodeExecutionTool20260120; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfMemoryTool20250818; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfTextEditor20250124; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfTextEditor20250429; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfTextEditor20250728; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfWebSearchTool20250305; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfWebFetchTool20250910; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfWebSearchTool20260209; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfWebFetchTool20260209; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfWebFetchTool20260309; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil { - return vt.AllowedCallers - } else if vt := u.OfToolSearchToolRegex20251119; vt != nil { - return vt.AllowedCallers +// Returns a pointer to the underlying variant's property, if present. +func (u toolUnionParamConfigsWait) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BrowserWaitConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *ComputerWaitConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) } return nil } -// Returns a pointer to the underlying variant's CacheControl property, if present. -func (u ToolUnionParam) GetCacheControl() *CacheControlEphemeralParam { - if vt := u.OfTool; vt != nil { - return &vt.CacheControl - } else if vt := u.OfBashTool20250124; vt != nil { - return &vt.CacheControl - } else if vt := u.OfCodeExecutionTool20250522; vt != nil { - return &vt.CacheControl - } else if vt := u.OfCodeExecutionTool20250825; vt != nil { - return &vt.CacheControl - } else if vt := u.OfCodeExecutionTool20260120; vt != nil { - return &vt.CacheControl - } else if vt := u.OfMemoryTool20250818; vt != nil { - return &vt.CacheControl - } else if vt := u.OfTextEditor20250124; vt != nil { - return &vt.CacheControl - } else if vt := u.OfTextEditor20250429; vt != nil { - return &vt.CacheControl - } else if vt := u.OfTextEditor20250728; vt != nil { - return &vt.CacheControl - } else if vt := u.OfWebSearchTool20250305; vt != nil { - return &vt.CacheControl - } else if vt := u.OfWebFetchTool20250910; vt != nil { - return &vt.CacheControl - } else if vt := u.OfWebSearchTool20260209; vt != nil { - return &vt.CacheControl - } else if vt := u.OfWebFetchTool20260209; vt != nil { - return &vt.CacheControl - } else if vt := u.OfWebFetchTool20260309; vt != nil { - return &vt.CacheControl - } else if vt := u.OfToolSearchToolBm25_20251119; vt != nil { - return &vt.CacheControl - } else if vt := u.OfToolSearchToolRegex20251119; vt != nil { - return &vt.CacheControl +// Returns a subunion which exports methods to access subproperties +// +// Or use AsAny() to get the underlying value +func (u toolUnionParamConfigs) GetZoom() (res toolUnionParamConfigsZoom) { + switch vt := u.any.(type) { + case *BrowserToolsetConfigsParam: + res.any = &vt.Zoom + case *ComputerToolsetConfigsParam: + res.any = &vt.Zoom + } + return res +} + +// Can have the runtime types [*BrowserZoomConfigParam], [*ComputerZoomConfigParam] +type toolUnionParamConfigsZoom struct{ any } + +// Use the following switch statement to get the type of the union: +// +// switch u.AsAny().(type) { +// case *anthropic.BrowserZoomConfigParam: +// case *anthropic.ComputerZoomConfigParam: +// default: +// fmt.Errorf("not present") +// } +func (u toolUnionParamConfigsZoom) AsAny() any { return u.any } + +// Returns a pointer to the underlying variant's property, if present. +func (u toolUnionParamConfigsZoom) GetDeferLoading() *bool { + switch vt := u.any.(type) { + case *BrowserZoomConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) + case *ComputerZoomConfigParam: + return paramutil.AddrIfPresent(vt.DeferLoading) } return nil } -// Returns a pointer to the underlying variant's InputExamples property, if -// present. -func (u ToolUnionParam) GetInputExamples() []map[string]any { - if vt := u.OfTool; vt != nil { - return vt.InputExamples - } else if vt := u.OfBashTool20250124; vt != nil { - return vt.InputExamples - } else if vt := u.OfMemoryTool20250818; vt != nil { - return vt.InputExamples - } else if vt := u.OfTextEditor20250124; vt != nil { - return vt.InputExamples - } else if vt := u.OfTextEditor20250429; vt != nil { - return vt.InputExamples - } else if vt := u.OfTextEditor20250728; vt != nil { - return vt.InputExamples +// Returns a pointer to the underlying variant's property, if present. +func (u toolUnionParamConfigsZoom) GetEnabled() *bool { + switch vt := u.any.(type) { + case *BrowserZoomConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) + case *ComputerZoomConfigParam: + return paramutil.AddrIfPresent(vt.Enabled) } return nil } @@ -7833,6 +11879,10 @@ func (u ToolUnionParam) GetAllowedDomains() []string { return vt.AllowedDomains } else if vt := u.OfWebFetchTool20260309; vt != nil { return vt.AllowedDomains + } else if vt := u.OfWebSearchTool20260318; vt != nil { + return vt.AllowedDomains + } else if vt := u.OfWebFetchTool20260318; vt != nil { + return vt.AllowedDomains } return nil } @@ -7850,6 +11900,10 @@ func (u ToolUnionParam) GetBlockedDomains() []string { return vt.BlockedDomains } else if vt := u.OfWebFetchTool20260309; vt != nil { return vt.BlockedDomains + } else if vt := u.OfWebSearchTool20260318; vt != nil { + return vt.BlockedDomains + } else if vt := u.OfWebFetchTool20260318; vt != nil { + return vt.BlockedDomains } return nil } @@ -7860,6 +11914,8 @@ func (u ToolUnionParam) GetUserLocation() *UserLocationParam { return &vt.UserLocation } else if vt := u.OfWebSearchTool20260209; vt != nil { return &vt.UserLocation + } else if vt := u.OfWebSearchTool20260318; vt != nil { + return &vt.UserLocation } return nil } @@ -7872,6 +11928,8 @@ func (u ToolUnionParam) GetCitations() *CitationsConfigParam { return &vt.Citations } else if vt := u.OfWebFetchTool20260309; vt != nil { return &vt.Citations + } else if vt := u.OfWebFetchTool20260318; vt != nil { + return &vt.Citations } return nil } @@ -7881,9 +11939,11 @@ type ToolUseBlock struct { // Tool invocation directly from the model. Caller ToolUseBlockCallerUnion `json:"caller" api:"required"` // necessary custom code modification - Input json.RawMessage `json:"input,required"` - Name string `json:"name" api:"required"` - Type constant.ToolUse `json:"type" default:"tool_use"` + Input json.RawMessage `json:"input,required"` + Name string `json:"name" api:"required"` + Type constant.ToolUse `json:"type" default:"tool_use"` + // For a toolset member tool_use, the toolset family. + ToolsetName string `json:"toolset_name" api:"nullable"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. JSON struct { ID respjson.Field @@ -7891,6 +11951,7 @@ type ToolUseBlock struct { Input respjson.Field Name respjson.Field Type respjson.Field + ToolsetName respjson.Field ExtraFields map[string]respjson.Field raw string } `json:"-"` @@ -7978,6 +12039,8 @@ type ToolUseBlockParam struct { ID string `json:"id" api:"required"` Input any `json:"input,omitzero" api:"required"` Name string `json:"name" api:"required"` + // For a toolset member tool_use, the toolset family this member belongs to. + ToolsetName param.Opt[string] `json:"toolset_name,omitzero"` // Create a cache control breakpoint at this content block. CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` // Tool invocation directly from the model. @@ -8099,6 +12162,13 @@ type Usage struct { InputTokens int64 `json:"input_tokens" api:"required"` // The number of output tokens which were used. OutputTokens int64 `json:"output_tokens" api:"required"` + // Breakdown of output tokens by category. + // + // `output_tokens` remains the inclusive, authoritative total used for billing. + // This object provides a read-only decomposition for observability — for example, + // how many of the billed output tokens were spent on internal reasoning that may + // have been summarized before being returned to you. + OutputTokensDetails OutputTokensDetails `json:"output_tokens_details" api:"required"` // The number of server tool requests. ServerToolUse ServerToolUsage `json:"server_tool_use" api:"required"` // If the request used the priority, standard, or batch tier. @@ -8113,6 +12183,7 @@ type Usage struct { InferenceGeo respjson.Field InputTokens respjson.Field OutputTokens respjson.Field + OutputTokensDetails respjson.Field ServerToolUse respjson.Field ServiceTier respjson.Field ExtraFields map[string]respjson.Field @@ -8220,7 +12291,8 @@ type WebFetchTool20250910Param struct { AllowedDomains []string `json:"allowed_domains,omitzero"` // List of domains to block fetching from BlockedDomains []string `json:"blocked_domains,omitzero"` - // Any of "direct", "code_execution_20250825", "code_execution_20260120". + // Any of "direct", "code_execution_20250825", "code_execution_20260120", + // "code_execution_20260521". AllowedCallers []string `json:"allowed_callers,omitzero"` // Create a cache control breakpoint at this content block. CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` @@ -8263,7 +12335,8 @@ type WebFetchTool20260209Param struct { AllowedDomains []string `json:"allowed_domains,omitzero"` // List of domains to block fetching from BlockedDomains []string `json:"blocked_domains,omitzero"` - // Any of "direct", "code_execution_20250825", "code_execution_20260120". + // Any of "direct", "code_execution_20250825", "code_execution_20260120", + // "code_execution_20260521". AllowedCallers []string `json:"allowed_callers,omitzero"` // Create a cache control breakpoint at this content block. CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` @@ -8312,7 +12385,8 @@ type WebFetchTool20260309Param struct { AllowedDomains []string `json:"allowed_domains,omitzero"` // List of domains to block fetching from BlockedDomains []string `json:"blocked_domains,omitzero"` - // Any of "direct", "code_execution_20250825", "code_execution_20260120". + // Any of "direct", "code_execution_20250825", "code_execution_20260120", + // "code_execution_20260521". AllowedCallers []string `json:"allowed_callers,omitzero"` // Create a cache control breakpoint at this content block. CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` @@ -8339,6 +12413,76 @@ func (r *WebFetchTool20260309Param) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } +// The properties Name, Type are required. +type WebFetchTool20260318Param struct { + // Maximum number of tokens used by including web page text content in the context. + // The limit is approximate and does not apply to binary content such as PDFs. + MaxContentTokens param.Opt[int64] `json:"max_content_tokens,omitzero"` + // Maximum number of times the tool can be used in the API request. + MaxUses param.Opt[int64] `json:"max_uses,omitzero"` + // If true, tool will not be included in initial system prompt. Only loaded when + // returned via tool_reference from tool search. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // When true, guarantees schema validation on tool names and inputs + Strict param.Opt[bool] `json:"strict,omitzero"` + // Whether to use cached content. Set to false to bypass the cache and fetch fresh + // content. Only set to false when the user explicitly requests fresh content or + // when fetching rapidly-changing sources. + UseCache param.Opt[bool] `json:"use_cache,omitzero"` + // List of domains to allow fetching from + AllowedDomains []string `json:"allowed_domains,omitzero"` + // List of domains to block fetching from + BlockedDomains []string `json:"blocked_domains,omitzero"` + // Any of "direct", "code_execution_20250825", "code_execution_20260120", + // "code_execution_20260521". + AllowedCallers []string `json:"allowed_callers,omitzero"` + // Create a cache control breakpoint at this content block. + CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` + // Citations configuration for fetched documents. Citations are disabled by + // default. + Citations CitationsConfigParam `json:"citations,omitzero"` + // How this tool's result blocks appear in the API response when the result was + // consumed by a completed code_execution call in the same turn. 'full' returns the + // complete content (default). 'excluded' drops the nested server_tool_use and + // result block pair entirely. Results from direct calls, or from code_execution + // calls that paused before completing, are always returned in full so they can be + // sent back on the next turn. + // + // Any of "full", "excluded". + ResponseInclusion WebFetchTool20260318ResponseInclusion `json:"response_inclusion,omitzero"` + // Name of the tool. + // + // This is how the tool will be called by the model and in `tool_use` blocks. + // + // This field can be elided, and will marshal its zero value as "web_fetch". + Name constant.WebFetch `json:"name" default:"web_fetch"` + // This field can be elided, and will marshal its zero value as + // "web_fetch_20260318". + Type constant.WebFetch20260318 `json:"type" default:"web_fetch_20260318"` + paramObj +} + +func (r WebFetchTool20260318Param) MarshalJSON() (data []byte, err error) { + type shadow WebFetchTool20260318Param + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *WebFetchTool20260318Param) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// How this tool's result blocks appear in the API response when the result was +// consumed by a completed code_execution call in the same turn. 'full' returns the +// complete content (default). 'excluded' drops the nested server_tool_use and +// result block pair entirely. Results from direct calls, or from code_execution +// calls that paused before completing, are always returned in full so they can be +// sent back on the next turn. +type WebFetchTool20260318ResponseInclusion string + +const ( + WebFetchTool20260318ResponseInclusionFull WebFetchTool20260318ResponseInclusion = "full" + WebFetchTool20260318ResponseInclusionExcluded WebFetchTool20260318ResponseInclusion = "excluded" +) + type WebFetchToolResultBlock struct { // Tool invocation directly from the model. Caller WebFetchToolResultBlockCallerUnion `json:"caller" api:"required"` @@ -8625,8 +12769,8 @@ func init() { type WebFetchToolResultErrorBlock struct { // Any of "invalid_tool_input", "url_too_long", "url_not_allowed", - // "url_not_accessible", "unsupported_content_type", "too_many_requests", - // "max_uses_exceeded", "unavailable". + // "url_not_in_prior_context", "url_not_accessible", "unsupported_content_type", + // "too_many_requests", "max_uses_exceeded", "unavailable". ErrorCode WebFetchToolResultErrorCode `json:"error_code" api:"required"` Type constant.WebFetchToolResultError `json:"type" default:"web_fetch_tool_result_error"` // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. @@ -8647,8 +12791,8 @@ func (r *WebFetchToolResultErrorBlock) UnmarshalJSON(data []byte) error { // The properties ErrorCode, Type are required. type WebFetchToolResultErrorBlockParam struct { // Any of "invalid_tool_input", "url_too_long", "url_not_allowed", - // "url_not_accessible", "unsupported_content_type", "too_many_requests", - // "max_uses_exceeded", "unavailable". + // "url_not_in_prior_context", "url_not_accessible", "unsupported_content_type", + // "too_many_requests", "max_uses_exceeded", "unavailable". ErrorCode WebFetchToolResultErrorCode `json:"error_code,omitzero" api:"required"` // This field can be elided, and will marshal its zero value as // "web_fetch_tool_result_error". @@ -8670,6 +12814,7 @@ const ( WebFetchToolResultErrorCodeInvalidToolInput WebFetchToolResultErrorCode = "invalid_tool_input" WebFetchToolResultErrorCodeURLTooLong WebFetchToolResultErrorCode = "url_too_long" WebFetchToolResultErrorCodeURLNotAllowed WebFetchToolResultErrorCode = "url_not_allowed" + WebFetchToolResultErrorCodeURLNotInPriorContext WebFetchToolResultErrorCode = "url_not_in_prior_context" WebFetchToolResultErrorCodeURLNotAccessible WebFetchToolResultErrorCode = "url_not_accessible" WebFetchToolResultErrorCodeUnsupportedContentType WebFetchToolResultErrorCode = "unsupported_content_type" WebFetchToolResultErrorCodeTooManyRequests WebFetchToolResultErrorCode = "too_many_requests" @@ -8736,7 +12881,8 @@ type WebSearchTool20250305Param struct { // If provided, these domains will never appear in results. Cannot be used // alongside `allowed_domains`. BlockedDomains []string `json:"blocked_domains,omitzero"` - // Any of "direct", "code_execution_20250825", "code_execution_20260120". + // Any of "direct", "code_execution_20250825", "code_execution_20260120", + // "code_execution_20260521". AllowedCallers []string `json:"allowed_callers,omitzero"` // Create a cache control breakpoint at this content block. CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` @@ -8778,7 +12924,8 @@ type WebSearchTool20260209Param struct { // If provided, these domains will never appear in results. Cannot be used // alongside `allowed_domains`. BlockedDomains []string `json:"blocked_domains,omitzero"` - // Any of "direct", "code_execution_20250825", "code_execution_20260120". + // Any of "direct", "code_execution_20250825", "code_execution_20260120", + // "code_execution_20260521". AllowedCallers []string `json:"allowed_callers,omitzero"` // Create a cache control breakpoint at this content block. CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` @@ -8805,6 +12952,71 @@ func (r *WebSearchTool20260209Param) UnmarshalJSON(data []byte) error { return apijson.UnmarshalRoot(data, r) } +// The properties Name, Type are required. +type WebSearchTool20260318Param struct { + // Maximum number of times the tool can be used in the API request. + MaxUses param.Opt[int64] `json:"max_uses,omitzero"` + // If true, tool will not be included in initial system prompt. Only loaded when + // returned via tool_reference from tool search. + DeferLoading param.Opt[bool] `json:"defer_loading,omitzero"` + // When true, guarantees schema validation on tool names and inputs + Strict param.Opt[bool] `json:"strict,omitzero"` + // If provided, only these domains will be included in results. Cannot be used + // alongside `blocked_domains`. + AllowedDomains []string `json:"allowed_domains,omitzero"` + // If provided, these domains will never appear in results. Cannot be used + // alongside `allowed_domains`. + BlockedDomains []string `json:"blocked_domains,omitzero"` + // Any of "direct", "code_execution_20250825", "code_execution_20260120", + // "code_execution_20260521". + AllowedCallers []string `json:"allowed_callers,omitzero"` + // Create a cache control breakpoint at this content block. + CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` + // How this tool's result blocks appear in the API response when the result was + // consumed by a completed code_execution call in the same turn. 'full' returns the + // complete content (default). 'excluded' drops the nested server_tool_use and + // result block pair entirely. Results from direct calls, or from code_execution + // calls that paused before completing, are always returned in full so they can be + // sent back on the next turn. + // + // Any of "full", "excluded". + ResponseInclusion WebSearchTool20260318ResponseInclusion `json:"response_inclusion,omitzero"` + // Parameters for the user's location. Used to provide more relevant search + // results. + UserLocation UserLocationParam `json:"user_location,omitzero"` + // Name of the tool. + // + // This is how the tool will be called by the model and in `tool_use` blocks. + // + // This field can be elided, and will marshal its zero value as "web_search". + Name constant.WebSearch `json:"name" default:"web_search"` + // This field can be elided, and will marshal its zero value as + // "web_search_20260318". + Type constant.WebSearch20260318 `json:"type" default:"web_search_20260318"` + paramObj +} + +func (r WebSearchTool20260318Param) MarshalJSON() (data []byte, err error) { + type shadow WebSearchTool20260318Param + return param.MarshalObject(r, (*shadow)(&r)) +} +func (r *WebSearchTool20260318Param) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// How this tool's result blocks appear in the API response when the result was +// consumed by a completed code_execution call in the same turn. 'full' returns the +// complete content (default). 'excluded' drops the nested server_tool_use and +// result block pair entirely. Results from direct calls, or from code_execution +// calls that paused before completing, are always returned in full so they can be +// sent back on the next turn. +type WebSearchTool20260318ResponseInclusion string + +const ( + WebSearchTool20260318ResponseInclusionFull WebSearchTool20260318ResponseInclusion = "full" + WebSearchTool20260318ResponseInclusionExcluded WebSearchTool20260318ResponseInclusion = "excluded" +) + // The properties ErrorCode, Type are required. type WebSearchToolRequestErrorParam struct { // Any of "invalid_tool_input", "unavailable", "max_uses_exceeded", @@ -9108,8 +13320,13 @@ type MessageNewParams struct { // Note that our models may stop _before_ reaching this maximum. This parameter // only specifies the absolute maximum number of tokens to generate. // + // Set to `0` to populate the + // [prompt cache](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#pre-warming-the-cache) + // without generating a response. + // // Different models have different maximum values for this parameter. See - // [models](https://docs.claude.com/en/docs/models-overview) for details. + // [models](https://platform.claude.com/docs/en/about-claude/models/overview) for + // details. MaxTokens int64 `json:"max_tokens" api:"required"` // Input messages. // @@ -9172,21 +13389,21 @@ type MessageNewParams struct { // { "role": "user", "content": [{ "type": "text", "text": "Hello, Claude" }] } // ``` // - // See [input examples](https://docs.claude.com/en/api/messages-examples). + // See + // [input examples](https://platform.claude.com/docs/en/build-with-claude/working-with-messages). // // Note that if you want to include a - // [system prompt](https://docs.claude.com/en/docs/system-prompts), you can use the - // top-level `system` parameter — there is no `"system"` role for input messages in - // the Messages API. + // [system prompt](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#give-claude-a-role), + // you can use the top-level `system` parameter — there is no `"system"` role for + // input messages in the Messages API. // // There is a limit of 100,000 messages in a single request. Messages []MessageParam `json:"messages,omitzero" api:"required"` - // The model that will complete your prompt.\n\nSee - // [models](https://docs.anthropic.com/en/docs/models-overview) for additional + // The model that will complete your prompt. + // + // See [models](https://docs.anthropic.com/en/docs/models-overview) for additional // details and options. Model Model `json:"model,omitzero" api:"required"` - // Container identifier for reuse across requests. - Container param.Opt[string] `json:"container,omitzero"` // Specifies the geographic region for inference processing. If not specified, the // workspace's `default_inference_geo` is used. InferenceGeo param.Opt[string] `json:"inference_geo,omitzero"` @@ -9204,19 +13421,21 @@ type MessageNewParams struct { // Used to remove "long tail" low probability responses. // [Learn more technical details here](https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277). // - // Recommended for advanced use cases only. You usually only need to use - // `temperature`. + // Recommended for advanced use cases only. TopK param.Opt[int64] `json:"top_k,omitzero"` // Use nucleus sampling. // // In nucleus sampling, we compute the cumulative distribution over all the options // for each subsequent token in decreasing probability order and cut it off once it - // reaches a particular probability specified by `top_p`. You should either alter - // `temperature` or `top_p`, but not both. + // reaches a particular probability specified by `top_p`. // - // Recommended for advanced use cases only. You usually only need to use - // `temperature`. + // Recommended for advanced use cases only. TopP param.Opt[float64] `json:"top_p,omitzero"` + // The user profile ID to attribute this request to. Use when acting on behalf of a + // party other than your organization. Requires the `user-profiles` beta header. + UserProfileID param.Opt[string] `header:"anthropic-user-profile-id,omitzero" json:"-"` + // Container identifier for reuse across requests. + Container MessageCreateParamsContainerUnion `json:"container,omitzero"` // Top-level cache control automatically applies a cache_control marker to the last // cacheable block in the request. CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` @@ -9228,7 +13447,8 @@ type MessageNewParams struct { // for this request. // // Anthropic offers different levels of service for your API requests. See - // [service-tiers](https://docs.claude.com/en/api/service-tiers) for details. + // [service-tiers](https://platform.claude.com/docs/en/api/service-tiers) for + // details. // // Any of "auto", "standard_only". ServiceTier MessageNewParamsServiceTier `json:"service_tier,omitzero"` @@ -9246,7 +13466,7 @@ type MessageNewParams struct { // // A system prompt is a way of providing context and instructions to Claude, such // as specifying a particular goal or role. See our - // [guide to system prompts](https://docs.claude.com/en/docs/system-prompts). + // [guide to system prompts](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#give-claude-a-role). System []TextBlockParam `json:"system,omitzero"` // Configuration for enabling Claude's extended thinking. // @@ -9255,7 +13475,7 @@ type MessageNewParams struct { // tokens and counts towards your `max_tokens` limit. // // See - // [extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking) + // [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking) // for details. Thinking ThinkingConfigParamUnion `json:"thinking,omitzero"` // How the model should use the provided tools. The model can use a specific tool, @@ -9270,9 +13490,9 @@ type MessageNewParams struct { // // There are two types of tools: **client tools** and **server tools**. The // behavior described below applies to client tools. For - // [server tools](https://docs.claude.com/en/docs/agents-and-tools/tool-use/overview#server-tools), + // [server tools](https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools), // see their individual documentation as each has its own behavior (e.g., the - // [web search tool](https://docs.claude.com/en/docs/agents-and-tools/tool-use/web-search-tool)). + // [web search tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool)). // // Each tool definition includes: // @@ -9341,7 +13561,9 @@ type MessageNewParams struct { // functions, or more generally whenever you want the model to produce a particular // JSON structure of output. // - // See our [guide](https://docs.claude.com/en/docs/tool-use) for more details. + // See our + // [guide](https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview) + // for more details. Tools []ToolUnionParam `json:"tools,omitzero"` paramObj } @@ -9358,7 +13580,8 @@ func (r *MessageNewParams) UnmarshalJSON(data []byte) error { // for this request. // // Anthropic offers different levels of service for your API requests. See -// [service-tiers](https://docs.claude.com/en/api/service-tiers) for details. +// [service-tiers](https://platform.claude.com/docs/en/api/service-tiers) for +// details. type MessageNewParamsServiceTier string const ( @@ -9428,19 +13651,24 @@ type MessageCountTokensParams struct { // { "role": "user", "content": [{ "type": "text", "text": "Hello, Claude" }] } // ``` // - // See [input examples](https://docs.claude.com/en/api/messages-examples). + // See + // [input examples](https://platform.claude.com/docs/en/build-with-claude/working-with-messages). // // Note that if you want to include a - // [system prompt](https://docs.claude.com/en/docs/system-prompts), you can use the - // top-level `system` parameter — there is no `"system"` role for input messages in - // the Messages API. + // [system prompt](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#give-claude-a-role), + // you can use the top-level `system` parameter — there is no `"system"` role for + // input messages in the Messages API. // // There is a limit of 100,000 messages in a single request. Messages []MessageParam `json:"messages,omitzero" api:"required"` - // The model that will complete your prompt.\n\nSee - // [models](https://docs.anthropic.com/en/docs/models-overview) for additional + // The model that will complete your prompt. + // + // See [models](https://docs.anthropic.com/en/docs/models-overview) for additional // details and options. Model Model `json:"model,omitzero" api:"required"` + // The user profile ID to attribute this request to. Use when acting on behalf of a + // party other than your organization. Requires the `user-profiles` beta header. + UserProfileID param.Opt[string] `header:"anthropic-user-profile-id,omitzero" json:"-"` // Top-level cache control automatically applies a cache_control marker to the last // cacheable block in the request. CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` @@ -9450,7 +13678,7 @@ type MessageCountTokensParams struct { // // A system prompt is a way of providing context and instructions to Claude, such // as specifying a particular goal or role. See our - // [guide to system prompts](https://docs.claude.com/en/docs/system-prompts). + // [guide to system prompts](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#give-claude-a-role). System MessageCountTokensParamsSystemUnion `json:"system,omitzero"` // Configuration for enabling Claude's extended thinking. // @@ -9459,7 +13687,7 @@ type MessageCountTokensParams struct { // tokens and counts towards your `max_tokens` limit. // // See - // [extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking) + // [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking) // for details. Thinking ThinkingConfigParamUnion `json:"thinking,omitzero"` // How the model should use the provided tools. The model can use a specific tool, @@ -9474,9 +13702,9 @@ type MessageCountTokensParams struct { // // There are two types of tools: **client tools** and **server tools**. The // behavior described below applies to client tools. For - // [server tools](https://docs.claude.com/en/docs/agents-and-tools/tool-use/overview#server-tools), + // [server tools](https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools), // see their individual documentation as each has its own behavior (e.g., the - // [web search tool](https://docs.claude.com/en/docs/agents-and-tools/tool-use/web-search-tool)). + // [web search tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool)). // // Each tool definition includes: // @@ -9545,7 +13773,9 @@ type MessageCountTokensParams struct { // functions, or more generally whenever you want the model to produce a particular // JSON structure of output. // - // See our [guide](https://docs.claude.com/en/docs/tool-use) for more details. + // See our + // [guide](https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview) + // for more details. Tools []MessageCountTokensToolUnionParam `json:"tools,omitzero"` paramObj } diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/messagebatch.go b/vendor/github.com/anthropics/anthropic-sdk-go/messagebatch.go index 5448ddb7b..49efef9cb 100644 --- a/vendor/github.com/anthropics/anthropic-sdk-go/messagebatch.go +++ b/vendor/github.com/anthropics/anthropic-sdk-go/messagebatch.go @@ -50,11 +50,14 @@ func NewMessageBatchService(opts ...option.RequestOption) (r MessageBatchService // can take up to 24 hours to complete. // // Learn more about the Message Batches API in our -// [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) -func (r *MessageBatchService) New(ctx context.Context, body MessageBatchNewParams, opts ...option.RequestOption) (res *MessageBatch, err error) { +// [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing) +func (r *MessageBatchService) New(ctx context.Context, params MessageBatchNewParams, opts ...option.RequestOption) (res *MessageBatch, err error) { + if !param.IsOmitted(params.UserProfileID) { + opts = append(opts, option.WithHeader("anthropic-user-profile-id", fmt.Sprintf("%v", params.UserProfileID.Value))) + } opts = slices.Concat(r.Options, opts) path := "v1/messages/batches" - err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, params, &res, opts...) return res, err } @@ -63,7 +66,7 @@ func (r *MessageBatchService) New(ctx context.Context, body MessageBatchNewParam // `results_url` field in the response. // // Learn more about the Message Batches API in our -// [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) +// [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing) func (r *MessageBatchService) Get(ctx context.Context, messageBatchID string, opts ...option.RequestOption) (res *MessageBatch, err error) { opts = slices.Concat(r.Options, opts) if messageBatchID == "" { @@ -79,7 +82,7 @@ func (r *MessageBatchService) Get(ctx context.Context, messageBatchID string, op // returned first. // // Learn more about the Message Batches API in our -// [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) +// [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing) func (r *MessageBatchService) List(ctx context.Context, query MessageBatchListParams, opts ...option.RequestOption) (res *pagination.Page[MessageBatch], err error) { var raw *http.Response opts = slices.Concat(r.Options, opts) @@ -101,7 +104,7 @@ func (r *MessageBatchService) List(ctx context.Context, query MessageBatchListPa // returned first. // // Learn more about the Message Batches API in our -// [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) +// [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing) func (r *MessageBatchService) ListAutoPaging(ctx context.Context, query MessageBatchListParams, opts ...option.RequestOption) *pagination.PageAutoPager[MessageBatch] { return pagination.NewPageAutoPager(r.List(ctx, query, opts...)) } @@ -112,7 +115,7 @@ func (r *MessageBatchService) ListAutoPaging(ctx context.Context, query MessageB // like to delete an in-progress batch, you must first cancel it. // // Learn more about the Message Batches API in our -// [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) +// [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing) func (r *MessageBatchService) Delete(ctx context.Context, messageBatchID string, opts ...option.RequestOption) (res *DeletedMessageBatch, err error) { opts = slices.Concat(r.Options, opts) if messageBatchID == "" { @@ -135,7 +138,7 @@ func (r *MessageBatchService) Delete(ctx context.Context, messageBatchID string, // non-interruptible. // // Learn more about the Message Batches API in our -// [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) +// [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing) func (r *MessageBatchService) Cancel(ctx context.Context, messageBatchID string, opts ...option.RequestOption) (res *MessageBatch, err error) { opts = slices.Concat(r.Options, opts) if messageBatchID == "" { @@ -154,7 +157,7 @@ func (r *MessageBatchService) Cancel(ctx context.Context, messageBatchID string, // requests. Use the `custom_id` field to match results to requests. // // Learn more about the Message Batches API in our -// [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) +// [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing) func (r *MessageBatchService) ResultsStreaming(ctx context.Context, messageBatchID string, opts ...option.RequestOption) (stream *jsonl.Stream[MessageBatchIndividualResponse]) { var ( raw *http.Response @@ -491,6 +494,11 @@ type MessageBatchNewParams struct { // List of requests for prompt completion. Each is an individual request to create // a Message. Requests []MessageBatchNewParamsRequest `json:"requests,omitzero" api:"required"` + // The user profile ID to attribute the requests in this batch to. Use when acting + // on behalf of a party other than your organization. Requires the `user-profiles` + // beta header. Applies to every request in the batch; an individual request whose + // `user_profile_id` body field conflicts with this header is errored. + UserProfileID param.Opt[string] `header:"anthropic-user-profile-id,omitzero" json:"-"` paramObj } @@ -511,7 +519,8 @@ type MessageBatchNewParamsRequest struct { CustomID string `json:"custom_id" api:"required"` // Messages API creation parameters for the individual request. // - // See the [Messages API reference](https://docs.claude.com/en/api/messages) for + // See the + // [Messages API reference](https://platform.claude.com/docs/en/api/messages) for // full documentation on available parameters. Params MessageBatchNewParamsRequestParams `json:"params,omitzero" api:"required"` paramObj @@ -527,7 +536,8 @@ func (r *MessageBatchNewParamsRequest) UnmarshalJSON(data []byte) error { // Messages API creation parameters for the individual request. // -// See the [Messages API reference](https://docs.claude.com/en/api/messages) for +// See the +// [Messages API reference](https://platform.claude.com/docs/en/api/messages) for // full documentation on available parameters. // // The properties MaxTokens, Messages, Model are required. @@ -537,8 +547,13 @@ type MessageBatchNewParamsRequestParams struct { // Note that our models may stop _before_ reaching this maximum. This parameter // only specifies the absolute maximum number of tokens to generate. // + // Set to `0` to populate the + // [prompt cache](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#pre-warming-the-cache) + // without generating a response. + // // Different models have different maximum values for this parameter. See - // [models](https://docs.claude.com/en/docs/models-overview) for details. + // [models](https://platform.claude.com/docs/en/about-claude/models/overview) for + // details. MaxTokens int64 `json:"max_tokens" api:"required"` // Input messages. // @@ -601,27 +616,28 @@ type MessageBatchNewParamsRequestParams struct { // { "role": "user", "content": [{ "type": "text", "text": "Hello, Claude" }] } // ``` // - // See [input examples](https://docs.claude.com/en/api/messages-examples). + // See + // [input examples](https://platform.claude.com/docs/en/build-with-claude/working-with-messages). // // Note that if you want to include a - // [system prompt](https://docs.claude.com/en/docs/system-prompts), you can use the - // top-level `system` parameter — there is no `"system"` role for input messages in - // the Messages API. + // [system prompt](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#give-claude-a-role), + // you can use the top-level `system` parameter — there is no `"system"` role for + // input messages in the Messages API. // // There is a limit of 100,000 messages in a single request. Messages []MessageParam `json:"messages,omitzero" api:"required"` - // The model that will complete your prompt.\n\nSee - // [models](https://docs.anthropic.com/en/docs/models-overview) for additional + // The model that will complete your prompt. + // + // See [models](https://docs.anthropic.com/en/docs/models-overview) for additional // details and options. Model Model `json:"model,omitzero" api:"required"` - // Container identifier for reuse across requests. - Container param.Opt[string] `json:"container,omitzero"` // Specifies the geographic region for inference processing. If not specified, the // workspace's `default_inference_geo` is used. InferenceGeo param.Opt[string] `json:"inference_geo,omitzero"` // Whether to incrementally stream the response using server-sent events. // - // See [streaming](https://docs.claude.com/en/api/messages-streaming) for details. + // See [streaming](https://platform.claude.com/docs/en/build-with-claude/streaming) + // for details. Stream param.Opt[bool] `json:"stream,omitzero"` // Amount of randomness injected into the response. // @@ -641,8 +657,7 @@ type MessageBatchNewParamsRequestParams struct { // Used to remove "long tail" low probability responses. // [Learn more technical details here](https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277). // - // Recommended for advanced use cases only. You usually only need to use - // `temperature`. + // Recommended for advanced use cases only. // // Deprecated: Deprecated. Models released after Claude Opus 4.6 do not accept // top_k; any value will be rejected with a 400 error. @@ -651,16 +666,16 @@ type MessageBatchNewParamsRequestParams struct { // // In nucleus sampling, we compute the cumulative distribution over all the options // for each subsequent token in decreasing probability order and cut it off once it - // reaches a particular probability specified by `top_p`. You should either alter - // `temperature` or `top_p`, but not both. + // reaches a particular probability specified by `top_p`. // - // Recommended for advanced use cases only. You usually only need to use - // `temperature`. + // Recommended for advanced use cases only. // // Deprecated: Deprecated. Models released after Claude Opus 4.6 do not support // setting top_p. A value >= 0.99 will be accepted for backwards compatibility, all // other values will be rejected with a 400 error. TopP param.Opt[float64] `json:"top_p,omitzero"` + // Container identifier for reuse across requests. + Container MessageCreateParamsContainerUnion `json:"container,omitzero"` // Top-level cache control automatically applies a cache_control marker to the last // cacheable block in the request. CacheControl CacheControlEphemeralParam `json:"cache_control,omitzero"` @@ -672,7 +687,8 @@ type MessageBatchNewParamsRequestParams struct { // for this request. // // Anthropic offers different levels of service for your API requests. See - // [service-tiers](https://docs.claude.com/en/api/service-tiers) for details. + // [service-tiers](https://platform.claude.com/docs/en/api/service-tiers) for + // details. // // Any of "auto", "standard_only". ServiceTier string `json:"service_tier,omitzero"` @@ -690,7 +706,7 @@ type MessageBatchNewParamsRequestParams struct { // // A system prompt is a way of providing context and instructions to Claude, such // as specifying a particular goal or role. See our - // [guide to system prompts](https://docs.claude.com/en/docs/system-prompts). + // [guide to system prompts](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#give-claude-a-role). System []TextBlockParam `json:"system,omitzero"` // Configuration for enabling Claude's extended thinking. // @@ -699,7 +715,7 @@ type MessageBatchNewParamsRequestParams struct { // tokens and counts towards your `max_tokens` limit. // // See - // [extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking) + // [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking) // for details. Thinking ThinkingConfigParamUnion `json:"thinking,omitzero"` // How the model should use the provided tools. The model can use a specific tool, @@ -714,9 +730,9 @@ type MessageBatchNewParamsRequestParams struct { // // There are two types of tools: **client tools** and **server tools**. The // behavior described below applies to client tools. For - // [server tools](https://docs.claude.com/en/docs/agents-and-tools/tool-use/overview#server-tools), + // [server tools](https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools), // see their individual documentation as each has its own behavior (e.g., the - // [web search tool](https://docs.claude.com/en/docs/agents-and-tools/tool-use/web-search-tool)). + // [web search tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool)). // // Each tool definition includes: // @@ -785,7 +801,9 @@ type MessageBatchNewParamsRequestParams struct { // functions, or more generally whenever you want the model to produce a particular // JSON structure of output. // - // See our [guide](https://docs.claude.com/en/docs/tool-use) for more details. + // See our + // [guide](https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview) + // for more details. Tools []ToolUnionParam `json:"tools,omitzero"` paramObj } @@ -821,7 +839,7 @@ type MessageBatchListParams struct { // URLQuery serializes [MessageBatchListParams]'s query parameters as `url.Values`. func (r MessageBatchListParams) URLQuery() (v url.Values, err error) { return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ - ArrayFormat: apiquery.ArrayQueryFormatComma, + ArrayFormat: apiquery.ArrayQueryFormatBrackets, NestedFormat: apiquery.NestedQueryFormatBrackets, }) } diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/messageutil.go b/vendor/github.com/anthropics/anthropic-sdk-go/messageutil.go index e735e4794..ccb77234c 100644 --- a/vendor/github.com/anthropics/anthropic-sdk-go/messageutil.go +++ b/vendor/github.com/anthropics/anthropic-sdk-go/messageutil.go @@ -3,14 +3,19 @@ package anthropic import ( "encoding/json" "fmt" + "strings" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" + + "github.com/anthropics/anthropic-sdk-go/internal/apijson" "github.com/anthropics/anthropic-sdk-go/internal/paramutil" "github.com/anthropics/anthropic-sdk-go/packages/param" ) // Accumulate builds up the Message incrementally from a MessageStreamEvent. The Message then can be used as -// any other Message, except with the caveat that the Message.JSON field which normally can be used to inspect -// the JSON sent over the network may not be populated fully. +// any other Message, including the Message.JSON field, which holds the wire JSON with the streamed deltas +// applied and is complete once message_stop arrives. // // message := anthropic.Message{} // for stream.Next() { @@ -22,69 +27,166 @@ func (acc *Message) Accumulate(event MessageStreamEventUnion) error { return fmt.Errorf("accumulate: cannot accumulate into nil Message") } - switch event := event.AsAny().(type) { - case MessageStartEvent: + switch event.Type { + case "message_start": *acc = event.Message - case MessageDeltaEvent: + case "message_delta": + // stop_reason, stop_sequence and stop_details are always sent and null is + // their final value when the turn carries no such detail. acc.StopReason = event.Delta.StopReason acc.StopSequence = event.Delta.StopSequence + acc.StopDetails = event.Delta.StopDetails + if event.Delta.JSON.Container.Valid() { + acc.Container = event.Delta.Container + } + // Every usage count here is a cumulative whole-message total, so it + // overwrites rather than adds; the ones that do not apply are omitted, and + // message_start keeps the last word on those. acc.Usage.OutputTokens = event.Usage.OutputTokens - case ContentBlockStartEvent: + if event.Usage.JSON.InputTokens.Valid() { + acc.Usage.InputTokens = event.Usage.InputTokens + } + if event.Usage.JSON.CacheCreationInputTokens.Valid() { + acc.Usage.CacheCreationInputTokens = event.Usage.CacheCreationInputTokens + } + if event.Usage.JSON.CacheReadInputTokens.Valid() { + acc.Usage.CacheReadInputTokens = event.Usage.CacheReadInputTokens + } + if event.Usage.JSON.ServerToolUse.Valid() { + acc.Usage.ServerToolUse = event.Usage.ServerToolUse + } + if event.Usage.JSON.OutputTokensDetails.Valid() { + acc.Usage.OutputTokensDetails = event.Usage.OutputTokensDetails + } + acc.JSON.raw = mergeRaw(acc.JSON.raw, "", event.Delta.JSON.raw) + acc.JSON.raw = mergeRaw(acc.JSON.raw, "usage", event.Usage.RawJSON()) + case "content_block_start": + // Content blocks start in index order with no gaps: a start event always + // addresses the slot right after the previous block, even when deltas and + // stops for still-open blocks interleave after it. + if event.Index != int64(len(acc.Content)) { + return fmt.Errorf("received event of type %s for content block at index %d, expected index %d", event.Type, event.Index, len(acc.Content)) + } acc.Content = append(acc.Content, ContentBlockUnion{}) - err := acc.Content[len(acc.Content)-1].UnmarshalJSON([]byte(event.ContentBlock.RawJSON())) + err := acc.Content[event.Index].UnmarshalJSON([]byte(event.ContentBlock.RawJSON())) if err != nil { return err } - case ContentBlockDeltaEvent: - if len(acc.Content) == 0 { - return fmt.Errorf("received event of type %s but there was no content block", event.Type) + case "content_block_delta": + if err := checkContentBlockIndex(event.Type, event.Index, len(acc.Content)); err != nil { + return err } - cb := &acc.Content[len(acc.Content)-1] - switch delta := event.Delta.AsAny().(type) { - case TextDelta: - cb.Text += delta.Text - case InputJSONDelta: - if len(delta.PartialJSON) != 0 { + cb := &acc.Content[event.Index] + switch event.Delta.Type { + case "text_delta": + cb.Text += event.Delta.Text + case "input_json_delta": + if len(event.Delta.PartialJSON) != 0 { if string(cb.Input) == "{}" { - cb.Input = []byte(delta.PartialJSON) + cb.Input = []byte(event.Delta.PartialJSON) } else { - cb.Input = append(cb.Input, []byte(delta.PartialJSON)...) + cb.Input = append(cb.Input, event.Delta.PartialJSON...) } } - case ThinkingDelta: - cb.Thinking += delta.Thinking - case SignatureDelta: - cb.Signature += delta.Signature - case CitationsDelta: + case "thinking_delta": + cb.Thinking += event.Delta.Thinking + case "signature_delta": + cb.Signature += event.Delta.Signature + case "citations_delta": citation := TextCitationUnion{} - err := citation.UnmarshalJSON([]byte(delta.Citation.RawJSON())) + err := citation.UnmarshalJSON([]byte(event.Delta.Citation.RawJSON())) if err != nil { return fmt.Errorf("could not unmarshal citation delta into citation type: %w", err) } cb.Citations = append(cb.Citations, citation) } - case MessageStopEvent: - // Re-marshal the accumulated message to update JSON.raw so that AsAny() - // returns the accumulated data rather than the original stream data - accJSON, err := json.Marshal(acc) - if err != nil { - return fmt.Errorf("error converting accumulated message to JSON: %w", err) + case "message_stop": + // A block whose stop event never arrived has not been refreshed yet. + for i := range acc.Content { + refreshContentBlockRaw(&acc.Content[i]) } - acc.JSON.raw = string(accJSON) - case ContentBlockStopEvent: - // Re-marshal the content block to update JSON.raw so that AsAny() - // returns the accumulated data rather than the original stream data - if len(acc.Content) == 0 { - return fmt.Errorf("received event of type %s but there was no content block", event.Type) + acc.JSON.raw, _ = sjson.SetRaw(acc.JSON.raw, "content", rawArray(acc.Content)) + case "content_block_stop": + if err := checkContentBlockIndex(event.Type, event.Index, len(acc.Content)); err != nil { + return err } - contentBlock := &acc.Content[len(acc.Content)-1] - cbJSON, err := json.Marshal(contentBlock) - if err != nil { - return fmt.Errorf("error converting content block to JSON: %w", err) + refreshContentBlockRaw(&acc.Content[event.Index]) + } + + return nil +} + +// refreshContentBlockRaw overlays the delta-mutated fields onto the block's +// wire JSON, leaving a block that received no deltas byte for byte. +func refreshContentBlockRaw(cb *ContentBlockUnion) { + raw := cb.JSON.raw + if cb.Text != "" { + raw, _ = sjson.SetRaw(raw, "text", jsonString(cb.Text)) + } + if cb.Thinking != "" { + raw, _ = sjson.SetRaw(raw, "thinking", jsonString(cb.Thinking)) + } + if cb.Signature != "" { + raw, _ = sjson.SetRaw(raw, "signature", jsonString(cb.Signature)) + } + if json.Valid(cb.Input) { + raw, _ = sjson.SetRaw(raw, "input", string(cb.Input)) + } else if len(cb.Input) > 0 { + // A cut-off tool call left non-JSON input; empty it so the block marshals. + cb.Input = json.RawMessage(`{}`) + } + if len(cb.Citations) > 0 { + raw, _ = sjson.SetRaw(raw, "citations", rawArray(cb.Citations)) + } + cb.JSON.raw = raw +} + +// jsonString encodes s as the server does, leaving <, > and & literal, which +// sjson.Set does inconsistently. +func jsonString(s string) string { + var b strings.Builder + enc := json.NewEncoder(&b) + enc.SetEscapeHTML(false) + enc.Encode(s) + return strings.TrimSuffix(b.String(), "\n") +} + +// mergeRaw merges the wire object src into dst at path, skipping the nulls +// message_delta sends for values it is not updating. +func mergeRaw(dst, path, src string) string { + if path != "" { + path += "." + } + gjson.Parse(src).ForEach(func(key, value gjson.Result) bool { + if value.Type == gjson.Null { + return true + } + dst, _ = sjson.SetRaw(dst, path+apijson.EscapeSJSONKey(key.String()), value.Raw) + return true + }) + return dst +} + +// rawArray renders the wire JSON of each item as an array, skipping any item +// with none, such as a block whose start event carried no content_block. +func rawArray[T interface{ RawJSON() string }](items []T) string { + raws := make([]string, 0, len(items)) + for _, item := range items { + if raw := item.RawJSON(); raw != "" { + raws = append(raws, raw) } - contentBlock.JSON.raw = string(cbJSON) } + return "[" + strings.Join(raws, ",") + "]" +} +// checkContentBlockIndex reports an error if a stream event's index does not +// address one of the numBlocks content blocks accumulated so far. Delta and +// stop events may interleave across open content blocks, so they address +// blocks by index rather than applying to the most recently started block. +func checkContentBlockIndex(eventType string, index int64, numBlocks int) error { + if index < 0 || index >= int64(numBlocks) { + return fmt.Errorf("received event of type %s for content block at index %d but there are only %d content blocks", eventType, index, numBlocks) + } return nil } @@ -147,9 +249,45 @@ func (r ToolUseBlock) ToParam() ToolUseBlockParam { toolUse.ID = r.ID toolUse.Input = r.Input toolUse.Name = r.Name + toolUse.ToolsetName = paramutil.ToOpt(r.ToolsetName, r.JSON.ToolsetName) + if r.JSON.Caller.Valid() { + toolUse.Caller = r.Caller.toParam() + } return toolUse } +// toParam converts a caller. The other three caller unions share this layout +// and convert through it. +func (r ToolUseBlockCallerUnion) toParam() ToolUseBlockParamCallerUnion { + var p ToolUseBlockParamCallerUnion + switch v := r.AsAny().(type) { + case DirectCaller: + c := v.ToParam() + p.OfDirect = &c + case ServerToolCaller: + c := v.ToParam() + p.OfCodeExecution20250825 = &c + case ServerToolCaller20260120: + c := v.ToParam() + p.OfCodeExecution20260120 = &c + default: + p = param.Override[ToolUseBlockParamCallerUnion](json.RawMessage(r.RawJSON())) + } + return p +} + +func (r ServerToolUseBlockCallerUnion) toParam() ServerToolUseBlockParamCallerUnion { + return ServerToolUseBlockParamCallerUnion(ToolUseBlockCallerUnion(r).toParam()) +} + +func (r WebSearchToolResultBlockCallerUnion) toParam() WebSearchToolResultBlockParamCallerUnion { + return WebSearchToolResultBlockParamCallerUnion(ToolUseBlockCallerUnion(r).toParam()) +} + +func (r WebFetchToolResultBlockCallerUnion) toParam() WebFetchToolResultBlockParamCallerUnion { + return WebFetchToolResultBlockParamCallerUnion(ToolUseBlockCallerUnion(r).toParam()) +} + func (citationVariant CitationCharLocation) toParamUnion() TextCitationParamUnion { var citationParam CitationCharLocationParam citationParam.Type = citationVariant.Type @@ -165,6 +303,7 @@ func (citationVariant CitationPageLocation) toParamUnion() TextCitationParamUnio var citationParam CitationPageLocationParam citationParam.Type = citationVariant.Type citationParam.DocumentTitle = paramutil.ToOpt(citationVariant.DocumentTitle, citationVariant.JSON.DocumentTitle) + citationParam.CitedText = citationVariant.CitedText citationParam.DocumentIndex = citationVariant.DocumentIndex citationParam.EndPageNumber = citationVariant.EndPageNumber citationParam.StartPageNumber = citationVariant.StartPageNumber @@ -187,6 +326,10 @@ func (citationVariant CitationsSearchResultLocation) toParamUnion() TextCitation citationParam.Type = citationVariant.Type citationParam.CitedText = citationVariant.CitedText citationParam.Title = paramutil.ToOpt(citationVariant.Title, citationVariant.JSON.Title) + citationParam.EndBlockIndex = citationVariant.EndBlockIndex + citationParam.SearchResultIndex = citationVariant.SearchResultIndex + citationParam.Source = citationVariant.Source + citationParam.StartBlockIndex = citationVariant.StartBlockIndex return TextCitationParamUnion{OfSearchResultLocation: &citationParam} } @@ -195,6 +338,8 @@ func (citationVariant CitationsWebSearchResultLocation) toParamUnion() TextCitat citationParam.Type = citationVariant.Type citationParam.CitedText = citationVariant.CitedText citationParam.Title = paramutil.ToOpt(citationVariant.Title, citationVariant.JSON.Title) + citationParam.EncryptedIndex = citationVariant.EncryptedIndex + citationParam.URL = citationVariant.URL return TextCitationParamUnion{OfWebSearchResultLocation: &citationParam} } @@ -230,6 +375,9 @@ func (r ServerToolUseBlock) ToParam() ServerToolUseBlockParam { p.ID = r.ID p.Input = r.Input p.Name = ServerToolUseBlockParamName(r.Name) + if r.JSON.Caller.Valid() { + p.Caller = r.Caller.toParam() + } return p } @@ -238,6 +386,9 @@ func (r WebSearchToolResultBlock) ToParam() WebSearchToolResultBlockParam { p.Type = r.Type p.ToolUseID = r.ToolUseID p.Content = r.Content.ToParam() + if r.JSON.Caller.Valid() { + p.Caller = r.Caller.toParam() + } return p } @@ -254,7 +405,9 @@ func (r WebSearchResultBlock) ToParam() WebSearchResultBlockParam { func (r WebSearchToolResultBlockContentUnion) ToParam() WebSearchToolResultBlockParamContentUnion { var p WebSearchToolResultBlockParamContentUnion - if len(r.OfWebSearchResultBlockArray) > 0 { + if r.JSON.OfWebSearchResultBlockArray.Valid() { + // content is required, so send [] rather than omitting it. + p.OfWebSearchToolResultBlockItem = make([]WebSearchResultBlockParam, 0, len(r.OfWebSearchResultBlockArray)) for _, block := range r.OfWebSearchResultBlockArray { p.OfWebSearchToolResultBlockItem = append(p.OfWebSearchToolResultBlockItem, block.ToParam()) } @@ -301,6 +454,16 @@ func (r WebFetchToolResultBlock) ToParam() WebFetchToolResultBlockParam { var p WebFetchToolResultBlockParam p.Type = r.Type p.ToolUseID = r.ToolUseID + if r.Content.JSON.ErrorCode.Valid() { + p.Content.OfRequestWebFetchToolResultError = &WebFetchToolResultErrorBlockParam{ + ErrorCode: r.Content.ErrorCode, + } + } else { + p.Content = param.Override[WebFetchToolResultBlockParamContentUnion](json.RawMessage(r.Content.RawJSON())) + } + if r.JSON.Caller.Valid() { + p.Caller = r.Caller.toParam() + } return p } @@ -322,6 +485,8 @@ func (r BashCodeExecutionToolResultBlock) ToParam() BashCodeExecutionToolResultB } } else { requestBashContentResult := &BashCodeExecutionResultBlockParam{ + // content is required, so send [] rather than omitting it. + Content: make([]BashCodeExecutionOutputBlockParam, 0, len(r.Content.Content)), ReturnCode: r.Content.ReturnCode, Stderr: r.Content.Stderr, Stdout: r.Content.Stdout, @@ -346,19 +511,30 @@ func (r CodeExecutionToolResultBlock) ToParam() CodeExecutionToolResultBlockPara var p CodeExecutionToolResultBlockParam p.Type = r.Type p.ToolUseID = r.ToolUseID - if r.Content.JSON.ErrorCode.Valid() { + // content is required, so send [] rather than omitting it. + files := make([]CodeExecutionOutputBlockParam, 0, len(r.Content.Content)) + for _, block := range r.Content.Content { + files = append(files, block.ToParam()) + } + switch { + case r.Content.JSON.ErrorCode.Valid(): p.Content.OfRequestCodeExecutionToolResultError = &CodeExecutionToolResultErrorParam{ ErrorCode: r.Content.ErrorCode, } - } else { + case r.Content.JSON.EncryptedStdout.Valid(): + p.Content.OfRequestEncryptedCodeExecutionResultBlock = &EncryptedCodeExecutionResultBlockParam{ + Content: files, + EncryptedStdout: r.Content.EncryptedStdout, + ReturnCode: r.Content.ReturnCode, + Stderr: r.Content.Stderr, + } + default: p.Content.OfRequestCodeExecutionResultBlock = &CodeExecutionResultBlockParam{ + Content: files, ReturnCode: r.Content.ReturnCode, Stderr: r.Content.Stderr, Stdout: r.Content.Stdout, } - for _, block := range r.Content.Content { - p.Content.OfRequestCodeExecutionResultBlock.Content = append(p.Content.OfRequestCodeExecutionResultBlock.Content, block.ToParam()) - } } return p } @@ -380,7 +556,7 @@ func (r TextEditorCodeExecutionToolResultBlock) ToParam() TextEditorCodeExecutio ErrorMessage: paramutil.ToOpt(r.Content.ErrorMessage, r.Content.JSON.ErrorMessage), } } else { - p.Content = param.Override[TextEditorCodeExecutionToolResultBlockParamContentUnion](r.Content.RawJSON()) + p.Content = param.Override[TextEditorCodeExecutionToolResultBlockParamContentUnion](json.RawMessage(r.Content.RawJSON())) } return p } @@ -391,10 +567,14 @@ func (r ToolSearchToolResultBlock) ToParam() ToolSearchToolResultBlockParam { p.ToolUseID = r.ToolUseID if r.Content.JSON.ErrorCode.Valid() { p.Content.OfRequestToolSearchToolResultError = &ToolSearchToolResultErrorParam{ - ErrorCode: ToolSearchToolResultErrorCode(r.Content.ErrorCode), + ErrorCode: ToolSearchToolResultErrorCode(r.Content.ErrorCode), + ErrorMessage: paramutil.ToOpt(r.Content.ErrorMessage, r.Content.JSON.ErrorMessage), } } else { - p.Content.OfRequestToolSearchToolSearchResultBlock = &ToolSearchToolSearchResultBlockParam{} + p.Content.OfRequestToolSearchToolSearchResultBlock = &ToolSearchToolSearchResultBlockParam{ + // tool_references is required, so send [] rather than omitting it. + ToolReferences: make([]ToolReferenceBlockParam, 0, len(r.Content.ToolReferences)), + } for _, block := range r.Content.ToolReferences { p.Content.OfRequestToolSearchToolSearchResultBlock.ToolReferences = append( p.Content.OfRequestToolSearchToolSearchResultBlock.ToolReferences, diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/model.go b/vendor/github.com/anthropics/anthropic-sdk-go/model.go index fce1a1fc6..afef9c46b 100644 --- a/vendor/github.com/anthropics/anthropic-sdk-go/model.go +++ b/vendor/github.com/anthropics/anthropic-sdk-go/model.go @@ -315,7 +315,7 @@ type ModelListParams struct { // URLQuery serializes [ModelListParams]'s query parameters as `url.Values`. func (r ModelListParams) URLQuery() (v url.Values, err error) { return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ - ArrayFormat: apiquery.ArrayQueryFormatComma, + ArrayFormat: apiquery.ArrayQueryFormatBrackets, NestedFormat: apiquery.NestedQueryFormatBrackets, }) } diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/option/middleware.go b/vendor/github.com/anthropics/anthropic-sdk-go/option/middleware.go index 8ec9dd60b..4be098757 100644 --- a/vendor/github.com/anthropics/anthropic-sdk-go/option/middleware.go +++ b/vendor/github.com/anthropics/anthropic-sdk-go/option/middleware.go @@ -8,6 +8,10 @@ import ( "net/http/httputil" ) +// sensitiveLogHeaders are redacted before request and response content is +// written to the debug logger. +var sensitiveLogHeaders = []string{"authorization", "api-key", "x-api-key", "cookie", "set-cookie"} + // WithDebugLog logs the HTTP request and response content. // If the logger parameter is nil, it uses the default logger. // @@ -20,7 +24,7 @@ func WithDebugLog(logger *log.Logger) RequestOption { logger = log.Default() } - if reqBytes, err := httputil.DumpRequest(req, true); err == nil { + if reqBytes, err := dumpRedactedRequest(req); err == nil { logger.Printf("Request Content:\n%s\n", reqBytes) } @@ -29,10 +33,48 @@ func WithDebugLog(logger *log.Logger) RequestOption { return resp, err } - if respBytes, err := httputil.DumpResponse(resp, true); err == nil { + if respBytes, err := dumpRedactedResponse(resp); err == nil { logger.Printf("Response Content:\n%s\n", respBytes) } return resp, err }) } + +// dumpRedactedRequest dumps req with sensitive headers replaced. The +// original headers are restored via defer so a panic in DumpRequest cannot +// leak the placeholder map into the live request sent downstream. +func dumpRedactedRequest(req *http.Request) ([]byte, error) { + origHeaders := req.Header + req.Header = redactDebugHeaders(origHeaders) + defer func() { req.Header = origHeaders }() + return httputil.DumpRequest(req, true) +} + +func dumpRedactedResponse(resp *http.Response) ([]byte, error) { + origHeaders := resp.Header + resp.Header = redactDebugHeaders(origHeaders) + defer func() { resp.Header = origHeaders }() + return httputil.DumpResponse(resp, true) +} + +func redactDebugHeaders(headers http.Header) http.Header { + var redacted http.Header + for _, name := range sensitiveLogHeaders { + values := headers.Values(name) + if len(values) == 0 { + continue + } + if redacted == nil { + redacted = headers.Clone() + } + redacted.Del(name) + for range values { + redacted.Add(name, "***") + } + } + if redacted == nil { + return headers + } + return redacted +} diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/option/requestoption.go b/vendor/github.com/anthropics/anthropic-sdk-go/option/requestoption.go index 8be1d9746..4c1008a7c 100644 --- a/vendor/github.com/anthropics/anthropic-sdk-go/option/requestoption.go +++ b/vendor/github.com/anthropics/anthropic-sdk-go/option/requestoption.go @@ -4,17 +4,135 @@ package option import ( "bytes" + "context" "fmt" "io" "net/http" "net/url" + "os" "strings" + "sync" "time" + "github.com/anthropics/anthropic-sdk-go/config" + "github.com/anthropics/anthropic-sdk-go/internal/auth" "github.com/anthropics/anthropic-sdk-go/internal/requestconfig" "github.com/tidwall/sjson" ) +// IdentityTokenFunc returns a fresh JWT identity token (e.g. from SPIFFE/SPIRE, +// the GCP metadata server, or any other OIDC-compatible provider). It is +// invoked once per federation token exchange; implementations should be safe +// for concurrent use. +type IdentityTokenFunc func(ctx context.Context) (string, error) + +// FederationOptions configures a federation-based token exchange. +type FederationOptions struct { + // FederationRuleID identifies the OidcFederationRule governing this + // exchange. Required; must be a tagged ID with the "fdrl_" prefix. + FederationRuleID string + // OrganizationID is the UUID of the Anthropic organization the + // federation rule belongs to. Required. + OrganizationID string + // ServiceAccountID is an optional expected-target check for federation + // rules with target_type=SERVICE_ACCOUNT. Must be a tagged ID with the + // "svac_" prefix. Omit for target_type=USER rules, where the principal + // is derived from the JWT claims. + ServiceAccountID string + // WorkspaceID is an optional `wrkspc_*` tagged ID, or the literal + // "default" to scope the token to the organization's default workspace. + // When omitted the server picks the rule's sole enabled workspace, else + // the org default if the rule covers it. Required when the rule enables + // more than one non-default workspace, or to target a specific workspace + // other than the one the server would pick. The minted token is + // workspace-scoped: per-request workspace selection (the + // anthropic-workspace-id header) is not supported for federation + // tokens — switching workspaces requires a new token exchange with a + // different WorkspaceID. + WorkspaceID string +} + +// identityTokenFuncAdapter adapts an [IdentityTokenFunc] to the internal +// [auth.IdentityTokenProvider] interface without leaking the internal type. +type identityTokenFuncAdapter struct { + fn IdentityTokenFunc +} + +func (a identityTokenFuncAdapter) GetIdentityToken(ctx context.Context) (string, error) { + if a.fn == nil { + return "", fmt.Errorf("option: IdentityTokenFunc is nil") + } + return a.fn(ctx) +} + +// errOption returns a [RequestOption] whose Apply unconditionally returns +// err. Used to defer validation errors from option constructors so they +// surface on the first request rather than at option-construction time. +func errOption(err error) RequestOption { + return requestconfig.RequestOptionFunc(func(*requestconfig.RequestConfig) error { + return err + }) +} + +// IdentityTokenFile returns an [IdentityTokenFunc] that reads a JWT from path +// on each invocation. Use it for Kubernetes projected service account tokens +// and similar rotating on-disk credentials — the file is re-read on every +// federation exchange so rotations are picked up automatically. Surrounding +// whitespace is trimmed; an empty file is treated as an error. +// +// Passing this as the provider to [WithFederationTokenProvider] takes +// precedence over the ANTHROPIC_IDENTITY_TOKEN_FILE environment variable: +// explicit options always beat env-var auto-discovery. The env var only +// applies when the client is constructed without a [WithFederationTokenProvider] +// option (or equivalent). +// +// The returned function is safe for concurrent use. +// +// Typical usage: +// +// client := anthropic.NewClient( +// option.WithFederationTokenProvider( +// option.IdentityTokenFile("/var/run/secrets/anthropic.com/token"), +// option.FederationOptions{ +// FederationRuleID: "fdrl_...", +// OrganizationID: os.Getenv("ANTHROPIC_ORGANIZATION_ID"), +// }, +// ), +// ) +func IdentityTokenFile(path string) IdentityTokenFunc { + return (&auth.IdentityTokenFile{Path: path}).GetIdentityToken +} + +// WithFederationTokenProvider returns a [RequestOption] that authenticates +// requests using workload identity federation, exchanging a caller-supplied +// identity token for a short-lived Anthropic access token. Use this to +// integrate custom OIDC token sources (SPIFFE/SPIRE, cloud provider SDKs, +// etc.) without staging the token through a file. +// +// provider is called on each token exchange to fetch a fresh JWT. +// opts.FederationRuleID and opts.OrganizationID are required. +// +// The [auth.TokenCache] built by [auth.WithAuthMiddleware] is shared across +// requests, so a token is only re-exchanged when it enters the refresh window. +func WithFederationTokenProvider(provider IdentityTokenFunc, opts FederationOptions) RequestOption { + switch { + case provider == nil: + return errOption(fmt.Errorf("option: WithFederationTokenProvider: provider is nil")) + case opts.FederationRuleID == "": + return errOption(fmt.Errorf("option: WithFederationTokenProvider: FederationRuleID is required")) + case opts.OrganizationID == "": + return errOption(fmt.Errorf("option: WithFederationTokenProvider: OrganizationID is required")) + } + tokenProvider := auth.NewOIDCFederationCredentials(auth.OIDCFederationConfig{ + IdentityProvider: identityTokenFuncAdapter{fn: provider}, + FederationRuleID: opts.FederationRuleID, + OrganizationID: opts.OrganizationID, + ServiceAccountID: opts.ServiceAccountID, + WorkspaceID: opts.WorkspaceID, + }) + return auth.WithAuthMiddleware(tokenProvider) +} + // RequestOption is an option for the requests made by the anthropic API Client // which can be supplied to clients, services, and methods. You can read more about this functional // options pattern in our [README]. @@ -261,6 +379,251 @@ func WithRequestTimeout(dur time.Duration) RequestOption { }) } +// withConfigClientKey mirrors auth.clientKey: one auth.TokenCache per transport. +type withConfigClientKey struct { + httpClient *http.Client + customDoer requestconfig.HTTPDoer +} + +// WithConfig returns a [RequestOption] that authenticates requests using +// the given [config.Config]. +// +// Credential resolution is deferred to a request-time middleware so a +// later [WithAPIKey] / [WithAuthToken] (tier-1 explicit-credential +// precedence) can preempt the profile — even when the profile's +// credentials are missing or broken. The same escape-hatch shape as +// [explicitProfileErrorOption] applies: if the final RequestConfig has a +// static APIKey/AuthToken, or the request already carries an +// Authorization / X-Api-Key header, the profile is treated as shadowed +// and resolution is skipped entirely. +// +// The config's non-credential fields (BaseURL, WorkspaceID) apply at +// option-Apply time and do not depend on credential resolution. BaseURL +// only takes effect when no explicit [WithBaseURL] is present. +// +// When a static credential shadows the profile, a one-shot warning is +// emitted so users migrating from API keys can tell why their profile is +// being ignored. Use [WithConfigQuiet] to suppress that warning when the +// caller has its own, richer diagnostic. +func WithConfig(cfg *config.Config) RequestOption { + return withConfig(cfg, false) +} + +// WithConfigQuiet is identical to [WithConfig] but suppresses the one-shot +// "static credential shadows profile" warning. Intended for callers (such as +// the CLI) that detect the same condition themselves and emit a more +// specific multi-auth diagnostic, so users don't see two warnings for the +// same thing. +func WithConfigQuiet(cfg *config.Config) RequestOption { + return withConfig(cfg, true) +} + +// WithProfile returns a [RequestOption] that loads the named profile from +// the default config directory (see [config.DefaultDir]) and authenticates +// requests using it — equivalent to setting ANTHROPIC_PROFILE=name and +// constructing a zero-config client. Shorthand for: +// +// cfg, err := config.LoadProfile(config.DefaultDir(), name) +// ... option.WithConfig(cfg) +// +// If the profile cannot be loaded, the error is deferred to the first +// request and is preempted by a static credential ([WithAPIKey] / +// [WithAuthToken]) — the same escape hatch as the ANTHROPIC_PROFILE env +// path. As with [WithConfig], a static credential shadows the profile at +// request time and a one-shot warning is emitted. +func WithProfile(name string) RequestOption { + if name == "" { + return errOption(fmt.Errorf("option: WithProfile: profile name is empty")) + } + cfg, err := config.LoadProfile(config.DefaultDir(), name) + if err != nil { + loadErr := fmt.Errorf("option: WithProfile(%q): %w", name, err) + return requestconfig.RequestOptionFunc(func(r *requestconfig.RequestConfig) error { + rc := r + check := func(req *http.Request, next func(*http.Request) (*http.Response, error)) (*http.Response, error) { + if rc.APIKey != "" || rc.AuthToken != "" { + return next(req) + } + if req.Header.Get("Authorization") != "" || req.Header.Get("X-Api-Key") != "" { + return next(req) + } + return nil, loadErr + } + r.Middlewares = append(r.Middlewares, check) + return nil + }) + } + return withConfig(cfg, false) +} + +// joinedOption is the [RequestOption] returned by [Join]. It is a distinct +// type (rather than a RequestOptionFunc closure) so that +// [HasWithoutEnvironmentDefaults] can look inside it. +type joinedOption []RequestOption + +func (opts joinedOption) Apply(r *requestconfig.RequestConfig) error { + return r.Apply(opts...) +} + +// Join returns a single [RequestOption] that applies opts in order, at the +// position the joined option occupies in the caller's option list. It is +// equivalent to passing opts individually at that position, and lets a +// function that configures several aspects of a client return one option: +// +// func WithPlatform(cfg Config) option.RequestOption { +// return option.Join( +// option.WithoutEnvironmentDefaults(), +// option.WithBaseURL(cfg.URL), +// option.WithMiddleware(cfg.middleware()), +// ) +// } +// +// A [WithoutEnvironmentDefaults] marker nested inside a Join (at any depth) +// is still recognized by anthropic.NewClient. +func Join(opts ...RequestOption) RequestOption { + return joinedOption(opts) +} + +// withoutEnvironmentDefaultsOption is the marker type returned by +// [WithoutEnvironmentDefaults]. Its Apply is a no-op; it is detected by +// [HasWithoutEnvironmentDefaults] before options are applied. +type withoutEnvironmentDefaultsOption struct{} + +func (withoutEnvironmentDefaultsOption) Apply(*requestconfig.RequestConfig) error { return nil } + +// WithoutEnvironmentDefaults returns a marker [RequestOption] that, when +// passed to anthropic.NewClient, causes it to skip the environment-based +// credential autoload performed by anthropic.DefaultClientOptions +// (ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN, ANTHROPIC_PROFILE, env +// federation, fallback profile, ANTHROPIC_BASE_URL). The hardcoded +// production base-URL default is still applied so callers that supply only +// credentials get a working client. +// +// Intended for callers that perform their own credential resolution (such +// as the CLI) and want full control over which auth source is used, without +// the SDK's autoloader contributing a second [WithConfig] that would emit a +// duplicate shadow-warning. +func WithoutEnvironmentDefaults() RequestOption { + return withoutEnvironmentDefaultsOption{} +} + +// HasWithoutEnvironmentDefaults reports whether opts contains a +// [WithoutEnvironmentDefaults] marker, looking inside options combined with +// [Join] at any depth. Used by anthropic.NewClient to decide whether to +// prepend anthropic.DefaultClientOptions. +func HasWithoutEnvironmentDefaults(opts []RequestOption) bool { + for _, o := range opts { + switch o := o.(type) { + case withoutEnvironmentDefaultsOption: + return true + case joinedOption: + if HasWithoutEnvironmentDefaults(o) { + return true + } + } + } + return false +} + +func withConfig(cfg *config.Config, quiet bool) RequestOption { + var ( + shadowOnce sync.Once + resolveOnce sync.Once + provider auth.TokenProvider + resolveErr error + + cacheMu sync.Mutex + cacheBy = map[withConfigClientKey]*auth.TokenCache{} + ) + return requestconfig.RequestOptionFunc(func(r *requestconfig.RequestConfig) error { + // Non-credential config — applied unconditionally so a profile's + // base_url / workspace_id are honored even when its credentials + // are shadowed by a later WithAPIKey or fail to resolve. + if cfg.BaseURL != "" && r.BaseURL == nil { + if err := WithBaseURL(cfg.BaseURL).Apply(r); err != nil { + return err + } + } + // For federation profiles workspace_id is sent in the jwt-bearer + // exchange body, not as a request header (the minted token is + // already workspace-scoped, so the header would be ignored). + isFederation := cfg.AuthenticationInfo != nil && + cfg.AuthenticationInfo.Type == config.AuthenticationTypeOIDCFederation + if cfg.WorkspaceID != "" && !isFederation { + if err := WithHeader("anthropic-workspace-id", cfg.WorkspaceID).Apply(r); err != nil { + return err + } + } + + // Both checks below are request-time middlewares so they observe + // the RequestConfig after ALL options have applied — order of + // WithConfig vs WithAPIKey/WithAuthToken in the caller's option + // list doesn't matter. + rc := r + if !quiet { + shadowCheck := func(req *http.Request, next func(*http.Request) (*http.Response, error)) (*http.Response, error) { + shadowOnce.Do(func() { + switch { + case rc.APIKey != "": + auth.WarnConfigShadowed("ANTHROPIC_API_KEY", detectShadowSource("ANTHROPIC_API_KEY")) + case rc.AuthToken != "": + auth.WarnConfigShadowed("ANTHROPIC_AUTH_TOKEN", detectShadowSource("ANTHROPIC_AUTH_TOKEN")) + } + }) + return next(req) + } + r.Middlewares = append(r.Middlewares, shadowCheck) + } + + credCheck := func(req *http.Request, next func(*http.Request) (*http.Response, error)) (*http.Response, error) { + if rc.APIKey != "" || rc.AuthToken != "" { + return next(req) + } + if req.Header.Get("Authorization") != "" || req.Header.Get("X-Api-Key") != "" { + return next(req) + } + resolveOnce.Do(func() { + result, err := auth.ResolveCredentials(cfg) + if err != nil { + resolveErr = err + return + } + provider = result.Provider + }) + if resolveErr != nil { + return nil, resolveErr + } + + handler := rc.HTTPClient.Do + if rc.CustomHTTPDoer != nil { + handler = rc.CustomHTTPDoer.Do + } + key := withConfigClientKey{httpClient: rc.HTTPClient, customDoer: rc.CustomHTTPDoer} + cacheMu.Lock() + cache, ok := cacheBy[key] + if !ok { + cache = auth.NewTokenCache(provider, handler) + cacheBy[key] = cache + } + cacheMu.Unlock() + return auth.NewMiddleware(cache, rc)(req, next) + } + r.Middlewares = append(r.Middlewares, credCheck) + return nil + }) +} + +// detectShadowSource classifies where the shadowing static credential +// came from by inspecting whether the named env var is set. When the env +// var has a non-empty value the source is [auth.ConfigShadowFromEnv]; +// otherwise the credential must have come from an explicit option call. +func detectShadowSource(envVar string) auth.ConfigShadowSource { + if v, ok := os.LookupEnv(envVar); ok && v != "" { + return auth.ConfigShadowFromEnv + } + return auth.ConfigShadowFromOption +} + // WithEnvironmentProduction returns a RequestOption that sets the current // environment to be the "production" environment. An environment specifies which base URL // to use by default. @@ -283,3 +646,11 @@ func WithAuthToken(value string) RequestOption { return r.Apply(WithHeader("authorization", fmt.Sprintf("Bearer %s", r.AuthToken))) }) } + +// WithWebhookKey returns a RequestOption that sets the client setting "webhook_key". +func WithWebhookKey(value string) RequestOption { + return requestconfig.PreRequestOptionFunc(func(r *requestconfig.RequestConfig) error { + r.WebhookKey = value + return nil + }) +} diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/packages/jsonl/jsonl.go b/vendor/github.com/anthropics/anthropic-sdk-go/packages/jsonl/jsonl.go index 676445304..f94515dcd 100644 --- a/vendor/github.com/anthropics/anthropic-sdk-go/packages/jsonl/jsonl.go +++ b/vendor/github.com/anthropics/anthropic-sdk-go/packages/jsonl/jsonl.go @@ -26,9 +26,11 @@ func NewStream[T any](res *http.Response, err error) *Stream[T] { return &Stream[T]{err: fmt.Errorf("No streaming response body")} } + scn := bufio.NewScanner(res.Body) + scn.Buffer(nil, bufio.MaxScanTokenSize<<9) return &Stream[T]{ rc: res.Body, - scn: bufio.NewScanner(res.Body), + scn: scn, err: err, } } @@ -39,6 +41,9 @@ func (s *Stream[T]) Next() bool { } if !s.scn.Scan() { + if err := s.scn.Err(); err != nil { + s.err = err + } return false } @@ -58,5 +63,8 @@ func (s *Stream[T]) Err() error { } func (s *Stream[T]) Close() error { + if s.rc == nil { + return nil + } return s.rc.Close() } diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/packages/pagination/pagination.go b/vendor/github.com/anthropics/anthropic-sdk-go/packages/pagination/pagination.go index d0dd33a0b..fa182b2c7 100644 --- a/vendor/github.com/anthropics/anthropic-sdk-go/packages/pagination/pagination.go +++ b/vendor/github.com/anthropics/anthropic-sdk-go/packages/pagination/pagination.go @@ -342,3 +342,105 @@ func (r *PageCursorAutoPager[T]) Err() error { func (r *PageCursorAutoPager[T]) Index() int { return r.run } + +type BidirectionalPageCursor[T any] struct { + Data []T `json:"data"` + NextPage string `json:"next_page" api:"nullable"` + PrevPage string `json:"prev_page" api:"nullable"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Data respjson.Field + NextPage respjson.Field + PrevPage respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` + cfg *requestconfig.RequestConfig + res *http.Response +} + +// Returns the unmodified JSON received from the API +func (r BidirectionalPageCursor[T]) RawJSON() string { return r.JSON.raw } +func (r *BidirectionalPageCursor[T]) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// GetNextPage returns the next page as defined by this pagination style. When +// there is no next page, this function will return a 'nil' for the page value, but +// will not return an error +func (r *BidirectionalPageCursor[T]) GetNextPage() (res *BidirectionalPageCursor[T], err error) { + if len(r.Data) == 0 { + return nil, nil + } + next := r.NextPage + if len(next) == 0 { + return nil, nil + } + cfg := r.cfg.Clone(r.cfg.Context) + err = cfg.Apply(option.WithQuery("page", next)) + if err != nil { + return nil, err + } + var raw *http.Response + cfg.ResponseInto = &raw + cfg.ResponseBodyInto = &res + err = cfg.Execute() + if err != nil { + return nil, err + } + res.SetPageConfig(cfg, raw) + return res, nil +} + +func (r *BidirectionalPageCursor[T]) SetPageConfig(cfg *requestconfig.RequestConfig, res *http.Response) { + if r == nil { + r = &BidirectionalPageCursor[T]{} + } + r.cfg = cfg + r.res = res +} + +type BidirectionalPageCursorAutoPager[T any] struct { + page *BidirectionalPageCursor[T] + cur T + idx int + run int + err error + paramObj +} + +func NewBidirectionalPageCursorAutoPager[T any](page *BidirectionalPageCursor[T], err error) *BidirectionalPageCursorAutoPager[T] { + return &BidirectionalPageCursorAutoPager[T]{ + page: page, + err: err, + } +} + +func (r *BidirectionalPageCursorAutoPager[T]) Next() bool { + if r.page == nil || len(r.page.Data) == 0 { + return false + } + if r.idx >= len(r.page.Data) { + r.idx = 0 + r.page, r.err = r.page.GetNextPage() + if r.err != nil || r.page == nil || len(r.page.Data) == 0 { + return false + } + } + r.cur = r.page.Data[r.idx] + r.run += 1 + r.idx += 1 + return true +} + +func (r *BidirectionalPageCursorAutoPager[T]) Current() T { + return r.cur +} + +func (r *BidirectionalPageCursorAutoPager[T]) Err() error { + return r.err +} + +func (r *BidirectionalPageCursorAutoPager[T]) Index() int { + return r.run +} diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/packages/param/encoder.go b/vendor/github.com/anthropics/anthropic-sdk-go/packages/param/encoder.go index 1ce37ce3a..2e6f2c6ff 100644 --- a/vendor/github.com/anthropics/anthropic-sdk-go/packages/param/encoder.go +++ b/vendor/github.com/anthropics/anthropic-sdk-go/packages/param/encoder.go @@ -52,12 +52,18 @@ func MarshalWithExtras[T ParamStruct, R any](f T, underlying any, extras map[str var a any = v if a == Omit { // Errors when handling ForceOmitted are ignored. - if b, e := sjson.DeleteBytes(bytes, k); e == nil { + if b, e := sjson.DeleteBytes(bytes, EscapeSJSONKey(k)); e == nil { bytes = b } continue } - bytes, err = sjson.SetBytes(bytes, EscapeSJSONKey(k), v) + // Marshal the value ourselves so extras are HTML-escaped and + // validated like every other field; sjson would insert it raw. + raw, err := shimjson.Marshal(v) + if err != nil { + return nil, err + } + bytes, err = sjson.SetRawBytes(bytes, EscapeSJSONKey(k), raw) if err != nil { return nil, err } @@ -66,7 +72,7 @@ func MarshalWithExtras[T ParamStruct, R any](f T, underlying any, extras map[str } else if ovr, ok := f.Overrides(); ok { return shimjson.Marshal(ovr) } else { - return shimjson.Marshal(underlying) + return shimjson.Marshal(underlying, shimjson.WithSkipCompaction(true)) } } @@ -96,7 +102,7 @@ func MarshalUnion[T ParamStruct](metadata T, variants ...any) ([]byte, error) { Err: fmt.Errorf("expected union to have only one present variant, got %d", nPresent), } } - return shimjson.Marshal(variants[presentIdx]) + return shimjson.Marshal(variants[presentIdx], shimjson.WithSkipCompaction(true)) } // typeFor is shimmed from Go 1.23 "reflect" package diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/packages/ssestream/ssestream.go b/vendor/github.com/anthropics/anthropic-sdk-go/packages/ssestream/ssestream.go index 3ada309e6..5b214d6e3 100644 --- a/vendor/github.com/anthropics/anthropic-sdk-go/packages/ssestream/ssestream.go +++ b/vendor/github.com/anthropics/anthropic-sdk-go/packages/ssestream/ssestream.go @@ -10,6 +10,8 @@ import ( "io" "net/http" "strings" + + "github.com/anthropics/anthropic-sdk-go/internal/apierror" ) type Decoder interface { @@ -33,9 +35,45 @@ func NewDecoder(res *http.Response) Decoder { scn.Buffer(nil, bufio.MaxScanTokenSize<<9) decoder = &eventStreamDecoder{rc: res.Body, scn: scn} } + + // richDecoder needs the http request to provide helpful errors + // Aside from the error case there should be no difference + // from the underlying decoder. + if res.Request != nil { + return richErrorDecoder{Decoder: decoder, resp: res} + } + return decoder } +// richErrorDecoder wraps a Decoder and carries the original [*http.Response] +// so that it can construct rich API errors from SSE error events. +// +// A richErrorDecoder is used by [Stream] to construct errors whenever possible. +// [Stream] needs to rely on the underlying decoder, because the [Stream] has +// no access to the original http request. +// +// There should be no other differences from the underlying decoder. +type richErrorDecoder struct { + Decoder + resp *http.Response +} + +func (d *richErrorDecoder) newAPIError(errorJSON []byte) error { + aerr := &apierror.Error{} + if d.resp != nil { + aerr.Request = d.resp.Request + aerr.Response = d.resp + aerr.StatusCode = d.resp.StatusCode + aerr.RequestID = d.resp.Header.Get("request-id") + aerr.WorkspaceID = d.resp.Header.Get("anthropic-workspace-id") + } + if aerr.UnmarshalJSON(errorJSON) != nil { + return fmt.Errorf("received error while streaming: %s", string(errorJSON)) + } + return aerr +} + var decoderTypes = map[string](func(io.ReadCloser) Decoder){} func RegisterDecoder(contentType string, decoder func(io.ReadCloser) Decoder) { @@ -159,7 +197,7 @@ func (s *Stream[T]) Next() bool { } s.cur = nxt return true - case "message_start", "message_delta", "message_stop", "content_block_start", "content_block_delta", "content_block_stop", "message", "user.message", "user.interrupt", "user.tool_confirmation", "user.custom_tool_result", "agent.message", "agent.thinking", "agent.tool_use", "agent.tool_result", "agent.mcp_tool_use", "agent.mcp_tool_result", "agent.custom_tool_use", "agent.thread_context_compacted", "session.status_running", "session.status_idle", "session.status_rescheduled", "session.status_terminated", "session.error", "session.deleted", "span.model_request_start", "span.model_request_end": + case "message_start", "message_delta", "message_stop", "content_block_start", "content_block_delta", "content_block_stop", "message", "user.message", "user.interrupt", "user.tool_confirmation", "user.custom_tool_result", "user.tool_result", "agent.message", "agent.thinking", "agent.tool_use", "agent.tool_result", "agent.mcp_tool_use", "agent.mcp_tool_result", "agent.custom_tool_use", "agent.thread_context_compacted", "session.status_running", "session.status_idle", "session.status_rescheduled", "session.status_terminated", "session.error", "session.deleted", "session.updated", "span.model_request_start", "span.model_request_end", "span.outcome_evaluation_start", "span.outcome_evaluation_ongoing", "span.outcome_evaluation_end", "user.define_outcome", "agent.thread_message_received", "agent.thread_message_sent", "agent.session_thread_message_received", "agent.session_thread_message_sent", "session.thread_created", "session.thread_status_created", "session.thread_status_running", "session.thread_status_idle", "session.thread_status_rescheduled", "session.thread_status_terminated", "event_start", "event_delta", "system.message": var nxt T s.err = json.Unmarshal(s.decoder.Event().Data, &nxt) if s.err != nil { @@ -170,7 +208,12 @@ func (s *Stream[T]) Next() bool { case "ping": continue case "error": - s.err = fmt.Errorf("received error while streaming: %s", string(s.decoder.Event().Data)) + data := s.decoder.Event().Data + if ed, ok := s.decoder.(richErrorDecoder); ok { + s.err = ed.newAPIError(data) + } else { + s.err = fmt.Errorf("received error while streaming: %s", string(data)) + } return false } } diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/schemautil.go b/vendor/github.com/anthropics/anthropic-sdk-go/schemautil.go index 0c27c1e32..dcb5932f8 100644 --- a/vendor/github.com/anthropics/anthropic-sdk-go/schemautil.go +++ b/vendor/github.com/anthropics/anthropic-sdk-go/schemautil.go @@ -1,13 +1,268 @@ package anthropic import ( + "encoding/json" "fmt" - "maps" + "reflect" "slices" "sort" "strings" + + "github.com/invopop/jsonschema" + orderedmap "github.com/pb33f/ordered-map/v2" ) +// supportedSchemaKeySet is a set version of supportedSchemaKeys for O(1) lookups. +var supportedSchemaKeySet = func() map[string]bool { + m := make(map[string]bool, len(supportedSchemaKeys)) + for _, k := range supportedSchemaKeys { + m[k] = true + } + return m +}() + +// transformSchema transforms a [jsonschema.Schema] in-place to ensure it +// conforms to the Anthropic API's expectations. +// +// The transformation process: +// - Preserves $ref references +// - Transforms $defs, anyOf, and allOf recursively +// - Handles oneOf by converting it to anyOf +// - Ensures objects have additionalProperties: false +// - Filters string formats to only supported ones +// - Limits array minItems to 0 or 1 +// - Appends unsupported properties to the description +func transformSchema(s *jsonschema.Schema) { + if s == nil { + return + } + + // $ref is not supported alongside other properties + if s.Ref != "" { + *s = jsonschema.Schema{Ref: s.Ref} + return + } + + // Collect and clear fields not in the supported set + extras := extractUnsupportedFields(s) + + // Transform $defs recursively + for _, def := range s.Definitions { + transformSchema(def) + } + + // Convert oneOf to anyOf before recursing so variants are transformed once. + if len(s.OneOf) > 0 && len(s.AnyOf) == 0 { + s.AnyOf = s.OneOf + } + s.OneOf = nil + + // Recurse into anyOf variants, dropping any that transformSchema zeroed out + // as invalid — a zero jsonschema.Schema marshals as the literal JSON `true`, + // which would otherwise leak into the variant list as a match-everything. + if len(s.AnyOf) > 0 { + kept := s.AnyOf[:0] + for _, variant := range s.AnyOf { + transformSchema(variant) + if variant != nil && !reflect.ValueOf(*variant).IsZero() { + kept = append(kept, variant) + } + } + s.AnyOf = kept + } + + // Recurse into allOf variants. Unlike anyOf, a zeroed-out (`true`) variant + // adds no constraint to a conjunction, so there's no need to prune. + for _, variant := range s.AllOf { + transformSchema(variant) + } + + // Bail if the schema carries no shape information — schema is invalid or a + // boolean schema. enum/const/allOf can all stand in for an explicit type. + // Boolean schemas (JSON true/false) carry meaning in an unexported field + // that zeroing would clear, flipping false→true. Detect them by checking + // whether any exported field is non-zero: if not, the schema is either + // boolean (preserve) or truly empty (zeroing is a no-op anyway). + if s.Type == "" && len(s.AnyOf) == 0 && len(s.AllOf) == 0 && len(s.Enum) == 0 && s.Const == nil { + if !hasExportedContent(s) { + return + } + *s = jsonschema.Schema{} + return + } + + switch s.Type { + case "object": + if s.Properties != nil { + for pair := s.Properties.Oldest(); pair != nil; pair = pair.Next() { + transformSchema(pair.Value) + } + s.AdditionalProperties = jsonschema.FalseSchema + } else if s.AdditionalProperties != nil { + // Dictionary-style schema (e.g. Go map types): no fixed properties, + // additionalProperties describes the value type. Preserve and recurse. + transformSchema(s.AdditionalProperties) + } else { + s.Properties = orderedmap.New[string, *jsonschema.Schema]() + s.AdditionalProperties = jsonschema.FalseSchema + } + + case "string": + if s.Format != "" && !slices.Contains(supportedStringFormats, s.Format) { + extras["format"] = s.Format + s.Format = "" + } + + case "array": + if s.Items != nil { + transformSchema(s.Items) + } + if s.MinItems != nil && *s.MinItems != 0 && *s.MinItems != 1 { + extras["minItems"] = *s.MinItems + s.MinItems = nil + } + } + + // Append unsupported properties to description + if len(extras) > 0 { + keys := make([]string, 0, len(extras)) + for k := range extras { + keys = append(keys, k) + } + sort.Strings(keys) + + parts := make([]string, 0, len(keys)) + for _, k := range keys { + parts = append(parts, fmt.Sprintf("%s: %s", k, formatExtraValue(extras[k]))) + } + + extraStr := "{" + strings.Join(parts, ", ") + "}" + if s.Description != "" { + s.Description += "\n\n" + extraStr + } else { + s.Description = extraStr + } + } +} + +// transformSchemaMap transforms a JSON schema map to conform to Anthropic's API +// requirements. It delegates to [transformSchema] via a JSON round-trip. +func transformSchemaMap(jsonSchema map[string]any) map[string]any { + if jsonSchema == nil { + return nil + } + + b, err := json.Marshal(jsonSchema) + if err != nil { + return nil + } + + var s jsonschema.Schema + if err := json.Unmarshal(b, &s); err != nil { + return nil + } + + transformSchema(&s) + + result, err := json.Marshal(&s) + if err != nil { + return nil + } + + var out map[string]any + if err := json.Unmarshal(result, &out); err != nil { + return nil + } + return out +} + +// formatExtraValue renders a value extracted from the schema for inclusion in +// the description. Composite values (*Schema, []*Schema, maps) are +// JSON-marshaled so they render readably instead of as Go pointer dumps. +// Scalars use %v so strings stay unquoted. Pointers are dereferenced first: +// many keywords (maxLength, maxItems, ...) are pointer-typed on the schema +// struct, and %v on a pointer prints its address. +func formatExtraValue(v any) string { + rv := reflect.ValueOf(v) + for rv.Kind() == reflect.Pointer { + if rv.IsNil() { + return "null" + } + rv = rv.Elem() + } + // A JSON null in Extras arrives as an untyped nil, which has no Kind. + if !rv.IsValid() { + return "null" + } + switch rv.Kind() { + case reflect.Slice, reflect.Array, reflect.Map, reflect.Struct: + if b, err := json.Marshal(v); err == nil { + return string(b) + } + } + return fmt.Sprintf("%v", rv.Interface()) +} + +// hasExportedContent reports whether any exported field on the schema is non-zero. +// Boolean schemas (JSON true/false) store their value in an unexported field, so +// they return false here despite being meaningful. +func hasExportedContent(s *jsonschema.Schema) bool { + v := reflect.ValueOf(s).Elem() + t := v.Type() + for i := range t.NumField() { + if t.Field(i).IsExported() && !v.Field(i).IsZero() { + return true + } + } + return false +} + +// extractUnsupportedFields uses reflection to find non-zero exported fields on +// the schema whose JSON key is not in the supported set. It collects their +// values into a map and zeros the fields, so they won't appear in the marshaled +// output. This avoids enumerating every field explicitly and automatically +// handles new fields added to the jsonschema library. +func extractUnsupportedFields(s *jsonschema.Schema) map[string]any { + extras := make(map[string]any) + v := reflect.ValueOf(s).Elem() + t := v.Type() + + for i := range t.NumField() { + field := t.Field(i) + if !field.IsExported() { + continue + } + + jsonTag := field.Tag.Get("json") + name, _, _ := strings.Cut(jsonTag, ",") + if name == "" || name == "-" { + continue + } + + if supportedSchemaKeySet[name] { + continue + } + + fv := v.Field(i) + if fv.IsZero() { + continue + } + + extras[name] = fv.Interface() + fv.SetZero() + } + + // Handle the Extras map (tagged json:"-", inlined by Schema.MarshalJSON) + for k, val := range s.Extras { + if !supportedSchemaKeySet[k] { + extras[k] = val + } + } + s.Extras = nil + + return extras +} + // BetaJSONSchemaOutputFormat creates a BetaJSONOutputFormatParam from a JSON schema map. // It transforms the schema to ensure compatibility with Anthropic's JSON schema requirements. // @@ -30,13 +285,13 @@ import ( // OutputFormat: outputFormat, // }) func BetaJSONSchemaOutputFormat(jsonSchema map[string]any) BetaJSONOutputFormatParam { - return BetaJSONOutputFormatParam{Schema: transformSchema(jsonSchema)} + return BetaJSONOutputFormatParam{Schema: transformSchemaMap(jsonSchema)} } // BetaToolInputSchema creates a BetaToolInputSchemaParam from a JSON schema map. // It transforms the schema to ensure compatibility with Anthropic's tool calling requirements. func BetaToolInputSchema(jsonSchema map[string]any) BetaToolInputSchemaParam { - return BetaToolInputSchemaParam{ExtraFields: transformSchema(jsonSchema)} + return BetaToolInputSchemaParam{ExtraFields: transformSchemaMap(jsonSchema)} } var supportedStringFormats = []string{ @@ -58,9 +313,14 @@ var supportedSchemaKeys = []string{ "type", "anyOf", "oneOf", + "allOf", "description", "title", + // Value constraints + "enum", + "const", + // Object-specific keys "properties", "additionalProperties", @@ -72,173 +332,5 @@ var supportedSchemaKeys = []string{ // String-specific keys "format", -} - -// TransformSchema transforms a JSON schema to ensure it conforms to the Anthropic API's expectations. -// It returns nil if the transformed schema is empty. -// -// The transformation process: -// - Preserves $ref references -// - Transforms $defs recursively -// - Handles anyOf/oneOf by converting oneOf to anyOf -// - Ensures objects have additionalProperties: false -// - Filters string formats to only supported ones -// - Limits array minItems to 0 or 1 -// - Appends unsupported properties to the description -// -// Example: -// -// schema := map[string]any{ -// "type": "integer", -// "minimum": 1, -// "maximum": 10, -// "description": "A number", -// } -// transformed := TransformSchema(schema) -// // Result: {"type": "integer", "description": "A number\n\n{minimum: 1, maximum: 10}"} -func transformSchema(jsonSchema map[string]any) map[string]any { - if jsonSchema == nil { - return nil - } - - strictSchema := make(map[string]any) - - // Create a copy to avoid modifying the original - schemaCopy := make(map[string]any) - maps.Copy(schemaCopy, jsonSchema) - - // $ref is not supported alongside other properties - if ref, ok := schemaCopy["$ref"]; ok { - strictSchema["$ref"] = ref - return strictSchema - } - - for _, key := range supportedSchemaKeys { - value, exists := schemaCopy[key] - if exists { - delete(schemaCopy, key) - strictSchema[key] = value - } - } - - if defs, ok := strictSchema["$defs"]; ok { - if defsMap, ok := defs.(map[string]any); ok { - strictDefs := make(map[string]any) - strictSchema["$defs"] = strictDefs - - for name, schema := range defsMap { - if schemaMap, ok := schema.(map[string]any); ok { - strictDefs[name] = transformSchema(schemaMap) - } - } - } - } - - typeValue, _ := strictSchema["type"] - anyOf, _ := strictSchema["anyOf"] - oneOf, _ := strictSchema["oneOf"] - - if anyOfSlice, ok := anyOf.([]any); ok { - transformedVariants := make([]any, 0, len(anyOfSlice)) - for _, variant := range anyOfSlice { - variantMap, ok := variant.(map[string]any) - if !ok { - continue - } - if transformed := transformSchema(variantMap); transformed != nil { - transformedVariants = append(transformedVariants, transformed) - } - } - strictSchema["anyOf"] = transformedVariants - } else if oneOfSlice, ok := oneOf.([]any); ok { - transformedVariants := make([]any, 0, len(oneOfSlice)) - for _, variant := range oneOfSlice { - if variantMap, ok := variant.(map[string]any); ok { - if transformed := transformSchema(variantMap); transformed != nil { - transformedVariants = append(transformedVariants, transformed) - } - } - } - delete(strictSchema, "oneOf") - strictSchema["anyOf"] = transformedVariants - } else { - if typeValue == nil { - // schema is completely invalid, we have to bail - return nil - } - - strictSchema["type"] = typeValue - } - - typeStr, _ := typeValue.(string) - switch typeStr { - case "object": - if properties, ok := strictSchema["properties"]; ok { - if propsMap, ok := properties.(map[string]any); ok { - transformedProps := make(map[string]any) - for key, propSchema := range propsMap { - if propSchemaMap, ok := propSchema.(map[string]any); ok { - transformedProps[key] = transformSchema(propSchemaMap) - } - } - strictSchema["properties"] = transformedProps - } - } else { - strictSchema["properties"] = make(map[string]any) - } - - strictSchema["additionalProperties"] = false - - case "string": - if format, ok := strictSchema["format"]; ok { - if formatStr, ok := format.(string); ok { - if !slices.Contains(supportedStringFormats, formatStr) { - schemaCopy["format"] = format - delete(strictSchema, "format") - } - } - } - - case "array": - if items, ok := strictSchema["items"]; ok { - if itemsMap, ok := items.(map[string]any); ok { - strictSchema["items"] = transformSchema(itemsMap) - } - } - - if minItems, ok := strictSchema["minItems"]; ok { - if minItems != 0 && minItems != 1 { - schemaCopy["minItems"] = minItems - delete(strictSchema, "minItems") - } - } - - case "boolean", "integer", "number", "null": - // These types are supported as-is - } - - if len(schemaCopy) > 0 { - description := strictSchema["description"] - descStr, _ := description.(string) - - // Sort keys for deterministic output - keys := make([]string, 0, len(schemaCopy)) - for key := range schemaCopy { - keys = append(keys, key) - } - sort.Strings(keys) - - extraProps := make([]string, 0, len(keys)) - for _, key := range keys { - extraProps = append(extraProps, fmt.Sprintf("%s: %v", key, schemaCopy[key])) - } - - if descStr != "" { - strictSchema["description"] = descStr + "\n\n{" + strings.Join(extraProps, ", ") + "}" - } else { - strictSchema["description"] = "{" + strings.Join(extraProps, ", ") + "}" - } - } - - return strictSchema + "pattern", } diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/shared/constant/constants.go b/vendor/github.com/anthropics/anthropic-sdk-go/shared/constant/constants.go index acb587dd2..0d5f65b8d 100644 --- a/vendor/github.com/anthropics/anthropic-sdk-go/shared/constant/constants.go +++ b/vendor/github.com/anthropics/anthropic-sdk-go/shared/constant/constants.go @@ -14,7 +14,6 @@ var ModelNonStreamingTokens = map[string]int{ "claude-opus-4-0": 8192, "anthropic.claude-opus-4-20250514-v1:0": 8192, "claude-opus-4@20250514": 8192, - "claude-opus-4-1-20250805": 8192, "anthropic.claude-opus-4-1-20250805-v1:0": 8192, "claude-opus-4-1@20250805": 8192, } @@ -39,14 +38,22 @@ type AdvisorRedactedResult string // Always "advisor_redacted_ type AdvisorResult string // Always "advisor_result" type AdvisorToolResult string // Always "advisor_tool_result" type AdvisorToolResultError string // Always "advisor_tool_result_error" +type AgentArchived string // Always "agent.archived" +type AgentCreated string // Always "agent.created" +type AgentDeleted string // Always "agent.deleted" +type AgentUpdated string // Always "agent.updated" type All string // Always "all" type Any string // Always "any" type APIError string // Always "api_error" +type APIKey string // Always "api_key" type ApplicationPDF string // Always "application/pdf" type Approximate string // Always "approximate" type Assistant string // Always "assistant" +type Attached string // Always "attached" type AuthenticationError string // Always "authentication_error" type Auto string // Always "auto" +type AWS string // Always "aws" +type Azure string // Always "azure" type Base64 string // Always "base64" type Bash string // Always "bash" type Bash20241022 string // Always "bash_20241022" @@ -56,6 +63,8 @@ type BashCodeExecutionResult string // Always "bash_code_executi type BashCodeExecutionToolResult string // Always "bash_code_execution_tool_result" type BashCodeExecutionToolResultError string // Always "bash_code_execution_tool_result_error" type BillingError string // Always "billing_error" +type BrowserState string // Always "browser_state" +type BrowserToolset20260801 string // Always "browser_toolset_20260801" type Canceled string // Always "canceled" type CharLocation string // Always "char_location" type CitationsDelta string // Always "citations_delta" @@ -66,6 +75,7 @@ type CodeExecution string // Always "code_execution" type CodeExecution20250522 string // Always "code_execution_20250522" type CodeExecution20250825 string // Always "code_execution_20250825" type CodeExecution20260120 string // Always "code_execution_20260120" +type CodeExecution20260521 string // Always "code_execution_20260521" type CodeExecutionOutput string // Always "code_execution_output" type CodeExecutionResult string // Always "code_execution_result" type CodeExecutionToolResult string // Always "code_execution_tool_result" @@ -78,6 +88,7 @@ type Computer string // Always "computer" type Computer20241022 string // Always "computer_20241022" type Computer20250124 string // Always "computer_20250124" type Computer20251124 string // Always "computer_20251124" +type ComputerToolset20260801 string // Always "computer_toolset_20260801" type ContainerUpload string // Always "container_upload" type Content string // Always "content" type ContentBlockDelta string // Always "content_block_delta" @@ -85,57 +96,133 @@ type ContentBlockLocation string // Always "content_block_loc type ContentBlockStart string // Always "content_block_start" type ContentBlockStop string // Always "content_block_stop" type Create string // Always "create" +type Default string // Always "default" type Delete string // Always "delete" +type DeploymentRunFailed string // Always "deployment_run.failed" +type DeploymentRunStarted string // Always "deployment_run.started" +type DeploymentRunSucceeded string // Always "deployment_run.succeeded" +type DeploymentArchived string // Always "deployment.archived" +type DeploymentCreated string // Always "deployment.created" +type DeploymentDeleted string // Always "deployment.deleted" +type DeploymentPaused string // Always "deployment.paused" +type DeploymentUnpaused string // Always "deployment.unpaused" +type DeploymentUpdated string // Always "deployment.updated" type Direct string // Always "direct" type Disabled string // Always "disabled" +type Discovery string // Always "discovery" type Document string // Always "document" +type DownloadCompleted string // Always "download_completed" +type DownloadFailed string // Always "download_failed" +type DownloadStarted string // Always "download_started" +type Edit string // Always "edit" type Enabled string // Always "enabled" type EncryptedCodeExecutionResult string // Always "encrypted_code_execution_result" type Environment string // Always "environment" -type EnvironmentDeleted string // Always "environment_deleted" +type EnvironmentArchived string // Always "environment.archived" +type EnvironmentCreated string // Always "environment.created" +type EnvironmentDeleted string // Always "environment.deleted" +type EnvironmentUpdated string // Always "environment.updated" type Ephemeral string // Always "ephemeral" type Error string // Always "error" type Errored string // Always "errored" +type Event string // Always "event" type Expired string // Always "expired" +type ExplicitURL string // Always "explicit_url" +type ExternalKey string // Always "external_key" +type ExternalKeyDeleted string // Always "external_key_deleted" +type ExternalKeyValidation string // Always "external_key_validation" +type Fallback string // Always "fallback" +type FallbackMessage string // Always "fallback_message" +type FederationIssuer string // Always "federation_issuer" +type FederationRule string // Always "federation_rule" +type FederationRuleWorkspace string // Always "federation_rule_workspace" +type FederationRuleWorkspaceDeleted string // Always "federation_rule_workspace_deleted" type File string // Always "file" +type GCP string // Always "gcp" +type Glob string // Always "glob" +type Grep string // Always "grep" type Image string // Always "image" +type Inline string // Always "inline" type InputJSONDelta string // Always "input_json_delta" type InputTokens string // Always "input_tokens" type Insert string // Always "insert" type InvalidRequestError string // Always "invalid_request_error" +type Invite string // Always "invite" +type InviteDeleted string // Always "invite_deleted" type JSONSchema string // Always "json_schema" type Limited string // Always "limited" +type MCPToolReference string // Always "mcp_tool_reference" type MCPToolResult string // Always "mcp_tool_result" type MCPToolUse string // Always "mcp_tool_use" type MCPToolset string // Always "mcp_toolset" +type MCPToolsetReference string // Always "mcp_toolset_reference" type Memory string // Always "memory" type Memory20250818 string // Always "memory_20250818" +type MemoryStoreArchived string // Always "memory_store.archived" +type MemoryStoreCreated string // Always "memory_store.created" +type MemoryStoreDeleted string // Always "memory_store.deleted" type Message string // Always "message" type MessageBatch string // Always "message_batch" type MessageBatchDeleted string // Always "message_batch_deleted" type MessageDelta string // Always "message_delta" type MessageStart string // Always "message_start" type MessageStop string // Always "message_stop" +type MessagesChanged string // Always "messages_changed" type Model string // Always "model" +type ModelChanged string // Always "model_changed" type None string // Always "none" +type NotApplied string // Always "not_applied" type NotFoundError string // Always "not_found_error" type Object string // Always "object" +type Organization string // Always "organization" type OverloadedError string // Always "overloaded_error" type PageLocation string // Always "page_location" type PermissionError string // Always "permission_error" +type PreviousMessageNotFound string // Always "previous_message_not_found" +type RateLimit string // Always "rate_limit" type RateLimitError string // Always "rate_limit_error" +type Read string // Always "read" type RedactedThinking string // Always "redacted_thinking" +type Redeemed string // Always "redeemed" type Refusal string // Always "refusal" type Rename string // Always "rename" type SearchResult string // Always "search_result" type SearchResultLocation string // Always "search_result_location" +type SelfHosted string // Always "self_hosted" type ServerToolUse string // Always "server_tool_use" +type ServiceAccount string // Always "service_account" +type ServiceAccountActor string // Always "service_account_actor" +type ServiceAccountWorkspaceMember string // Always "service_account_workspace_member" +type ServiceAccountWorkspaceMemberDeleted string // Always "service_account_workspace_member_deleted" type Session string // Always "session" +type SessionArchived string // Always "session.archived" +type SessionBudgetReached string // Always "session.budget_reached" +type SessionCreated string // Always "session.created" +type SessionDeleted string // Always "session.deleted" +type SessionIdled string // Always "session.idled" +type SessionOutcomeEvaluationEnded string // Always "session.outcome_evaluation_ended" +type SessionPending string // Always "session.pending" +type SessionRequiresAction string // Always "session.requires_action" +type SessionRunning string // Always "session.running" +type SessionStatusIdled string // Always "session.status_idled" +type SessionStatusRescheduled string // Always "session.status_rescheduled" +type SessionStatusRunStarted string // Always "session.status_run_started" +type SessionStatusTerminated string // Always "session.status_terminated" +type SessionThreadCreated string // Always "session.thread_created" +type SessionThreadIdled string // Always "session.thread_idled" +type SessionThreadTerminated string // Always "session.thread_terminated" +type SessionUpdated string // Always "session.updated" type SignatureDelta string // Always "signature_delta" +type Skill string // Always "skill" +type SkillDeleted string // Always "skill_deleted" +type SkillVersion string // Always "skill_version" +type SkillVersionDeleted string // Always "skill_version_deleted" type StrReplace string // Always "str_replace" type StrReplaceBasedEditTool string // Always "str_replace_based_edit_tool" type StrReplaceEditor string // Always "str_replace_editor" type Succeeded string // Always "succeeded" +type SystemChanged string // Always "system_changed" +type TabOpened string // Always "tab_opened" type Text string // Always "text" type TextDelta string // Always "text_delta" type TextEditor20241022 string // Always "text_editor_20241022" @@ -154,7 +241,9 @@ type ThinkingTurns string // Always "thinking_turns" type TimeoutError string // Always "timeout_error" type Tokens string // Always "tokens" type Tool string // Always "tool" +type ToolAddition string // Always "tool_addition" type ToolReference string // Always "tool_reference" +type ToolRemoval string // Always "tool_removal" type ToolResult string // Always "tool_result" type ToolSearchToolBm25 string // Always "tool_search_tool_bm25" type ToolSearchToolRegex string // Always "tool_search_tool_regex" @@ -163,23 +252,49 @@ type ToolSearchToolResultError string // Always "tool_search_tool_ type ToolSearchToolSearchResult string // Always "tool_search_tool_search_result" type ToolUse string // Always "tool_use" type ToolUses string // Always "tool_uses" +type ToolsChanged string // Always "tools_changed" +type Tunnel string // Always "tunnel" +type TunnelCertificate string // Always "tunnel_certificate" +type TunnelToken string // Always "tunnel_token" +type Unattached string // Always "unattached" +type Unavailable string // Always "unavailable" type Unrestricted string // Always "unrestricted" type URL string // Always "url" +type User string // Always "user" +type UserActor string // Always "user_actor" +type UserDeleted string // Always "user_deleted" +type VaultCredentialArchived string // Always "vault_credential.archived" +type VaultCredentialCreated string // Always "vault_credential.created" +type VaultCredentialDeleted string // Always "vault_credential.deleted" +type VaultCredentialRefreshFailed string // Always "vault_credential.refresh_failed" +type VaultArchived string // Always "vault.archived" +type VaultCreated string // Always "vault.created" +type VaultDeleted string // Always "vault.deleted" type View string // Always "view" type WebFetch string // Always "web_fetch" type WebFetch20250910 string // Always "web_fetch_20250910" type WebFetch20260209 string // Always "web_fetch_20260209" type WebFetch20260309 string // Always "web_fetch_20260309" +type WebFetch20260318 string // Always "web_fetch_20260318" type WebFetchResult string // Always "web_fetch_result" type WebFetchToolResult string // Always "web_fetch_tool_result" type WebFetchToolResultError string // Always "web_fetch_tool_result_error" type WebSearch string // Always "web_search" type WebSearch20250305 string // Always "web_search_20250305" type WebSearch20260209 string // Always "web_search_20260209" +type WebSearch20260318 string // Always "web_search_20260318" type WebSearchResult string // Always "web_search_result" type WebSearchResultLocation string // Always "web_search_result_location" type WebSearchToolResult string // Always "web_search_tool_result" type WebSearchToolResultError string // Always "web_search_tool_result_error" +type Work string // Always "work" +type WorkHeartbeat string // Always "work_heartbeat" +type WorkQueueStats string // Always "work_queue_stats" +type Workspace string // Always "workspace" +type WorkspaceMember string // Always "workspace_member" +type WorkspaceMemberDeleted string // Always "workspace_member_deleted" +type WorkspaceRateLimit string // Always "workspace_rate_limit" +type Write string // Always "write" func (c Adaptive) Default() Adaptive { return "adaptive" } func (c Advisor) Default() Advisor { return "advisor" } @@ -189,14 +304,22 @@ func (c AdvisorRedactedResult) Default() AdvisorRedactedResult { return "advis func (c AdvisorResult) Default() AdvisorResult { return "advisor_result" } func (c AdvisorToolResult) Default() AdvisorToolResult { return "advisor_tool_result" } func (c AdvisorToolResultError) Default() AdvisorToolResultError { return "advisor_tool_result_error" } +func (c AgentArchived) Default() AgentArchived { return "agent.archived" } +func (c AgentCreated) Default() AgentCreated { return "agent.created" } +func (c AgentDeleted) Default() AgentDeleted { return "agent.deleted" } +func (c AgentUpdated) Default() AgentUpdated { return "agent.updated" } func (c All) Default() All { return "all" } func (c Any) Default() Any { return "any" } func (c APIError) Default() APIError { return "api_error" } +func (c APIKey) Default() APIKey { return "api_key" } func (c ApplicationPDF) Default() ApplicationPDF { return "application/pdf" } func (c Approximate) Default() Approximate { return "approximate" } func (c Assistant) Default() Assistant { return "assistant" } +func (c Attached) Default() Attached { return "attached" } func (c AuthenticationError) Default() AuthenticationError { return "authentication_error" } func (c Auto) Default() Auto { return "auto" } +func (c AWS) Default() AWS { return "aws" } +func (c Azure) Default() Azure { return "azure" } func (c Base64) Default() Base64 { return "base64" } func (c Bash) Default() Bash { return "bash" } func (c Bash20241022) Default() Bash20241022 { return "bash_20241022" } @@ -213,95 +336,197 @@ func (c BashCodeExecutionToolResult) Default() BashCodeExecutionToolResult { func (c BashCodeExecutionToolResultError) Default() BashCodeExecutionToolResultError { return "bash_code_execution_tool_result_error" } -func (c BillingError) Default() BillingError { return "billing_error" } -func (c Canceled) Default() Canceled { return "canceled" } -func (c CharLocation) Default() CharLocation { return "char_location" } -func (c CitationsDelta) Default() CitationsDelta { return "citations_delta" } -func (c ClearThinking20251015) Default() ClearThinking20251015 { return "clear_thinking_20251015" } -func (c ClearToolUses20250919) Default() ClearToolUses20250919 { return "clear_tool_uses_20250919" } -func (c Cloud) Default() Cloud { return "cloud" } -func (c CodeExecution) Default() CodeExecution { return "code_execution" } -func (c CodeExecution20250522) Default() CodeExecution20250522 { return "code_execution_20250522" } -func (c CodeExecution20250825) Default() CodeExecution20250825 { return "code_execution_20250825" } -func (c CodeExecution20260120) Default() CodeExecution20260120 { return "code_execution_20260120" } -func (c CodeExecutionOutput) Default() CodeExecutionOutput { return "code_execution_output" } -func (c CodeExecutionResult) Default() CodeExecutionResult { return "code_execution_result" } +func (c BillingError) Default() BillingError { return "billing_error" } +func (c BrowserState) Default() BrowserState { return "browser_state" } +func (c BrowserToolset20260801) Default() BrowserToolset20260801 { return "browser_toolset_20260801" } +func (c Canceled) Default() Canceled { return "canceled" } +func (c CharLocation) Default() CharLocation { return "char_location" } +func (c CitationsDelta) Default() CitationsDelta { return "citations_delta" } +func (c ClearThinking20251015) Default() ClearThinking20251015 { return "clear_thinking_20251015" } +func (c ClearToolUses20250919) Default() ClearToolUses20250919 { return "clear_tool_uses_20250919" } +func (c Cloud) Default() Cloud { return "cloud" } +func (c CodeExecution) Default() CodeExecution { return "code_execution" } +func (c CodeExecution20250522) Default() CodeExecution20250522 { return "code_execution_20250522" } +func (c CodeExecution20250825) Default() CodeExecution20250825 { return "code_execution_20250825" } +func (c CodeExecution20260120) Default() CodeExecution20260120 { return "code_execution_20260120" } +func (c CodeExecution20260521) Default() CodeExecution20260521 { return "code_execution_20260521" } +func (c CodeExecutionOutput) Default() CodeExecutionOutput { return "code_execution_output" } +func (c CodeExecutionResult) Default() CodeExecutionResult { return "code_execution_result" } func (c CodeExecutionToolResult) Default() CodeExecutionToolResult { return "code_execution_tool_result" } func (c CodeExecutionToolResultError) Default() CodeExecutionToolResultError { return "code_execution_tool_result_error" } -func (c Compact20260112) Default() Compact20260112 { return "compact_20260112" } -func (c Compaction) Default() Compaction { return "compaction" } -func (c CompactionDelta) Default() CompactionDelta { return "compaction_delta" } -func (c Completion) Default() Completion { return "completion" } -func (c Computer) Default() Computer { return "computer" } -func (c Computer20241022) Default() Computer20241022 { return "computer_20241022" } -func (c Computer20250124) Default() Computer20250124 { return "computer_20250124" } -func (c Computer20251124) Default() Computer20251124 { return "computer_20251124" } -func (c ContainerUpload) Default() ContainerUpload { return "container_upload" } -func (c Content) Default() Content { return "content" } -func (c ContentBlockDelta) Default() ContentBlockDelta { return "content_block_delta" } -func (c ContentBlockLocation) Default() ContentBlockLocation { return "content_block_location" } -func (c ContentBlockStart) Default() ContentBlockStart { return "content_block_start" } -func (c ContentBlockStop) Default() ContentBlockStop { return "content_block_stop" } -func (c Create) Default() Create { return "create" } -func (c Delete) Default() Delete { return "delete" } -func (c Direct) Default() Direct { return "direct" } -func (c Disabled) Default() Disabled { return "disabled" } -func (c Document) Default() Document { return "document" } -func (c Enabled) Default() Enabled { return "enabled" } +func (c Compact20260112) Default() Compact20260112 { return "compact_20260112" } +func (c Compaction) Default() Compaction { return "compaction" } +func (c CompactionDelta) Default() CompactionDelta { return "compaction_delta" } +func (c Completion) Default() Completion { return "completion" } +func (c Computer) Default() Computer { return "computer" } +func (c Computer20241022) Default() Computer20241022 { return "computer_20241022" } +func (c Computer20250124) Default() Computer20250124 { return "computer_20250124" } +func (c Computer20251124) Default() Computer20251124 { return "computer_20251124" } +func (c ComputerToolset20260801) Default() ComputerToolset20260801 { + return "computer_toolset_20260801" +} +func (c ContainerUpload) Default() ContainerUpload { return "container_upload" } +func (c Content) Default() Content { return "content" } +func (c ContentBlockDelta) Default() ContentBlockDelta { return "content_block_delta" } +func (c ContentBlockLocation) Default() ContentBlockLocation { return "content_block_location" } +func (c ContentBlockStart) Default() ContentBlockStart { return "content_block_start" } +func (c ContentBlockStop) Default() ContentBlockStop { return "content_block_stop" } +func (c Create) Default() Create { return "create" } +func (c Default) Default() Default { return "default" } +func (c Delete) Default() Delete { return "delete" } +func (c DeploymentRunFailed) Default() DeploymentRunFailed { return "deployment_run.failed" } +func (c DeploymentRunStarted) Default() DeploymentRunStarted { return "deployment_run.started" } +func (c DeploymentRunSucceeded) Default() DeploymentRunSucceeded { return "deployment_run.succeeded" } +func (c DeploymentArchived) Default() DeploymentArchived { return "deployment.archived" } +func (c DeploymentCreated) Default() DeploymentCreated { return "deployment.created" } +func (c DeploymentDeleted) Default() DeploymentDeleted { return "deployment.deleted" } +func (c DeploymentPaused) Default() DeploymentPaused { return "deployment.paused" } +func (c DeploymentUnpaused) Default() DeploymentUnpaused { return "deployment.unpaused" } +func (c DeploymentUpdated) Default() DeploymentUpdated { return "deployment.updated" } +func (c Direct) Default() Direct { return "direct" } +func (c Disabled) Default() Disabled { return "disabled" } +func (c Discovery) Default() Discovery { return "discovery" } +func (c Document) Default() Document { return "document" } +func (c DownloadCompleted) Default() DownloadCompleted { return "download_completed" } +func (c DownloadFailed) Default() DownloadFailed { return "download_failed" } +func (c DownloadStarted) Default() DownloadStarted { return "download_started" } +func (c Edit) Default() Edit { return "edit" } +func (c Enabled) Default() Enabled { return "enabled" } func (c EncryptedCodeExecutionResult) Default() EncryptedCodeExecutionResult { return "encrypted_code_execution_result" } -func (c Environment) Default() Environment { return "environment" } -func (c EnvironmentDeleted) Default() EnvironmentDeleted { return "environment_deleted" } -func (c Ephemeral) Default() Ephemeral { return "ephemeral" } -func (c Error) Default() Error { return "error" } -func (c Errored) Default() Errored { return "errored" } -func (c Expired) Default() Expired { return "expired" } -func (c File) Default() File { return "file" } -func (c Image) Default() Image { return "image" } -func (c InputJSONDelta) Default() InputJSONDelta { return "input_json_delta" } -func (c InputTokens) Default() InputTokens { return "input_tokens" } -func (c Insert) Default() Insert { return "insert" } -func (c InvalidRequestError) Default() InvalidRequestError { return "invalid_request_error" } -func (c JSONSchema) Default() JSONSchema { return "json_schema" } -func (c Limited) Default() Limited { return "limited" } -func (c MCPToolResult) Default() MCPToolResult { return "mcp_tool_result" } -func (c MCPToolUse) Default() MCPToolUse { return "mcp_tool_use" } -func (c MCPToolset) Default() MCPToolset { return "mcp_toolset" } -func (c Memory) Default() Memory { return "memory" } -func (c Memory20250818) Default() Memory20250818 { return "memory_20250818" } -func (c Message) Default() Message { return "message" } -func (c MessageBatch) Default() MessageBatch { return "message_batch" } -func (c MessageBatchDeleted) Default() MessageBatchDeleted { return "message_batch_deleted" } -func (c MessageDelta) Default() MessageDelta { return "message_delta" } -func (c MessageStart) Default() MessageStart { return "message_start" } -func (c MessageStop) Default() MessageStop { return "message_stop" } -func (c Model) Default() Model { return "model" } -func (c None) Default() None { return "none" } -func (c NotFoundError) Default() NotFoundError { return "not_found_error" } -func (c Object) Default() Object { return "object" } -func (c OverloadedError) Default() OverloadedError { return "overloaded_error" } -func (c PageLocation) Default() PageLocation { return "page_location" } -func (c PermissionError) Default() PermissionError { return "permission_error" } +func (c Environment) Default() Environment { return "environment" } +func (c EnvironmentArchived) Default() EnvironmentArchived { return "environment.archived" } +func (c EnvironmentCreated) Default() EnvironmentCreated { return "environment.created" } +func (c EnvironmentDeleted) Default() EnvironmentDeleted { return "environment.deleted" } +func (c EnvironmentUpdated) Default() EnvironmentUpdated { return "environment.updated" } +func (c Ephemeral) Default() Ephemeral { return "ephemeral" } +func (c Error) Default() Error { return "error" } +func (c Errored) Default() Errored { return "errored" } +func (c Event) Default() Event { return "event" } +func (c Expired) Default() Expired { return "expired" } +func (c ExplicitURL) Default() ExplicitURL { return "explicit_url" } +func (c ExternalKey) Default() ExternalKey { return "external_key" } +func (c ExternalKeyDeleted) Default() ExternalKeyDeleted { return "external_key_deleted" } +func (c ExternalKeyValidation) Default() ExternalKeyValidation { return "external_key_validation" } +func (c Fallback) Default() Fallback { return "fallback" } +func (c FallbackMessage) Default() FallbackMessage { return "fallback_message" } +func (c FederationIssuer) Default() FederationIssuer { return "federation_issuer" } +func (c FederationRule) Default() FederationRule { return "federation_rule" } +func (c FederationRuleWorkspace) Default() FederationRuleWorkspace { + return "federation_rule_workspace" +} +func (c FederationRuleWorkspaceDeleted) Default() FederationRuleWorkspaceDeleted { + return "federation_rule_workspace_deleted" +} +func (c File) Default() File { return "file" } +func (c GCP) Default() GCP { return "gcp" } +func (c Glob) Default() Glob { return "glob" } +func (c Grep) Default() Grep { return "grep" } +func (c Image) Default() Image { return "image" } +func (c Inline) Default() Inline { return "inline" } +func (c InputJSONDelta) Default() InputJSONDelta { return "input_json_delta" } +func (c InputTokens) Default() InputTokens { return "input_tokens" } +func (c Insert) Default() Insert { return "insert" } +func (c InvalidRequestError) Default() InvalidRequestError { return "invalid_request_error" } +func (c Invite) Default() Invite { return "invite" } +func (c InviteDeleted) Default() InviteDeleted { return "invite_deleted" } +func (c JSONSchema) Default() JSONSchema { return "json_schema" } +func (c Limited) Default() Limited { return "limited" } +func (c MCPToolReference) Default() MCPToolReference { return "mcp_tool_reference" } +func (c MCPToolResult) Default() MCPToolResult { return "mcp_tool_result" } +func (c MCPToolUse) Default() MCPToolUse { return "mcp_tool_use" } +func (c MCPToolset) Default() MCPToolset { return "mcp_toolset" } +func (c MCPToolsetReference) Default() MCPToolsetReference { return "mcp_toolset_reference" } +func (c Memory) Default() Memory { return "memory" } +func (c Memory20250818) Default() Memory20250818 { return "memory_20250818" } +func (c MemoryStoreArchived) Default() MemoryStoreArchived { return "memory_store.archived" } +func (c MemoryStoreCreated) Default() MemoryStoreCreated { return "memory_store.created" } +func (c MemoryStoreDeleted) Default() MemoryStoreDeleted { return "memory_store.deleted" } +func (c Message) Default() Message { return "message" } +func (c MessageBatch) Default() MessageBatch { return "message_batch" } +func (c MessageBatchDeleted) Default() MessageBatchDeleted { return "message_batch_deleted" } +func (c MessageDelta) Default() MessageDelta { return "message_delta" } +func (c MessageStart) Default() MessageStart { return "message_start" } +func (c MessageStop) Default() MessageStop { return "message_stop" } +func (c MessagesChanged) Default() MessagesChanged { return "messages_changed" } +func (c Model) Default() Model { return "model" } +func (c ModelChanged) Default() ModelChanged { return "model_changed" } +func (c None) Default() None { return "none" } +func (c NotApplied) Default() NotApplied { return "not_applied" } +func (c NotFoundError) Default() NotFoundError { return "not_found_error" } +func (c Object) Default() Object { return "object" } +func (c Organization) Default() Organization { return "organization" } +func (c OverloadedError) Default() OverloadedError { return "overloaded_error" } +func (c PageLocation) Default() PageLocation { return "page_location" } +func (c PermissionError) Default() PermissionError { return "permission_error" } +func (c PreviousMessageNotFound) Default() PreviousMessageNotFound { + return "previous_message_not_found" +} +func (c RateLimit) Default() RateLimit { return "rate_limit" } func (c RateLimitError) Default() RateLimitError { return "rate_limit_error" } +func (c Read) Default() Read { return "read" } func (c RedactedThinking) Default() RedactedThinking { return "redacted_thinking" } +func (c Redeemed) Default() Redeemed { return "redeemed" } func (c Refusal) Default() Refusal { return "refusal" } func (c Rename) Default() Rename { return "rename" } func (c SearchResult) Default() SearchResult { return "search_result" } func (c SearchResultLocation) Default() SearchResultLocation { return "search_result_location" } +func (c SelfHosted) Default() SelfHosted { return "self_hosted" } func (c ServerToolUse) Default() ServerToolUse { return "server_tool_use" } +func (c ServiceAccount) Default() ServiceAccount { return "service_account" } +func (c ServiceAccountActor) Default() ServiceAccountActor { return "service_account_actor" } +func (c ServiceAccountWorkspaceMember) Default() ServiceAccountWorkspaceMember { + return "service_account_workspace_member" +} +func (c ServiceAccountWorkspaceMemberDeleted) Default() ServiceAccountWorkspaceMemberDeleted { + return "service_account_workspace_member_deleted" +} func (c Session) Default() Session { return "session" } -func (c SignatureDelta) Default() SignatureDelta { return "signature_delta" } -func (c StrReplace) Default() StrReplace { return "str_replace" } +func (c SessionArchived) Default() SessionArchived { return "session.archived" } +func (c SessionBudgetReached) Default() SessionBudgetReached { return "session.budget_reached" } +func (c SessionCreated) Default() SessionCreated { return "session.created" } +func (c SessionDeleted) Default() SessionDeleted { return "session.deleted" } +func (c SessionIdled) Default() SessionIdled { return "session.idled" } +func (c SessionOutcomeEvaluationEnded) Default() SessionOutcomeEvaluationEnded { + return "session.outcome_evaluation_ended" +} +func (c SessionPending) Default() SessionPending { return "session.pending" } +func (c SessionRequiresAction) Default() SessionRequiresAction { return "session.requires_action" } +func (c SessionRunning) Default() SessionRunning { return "session.running" } +func (c SessionStatusIdled) Default() SessionStatusIdled { return "session.status_idled" } +func (c SessionStatusRescheduled) Default() SessionStatusRescheduled { + return "session.status_rescheduled" +} +func (c SessionStatusRunStarted) Default() SessionStatusRunStarted { + return "session.status_run_started" +} +func (c SessionStatusTerminated) Default() SessionStatusTerminated { + return "session.status_terminated" +} +func (c SessionThreadCreated) Default() SessionThreadCreated { return "session.thread_created" } +func (c SessionThreadIdled) Default() SessionThreadIdled { return "session.thread_idled" } +func (c SessionThreadTerminated) Default() SessionThreadTerminated { + return "session.thread_terminated" +} +func (c SessionUpdated) Default() SessionUpdated { return "session.updated" } +func (c SignatureDelta) Default() SignatureDelta { return "signature_delta" } +func (c Skill) Default() Skill { return "skill" } +func (c SkillDeleted) Default() SkillDeleted { return "skill_deleted" } +func (c SkillVersion) Default() SkillVersion { return "skill_version" } +func (c SkillVersionDeleted) Default() SkillVersionDeleted { return "skill_version_deleted" } +func (c StrReplace) Default() StrReplace { return "str_replace" } func (c StrReplaceBasedEditTool) Default() StrReplaceBasedEditTool { return "str_replace_based_edit_tool" } func (c StrReplaceEditor) Default() StrReplaceEditor { return "str_replace_editor" } func (c Succeeded) Default() Succeeded { return "succeeded" } +func (c SystemChanged) Default() SystemChanged { return "system_changed" } +func (c TabOpened) Default() TabOpened { return "tab_opened" } func (c Text) Default() Text { return "text" } func (c TextDelta) Default() TextDelta { return "text_delta" } func (c TextEditor20241022) Default() TextEditor20241022 { return "text_editor_20241022" } @@ -330,7 +555,9 @@ func (c ThinkingTurns) Default() ThinkingTurns { return "thinking_ func (c TimeoutError) Default() TimeoutError { return "timeout_error" } func (c Tokens) Default() Tokens { return "tokens" } func (c Tool) Default() Tool { return "tool" } +func (c ToolAddition) Default() ToolAddition { return "tool_addition" } func (c ToolReference) Default() ToolReference { return "tool_reference" } +func (c ToolRemoval) Default() ToolRemoval { return "tool_removal" } func (c ToolResult) Default() ToolResult { return "tool_result" } func (c ToolSearchToolBm25) Default() ToolSearchToolBm25 { return "tool_search_tool_bm25" } func (c ToolSearchToolRegex) Default() ToolSearchToolRegex { return "tool_search_tool_regex" } @@ -341,15 +568,36 @@ func (c ToolSearchToolResultError) Default() ToolSearchToolResultError { func (c ToolSearchToolSearchResult) Default() ToolSearchToolSearchResult { return "tool_search_tool_search_result" } -func (c ToolUse) Default() ToolUse { return "tool_use" } -func (c ToolUses) Default() ToolUses { return "tool_uses" } -func (c Unrestricted) Default() Unrestricted { return "unrestricted" } -func (c URL) Default() URL { return "url" } +func (c ToolUse) Default() ToolUse { return "tool_use" } +func (c ToolUses) Default() ToolUses { return "tool_uses" } +func (c ToolsChanged) Default() ToolsChanged { return "tools_changed" } +func (c Tunnel) Default() Tunnel { return "tunnel" } +func (c TunnelCertificate) Default() TunnelCertificate { return "tunnel_certificate" } +func (c TunnelToken) Default() TunnelToken { return "tunnel_token" } +func (c Unattached) Default() Unattached { return "unattached" } +func (c Unavailable) Default() Unavailable { return "unavailable" } +func (c Unrestricted) Default() Unrestricted { return "unrestricted" } +func (c URL) Default() URL { return "url" } +func (c User) Default() User { return "user" } +func (c UserActor) Default() UserActor { return "user_actor" } +func (c UserDeleted) Default() UserDeleted { return "user_deleted" } +func (c VaultCredentialArchived) Default() VaultCredentialArchived { + return "vault_credential.archived" +} +func (c VaultCredentialCreated) Default() VaultCredentialCreated { return "vault_credential.created" } +func (c VaultCredentialDeleted) Default() VaultCredentialDeleted { return "vault_credential.deleted" } +func (c VaultCredentialRefreshFailed) Default() VaultCredentialRefreshFailed { + return "vault_credential.refresh_failed" +} +func (c VaultArchived) Default() VaultArchived { return "vault.archived" } +func (c VaultCreated) Default() VaultCreated { return "vault.created" } +func (c VaultDeleted) Default() VaultDeleted { return "vault.deleted" } func (c View) Default() View { return "view" } func (c WebFetch) Default() WebFetch { return "web_fetch" } func (c WebFetch20250910) Default() WebFetch20250910 { return "web_fetch_20250910" } func (c WebFetch20260209) Default() WebFetch20260209 { return "web_fetch_20260209" } func (c WebFetch20260309) Default() WebFetch20260309 { return "web_fetch_20260309" } +func (c WebFetch20260318) Default() WebFetch20260318 { return "web_fetch_20260318" } func (c WebFetchResult) Default() WebFetchResult { return "web_fetch_result" } func (c WebFetchToolResult) Default() WebFetchToolResult { return "web_fetch_tool_result" } func (c WebFetchToolResultError) Default() WebFetchToolResultError { @@ -358,6 +606,7 @@ func (c WebFetchToolResultError) Default() WebFetchToolResultError { func (c WebSearch) Default() WebSearch { return "web_search" } func (c WebSearch20250305) Default() WebSearch20250305 { return "web_search_20250305" } func (c WebSearch20260209) Default() WebSearch20260209 { return "web_search_20260209" } +func (c WebSearch20260318) Default() WebSearch20260318 { return "web_search_20260318" } func (c WebSearchResult) Default() WebSearchResult { return "web_search_result" } func (c WebSearchResultLocation) Default() WebSearchResultLocation { return "web_search_result_location" @@ -366,119 +615,215 @@ func (c WebSearchToolResult) Default() WebSearchToolResult { return "web_search_ func (c WebSearchToolResultError) Default() WebSearchToolResultError { return "web_search_tool_result_error" } +func (c Work) Default() Work { return "work" } +func (c WorkHeartbeat) Default() WorkHeartbeat { return "work_heartbeat" } +func (c WorkQueueStats) Default() WorkQueueStats { return "work_queue_stats" } +func (c Workspace) Default() Workspace { return "workspace" } +func (c WorkspaceMember) Default() WorkspaceMember { return "workspace_member" } +func (c WorkspaceMemberDeleted) Default() WorkspaceMemberDeleted { return "workspace_member_deleted" } +func (c WorkspaceRateLimit) Default() WorkspaceRateLimit { return "workspace_rate_limit" } +func (c Write) Default() Write { return "write" } -func (c Adaptive) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Advisor) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Advisor20260301) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c AdvisorMessage) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c AdvisorRedactedResult) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c AdvisorResult) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c AdvisorToolResult) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c AdvisorToolResultError) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c All) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Any) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c APIError) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ApplicationPDF) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Approximate) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Assistant) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c AuthenticationError) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Auto) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Base64) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Bash) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Bash20241022) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Bash20250124) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c BashCodeExecutionOutput) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c BashCodeExecutionResult) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c BashCodeExecutionToolResult) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c BashCodeExecutionToolResultError) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c BillingError) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Canceled) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c CharLocation) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c CitationsDelta) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ClearThinking20251015) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ClearToolUses20250919) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Cloud) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c CodeExecution) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c CodeExecution20250522) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c CodeExecution20250825) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c CodeExecution20260120) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c CodeExecutionOutput) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c CodeExecutionResult) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c CodeExecutionToolResult) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c CodeExecutionToolResultError) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Compact20260112) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Compaction) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c CompactionDelta) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Completion) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Computer) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Computer20241022) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Computer20250124) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Computer20251124) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ContainerUpload) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Content) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ContentBlockDelta) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ContentBlockLocation) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ContentBlockStart) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ContentBlockStop) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Create) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Delete) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Direct) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Disabled) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Document) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Enabled) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c EncryptedCodeExecutionResult) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Environment) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c EnvironmentDeleted) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Ephemeral) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Error) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Errored) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Expired) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c File) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Image) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c InputJSONDelta) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c InputTokens) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Insert) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c InvalidRequestError) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c JSONSchema) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Limited) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c MCPToolResult) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c MCPToolUse) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c MCPToolset) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Memory) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Memory20250818) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Message) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c MessageBatch) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c MessageBatchDeleted) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c MessageDelta) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c MessageStart) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c MessageStop) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Model) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c None) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c NotFoundError) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Object) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c OverloadedError) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c PageLocation) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c PermissionError) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c RateLimitError) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c RedactedThinking) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Refusal) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Rename) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c SearchResult) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c SearchResultLocation) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c ServerToolUse) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Session) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c SignatureDelta) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c StrReplace) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c StrReplaceBasedEditTool) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c StrReplaceEditor) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Succeeded) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c Text) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c TextDelta) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c TextEditor20241022) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c TextEditor20250124) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c TextEditor20250429) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c TextEditor20250728) MarshalJSON() ([]byte, error) { return marshalString(c) } -func (c TextEditorCodeExecutionCreateResult) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Adaptive) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Advisor) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Advisor20260301) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c AdvisorMessage) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c AdvisorRedactedResult) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c AdvisorResult) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c AdvisorToolResult) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c AdvisorToolResultError) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c AgentArchived) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c AgentCreated) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c AgentDeleted) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c AgentUpdated) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c All) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Any) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c APIError) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c APIKey) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ApplicationPDF) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Approximate) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Assistant) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Attached) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c AuthenticationError) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Auto) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c AWS) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Azure) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Base64) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Bash) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Bash20241022) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Bash20250124) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c BashCodeExecutionOutput) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c BashCodeExecutionResult) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c BashCodeExecutionToolResult) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c BashCodeExecutionToolResultError) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c BillingError) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c BrowserState) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c BrowserToolset20260801) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Canceled) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c CharLocation) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c CitationsDelta) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ClearThinking20251015) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ClearToolUses20250919) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Cloud) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c CodeExecution) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c CodeExecution20250522) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c CodeExecution20250825) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c CodeExecution20260120) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c CodeExecution20260521) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c CodeExecutionOutput) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c CodeExecutionResult) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c CodeExecutionToolResult) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c CodeExecutionToolResultError) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Compact20260112) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Compaction) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c CompactionDelta) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Completion) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Computer) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Computer20241022) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Computer20250124) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Computer20251124) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ComputerToolset20260801) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ContainerUpload) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Content) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ContentBlockDelta) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ContentBlockLocation) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ContentBlockStart) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ContentBlockStop) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Create) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Default) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Delete) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c DeploymentRunFailed) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c DeploymentRunStarted) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c DeploymentRunSucceeded) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c DeploymentArchived) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c DeploymentCreated) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c DeploymentDeleted) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c DeploymentPaused) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c DeploymentUnpaused) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c DeploymentUpdated) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Direct) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Disabled) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Discovery) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Document) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c DownloadCompleted) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c DownloadFailed) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c DownloadStarted) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Edit) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Enabled) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c EncryptedCodeExecutionResult) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Environment) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c EnvironmentArchived) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c EnvironmentCreated) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c EnvironmentDeleted) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c EnvironmentUpdated) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Ephemeral) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Error) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Errored) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Event) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Expired) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ExplicitURL) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ExternalKey) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ExternalKeyDeleted) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ExternalKeyValidation) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Fallback) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c FallbackMessage) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c FederationIssuer) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c FederationRule) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c FederationRuleWorkspace) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c FederationRuleWorkspaceDeleted) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c File) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c GCP) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Glob) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Grep) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Image) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Inline) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c InputJSONDelta) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c InputTokens) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Insert) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c InvalidRequestError) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Invite) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c InviteDeleted) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c JSONSchema) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Limited) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c MCPToolReference) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c MCPToolResult) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c MCPToolUse) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c MCPToolset) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c MCPToolsetReference) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Memory) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Memory20250818) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c MemoryStoreArchived) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c MemoryStoreCreated) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c MemoryStoreDeleted) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Message) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c MessageBatch) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c MessageBatchDeleted) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c MessageDelta) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c MessageStart) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c MessageStop) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c MessagesChanged) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Model) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ModelChanged) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c None) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c NotApplied) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c NotFoundError) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Object) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Organization) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c OverloadedError) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c PageLocation) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c PermissionError) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c PreviousMessageNotFound) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c RateLimit) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c RateLimitError) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Read) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c RedactedThinking) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Redeemed) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Refusal) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Rename) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c SearchResult) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c SearchResultLocation) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c SelfHosted) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ServerToolUse) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ServiceAccount) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ServiceAccountActor) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ServiceAccountWorkspaceMember) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ServiceAccountWorkspaceMemberDeleted) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Session) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c SessionArchived) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c SessionBudgetReached) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c SessionCreated) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c SessionDeleted) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c SessionIdled) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c SessionOutcomeEvaluationEnded) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c SessionPending) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c SessionRequiresAction) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c SessionRunning) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c SessionStatusIdled) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c SessionStatusRescheduled) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c SessionStatusRunStarted) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c SessionStatusTerminated) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c SessionThreadCreated) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c SessionThreadIdled) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c SessionThreadTerminated) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c SessionUpdated) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c SignatureDelta) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Skill) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c SkillDeleted) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c SkillVersion) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c SkillVersionDeleted) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c StrReplace) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c StrReplaceBasedEditTool) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c StrReplaceEditor) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Succeeded) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c SystemChanged) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c TabOpened) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Text) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c TextDelta) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c TextEditor20241022) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c TextEditor20250124) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c TextEditor20250429) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c TextEditor20250728) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c TextEditorCodeExecutionCreateResult) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c TextEditorCodeExecutionStrReplaceResult) MarshalJSON() ([]byte, error) { return marshalString(c) } @@ -494,7 +839,9 @@ func (c ThinkingTurns) MarshalJSON() ([]byte, error) { retur func (c TimeoutError) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c Tokens) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c Tool) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ToolAddition) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c ToolReference) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ToolRemoval) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c ToolResult) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c ToolSearchToolBm25) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c ToolSearchToolRegex) MarshalJSON() ([]byte, error) { return marshalString(c) } @@ -503,23 +850,49 @@ func (c ToolSearchToolResultError) MarshalJSON() ([]byte, error) { retur func (c ToolSearchToolSearchResult) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c ToolUse) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c ToolUses) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c ToolsChanged) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Tunnel) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c TunnelCertificate) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c TunnelToken) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Unattached) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Unavailable) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c Unrestricted) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c URL) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c User) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c UserActor) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c UserDeleted) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c VaultCredentialArchived) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c VaultCredentialCreated) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c VaultCredentialDeleted) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c VaultCredentialRefreshFailed) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c VaultArchived) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c VaultCreated) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c VaultDeleted) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c View) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c WebFetch) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c WebFetch20250910) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c WebFetch20260209) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c WebFetch20260309) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c WebFetch20260318) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c WebFetchResult) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c WebFetchToolResult) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c WebFetchToolResultError) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c WebSearch) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c WebSearch20250305) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c WebSearch20260209) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c WebSearch20260318) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c WebSearchResult) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c WebSearchResultLocation) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c WebSearchToolResult) MarshalJSON() ([]byte, error) { return marshalString(c) } func (c WebSearchToolResultError) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Work) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c WorkHeartbeat) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c WorkQueueStats) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Workspace) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c WorkspaceMember) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c WorkspaceMemberDeleted) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c WorkspaceRateLimit) MarshalJSON() ([]byte, error) { return marshalString(c) } +func (c Write) MarshalJSON() ([]byte, error) { return marshalString(c) } type constant[T any] interface { Constant[T] diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/skill.go b/vendor/github.com/anthropics/anthropic-sdk-go/skill.go new file mode 100644 index 000000000..8163d6246 --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/skill.go @@ -0,0 +1,277 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +package anthropic + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "mime/multipart" + "net/http" + "net/url" + "slices" + "time" + + "github.com/anthropics/anthropic-sdk-go/internal/apiform" + "github.com/anthropics/anthropic-sdk-go/internal/apijson" + "github.com/anthropics/anthropic-sdk-go/internal/apiquery" + "github.com/anthropics/anthropic-sdk-go/internal/requestconfig" + "github.com/anthropics/anthropic-sdk-go/option" + "github.com/anthropics/anthropic-sdk-go/packages/pagination" + "github.com/anthropics/anthropic-sdk-go/packages/param" + "github.com/anthropics/anthropic-sdk-go/packages/respjson" + "github.com/anthropics/anthropic-sdk-go/shared/constant" +) + +// SkillService contains methods and other services that help with interacting with +// the anthropic API. +// +// Note, unlike clients, this service does not read variables from the environment +// automatically. You should not instantiate this service directly, and instead use +// the [NewSkillService] method instead. +type SkillService struct { + Options []option.RequestOption + Versions SkillVersionService +} + +// NewSkillService generates a new service that applies the given options to each +// request. These options are applied after the parent client's options (if there +// is one), and before any request-specific options. +func NewSkillService(opts ...option.RequestOption) (r SkillService) { + r = SkillService{} + r.Options = opts + r.Versions = NewSkillVersionService(opts...) + return +} + +// Create Skill +func (r *SkillService) New(ctx context.Context, body SkillNewParams, opts ...option.RequestOption) (res *Skill, err error) { + opts = slices.Concat(r.Options, opts) + path := "v1/skills" + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...) + return res, err +} + +// Get Skill +func (r *SkillService) Get(ctx context.Context, skillID string, opts ...option.RequestOption) (res *Skill, err error) { + opts = slices.Concat(r.Options, opts) + if skillID == "" { + err = errors.New("missing required skill_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/skills/%s", skillID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...) + return res, err +} + +// List Skills +func (r *SkillService) List(ctx context.Context, query SkillListParams, opts ...option.RequestOption) (res *pagination.PageCursor[Skill], err error) { + var raw *http.Response + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithResponseInto(&raw)}, opts...) + path := "v1/skills" + cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, query, &res, opts...) + if err != nil { + return nil, err + } + err = cfg.Execute() + if err != nil { + return nil, err + } + res.SetPageConfig(cfg, raw) + return res, nil +} + +// List Skills +func (r *SkillService) ListAutoPaging(ctx context.Context, query SkillListParams, opts ...option.RequestOption) *pagination.PageCursorAutoPager[Skill] { + return pagination.NewPageCursorAutoPager(r.List(ctx, query, opts...)) +} + +// Delete Skill +func (r *SkillService) Delete(ctx context.Context, skillID string, opts ...option.RequestOption) (res *DeletedSkill, err error) { + opts = slices.Concat(r.Options, opts) + if skillID == "" { + err = errors.New("missing required skill_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/skills/%s", skillID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodDelete, path, nil, &res, opts...) + return res, err +} + +type DeletedSkill struct { + // Unique identifier for the skill. + // + // The format and length of IDs may change over time. + ID string `json:"id" api:"required"` + // Deleted object type. + // + // For Skills, this is always `"skill_deleted"`. + Type constant.SkillDeleted `json:"type" default:"skill_deleted"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r DeletedSkill) RawJSON() string { return r.JSON.raw } +func (r *DeletedSkill) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type Skill struct { + // Unique identifier for the skill. + // + // The format and length of IDs may change over time. + ID string `json:"id" api:"required"` + // ISO 8601 timestamp of when the skill was created. + CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"` + // Human-readable, single-line label for the Skill. Maximum 255 characters. Always + // set: derived from the SKILL.md frontmatter `name` when omitted at creation. Not + // unique. + DisplayName string `json:"display_name" api:"required"` + // ID of the newest Skill Version — what `latest` references resolve to. Always + // set: a Skill holds at least one version. + LatestVersionID string `json:"latest_version_id" api:"required"` + // Where the Skill comes from. + // + // Possible values: + // + // - `"custom"`: authored by the platform user; private to their workspace + // - `"anthropic"`: published by Anthropic; shared and read-only + // - `"anthropic_example"`: Anthropic-published sample Skill + // - `"plugin"`: resolved from an installed plugin + Source SkillSource `json:"source" api:"required"` + // Object type. + // + // For Skills, this is always `"skill"`. + Type constant.Skill `json:"type" default:"skill"` + // ISO 8601 timestamp of when the skill was last updated. + UpdatedAt time.Time `json:"updated_at" api:"required" format:"date-time"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + CreatedAt respjson.Field + DisplayName respjson.Field + LatestVersionID respjson.Field + Source respjson.Field + Type respjson.Field + UpdatedAt respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r Skill) RawJSON() string { return r.JSON.raw } +func (r *Skill) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type SkillSource struct { + // Where the Skill comes from. + // + // Possible values: + // + // - `"custom"`: authored by the platform user; private to their workspace + // - `"anthropic"`: published by Anthropic; shared and read-only + // - `"anthropic_example"`: Anthropic-published sample Skill + // - `"plugin"`: resolved from an installed plugin + // + // Any of "custom", "anthropic", "anthropic_example", "plugin". + Type SkillSourceType `json:"type" api:"required"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r SkillSource) RawJSON() string { return r.JSON.raw } +func (r *SkillSource) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +// Where the Skill comes from. +// +// Possible values: +// +// - `"custom"`: authored by the platform user; private to their workspace +// - `"anthropic"`: published by Anthropic; shared and read-only +// - `"anthropic_example"`: Anthropic-published sample Skill +// - `"plugin"`: resolved from an installed plugin +type SkillSourceType string + +const ( + SkillSourceTypeCustom SkillSourceType = "custom" + SkillSourceTypeAnthropic SkillSourceType = "anthropic" + SkillSourceTypeAnthropicExample SkillSourceType = "anthropic_example" + SkillSourceTypePlugin SkillSourceType = "plugin" +) + +type SkillNewParams struct { + // Files to upload for the skill. + // + // All files must be in the same top-level directory and must include a SKILL.md + // file at the root of that directory. + Files []io.Reader `json:"files,omitzero" api:"required" format:"binary"` + // Human-readable, single-line label for the Skill. Maximum 255 characters. Always + // set: derived from the SKILL.md frontmatter `name` when omitted at creation. Not + // unique. + DisplayName param.Opt[string] `json:"display_name,omitzero"` + paramObj +} + +func (r SkillNewParams) MarshalMultipart() (data []byte, contentType string, err error) { + buf := bytes.NewBuffer(nil) + writer := multipart.NewWriter(buf) + err = apiform.MarshalRoot(r, writer) + if err == nil { + err = apiform.WriteExtras(writer, r.ExtraFields()) + } + if err != nil { + writer.Close() + return nil, "", err + } + err = writer.Close() + if err != nil { + return nil, "", err + } + return buf.Bytes(), writer.FormDataContentType(), nil +} + +type SkillListParams struct { + // Pagination token for fetching a specific page of results. + // + // Pass the value from a previous response's `next_page` field to get the next page + // of results. + Page param.Opt[string] `query:"page,omitzero" json:"-"` + // Filter skills by source. + // + // If provided, only skills from the specified source will be returned: + // + // - `"custom"`: only return user-created skills + // - `"anthropic"`: only return Anthropic-created skills + Source param.Opt[string] `query:"source,omitzero" json:"-"` + // Number of results to return per page. + // + // Ranges from `1` to `1000`. Defaults to `20`. + Limit param.Opt[int64] `query:"limit,omitzero" json:"-"` + paramObj +} + +// URLQuery serializes [SkillListParams]'s query parameters as `url.Values`. +func (r SkillListParams) URLQuery() (v url.Values, err error) { + return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ + ArrayFormat: apiquery.ArrayQueryFormatBrackets, + NestedFormat: apiquery.NestedQueryFormatBrackets, + }) +} diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/skillversion.go b/vendor/github.com/anthropics/anthropic-sdk-go/skillversion.go new file mode 100644 index 000000000..765fe8cba --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/skillversion.go @@ -0,0 +1,242 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +package anthropic + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "mime/multipart" + "net/http" + "net/url" + "slices" + "time" + + "github.com/anthropics/anthropic-sdk-go/internal/apiform" + "github.com/anthropics/anthropic-sdk-go/internal/apijson" + "github.com/anthropics/anthropic-sdk-go/internal/apiquery" + "github.com/anthropics/anthropic-sdk-go/internal/requestconfig" + "github.com/anthropics/anthropic-sdk-go/option" + "github.com/anthropics/anthropic-sdk-go/packages/pagination" + "github.com/anthropics/anthropic-sdk-go/packages/param" + "github.com/anthropics/anthropic-sdk-go/packages/respjson" + "github.com/anthropics/anthropic-sdk-go/shared/constant" +) + +// SkillVersionService contains methods and other services that help with +// interacting with the anthropic API. +// +// Note, unlike clients, this service does not read variables from the environment +// automatically. You should not instantiate this service directly, and instead use +// the [NewSkillVersionService] method instead. +type SkillVersionService struct { + Options []option.RequestOption +} + +// NewSkillVersionService generates a new service that applies the given options to +// each request. These options are applied after the parent client's options (if +// there is one), and before any request-specific options. +func NewSkillVersionService(opts ...option.RequestOption) (r SkillVersionService) { + r = SkillVersionService{} + r.Options = opts + return +} + +// Create Skill Version +func (r *SkillVersionService) New(ctx context.Context, skillID string, body SkillVersionNewParams, opts ...option.RequestOption) (res *SkillVersion, err error) { + opts = slices.Concat(r.Options, opts) + if skillID == "" { + err = errors.New("missing required skill_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/skills/%s/versions", skillID) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...) + return res, err +} + +// Get Skill Version +func (r *SkillVersionService) Get(ctx context.Context, version string, query SkillVersionGetParams, opts ...option.RequestOption) (res *SkillVersion, err error) { + opts = slices.Concat(r.Options, opts) + if query.SkillID == "" { + err = errors.New("missing required skill_id parameter") + return nil, err + } + if version == "" { + err = errors.New("missing required version parameter") + return nil, err + } + path := fmt.Sprintf("v1/skills/%s/versions/%s", query.SkillID, version) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...) + return res, err +} + +// List Skill Versions +func (r *SkillVersionService) List(ctx context.Context, skillID string, query SkillVersionListParams, opts ...option.RequestOption) (res *pagination.PageCursor[SkillVersion], err error) { + var raw *http.Response + opts = slices.Concat(r.Options, opts) + opts = append([]option.RequestOption{option.WithResponseInto(&raw)}, opts...) + if skillID == "" { + err = errors.New("missing required skill_id parameter") + return nil, err + } + path := fmt.Sprintf("v1/skills/%s/versions", skillID) + cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, query, &res, opts...) + if err != nil { + return nil, err + } + err = cfg.Execute() + if err != nil { + return nil, err + } + res.SetPageConfig(cfg, raw) + return res, nil +} + +// List Skill Versions +func (r *SkillVersionService) ListAutoPaging(ctx context.Context, skillID string, query SkillVersionListParams, opts ...option.RequestOption) *pagination.PageCursorAutoPager[SkillVersion] { + return pagination.NewPageCursorAutoPager(r.List(ctx, skillID, query, opts...)) +} + +// Delete Skill Version +func (r *SkillVersionService) Delete(ctx context.Context, version string, body SkillVersionDeleteParams, opts ...option.RequestOption) (res *DeletedSkillVersion, err error) { + opts = slices.Concat(r.Options, opts) + if body.SkillID == "" { + err = errors.New("missing required skill_id parameter") + return nil, err + } + if version == "" { + err = errors.New("missing required version parameter") + return nil, err + } + path := fmt.Sprintf("v1/skills/%s/versions/%s", body.SkillID, version) + err = requestconfig.ExecuteNewRequest(ctx, http.MethodDelete, path, nil, &res, opts...) + return res, err +} + +type DeletedSkillVersion struct { + // Unique identifier for this Skill Version. The id addresses the version in paths + // and pins it in references. + ID string `json:"id" api:"required"` + // Deleted object type. + // + // For Skill Versions, this is always `"skill_version_deleted"`. + Type constant.SkillVersionDeleted `json:"type" default:"skill_version_deleted"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r DeletedSkillVersion) RawJSON() string { return r.JSON.raw } +func (r *DeletedSkillVersion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type SkillVersion struct { + // Unique identifier for this Skill Version. The id addresses the version in paths + // and pins it in references. + ID string `json:"id" api:"required"` + // ISO 8601 timestamp of when the skill was created. + CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"` + // Description of the skill version. + // + // This is extracted from the SKILL.md file in the skill upload. + Description string `json:"description" api:"required"` + // The Skill's immutable kebab-case slug, set at creation from the first upload's + // SKILL.md frontmatter `name` (or its enclosing directory). Every later upload + // must resolve to the same value. Also the top-level directory of the Skill's + // mounted files and the base name of a downloaded archive. + Name string `json:"name" api:"required"` + // Unique identifier for the skill. + // + // The format and length of IDs may change over time. + SkillID string `json:"skill_id" api:"required"` + // Object type. + // + // For Skill Versions, this is always `"skill_version"`. + Type constant.SkillVersion `json:"type" default:"skill_version"` + // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. + JSON struct { + ID respjson.Field + CreatedAt respjson.Field + Description respjson.Field + Name respjson.Field + SkillID respjson.Field + Type respjson.Field + ExtraFields map[string]respjson.Field + raw string + } `json:"-"` +} + +// Returns the unmodified JSON received from the API +func (r SkillVersion) RawJSON() string { return r.JSON.raw } +func (r *SkillVersion) UnmarshalJSON(data []byte) error { + return apijson.UnmarshalRoot(data, r) +} + +type SkillVersionNewParams struct { + // Files to upload for the skill. + // + // All files must be in the same top-level directory and must include a SKILL.md + // file at the root of that directory. + Files []io.Reader `json:"files,omitzero" api:"required" format:"binary"` + paramObj +} + +func (r SkillVersionNewParams) MarshalMultipart() (data []byte, contentType string, err error) { + buf := bytes.NewBuffer(nil) + writer := multipart.NewWriter(buf) + err = apiform.MarshalRoot(r, writer) + if err == nil { + err = apiform.WriteExtras(writer, r.ExtraFields()) + } + if err != nil { + writer.Close() + return nil, "", err + } + err = writer.Close() + if err != nil { + return nil, "", err + } + return buf.Bytes(), writer.FormDataContentType(), nil +} + +type SkillVersionGetParams struct { + // Unique identifier for the skill. + // + // The format and length of IDs may change over time. + SkillID string `path:"skill_id" api:"required" json:"-"` + paramObj +} + +type SkillVersionListParams struct { + // Number of results to return per page. + // + // Ranges from `1` to `1000`. Defaults to `20`. + Limit param.Opt[int64] `query:"limit,omitzero" json:"-"` + // Optionally set to the `next_page` token from the previous response. + Page param.Opt[string] `query:"page,omitzero" json:"-"` + paramObj +} + +// URLQuery serializes [SkillVersionListParams]'s query parameters as `url.Values`. +func (r SkillVersionListParams) URLQuery() (v url.Values, err error) { + return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ + ArrayFormat: apiquery.ArrayQueryFormatBrackets, + NestedFormat: apiquery.NestedQueryFormatBrackets, + }) +} + +type SkillVersionDeleteParams struct { + // Unique identifier for the skill. + // + // The format and length of IDs may change over time. + SkillID string `path:"skill_id" api:"required" json:"-"` + paramObj +} diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/tools.md b/vendor/github.com/anthropics/anthropic-sdk-go/tools.md index 53b576992..753866781 100644 --- a/vendor/github.com/anthropics/anthropic-sdk-go/tools.md +++ b/vendor/github.com/anthropics/anthropic-sdk-go/tools.md @@ -102,9 +102,9 @@ rawTool, err := toolrunner.NewBetaToolFromBytes( The `BetaToolRunner` automatically handles the conversation loop between Claude and your tools. On each iteration, it: 1. Sends the current messages to Claude -2. If Claude responds with tool calls, executes them in parallel -3. Adds the tool results to the conversation -4. Repeats until Claude produces a final response (no tool calls) +2. If the message's `StopReason` is `tool_use`, executes the requested tools in parallel and adds the results to the conversation +3. If it is `pause_turn` or `compaction`, sends the turn back unchanged so the server can resume it +4. Repeats until Claude stops for any other reason (e.g. `end_turn`, `max_tokens`), returning that final message without running tools ### Basic Usage @@ -113,7 +113,7 @@ tools := []anthropic.BetaTool{weatherTool} runner := client.Beta.Messages.NewToolRunner(tools, anthropic.BetaToolRunnerParams{ BetaMessageNewParams: anthropic.BetaMessageNewParams{ - Model: anthropic.ModelClaudeSonnet4_20250514, + Model: anthropic.ModelClaudeSonnet4_5_20250929, MaxTokens: 1024, Messages: []anthropic.BetaMessageParam{ anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("What's the weather in Tokyo?")), @@ -169,7 +169,7 @@ Use `BetaToolRunnerStreaming` via `NewToolRunnerStreaming()` for streaming respo ```go runner := client.Beta.Messages.NewToolRunnerStreaming(tools, anthropic.BetaToolRunnerParams{ BetaMessageNewParams: anthropic.BetaMessageNewParams{ - Model: anthropic.ModelClaudeSonnet4_20250514, + Model: anthropic.ModelClaudeSonnet4_5_20250929, MaxTokens: 1024, Messages: []anthropic.BetaMessageParam{ anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("What's the weather in Tokyo?")), @@ -207,7 +207,7 @@ for !runner.IsCompleted() { ### Max Iterations -Limit the number of API calls to prevent runaway loops. When set to 0 (the default), there is no limit and the runner continues until the model stops using tools: +Limit the number of API calls to prevent runaway loops. When set to 0 (the default), there is no limit and the runner continues until the model's stop reason ends the loop: ```go runner := client.Beta.Messages.NewToolRunner(tools, anthropic.BetaToolRunnerParams{ @@ -284,9 +284,19 @@ When Claude requests multiple tool calls in a single message, they are executed - Proper context cancellation handling - Results returned in the correct order +## Managed-agents sessions + +The same `anthropic.BetaTool` shape works for managed-agents sessions. Two helpers cover the self-hosted side: + +- `client.Beta.Sessions.Events.NewToolRunner(ctx, sessionID, anthropic.SessionToolRunnerOptions{...})` — the sessions-side counterpart to `client.Beta.Messages.NewToolRunner`. The session id is a positional argument (matching `list`/`send`/`stream` on the events resource); the options struct carries the tool registry and tuning knobs. It attaches to a session's event stream, dispatches the registered tools on both `agent.tool_use` (builtin tools, answered with `user.tool_result`) and `agent.custom_tool_use` (user-defined function tools, answered with `user.custom_tool_result`), and stops after the session is idle past `MaxIdle`. It does *only* that — no work claiming, lease heartbeating, or skill download. +- `environments.NewEnvironmentWorker(client, environments.EnvironmentWorkerOptions{...})` (in `github.com/anthropics/anthropic-sdk-go/lib/environments`) — the full self-hosted runner: it composes `environments.WorkPoller` (claim work) with a per-session `SessionToolRunner`, sets up the workdir + downloads the session agent's skills, heartbeats the work-item lease in parallel, force-stops the work on exit, and loops. A single `EnvironmentKey` authorizes everything — both the work-poll calls and the per-session calls. `worker.Run(ctx)` drives the poll loop (requires `EnvironmentID` + `EnvironmentKey`); `worker.HandleItem(ctx, environments.HandleItemOptions{...})` runs that same per-item flow (skills + run + heartbeat + force-stop) once for a work item you have already claimed yourself. Each `HandleItemOptions` field — `WorkID` / `EnvironmentID` / `SessionID` / `EnvironmentKey` — falls back to `ANTHROPIC_WORK_ID` / `ANTHROPIC_ENVIRONMENT_ID` / `ANTHROPIC_SESSION_ID` / `ANTHROPIC_ENVIRONMENT_KEY` when left empty (and `EnvironmentKey` also falls back to the worker's own `EnvironmentKey` option), so inside an `ant worker poll --on-work` hook (which exports all of them) it is just `worker.HandleItem(ctx, environments.HandleItemOptions{})`. If you are iterating `environments.WorkPoller` yourself, pass the claimed item through: `worker.HandleItem(ctx, environments.HandleItemOptions{WorkID: work.ID, EnvironmentID: work.EnvironmentID, SessionID: work.Data.ID, EnvironmentKey: environmentKey})`. + +The standard `agent_toolset_20260401` tools (`bash`, `read`, `write`, `edit`, `glob`, `grep`), the workdir/skills `AgentToolContext`, and the skill-download helper live in `github.com/anthropics/anthropic-sdk-go/tools/agenttoolset`; `agenttoolset.BetaAgentToolset20260401(env)` returns them as a plain `[]anthropic.BetaTool` you can filter or extend. The file tools confine to the workdir (symlink-aware) and are safe without a sandbox; `bash` is unrestricted and should run inside one. + ## Examples See the [examples](./examples) directory for complete working examples: - [examples/tool-runner](./examples/tool-runner) - Basic tool runner usage - [examples/tool-runner-streaming](./examples/tool-runner-streaming) - Streaming with tool runner +- [examples/managed-agents-self-hosted-sandbox-worker](./examples/managed-agents-self-hosted-sandbox-worker) - Self-hosted environment worker diff --git a/vendor/github.com/anthropics/anthropic-sdk-go/unmarshalcompat.go b/vendor/github.com/anthropics/anthropic-sdk-go/unmarshalcompat.go new file mode 100644 index 000000000..6b60b936e --- /dev/null +++ b/vendor/github.com/anthropics/anthropic-sdk-go/unmarshalcompat.go @@ -0,0 +1,40 @@ +package anthropic + +// To accept the API's `string | []T` form, register string promotion +// for beta content unions. The generator already covers the non-beta +// ones (message.go init). + +import ( + "reflect" + + "github.com/anthropics/anthropic-sdk-go/internal/apijson" + + "github.com/tidwall/gjson" +) + +func registerStringPromotion[SliceT ~[]E, E any](wrap func(string) E) { + apijson.RegisterCustomDecoder[SliceT](func(node gjson.Result, value reflect.Value, defaultDecoder func(gjson.Result, reflect.Value) error) error { + if node.Type == gjson.String { + arrayValue := reflect.MakeSlice(value.Type(), 1, 1) + arrayValue.Index(0).Set(reflect.ValueOf(wrap(node.String()))) + value.Set(arrayValue) + return nil + } + return defaultDecoder(node, value) + }) +} + +func init() { + registerStringPromotion[[]TextBlockParam](func(s string) TextBlockParam { + return TextBlockParam{Text: s} + }) + registerStringPromotion[[]BetaTextBlockParam](func(s string) BetaTextBlockParam { + return BetaTextBlockParam{Text: s} + }) + registerStringPromotion[[]BetaContentBlockParamUnion](func(s string) BetaContentBlockParamUnion { + return BetaContentBlockParamUnion{OfText: &BetaTextBlockParam{Text: s}} + }) + registerStringPromotion[[]BetaToolResultBlockParamContentUnion](func(s string) BetaToolResultBlockParamContentUnion { + return BetaToolResultBlockParamContentUnion{OfText: &BetaTextBlockParam{Text: s}} + }) +} diff --git a/vendor/github.com/invopop/jsonschema/.gitignore b/vendor/github.com/invopop/jsonschema/.gitignore new file mode 100644 index 000000000..8ef0e14fc --- /dev/null +++ b/vendor/github.com/invopop/jsonschema/.gitignore @@ -0,0 +1,2 @@ +vendor/ +.idea/ diff --git a/vendor/github.com/invopop/jsonschema/.golangci.yml b/vendor/github.com/invopop/jsonschema/.golangci.yml new file mode 100644 index 000000000..bd9586bc2 --- /dev/null +++ b/vendor/github.com/invopop/jsonschema/.golangci.yml @@ -0,0 +1,80 @@ +version: "2" +run: + tests: true +linters: + enable: + - dupl + - goconst + - gocritic + - gocyclo + - nakedret + - revive + - unconvert + - unparam + settings: + dupl: + threshold: 100 + goconst: + min-len: 8 + min-occurrences: 3 + gocritic: + disabled-checks: + - ifElseChain + gocyclo: + min-complexity: 20 + govet: + enable: + - shadow + exclusions: + generated: lax + rules: + - path: (.+)\.go$ + text: '^(G104|G204):' + - path: (.+)\.go$ + text: Error return value of .(.*\.Help|.*\.MarkFlagRequired|(os\.)?std(out|err)\..*|.*Close|.*Flush|os\.Remove(All)?|.*Print(f|ln|)|os\.(Un)?Setenv). is not checked + - path: (.+)\.go$ + text: 'internal error: no range for' + - path: (.+)\.go$ + text: exported method `.*\.(MarshalJSON|UnmarshalJSON|URN|Payload|GoString|Close|Provides|Requires|ExcludeFromHash|MarshalText|UnmarshalText|Description|Check|Poll|Severity)` should have comment or be unexported + - path: (.+)\.go$ + text: composite literal uses unkeyed fields + - path: (.+)\.go$ + text: declaration of "err" shadows declaration + - path: (.+)\.go$ + text: by other packages, and that stutters + - path: (.+)\.go$ + text: Potential file inclusion via variable + - path: (.+)\.go$ + text: at least one file in a package should have a package comment + - path: (.+)\.go$ + text: bad syntax for struct tag pair + paths: + - cmd/protopkg/main.go + - resources + - old + - third_party$ + - builtin$ + - examples$ +issues: + max-issues-per-linter: 0 + max-same-issues: 50 +formatters: + enable: + - gofmt + - goimports + settings: + gofmt: + rewrite-rules: + - pattern: interface{} + replacement: any + - pattern: a[b:len(a)] + replacement: a[b:] + exclusions: + generated: lax + paths: + - cmd/protopkg/main.go + - resources + - old + - third_party$ + - builtin$ + - examples$ diff --git a/vendor/github.com/invopop/jsonschema/COPYING b/vendor/github.com/invopop/jsonschema/COPYING new file mode 100644 index 000000000..2993ec085 --- /dev/null +++ b/vendor/github.com/invopop/jsonschema/COPYING @@ -0,0 +1,19 @@ +Copyright (C) 2014 Alec Thomas + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/invopop/jsonschema/README.md b/vendor/github.com/invopop/jsonschema/README.md new file mode 100644 index 000000000..bc29120ce --- /dev/null +++ b/vendor/github.com/invopop/jsonschema/README.md @@ -0,0 +1,374 @@ +# Go JSON Schema Reflection + +[![Lint](https://github.com/invopop/jsonschema/actions/workflows/lint.yaml/badge.svg)](https://github.com/invopop/jsonschema/actions/workflows/lint.yaml) +[![Test Go](https://github.com/invopop/jsonschema/actions/workflows/test.yaml/badge.svg)](https://github.com/invopop/jsonschema/actions/workflows/test.yaml) +[![Go Report Card](https://goreportcard.com/badge/github.com/invopop/jsonschema)](https://goreportcard.com/report/github.com/invopop/jsonschema) +[![GoDoc](https://godoc.org/github.com/invopop/jsonschema?status.svg)](https://godoc.org/github.com/invopop/jsonschema) +[![codecov](https://codecov.io/gh/invopop/jsonschema/graph/badge.svg?token=JMEB8W8GNZ)](https://codecov.io/gh/invopop/jsonschema) +![Latest Tag](https://img.shields.io/github/v/tag/invopop/jsonschema) + +This package can be used to generate [JSON Schemas](http://json-schema.org/latest/json-schema-validation.html) from Go types through reflection. + +- Supports arbitrarily complex types, including `interface{}`, maps, slices, etc. +- Supports json-schema features such as minLength, maxLength, pattern, format, etc. +- Supports simple string and numeric enums. +- Supports custom property fields via the `jsonschema_extras` struct tag. + +This repository is a fork of the original [jsonschema](https://github.com/alecthomas/jsonschema) by [@alecthomas](https://github.com/alecthomas). At [Invopop](https://invopop.com) we use jsonschema as a cornerstone in our [GOBL library](https://github.com/invopop/gobl), and wanted to be able to continue building and adding features without taking up Alec's time. There have been a few significant changes that probably mean this version is a not compatible with with Alec's: + +- The original was stuck on the draft-04 version of JSON Schema, we've now moved to the latest JSON Schema Draft 2020-12. +- Schema IDs are added automatically from the current Go package's URL in order to be unique, and can be disabled with the `Anonymous` option. +- Support for the `FullyQualifyTypeName` option has been removed. If you have conflicts, you should use multiple schema files with different IDs, set the `DoNotReference` option to true to hide definitions completely, or add your own naming strategy using the `Namer` property. +- Support for `yaml` tags and related options has been dropped for the sake of simplification. There were a [few inconsistencies](https://github.com/invopop/jsonschema/pull/21) around this that have now been fixed. + +## Versions + +This project is still under v0 scheme, as per Go convention, breaking changes are likely. Please pin go modules to version tags or branches, and reach out if you think something can be improved. + +Go version >= 1.24 is now required. We aim for one below the last supported Go version. + +## Example + +The following Go type: + +```go +type TestUser struct { + ID int `json:"id"` + Name string `json:"name" jsonschema:"title=the name,description=The name of a friend,example=joe,example=lucy,default=alex"` + Friends []int `json:"friends,omitempty" jsonschema_description:"The list of IDs, omitted when empty"` + Tags map[string]interface{} `json:"tags,omitempty" jsonschema_extras:"a=b,foo=bar,foo=bar1"` + BirthDate time.Time `json:"birth_date,omitzero" jsonschema:"oneof_required=date"` // omitzero requires Go 1.24+ + YearOfBirth string `json:"year_of_birth,omitempty" jsonschema:"oneof_required=year"` + Metadata interface{} `json:"metadata,omitempty" jsonschema:"oneof_type=string;array"` + FavColor string `json:"fav_color,omitempty" jsonschema:"enum=red,enum=green,enum=blue"` +} +``` + +Results in following JSON Schema: + +```go +jsonschema.Reflect(&TestUser{}) +``` + +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/invopop/jsonschema_test/test-user", + "$ref": "#/$defs/TestUser", + "$defs": { + "TestUser": { + "oneOf": [ + { + "required": ["birth_date"], + "title": "date" + }, + { + "required": ["year_of_birth"], + "title": "year" + } + ], + "properties": { + "id": { + "type": "integer" + }, + "name": { + "type": "string", + "title": "the name", + "description": "The name of a friend", + "default": "alex", + "examples": ["joe", "lucy"] + }, + "friends": { + "items": { + "type": "integer" + }, + "type": "array", + "description": "The list of IDs, omitted when empty" + }, + "tags": { + "type": "object", + "a": "b", + "foo": ["bar", "bar1"] + }, + "birth_date": { + "type": "string", + "format": "date-time" + }, + "year_of_birth": { + "type": "string" + }, + "metadata": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "array" + } + ] + }, + "fav_color": { + "type": "string", + "enum": ["red", "green", "blue"] + } + }, + "additionalProperties": false, + "type": "object", + "required": ["id", "name"] + } + } +} +``` + +## YAML + +Support for `yaml` tags has now been removed. If you feel very strongly about this, we've opened a discussion to hear your comments: https://github.com/invopop/jsonschema/discussions/28 + +The recommended approach if you need to deal with YAML data is to first convert to JSON. The [invopop/yaml](https://github.com/invopop/yaml) library will make this trivial. + +## Configurable behaviour + +The behaviour of the schema generator can be altered with parameters when a `jsonschema.Reflector` +instance is created. + +### ExpandedStruct + +If set to `true`, makes the top level struct not to reference itself in the definitions. But type passed should be a struct type. + +eg. + +```go +type GrandfatherType struct { + FamilyName string `json:"family_name" jsonschema:"required"` +} + +type SomeBaseType struct { + SomeBaseProperty int `json:"some_base_property"` + // The jsonschema required tag is nonsensical for private and ignored properties. + // Their presence here tests that the fields *will not* be required in the output + // schema, even if they are tagged required. + somePrivateBaseProperty string `json:"i_am_private" jsonschema:"required"` + SomeIgnoredBaseProperty string `json:"-" jsonschema:"required"` + SomeSchemaIgnoredProperty string `jsonschema:"-,required"` + SomeUntaggedBaseProperty bool `jsonschema:"required"` + someUnexportedUntaggedBaseProperty bool + Grandfather GrandfatherType `json:"grand"` +} +``` + +will output: + +```json +{ + "$schema": "http://json-schema.org/draft/2020-12/schema", + "required": ["some_base_property", "grand", "SomeUntaggedBaseProperty"], + "properties": { + "SomeUntaggedBaseProperty": { + "type": "boolean" + }, + "grand": { + "$schema": "http://json-schema.org/draft/2020-12/schema", + "$ref": "#/definitions/GrandfatherType" + }, + "some_base_property": { + "type": "integer" + } + }, + "type": "object", + "$defs": { + "GrandfatherType": { + "required": ["family_name"], + "properties": { + "family_name": { + "type": "string" + } + }, + "additionalProperties": false, + "type": "object" + } + } +} +``` + +### Using Go Comments + +Writing a good schema with descriptions inside tags can become cumbersome and tedious, especially if you already have some Go comments around your types and field definitions. If you'd like to take advantage of these existing comments, you can use the `AddGoComments(base, path string)` method that forms part of the reflector to parse your go files and automatically generate a dictionary of Go import paths, types, and fields, to individual comments. These will then be used automatically as description fields, and can be overridden with a manual definition if needed. + +Take a simplified example of a User struct which for the sake of simplicity we assume is defined inside this package: + +```go +package main + +// User is used as a base to provide tests for comments. +type User struct { + // Unique sequential identifier. + ID int `json:"id" jsonschema:"required"` + // Name of the user + Name string `json:"name"` +} +``` + +To get the comments provided into your JSON schema, use a regular `Reflector` and add the go code using an import module URL and path. Fully qualified go module paths cannot be determined reliably by the `go/parser` library, so we need to introduce this manually: + +```go +r := new(Reflector) +if err := r.AddGoComments("github.com/invopop/jsonschema", "./"); err != nil { + // deal with error +} +s := r.Reflect(&User{}) +// output +``` + +Expect the results to be similar to: + +```json +{ + "$schema": "http://json-schema.org/draft/2020-12/schema", + "$ref": "#/$defs/User", + "$defs": { + "User": { + "required": ["id"], + "properties": { + "id": { + "type": "integer", + "description": "Unique sequential identifier." + }, + "name": { + "type": "string", + "description": "Name of the user" + } + }, + "additionalProperties": false, + "type": "object", + "description": "User is used as a base to provide tests for comments." + } + } +} +``` + +### Custom Key Naming + +In some situations, the keys actually used to write files are different from Go structs'. + +This is often the case when writing a configuration file to YAML or JSON from a Go struct, or when returning a JSON response for a Web API: APIs typically use snake_case, while Go uses PascalCase. + +You can pass a `func(string) string` function to `Reflector`'s `KeyNamer` option to map Go field names to JSON key names and reflect the aforementioned transformations, without having to specify `json:"..."` on every struct field. + +For example, consider the following struct + +```go +type User struct { + GivenName string + PasswordSalted []byte `json:"salted_password"` +} +``` + +We can transform field names to snake_case in the generated JSON schema: + +```go +r := new(jsonschema.Reflector) +r.KeyNamer = strcase.SnakeCase // from package github.com/stoewer/go-strcase + +r.Reflect(&User{}) +``` + +Will yield + +```diff + { + "$schema": "http://json-schema.org/draft/2020-12/schema", + "$ref": "#/$defs/User", + "$defs": { + "User": { + "properties": { +- "GivenName": { ++ "given_name": { + "type": "string" + }, + "salted_password": { + "type": "string", + "contentEncoding": "base64" + } + }, + "additionalProperties": false, + "type": "object", +- "required": ["GivenName", "salted_password"] ++ "required": ["given_name", "salted_password"] + } + } + } +``` + +As you can see, if a field name has a `json:""` tag set, the `key` argument to `KeyNamer` will have the value of that tag. + +### Custom Type Definitions + +Sometimes it can be useful to have custom JSON Marshal and Unmarshal methods in your structs that automatically convert for example a string into an object. + +This library will recognize and attempt to call four different methods that help you adjust schemas to your specific needs: + +- `JSONSchema() *Schema` - will prevent auto-generation of the schema so that you can provide your own definition. +- `JSONSchemaExtend(schema *jsonschema.Schema)` - will be called _after_ the schema has been generated, allowing you to add or manipulate the fields easily. +- `JSONSchemaAlias() any` - is called when reflecting the type of object and allows for an alternative to be used instead. +- `JSONSchemaProperty(prop string) any` - will be called for every property inside a struct giving you the chance to provide an alternative object to convert into a schema. + +Note that all of these methods **must** be defined on a non-pointer object for them to be called. + +Take the following simplified example of a `CompactDate` that only includes the Year and Month: + +```go +type CompactDate struct { + Year int + Month int +} + +func (d *CompactDate) UnmarshalJSON(data []byte) error { + if len(data) != 9 { + return errors.New("invalid compact date length") + } + var err error + d.Year, err = strconv.Atoi(string(data[1:5])) + if err != nil { + return err + } + d.Month, err = strconv.Atoi(string(data[7:8])) + if err != nil { + return err + } + return nil +} + +func (d *CompactDate) MarshalJSON() ([]byte, error) { + buf := new(bytes.Buffer) + buf.WriteByte('"') + buf.WriteString(fmt.Sprintf("%d-%02d", d.Year, d.Month)) + buf.WriteByte('"') + return buf.Bytes(), nil +} + +func (CompactDate) JSONSchema() *Schema { + return &Schema{ + Type: "string", + Title: "Compact Date", + Description: "Short date that only includes year and month", + Pattern: "^[0-9]{4}-[0-1][0-9]$", + } +} +``` + +The resulting schema generated for this struct would look like: + +```json +{ + "$schema": "http://json-schema.org/draft/2020-12/schema", + "$ref": "#/$defs/CompactDate", + "$defs": { + "CompactDate": { + "pattern": "^[0-9]{4}-[0-1][0-9]$", + "type": "string", + "title": "Compact Date", + "description": "Short date that only includes year and month" + } + } +} +``` diff --git a/vendor/github.com/invopop/jsonschema/id.go b/vendor/github.com/invopop/jsonschema/id.go new file mode 100644 index 000000000..73fafb38d --- /dev/null +++ b/vendor/github.com/invopop/jsonschema/id.go @@ -0,0 +1,76 @@ +package jsonschema + +import ( + "errors" + "fmt" + "net/url" + "strings" +) + +// ID represents a Schema ID type which should always be a URI. +// See draft-bhutton-json-schema-00 section 8.2.1 +type ID string + +// EmptyID is used to explicitly define an ID with no value. +const EmptyID ID = "" + +// Validate is used to check if the ID looks like a proper schema. +// This is done by parsing the ID as a URL and checking it has all the +// relevant parts. +func (id ID) Validate() error { + u, err := url.Parse(id.String()) + if err != nil { + return fmt.Errorf("invalid URL: %w", err) + } + if u.Hostname() == "" { + return errors.New("missing hostname") + } + if !strings.Contains(u.Hostname(), ".") { + return errors.New("hostname does not look valid") + } + if u.Path == "" { + return errors.New("path is expected") + } + if u.Scheme != "https" && u.Scheme != "http" { + return errors.New("unexpected schema") + } + return nil +} + +// Anchor sets the anchor part of the schema URI. +func (id ID) Anchor(name string) ID { + b := id.Base() + return ID(b.String() + "#" + name) +} + +// Def adds or replaces a definition identifier. +func (id ID) Def(name string) ID { + b := id.Base() + return ID(b.String() + "#/$defs/" + name) +} + +// Add appends the provided path to the id, and removes any +// anchor data that might be there. +func (id ID) Add(path string) ID { + b := id.Base() + if !strings.HasPrefix(path, "/") { + path = "/" + path + } + return ID(b.String() + path) +} + +// Base removes any anchor information from the schema +func (id ID) Base() ID { + s := id.String() + i := strings.LastIndex(s, "#") + if i != -1 { + s = s[0:i] + } + s = strings.TrimRight(s, "/") + return ID(s) +} + +// String provides string version of ID +func (id ID) String() string { + return string(id) +} diff --git a/vendor/github.com/invopop/jsonschema/reflect.go b/vendor/github.com/invopop/jsonschema/reflect.go new file mode 100644 index 000000000..143dfa81d --- /dev/null +++ b/vendor/github.com/invopop/jsonschema/reflect.go @@ -0,0 +1,1178 @@ +// Package jsonschema uses reflection to generate JSON Schemas from Go types [1]. +// +// If json tags are present on struct fields, they will be used to infer +// property names and if a property is required (omitempty or omitzero is present). +// +// [1] http://json-schema.org/latest/json-schema-validation.html +package jsonschema + +import ( + "bytes" + "encoding/json" + "net" + "net/url" + "reflect" + "strconv" + "strings" + "time" +) + +// customSchemaImpl is used to detect if the type provides it's own +// custom Schema Type definition to use instead. Very useful for situations +// where there are custom JSON Marshal and Unmarshal methods. +type customSchemaImpl interface { + JSONSchema() *Schema +} + +// Function to be run after the schema has been generated. +// this will let you modify a schema afterwards +type extendSchemaImpl interface { + JSONSchemaExtend(*Schema) +} + +// If the object to be reflected defines a `JSONSchemaAlias` method, its type will +// be used instead of the original type. +type aliasSchemaImpl interface { + JSONSchemaAlias() any +} + +// If an object to be reflected defines a `JSONSchemaPropertyAlias` method, +// it will be called for each property to determine if another object +// should be used for the contents. +type propertyAliasSchemaImpl interface { + JSONSchemaProperty(prop string) any +} + +var customAliasSchema = reflect.TypeOf((*aliasSchemaImpl)(nil)).Elem() +var customPropertyAliasSchema = reflect.TypeOf((*propertyAliasSchemaImpl)(nil)).Elem() + +var customType = reflect.TypeOf((*customSchemaImpl)(nil)).Elem() +var extendType = reflect.TypeOf((*extendSchemaImpl)(nil)).Elem() + +// customSchemaGetFieldDocString +type customSchemaGetFieldDocString interface { + GetFieldDocString(fieldName string) string +} + +type customGetFieldDocString func(fieldName string) string + +var customStructGetFieldDocString = reflect.TypeOf((*customSchemaGetFieldDocString)(nil)).Elem() + +// Reflect reflects to Schema from a value using the default Reflector +func Reflect(v any) *Schema { + return ReflectFromType(reflect.TypeOf(v)) +} + +// ReflectFromType generates root schema using the default Reflector +func ReflectFromType(t reflect.Type) *Schema { + r := &Reflector{} + return r.ReflectFromType(t) +} + +// A Reflector reflects values into a Schema. +type Reflector struct { + // BaseSchemaID defines the URI that will be used as a base to determine Schema + // IDs for models. For example, a base Schema ID of `https://invopop.com/schemas` + // when defined with a struct called `User{}`, will result in a schema with an + // ID set to `https://invopop.com/schemas/user`. + // + // If no `BaseSchemaID` is provided, we'll take the type's complete package path + // and use that as a base instead. Set `Anonymous` to try if you do not want to + // include a schema ID. + BaseSchemaID ID + + // Anonymous when true will hide the auto-generated Schema ID and provide what is + // known as an "anonymous schema". As a rule, this is not recommended. + Anonymous bool + + // AssignAnchor when true will use the original struct's name as an anchor inside + // every definition, including the root schema. These can be useful for having a + // reference to the original struct's name in CamelCase instead of the snake-case used + // by default for URI compatibility. + // + // Anchors do not appear to be widely used out in the wild, so at this time the + // anchors themselves will not be used inside generated schema. + AssignAnchor bool + + // AllowAdditionalProperties will cause the Reflector to generate a schema + // without additionalProperties set to 'false' for all struct types. This means + // the presence of additional keys in JSON objects will not cause validation + // to fail. Note said additional keys will simply be dropped when the + // validated JSON is unmarshaled. + AllowAdditionalProperties bool + + // RequiredFromJSONSchemaTags will cause the Reflector to generate a schema + // that requires any key tagged with `jsonschema:required`, overriding the + // default of requiring any key *not* tagged with `json:,omitempty` or `json:,omitzero`. + RequiredFromJSONSchemaTags bool + + // Do not reference definitions. This will remove the top-level $defs map and + // instead cause the entire structure of types to be output in one tree. The + // list of type definitions (`$defs`) will not be included. + DoNotReference bool + + // ExpandedStruct when true will include the reflected type's definition in the + // root as opposed to a definition with a reference. + ExpandedStruct bool + + // FieldNameTag will change the tag used to get field names. json tags are used by default. + FieldNameTag string + + // IgnoredTypes defines a slice of types that should be ignored in the schema, + // switching to just allowing additional properties instead. + IgnoredTypes []any + + // Lookup allows a function to be defined that will provide a custom mapping of + // types to Schema IDs. This allows existing schema documents to be referenced + // by their ID instead of being embedded into the current schema definitions. + // Reflected types will never be pointers, only underlying elements. + Lookup func(reflect.Type) ID + + // Mapper is a function that can be used to map custom Go types to jsonschema schemas. + Mapper func(reflect.Type) *Schema + + // Namer allows customizing of type names. The default is to use the type's name + // provided by the reflect package. + Namer func(reflect.Type) string + + // KeyNamer allows customizing of key names. + // The default is to use the key's name as is, or the json tag if present. + // If a json tag is present, KeyNamer will receive the tag's name as an argument, not the original key name. + KeyNamer func(string) string + + // AdditionalFields allows adding structfields for a given type + AdditionalFields func(reflect.Type) []reflect.StructField + + // LookupComment allows customizing comment lookup. Given a reflect.Type and optionally + // a field name, it should return the comment string associated with this type or field. + // + // If the field name is empty, it should return the type's comment; otherwise, the field's + // comment should be returned. If no comment is found, an empty string should be returned. + // + // When set, this function is called before the below CommentMap lookup mechanism. However, + // if it returns an empty string, the CommentMap is still consulted. + LookupComment func(reflect.Type, string) string + + // CommentMap is a dictionary of fully qualified go types and fields to comment + // strings that will be used if a description has not already been provided in + // the tags. Types and fields are added to the package path using "." as a + // separator. + // + // Type descriptions should be defined like: + // + // map[string]string{"github.com/invopop/jsonschema.Reflector": "A Reflector reflects values into a Schema."} + // + // And Fields defined as: + // + // map[string]string{"github.com/invopop/jsonschema.Reflector.DoNotReference": "Do not reference definitions."} + // + // See also: AddGoComments, LookupComment + CommentMap map[string]string +} + +// Reflect reflects to Schema from a value. +func (r *Reflector) Reflect(v any) *Schema { + return r.ReflectFromType(reflect.TypeOf(v)) +} + +// ReflectFromType generates root schema +func (r *Reflector) ReflectFromType(t reflect.Type) *Schema { + if t.Kind() == reflect.Ptr { + t = t.Elem() // re-assign from pointer + } + + name := r.typeName(t) + + s := new(Schema) + definitions := Definitions{} + s.Definitions = definitions + bs := r.reflectTypeToSchemaWithID(definitions, t) + if r.ExpandedStruct { + if def := definitions[name]; def != nil { + *s = *def + delete(definitions, name) + } else { + *s = *bs + } + } else { + *s = *bs + } + + // Attempt to set the schema ID + if !r.Anonymous && s.ID == EmptyID { + baseSchemaID := r.BaseSchemaID + if baseSchemaID == EmptyID { + id := ID("https://" + t.PkgPath()) + if err := id.Validate(); err == nil { + // it's okay to silently ignore URL errors + baseSchemaID = id + } + } + if baseSchemaID != EmptyID { + s.ID = baseSchemaID.Add(ToSnakeCase(name)) + } + } + + s.Version = Version + if !r.DoNotReference { + s.Definitions = definitions + } + + return s +} + +// Available Go defined types for JSON Schema Validation. +// RFC draft-wright-json-schema-validation-00, section 7.3 +var ( + timeType = reflect.TypeOf(time.Time{}) // date-time RFC section 7.3.1 + ipType = reflect.TypeOf(net.IP{}) // ipv4 and ipv6 RFC section 7.3.4, 7.3.5 + uriType = reflect.TypeOf(url.URL{}) // uri RFC section 7.3.6 +) + +// Byte slices will be encoded as base64 +var byteSliceType = reflect.TypeOf([]byte(nil)) + +// Except for json.RawMessage +var rawMessageType = reflect.TypeOf(json.RawMessage{}) + +// Go code generated from protobuf enum types should fulfil this interface. +type protoEnum interface { + EnumDescriptor() ([]byte, []int) +} + +var protoEnumType = reflect.TypeOf((*protoEnum)(nil)).Elem() + +// SetBaseSchemaID is a helper use to be able to set the reflectors base +// schema ID from a string as opposed to then ID instance. +func (r *Reflector) SetBaseSchemaID(id string) { + r.BaseSchemaID = ID(id) +} + +func (r *Reflector) refOrReflectTypeToSchema(definitions Definitions, t reflect.Type) *Schema { + id := r.lookupID(t) + if id != EmptyID { + return &Schema{ + Ref: id.String(), + } + } + + // Already added to definitions? + if def := r.refDefinition(definitions, t); def != nil { + return def + } + + return r.reflectTypeToSchemaWithID(definitions, t) +} + +func (r *Reflector) reflectTypeToSchemaWithID(defs Definitions, t reflect.Type) *Schema { + s := r.reflectTypeToSchema(defs, t) + if s != nil { + if r.Lookup != nil { + id := r.Lookup(t) + if id != EmptyID { + s.ID = id + } + } + } + return s +} + +func (r *Reflector) reflectTypeToSchema(definitions Definitions, t reflect.Type) *Schema { + // only try to reflect non-pointers + if t.Kind() == reflect.Ptr { + return r.refOrReflectTypeToSchema(definitions, t.Elem()) + } + + // Check if the there is an alias method that provides an object + // that we should use instead of this one. + if t.Implements(customAliasSchema) { + v := reflect.New(t) + o := v.Interface().(aliasSchemaImpl) + t = reflect.TypeOf(o.JSONSchemaAlias()) + return r.refOrReflectTypeToSchema(definitions, t) + } + + // Do any pre-definitions exist? + if r.Mapper != nil { + if t := r.Mapper(t); t != nil { + return t + } + } + if rt := r.reflectCustomSchema(definitions, t); rt != nil { + return rt + } + + // Prepare a base to which details can be added + st := new(Schema) + + // jsonpb will marshal protobuf enum options as either strings or integers. + // It will unmarshal either. + if t.Implements(protoEnumType) { + st.OneOf = []*Schema{ + {Type: "string"}, + {Type: "integer"}, + } + return st + } + + // Defined format types for JSON Schema Validation + // RFC draft-wright-json-schema-validation-00, section 7.3 + // TODO email RFC section 7.3.2, hostname RFC section 7.3.3, uriref RFC section 7.3.7 + if t == ipType { + // TODO differentiate ipv4 and ipv6 RFC section 7.3.4, 7.3.5 + st.Type = "string" + st.Format = "ipv4" + return st + } + + switch t.Kind() { + case reflect.Struct: + r.reflectStruct(definitions, t, st) + + case reflect.Slice, reflect.Array: + r.reflectSliceOrArray(definitions, t, st) + + case reflect.Map: + r.reflectMap(definitions, t, st) + + case reflect.Interface: + // empty + + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, + reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + st.Type = "integer" + + case reflect.Float32, reflect.Float64: + st.Type = "number" + + case reflect.Bool: + st.Type = "boolean" + + case reflect.String: + st.Type = "string" + + default: + panic("unsupported type " + t.String()) + } + + r.reflectSchemaExtend(definitions, t, st) + + // Always try to reference the definition which may have just been created + if def := r.refDefinition(definitions, t); def != nil { + return def + } + + return st +} + +func (r *Reflector) reflectCustomSchema(definitions Definitions, t reflect.Type) *Schema { + if t.Kind() == reflect.Ptr { + return r.reflectCustomSchema(definitions, t.Elem()) + } + + if t.Implements(customType) { + v := reflect.New(t) + o := v.Interface().(customSchemaImpl) + st := o.JSONSchema() + r.addDefinition(definitions, t, st) + if ref := r.refDefinition(definitions, t); ref != nil { + return ref + } + return st + } + + return nil +} + +func (r *Reflector) reflectSchemaExtend(definitions Definitions, t reflect.Type, s *Schema) *Schema { + if t.Implements(extendType) { + v := reflect.New(t) + o := v.Interface().(extendSchemaImpl) + o.JSONSchemaExtend(s) + if ref := r.refDefinition(definitions, t); ref != nil { + return ref + } + } + + return s +} + +func (r *Reflector) reflectSliceOrArray(definitions Definitions, t reflect.Type, st *Schema) { + if t == rawMessageType { + return + } + + r.addDefinition(definitions, t, st) + + if st.Description == "" { + st.Description = r.lookupComment(t, "") + } + + if t.Kind() == reflect.Array { + l := uint64(t.Len()) + st.MinItems = &l + st.MaxItems = &l + } + if t.Kind() == reflect.Slice && t.Elem() == byteSliceType.Elem() { + st.Type = "string" + // NOTE: ContentMediaType is not set here + st.ContentEncoding = "base64" + } else { + st.Type = "array" + st.Items = r.refOrReflectTypeToSchema(definitions, t.Elem()) + } +} + +func (r *Reflector) reflectMap(definitions Definitions, t reflect.Type, st *Schema) { + r.addDefinition(definitions, t, st) + + st.Type = "object" + if st.Description == "" { + st.Description = r.lookupComment(t, "") + } + + switch t.Key().Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + st.PatternProperties = map[string]*Schema{ + "^[0-9]+$": r.refOrReflectTypeToSchema(definitions, t.Elem()), + } + st.AdditionalProperties = FalseSchema + return + } + if t.Elem().Kind() != reflect.Interface { + st.AdditionalProperties = r.refOrReflectTypeToSchema(definitions, t.Elem()) + } +} + +// Reflects a struct to a JSON Schema type. +func (r *Reflector) reflectStruct(definitions Definitions, t reflect.Type, s *Schema) { + // Handle special types + switch t { + case timeType: // date-time RFC section 7.3.1 + s.Type = "string" + s.Format = "date-time" + return + case uriType: // uri RFC section 7.3.6 + s.Type = "string" + s.Format = "uri" + return + } + + r.addDefinition(definitions, t, s) + s.Type = "object" + s.Properties = NewProperties() + s.Description = r.lookupComment(t, "") + if r.AssignAnchor { + s.Anchor = t.Name() + } + if !r.AllowAdditionalProperties && s.AdditionalProperties == nil { + s.AdditionalProperties = FalseSchema + } + + ignored := false + for _, it := range r.IgnoredTypes { + if reflect.TypeOf(it) == t { + ignored = true + break + } + } + if !ignored { + r.reflectStructFields(s, definitions, t) + } +} + +func (r *Reflector) reflectStructFields(st *Schema, definitions Definitions, t reflect.Type) { + if t.Kind() == reflect.Ptr { + t = t.Elem() + } + if t.Kind() != reflect.Struct { + return + } + + var getFieldDocString customGetFieldDocString + if t.Implements(customStructGetFieldDocString) { + v := reflect.New(t) + o := v.Interface().(customSchemaGetFieldDocString) + getFieldDocString = o.GetFieldDocString + } + + customPropertyMethod := func(string) any { + return nil + } + if t.Implements(customPropertyAliasSchema) { + v := reflect.New(t) + o := v.Interface().(propertyAliasSchemaImpl) + customPropertyMethod = o.JSONSchemaProperty + } + + handleField := func(f reflect.StructField) { + name, shouldEmbed, required, nullable := r.reflectFieldName(f) + // if anonymous and exported type should be processed recursively + // current type should inherit properties of anonymous one + if name == "" { + if shouldEmbed { + r.reflectStructFields(st, definitions, f.Type) + } + return + } + + // If a JSONSchemaAlias(prop string) method is defined, attempt to use + // the provided object's type instead of the field's type. + var property *Schema + if alias := customPropertyMethod(name); alias != nil { + property = r.refOrReflectTypeToSchema(definitions, reflect.TypeOf(alias)) + } else { + property = r.refOrReflectTypeToSchema(definitions, f.Type) + } + + property.structKeywordsFromTags(f, st, name) + if property.Description == "" { + property.Description = r.lookupComment(t, f.Name) + } + if getFieldDocString != nil { + property.Description = getFieldDocString(f.Name) + } + + if nullable { + property = &Schema{ + OneOf: []*Schema{ + property, + { + Type: "null", + }, + }, + } + } + + st.Properties.Set(name, property) + if required { + st.Required = appendUniqueString(st.Required, name) + } + } + + for i := 0; i < t.NumField(); i++ { + f := t.Field(i) + handleField(f) + } + if r.AdditionalFields != nil { + if af := r.AdditionalFields(t); af != nil { + for _, sf := range af { + handleField(sf) + } + } + } +} + +func appendUniqueString(base []string, value string) []string { + for _, v := range base { + if v == value { + return base + } + } + return append(base, value) +} + +// addDefinition will append the provided schema. If needed, an ID and anchor will also be added. +func (r *Reflector) addDefinition(definitions Definitions, t reflect.Type, s *Schema) { + name := r.typeName(t) + if name == "" { + return + } + definitions[name] = s +} + +// refDefinition will provide a schema with a reference to an existing definition. +func (r *Reflector) refDefinition(definitions Definitions, t reflect.Type) *Schema { + if r.DoNotReference { + return nil + } + name := r.typeName(t) + if name == "" { + return nil + } + if _, ok := definitions[name]; !ok { + return nil + } + return &Schema{ + Ref: "#/$defs/" + name, + } +} + +func (r *Reflector) lookupID(t reflect.Type) ID { + if r.Lookup != nil { + if t.Kind() == reflect.Ptr { + t = t.Elem() + } + return r.Lookup(t) + + } + return EmptyID +} + +func (t *Schema) structKeywordsFromTags(f reflect.StructField, parent *Schema, propertyName string) { + t.Description = f.Tag.Get("jsonschema_description") + + tags := splitOnUnescapedCommas(f.Tag.Get("jsonschema")) + tags = t.genericKeywords(tags, parent, propertyName) + + // The encoding/json ",string" option causes integer, float and boolean + // fields to be encoded as JSON strings. Override the reflected type + // accordingly before running type-specific keyword parsing so the + // generated schema matches the on-the-wire representation. + jsonTags := strings.Split(f.Tag.Get("json"), ",") + switch t.Type { + case "integer", "number", "boolean": + if jsonTagHasOption(jsonTags, "string") { + t.Type = "string" + } + } + + switch t.Type { + case "string": + t.stringKeywords(tags) + case "number": + t.numericalKeywords(tags) + case "integer": + t.numericalKeywords(tags) + case "array": + t.arrayKeywords(tags) + case "boolean": + t.booleanKeywords(tags) + } + extras := splitOnUnescapedCommas(f.Tag.Get("jsonschema_extras")) + t.extraKeywords(extras) +} + +// read struct tags for generic keywords +func (t *Schema) genericKeywords(tags []string, parent *Schema, propertyName string) []string { //nolint:gocyclo + unprocessed := make([]string, 0, len(tags)) + for _, tag := range tags { + nameValue := strings.SplitN(tag, "=", 2) + if len(nameValue) == 2 { + name, val := nameValue[0], nameValue[1] + switch name { + case "title": + t.Title = val + case "description": + t.Description = val + case "type": + t.Type = val + case "anchor": + t.Anchor = val + case "oneof_required": + var typeFound *Schema + for i := range parent.OneOf { + if parent.OneOf[i].Title == nameValue[1] { + typeFound = parent.OneOf[i] + } + } + if typeFound == nil { + typeFound = &Schema{ + Title: nameValue[1], + Required: []string{}, + } + parent.OneOf = append(parent.OneOf, typeFound) + } + typeFound.Required = append(typeFound.Required, propertyName) + case "anyof_required": + var typeFound *Schema + for i := range parent.AnyOf { + if parent.AnyOf[i].Title == nameValue[1] { + typeFound = parent.AnyOf[i] + } + } + if typeFound == nil { + typeFound = &Schema{ + Title: nameValue[1], + Required: []string{}, + } + parent.AnyOf = append(parent.AnyOf, typeFound) + } + typeFound.Required = append(typeFound.Required, propertyName) + case "oneof_ref": + subSchema := t + if t.Items != nil { + subSchema = t.Items + } + if subSchema.OneOf == nil { + subSchema.OneOf = make([]*Schema, 0, 1) + } + subSchema.Ref = "" + refs := strings.Split(nameValue[1], ";") + for _, r := range refs { + subSchema.OneOf = append(subSchema.OneOf, &Schema{ + Ref: r, + }) + } + case "oneof_type": + if t.OneOf == nil { + t.OneOf = make([]*Schema, 0, 1) + } + t.Type = "" + types := strings.Split(nameValue[1], ";") + for _, ty := range types { + t.OneOf = append(t.OneOf, &Schema{ + Type: ty, + }) + } + case "anyof_ref": + subSchema := t + if t.Items != nil { + subSchema = t.Items + } + if subSchema.AnyOf == nil { + subSchema.AnyOf = make([]*Schema, 0, 1) + } + subSchema.Ref = "" + refs := strings.Split(nameValue[1], ";") + for _, r := range refs { + subSchema.AnyOf = append(subSchema.AnyOf, &Schema{ + Ref: r, + }) + } + case "anyof_type": + if t.AnyOf == nil { + t.AnyOf = make([]*Schema, 0, 1) + } + t.Type = "" + types := strings.Split(nameValue[1], ";") + for _, ty := range types { + t.AnyOf = append(t.AnyOf, &Schema{ + Type: ty, + }) + } + default: + unprocessed = append(unprocessed, tag) + } + } + } + return unprocessed +} + +// read struct tags for boolean type keywords +func (t *Schema) booleanKeywords(tags []string) { + for _, tag := range tags { + nameValue := strings.Split(tag, "=") + if len(nameValue) != 2 { + continue + } + name, val := nameValue[0], nameValue[1] + if name == "default" { + switch val { + case "true": + t.Default = true + case "false": + t.Default = false + } + } + } +} + +// read struct tags for string type keywords +func (t *Schema) stringKeywords(tags []string) { + for _, tag := range tags { + nameValue := strings.SplitN(tag, "=", 2) + if len(nameValue) == 2 { + name, val := nameValue[0], nameValue[1] + switch name { + case "minLength": + t.MinLength = parseUint(val) + case "maxLength": + t.MaxLength = parseUint(val) + case "pattern": + t.Pattern = val + case "format": + t.Format = val + case "readOnly": + i, _ := strconv.ParseBool(val) + t.ReadOnly = i + case "writeOnly": + i, _ := strconv.ParseBool(val) + t.WriteOnly = i + case "default": + t.Default = val + case "example": + t.Examples = append(t.Examples, val) + case "enum": + t.Enum = append(t.Enum, val) + } + } + } +} + +// read struct tags for numerical type keywords +func (t *Schema) numericalKeywords(tags []string) { + for _, tag := range tags { + nameValue := strings.Split(tag, "=") + if len(nameValue) == 2 { + name, val := nameValue[0], nameValue[1] + switch name { + case "multipleOf": + t.MultipleOf, _ = toJSONNumber(val) + case "minimum": + t.Minimum, _ = toJSONNumber(val) + case "maximum": + t.Maximum, _ = toJSONNumber(val) + case "exclusiveMaximum": + t.ExclusiveMaximum, _ = toJSONNumber(val) + case "exclusiveMinimum": + t.ExclusiveMinimum, _ = toJSONNumber(val) + case "default": + if num, ok := toJSONNumber(val); ok { + t.Default = num + } + case "example": + if num, ok := toJSONNumber(val); ok { + t.Examples = append(t.Examples, num) + } + case "enum": + if num, ok := toJSONNumber(val); ok { + t.Enum = append(t.Enum, num) + } + } + } + } +} + +// read struct tags for object type keywords +// func (t *Type) objectKeywords(tags []string) { +// for _, tag := range tags{ +// nameValue := strings.Split(tag, "=") +// name, val := nameValue[0], nameValue[1] +// switch name{ +// case "dependencies": +// t.Dependencies = val +// break; +// case "patternProperties": +// t.PatternProperties = val +// break; +// } +// } +// } + +// read struct tags for array type keywords +func (t *Schema) arrayKeywords(tags []string) { + var defaultValues []any + + unprocessed := make([]string, 0, len(tags)) + for _, tag := range tags { + nameValue := strings.Split(tag, "=") + if len(nameValue) == 2 { + name, val := nameValue[0], nameValue[1] + switch name { + case "minItems": + t.MinItems = parseUint(val) + case "maxItems": + t.MaxItems = parseUint(val) + case "uniqueItems": + t.UniqueItems = true + case "default": + defaultValues = append(defaultValues, val) + case "format": + t.Items.Format = val + case "pattern": + t.Items.Pattern = val + default: + unprocessed = append(unprocessed, tag) // left for further processing by underlying type + } + } + } + if len(defaultValues) > 0 { + t.Default = defaultValues + } + + if len(unprocessed) == 0 { + // we don't have anything else to process + return + } + + switch t.Items.Type { + case "string": + t.Items.stringKeywords(unprocessed) + case "number": + t.Items.numericalKeywords(unprocessed) + case "integer": + t.Items.numericalKeywords(unprocessed) + case "array": + // explicitly don't support traversal for the [][]..., as it's unclear where the array tags belong + case "boolean": + t.Items.booleanKeywords(unprocessed) + } +} + +func (t *Schema) extraKeywords(tags []string) { + for _, tag := range tags { + nameValue := strings.SplitN(tag, "=", 2) + if len(nameValue) == 2 { + t.setExtra(nameValue[0], nameValue[1]) + } + } +} + +func (t *Schema) setExtra(key, val string) { + if t.Extras == nil { + t.Extras = map[string]any{} + } + if existingVal, ok := t.Extras[key]; ok { + switch existingVal := existingVal.(type) { + case string: + t.Extras[key] = []string{existingVal, val} + case []string: + t.Extras[key] = append(existingVal, val) + case int: + t.Extras[key], _ = strconv.Atoi(val) + case bool: + t.Extras[key] = (val == "true" || val == "t") + } + } else { + switch key { + case "minimum": + t.Extras[key], _ = strconv.Atoi(val) + default: + var x any + switch val { + case "true": + x = true + case "false": + x = false + default: + x = val + } + t.Extras[key] = x + } + } +} + +func requiredFromJSONTags(tags []string, val *bool) { + if ignoredByJSONTags(tags) { + return + } + + for _, tag := range tags[1:] { + if tag == "omitempty" || tag == "omitzero" { + *val = false + return + } + } + *val = true +} + +func requiredFromJSONSchemaTags(tags []string, val *bool) { + if ignoredByJSONSchemaTags(tags) { + return + } + for _, tag := range tags { + if tag == "required" { + *val = true + } + } +} + +func nullableFromJSONSchemaTags(tags []string) bool { + if ignoredByJSONSchemaTags(tags) { + return false + } + for _, tag := range tags { + if tag == "nullable" { + return true + } + } + return false +} + +func ignoredByJSONTags(tags []string) bool { + return tags[0] == "-" +} + +func ignoredByJSONSchemaTags(tags []string) bool { + return tags[0] == "-" +} + +func inlinedByJSONTags(tags []string) bool { + for _, tag := range tags[1:] { + if tag == "inline" { + return true + } + } + return false +} + +// jsonTagHasOption reports whether the parsed json struct tag contains the +// given option. The first element of tags is assumed to be the field name, as +// produced by strings.Split on a raw json tag value, and is skipped. +func jsonTagHasOption(tags []string, option string) bool { + for _, tag := range tags[1:] { + if tag == option { + return true + } + } + return false +} + +// toJSONNumber converts string to *json.Number. +// It'll aso return whether the number is valid. +func toJSONNumber(s string) (json.Number, bool) { + num := json.Number(s) + if _, err := num.Int64(); err == nil { + return num, true + } + if _, err := num.Float64(); err == nil { + return num, true + } + return json.Number(""), false +} + +func parseUint(num string) *uint64 { + val, err := strconv.ParseUint(num, 10, 64) + if err != nil { + return nil + } + return &val +} + +func (r *Reflector) fieldNameTag() string { + if r.FieldNameTag != "" { + return r.FieldNameTag + } + return "json" +} + +func (r *Reflector) reflectFieldName(f reflect.StructField) (string, bool, bool, bool) { + jsonTagString := f.Tag.Get(r.fieldNameTag()) + jsonTags := strings.Split(jsonTagString, ",") + + if ignoredByJSONTags(jsonTags) { + return "", false, false, false + } + + schemaTags := strings.Split(f.Tag.Get("jsonschema"), ",") + if ignoredByJSONSchemaTags(schemaTags) { + return "", false, false, false + } + + var required bool + if !r.RequiredFromJSONSchemaTags { + requiredFromJSONTags(jsonTags, &required) + } + requiredFromJSONSchemaTags(schemaTags, &required) + + nullable := nullableFromJSONSchemaTags(schemaTags) + + if f.Anonymous && jsonTags[0] == "" { + // As per JSON Marshal rules, anonymous structs are inherited + if f.Type.Kind() == reflect.Struct { + return "", true, false, false + } + + // As per JSON Marshal rules, anonymous pointer to structs are inherited + if f.Type.Kind() == reflect.Ptr && f.Type.Elem().Kind() == reflect.Struct { + return "", true, false, false + } + } + + // As per JSON Marshal rules, inline nested structs that have `inline` tag. + if inlinedByJSONTags(jsonTags) { + return "", true, false, false + } + + // Try to determine the name from the different combos + name := f.Name + if jsonTags[0] != "" { + name = jsonTags[0] + } + if !f.Anonymous && f.PkgPath != "" { + // field not anonymous and not export has no export name + name = "" + } else if r.KeyNamer != nil { + name = r.KeyNamer(name) + } + + return name, false, required, nullable +} + +// UnmarshalJSON is used to parse a schema object or boolean. +func (t *Schema) UnmarshalJSON(data []byte) error { + if bytes.Equal(data, []byte("true")) { + *t = *TrueSchema + return nil + } else if bytes.Equal(data, []byte("false")) { + *t = *FalseSchema + return nil + } + type SchemaAlt Schema + aux := &struct { + *SchemaAlt + }{ + SchemaAlt: (*SchemaAlt)(t), + } + return json.Unmarshal(data, aux) +} + +// MarshalJSON is used to serialize a schema object or boolean. +func (t *Schema) MarshalJSON() ([]byte, error) { + if t.boolean != nil { + if *t.boolean { + return []byte("true"), nil + } + return []byte("false"), nil + } + if reflect.DeepEqual(&Schema{}, t) { + // Don't bother returning empty schemas + return []byte("true"), nil + } + type SchemaAlt Schema + b, err := json.Marshal((*SchemaAlt)(t)) + if err != nil { + return nil, err + } + if len(t.Extras) == 0 { + return b, nil + } + m, err := json.Marshal(t.Extras) + if err != nil { + return nil, err + } + if len(b) == 2 { + return m, nil + } + b[len(b)-1] = ',' + return append(b, m[1:]...), nil +} + +func (r *Reflector) typeName(t reflect.Type) string { + if r.Namer != nil { + if name := r.Namer(t); name != "" { + return name + } + } + return t.Name() +} + +// Split on commas that are not preceded by `\`. +// This way, we prevent splitting regexes +func splitOnUnescapedCommas(tagString string) []string { + ret := make([]string, 0) + separated := strings.Split(tagString, ",") + ret = append(ret, separated[0]) + i := 0 + for _, nextTag := range separated[1:] { + if len(ret[i]) == 0 { + ret = append(ret, nextTag) + i++ + continue + } + + if ret[i][len(ret[i])-1] == '\\' { + ret[i] = ret[i][:len(ret[i])-1] + "," + nextTag + } else { + ret = append(ret, nextTag) + i++ + } + } + + return ret +} + +func fullyQualifiedTypeName(t reflect.Type) string { + return t.PkgPath() + "." + t.Name() +} diff --git a/vendor/github.com/invopop/jsonschema/reflect_comments.go b/vendor/github.com/invopop/jsonschema/reflect_comments.go new file mode 100644 index 000000000..fe4819882 --- /dev/null +++ b/vendor/github.com/invopop/jsonschema/reflect_comments.go @@ -0,0 +1,160 @@ +package jsonschema + +import ( + "fmt" + "io/fs" + gopath "path" + "path/filepath" + "reflect" + "strings" + + "go/ast" + "go/doc" + "go/parser" + "go/token" +) + +type commentOptions struct { + fullObjectText bool // use the first sentence only? +} + +// CommentOption allows for special configuration options when preparing Go +// source files for comment extraction. +type CommentOption func(*commentOptions) + +// WithFullComment will configure the comment extraction to process to use an +// object type's full comment text instead of just the synopsis. +func WithFullComment() CommentOption { + return func(o *commentOptions) { + o.fullObjectText = true + } +} + +// AddGoComments will update the reflectors comment map with all the comments +// found in the provided source directories including sub-directories, in order to +// generate a dictionary of comments associated with Types and Fields. The results +// will be added to the `Reflect.CommentMap` ready to use with Schema "description" +// fields. +// +// The `go/parser` library is used to extract all the comments and unfortunately doesn't +// have a built-in way to determine the fully qualified name of a package. The `base` +// parameter, the URL used to import that package, is thus required to be able to match +// reflected types. +// +// When parsing type comments, by default we use the `go/doc`'s Synopsis method to extract +// the first phrase only. Field comments, which tend to be much shorter, will include everything. +// This behavior can be changed by using the `WithFullComment` option. +func (r *Reflector) AddGoComments(base, path string, opts ...CommentOption) error { + if r.CommentMap == nil { + r.CommentMap = make(map[string]string) + } + co := new(commentOptions) + for _, opt := range opts { + opt(co) + } + + return r.extractGoComments(base, path, r.CommentMap, co) +} + +func (r *Reflector) extractGoComments(base, path string, commentMap map[string]string, opts *commentOptions) error { + fset := token.NewFileSet() + // importPath -> packageName -> files (a directory may hold multiple + // packages, e.g. foo and foo_test). + dict := make(map[string]map[string][]*ast.File) + err := filepath.Walk(path, func(p string, info fs.FileInfo, err error) error { + if err != nil { + return err + } + if info.IsDir() || !strings.HasSuffix(p, ".go") { + return nil + } + f, err := parser.ParseFile(fset, p, nil, parser.ParseComments) + if err != nil { + return err + } + k := gopath.Join(base, filepath.Dir(p)) + if dict[k] == nil { + dict[k] = make(map[string][]*ast.File) + } + dict[k][f.Name.Name] = append(dict[k][f.Name.Name], f) + return nil + }) + if err != nil { + return err + } + + for pkg, byName := range dict { + for _, files := range byName { + docPkg, err := doc.NewFromFiles(fset, files, pkg, doc.AllDecls|doc.PreserveAST) + if err != nil { + return err + } + for _, f := range files { + collectFileComments(docPkg, f, pkg, commentMap, opts) + } + } + } + + return nil +} + +func collectFileComments(docPkg *doc.Package, f *ast.File, pkg string, commentMap map[string]string, opts *commentOptions) { + gtxt := "" + typ := "" + ast.Inspect(f, func(n ast.Node) bool { + switch x := n.(type) { + case *ast.TypeSpec: + typ = x.Name.String() + if !ast.IsExported(typ) { + typ = "" + return true + } + txt := x.Doc.Text() + if txt == "" && gtxt != "" { + txt = gtxt + gtxt = "" + } + if !opts.fullObjectText { + txt = docPkg.Synopsis(txt) + } + commentMap[fmt.Sprintf("%s.%s", pkg, typ)] = strings.TrimSpace(txt) + case *ast.Field: + txt := x.Doc.Text() + if txt == "" { + txt = x.Comment.Text() + } + if typ == "" || txt == "" { + return true + } + for _, n := range x.Names { + if ast.IsExported(n.String()) { + k := fmt.Sprintf("%s.%s.%s", pkg, typ, n) + commentMap[k] = strings.TrimSpace(txt) + } + } + case *ast.GenDecl: + // remember for the next type + gtxt = x.Doc.Text() + } + return true + }) +} + +func (r *Reflector) lookupComment(t reflect.Type, name string) string { + if r.LookupComment != nil { + if comment := r.LookupComment(t, name); comment != "" { + return comment + } + } + + if r.CommentMap == nil { + return "" + } + + n := fullyQualifiedTypeName(t) + if name != "" { + n = n + "." + name + } + + return r.CommentMap[n] +} diff --git a/vendor/github.com/invopop/jsonschema/schema.go b/vendor/github.com/invopop/jsonschema/schema.go new file mode 100644 index 000000000..543e86325 --- /dev/null +++ b/vendor/github.com/invopop/jsonschema/schema.go @@ -0,0 +1,94 @@ +package jsonschema + +import ( + "encoding/json" + + orderedmap "github.com/pb33f/ordered-map/v2" +) + +// Version is the JSON Schema version. +var Version = "https://json-schema.org/draft/2020-12/schema" + +// Schema represents a JSON Schema object type. +// RFC draft-bhutton-json-schema-00 section 4.3 +type Schema struct { + // RFC draft-bhutton-json-schema-00 + Version string `json:"$schema,omitempty"` // section 8.1.1 + ID ID `json:"$id,omitempty"` // section 8.2.1 + Anchor string `json:"$anchor,omitempty"` // section 8.2.2 + Ref string `json:"$ref,omitempty"` // section 8.2.3.1 + DynamicRef string `json:"$dynamicRef,omitempty"` // section 8.2.3.2 + Definitions Definitions `json:"$defs,omitempty"` // section 8.2.4 + Comments string `json:"$comment,omitempty"` // section 8.3 + // RFC draft-bhutton-json-schema-00 section 10.2.1 (Sub-schemas with logic) + AllOf []*Schema `json:"allOf,omitempty"` // section 10.2.1.1 + AnyOf []*Schema `json:"anyOf,omitempty"` // section 10.2.1.2 + OneOf []*Schema `json:"oneOf,omitempty"` // section 10.2.1.3 + Not *Schema `json:"not,omitempty"` // section 10.2.1.4 + // RFC draft-bhutton-json-schema-00 section 10.2.2 (Apply sub-schemas conditionally) + If *Schema `json:"if,omitempty"` // section 10.2.2.1 + Then *Schema `json:"then,omitempty"` // section 10.2.2.2 + Else *Schema `json:"else,omitempty"` // section 10.2.2.3 + DependentSchemas map[string]*Schema `json:"dependentSchemas,omitempty"` // section 10.2.2.4 + // RFC draft-bhutton-json-schema-00 section 10.3.1 (arrays) + PrefixItems []*Schema `json:"prefixItems,omitempty"` // section 10.3.1.1 + Items *Schema `json:"items,omitempty"` // section 10.3.1.2 (replaces additionalItems) + Contains *Schema `json:"contains,omitempty"` // section 10.3.1.3 + // RFC draft-bhutton-json-schema-00 section 10.3.2 (sub-schemas) + Properties *orderedmap.OrderedMap[string, *Schema] `json:"properties,omitempty"` // section 10.3.2.1 + PatternProperties map[string]*Schema `json:"patternProperties,omitempty"` // section 10.3.2.2 + AdditionalProperties *Schema `json:"additionalProperties,omitempty"` // section 10.3.2.3 + PropertyNames *Schema `json:"propertyNames,omitempty"` // section 10.3.2.4 + // RFC draft-bhutton-json-schema-validation-00, section 6 + Type string `json:"type,omitempty"` // section 6.1.1 + Enum []any `json:"enum,omitempty"` // section 6.1.2 + Const any `json:"const,omitempty"` // section 6.1.3 + MultipleOf json.Number `json:"multipleOf,omitempty"` // section 6.2.1 + Maximum json.Number `json:"maximum,omitempty"` // section 6.2.2 + ExclusiveMaximum json.Number `json:"exclusiveMaximum,omitempty"` // section 6.2.3 + Minimum json.Number `json:"minimum,omitempty"` // section 6.2.4 + ExclusiveMinimum json.Number `json:"exclusiveMinimum,omitempty"` // section 6.2.5 + MaxLength *uint64 `json:"maxLength,omitempty"` // section 6.3.1 + MinLength *uint64 `json:"minLength,omitempty"` // section 6.3.2 + Pattern string `json:"pattern,omitempty"` // section 6.3.3 + MaxItems *uint64 `json:"maxItems,omitempty"` // section 6.4.1 + MinItems *uint64 `json:"minItems,omitempty"` // section 6.4.2 + UniqueItems bool `json:"uniqueItems,omitempty"` // section 6.4.3 + MaxContains *uint64 `json:"maxContains,omitempty"` // section 6.4.4 + MinContains *uint64 `json:"minContains,omitempty"` // section 6.4.5 + MaxProperties *uint64 `json:"maxProperties,omitempty"` // section 6.5.1 + MinProperties *uint64 `json:"minProperties,omitempty"` // section 6.5.2 + Required []string `json:"required,omitempty"` // section 6.5.3 + DependentRequired map[string][]string `json:"dependentRequired,omitempty"` // section 6.5.4 + // RFC draft-bhutton-json-schema-validation-00, section 7 + Format string `json:"format,omitempty"` + // RFC draft-bhutton-json-schema-validation-00, section 8 + ContentEncoding string `json:"contentEncoding,omitempty"` // section 8.3 + ContentMediaType string `json:"contentMediaType,omitempty"` // section 8.4 + ContentSchema *Schema `json:"contentSchema,omitempty"` // section 8.5 + // RFC draft-bhutton-json-schema-validation-00, section 9 + Title string `json:"title,omitempty"` // section 9.1 + Description string `json:"description,omitempty"` // section 9.1 + Default any `json:"default,omitempty"` // section 9.2 + Deprecated bool `json:"deprecated,omitempty"` // section 9.3 + ReadOnly bool `json:"readOnly,omitempty"` // section 9.4 + WriteOnly bool `json:"writeOnly,omitempty"` // section 9.4 + Examples []any `json:"examples,omitempty"` // section 9.5 + + Extras map[string]any `json:"-"` + + // Special boolean representation of the Schema - section 4.3.2 + boolean *bool +} + +var ( + // TrueSchema defines a schema with a true value + TrueSchema = &Schema{boolean: &[]bool{true}[0]} + // FalseSchema defines a schema with a false value + FalseSchema = &Schema{boolean: &[]bool{false}[0]} +) + +// Definitions hold schema definitions. +// http://json-schema.org/latest/json-schema-validation.html#rfc.section.5.26 +// RFC draft-wright-json-schema-validation-00, section 5.26 +type Definitions map[string]*Schema diff --git a/vendor/github.com/invopop/jsonschema/utils.go b/vendor/github.com/invopop/jsonschema/utils.go new file mode 100644 index 000000000..3ae8a8ed2 --- /dev/null +++ b/vendor/github.com/invopop/jsonschema/utils.go @@ -0,0 +1,26 @@ +package jsonschema + +import ( + "regexp" + "strings" + + orderedmap "github.com/pb33f/ordered-map/v2" +) + +var matchFirstCap = regexp.MustCompile("(.)([A-Z][a-z]+)") +var matchAllCap = regexp.MustCompile("([a-z0-9])([A-Z])") + +// ToSnakeCase converts the provided string into snake case using dashes. +// This is useful for Schema IDs and definitions to be coherent with +// common JSON Schema examples. +func ToSnakeCase(str string) string { + snake := matchFirstCap.ReplaceAllString(str, "${1}-${2}") + snake = matchAllCap.ReplaceAllString(snake, "${1}-${2}") + return strings.ToLower(snake) +} + +// NewProperties is a helper method to instantiate a new properties ordered +// map. +func NewProperties() *orderedmap.OrderedMap[string, *Schema] { + return orderedmap.New[string, *Schema]() +} diff --git a/vendor/github.com/standard-webhooks/standard-webhooks/libraries/LICENSE b/vendor/github.com/standard-webhooks/standard-webhooks/libraries/LICENSE new file mode 100644 index 000000000..55b14b3a3 --- /dev/null +++ b/vendor/github.com/standard-webhooks/standard-webhooks/libraries/LICENSE @@ -0,0 +1,21 @@ +The MIT License + +Copyright (c) 2023 Svix (https://www.svix.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/vendor/github.com/standard-webhooks/standard-webhooks/libraries/go/README.md b/vendor/github.com/standard-webhooks/standard-webhooks/libraries/go/README.md new file mode 100644 index 000000000..54d28971e --- /dev/null +++ b/vendor/github.com/standard-webhooks/standard-webhooks/libraries/go/README.md @@ -0,0 +1,40 @@ +Go library for Standard Webhooks + +# Example + +Verifying a webhook payload: + +```go +import ( + standardwebhooks "github.com/standard-webhooks/standard-webhooks/libraries/go" +) + +wh, err := standardwebhooks.NewWebhook(base64Secret) +err = wh.Verify(webhookPayload, webhookHeaders) +``` + +# Development + +## Requirements + + - go >= 1.16 + +## Contributing + +Before opening a PR be sure to format your code! + +```sh +go fmt ./... +``` + +## Running Tests + +Simply run: + +```sh +go test ./... +``` + +## Publishing + +Releases use go modules and are automatically published by tagging the release commit. diff --git a/vendor/github.com/standard-webhooks/standard-webhooks/libraries/go/webhook.go b/vendor/github.com/standard-webhooks/standard-webhooks/libraries/go/webhook.go new file mode 100644 index 000000000..0fa769ba5 --- /dev/null +++ b/vendor/github.com/standard-webhooks/standard-webhooks/libraries/go/webhook.go @@ -0,0 +1,160 @@ +package standardwebhooks + +import ( + "crypto/hmac" + "crypto/sha256" + "encoding/base64" + "errors" + "fmt" + "net/http" + "strconv" + "strings" + "time" +) + +const ( + HeaderWebhookID string = "webhook-id" + HeaderWebhookSignature string = "webhook-signature" + HeaderWebhookTimestamp string = "webhook-timestamp" + + webhookSecretPrefix string = "whsec_" +) + +var base64enc = base64.StdEncoding + +var tolerance time.Duration = 5 * time.Minute + +var ( + ErrRequiredHeaders = errors.New("missing required headers") + ErrInvalidHeaders = errors.New("invalid signature headers") + ErrNoMatchingSignature = errors.New("no matching signature found") + ErrMessageTooOld = errors.New("message timestamp too old") + ErrMessageTooNew = errors.New("message timestamp too new") +) + +type Webhook struct { + key []byte +} + +func NewWebhook(secret string) (*Webhook, error) { + key, err := base64enc.DecodeString(strings.TrimPrefix(secret, webhookSecretPrefix)) + if err != nil { + return nil, fmt.Errorf("unable to create webhook, err: %w", err) + } + return &Webhook{ + key: key, + }, nil +} + +func NewWebhookRaw(secret []byte) (*Webhook, error) { + return &Webhook{ + key: secret, + }, nil +} + +// Verify validates the payload against the webhook signature headers +// using the webhooks signing secret. +// +// Returns an error if the body or headers are missing/unreadable +// or if the signature doesn't match. +func (wh *Webhook) Verify(payload []byte, headers http.Header) error { + return wh.verify(payload, headers, true) +} + +// VerifyIgnoringTimestamp validates the payload against the webhook signature headers +// using the webhooks signing secret. +// +// Returns an error if the body or headers are missing/unreadable +// or if the signature doesn't match. +// +// WARNING: This function does not check the signature's timestamp. +// We recommend using the `Verify` function instead. +func (wh *Webhook) VerifyIgnoringTimestamp(payload []byte, headers http.Header) error { + return wh.verify(payload, headers, false) +} + +func (wh *Webhook) verify(payload []byte, headers http.Header, enforceTolerance bool) error { + msgId := headers.Get(HeaderWebhookID) + msgSignature := headers.Get(HeaderWebhookSignature) + msgTimestamp := headers.Get(HeaderWebhookTimestamp) + if msgId == "" || msgSignature == "" || msgTimestamp == "" { + return fmt.Errorf("unable to verify payload, err: %w", ErrRequiredHeaders) + } + + timestamp, err := parseTimestampHeader(msgTimestamp) + if err != nil { + return fmt.Errorf("unable to verify payload, err: %w", err) + } + + if enforceTolerance { + if err := verifyTimestamp(timestamp); err != nil { + return fmt.Errorf("unable to verify payload, err: %w", err) + } + } + + _, expectedSignature, err := wh.sign(msgId, timestamp, payload) + if err != nil { + return fmt.Errorf("unable to verify payload, err: %w", err) + } + + passedSignatures := strings.Split(msgSignature, " ") + for _, versionedSignature := range passedSignatures { + sigParts := strings.Split(versionedSignature, ",") + if len(sigParts) < 2 { + continue + } + + version := sigParts[0] + + if version != "v1" { + continue + } + + signature := []byte(sigParts[1]) + + if hmac.Equal(signature, expectedSignature) { + return nil + } + } + + return fmt.Errorf("unable to verify payload, err: %w", ErrNoMatchingSignature) +} + +func (wh *Webhook) Sign(msgId string, timestamp time.Time, payload []byte) (string, error) { + version, signature, err := wh.sign(msgId, timestamp, payload) + return fmt.Sprintf("%s,%s", version, signature), err +} + +func (wh *Webhook) sign(msgId string, timestamp time.Time, payload []byte) (version string, signature []byte, err error) { + toSign := fmt.Sprintf("%s.%d.%s", msgId, timestamp.Unix(), payload) + + h := hmac.New(sha256.New, wh.key) + h.Write([]byte(toSign)) + sig := make([]byte, base64enc.EncodedLen(h.Size())) + base64enc.Encode(sig, h.Sum(nil)) + + return "v1", sig, nil +} + +func parseTimestampHeader(timestampHeader string) (time.Time, error) { + timeInt, err := strconv.ParseInt(timestampHeader, 10, 64) + if err != nil { + return time.Time{}, fmt.Errorf("unable to parse timestamp header, err: %w", errors.Join(err, ErrInvalidHeaders)) + } + timestamp := time.Unix(timeInt, 0) + return timestamp, nil +} + +func verifyTimestamp(timestamp time.Time) error { + now := time.Now() + + if now.Sub(timestamp) > tolerance { + return ErrMessageTooOld + } + + if timestamp.After(now.Add(tolerance)) { + return ErrMessageTooNew + } + + return nil +} diff --git a/vendor/modules.txt b/vendor/modules.txt index 717f5f7c6..f608f6a51 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -87,19 +87,23 @@ github.com/AzureAD/microsoft-authentication-library-for-go/apps/public # github.com/alecthomas/units v0.0.0-20240927000941-0f3dac36c52b ## explicit; go 1.15 github.com/alecthomas/units -# github.com/anthropics/anthropic-sdk-go v1.37.0 -## explicit; go 1.23.0 +# github.com/anthropics/anthropic-sdk-go v1.67.0 +## explicit; go 1.24 github.com/anthropics/anthropic-sdk-go +github.com/anthropics/anthropic-sdk-go/config github.com/anthropics/anthropic-sdk-go/internal github.com/anthropics/anthropic-sdk-go/internal/apierror github.com/anthropics/anthropic-sdk-go/internal/apiform github.com/anthropics/anthropic-sdk-go/internal/apijson github.com/anthropics/anthropic-sdk-go/internal/apiquery +github.com/anthropics/anthropic-sdk-go/internal/auth github.com/anthropics/anthropic-sdk-go/internal/encoding/json github.com/anthropics/anthropic-sdk-go/internal/encoding/json/sentinel github.com/anthropics/anthropic-sdk-go/internal/encoding/json/shims github.com/anthropics/anthropic-sdk-go/internal/paramutil github.com/anthropics/anthropic-sdk-go/internal/requestconfig +github.com/anthropics/anthropic-sdk-go/internal/sendwindow +github.com/anthropics/anthropic-sdk-go/internal/stainlessheader github.com/anthropics/anthropic-sdk-go/option github.com/anthropics/anthropic-sdk-go/packages/jsonl github.com/anthropics/anthropic-sdk-go/packages/pagination @@ -486,6 +490,9 @@ github.com/hashicorp/go-version # github.com/inconshreveable/mousetrap v1.1.0 ## explicit; go 1.18 github.com/inconshreveable/mousetrap +# github.com/invopop/jsonschema v0.14.0 +## explicit; go 1.24 +github.com/invopop/jsonschema # github.com/jpillora/backoff v1.0.0 ## explicit; go 1.13 github.com/jpillora/backoff @@ -880,6 +887,9 @@ github.com/spf13/cobra # github.com/spf13/pflag v1.0.10 ## explicit; go 1.12 github.com/spf13/pflag +# github.com/standard-webhooks/standard-webhooks/libraries v0.0.1 +## explicit; go 1.21.0 +github.com/standard-webhooks/standard-webhooks/libraries/go # github.com/stretchr/testify v1.11.1 ## explicit; go 1.17 github.com/stretchr/testify/assert