fastclaude 0.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,202 @@
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
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,6 @@
1
+ include pyproject.toml
2
+ include LICENSE
3
+ include CONTRIBUTING.md
4
+ include README.md
5
+ recursive-exclude * __pycache__
6
+ recursive-include fastclaude/data *
@@ -0,0 +1,50 @@
1
+ Metadata-Version: 2.4
2
+ Name: fastclaude
3
+ Version: 0.0.1
4
+ Summary: Small completions-style Python interface backed by the Claude CLI
5
+ Author-email: Jeremy Howard <github@jhoward.fastmail.fm>
6
+ License: Apache-2.0
7
+ Project-URL: Repository, https://github.com/AnswerDotAI/fastclaude
8
+ Project-URL: Documentation, https://AnswerDotAI.github.io/fastclaude/
9
+ Keywords: nbdev
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3 :: Only
12
+ Requires-Python: >=3.10
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: python-fastllm>=0.0.42
16
+ Provides-Extra: dev
17
+ Requires-Dist: claude-agent-sdk; extra == "dev"
18
+ Dynamic: license-file
19
+
20
+ # fastclaude
21
+
22
+
23
+ <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
24
+
25
+ `fastclaude` is a small, completions-style Python interface backed by the installed Claude Code executable. It inherits Claude CLI authentication, including OAuth and subscriptions, without requiring direct Anthropic API integration.
26
+
27
+ - accepts complete, editable histories as [`aidialog.msg_parts.Msg`](https://AnswerDotAI.github.io/aidialog/msg_parts.html#msg) objects
28
+ - compiles them into real Claude Code sessions rather than flattening them into a prompt
29
+ - lets Claude own the live agent loop
30
+ - exposes ordinary annotated Python callables as tools
31
+ - streams Claude output and supports native interruption
32
+ - remains stateless across requests
33
+
34
+ See [DEV.md](DEV.md) for the complete design, protocol findings, source references, and implementation.
35
+
36
+ ## Installation
37
+
38
+ ``` sh
39
+ pip install fastclaude
40
+ ```
41
+
42
+ ## Development
43
+
44
+ ``` sh
45
+ pip install -e .
46
+ ```
47
+
48
+ ## License
49
+
50
+ Apache License 2.0.
@@ -0,0 +1,31 @@
1
+ # fastclaude
2
+
3
+
4
+ <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
5
+
6
+ `fastclaude` is a small, completions-style Python interface backed by the installed Claude Code executable. It inherits Claude CLI authentication, including OAuth and subscriptions, without requiring direct Anthropic API integration.
7
+
8
+ - accepts complete, editable histories as [`aidialog.msg_parts.Msg`](https://AnswerDotAI.github.io/aidialog/msg_parts.html#msg) objects
9
+ - compiles them into real Claude Code sessions rather than flattening them into a prompt
10
+ - lets Claude own the live agent loop
11
+ - exposes ordinary annotated Python callables as tools
12
+ - streams Claude output and supports native interruption
13
+ - remains stateless across requests
14
+
15
+ See [DEV.md](DEV.md) for the complete design, protocol findings, source references, and implementation.
16
+
17
+ ## Installation
18
+
19
+ ``` sh
20
+ pip install fastclaude
21
+ ```
22
+
23
+ ## Development
24
+
25
+ ``` sh
26
+ pip install -e .
27
+ ```
28
+
29
+ ## License
30
+
31
+ Apache License 2.0.
@@ -0,0 +1,9 @@
1
+ """Small completions-style Python interface backed by the Claude CLI
2
+
3
+ Modules:
4
+
5
+ - `fastclaude.core`: `astream` and `ClaudeRun`: stateless completions through the installed Claude Code
6
+ - `fastclaude.protocol`: Claude Code's stream-json wire protocol: NDJSON transport, control routing, and the callable-tool bridge
7
+ - `fastclaude.session`: Read, write, and build native Claude Code session transcripts"""
8
+
9
+ __version__ = "0.0.1"
@@ -0,0 +1,72 @@
1
+ # Autogenerated by nbdev
2
+
3
+ d = { 'settings': { 'branch': 'main',
4
+ 'doc_baseurl': '/fastclaude',
5
+ 'doc_host': 'https://AnswerDotAI.github.io',
6
+ 'git_url': 'https://github.com/AnswerDotAI/fastclaude',
7
+ 'lib_path': 'fastclaude'},
8
+ 'syms': { 'fastclaude.core': { 'fastclaude.core.ClaudeRun': ('core.html#clauderun', 'fastclaude/core.py'),
9
+ 'fastclaude.core.ClaudeRun.__aiter__': ('core.html#clauderun.__aiter__', 'fastclaude/core.py'),
10
+ 'fastclaude.core.ClaudeRun.__init__': ('core.html#clauderun.__init__', 'fastclaude/core.py'),
11
+ 'fastclaude.core.ClaudeRun._cleanup': ('core.html#clauderun._cleanup', 'fastclaude/core.py'),
12
+ 'fastclaude.core.ClaudeRun._drain': ('core.html#clauderun._drain', 'fastclaude/core.py'),
13
+ 'fastclaude.core.ClaudeRun._kick': ('core.html#clauderun._kick', 'fastclaude/core.py'),
14
+ 'fastclaude.core.ClaudeRun._run': ('core.html#clauderun._run', 'fastclaude/core.py'),
15
+ 'fastclaude.core.ClaudeRun._spawn': ('core.html#clauderun._spawn', 'fastclaude/core.py'),
16
+ 'fastclaude.core.ClaudeRun._track': ('core.html#clauderun._track', 'fastclaude/core.py'),
17
+ 'fastclaude.core.ClaudeRun.aclose': ('core.html#clauderun.aclose', 'fastclaude/core.py'),
18
+ 'fastclaude.core.ClaudeRun.interrupt': ('core.html#clauderun.interrupt', 'fastclaude/core.py'),
19
+ 'fastclaude.core._flat': ('core.html#_flat', 'fastclaude/core.py'),
20
+ 'fastclaude.core._unq': ('core.html#_unq', 'fastclaude/core.py'),
21
+ 'fastclaude.core.astream': ('core.html#astream', 'fastclaude/core.py'),
22
+ 'fastclaude.core.claude_cmd': ('core.html#claude_cmd', 'fastclaude/core.py'),
23
+ 'fastclaude.core.claude_env': ('core.html#claude_env', 'fastclaude/core.py'),
24
+ 'fastclaude.core.compile_msgs': ('core.html#compile_msgs', 'fastclaude/core.py'),
25
+ 'fastclaude.core.work_dir': ('core.html#work_dir', 'fastclaude/core.py')},
26
+ 'fastclaude.protocol': { 'fastclaude.protocol.ClaudeProto': ('protocol.html#claudeproto', 'fastclaude/protocol.py'),
27
+ 'fastclaude.protocol.ClaudeProto.__init__': ( 'protocol.html#claudeproto.__init__',
28
+ 'fastclaude/protocol.py'),
29
+ 'fastclaude.protocol.ClaudeProto._handle': ( 'protocol.html#claudeproto._handle',
30
+ 'fastclaude/protocol.py'),
31
+ 'fastclaude.protocol.ClaudeProto._resolve': ( 'protocol.html#claudeproto._resolve',
32
+ 'fastclaude/protocol.py'),
33
+ 'fastclaude.protocol.ClaudeProto.aclose': ( 'protocol.html#claudeproto.aclose',
34
+ 'fastclaude/protocol.py'),
35
+ 'fastclaude.protocol.ClaudeProto.events': ( 'protocol.html#claudeproto.events',
36
+ 'fastclaude/protocol.py'),
37
+ 'fastclaude.protocol.ClaudeProto.initialize': ( 'protocol.html#claudeproto.initialize',
38
+ 'fastclaude/protocol.py'),
39
+ 'fastclaude.protocol.ClaudeProto.interrupt': ( 'protocol.html#claudeproto.interrupt',
40
+ 'fastclaude/protocol.py'),
41
+ 'fastclaude.protocol.ClaudeProto.send': ('protocol.html#claudeproto.send', 'fastclaude/protocol.py'),
42
+ 'fastclaude.protocol.ClaudeProto.send_req': ( 'protocol.html#claudeproto.send_req',
43
+ 'fastclaude/protocol.py'),
44
+ 'fastclaude.protocol.mcp_dispatch': ('protocol.html#mcp_dispatch', 'fastclaude/protocol.py'),
45
+ 'fastclaude.protocol.mk_tools': ('protocol.html#mk_tools', 'fastclaude/protocol.py'),
46
+ 'fastclaude.protocol.read_msgs': ('protocol.html#read_msgs', 'fastclaude/protocol.py'),
47
+ 'fastclaude.protocol.tool_content': ('protocol.html#tool_content', 'fastclaude/protocol.py'),
48
+ 'fastclaude.protocol.tool_spec': ('protocol.html#tool_spec', 'fastclaude/protocol.py')},
49
+ 'fastclaude.session': { 'fastclaude.session._chain': ('session.html#_chain', 'fastclaude/session.py'),
50
+ 'fastclaude.session._est_toks': ('session.html#_est_toks', 'fastclaude/session.py'),
51
+ 'fastclaude.session._now': ('session.html#_now', 'fastclaude/session.py'),
52
+ 'fastclaude.session._txts': ('session.html#_txts', 'fastclaude/session.py'),
53
+ 'fastclaude.session.append_sess': ('session.html#append_sess', 'fastclaude/session.py'),
54
+ 'fastclaude.session.canon': ('session.html#canon', 'fastclaude/session.py'),
55
+ 'fastclaude.session.cur_sess': ('session.html#cur_sess', 'fastclaude/session.py'),
56
+ 'fastclaude.session.load_recs': ('session.html#load_recs', 'fastclaude/session.py'),
57
+ 'fastclaude.session.load_sess': ('session.html#load_sess', 'fastclaude/session.py'),
58
+ 'fastclaude.session.mk_rec': ('session.html#mk_rec', 'fastclaude/session.py'),
59
+ 'fastclaude.session.mk_tr': ('session.html#mk_tr', 'fastclaude/session.py'),
60
+ 'fastclaude.session.mk_tu': ('session.html#mk_tu', 'fastclaude/session.py'),
61
+ 'fastclaude.session.msgs2recs': ('session.html#msgs2recs', 'fastclaude/session.py'),
62
+ 'fastclaude.session.msgs2sess': ('session.html#msgs2sess', 'fastclaude/session.py'),
63
+ 'fastclaude.session.prefix_tools': ('session.html#prefix_tools', 'fastclaude/session.py'),
64
+ 'fastclaude.session.rec_txt': ('session.html#rec_txt', 'fastclaude/session.py'),
65
+ 'fastclaude.session.save_sess': ('session.html#save_sess', 'fastclaude/session.py'),
66
+ 'fastclaude.session.sess_dir': ('session.html#sess_dir', 'fastclaude/session.py'),
67
+ 'fastclaude.session.sess_file': ('session.html#sess_file', 'fastclaude/session.py'),
68
+ 'fastclaude.session.sess_id': ('session.html#sess_id', 'fastclaude/session.py'),
69
+ 'fastclaude.session.sess_thread': ('session.html#sess_thread', 'fastclaude/session.py'),
70
+ 'fastclaude.session.stable_uuid': ('session.html#stable_uuid', 'fastclaude/session.py'),
71
+ 'fastclaude.session.tool_turn': ('session.html#tool_turn', 'fastclaude/session.py'),
72
+ 'fastclaude.session.uniq_path': ('session.html#uniq_path', 'fastclaude/session.py')}}}
@@ -0,0 +1,200 @@
1
+ """`astream` and `ClaudeRun`: stateless completions through the installed Claude Code
2
+
3
+ `astream(msgs, ...)` returns a `ClaudeRun`: one stateless completion through the installed `claude`, using its login and subscription. The complete history (as `aidialog.msg_parts.Msg`s, ending with a real user prompt) is compiled into a native transcript via `fastclaude.session` under a fresh random session id and resumed; callable tools are served in-process via `fastclaude.protocol`; iteration yields the raw stream-json events; `.messages` accumulates the canonical trace (signatures intact, tool names unqualified) and `.result` the terminal result, so the next request can replay everything. `run.interrupt()` ends a turn natively, and closing the stream interrupts, drains, escalates to terminate/kill, and removes the transcript. Runs default to an isolated XDG cache work dir, so no real project's sessions or settings are touched; pass `cwd=` for project context, and `native_tools=` to enable built-ins such as `'WebSearch'`.
4
+
5
+ Docs: https://AnswerDotAI.github.io/fastclaude/core.html.md"""
6
+
7
+ # AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/02_core.ipynb.
8
+
9
+ # %% auto #0
10
+ __all__ = ['MCP_SERVER', 'MCP_PREFIX', 'SERVER_TOOLS', 'work_dir', 'compile_msgs', 'claude_cmd', 'claude_env', 'ClaudeRun',
11
+ 'astream']
12
+
13
+ # %% ../nbs/02_core.ipynb #326ece78
14
+ import asyncio, json, os, shutil, uuid
15
+ from contextlib import suppress
16
+ from fastcore.utils import *
17
+ from fastcore.meta import delegates
18
+ from fastcore.xdg import xdg_cache_home
19
+ from fastllm.anthropic import denorm_msgs, norm_parts
20
+ from fastllm.types import unwrap_typed
21
+ from aidialog.msg_parts import Msg, Text, ToolUse, ToolResult, Media
22
+ from .session import *
23
+ from .protocol import *
24
+
25
+ # %% ../nbs/02_core.ipynb #b5122707
26
+ MCP_SERVER = 'fastclaude'
27
+ MCP_PREFIX = f'mcp__{MCP_SERVER}__'
28
+ SERVER_TOOLS = ('WebSearch','WebFetch')
29
+
30
+ def work_dir():
31
+ "The default run directory: an isolated pseudo-project under the XDG cache dir"
32
+ p = xdg_cache_home()/'fastclaude'
33
+ p.mkdir(parents=True, exist_ok=True)
34
+ return p
35
+
36
+ # %% ../nbs/02_core.ipynb #7feb4c5d
37
+ def compile_msgs(
38
+ msgs, # Complete history as `Msg`s, ending with a real user prompt
39
+ ):
40
+ "`(history, prompt)`: qualified wire messages for the transcript, and the live turn's content"
41
+ msgs = listify(msgs)
42
+ if not msgs: raise ValueError('empty message history')
43
+ last = msgs[-1]
44
+ if last.role!='user' or not any(isinstance(p, (Text,Media)) for p in last.content):
45
+ raise ValueError('history must end with a user message containing a real prompt, not only tool results')
46
+ den = denorm_msgs(msgs)
47
+ return prefix_tools(den[:-1], MCP_PREFIX, skip=SERVER_TOOLS), den[-1]['content']
48
+
49
+ # %% ../nbs/02_core.ipynb #0c3b7a6a
50
+ def claude_cmd(
51
+ model=None, # Model alias or full name; None uses the user's default
52
+ resume=None, # Session id to resume, i.e. the transcript just written
53
+ system=None, # System prompt; None keeps Claude Code's own
54
+ tools=False, # Offer the private SDK MCP server?
55
+ native_tools=(), # Built-in Claude Code tools to enable, e.g. 'WebSearch'
56
+ allowed=(), # `--allowedTools` entries, e.g. qualified callable names
57
+ claude_path=None, # Explicit claude executable; found on PATH if None
58
+ ):
59
+ "argv for one headless stream-json claude run"
60
+ c = [str(claude_path or shutil.which('claude') or 'claude'), '--output-format','stream-json',
61
+ '--input-format','stream-json', '--verbose', '--include-partial-messages']
62
+ if model: c += ['--model', model]
63
+ if system is not None: c += ['--system-prompt', system]
64
+ if resume: c += [f'--resume={resume}']
65
+ if tools: c += ['--mcp-config', json.dumps(dict(mcpServers={MCP_SERVER: dict(type='sdk', name=MCP_SERVER)}))]
66
+ c.append('--strict-mcp-config')
67
+ c += ['--tools', ','.join(native_tools)]
68
+ if allowed: c += ['--allowedTools', ','.join(allowed)]
69
+ return c
70
+
71
+ def claude_env():
72
+ "A child environment that cannot bill an API key and does not think it is nested"
73
+ env = dict(os.environ, ANTHROPIC_API_KEY='')
74
+ env.pop('CLAUDECODE', None)
75
+ return env
76
+
77
+ # %% ../nbs/02_core.ipynb #ad501dc1
78
+ class ClaudeRun:
79
+ "One stateless completion: a fresh transcript, one claude process, streamed events, a canonical trace"
80
+ def __init__(self,
81
+ msgs, # Complete history as `Msg`s, ending with a real user prompt
82
+ model='sonnet', # Model alias or full name
83
+ system=None, # System prompt; None keeps Claude Code's own
84
+ tools=None, # Callable tools, in either `tool_spec` form
85
+ cwd=None, # Project directory for the run; the isolated `work_dir()` if None
86
+ native_tools=(), # Built-in Claude Code tools to enable, e.g. 'WebSearch'
87
+ claude_path=None, # Explicit claude executable; found on PATH if None
88
+ ):
89
+ store_attr()
90
+ self.messages,self.result,self.proc,self.proto = [],None,None,None
91
+ self._names,self._closed,self._spath = {},False,None
92
+
93
+ def __aiter__(self):
94
+ if not hasattr(self, '_it'): self._it = self._run()
95
+ return self._it
96
+
97
+ @delegates(ClaudeRun)
98
+ def astream(msgs, **kwargs):
99
+ "Start one stateless completion; iterate the returned `ClaudeRun` for its raw events"
100
+ return ClaudeRun(msgs, **kwargs)
101
+
102
+ # %% ../nbs/02_core.ipynb #e5bc11c4
103
+ @patch
104
+ async def _spawn(self:ClaudeRun):
105
+ "Compile and file the history, then start claude resuming it; returns the live turn's content"
106
+ self.cwd = Path(self.cwd) if self.cwd else work_dir()
107
+ hist,prompt = compile_msgs(self.msgs)
108
+ sid = str(uuid.uuid4())
109
+ if hist:
110
+ save_sess(msgs2recs(hist, key=sid, cwd=self.cwd), sid, self.cwd)
111
+ self._spath = sess_file(sid, self.cwd)
112
+ schemas,_ = mk_tools(self.tools or [])
113
+ allowed = [MCP_PREFIX+s['name'] for s in schemas] + list(self.native_tools)
114
+ argv = claude_cmd(self.model, resume=sid if hist else None, system=self.system, tools=bool(schemas),
115
+ native_tools=self.native_tools, allowed=allowed, claude_path=self.claude_path)
116
+ self.proc = await asyncio.create_subprocess_exec(*argv, stdin=asyncio.subprocess.PIPE,
117
+ stdout=asyncio.subprocess.PIPE, limit=2**25, cwd=self.cwd, env=claude_env())
118
+ self.proto = ClaudeProto(self.proc, tools=self.tools, server=MCP_SERVER)
119
+ return prompt
120
+
121
+ # %% ../nbs/02_core.ipynb #8d5f8fe6
122
+ def _unq(nm): return nm[len(MCP_PREFIX):] if nm and nm.startswith(MCP_PREFIX) else nm
123
+ def _flat(c): return c if isinstance(c, str) else '\n'.join(b.get('text','') for b in c if b.get('type')=='text')
124
+
125
+ @patch
126
+ def _track(self:ClaudeRun, m):
127
+ "Fold one raw event into `.messages` and `.result`"
128
+ t,c = m.get('type'), nested_idx(m, 'message', 'content')
129
+ if t=='assistant' and isinstance(c, list):
130
+ parts = norm_parts(m['message'])
131
+ for p in parts:
132
+ if isinstance(p, ToolUse): p.name = self._names[p.id] = _unq(p.name)
133
+ self.messages.append(Msg('assistant', parts))
134
+ elif t=='user' and isinstance(c, list) and c and all(b.get('type')=='tool_result' for b in c):
135
+ self.messages.append(Msg('tool', [ToolResult(id=b.get('tool_use_id'), name=self._names.get(b.get('tool_use_id')),
136
+ text=unwrap_typed(_flat(b.get('content','')))) for b in c]))
137
+ elif t=='result': self.result = m
138
+
139
+ # %% ../nbs/02_core.ipynb #ea5dbde9
140
+ @patch
141
+ async def _kick(self:ClaudeRun, prompt):
142
+ "Handshake, then the one live user turn"
143
+ await self.proto.initialize()
144
+ await self.proto.send(dict(type='user', message=dict(role='user', content=prompt)))
145
+
146
+ @patch
147
+ async def _run(self:ClaudeRun):
148
+ "The event stream: spawn, kick off, yield raw events until the terminal result"
149
+ prompt = await self._spawn()
150
+ kick = asyncio.create_task(self._kick(prompt))
151
+ try:
152
+ async for m in self.proto.events():
153
+ self._track(m)
154
+ yield m
155
+ if m.get('type')=='result': break
156
+ finally:
157
+ kick.cancel()
158
+ await self.aclose()
159
+
160
+ @patch
161
+ async def interrupt(self:ClaudeRun, timeout=30):
162
+ "Claude's native interrupt: end the current turn; the stream stays open to drain the aborted tail"
163
+ return await self.proto.interrupt(timeout)
164
+
165
+ # %% ../nbs/02_core.ipynb #d1f78540
166
+ @patch
167
+ async def _drain(self:ClaudeRun, timeout=10):
168
+ "Read the aborted turn's tail directly, resolving control responses and folding events into the trace"
169
+ async def _go():
170
+ async for m in read_msgs(self.proc.stdout):
171
+ if m.get('type')=='control_response': self.proto._resolve(m)
172
+ else: self._track(m)
173
+ if m.get('type')=='result': return
174
+ with suppress(Exception): await asyncio.wait_for(_go(), timeout)
175
+
176
+ @patch
177
+ async def _cleanup(self:ClaudeRun):
178
+ p = self.proc
179
+ if p and p.returncode is None:
180
+ if self.result is None and p.stdin and not p.stdin.is_closing():
181
+ t = asyncio.create_task(self._drain())
182
+ with suppress(Exception): await asyncio.wait_for(self.proto.interrupt(), 5)
183
+ await t
184
+ with suppress(Exception): p.stdin.close()
185
+ try: await asyncio.wait_for(p.wait(), 5)
186
+ except (TimeoutError, asyncio.TimeoutError):
187
+ with suppress(ProcessLookupError): p.terminate()
188
+ try: await asyncio.wait_for(p.wait(), 5)
189
+ except (TimeoutError, asyncio.TimeoutError):
190
+ with suppress(ProcessLookupError): p.kill()
191
+ with suppress(Exception): await p.wait()
192
+ if self.proto: await self.proto.aclose()
193
+ if self._spath: Path(self._spath).unlink(missing_ok=True)
194
+
195
+ @patch
196
+ async def aclose(self:ClaudeRun):
197
+ "Interrupt if mid-turn, drain, close, escalate, and remove the transcript; idempotent and cancellation-shielded"
198
+ if self._closed: return
199
+ self._closed = True
200
+ await asyncio.shield(asyncio.create_task(self._cleanup()))