pi-sidecar-client 0.1.0.dev1__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.
- pi_sidecar_client-0.1.0.dev1/LICENSE +191 -0
- pi_sidecar_client-0.1.0.dev1/PKG-INFO +11 -0
- pi_sidecar_client-0.1.0.dev1/README.md +158 -0
- pi_sidecar_client-0.1.0.dev1/pi_sidecar_client/__init__.py +352 -0
- pi_sidecar_client-0.1.0.dev1/pi_sidecar_client.egg-info/PKG-INFO +11 -0
- pi_sidecar_client-0.1.0.dev1/pi_sidecar_client.egg-info/SOURCES.txt +9 -0
- pi_sidecar_client-0.1.0.dev1/pi_sidecar_client.egg-info/dependency_links.txt +1 -0
- pi_sidecar_client-0.1.0.dev1/pi_sidecar_client.egg-info/requires.txt +2 -0
- pi_sidecar_client-0.1.0.dev1/pi_sidecar_client.egg-info/top_level.txt +1 -0
- pi_sidecar_client-0.1.0.dev1/pyproject.toml +60 -0
- pi_sidecar_client-0.1.0.dev1/setup.cfg +4 -0
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
Copyright 2025 myk-org
|
|
180
|
+
|
|
181
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
182
|
+
you may not use this file except in compliance with the License.
|
|
183
|
+
You may obtain a copy of the License at
|
|
184
|
+
|
|
185
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
186
|
+
|
|
187
|
+
Unless required by applicable law or agreed to in writing, software
|
|
188
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
189
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
190
|
+
See the License for the specific language governing permissions and
|
|
191
|
+
limitations under the License.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pi-sidecar-client
|
|
3
|
+
Version: 0.1.0.dev1
|
|
4
|
+
Summary: Python client for the Pi SDK sidecar service
|
|
5
|
+
License: Apache-2.0
|
|
6
|
+
Project-URL: Repository, https://github.com/myk-org/pi-sidecar
|
|
7
|
+
Requires-Python: >=3.10
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Requires-Dist: httpx>=0.27
|
|
10
|
+
Requires-Dist: python-simple-logger
|
|
11
|
+
Dynamic: license-file
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
# pi-sidecar
|
|
2
|
+
|
|
3
|
+
A standalone HTTP service that wraps the [Pi coding agent SDK](https://www.npmjs.com/package/@earendil-works/pi-coding-agent), exposing AI sessions over a simple JSON API. Ships with a Python client for easy integration.
|
|
4
|
+
|
|
5
|
+
## Packages
|
|
6
|
+
|
|
7
|
+
| Package | Language | Install |
|
|
8
|
+
|---------|----------|---------|
|
|
9
|
+
| `@myk-org/pi-sidecar` | TypeScript | `npm install @myk-org/pi-sidecar` |
|
|
10
|
+
| `pi-sidecar-client` | Python ≥ 3.10 | `pip install pi-sidecar-client` |
|
|
11
|
+
|
|
12
|
+
## Provider Support
|
|
13
|
+
|
|
14
|
+
| Provider | Sidecar name | Required env vars / config |
|
|
15
|
+
|----------|-------------|---------------------------|
|
|
16
|
+
| Gemini | `google` | `GOOGLE_API_KEY` or Application Default Credentials |
|
|
17
|
+
| Claude (Vertex AI) | `google-vertex-claude` | `GOOGLE_APPLICATION_CREDENTIALS`, Vertex extension (`SIDECAR_VERTEX_EXTENSION_PATH`) |
|
|
18
|
+
| Claude (API key) | `anthropic` | `ANTHROPIC_API_KEY` |
|
|
19
|
+
| Cursor (via acpx) | `acpx-cursor` | `ACPX_AGENTS=cursor`, acpx CLI on `$PATH`, ACPX extension (`SIDECAR_ACPX_EXTENSION_PATH`) |
|
|
20
|
+
|
|
21
|
+
> **Note:** The Python client accepts friendly provider names (`gemini`, `claude`, `cursor`) and maps them internally to sidecar provider names (`google`, `google-vertex-claude`, `acpx-cursor`).
|
|
22
|
+
|
|
23
|
+
## HTTP API
|
|
24
|
+
|
|
25
|
+
All endpoints accept/return JSON. Default base URL: `http://127.0.0.1:9100`.
|
|
26
|
+
|
|
27
|
+
| Method | Path | Description |
|
|
28
|
+
|--------|------|-------------|
|
|
29
|
+
| `GET` | `/health` | Returns `{"status":"ok","sessions":N}`. 503 while model discovery is in progress. |
|
|
30
|
+
| `GET` | `/models` | List all discovered models. |
|
|
31
|
+
| `POST` | `/models/refresh` | Re-run model discovery and return updated list. |
|
|
32
|
+
| `POST` | `/sessions` | Create a session. Body: `{provider, model, system_prompt, cwd?, custom_tools?}` → `{session_id}` |
|
|
33
|
+
| `POST` | `/sessions/:id/prompt` | Send a message. Body: `{message}` → `{text, usage}` |
|
|
34
|
+
| `POST` | `/sessions/:id/abort` | Abort an in-progress prompt. |
|
|
35
|
+
| `DELETE` | `/sessions/:id` | Delete a session and free resources. |
|
|
36
|
+
|
|
37
|
+
## TypeScript Usage
|
|
38
|
+
|
|
39
|
+
### Programmatic
|
|
40
|
+
|
|
41
|
+
```ts
|
|
42
|
+
import { startSidecar } from "@myk-org/pi-sidecar";
|
|
43
|
+
|
|
44
|
+
startSidecar({ port: 9100, host: "127.0.0.1" });
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
### Standalone
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
npm run build
|
|
51
|
+
node dist/server.js # listens on 127.0.0.1:9100
|
|
52
|
+
SIDECAR_PORT=9200 node dist/server.js # custom port
|
|
53
|
+
DEV_MODE=true node dist/server.js # bind 0.0.0.0
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
## Python Client Usage
|
|
57
|
+
|
|
58
|
+
### Single-shot call (auto-cleanup)
|
|
59
|
+
|
|
60
|
+
```python
|
|
61
|
+
from pi_sidecar_client import call_ai_once
|
|
62
|
+
|
|
63
|
+
result = await call_ai_once(
|
|
64
|
+
"Summarize this log file",
|
|
65
|
+
ai_provider="gemini",
|
|
66
|
+
ai_model="gemini-2.5-flash",
|
|
67
|
+
system_prompt="You are a log analyst.",
|
|
68
|
+
)
|
|
69
|
+
print(result.text)
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
### Multi-turn conversation (session reuse)
|
|
73
|
+
|
|
74
|
+
```python
|
|
75
|
+
from pi_sidecar_client import call_ai, get_sidecar_client
|
|
76
|
+
|
|
77
|
+
r1 = await call_ai("Analyze this failure", ai_provider="claude", ai_model="claude-sonnet-4-20250514")
|
|
78
|
+
r2 = await call_ai("Now suggest a fix", session_id=r1.session_id)
|
|
79
|
+
|
|
80
|
+
# Clean up when done
|
|
81
|
+
await get_sidecar_client().delete_session(r2.session_id)
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
### Direct client usage
|
|
85
|
+
|
|
86
|
+
```python
|
|
87
|
+
from pi_sidecar_client import SidecarClient
|
|
88
|
+
|
|
89
|
+
client = SidecarClient("http://127.0.0.1:9100")
|
|
90
|
+
try:
|
|
91
|
+
sid = await client.create_session(
|
|
92
|
+
provider="google",
|
|
93
|
+
model="gemini-2.5-flash",
|
|
94
|
+
system_prompt="You are helpful.",
|
|
95
|
+
)
|
|
96
|
+
result = await client.prompt(sid, "Hello!")
|
|
97
|
+
print(result.text)
|
|
98
|
+
await client.delete_session(sid)
|
|
99
|
+
finally:
|
|
100
|
+
await client.close()
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
### List models
|
|
104
|
+
|
|
105
|
+
```python
|
|
106
|
+
from pi_sidecar_client import list_models
|
|
107
|
+
|
|
108
|
+
all_models = await list_models()
|
|
109
|
+
gemini_only = await list_models(provider="gemini")
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
## Testing
|
|
113
|
+
|
|
114
|
+
**TypeScript sidecar:**
|
|
115
|
+
|
|
116
|
+
```bash
|
|
117
|
+
npm install
|
|
118
|
+
npm test
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
**Python client:**
|
|
122
|
+
|
|
123
|
+
```bash
|
|
124
|
+
pip install -e '.[tests]'
|
|
125
|
+
pytest
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
## Examples
|
|
129
|
+
|
|
130
|
+
See the [`examples/`](examples/) directory for usage patterns:
|
|
131
|
+
|
|
132
|
+
| File | Description |
|
|
133
|
+
|------|-------------|
|
|
134
|
+
| `basic_prompt.py` | Single-shot AI call with `call_ai_once()` |
|
|
135
|
+
| `multi_turn.py` | Multi-turn conversation with session reuse |
|
|
136
|
+
| `list_models.py` | Discover available models by provider |
|
|
137
|
+
| `health_check.py` | Verify sidecar is running and ready |
|
|
138
|
+
| `parallel_tasks.py` | Run multiple AI calls with concurrency limiting |
|
|
139
|
+
| `usage_tracking.py` | Track token usage with a pluggable callback |
|
|
140
|
+
| `start-sidecar.ts` | Start the sidecar programmatically (TypeScript) |
|
|
141
|
+
|
|
142
|
+
## Configuration
|
|
143
|
+
|
|
144
|
+
| Variable | Default | Description |
|
|
145
|
+
|----------|---------|-------------|
|
|
146
|
+
| `SIDECAR_PORT` | `9100` | HTTP listen port |
|
|
147
|
+
| `SIDECAR_URL` | `http://127.0.0.1:9100` | Base URL used by the Python client |
|
|
148
|
+
| `DEV_MODE` | `false` | Set `true` to bind `0.0.0.0` instead of `127.0.0.1` |
|
|
149
|
+
| `ACPX_AGENTS` | *(empty)* | Comma-separated list of acpx agents to discover models from (e.g. `cursor`) |
|
|
150
|
+
| `SIDECAR_ACPX_EXTENSION_PATH` | auto-resolved via `require.resolve` from `pi-orchestrator-config` | Path to the acpx provider extension |
|
|
151
|
+
| `SIDECAR_VERTEX_EXTENSION_PATH` | auto-resolved via `require.resolve` from `node_modules` | Path to the Vertex Claude extension |
|
|
152
|
+
| `SIDECAR_WATCHDOG_URL` | *(disabled)* | Health endpoint URL for watchdog monitoring. When set, the sidecar monitors this URL and shuts down if it becomes unresponsive. Disabled by default for standalone usage. |
|
|
153
|
+
|
|
154
|
+
## Architecture Notes
|
|
155
|
+
|
|
156
|
+
- **Watchdog**: opt-in health-check poller activated via `SIDECAR_WATCHDOG_URL`. When enabled, monitors the given URL and shuts down the sidecar after 30 s of consecutive failures. Disabled by default for standalone usage.
|
|
157
|
+
- **Stale session cleanup**: sessions idle for >1 hour are automatically disposed (checked every 10 minutes).
|
|
158
|
+
- **Model discovery**: runs at startup; `/health` returns 503 until complete.
|
|
@@ -0,0 +1,352 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import inspect
|
|
3
|
+
import os
|
|
4
|
+
from collections.abc import Callable
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import httpx
|
|
9
|
+
from simple_logger.logger import get_logger
|
|
10
|
+
|
|
11
|
+
logger = get_logger(name=__name__, level=os.environ.get("LOG_LEVEL", "INFO"))
|
|
12
|
+
|
|
13
|
+
SIDECAR_URL = os.environ.get("SIDECAR_URL", "http://127.0.0.1:9100")
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"AIResult",
|
|
17
|
+
"AITokenUsage",
|
|
18
|
+
"SidecarClient",
|
|
19
|
+
"call_ai",
|
|
20
|
+
"call_ai_once",
|
|
21
|
+
"check_sidecar_available",
|
|
22
|
+
"get_sidecar_client",
|
|
23
|
+
"list_models",
|
|
24
|
+
"run_parallel_with_limit",
|
|
25
|
+
"set_usage_recorder",
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass
|
|
30
|
+
class AITokenUsage:
|
|
31
|
+
"""Token usage data from an AI call."""
|
|
32
|
+
|
|
33
|
+
input_tokens: int = 0
|
|
34
|
+
output_tokens: int = 0
|
|
35
|
+
cache_read_tokens: int = 0
|
|
36
|
+
cache_write_tokens: int = 0
|
|
37
|
+
cost_usd: float | None = None
|
|
38
|
+
duration_ms: int | None = None
|
|
39
|
+
provider: str = ""
|
|
40
|
+
model: str = ""
|
|
41
|
+
session_id: str = ""
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
# Module-level callback — consumers register their storage function
|
|
45
|
+
_usage_recorder: Callable | None = None
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def set_usage_recorder(callback: Callable) -> None:
|
|
49
|
+
"""Register a callback for recording AI token usage.
|
|
50
|
+
|
|
51
|
+
The callback signature:
|
|
52
|
+
async def recorder(*, request_id, result, call_type, prompt_chars, ai_provider, ai_model)
|
|
53
|
+
"""
|
|
54
|
+
global _usage_recorder
|
|
55
|
+
_usage_recorder = callback
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@dataclass
|
|
59
|
+
class AIResult:
|
|
60
|
+
"""Result from an AI call."""
|
|
61
|
+
|
|
62
|
+
success: bool
|
|
63
|
+
text: str
|
|
64
|
+
usage: AITokenUsage | None = None
|
|
65
|
+
session_id: str | None = None
|
|
66
|
+
|
|
67
|
+
async def record_usage(
|
|
68
|
+
self,
|
|
69
|
+
*,
|
|
70
|
+
request_id: str,
|
|
71
|
+
call_type: str,
|
|
72
|
+
prompt_chars: int = 0,
|
|
73
|
+
ai_provider: str = "",
|
|
74
|
+
ai_model: str = "",
|
|
75
|
+
) -> None:
|
|
76
|
+
"""Record token usage via the registered callback. Best-effort — never raises."""
|
|
77
|
+
if not _usage_recorder:
|
|
78
|
+
return
|
|
79
|
+
try:
|
|
80
|
+
maybe_coro = _usage_recorder(
|
|
81
|
+
request_id=request_id,
|
|
82
|
+
result=self,
|
|
83
|
+
call_type=call_type,
|
|
84
|
+
prompt_chars=prompt_chars,
|
|
85
|
+
ai_provider=ai_provider,
|
|
86
|
+
ai_model=ai_model,
|
|
87
|
+
)
|
|
88
|
+
if inspect.isawaitable(maybe_coro):
|
|
89
|
+
await maybe_coro
|
|
90
|
+
except Exception:
|
|
91
|
+
logger.debug("Failed to record usage", exc_info=True)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
# Provider mapping: friendly provider names → sidecar provider names
|
|
95
|
+
_PROVIDER_MAP = {
|
|
96
|
+
"cursor": "acpx-cursor",
|
|
97
|
+
"claude": "google-vertex-claude",
|
|
98
|
+
"gemini": "google",
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _map_provider_model(provider: str, model: str) -> tuple[str, str]:
|
|
103
|
+
"""Map friendly provider/model names to sidecar provider/model."""
|
|
104
|
+
sidecar_provider = _PROVIDER_MAP.get(provider, provider)
|
|
105
|
+
sidecar_model = model
|
|
106
|
+
# Cursor models need the cursor: prefix
|
|
107
|
+
if sidecar_provider == "acpx-cursor" and not model.startswith("cursor:"):
|
|
108
|
+
sidecar_model = f"cursor:{model}"
|
|
109
|
+
return sidecar_provider, sidecar_model
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class SidecarClient:
|
|
113
|
+
"""HTTP client for the Pi SDK sidecar service."""
|
|
114
|
+
|
|
115
|
+
def __init__(self, base_url: str = SIDECAR_URL):
|
|
116
|
+
self._base_url = base_url.rstrip("/")
|
|
117
|
+
self._client = httpx.AsyncClient(base_url=self._base_url, timeout=600.0)
|
|
118
|
+
|
|
119
|
+
async def health(self) -> dict:
|
|
120
|
+
"""Check sidecar health."""
|
|
121
|
+
resp = await self._client.get("/health")
|
|
122
|
+
resp.raise_for_status()
|
|
123
|
+
return resp.json()
|
|
124
|
+
|
|
125
|
+
async def get_models(self) -> list[dict]:
|
|
126
|
+
"""Get available models."""
|
|
127
|
+
resp = await self._client.get("/models")
|
|
128
|
+
resp.raise_for_status()
|
|
129
|
+
return resp.json().get("models", [])
|
|
130
|
+
|
|
131
|
+
async def refresh_models(self) -> list[dict]:
|
|
132
|
+
"""Trigger model discovery and return updated list."""
|
|
133
|
+
resp = await self._client.post("/models/refresh")
|
|
134
|
+
resp.raise_for_status()
|
|
135
|
+
return resp.json().get("models", [])
|
|
136
|
+
|
|
137
|
+
async def create_session(
|
|
138
|
+
self,
|
|
139
|
+
*,
|
|
140
|
+
provider: str,
|
|
141
|
+
model: str,
|
|
142
|
+
system_prompt: str,
|
|
143
|
+
cwd: str = "/tmp",
|
|
144
|
+
custom_tools: list | None = None,
|
|
145
|
+
) -> str:
|
|
146
|
+
"""Create a new AI session. Returns session_id."""
|
|
147
|
+
sidecar_provider, sidecar_model = _map_provider_model(provider, model)
|
|
148
|
+
body: dict[str, Any] = {
|
|
149
|
+
"provider": sidecar_provider,
|
|
150
|
+
"model": sidecar_model,
|
|
151
|
+
"system_prompt": system_prompt,
|
|
152
|
+
"cwd": cwd,
|
|
153
|
+
}
|
|
154
|
+
if custom_tools:
|
|
155
|
+
body["custom_tools"] = custom_tools
|
|
156
|
+
resp = await self._client.post("/sessions", json=body)
|
|
157
|
+
resp.raise_for_status()
|
|
158
|
+
return resp.json()["session_id"]
|
|
159
|
+
|
|
160
|
+
async def prompt(self, session_id: str, message: str, timeout: float | None = None) -> AIResult:
|
|
161
|
+
"""Send a message to a session. Returns AIResult."""
|
|
162
|
+
request_timeout = timeout or self._client.timeout
|
|
163
|
+
resp = await self._client.post(
|
|
164
|
+
f"/sessions/{session_id}/prompt",
|
|
165
|
+
json={"message": message},
|
|
166
|
+
timeout=request_timeout,
|
|
167
|
+
)
|
|
168
|
+
if resp.status_code != 200:
|
|
169
|
+
try:
|
|
170
|
+
payload = resp.json()
|
|
171
|
+
error = payload.get("error", resp.text) if isinstance(payload, dict) else resp.text
|
|
172
|
+
except ValueError:
|
|
173
|
+
error = resp.text or f"HTTP {resp.status_code}"
|
|
174
|
+
return AIResult(success=False, text=error)
|
|
175
|
+
|
|
176
|
+
data = resp.json()
|
|
177
|
+
usage_data = data.get("usage", {})
|
|
178
|
+
usage = AITokenUsage(
|
|
179
|
+
input_tokens=usage_data.get("input_tokens", 0),
|
|
180
|
+
output_tokens=usage_data.get("output_tokens", 0),
|
|
181
|
+
cache_read_tokens=usage_data.get("cache_read_tokens", 0),
|
|
182
|
+
cache_write_tokens=usage_data.get("cache_write_tokens", 0),
|
|
183
|
+
cost_usd=usage_data.get("cost_usd"),
|
|
184
|
+
duration_ms=usage_data.get("duration_ms"),
|
|
185
|
+
)
|
|
186
|
+
return AIResult(
|
|
187
|
+
success=True,
|
|
188
|
+
text=data.get("text", ""),
|
|
189
|
+
usage=usage,
|
|
190
|
+
)
|
|
191
|
+
|
|
192
|
+
async def abort(self, session_id: str) -> None:
|
|
193
|
+
"""Abort an in-progress prompt."""
|
|
194
|
+
resp = await self._client.post(f"/sessions/{session_id}/abort")
|
|
195
|
+
resp.raise_for_status()
|
|
196
|
+
|
|
197
|
+
async def delete_session(self, session_id: str) -> None:
|
|
198
|
+
"""Delete a session."""
|
|
199
|
+
resp = await self._client.delete(f"/sessions/{session_id}")
|
|
200
|
+
resp.raise_for_status()
|
|
201
|
+
|
|
202
|
+
async def close(self) -> None:
|
|
203
|
+
"""Close the HTTP client."""
|
|
204
|
+
await self._client.aclose()
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
# Singleton client
|
|
208
|
+
_client: SidecarClient | None = None
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def get_sidecar_client() -> SidecarClient:
|
|
212
|
+
"""Get the singleton sidecar client."""
|
|
213
|
+
global _client
|
|
214
|
+
if _client is None:
|
|
215
|
+
_client = SidecarClient()
|
|
216
|
+
return _client
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
# --- Convenience functions for single-shot AI calls ---
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
async def call_ai(
|
|
223
|
+
prompt: str,
|
|
224
|
+
*,
|
|
225
|
+
ai_provider: str = "",
|
|
226
|
+
ai_model: str = "",
|
|
227
|
+
cwd: str | None = None,
|
|
228
|
+
system_prompt: str = "",
|
|
229
|
+
ai_cli_timeout: int | None = None,
|
|
230
|
+
session_id: str | None = None,
|
|
231
|
+
custom_tools: list | None = None,
|
|
232
|
+
) -> AIResult:
|
|
233
|
+
"""Call AI via the sidecar.
|
|
234
|
+
|
|
235
|
+
Creates a new session (or reuses *session_id*), sends the prompt,
|
|
236
|
+
and returns the result with session_id attached.
|
|
237
|
+
|
|
238
|
+
Session lifecycle:
|
|
239
|
+
- Caller is responsible for deleting sessions when done.
|
|
240
|
+
- For single-shot calls, use ``call_ai_once(...)``
|
|
241
|
+
or call ``client.delete_session()`` manually after.
|
|
242
|
+
- For multi-turn (peer debate), pass ``session_id`` from the
|
|
243
|
+
previous result to continue the conversation.
|
|
244
|
+
"""
|
|
245
|
+
client = get_sidecar_client()
|
|
246
|
+
created_session = False
|
|
247
|
+
try:
|
|
248
|
+
if not session_id:
|
|
249
|
+
session_id = await client.create_session(
|
|
250
|
+
provider=ai_provider,
|
|
251
|
+
model=ai_model,
|
|
252
|
+
system_prompt=system_prompt or "You are a helpful assistant.",
|
|
253
|
+
cwd=cwd or "/tmp",
|
|
254
|
+
custom_tools=custom_tools,
|
|
255
|
+
)
|
|
256
|
+
created_session = True
|
|
257
|
+
# Convert minutes to seconds for httpx timeout
|
|
258
|
+
timeout = ai_cli_timeout * 60.0 if ai_cli_timeout else None
|
|
259
|
+
result = await client.prompt(session_id, prompt, timeout=timeout)
|
|
260
|
+
# Attach session_id to result so callers can reuse or clean up
|
|
261
|
+
result.session_id = session_id
|
|
262
|
+
return result
|
|
263
|
+
except Exception as e:
|
|
264
|
+
logger.error("Sidecar call failed: %s", e)
|
|
265
|
+
# Clean up session if WE created it and the prompt failed
|
|
266
|
+
cleanup_succeeded = False
|
|
267
|
+
if created_session and session_id:
|
|
268
|
+
try:
|
|
269
|
+
await client.delete_session(session_id)
|
|
270
|
+
cleanup_succeeded = True
|
|
271
|
+
except Exception:
|
|
272
|
+
logger.debug("Failed to cleanup leaked session %s", session_id, exc_info=True)
|
|
273
|
+
return AIResult(
|
|
274
|
+
success=False,
|
|
275
|
+
text=str(e),
|
|
276
|
+
session_id=None if cleanup_succeeded else session_id,
|
|
277
|
+
)
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
async def call_ai_once(
|
|
281
|
+
prompt: str,
|
|
282
|
+
*,
|
|
283
|
+
ai_provider: str = "",
|
|
284
|
+
ai_model: str = "",
|
|
285
|
+
cwd: str | None = None,
|
|
286
|
+
system_prompt: str = "",
|
|
287
|
+
ai_cli_timeout: int | None = None,
|
|
288
|
+
custom_tools: list | None = None,
|
|
289
|
+
) -> AIResult:
|
|
290
|
+
"""Single-shot AI call with automatic session cleanup.
|
|
291
|
+
|
|
292
|
+
Creates a session, sends the prompt, and always deletes the session.
|
|
293
|
+
Use this for one-off calls (analysis, bug creation, etc.).
|
|
294
|
+
Use ``call_ai`` directly for multi-turn conversations (peer debate).
|
|
295
|
+
"""
|
|
296
|
+
result = await call_ai(
|
|
297
|
+
prompt,
|
|
298
|
+
ai_provider=ai_provider,
|
|
299
|
+
ai_model=ai_model,
|
|
300
|
+
cwd=cwd,
|
|
301
|
+
system_prompt=system_prompt,
|
|
302
|
+
ai_cli_timeout=ai_cli_timeout,
|
|
303
|
+
custom_tools=custom_tools,
|
|
304
|
+
)
|
|
305
|
+
# Always clean up — this is a single-shot call
|
|
306
|
+
if result.session_id:
|
|
307
|
+
try:
|
|
308
|
+
await get_sidecar_client().delete_session(result.session_id)
|
|
309
|
+
result.session_id = None # Clear so caller doesn't try to reuse
|
|
310
|
+
except Exception:
|
|
311
|
+
logger.debug("Failed to cleanup session %s after call_ai_once", result.session_id, exc_info=True)
|
|
312
|
+
# Preserve session_id so caller can retry cleanup
|
|
313
|
+
return result
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
async def list_models(provider: str = "") -> list[dict]:
|
|
317
|
+
"""List available models, optionally filtered by provider."""
|
|
318
|
+
client = get_sidecar_client()
|
|
319
|
+
models = await client.get_models()
|
|
320
|
+
if provider:
|
|
321
|
+
sidecar_provider = _PROVIDER_MAP.get(provider, provider)
|
|
322
|
+
models = [m for m in models if m.get("provider") == sidecar_provider]
|
|
323
|
+
return models
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
async def check_sidecar_available() -> tuple[bool, str]:
|
|
327
|
+
"""Check if the sidecar service is available and ready."""
|
|
328
|
+
try:
|
|
329
|
+
client = get_sidecar_client()
|
|
330
|
+
resp = await client._client.get("/health")
|
|
331
|
+
data = resp.json()
|
|
332
|
+
if resp.status_code == 200 and data.get("status") == "ok":
|
|
333
|
+
return True, "Sidecar is ready"
|
|
334
|
+
if resp.status_code == 503 and data.get("status") == "starting":
|
|
335
|
+
return False, f"Sidecar starting: {data.get('message', 'model discovery in progress')}"
|
|
336
|
+
return False, f"Sidecar unhealthy (HTTP {resp.status_code}): {data}"
|
|
337
|
+
except Exception as e:
|
|
338
|
+
return False, f"Sidecar unavailable: {e}"
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
async def run_parallel_with_limit(
|
|
342
|
+
tasks: list,
|
|
343
|
+
max_concurrency: int = 5,
|
|
344
|
+
) -> list:
|
|
345
|
+
"""Run async tasks in parallel with concurrency limit."""
|
|
346
|
+
semaphore = asyncio.Semaphore(max_concurrency)
|
|
347
|
+
|
|
348
|
+
async def limited(coro):
|
|
349
|
+
async with semaphore:
|
|
350
|
+
return await coro
|
|
351
|
+
|
|
352
|
+
return await asyncio.gather(*(limited(t) for t in tasks), return_exceptions=True)
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pi-sidecar-client
|
|
3
|
+
Version: 0.1.0.dev1
|
|
4
|
+
Summary: Python client for the Pi SDK sidecar service
|
|
5
|
+
License: Apache-2.0
|
|
6
|
+
Project-URL: Repository, https://github.com/myk-org/pi-sidecar
|
|
7
|
+
Requires-Python: >=3.10
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Requires-Dist: httpx>=0.27
|
|
10
|
+
Requires-Dist: python-simple-logger
|
|
11
|
+
Dynamic: license-file
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
pi_sidecar_client/__init__.py
|
|
5
|
+
pi_sidecar_client.egg-info/PKG-INFO
|
|
6
|
+
pi_sidecar_client.egg-info/SOURCES.txt
|
|
7
|
+
pi_sidecar_client.egg-info/dependency_links.txt
|
|
8
|
+
pi_sidecar_client.egg-info/requires.txt
|
|
9
|
+
pi_sidecar_client.egg-info/top_level.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
pi_sidecar_client
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68.0", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "pi-sidecar-client"
|
|
7
|
+
version = "0.1.0.dev1"
|
|
8
|
+
description = "Python client for the Pi SDK sidecar service"
|
|
9
|
+
license = {text = "Apache-2.0"}
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
dependencies = ["httpx>=0.27", "python-simple-logger"]
|
|
12
|
+
|
|
13
|
+
[project.urls]
|
|
14
|
+
Repository = "https://github.com/myk-org/pi-sidecar"
|
|
15
|
+
|
|
16
|
+
[tool.setuptools.packages.find]
|
|
17
|
+
include = ["pi_sidecar_client*"]
|
|
18
|
+
|
|
19
|
+
[tool.pytest.ini_options]
|
|
20
|
+
asyncio_mode = "auto"
|
|
21
|
+
testpaths = ["tests/test_python"]
|
|
22
|
+
|
|
23
|
+
[tool.ruff]
|
|
24
|
+
preview = true
|
|
25
|
+
line-length = 120
|
|
26
|
+
fix = true
|
|
27
|
+
output-format = "grouped"
|
|
28
|
+
|
|
29
|
+
[tool.ruff.format]
|
|
30
|
+
exclude = [".git", ".venv", ".mypy_cache", ".tox", "__pycache__"]
|
|
31
|
+
|
|
32
|
+
[tool.ruff.lint]
|
|
33
|
+
select = ["E", "F", "W", "I", "B", "UP", "PLC0415", "ARG", "RUF059"]
|
|
34
|
+
|
|
35
|
+
[tool.ruff.lint.per-file-ignores]
|
|
36
|
+
"*" = ["E501"]
|
|
37
|
+
"/*tests/*" = ["ARG"]
|
|
38
|
+
|
|
39
|
+
[tool.mypy]
|
|
40
|
+
check_untyped_defs = false
|
|
41
|
+
disallow_any_generics = false
|
|
42
|
+
disallow_incomplete_defs = true
|
|
43
|
+
disallow_untyped_defs = false
|
|
44
|
+
no_implicit_optional = true
|
|
45
|
+
show_error_codes = true
|
|
46
|
+
warn_unused_ignores = true
|
|
47
|
+
strict_equality = true
|
|
48
|
+
extra_checks = true
|
|
49
|
+
warn_unused_configs = true
|
|
50
|
+
warn_redundant_casts = true
|
|
51
|
+
|
|
52
|
+
[[tool.mypy.overrides]]
|
|
53
|
+
module = "simple_logger.*"
|
|
54
|
+
ignore_missing_imports = true
|
|
55
|
+
|
|
56
|
+
[dependency-groups]
|
|
57
|
+
dev = [
|
|
58
|
+
"pytest",
|
|
59
|
+
"pytest-asyncio",
|
|
60
|
+
]
|