pydantic-claude-code 0.7.0__tar.gz → 0.7.2__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.
- {pydantic_claude_code-0.7.0 → pydantic_claude_code-0.7.2}/PKG-INFO +22 -13
- {pydantic_claude_code-0.7.0 → pydantic_claude_code-0.7.2}/README.md +20 -11
- pydantic_claude_code-0.7.2/install.sh +24 -0
- {pydantic_claude_code-0.7.0 → pydantic_claude_code-0.7.2}/pyproject.toml +2 -2
- pydantic_claude_code-0.7.2/scripts/sync_gist.sh +25 -0
- {pydantic_claude_code-0.7.0 → pydantic_claude_code-0.7.2}/src/pydantic_ai_claude_code/__init__.py +1 -1
- {pydantic_claude_code-0.7.0 → pydantic_claude_code-0.7.2}/src/pydantic_ai_claude_code/auth.py +59 -3
- {pydantic_claude_code-0.7.0 → pydantic_claude_code-0.7.2}/src/pydantic_ai_claude_code/clai2.py +52 -3
- {pydantic_claude_code-0.7.0 → pydantic_claude_code-0.7.2}/src/pydantic_ai_claude_code/model.py +31 -23
- {pydantic_claude_code-0.7.0 → pydantic_claude_code-0.7.2}/src/pydantic_ai_claude_code/provider.py +10 -3
- {pydantic_claude_code-0.7.0 → pydantic_claude_code-0.7.2}/src/pydantic_ai_claude_code/storage.py +5 -0
- {pydantic_claude_code-0.7.0 → pydantic_claude_code-0.7.2}/src/pydantic_ai_claude_code/updates.py +3 -1
- {pydantic_claude_code-0.7.0 → pydantic_claude_code-0.7.2}/tests/test_clai2.py +88 -0
- pydantic_claude_code-0.7.2/tests/test_install.py +70 -0
- pydantic_claude_code-0.7.2/tests/test_model.py +94 -0
- pydantic_claude_code-0.7.2/tests/test_refresh.py +137 -0
- {pydantic_claude_code-0.7.0 → pydantic_claude_code-0.7.2}/uv.lock +1 -1
- pydantic_claude_code-0.7.0/install.sh +0 -27
- pydantic_claude_code-0.7.0/tests/test_install.py +0 -80
- pydantic_claude_code-0.7.0/tests/test_model.py +0 -59
- {pydantic_claude_code-0.7.0 → pydantic_claude_code-0.7.2}/.github/workflows/ci.yml +0 -0
- {pydantic_claude_code-0.7.0 → pydantic_claude_code-0.7.2}/.github/workflows/publish.yml +0 -0
- {pydantic_claude_code-0.7.0 → pydantic_claude_code-0.7.2}/.gitignore +0 -0
- {pydantic_claude_code-0.7.0 → pydantic_claude_code-0.7.2}/LICENSE +0 -0
- {pydantic_claude_code-0.7.0 → pydantic_claude_code-0.7.2}/examples/basic.py +0 -0
- {pydantic_claude_code-0.7.0 → pydantic_claude_code-0.7.2}/src/pydantic_ai_claude_code/__main__.py +0 -0
- {pydantic_claude_code-0.7.0 → pydantic_claude_code-0.7.2}/src/pydantic_ai_claude_code/config.py +0 -0
- {pydantic_claude_code-0.7.0 → pydantic_claude_code-0.7.2}/src/pydantic_ai_claude_code/credentials.py +0 -0
- {pydantic_claude_code-0.7.0 → pydantic_claude_code-0.7.2}/src/pydantic_ai_claude_code/flow.py +0 -0
- {pydantic_claude_code-0.7.0 → pydantic_claude_code-0.7.2}/src/pydantic_ai_claude_code/py.typed +0 -0
- {pydantic_claude_code-0.7.0 → pydantic_claude_code-0.7.2}/tests/conftest.py +0 -0
- {pydantic_claude_code-0.7.0 → pydantic_claude_code-0.7.2}/tests/test_callback_server.py +0 -0
- {pydantic_claude_code-0.7.0 → pydantic_claude_code-0.7.2}/tests/test_credentials.py +0 -0
- {pydantic_claude_code-0.7.0 → pydantic_claude_code-0.7.2}/tests/test_flow.py +0 -0
- {pydantic_claude_code-0.7.0 → pydantic_claude_code-0.7.2}/tests/test_integration.py +0 -0
- {pydantic_claude_code-0.7.0 → pydantic_claude_code-0.7.2}/tests/test_keyring_store.py +0 -0
- {pydantic_claude_code-0.7.0 → pydantic_claude_code-0.7.2}/tests/test_provider.py +0 -0
- {pydantic_claude_code-0.7.0 → pydantic_claude_code-0.7.2}/tests/test_storage.py +0 -0
- {pydantic_claude_code-0.7.0 → pydantic_claude_code-0.7.2}/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.7.
|
|
3
|
+
Version: 0.7.2
|
|
4
4
|
Summary: Use your Claude Code subscription from a Pydantic AI Agent or CLAI2, with full tool support
|
|
5
|
-
Project-URL:
|
|
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://
|
|
67
|
+
curl -fsSL https://gist.githubusercontent.com/mpfaffenberger/bd75c7b424ffdc6d81645bfe7de822d3/raw/install.sh | sh
|
|
68
68
|
```
|
|
69
69
|
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
`
|
|
74
|
-
|
|
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,
|
|
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
|
-
|
|
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:
|
|
@@ -150,6 +153,10 @@ or the file `auth-NAME.json` next to `auth.json`. To pool accounts, put them in
|
|
|
150
153
|
a CLAI2 fallback chain, `/chain NAME MODEL MODEL...`, then `/model chain:NAME`.
|
|
151
154
|
Older CLAI2 builds ignore profiles.
|
|
152
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
|
+
|
|
153
160
|
### Settings menu
|
|
154
161
|
|
|
155
162
|
`/plugins configure claude_code`, `C` in `/plugins`, or a bare `/claude_code`
|
|
@@ -329,8 +336,10 @@ uv run pytest
|
|
|
329
336
|
|
|
330
337
|
To release, bump `version` in `pyproject.toml` and `__version__` in
|
|
331
338
|
`src/pydantic_ai_claude_code/__init__.py` (a test checks they match), merge, and
|
|
332
|
-
push a matching tag (`git tag v0.7.
|
|
333
|
-
builds, and uploads it to PyPI with the `PYPI_API_TOKEN` repository secret.
|
|
339
|
+
push a matching tag (`git tag v0.7.2 && git push origin v0.7.2`). 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.
|
|
334
343
|
|
|
335
344
|
The tests never touch your real keychain or token file. They run against a
|
|
336
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://
|
|
38
|
+
curl -fsSL https://gist.githubusercontent.com/mpfaffenberger/bd75c7b424ffdc6d81645bfe7de822d3/raw/install.sh | sh
|
|
39
39
|
```
|
|
40
40
|
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
`
|
|
45
|
-
|
|
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,
|
|
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
|
-
|
|
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:
|
|
@@ -121,6 +124,10 @@ or the file `auth-NAME.json` next to `auth.json`. To pool accounts, put them in
|
|
|
121
124
|
a CLAI2 fallback chain, `/chain NAME MODEL MODEL...`, then `/model chain:NAME`.
|
|
122
125
|
Older CLAI2 builds ignore profiles.
|
|
123
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
|
+
|
|
124
131
|
### Settings menu
|
|
125
132
|
|
|
126
133
|
`/plugins configure claude_code`, `C` in `/plugins`, or a bare `/claude_code`
|
|
@@ -300,8 +307,10 @@ uv run pytest
|
|
|
300
307
|
|
|
301
308
|
To release, bump `version` in `pyproject.toml` and `__version__` in
|
|
302
309
|
`src/pydantic_ai_claude_code/__init__.py` (a test checks they match), merge, and
|
|
303
|
-
push a matching tag (`git tag v0.7.
|
|
304
|
-
builds, and uploads it to PyPI with the `PYPI_API_TOKEN` repository secret.
|
|
310
|
+
push a matching tag (`git tag v0.7.2 && git push origin v0.7.2`). 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.
|
|
305
314
|
|
|
306
315
|
The tests never touch your real keychain or token file. They run against a
|
|
307
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.7.
|
|
7
|
+
version = "0.7.2"
|
|
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
|
-
|
|
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."
|
{pydantic_claude_code-0.7.0 → pydantic_claude_code-0.7.2}/src/pydantic_ai_claude_code/__init__.py
RENAMED
|
@@ -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.7.
|
|
29
|
+
__version__ = "0.7.2"
|
|
30
30
|
"""Matches `version` in pyproject.toml (a test checks), so a copied folder knows its release."""
|
|
31
31
|
|
|
32
32
|
|
{pydantic_claude_code-0.7.0 → pydantic_claude_code-0.7.2}/src/pydantic_ai_claude_code/auth.py
RENAMED
|
@@ -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):
|
|
@@ -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__(
|
|
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
|
{pydantic_claude_code-0.7.0 → pydantic_claude_code-0.7.2}/src/pydantic_ai_claude_code/clai2.py
RENAMED
|
@@ -12,16 +12,20 @@ Plugin settings, which are plaintext SQLite, hold only the storage choice.
|
|
|
12
12
|
|
|
13
13
|
On a CLAI2 build with auth profiles, `/login claude-code@PROFILE` signs in another account, kept apart from the
|
|
14
14
|
default one, and `claude-code@PROFILE:MODEL` runs on it. A CLAI2 fallback chain can pool those accounts.
|
|
15
|
+
On a CLAI2 build with account usage, `/accounts` shows each account's five-hour and weekly usage.
|
|
15
16
|
"""
|
|
16
17
|
|
|
17
18
|
from __future__ import annotations
|
|
18
19
|
|
|
19
20
|
import asyncio
|
|
20
21
|
import dataclasses
|
|
22
|
+
import importlib
|
|
21
23
|
import sys
|
|
22
24
|
from collections.abc import Callable, Sequence
|
|
23
|
-
from
|
|
25
|
+
from datetime import datetime
|
|
26
|
+
from typing import IO, Any, cast, get_args
|
|
24
27
|
|
|
28
|
+
from anthropic import APIError
|
|
25
29
|
from pydantic import BaseModel, ConfigDict, Field, ValidationError
|
|
26
30
|
from pydantic_ai.exceptions import UserError
|
|
27
31
|
from pydantic_clai2.commands import Command
|
|
@@ -168,6 +172,10 @@ class Providers:
|
|
|
168
172
|
|
|
169
173
|
def model(self, name: str, source: ClaudeCodeConfig, profile: str | None = None) -> ClaudeCodeModel:
|
|
170
174
|
"""Build `name` on the stored sign-in, raising `UserError` with setup steps when there is none."""
|
|
175
|
+
return ClaudeCodeModel(name, provider=self.provider(source, profile))
|
|
176
|
+
|
|
177
|
+
def provider(self, source: ClaudeCodeConfig, profile: str | None = None) -> ClaudeCodeProvider:
|
|
178
|
+
"""The provider for the stored sign-in, shared by models and usage checks."""
|
|
171
179
|
key = (source.settings.credentials, profile)
|
|
172
180
|
store = source.store(profile)
|
|
173
181
|
credentials = store.load()
|
|
@@ -176,7 +184,44 @@ class Providers:
|
|
|
176
184
|
provider = self._cached.get(key)
|
|
177
185
|
if provider is None or provider.credentials != credentials:
|
|
178
186
|
provider = self._cached[key] = ClaudeCodeProvider(credentials, store=store)
|
|
179
|
-
return
|
|
187
|
+
return provider
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
USAGE_PATH = "/api/oauth/usage"
|
|
191
|
+
"""What Claude Code's `/usage` reads. The provider's auth signs and refreshes the request like a model call."""
|
|
192
|
+
|
|
193
|
+
USAGE_WINDOWS = {"five_hour": "5h", "seven_day": "7d", "seven_day_opus": "7d opus", "seven_day_sonnet": "7d sonnet"}
|
|
194
|
+
"""The windows CLAI2's `/accounts` shows, by the usage response's key; ones the plan lacks come back null."""
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
class _UsageWindow(BaseModel):
|
|
198
|
+
utilization: float
|
|
199
|
+
resets_at: datetime | None = None
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _usage_types() -> tuple[Any, Any]:
|
|
203
|
+
"""CLAI2's `AccountUsage` and `UsageWindow`; only builds that offer `PluginLogin.usage` ask for usage."""
|
|
204
|
+
plugins = importlib.import_module("pydantic_clai2.plugins")
|
|
205
|
+
return plugins.AccountUsage, plugins.UsageWindow
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
async def account_usage(provider: ClaudeCodeProvider) -> Any:
|
|
209
|
+
"""The subscription's five-hour and weekly windows, as CLAI2's `AccountUsage`."""
|
|
210
|
+
try:
|
|
211
|
+
body = await provider.client.with_options(max_retries=0, timeout=10).get(USAGE_PATH, cast_to=object)
|
|
212
|
+
except APIError as exc:
|
|
213
|
+
raise UserError(f"Claude Code usage unavailable: {exc.message}") from None
|
|
214
|
+
if not isinstance(body, dict):
|
|
215
|
+
raise UserError("Claude Code returned usage the plugin cannot read.")
|
|
216
|
+
usage_type, window_type = _usage_types()
|
|
217
|
+
windows: list[Any] = []
|
|
218
|
+
for key, label in USAGE_WINDOWS.items():
|
|
219
|
+
try:
|
|
220
|
+
window = _UsageWindow.model_validate(cast("dict[str, object]", body).get(key))
|
|
221
|
+
except ValidationError:
|
|
222
|
+
continue # absent, null, or a shape this version does not know
|
|
223
|
+
windows.append(window_type(label=label, used_percent=window.utilization, resets_at=window.resets_at))
|
|
224
|
+
return usage_type(windows=tuple(windows))
|
|
180
225
|
|
|
181
226
|
|
|
182
227
|
def status(source: ClaudeCodeConfig, profile: str | None = None) -> str:
|
|
@@ -301,10 +346,14 @@ class ClaudeCodePlugin(Plugin[ClaudeCodeSettings]):
|
|
|
301
346
|
name=LOGIN,
|
|
302
347
|
handler=self._sign_in,
|
|
303
348
|
models=self.provider.names,
|
|
304
|
-
**_supported(PluginLogin, profile_handler=self._sign_in_profile),
|
|
349
|
+
**_supported(PluginLogin, profile_handler=self._sign_in_profile, usage=self._usage),
|
|
305
350
|
),
|
|
306
351
|
)
|
|
307
352
|
|
|
353
|
+
async def _usage(self, profile: str | None) -> Any:
|
|
354
|
+
provider = await asyncio.to_thread(self._providers.provider, self.source, profile)
|
|
355
|
+
return await account_usage(provider)
|
|
356
|
+
|
|
308
357
|
async def _sign_in(self) -> str:
|
|
309
358
|
return await sign_in(self.source, self._show_url)
|
|
310
359
|
|
{pydantic_claude_code-0.7.0 → pydantic_claude_code-0.7.2}/src/pydantic_ai_claude_code/model.py
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"""The Claude Code model: an `AnthropicModel` with the Claude Code persona
|
|
1
|
+
"""The Claude Code model: an `AnthropicModel` whose system prompt always opens with the Claude Code persona."""
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
@@ -6,9 +6,10 @@ from collections.abc import AsyncGenerator, Iterator
|
|
|
6
6
|
from contextlib import asynccontextmanager, contextmanager
|
|
7
7
|
from typing import Any
|
|
8
8
|
|
|
9
|
+
from anthropic.types.beta import BetaMessageParam, BetaTextBlockParam
|
|
9
10
|
from pydantic_ai import RunContext
|
|
10
11
|
from pydantic_ai.exceptions import ModelAPIError
|
|
11
|
-
from pydantic_ai.messages import ModelMessage,
|
|
12
|
+
from pydantic_ai.messages import ModelMessage, ModelResponse
|
|
12
13
|
from pydantic_ai.models import ModelRequestParameters, StreamedResponse
|
|
13
14
|
from pydantic_ai.models.anthropic import AnthropicModel, AnthropicModelSettings
|
|
14
15
|
from pydantic_ai.providers import Provider
|
|
@@ -21,10 +22,8 @@ from .auth import ClaudeCodeSignInExpiredError
|
|
|
21
22
|
class ClaudeCodeModel(AnthropicModel):
|
|
22
23
|
"""AnthropicModel whose system prompt opens with the Claude Code persona.
|
|
23
24
|
|
|
24
|
-
The subscription backend expects the
|
|
25
|
-
|
|
26
|
-
once it's in history it stays, and repeated `prepare_messages` calls don't
|
|
27
|
-
duplicate it.
|
|
25
|
+
The subscription backend expects the persona as the first `system` block, on its own. That is enforced
|
|
26
|
+
on every request as it is built, not in message history, which compaction rewrites: see `_persona_first`.
|
|
28
27
|
"""
|
|
29
28
|
|
|
30
29
|
def __init__(
|
|
@@ -51,12 +50,14 @@ class ClaudeCodeModel(AnthropicModel):
|
|
|
51
50
|
)
|
|
52
51
|
super().__init__(model_name, provider=provider, settings={**defaults, **(settings or {})}, **kwargs)
|
|
53
52
|
|
|
54
|
-
def
|
|
53
|
+
async def _map_message(
|
|
55
54
|
self,
|
|
56
55
|
messages: list[ModelMessage],
|
|
57
|
-
model_request_parameters
|
|
58
|
-
|
|
59
|
-
|
|
56
|
+
model_request_parameters: ModelRequestParameters,
|
|
57
|
+
model_settings: AnthropicModelSettings,
|
|
58
|
+
) -> tuple[str | list[BetaTextBlockParam], list[BetaMessageParam]]:
|
|
59
|
+
system, anthropic_messages = await super()._map_message(messages, model_request_parameters, model_settings)
|
|
60
|
+
return _persona_first(system), anthropic_messages
|
|
60
61
|
|
|
61
62
|
async def request(
|
|
62
63
|
self,
|
|
@@ -96,16 +97,23 @@ def _surface_expired_sign_in() -> Iterator[None]:
|
|
|
96
97
|
raise
|
|
97
98
|
|
|
98
99
|
|
|
99
|
-
def
|
|
100
|
-
"""
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
100
|
+
def _persona_first(system: str | list[BetaTextBlockParam]) -> list[BetaTextBlockParam]:
|
|
101
|
+
"""`system` as blocks, the first being the persona alone and no other block repeating it.
|
|
102
|
+
|
|
103
|
+
History cannot be trusted to keep the persona in place: `AnthropicModel` joins all of a run's opening
|
|
104
|
+
`SystemPromptPart`s into one block, and compaction rewrites them, which once left a conversation summary
|
|
105
|
+
inside the persona's block. So every request is fixed up here, whatever its history holds. A cache
|
|
106
|
+
breakpoint on a block that held only the persona stays with the persona.
|
|
107
|
+
"""
|
|
108
|
+
persona = BetaTextBlockParam(type="text", text=config.CLAUDE_CODE_SYSTEM_PROMPT)
|
|
109
|
+
rest: list[BetaTextBlockParam] = []
|
|
110
|
+
for block in [BetaTextBlockParam(type="text", text=system)] if isinstance(system, str) else system:
|
|
111
|
+
pieces = (piece.strip() for piece in block["text"].split(config.CLAUDE_CODE_SYSTEM_PROMPT))
|
|
112
|
+
text = "\n\n".join(piece for piece in pieces if piece)
|
|
113
|
+
if text:
|
|
114
|
+
kept = block.copy()
|
|
115
|
+
kept["text"] = text
|
|
116
|
+
rest.append(kept)
|
|
117
|
+
elif "cache_control" in block:
|
|
118
|
+
(rest[-1] if rest else persona)["cache_control"] = block["cache_control"]
|
|
119
|
+
return [persona, *rest]
|
{pydantic_claude_code-0.7.0 → pydantic_claude_code-0.7.2}/src/pydantic_ai_claude_code/provider.py
RENAMED
|
@@ -12,7 +12,7 @@ from pydantic_ai.providers.anthropic import AnthropicProvider
|
|
|
12
12
|
from . import config
|
|
13
13
|
from .auth import CredentialsRefreshCallback, _ClaudeCodeAuth
|
|
14
14
|
from .credentials import ClaudeCodeCredentials
|
|
15
|
-
from .storage import TokenStore, default_store
|
|
15
|
+
from .storage import TokenStore, default_store, refresh_lock_path
|
|
16
16
|
|
|
17
17
|
|
|
18
18
|
class ClaudeCodeProvider(AnthropicProvider):
|
|
@@ -43,7 +43,9 @@ class ClaudeCodeProvider(AnthropicProvider):
|
|
|
43
43
|
the store (which defaults to the OS keyring, falling back to a file).
|
|
44
44
|
store: Token store used to persist refreshed credentials. When
|
|
45
45
|
credentials are loaded from the store, refreshes are persisted
|
|
46
|
-
back to it automatically.
|
|
46
|
+
back to it automatically. With a store, a refresh first adopts
|
|
47
|
+
tokens another process saved, under a lock all processes share,
|
|
48
|
+
since each refresh revokes the previous refresh token.
|
|
47
49
|
on_credentials_refresh: Optional callback in place of automatic
|
|
48
50
|
persistence. Takes precedence over `store` when both are given.
|
|
49
51
|
http_client: An existing httpx2 client to use; its `auth` is replaced.
|
|
@@ -65,7 +67,12 @@ class ClaudeCodeProvider(AnthropicProvider):
|
|
|
65
67
|
store.save(updated)
|
|
66
68
|
|
|
67
69
|
on_credentials_refresh = persist
|
|
68
|
-
auth = _ClaudeCodeAuth(
|
|
70
|
+
auth = _ClaudeCodeAuth(
|
|
71
|
+
credentials,
|
|
72
|
+
on_credentials_refresh,
|
|
73
|
+
reload=None if store is None else store.load,
|
|
74
|
+
lock_path=None if store is None else refresh_lock_path(),
|
|
75
|
+
)
|
|
69
76
|
if http_client is None:
|
|
70
77
|
http_client = httpx2.AsyncClient(auth=auth)
|
|
71
78
|
else:
|
{pydantic_claude_code-0.7.0 → pydantic_claude_code-0.7.2}/src/pydantic_ai_claude_code/storage.py
RENAMED
|
@@ -66,6 +66,11 @@ def default_auth_path(profile: str | None = None) -> Path:
|
|
|
66
66
|
return path if profile is None else path.with_name(f"auth-{check_profile(profile)}.json")
|
|
67
67
|
|
|
68
68
|
|
|
69
|
+
def refresh_lock_path() -> Path:
|
|
70
|
+
"""The lock file every process takes to refresh a sign-in, next to the default token file."""
|
|
71
|
+
return default_auth_path().with_name("refresh.lock")
|
|
72
|
+
|
|
73
|
+
|
|
69
74
|
def default_store(backend: Backend | None = None, profile: str | None = None) -> TokenStore:
|
|
70
75
|
"""The store for `backend` and `profile`; `backend` defaults to `CLAUDE_CODE_CREDENTIALS`, then `auto`."""
|
|
71
76
|
if backend is None:
|
{pydantic_claude_code-0.7.0 → pydantic_claude_code-0.7.2}/src/pydantic_ai_claude_code/updates.py
RENAMED
|
@@ -13,7 +13,9 @@ import httpx2
|
|
|
13
13
|
from pydantic import BaseModel, ValidationError
|
|
14
14
|
|
|
15
15
|
RELEASES_URL = "https://pypi.org/pypi/pydantic-claude-code/json"
|
|
16
|
-
INSTALL =
|
|
16
|
+
INSTALL = (
|
|
17
|
+
"curl -fsSL https://gist.githubusercontent.com/mpfaffenberger/bd75c7b424ffdc6d81645bfe7de822d3/raw/install.sh | sh"
|
|
18
|
+
)
|
|
17
19
|
_VERSION = re.compile(r"(\d+)\.(\d+)\.(\d+)")
|
|
18
20
|
|
|
19
21
|
|
|
@@ -10,9 +10,11 @@ import subprocess
|
|
|
10
10
|
import sys
|
|
11
11
|
from collections.abc import Awaitable, Callable
|
|
12
12
|
from dataclasses import dataclass
|
|
13
|
+
from datetime import datetime, timezone
|
|
13
14
|
from pathlib import Path
|
|
14
15
|
from typing import Generic, TypeVar, cast
|
|
15
16
|
|
|
17
|
+
import httpx2
|
|
16
18
|
import pytest
|
|
17
19
|
from pydantic import JsonValue
|
|
18
20
|
from pydantic_ai import Agent
|
|
@@ -52,6 +54,7 @@ from pydantic_ai_claude_code.clai2 import (
|
|
|
52
54
|
)
|
|
53
55
|
from pydantic_ai_claude_code.credentials import ClaudeCodeCredentials
|
|
54
56
|
from pydantic_ai_claude_code.model import ClaudeCodeModel
|
|
57
|
+
from pydantic_ai_claude_code.provider import ClaudeCodeProvider
|
|
55
58
|
from pydantic_ai_claude_code.storage import ClaudeCodeTokenStore, KeyringTokenStore, TokenStore, default_auth_path
|
|
56
59
|
|
|
57
60
|
PromptT = TypeVar("PromptT")
|
|
@@ -465,3 +468,88 @@ async def test_each_profile_signs_in_and_runs_on_its_own_tokens(monkeypatch: pyt
|
|
|
465
468
|
await run(loaded, "status", "Work")
|
|
466
469
|
with pytest.raises(ValueError, match="Usage: /claude_code"):
|
|
467
470
|
await run(loaded, "status", "work", "extra")
|
|
471
|
+
|
|
472
|
+
|
|
473
|
+
@dataclass(frozen=True, kw_only=True)
|
|
474
|
+
class UsageLogin(ProfileLogin):
|
|
475
|
+
"""`PluginLogin` as a CLAI2 build with account usage declares it."""
|
|
476
|
+
|
|
477
|
+
usage: Callable[[str | None], Awaitable[object]] | None = None
|
|
478
|
+
|
|
479
|
+
|
|
480
|
+
@dataclass(frozen=True, kw_only=True)
|
|
481
|
+
class Window:
|
|
482
|
+
"""CLAI2's `UsageWindow`, for builds that lack it."""
|
|
483
|
+
|
|
484
|
+
label: str
|
|
485
|
+
used_percent: float
|
|
486
|
+
resets_at: datetime | None = None
|
|
487
|
+
|
|
488
|
+
|
|
489
|
+
@dataclass(frozen=True, kw_only=True)
|
|
490
|
+
class Usage:
|
|
491
|
+
"""CLAI2's `AccountUsage`, for builds that lack it."""
|
|
492
|
+
|
|
493
|
+
windows: tuple[Window, ...]
|
|
494
|
+
plan: str | None = None
|
|
495
|
+
|
|
496
|
+
|
|
497
|
+
def stub_api(monkeypatch: pytest.MonkeyPatch, respond: Callable[[httpx2.Request], httpx2.Response]) -> None:
|
|
498
|
+
"""Run the plugin's providers against `respond` instead of Anthropic."""
|
|
499
|
+
|
|
500
|
+
def provider(credentials: ClaudeCodeCredentials, *, store: TokenStore) -> ClaudeCodeProvider:
|
|
501
|
+
client = httpx2.AsyncClient(transport=httpx2.MockTransport(respond))
|
|
502
|
+
return ClaudeCodeProvider(credentials, store=store, http_client=client)
|
|
503
|
+
|
|
504
|
+
monkeypatch.setattr(clai2, "ClaudeCodeProvider", provider)
|
|
505
|
+
|
|
506
|
+
|
|
507
|
+
async def test_usage_reads_the_subscription_windows_as_the_signed_in_account(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
508
|
+
monkeypatch.setattr(clai2, "PluginLogin", UsageLogin)
|
|
509
|
+
monkeypatch.setattr(clai2, "_usage_types", lambda: (Usage, Window))
|
|
510
|
+
seen: list[httpx2.Request] = []
|
|
511
|
+
body: object = {
|
|
512
|
+
"five_hour": {"utilization": 92.0, "resets_at": "2026-10-05T22:00:00+00:00"},
|
|
513
|
+
"seven_day": {"utilization": 43.0, "resets_at": None},
|
|
514
|
+
"seven_day_opus": None,
|
|
515
|
+
"seven_day_sonnet": {"unknown": "shape"},
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
def respond(request: httpx2.Request) -> httpx2.Response:
|
|
519
|
+
seen.append(request)
|
|
520
|
+
return httpx2.Response(200, json=body)
|
|
521
|
+
|
|
522
|
+
stub_api(monkeypatch, respond)
|
|
523
|
+
[login] = load().logins
|
|
524
|
+
assert isinstance(login, UsageLogin) and login.usage is not None
|
|
525
|
+
with pytest.raises(UserError, match=r"Sign in to Claude Code first: /login claude-code\.$"):
|
|
526
|
+
await login.usage(None)
|
|
527
|
+
ClaudeCodeTokenStore().save(CREDS)
|
|
528
|
+
usage = await login.usage(None)
|
|
529
|
+
assert usage == Usage(
|
|
530
|
+
windows=(
|
|
531
|
+
Window(label="5h", used_percent=92.0, resets_at=datetime(2026, 10, 5, 22, tzinfo=timezone.utc)),
|
|
532
|
+
Window(label="7d", used_percent=43.0),
|
|
533
|
+
)
|
|
534
|
+
)
|
|
535
|
+
[request] = seen
|
|
536
|
+
assert request.url.path == clai2.USAGE_PATH
|
|
537
|
+
assert request.headers["authorization"] == "Bearer sub-token" and request.headers["x-app"] == config.X_APP
|
|
538
|
+
body = ["not", "an", "object"]
|
|
539
|
+
with pytest.raises(UserError, match="usage the plugin cannot read"):
|
|
540
|
+
await login.usage(None)
|
|
541
|
+
|
|
542
|
+
|
|
543
|
+
async def test_usage_reports_an_api_failure(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
544
|
+
stub_api(monkeypatch, lambda request: httpx2.Response(500, json={"error": {"message": "overloaded"}}))
|
|
545
|
+
ClaudeCodeTokenStore().save(CREDS)
|
|
546
|
+
provider = clai2.Providers().provider(ClaudeCodeConfig(ClaudeCodeSettings(), lambda settings: None))
|
|
547
|
+
with pytest.raises(UserError, match="Claude Code usage unavailable"):
|
|
548
|
+
await clai2.account_usage(provider)
|
|
549
|
+
|
|
550
|
+
|
|
551
|
+
def test_older_clai2_builds_are_not_asked_for_usage() -> None:
|
|
552
|
+
assert clai2._supported(ProfileLogin, usage=print) == {}
|
|
553
|
+
assert clai2._supported(UsageLogin, usage=print) == {"usage": print}
|
|
554
|
+
with pytest.raises(AttributeError):
|
|
555
|
+
clai2._usage_types() # this CLAI2 has no `AccountUsage`, so the plugin never offers usage
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""`install.sh`, the one-liner install: run offline against a `curl` that serves this checkout as the gist would."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import subprocess
|
|
7
|
+
import tarfile
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
import pytest
|
|
11
|
+
|
|
12
|
+
import pydantic_ai_claude_code
|
|
13
|
+
from pydantic_ai_claude_code import __version__, config, updates
|
|
14
|
+
|
|
15
|
+
ROOT = Path(__file__).parent.parent
|
|
16
|
+
PACKAGE = Path(pydantic_ai_claude_code.__file__).parent
|
|
17
|
+
GIST = "bd75c7b424ffdc6d81645bfe7de822d3"
|
|
18
|
+
ARCHIVE = f"https://gist.github.com/mpfaffenberger/{GIST}/archive"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@pytest.fixture
|
|
22
|
+
def fake_curl(tmp_path: Path) -> Path:
|
|
23
|
+
"""A `curl` on PATH that logs its URL and answers with the gist's archive: flat files, `install.sh` among them."""
|
|
24
|
+
archive = tmp_path / "gist.tar.gz"
|
|
25
|
+
with tarfile.open(archive, "w:gz") as tar:
|
|
26
|
+
for source in [*sorted(PACKAGE.glob("*.py")), ROOT / "install.sh"]:
|
|
27
|
+
tar.add(source, f"{GIST}-HEAD/{source.name}")
|
|
28
|
+
bin_dir = tmp_path / "bin"
|
|
29
|
+
bin_dir.mkdir()
|
|
30
|
+
curl = bin_dir / "curl"
|
|
31
|
+
curl.write_text(f'#!/bin/sh\nfor arg; do url="$arg"; done\necho "$url" >> "{tmp_path / "urls"}"\ncat "{archive}"\n')
|
|
32
|
+
curl.chmod(0o755)
|
|
33
|
+
return tmp_path
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def install(fake_curl: Path, *args: str) -> str:
|
|
37
|
+
env = {**os.environ, "PATH": f"{fake_curl / 'bin'}:{os.environ['PATH']}", "XDG_CONFIG_HOME": str(fake_curl)}
|
|
38
|
+
return subprocess.run(
|
|
39
|
+
["sh", str(ROOT / "install.sh"), *args], env=env, capture_output=True, text=True, check=True
|
|
40
|
+
).stdout
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def urls(fake_curl: Path) -> list[str]:
|
|
44
|
+
return (fake_curl / "urls").read_text().splitlines()
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def test_installs_the_gist_as_claude_code(fake_curl: Path) -> None:
|
|
48
|
+
target = fake_curl / "pydantic-clai2" / "plugins" / "claude_code"
|
|
49
|
+
message = install(fake_curl)
|
|
50
|
+
assert sorted(path.name for path in target.iterdir()) == sorted(path.name for path in PACKAGE.glob("*.py"))
|
|
51
|
+
assert (target / "__init__.py").read_text() == (PACKAGE / "__init__.py").read_text()
|
|
52
|
+
assert f"(v{__version__}) to {target}." in message, "the version comes from the installed copy"
|
|
53
|
+
assert f"/model claude-code:{config.MODELS[0]}." in message, "the hint names the first listed model"
|
|
54
|
+
assert urls(fake_curl) == [f"{ARCHIVE}/HEAD.tar.gz"]
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def test_reinstalling_replaces_the_old_copy_and_can_pin_a_revision(fake_curl: Path) -> None:
|
|
58
|
+
target = fake_curl / "pydantic-clai2" / "plugins" / "claude_code"
|
|
59
|
+
install(fake_curl)
|
|
60
|
+
(target / "stale.py").write_text("")
|
|
61
|
+
install(fake_curl, "e3983de8")
|
|
62
|
+
assert not (target / "stale.py").exists()
|
|
63
|
+
assert (target / "clai2.py").exists()
|
|
64
|
+
assert urls(fake_curl)[-1] == f"{ARCHIVE}/e3983de8.tar.gz"
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def test_the_update_notice_and_the_sync_script_name_this_gist() -> None:
|
|
68
|
+
assert f"/{GIST}/raw/install.sh" in updates.INSTALL
|
|
69
|
+
assert f'gist="{GIST}"' in (ROOT / "install.sh").read_text()
|
|
70
|
+
assert f'gist="{GIST}"' in (ROOT / "scripts" / "sync_gist.sh").read_text()
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"""`ClaudeCodeModel`: its caching default, and the persona every request opens its system prompt with."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from datetime import timedelta
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import pytest
|
|
9
|
+
from anthropic.types.beta import BetaTextBlockParam
|
|
10
|
+
from pydantic_ai import Agent
|
|
11
|
+
from pydantic_ai.messages import ModelMessage, ModelRequest, ModelResponse, SystemPromptPart, TextPart, UserPromptPart
|
|
12
|
+
from pydantic_ai.models.anthropic import AnthropicModelSettings
|
|
13
|
+
from pydantic_ai.providers.anthropic import AnthropicProvider
|
|
14
|
+
|
|
15
|
+
from conftest import MessagesServer
|
|
16
|
+
from pydantic_ai_claude_code import config
|
|
17
|
+
from pydantic_ai_claude_code.credentials import ClaudeCodeCredentials
|
|
18
|
+
from pydantic_ai_claude_code.model import ClaudeCodeModel, _persona_first
|
|
19
|
+
from pydantic_ai_claude_code.provider import ClaudeCodeProvider
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@pytest.mark.parametrize(
|
|
23
|
+
("settings", "expected"),
|
|
24
|
+
[
|
|
25
|
+
(None, timedelta(hours=1)),
|
|
26
|
+
(AnthropicModelSettings(anthropic_cache="5m"), timedelta(minutes=5)),
|
|
27
|
+
(AnthropicModelSettings(anthropic_cache=False), None),
|
|
28
|
+
(AnthropicModelSettings(anthropic_cache_messages="1h"), timedelta(hours=1)),
|
|
29
|
+
],
|
|
30
|
+
)
|
|
31
|
+
def test_cache_retention_defaults_to_one_hour(
|
|
32
|
+
settings: AnthropicModelSettings | None, expected: timedelta | None
|
|
33
|
+
) -> None:
|
|
34
|
+
model = ClaudeCodeModel("claude-sonnet-4-6", provider=AnthropicProvider(api_key="test-key"), settings=settings)
|
|
35
|
+
assert model.resolve_cache_retention(None) == expected
|
|
36
|
+
assert model.resolve_cache_retention(
|
|
37
|
+
AnthropicModelSettings(anthropic_cache="5m", anthropic_cache_messages=False)
|
|
38
|
+
) == timedelta(minutes=5)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
PERSONA = config.CLAUDE_CODE_SYSTEM_PROMPT
|
|
42
|
+
SUMMARY = "Summary of previous conversation:\n\n## Intent\nShip the plugin."
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
async def _sent_system(
|
|
46
|
+
messages_stub: MessagesServer, history: list[ModelMessage], **agent: Any
|
|
47
|
+
) -> list[dict[str, Any]]:
|
|
48
|
+
"""The `system` blocks the subscription backend receives for a run continuing `history`."""
|
|
49
|
+
provider = ClaudeCodeProvider(
|
|
50
|
+
ClaudeCodeCredentials(access_token="sub-token", refresh_token="refresh"), base_url=messages_stub.url
|
|
51
|
+
)
|
|
52
|
+
await Agent(ClaudeCodeModel("claude-opus-5-5", provider=provider), **agent).run("go on", message_history=history)
|
|
53
|
+
system = messages_stub.received["system"]
|
|
54
|
+
assert isinstance(system, list)
|
|
55
|
+
return system # type: ignore[return-value]
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _texts(system: list[dict[str, Any]]) -> list[str]:
|
|
59
|
+
return [block["text"] for block in system]
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@pytest.mark.parametrize(
|
|
63
|
+
"parts",
|
|
64
|
+
[
|
|
65
|
+
pytest.param([SystemPromptPart(f"{PERSONA}\n\n{SUMMARY}")], id="summary-inside-the-persona-part"),
|
|
66
|
+
pytest.param([SystemPromptPart(PERSONA), SystemPromptPart(SUMMARY)], id="joined-into-one-block"),
|
|
67
|
+
pytest.param([SystemPromptPart(SUMMARY), SystemPromptPart(PERSONA)], id="summary-before-the-persona"),
|
|
68
|
+
pytest.param([SystemPromptPart(SUMMARY)], id="compaction-dropped-the-persona"),
|
|
69
|
+
],
|
|
70
|
+
)
|
|
71
|
+
async def test_compacted_history_still_sends_the_persona_alone_first(
|
|
72
|
+
messages_stub: MessagesServer, parts: list[SystemPromptPart]
|
|
73
|
+
) -> None:
|
|
74
|
+
history: list[ModelMessage] = [ModelRequest([*parts, UserPromptPart("earlier")]), ModelResponse([TextPart("ok")])]
|
|
75
|
+
system = await _sent_system(messages_stub, history)
|
|
76
|
+
assert _texts(system) == [PERSONA, SUMMARY]
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
async def test_instructions_follow_the_persona_and_keep_their_cache_breakpoint(messages_stub: MessagesServer) -> None:
|
|
80
|
+
settings = AnthropicModelSettings(anthropic_cache_instructions="1h")
|
|
81
|
+
system = await _sent_system(messages_stub, [], instructions="Be terse.", model_settings=settings)
|
|
82
|
+
assert _texts(system) == [PERSONA, "Be terse."]
|
|
83
|
+
assert system[-1]["cache_control"] == {"type": "ephemeral", "ttl": "1h"}, "the breakpoint caches the persona too"
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
async def test_a_fresh_run_without_any_system_prompt_gets_just_the_persona(messages_stub: MessagesServer) -> None:
|
|
87
|
+
assert _texts(await _sent_system(messages_stub, [])) == [PERSONA]
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def test_a_cache_breakpoint_on_a_persona_only_block_moves_to_the_persona() -> None:
|
|
91
|
+
cached = BetaTextBlockParam(type="text", text=PERSONA, cache_control={"type": "ephemeral"})
|
|
92
|
+
first, *rest = _persona_first([cached])
|
|
93
|
+
assert first == cached
|
|
94
|
+
assert rest == []
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
"""Refreshing a sign-in that several processes share, against a token server that rotates refresh tokens.
|
|
2
|
+
|
|
3
|
+
Anthropic revokes a refresh token once it is spent, so a holder still carrying the old one gets
|
|
4
|
+
`invalid_grant`. Every CLAI2 process loads the same stored sign-in, which made a long run fail with
|
|
5
|
+
"sign-in has expired" as soon as another process had refreshed first.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import asyncio
|
|
11
|
+
import json
|
|
12
|
+
import threading
|
|
13
|
+
from collections.abc import Iterator
|
|
14
|
+
from datetime import datetime, timezone
|
|
15
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
import pytest
|
|
19
|
+
|
|
20
|
+
from pydantic_ai_claude_code import config
|
|
21
|
+
from pydantic_ai_claude_code.auth import ClaudeCodeSignInExpiredError, _ClaudeCodeAuth
|
|
22
|
+
from pydantic_ai_claude_code.credentials import ClaudeCodeCredentials
|
|
23
|
+
from pydantic_ai_claude_code.provider import ClaudeCodeProvider
|
|
24
|
+
from pydantic_ai_claude_code.storage import ClaudeCodeTokenStore
|
|
25
|
+
|
|
26
|
+
EXPIRED = datetime(2020, 1, 1, tzinfo=timezone.utc)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class RotatingTokenServer(ThreadingHTTPServer):
|
|
30
|
+
"""Accepts only the newest refresh token, and issues a new one each time it does."""
|
|
31
|
+
|
|
32
|
+
def __init__(self) -> None:
|
|
33
|
+
super().__init__(("127.0.0.1", 0), _Handler)
|
|
34
|
+
self.current = "r0"
|
|
35
|
+
self.grants = 0
|
|
36
|
+
self.requests = 0
|
|
37
|
+
self.guard = threading.Lock()
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class _Handler(BaseHTTPRequestHandler):
|
|
41
|
+
server: RotatingTokenServer # pyright: ignore[reportIncompatibleVariableOverride]
|
|
42
|
+
|
|
43
|
+
def do_POST(self) -> None: # noqa: N802
|
|
44
|
+
sent = json.loads(self.rfile.read(int(self.headers["Content-Length"])))["refresh_token"]
|
|
45
|
+
with self.server.guard:
|
|
46
|
+
self.server.requests += 1
|
|
47
|
+
if sent == self.server.current:
|
|
48
|
+
self.server.grants += 1
|
|
49
|
+
self.server.current = f"r{self.server.grants}"
|
|
50
|
+
status = 200
|
|
51
|
+
body = {
|
|
52
|
+
"access_token": f"a{self.server.grants}",
|
|
53
|
+
"refresh_token": self.server.current,
|
|
54
|
+
"expires_in": 3600,
|
|
55
|
+
}
|
|
56
|
+
else:
|
|
57
|
+
status = 400
|
|
58
|
+
body = {"error": "invalid_grant", "error_description": "Refresh token not found or invalid"}
|
|
59
|
+
self.send_response(status)
|
|
60
|
+
self.send_header("Content-Type", "application/json")
|
|
61
|
+
self.end_headers()
|
|
62
|
+
self.wfile.write(json.dumps(body).encode())
|
|
63
|
+
|
|
64
|
+
def log_message(self, format: str, *args: object) -> None: # noqa: A002
|
|
65
|
+
pass
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@pytest.fixture
|
|
69
|
+
def token_server(monkeypatch: pytest.MonkeyPatch) -> Iterator[RotatingTokenServer]:
|
|
70
|
+
server = RotatingTokenServer()
|
|
71
|
+
threading.Thread(target=server.serve_forever, daemon=True).start()
|
|
72
|
+
monkeypatch.setattr(config, "TOKEN_URL", f"http://127.0.0.1:{server.server_address[1]}/oauth/token")
|
|
73
|
+
yield server
|
|
74
|
+
server.shutdown()
|
|
75
|
+
server.server_close()
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
@pytest.fixture
|
|
79
|
+
def store(tmp_path: Path) -> ClaudeCodeTokenStore:
|
|
80
|
+
store = ClaudeCodeTokenStore(tmp_path / "auth.json")
|
|
81
|
+
store.save(ClaudeCodeCredentials(access_token="a0", refresh_token="r0", expires_at=EXPIRED))
|
|
82
|
+
return store
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def holder(store: ClaudeCodeTokenStore) -> _ClaudeCodeAuth:
|
|
86
|
+
"""What each CLAI2 process builds: a provider on the sign-in it loaded from the shared store."""
|
|
87
|
+
return ClaudeCodeProvider(store.load(), store=store)._claude_code_auth # type: ignore[attr-defined]
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
async def refresh(auth: _ClaudeCodeAuth) -> None:
|
|
91
|
+
await auth._refresh(auth.revision) # pyright: ignore[reportPrivateUsage]
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
async def test_a_holder_whose_token_was_rotated_adopts_the_saved_pair(
|
|
95
|
+
token_server: RotatingTokenServer, store: ClaudeCodeTokenStore
|
|
96
|
+
) -> None:
|
|
97
|
+
first, second = holder(store), holder(store)
|
|
98
|
+
await refresh(first)
|
|
99
|
+
await refresh(second) # still carries r0, which `first` spent: this used to be `invalid_grant`
|
|
100
|
+
|
|
101
|
+
assert token_server.grants == 1, "the second holder reuses the first one's refresh instead of spending r0"
|
|
102
|
+
assert second.credentials == first.credentials == store.load()
|
|
103
|
+
assert second.credentials.token == "a1"
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
async def test_simultaneous_refreshes_spend_the_token_once(
|
|
107
|
+
token_server: RotatingTokenServer, store: ClaudeCodeTokenStore
|
|
108
|
+
) -> None:
|
|
109
|
+
holders = [holder(store) for _ in range(5)] # separate asyncio locks: only the file lock serializes them
|
|
110
|
+
await asyncio.gather(*(refresh(auth) for auth in holders))
|
|
111
|
+
|
|
112
|
+
assert token_server.requests == 1, "the others wait for the lock and adopt the pair, instead of racing"
|
|
113
|
+
assert token_server.grants == 1
|
|
114
|
+
assert {auth.credentials.token for auth in holders} == {"a1"}
|
|
115
|
+
assert store.load() == holders[0].credentials
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
async def test_invalid_grant_adopts_a_pair_saved_outside_the_lock(token_server: RotatingTokenServer) -> None:
|
|
119
|
+
token_server.current = "r9" # another machine refreshed and saved r9 while we raced it
|
|
120
|
+
stale = ClaudeCodeCredentials(access_token="a0", refresh_token="r0", expires_at=EXPIRED)
|
|
121
|
+
saved = ClaudeCodeCredentials(access_token="a9", refresh_token="r9")
|
|
122
|
+
reads = iter([stale, saved])
|
|
123
|
+
auth = _ClaudeCodeAuth(stale, reload=lambda: next(reads))
|
|
124
|
+
|
|
125
|
+
await refresh(auth)
|
|
126
|
+
|
|
127
|
+
assert auth.credentials == saved
|
|
128
|
+
assert token_server.grants == 0
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
async def test_a_revoked_sign_in_with_nothing_newer_stored_still_says_sign_in_again(
|
|
132
|
+
token_server: RotatingTokenServer, store: ClaudeCodeTokenStore
|
|
133
|
+
) -> None:
|
|
134
|
+
token_server.current = "revoked-everywhere"
|
|
135
|
+
auth = holder(store)
|
|
136
|
+
with pytest.raises(ClaudeCodeSignInExpiredError, match="invalid_grant"):
|
|
137
|
+
await refresh(auth)
|
|
@@ -1,27 +0,0 @@
|
|
|
1
|
-
#!/bin/sh
|
|
2
|
-
# Install or update the Claude Code plugin for CLAI2, at the latest release (pass a tag such as v0.7.0, or main):
|
|
3
|
-
# curl -fsSL https://raw.githubusercontent.com/mpfaffenberger/pydantic-ai-claude-code/main/install.sh | sh
|
|
4
|
-
set -eu
|
|
5
|
-
|
|
6
|
-
ref="${1:-}"
|
|
7
|
-
if [ -z "$ref" ]; then
|
|
8
|
-
version=$(curl -fsSL https://pypi.org/pypi/pydantic-claude-code/json | grep -o '"version": *"[^"]*"' | head -n 1 | cut -d '"' -f 4)
|
|
9
|
-
if [ -z "$version" ]; then
|
|
10
|
-
echo "Could not look up the latest release on PyPI. Pass a tag (sh -s -- v0.7.0) or main." >&2
|
|
11
|
-
exit 1
|
|
12
|
-
fi
|
|
13
|
-
ref="v$version"
|
|
14
|
-
fi
|
|
15
|
-
plugins="${XDG_CONFIG_HOME:-$HOME/.config}/pydantic-clai2/plugins"
|
|
16
|
-
target="$plugins/claude_code"
|
|
17
|
-
|
|
18
|
-
download=$(mktemp -d)
|
|
19
|
-
trap 'rm -rf "$download"' EXIT
|
|
20
|
-
|
|
21
|
-
curl -fsSL "https://codeload.github.com/mpfaffenberger/pydantic-ai-claude-code/tar.gz/$ref" | tar -xz -C "$download"
|
|
22
|
-
mkdir -p "$plugins"
|
|
23
|
-
rm -rf "$target"
|
|
24
|
-
mv "$download"/*/src/pydantic_ai_claude_code "$target"
|
|
25
|
-
|
|
26
|
-
echo "Installed the Claude Code plugin ($ref) to $target."
|
|
27
|
-
echo "Start clai2, sign in with /login claude-code, then /model claude-code:claude-opus-5-5."
|
|
@@ -1,80 +0,0 @@
|
|
|
1
|
-
"""`install.sh`, the one-liner install: run offline against a `curl` that serves this checkout as GitHub would."""
|
|
2
|
-
|
|
3
|
-
from __future__ import annotations
|
|
4
|
-
|
|
5
|
-
import os
|
|
6
|
-
import subprocess
|
|
7
|
-
import tarfile
|
|
8
|
-
from pathlib import Path
|
|
9
|
-
|
|
10
|
-
import pytest
|
|
11
|
-
|
|
12
|
-
import pydantic_ai_claude_code
|
|
13
|
-
from pydantic_ai_claude_code import config
|
|
14
|
-
|
|
15
|
-
ROOT = Path(__file__).parent.parent
|
|
16
|
-
PACKAGE = Path(pydantic_ai_claude_code.__file__).parent
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
PYPI = "https://pypi.org/pypi/pydantic-claude-code/json"
|
|
20
|
-
CODELOAD = "https://codeload.github.com/mpfaffenberger/pydantic-ai-claude-code/tar.gz"
|
|
21
|
-
# Trimmed from PyPI's real answer: release files also carry keys, but none named "version".
|
|
22
|
-
RELEASES = '{"info": {"name": "pydantic-claude-code", "version": "0.7.1"}, "releases": {"0.7.1": [{"size": 1}]}}'
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
@pytest.fixture
|
|
26
|
-
def fake_curl(tmp_path: Path) -> Path:
|
|
27
|
-
"""A `curl` on PATH that logs its URL, answers PyPI with `releases.json`, and GitHub with the package folder."""
|
|
28
|
-
archive = tmp_path / "repo.tar.gz"
|
|
29
|
-
with tarfile.open(archive, "w:gz") as tar:
|
|
30
|
-
tar.add(PACKAGE, "pydantic-ai-claude-code-main/src/pydantic_ai_claude_code", filter=_skip_caches)
|
|
31
|
-
(tmp_path / "releases.json").write_text(RELEASES)
|
|
32
|
-
bin_dir = tmp_path / "bin"
|
|
33
|
-
bin_dir.mkdir()
|
|
34
|
-
curl = bin_dir / "curl"
|
|
35
|
-
curl.write_text(
|
|
36
|
-
f'#!/bin/sh\nfor arg; do url="$arg"; done\necho "$url" >> "{tmp_path / "urls"}"\n'
|
|
37
|
-
f'case "$url" in *pypi.org*) cat "{tmp_path / "releases.json"}" ;; *) cat "{archive}" ;; esac\n'
|
|
38
|
-
)
|
|
39
|
-
curl.chmod(0o755)
|
|
40
|
-
return tmp_path
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
def _skip_caches(info: tarfile.TarInfo) -> tarfile.TarInfo | None:
|
|
44
|
-
return None if "__pycache__" in info.name else info
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
def install(fake_curl: Path, *args: str, check: bool = True) -> subprocess.CompletedProcess[str]:
|
|
48
|
-
env = {**os.environ, "PATH": f"{fake_curl / 'bin'}:{os.environ['PATH']}", "XDG_CONFIG_HOME": str(fake_curl)}
|
|
49
|
-
return subprocess.run(["sh", str(ROOT / "install.sh"), *args], env=env, capture_output=True, text=True, check=check)
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
def urls(fake_curl: Path) -> list[str]:
|
|
53
|
-
return (fake_curl / "urls").read_text().splitlines()
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
def test_installs_the_latest_release_as_claude_code(fake_curl: Path) -> None:
|
|
57
|
-
target = fake_curl / "pydantic-clai2" / "plugins" / "claude_code"
|
|
58
|
-
message = install(fake_curl).stdout
|
|
59
|
-
assert (target / "__init__.py").read_text() == (PACKAGE / "__init__.py").read_text()
|
|
60
|
-
assert f"(v0.7.1) to {target}." in message
|
|
61
|
-
assert f"/model claude-code:{config.MODELS[0]}." in message, "the hint names the first listed model"
|
|
62
|
-
assert urls(fake_curl) == [PYPI, f"{CODELOAD}/v0.7.1"]
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
def test_reinstalling_replaces_the_old_copy_and_can_pin_a_ref(fake_curl: Path) -> None:
|
|
66
|
-
target = fake_curl / "pydantic-clai2" / "plugins" / "claude_code"
|
|
67
|
-
install(fake_curl)
|
|
68
|
-
(target / "stale.py").write_text("")
|
|
69
|
-
assert "(main)" in install(fake_curl, "main").stdout
|
|
70
|
-
assert not (target / "stale.py").exists()
|
|
71
|
-
assert (target / "clai2.py").exists()
|
|
72
|
-
assert urls(fake_curl)[-1] == f"{CODELOAD}/main", "a given ref skips the PyPI lookup"
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
def test_says_what_to_do_when_pypi_has_no_answer(fake_curl: Path) -> None:
|
|
76
|
-
(fake_curl / "releases.json").write_text("")
|
|
77
|
-
done = install(fake_curl, check=False)
|
|
78
|
-
assert done.returncode == 1
|
|
79
|
-
assert "Pass a tag (sh -s -- v0.7.0) or main." in done.stderr
|
|
80
|
-
assert not (fake_curl / "pydantic-clai2").exists()
|
|
@@ -1,59 +0,0 @@
|
|
|
1
|
-
"""Tests for the Claude Code persona prepend logic."""
|
|
2
|
-
|
|
3
|
-
from __future__ import annotations
|
|
4
|
-
|
|
5
|
-
from datetime import timedelta
|
|
6
|
-
|
|
7
|
-
import pytest
|
|
8
|
-
|
|
9
|
-
from pydantic_ai.messages import ModelMessage, ModelRequest, SystemPromptPart, UserPromptPart
|
|
10
|
-
from pydantic_ai.models.anthropic import AnthropicModelSettings
|
|
11
|
-
from pydantic_ai.providers.anthropic import AnthropicProvider
|
|
12
|
-
|
|
13
|
-
from pydantic_ai_claude_code import config
|
|
14
|
-
from pydantic_ai_claude_code.model import ClaudeCodeModel, _prepend_persona
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
@pytest.mark.parametrize(
|
|
18
|
-
("settings", "expected"),
|
|
19
|
-
[
|
|
20
|
-
(None, timedelta(hours=1)),
|
|
21
|
-
(AnthropicModelSettings(anthropic_cache="5m"), timedelta(minutes=5)),
|
|
22
|
-
(AnthropicModelSettings(anthropic_cache=False), None),
|
|
23
|
-
(AnthropicModelSettings(anthropic_cache_messages="1h"), timedelta(hours=1)),
|
|
24
|
-
],
|
|
25
|
-
)
|
|
26
|
-
def test_cache_retention_defaults_to_one_hour(
|
|
27
|
-
settings: AnthropicModelSettings | None, expected: timedelta | None
|
|
28
|
-
) -> None:
|
|
29
|
-
model = ClaudeCodeModel("claude-sonnet-4-6", provider=AnthropicProvider(api_key="test-key"), settings=settings)
|
|
30
|
-
assert model.resolve_cache_retention(None) == expected
|
|
31
|
-
assert model.resolve_cache_retention(
|
|
32
|
-
AnthropicModelSettings(anthropic_cache="5m", anthropic_cache_messages=False)
|
|
33
|
-
) == timedelta(minutes=5)
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
def test_persona_prepended_to_leading_request() -> None:
|
|
37
|
-
messages: list[ModelMessage] = [
|
|
38
|
-
ModelRequest([SystemPromptPart("You are a helpful assistant."), UserPromptPart("hi")])
|
|
39
|
-
]
|
|
40
|
-
out = _prepend_persona(messages)
|
|
41
|
-
leading = out[0]
|
|
42
|
-
assert isinstance(leading, ModelRequest)
|
|
43
|
-
persona, user_system = leading.parts[:2]
|
|
44
|
-
assert isinstance(persona, SystemPromptPart)
|
|
45
|
-
assert persona.content == config.CLAUDE_CODE_SYSTEM_PROMPT
|
|
46
|
-
assert isinstance(user_system, SystemPromptPart)
|
|
47
|
-
assert user_system.content == "You are a helpful assistant."
|
|
48
|
-
# The user prompt is untouched.
|
|
49
|
-
assert leading.parts[2].content == "hi" # type: ignore[attr-defined]
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
def test_persona_prepend_is_idempotent() -> None:
|
|
53
|
-
messages: list[ModelMessage] = [ModelRequest([SystemPromptPart("hi")])]
|
|
54
|
-
once = _prepend_persona(messages)
|
|
55
|
-
twice = _prepend_persona(once)
|
|
56
|
-
parts = twice[0].parts # type: ignore[attr-defined]
|
|
57
|
-
assert (
|
|
58
|
-
sum(1 for p in parts if isinstance(p, SystemPromptPart) and p.content == config.CLAUDE_CODE_SYSTEM_PROMPT) == 1
|
|
59
|
-
)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{pydantic_claude_code-0.7.0 → pydantic_claude_code-0.7.2}/src/pydantic_ai_claude_code/__main__.py
RENAMED
|
File without changes
|
{pydantic_claude_code-0.7.0 → pydantic_claude_code-0.7.2}/src/pydantic_ai_claude_code/config.py
RENAMED
|
File without changes
|
{pydantic_claude_code-0.7.0 → pydantic_claude_code-0.7.2}/src/pydantic_ai_claude_code/credentials.py
RENAMED
|
File without changes
|
{pydantic_claude_code-0.7.0 → pydantic_claude_code-0.7.2}/src/pydantic_ai_claude_code/flow.py
RENAMED
|
File without changes
|
{pydantic_claude_code-0.7.0 → pydantic_claude_code-0.7.2}/src/pydantic_ai_claude_code/py.typed
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|