pydantic-claude-code 0.6.2__tar.gz → 0.7.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.1}/PKG-INFO +43 -17
  2. {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.1}/README.md +41 -15
  3. pydantic_claude_code-0.7.1/install.sh +24 -0
  4. {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.1}/pyproject.toml +2 -2
  5. pydantic_claude_code-0.7.1/scripts/sync_gist.sh +25 -0
  6. {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.1}/src/pydantic_ai_claude_code/__init__.py +1 -1
  7. {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.1}/src/pydantic_ai_claude_code/auth.py +60 -4
  8. {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.1}/src/pydantic_ai_claude_code/clai2.py +128 -37
  9. {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.1}/src/pydantic_ai_claude_code/model.py +6 -2
  10. {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.1}/src/pydantic_ai_claude_code/provider.py +10 -3
  11. {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.1}/src/pydantic_ai_claude_code/storage.py +33 -13
  12. {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.1}/src/pydantic_ai_claude_code/updates.py +3 -1
  13. {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.1}/tests/test_clai2.py +166 -7
  14. pydantic_claude_code-0.7.1/tests/test_install.py +70 -0
  15. {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.1}/tests/test_keyring_store.py +14 -0
  16. pydantic_claude_code-0.7.1/tests/test_model.py +59 -0
  17. pydantic_claude_code-0.7.1/tests/test_refresh.py +137 -0
  18. {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.1}/tests/test_storage.py +8 -0
  19. {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.1}/uv.lock +1 -1
  20. pydantic_claude_code-0.6.2/install.sh +0 -27
  21. pydantic_claude_code-0.6.2/tests/test_install.py +0 -80
  22. pydantic_claude_code-0.6.2/tests/test_model.py +0 -32
  23. {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.1}/.github/workflows/ci.yml +0 -0
  24. {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.1}/.github/workflows/publish.yml +0 -0
  25. {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.1}/.gitignore +0 -0
  26. {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.1}/LICENSE +0 -0
  27. {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.1}/examples/basic.py +0 -0
  28. {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.1}/src/pydantic_ai_claude_code/__main__.py +0 -0
  29. {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.1}/src/pydantic_ai_claude_code/config.py +0 -0
  30. {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.1}/src/pydantic_ai_claude_code/credentials.py +0 -0
  31. {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.1}/src/pydantic_ai_claude_code/flow.py +0 -0
  32. {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.1}/src/pydantic_ai_claude_code/py.typed +0 -0
  33. {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.1}/tests/conftest.py +0 -0
  34. {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.1}/tests/test_callback_server.py +0 -0
  35. {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.1}/tests/test_credentials.py +0 -0
  36. {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.1}/tests/test_flow.py +0 -0
  37. {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.1}/tests/test_integration.py +0 -0
  38. {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.1}/tests/test_provider.py +0 -0
  39. {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.1}/tests/test_updates.py +0 -0
@@ -1,8 +1,8 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: pydantic-claude-code
3
- Version: 0.6.2
3
+ Version: 0.7.1
4
4
  Summary: Use your Claude Code subscription from a Pydantic AI Agent or CLAI2, with full tool support
5
- Project-URL: Repository, https://github.com/mpfaffenberger/pydantic-ai-claude-code
5
+ Project-URL: Source, https://gist.github.com/mpfaffenberger/bd75c7b424ffdc6d81645bfe7de822d3
6
6
  Project-URL: Homepage, https://pypi.org/project/pydantic-claude-code/
7
7
  Author: Michael Pfaffenberger
8
8
  License: MIT
@@ -64,23 +64,26 @@ so the stock agent, Coder, and your other plugins all keep working.
64
64
  One line installs the latest release of the plugin, and running it again updates it:
65
65
 
66
66
  ```bash
67
- curl -fsSL https://raw.githubusercontent.com/mpfaffenberger/pydantic-ai-claude-code/main/install.sh | sh
67
+ curl -fsSL https://gist.githubusercontent.com/mpfaffenberger/bd75c7b424ffdc6d81645bfe7de822d3/raw/install.sh | sh
68
68
  ```
69
69
 
70
- To pin a release, pass its tag (`... | sh -s -- v0.6.2`), or pass `main` for
71
- unreleased changes. The script downloads that version of this repo and copies the `src/pydantic_ai_claude_code` folder into CLAI2's
72
- plugins folder as `claude_code`, replacing any older copy. Nothing to
73
- `pip install`: everything the plugin imports (`pydantic-ai` with Anthropic
74
- support, `httpx2`, `keyring`) already ships with CLAI2.
70
+ The plugin is published as a [gist](https://gist.github.com/mpfaffenberger/bd75c7b424ffdc6d81645bfe7de822d3): its files are this repo's
71
+ `src/pydantic_ai_claude_code` folder at the latest release, plus `install.sh`.
72
+ The script downloads the gist and puts its files in CLAI2's plugins folder as
73
+ `claude_code`, replacing any older copy. To pin a release, pass a gist
74
+ revision (`... | sh -s -- REVISION`; the gist's revisions are named after
75
+ releases). Nothing to `pip install`: everything the plugin imports
76
+ (`pydantic-ai` with Anthropic support, `httpx2`, `keyring`) already ships with
77
+ CLAI2.
75
78
 
76
79
  The plugins folder is `$XDG_CONFIG_HOME/pydantic-clai2/plugins/`, which is
77
80
  `~/.config/pydantic-clai2/plugins/` by default on macOS and Linux: the folder
78
- next to CLAI2's `config.db`. To install by hand, copy the folder there yourself:
81
+ next to CLAI2's `config.db`. To install by hand, clone the gist there yourself
82
+ (`git pull` in that folder then updates it):
79
83
 
80
84
  ```bash
81
- git clone --depth 1 https://github.com/mpfaffenberger/pydantic-ai-claude-code /tmp/claude-code-plugin
82
85
  mkdir -p ~/.config/pydantic-clai2/plugins
83
- cp -R /tmp/claude-code-plugin/src/pydantic_ai_claude_code ~/.config/pydantic-clai2/plugins/claude_code
86
+ git clone https://gist.github.com/mpfaffenberger/bd75c7b424ffdc6d81645bfe7de822d3.git ~/.config/pydantic-clai2/plugins/claude_code
84
87
  ```
85
88
 
86
89
  To hack on the plugin, symlink the folder instead of copying it:
@@ -115,7 +118,7 @@ at it: `uv tool install pydantic-clai2 --with pydantic-claude-code`, then
115
118
 
116
119
  ### Sign in
117
120
 
118
- Run `/login claude`. Your browser opens Claude's sign-in page, and CLAI2
121
+ Run `/login claude-code` (it was `/login claude` before 0.7.0). Your browser opens Claude's sign-in page, and CLAI2
119
122
  prints the URL in case it doesn't. On a machine whose browser can't reach CLAI2
120
123
  (over SSH, or a remote box), open that URL on any machine and sign in. The
121
124
  browser then ends on a `http://localhost:.../callback?code=...` page that fails
@@ -125,7 +128,7 @@ Enter. CLAI2 counts the characters instead of echoing the code. Or open the sett
125
128
 
126
129
  ### Pick a model
127
130
 
128
- `/login claude` adds every model in the table above to your model list, so
131
+ `/login claude-code` adds every model in the table above to your model list, so
129
132
  `/model` offers them right away, and `/model_settings` sets thinking mode,
130
133
  effort, and the rest for each. On an older CLAI2, or for a model that isn't
131
134
  listed, open `/add_model` and choose the `claude-code` provider, or type one
@@ -139,6 +142,21 @@ directly:
139
142
  Headless runs work the same way:
140
143
  `clai2 -p "Summarize this repo" -m claude-code:claude-fable-5-1`.
141
144
 
145
+ ### Several accounts
146
+
147
+ On a CLAI2 build with auth profiles, `/login claude-code@NAME` signs in another
148
+ account under the profile `NAME` (lowercase letters, digits, `-` and `_`), and
149
+ `claude-code@NAME:MODEL` runs on it, for example
150
+ `/model claude-code@work:claude-opus-5-5`. Models without `@NAME` keep using
151
+ the default sign-in. Each profile has its own tokens: keyring user name `NAME`,
152
+ or the file `auth-NAME.json` next to `auth.json`. To pool accounts, put them in
153
+ a CLAI2 fallback chain, `/chain NAME MODEL MODEL...`, then `/model chain:NAME`.
154
+ Older CLAI2 builds ignore profiles.
155
+
156
+ On a CLAI2 build with account usage, `/accounts` shows each signed-in account's
157
+ five-hour and weekly usage, read from the endpoint Claude Code's `/usage` uses,
158
+ with the same tokens and refresh as model requests.
159
+
142
160
  ### Settings menu
143
161
 
144
162
  `/plugins configure claude_code`, `C` in `/plugins`, or a bare `/claude_code`
@@ -150,7 +168,8 @@ opens it. Every change is saved right away and applies from the next run.
150
168
  | Credential storage | `auto` (`CLAUDE_CODE_CREDENTIALS`, else keyring, else a file), `keyring`, or `file` | plugin settings (`credentials`) |
151
169
 
152
170
  `/claude_code logout` and `/claude_code status` do the
153
- same without the menu.
171
+ same without the menu; add a profile name (`/claude_code logout work`) for
172
+ another account.
154
173
 
155
174
  ### Where the sign-in lives
156
175
 
@@ -169,7 +188,7 @@ expire. Switching storage does not move an existing sign-in, so sign in again
169
188
  after switching.
170
189
 
171
190
  If a run says `Sign in to Claude Code first` or `Your Claude Code sign-in has
172
- expired`, run `/login claude`. If the
191
+ expired`, run `/login claude-code`. If the
173
192
  plugin fails to load with `cannot import name 'Plugin' from
174
193
  'pydantic_clai2.plugins'`, your CLAI2 predates class-based plugins: upgrade it as described under
175
194
  [Install](#install), or pin plugin 0.5.0.
@@ -182,6 +201,11 @@ provider. Instead of a `claude-code:` model string, construct
182
201
  `ClaudeCodeModel('claude-fable-5-1')` directly; it connects itself to a
183
202
  `ClaudeCodeProvider` by default.
184
203
 
204
+ `ClaudeCodeModel` enables prompt caching with a **1-hour TTL** by default. Override it with
205
+ `settings=AnthropicModelSettings(anthropic_cache="5m")`, or disable default caching with
206
+ `settings=AnthropicModelSettings(anthropic_cache=False)`. Per-request settings take precedence.
207
+ Tool-definition, static-instruction, and latest-tool-call breakpoints use Pydantic AI's caching implementation.
208
+
185
209
  ### Quick start
186
210
 
187
211
  ```python
@@ -312,8 +336,10 @@ uv run pytest
312
336
 
313
337
  To release, bump `version` in `pyproject.toml` and `__version__` in
314
338
  `src/pydantic_ai_claude_code/__init__.py` (a test checks they match), merge, and
315
- push a matching tag (`git tag v0.6.2 && git push origin v0.6.2`). The `Publish` workflow tests,
316
- builds, and uploads it to PyPI with the `PYPI_API_TOKEN` repository secret.
339
+ push a matching tag (`git tag v0.7.1 && git push origin v0.7.1`). The `Publish` workflow tests,
340
+ builds, and uploads it to PyPI with the `PYPI_API_TOKEN` repository secret. Then run
341
+ `scripts/sync_gist.sh` to publish the release to the install gist, which is what the one-liner and the
342
+ update notice install from.
317
343
 
318
344
  The tests never touch your real keychain or token file. They run against a
319
345
  local Messages API stub, including a full CLAI2 turn through the plugin.
@@ -35,23 +35,26 @@ so the stock agent, Coder, and your other plugins all keep working.
35
35
  One line installs the latest release of the plugin, and running it again updates it:
36
36
 
37
37
  ```bash
38
- curl -fsSL https://raw.githubusercontent.com/mpfaffenberger/pydantic-ai-claude-code/main/install.sh | sh
38
+ curl -fsSL https://gist.githubusercontent.com/mpfaffenberger/bd75c7b424ffdc6d81645bfe7de822d3/raw/install.sh | sh
39
39
  ```
40
40
 
41
- To pin a release, pass its tag (`... | sh -s -- v0.6.2`), or pass `main` for
42
- unreleased changes. The script downloads that version of this repo and copies the `src/pydantic_ai_claude_code` folder into CLAI2's
43
- plugins folder as `claude_code`, replacing any older copy. Nothing to
44
- `pip install`: everything the plugin imports (`pydantic-ai` with Anthropic
45
- support, `httpx2`, `keyring`) already ships with CLAI2.
41
+ The plugin is published as a [gist](https://gist.github.com/mpfaffenberger/bd75c7b424ffdc6d81645bfe7de822d3): its files are this repo's
42
+ `src/pydantic_ai_claude_code` folder at the latest release, plus `install.sh`.
43
+ The script downloads the gist and puts its files in CLAI2's plugins folder as
44
+ `claude_code`, replacing any older copy. To pin a release, pass a gist
45
+ revision (`... | sh -s -- REVISION`; the gist's revisions are named after
46
+ releases). Nothing to `pip install`: everything the plugin imports
47
+ (`pydantic-ai` with Anthropic support, `httpx2`, `keyring`) already ships with
48
+ CLAI2.
46
49
 
47
50
  The plugins folder is `$XDG_CONFIG_HOME/pydantic-clai2/plugins/`, which is
48
51
  `~/.config/pydantic-clai2/plugins/` by default on macOS and Linux: the folder
49
- next to CLAI2's `config.db`. To install by hand, copy the folder there yourself:
52
+ next to CLAI2's `config.db`. To install by hand, clone the gist there yourself
53
+ (`git pull` in that folder then updates it):
50
54
 
51
55
  ```bash
52
- git clone --depth 1 https://github.com/mpfaffenberger/pydantic-ai-claude-code /tmp/claude-code-plugin
53
56
  mkdir -p ~/.config/pydantic-clai2/plugins
54
- cp -R /tmp/claude-code-plugin/src/pydantic_ai_claude_code ~/.config/pydantic-clai2/plugins/claude_code
57
+ git clone https://gist.github.com/mpfaffenberger/bd75c7b424ffdc6d81645bfe7de822d3.git ~/.config/pydantic-clai2/plugins/claude_code
55
58
  ```
56
59
 
57
60
  To hack on the plugin, symlink the folder instead of copying it:
@@ -86,7 +89,7 @@ at it: `uv tool install pydantic-clai2 --with pydantic-claude-code`, then
86
89
 
87
90
  ### Sign in
88
91
 
89
- Run `/login claude`. Your browser opens Claude's sign-in page, and CLAI2
92
+ Run `/login claude-code` (it was `/login claude` before 0.7.0). Your browser opens Claude's sign-in page, and CLAI2
90
93
  prints the URL in case it doesn't. On a machine whose browser can't reach CLAI2
91
94
  (over SSH, or a remote box), open that URL on any machine and sign in. The
92
95
  browser then ends on a `http://localhost:.../callback?code=...` page that fails
@@ -96,7 +99,7 @@ Enter. CLAI2 counts the characters instead of echoing the code. Or open the sett
96
99
 
97
100
  ### Pick a model
98
101
 
99
- `/login claude` adds every model in the table above to your model list, so
102
+ `/login claude-code` adds every model in the table above to your model list, so
100
103
  `/model` offers them right away, and `/model_settings` sets thinking mode,
101
104
  effort, and the rest for each. On an older CLAI2, or for a model that isn't
102
105
  listed, open `/add_model` and choose the `claude-code` provider, or type one
@@ -110,6 +113,21 @@ directly:
110
113
  Headless runs work the same way:
111
114
  `clai2 -p "Summarize this repo" -m claude-code:claude-fable-5-1`.
112
115
 
116
+ ### Several accounts
117
+
118
+ On a CLAI2 build with auth profiles, `/login claude-code@NAME` signs in another
119
+ account under the profile `NAME` (lowercase letters, digits, `-` and `_`), and
120
+ `claude-code@NAME:MODEL` runs on it, for example
121
+ `/model claude-code@work:claude-opus-5-5`. Models without `@NAME` keep using
122
+ the default sign-in. Each profile has its own tokens: keyring user name `NAME`,
123
+ or the file `auth-NAME.json` next to `auth.json`. To pool accounts, put them in
124
+ a CLAI2 fallback chain, `/chain NAME MODEL MODEL...`, then `/model chain:NAME`.
125
+ Older CLAI2 builds ignore profiles.
126
+
127
+ On a CLAI2 build with account usage, `/accounts` shows each signed-in account's
128
+ five-hour and weekly usage, read from the endpoint Claude Code's `/usage` uses,
129
+ with the same tokens and refresh as model requests.
130
+
113
131
  ### Settings menu
114
132
 
115
133
  `/plugins configure claude_code`, `C` in `/plugins`, or a bare `/claude_code`
@@ -121,7 +139,8 @@ opens it. Every change is saved right away and applies from the next run.
121
139
  | Credential storage | `auto` (`CLAUDE_CODE_CREDENTIALS`, else keyring, else a file), `keyring`, or `file` | plugin settings (`credentials`) |
122
140
 
123
141
  `/claude_code logout` and `/claude_code status` do the
124
- same without the menu.
142
+ same without the menu; add a profile name (`/claude_code logout work`) for
143
+ another account.
125
144
 
126
145
  ### Where the sign-in lives
127
146
 
@@ -140,7 +159,7 @@ expire. Switching storage does not move an existing sign-in, so sign in again
140
159
  after switching.
141
160
 
142
161
  If a run says `Sign in to Claude Code first` or `Your Claude Code sign-in has
143
- expired`, run `/login claude`. If the
162
+ expired`, run `/login claude-code`. If the
144
163
  plugin fails to load with `cannot import name 'Plugin' from
145
164
  'pydantic_clai2.plugins'`, your CLAI2 predates class-based plugins: upgrade it as described under
146
165
  [Install](#install), or pin plugin 0.5.0.
@@ -153,6 +172,11 @@ provider. Instead of a `claude-code:` model string, construct
153
172
  `ClaudeCodeModel('claude-fable-5-1')` directly; it connects itself to a
154
173
  `ClaudeCodeProvider` by default.
155
174
 
175
+ `ClaudeCodeModel` enables prompt caching with a **1-hour TTL** by default. Override it with
176
+ `settings=AnthropicModelSettings(anthropic_cache="5m")`, or disable default caching with
177
+ `settings=AnthropicModelSettings(anthropic_cache=False)`. Per-request settings take precedence.
178
+ Tool-definition, static-instruction, and latest-tool-call breakpoints use Pydantic AI's caching implementation.
179
+
156
180
  ### Quick start
157
181
 
158
182
  ```python
@@ -283,8 +307,10 @@ uv run pytest
283
307
 
284
308
  To release, bump `version` in `pyproject.toml` and `__version__` in
285
309
  `src/pydantic_ai_claude_code/__init__.py` (a test checks they match), merge, and
286
- push a matching tag (`git tag v0.6.2 && git push origin v0.6.2`). The `Publish` workflow tests,
287
- builds, and uploads it to PyPI with the `PYPI_API_TOKEN` repository secret.
310
+ push a matching tag (`git tag v0.7.1 && git push origin v0.7.1`). The `Publish` workflow tests,
311
+ builds, and uploads it to PyPI with the `PYPI_API_TOKEN` repository secret. Then run
312
+ `scripts/sync_gist.sh` to publish the release to the install gist, which is what the one-liner and the
313
+ update notice install from.
288
314
 
289
315
  The tests never touch your real keychain or token file. They run against a
290
316
  local Messages API stub, including a full CLAI2 turn through the plugin.
@@ -0,0 +1,24 @@
1
+ #!/bin/sh
2
+ # Install or update the Claude Code plugin for CLAI2 from its gist, which holds the latest release
3
+ # (pass a gist revision to pin one):
4
+ # curl -fsSL https://gist.githubusercontent.com/mpfaffenberger/bd75c7b424ffdc6d81645bfe7de822d3/raw/install.sh | sh
5
+ set -eu
6
+
7
+ gist="bd75c7b424ffdc6d81645bfe7de822d3"
8
+ revision="${1:-HEAD}"
9
+ plugins="${XDG_CONFIG_HOME:-$HOME/.config}/pydantic-clai2/plugins"
10
+ target="$plugins/claude_code"
11
+
12
+ download=$(mktemp -d)
13
+ trap 'rm -rf "$download"' EXIT
14
+
15
+ curl -fsSL "https://gist.github.com/mpfaffenberger/$gist/archive/$revision.tar.gz" | tar -xz -C "$download"
16
+ folder=$(echo "$download"/*)
17
+ rm -f "$folder/install.sh"
18
+ mkdir -p "$plugins"
19
+ rm -rf "$target"
20
+ mv "$folder" "$target"
21
+
22
+ version=$(grep -o '^__version__ = "[^"]*"' "$target/__init__.py" | cut -d '"' -f 2)
23
+ echo "Installed the Claude Code plugin (v$version) to $target."
24
+ echo "Start clai2, sign in with /login claude-code, then /model claude-code:claude-opus-5-5."
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "pydantic-claude-code"
7
- version = "0.6.2"
7
+ version = "0.7.1"
8
8
  description = "Use your Claude Code subscription from a Pydantic AI Agent or CLAI2, with full tool support"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10,<3.15"
@@ -26,7 +26,7 @@ classifiers = [
26
26
  ]
27
27
 
28
28
  [project.urls]
29
- Repository = "https://github.com/mpfaffenberger/pydantic-ai-claude-code"
29
+ Source = "https://gist.github.com/mpfaffenberger/bd75c7b424ffdc6d81645bfe7de822d3"
30
30
  Homepage = "https://pypi.org/project/pydantic-claude-code/"
31
31
 
32
32
  [tool.hatch.build.targets.wheel]
@@ -0,0 +1,25 @@
1
+ #!/bin/sh
2
+ # Publish the plugin folder and install.sh to the install gist, after tagging a release:
3
+ # scripts/sync_gist.sh
4
+ # Mirrors src/pydantic_ai_claude_code (minus caches and the empty py.typed, which gists reject), so
5
+ # files removed here leave the gist too. Needs `gh auth login`, which git uses to push to the gist.
6
+ set -eu
7
+
8
+ gist="bd75c7b424ffdc6d81645bfe7de822d3"
9
+ root=$(cd "$(dirname "$0")/.." && pwd)
10
+ clone=$(mktemp -d)
11
+ trap 'rm -rf "$clone"' EXIT
12
+
13
+ gh auth setup-git
14
+ git clone -q "https://gist.github.com/$gist.git" "$clone"
15
+ git -C "$clone" rm -q --ignore-unmatch '*'
16
+ cp "$root"/src/pydantic_ai_claude_code/*.py "$root/install.sh" "$clone/"
17
+ git -C "$clone" add -A
18
+ version=$(grep -o '^__version__ = "[^"]*"' "$root/src/pydantic_ai_claude_code/__init__.py" | cut -d '"' -f 2)
19
+ if git -C "$clone" diff --cached --quiet; then
20
+ echo "The gist already holds v$version."
21
+ exit 0
22
+ fi
23
+ git -C "$clone" commit -q -m "v$version"
24
+ git -C "$clone" push -q
25
+ echo "Published v$version to https://gist.github.com/mpfaffenberger/$gist."
@@ -26,7 +26,7 @@ from .model import ClaudeCodeModel
26
26
  from .provider import ClaudeCodeProvider
27
27
  from .storage import ClaudeCodeTokenStore, KeyringTokenStore, default_auth_path, default_store
28
28
 
29
- __version__ = "0.6.2"
29
+ __version__ = "0.7.1"
30
30
  """Matches `version` in pyproject.toml (a test checks), so a copied folder knows its release."""
31
31
 
32
32
 
@@ -3,8 +3,11 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import asyncio
6
+ import os
6
7
  import time
7
- from collections.abc import AsyncGenerator, Awaitable, Callable
8
+ from collections.abc import AsyncGenerator, AsyncIterator, Awaitable, Callable
9
+ from contextlib import asynccontextmanager
10
+ from pathlib import Path
8
11
 
9
12
  import httpx2
10
13
 
@@ -15,6 +18,12 @@ from .credentials import ClaudeCodeCredentials
15
18
  from .flow import refresh_credentials
16
19
 
17
20
  CredentialsRefreshCallback = Callable[[ClaudeCodeCredentials], Awaitable[None]]
21
+ CredentialsReload = Callable[[], ClaudeCodeCredentials | None]
22
+
23
+ try:
24
+ import fcntl
25
+ except ImportError: # pragma: no cover - Windows: no cross-process lock, the store re-read still helps
26
+ fcntl = None
18
27
 
19
28
 
20
29
  class ClaudeCodeCredentialsPersistenceError(UserError):
@@ -32,7 +41,7 @@ class ClaudeCodeSignInExpiredError(UserError):
32
41
  """`reason` is why the refresh failed, as the token endpoint put it."""
33
42
  super().__init__(
34
43
  f"Your Claude Code sign-in has expired or was revoked; sign in again. ({reason}) "
35
- "In CLAI2 run /login claude; from Python, `await pydantic_ai_claude_code.login()` "
44
+ "In CLAI2 run /login claude-code; from Python, `await pydantic_ai_claude_code.login()` "
36
45
  "or `python -m pydantic_ai_claude_code login`."
37
46
  )
38
47
 
@@ -43,23 +52,70 @@ def _expires_soon(credentials: ClaudeCodeCredentials) -> bool:
43
52
  return time.time() + 30 >= credentials.expires_at.timestamp()
44
53
 
45
54
 
55
+ @asynccontextmanager
56
+ async def _exclusive(path: Path | None) -> AsyncIterator[None]:
57
+ """Hold an exclusive `flock` on `path` across processes; a no-op without a path or `fcntl`."""
58
+ if path is None or fcntl is None:
59
+ yield
60
+ return
61
+ path.parent.mkdir(parents=True, exist_ok=True)
62
+ fd = os.open(path, os.O_RDWR | os.O_CREAT, 0o600)
63
+ try:
64
+ await asyncio.to_thread(fcntl.flock, fd, fcntl.LOCK_EX)
65
+ yield
66
+ finally:
67
+ os.close(fd) # closing the descriptor releases the lock
68
+
69
+
46
70
  class _ClaudeCodeAuth(httpx2.Auth):
71
+ """Bearer auth that refreshes the token pair, coordinating with every other holder of the same sign-in.
72
+
73
+ Anthropic rotates the refresh token on each refresh and revokes the old one, so a process still holding
74
+ the old one gets `invalid_grant`. With `reload` (the token store's `load`), a refresh first adopts a
75
+ pair another process already saved, and `lock_path` serializes the reload, refresh, and save across
76
+ processes, so only one of them spends a given refresh token.
77
+ """
78
+
47
79
  requires_response_body = True
48
80
 
49
- def __init__(self, credentials: ClaudeCodeCredentials, callback: CredentialsRefreshCallback | None = None) -> None:
81
+ def __init__(
82
+ self,
83
+ credentials: ClaudeCodeCredentials,
84
+ callback: CredentialsRefreshCallback | None = None,
85
+ *,
86
+ reload: CredentialsReload | None = None,
87
+ lock_path: Path | None = None,
88
+ ) -> None:
50
89
  self.credentials = credentials
51
90
  self.callback = callback
91
+ self.reload = reload
92
+ self.lock_path = lock_path
52
93
  self.revision = 0
53
94
  self.lock = asyncio.Lock()
54
95
  self.refresh_client = httpx2.AsyncClient()
55
96
 
97
+ async def _adopt_stored(self) -> bool:
98
+ """Switch to the stored pair when another holder saved a newer one; whether it did."""
99
+ if self.reload is None:
100
+ return False
101
+ stored = await asyncio.to_thread(self.reload)
102
+ if stored is None or stored == self.credentials:
103
+ return False
104
+ self.credentials = stored
105
+ self.revision += 1
106
+ return True
107
+
56
108
  async def _refresh(self, used_revision: int) -> None:
57
- async with self.lock:
109
+ async with self.lock, _exclusive(self.lock_path):
58
110
  if self.revision != used_revision:
59
111
  return
112
+ if await self._adopt_stored() and not _expires_soon(self.credentials):
113
+ return
60
114
  try:
61
115
  updated = await refresh_credentials(self.credentials, http_client=self.refresh_client)
62
116
  except UserError as exc:
117
+ if await self._adopt_stored():
118
+ return # rotated by a holder outside the lock: another machine, or Windows
63
119
  raise ClaudeCodeSignInExpiredError(str(exc)) from exc
64
120
  self.credentials = updated
65
121
  self.revision += 1