grains-cli 0.1.0__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.
- grains_cli-0.1.0/LICENSE +202 -0
- grains_cli-0.1.0/PKG-INFO +47 -0
- grains_cli-0.1.0/README.md +22 -0
- grains_cli-0.1.0/grains_cli/__init__.py +1 -0
- grains_cli-0.1.0/grains_cli/dev.py +149 -0
- grains_cli-0.1.0/grains_cli/init.py +79 -0
- grains_cli-0.1.0/grains_cli/main.py +54 -0
- grains_cli-0.1.0/grains_cli/pay.py +144 -0
- grains_cli-0.1.0/grains_cli/templates.py +61 -0
- grains_cli-0.1.0/grains_cli/verify.py +36 -0
- grains_cli-0.1.0/grains_cli.egg-info/PKG-INFO +47 -0
- grains_cli-0.1.0/grains_cli.egg-info/SOURCES.txt +20 -0
- grains_cli-0.1.0/grains_cli.egg-info/dependency_links.txt +1 -0
- grains_cli-0.1.0/grains_cli.egg-info/entry_points.txt +2 -0
- grains_cli-0.1.0/grains_cli.egg-info/requires.txt +3 -0
- grains_cli-0.1.0/grains_cli.egg-info/top_level.txt +1 -0
- grains_cli-0.1.0/pyproject.toml +34 -0
- grains_cli-0.1.0/setup.cfg +4 -0
- grains_cli-0.1.0/tests/test_dev.py +181 -0
- grains_cli-0.1.0/tests/test_init.py +114 -0
- grains_cli-0.1.0/tests/test_pay.py +133 -0
- grains_cli-0.1.0/tests/test_verify.py +29 -0
grains_cli-0.1.0/LICENSE
ADDED
|
@@ -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,47 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: grains-cli
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Command-line tools for Grains: build, run, deploy, and pay AI agents.
|
|
5
|
+
Author: Grains
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://grains.run
|
|
8
|
+
Project-URL: Documentation, https://grains.run/docs.html
|
|
9
|
+
Project-URL: Repository, https://github.com/0000F8/grains
|
|
10
|
+
Keywords: ai,agents,llm,claude,mcp,x402,hosting
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
18
|
+
Requires-Python: >=3.10
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
License-File: LICENSE
|
|
21
|
+
Requires-Dist: grains-sdk[crypto]>=0.1.0
|
|
22
|
+
Requires-Dist: httpx
|
|
23
|
+
Requires-Dist: eth-account>=0.11
|
|
24
|
+
Dynamic: license-file
|
|
25
|
+
|
|
26
|
+
# grains-cli
|
|
27
|
+
|
|
28
|
+
Command-line tools for [Grains](https://grains.run) — build, run, deploy, and
|
|
29
|
+
pay AI agents.
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
pip install grains-cli
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Provides the `grains` command:
|
|
36
|
+
|
|
37
|
+
- `grains init` — scaffold an agent in the current directory (auto-detects
|
|
38
|
+
CrewAI / LangChain / LangGraph, or a plain handler).
|
|
39
|
+
- `grains dev` — run your agent locally against a task API.
|
|
40
|
+
- `grains verify <receipt.json>` — verify a payment receipt offline.
|
|
41
|
+
- `grains pay <api-url> <agent>` — pay a priced agent (x402 / EIP-3009) and
|
|
42
|
+
submit a task.
|
|
43
|
+
|
|
44
|
+
To deploy from inside Claude instead, use
|
|
45
|
+
[`grains-mcp`](https://pypi.org/project/grains-mcp/).
|
|
46
|
+
|
|
47
|
+
Docs: https://grains.run/docs.html · License: Apache-2.0
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# grains-cli
|
|
2
|
+
|
|
3
|
+
Command-line tools for [Grains](https://grains.run) — build, run, deploy, and
|
|
4
|
+
pay AI agents.
|
|
5
|
+
|
|
6
|
+
```bash
|
|
7
|
+
pip install grains-cli
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
Provides the `grains` command:
|
|
11
|
+
|
|
12
|
+
- `grains init` — scaffold an agent in the current directory (auto-detects
|
|
13
|
+
CrewAI / LangChain / LangGraph, or a plain handler).
|
|
14
|
+
- `grains dev` — run your agent locally against a task API.
|
|
15
|
+
- `grains verify <receipt.json>` — verify a payment receipt offline.
|
|
16
|
+
- `grains pay <api-url> <agent>` — pay a priced agent (x402 / EIP-3009) and
|
|
17
|
+
submit a task.
|
|
18
|
+
|
|
19
|
+
To deploy from inside Claude instead, use
|
|
20
|
+
[`grains-mcp`](https://pypi.org/project/grains-mcp/).
|
|
21
|
+
|
|
22
|
+
Docs: https://grains.run/docs.html · License: Apache-2.0
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""grains-cli: the `grains` console script (init, dev)."""
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
"""`grains dev` -- local task API backed by stdlib http.server."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import asyncio
|
|
5
|
+
import importlib.util
|
|
6
|
+
import json
|
|
7
|
+
import sys
|
|
8
|
+
import threading
|
|
9
|
+
import tomllib
|
|
10
|
+
import uuid
|
|
11
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from grains import Task, agent
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class _TaskStore:
|
|
18
|
+
def __init__(self):
|
|
19
|
+
self._lock = threading.Lock()
|
|
20
|
+
self._tasks: dict[str, dict] = {}
|
|
21
|
+
|
|
22
|
+
def create(self) -> str:
|
|
23
|
+
task_id = uuid.uuid4().hex
|
|
24
|
+
with self._lock:
|
|
25
|
+
self._tasks[task_id] = {"status": "queued", "reply": None, "error": None}
|
|
26
|
+
return task_id
|
|
27
|
+
|
|
28
|
+
def set(self, task_id: str, **fields) -> None:
|
|
29
|
+
with self._lock:
|
|
30
|
+
self._tasks[task_id].update(fields)
|
|
31
|
+
|
|
32
|
+
def get(self, task_id: str) -> dict | None:
|
|
33
|
+
with self._lock:
|
|
34
|
+
task = self._tasks.get(task_id)
|
|
35
|
+
return dict(task) if task is not None else None
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _load_entrypoint(target: Path, entrypoint: str):
|
|
39
|
+
module_name, _, func_name = entrypoint.partition(":")
|
|
40
|
+
if not module_name or not func_name:
|
|
41
|
+
raise ValueError(f"invalid entrypoint {entrypoint!r}; expected 'module:function'")
|
|
42
|
+
module_path = target / f"{module_name}.py"
|
|
43
|
+
spec = importlib.util.spec_from_file_location(module_name, module_path)
|
|
44
|
+
module = importlib.util.module_from_spec(spec)
|
|
45
|
+
sys.path.insert(0, str(target))
|
|
46
|
+
try:
|
|
47
|
+
spec.loader.exec_module(module)
|
|
48
|
+
finally:
|
|
49
|
+
sys.path.remove(str(target))
|
|
50
|
+
return getattr(module, func_name)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _run_task(task_id: str, store: _TaskStore, text: str, payload: dict) -> None:
|
|
54
|
+
store.set(task_id, status="working")
|
|
55
|
+
task = Task(id=task_id, text=text, payload=payload)
|
|
56
|
+
try:
|
|
57
|
+
reply = asyncio.run(agent.invoke(task))
|
|
58
|
+
except Exception as exc: # noqa: BLE001 -- surface any handler failure to the caller
|
|
59
|
+
store.set(task_id, status="failed", error=str(exc))
|
|
60
|
+
return
|
|
61
|
+
store.set(
|
|
62
|
+
task_id,
|
|
63
|
+
status="done",
|
|
64
|
+
reply={"text": reply.text, "data": reply.data},
|
|
65
|
+
charges=[{"value": c.value, "currency": c.currency} for c in task.charges],
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class _Handler(BaseHTTPRequestHandler):
|
|
70
|
+
store: _TaskStore
|
|
71
|
+
|
|
72
|
+
def log_message(self, *args) -> None: # silence default request logging
|
|
73
|
+
pass
|
|
74
|
+
|
|
75
|
+
def _json(self, code: int, body: dict) -> None:
|
|
76
|
+
payload = json.dumps(body).encode()
|
|
77
|
+
self.send_response(code)
|
|
78
|
+
self.send_header("Content-Type", "application/json")
|
|
79
|
+
self.send_header("Content-Length", str(len(payload)))
|
|
80
|
+
self.end_headers()
|
|
81
|
+
self.wfile.write(payload)
|
|
82
|
+
|
|
83
|
+
def do_GET(self) -> None:
|
|
84
|
+
if self.path == "/healthz":
|
|
85
|
+
self._json(200, {"status": "ok"})
|
|
86
|
+
return
|
|
87
|
+
if self.path.startswith("/tasks/"):
|
|
88
|
+
task_id = self.path[len("/tasks/"):]
|
|
89
|
+
task = self.store.get(task_id)
|
|
90
|
+
if task is None:
|
|
91
|
+
self._json(404, {"error": "task not found"})
|
|
92
|
+
return
|
|
93
|
+
self._json(200, task)
|
|
94
|
+
return
|
|
95
|
+
self._json(404, {"error": "not found"})
|
|
96
|
+
|
|
97
|
+
def do_POST(self) -> None:
|
|
98
|
+
if self.path != "/tasks":
|
|
99
|
+
self._json(404, {"error": "not found"})
|
|
100
|
+
return
|
|
101
|
+
try:
|
|
102
|
+
length = int(self.headers.get("Content-Length", 0))
|
|
103
|
+
except ValueError:
|
|
104
|
+
self._json(400, {"error": "invalid Content-Length"})
|
|
105
|
+
return
|
|
106
|
+
raw = self.rfile.read(length) if length else b"{}"
|
|
107
|
+
try:
|
|
108
|
+
body = json.loads(raw or b"{}")
|
|
109
|
+
except json.JSONDecodeError:
|
|
110
|
+
self._json(400, {"error": "invalid JSON"})
|
|
111
|
+
return
|
|
112
|
+
if not isinstance(body, dict):
|
|
113
|
+
self._json(400, {"error": "body must be a JSON object"})
|
|
114
|
+
return
|
|
115
|
+
task_id = self.store.create()
|
|
116
|
+
threading.Thread(
|
|
117
|
+
target=_run_task,
|
|
118
|
+
args=(task_id, self.store, body.get("text", ""), body.get("payload", {})),
|
|
119
|
+
daemon=True,
|
|
120
|
+
).start()
|
|
121
|
+
self._json(202, {"task_id": task_id})
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def serve(path: str, port: int = 0) -> ThreadingHTTPServer:
|
|
125
|
+
"""Load grains.toml + the entrypoint and start the task API in a background thread."""
|
|
126
|
+
target = Path(path).resolve()
|
|
127
|
+
config = tomllib.loads((target / "grains.toml").read_text())
|
|
128
|
+
handler_func = _load_entrypoint(target, config["agent"]["entrypoint"])
|
|
129
|
+
agent.handler(handler_func)
|
|
130
|
+
|
|
131
|
+
store = _TaskStore()
|
|
132
|
+
bound_handler = type("_BoundHandler", (_Handler,), {"store": store})
|
|
133
|
+
server = ThreadingHTTPServer(("127.0.0.1", port), bound_handler)
|
|
134
|
+
threading.Thread(target=server.serve_forever, daemon=True).start()
|
|
135
|
+
return server
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def cmd_dev(args) -> int:
|
|
139
|
+
server = serve(args.path, args.port)
|
|
140
|
+
host, port = server.server_address
|
|
141
|
+
print(f"grains dev listening on http://{host}:{port}")
|
|
142
|
+
try:
|
|
143
|
+
threading.Event().wait()
|
|
144
|
+
except KeyboardInterrupt:
|
|
145
|
+
pass
|
|
146
|
+
finally:
|
|
147
|
+
server.shutdown()
|
|
148
|
+
server.server_close()
|
|
149
|
+
return 0
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""`grains init` -- scaffold grains_app.py + grains.toml for a target project."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import re
|
|
5
|
+
import tomllib
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from . import templates
|
|
9
|
+
|
|
10
|
+
_FRAMEWORK_PRIORITY = ("crewai", "langgraph", "langchain")
|
|
11
|
+
_DEP_NAME_SPLIT = re.compile(r"[<>=!~\[; ]")
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _dep_names_from_requirements(path: Path) -> set[str]:
|
|
15
|
+
names = set()
|
|
16
|
+
if not path.exists():
|
|
17
|
+
return names
|
|
18
|
+
for line in path.read_text().splitlines():
|
|
19
|
+
line = line.split("#", 1)[0].strip()
|
|
20
|
+
if not line:
|
|
21
|
+
continue
|
|
22
|
+
name = _DEP_NAME_SPLIT.split(line, maxsplit=1)[0].strip().lower()
|
|
23
|
+
if name:
|
|
24
|
+
names.add(name)
|
|
25
|
+
return names
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _dep_names_from_pyproject(path: Path) -> set[str]:
|
|
29
|
+
names = set()
|
|
30
|
+
if not path.exists():
|
|
31
|
+
return names
|
|
32
|
+
try:
|
|
33
|
+
data = tomllib.loads(path.read_text())
|
|
34
|
+
except tomllib.TOMLDecodeError:
|
|
35
|
+
return names
|
|
36
|
+
deps = list(data.get("project", {}).get("dependencies", []))
|
|
37
|
+
deps.extend(data.get("tool", {}).get("poetry", {}).get("dependencies", {}).keys())
|
|
38
|
+
for dep in deps:
|
|
39
|
+
name = _DEP_NAME_SPLIT.split(dep, maxsplit=1)[0].strip().lower()
|
|
40
|
+
if name and name != "python":
|
|
41
|
+
names.add(name)
|
|
42
|
+
return names
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def detect_framework(target: Path) -> str:
|
|
46
|
+
names = _dep_names_from_requirements(target / "requirements.txt")
|
|
47
|
+
names |= _dep_names_from_pyproject(target / "pyproject.toml")
|
|
48
|
+
for framework in _FRAMEWORK_PRIORITY:
|
|
49
|
+
if framework in names:
|
|
50
|
+
return framework
|
|
51
|
+
return "none"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _sanitize_name(name: str) -> str:
|
|
55
|
+
name = re.sub(r"[^a-z0-9-]+", "-", name.lower())
|
|
56
|
+
name = re.sub(r"-+", "-", name).strip("-")
|
|
57
|
+
return name or "agent"
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def cmd_init(args) -> int:
|
|
61
|
+
target = Path(args.path).resolve()
|
|
62
|
+
target.mkdir(parents=True, exist_ok=True)
|
|
63
|
+
app_path = target / "grains_app.py"
|
|
64
|
+
toml_path = target / "grains.toml"
|
|
65
|
+
|
|
66
|
+
if not args.force:
|
|
67
|
+
existing = [p.name for p in (app_path, toml_path) if p.exists()]
|
|
68
|
+
if existing:
|
|
69
|
+
print(f"refusing to overwrite existing file(s): {', '.join(existing)} (use --force)")
|
|
70
|
+
return 1
|
|
71
|
+
|
|
72
|
+
framework = args.template or detect_framework(target)
|
|
73
|
+
app_path.write_text(templates.render_app(framework))
|
|
74
|
+
toml_path.write_text(templates.render_toml(_sanitize_name(target.name)))
|
|
75
|
+
|
|
76
|
+
print(f"detected framework: {framework}")
|
|
77
|
+
print(f"wrote {app_path}")
|
|
78
|
+
print(f"wrote {toml_path}")
|
|
79
|
+
return 0
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""grains CLI entrypoint (console script: `grains`)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
|
|
6
|
+
from . import dev as dev_cmd
|
|
7
|
+
from . import init as init_cmd
|
|
8
|
+
from . import pay as pay_cmd
|
|
9
|
+
from . import verify as verify_cmd
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
13
|
+
parser = argparse.ArgumentParser(prog="grains", description="Grains local dev CLI")
|
|
14
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
15
|
+
|
|
16
|
+
p_init = sub.add_parser("init", help="scaffold a new agent in the target directory")
|
|
17
|
+
p_init.add_argument("path", nargs="?", default=".")
|
|
18
|
+
p_init.add_argument("--force", action="store_true", help="overwrite existing files")
|
|
19
|
+
p_init.add_argument(
|
|
20
|
+
"--template",
|
|
21
|
+
choices=["crewai", "langgraph", "langchain", "none"],
|
|
22
|
+
default=None,
|
|
23
|
+
help="force a template instead of auto-detecting the framework",
|
|
24
|
+
)
|
|
25
|
+
p_init.set_defaults(func=init_cmd.cmd_init)
|
|
26
|
+
|
|
27
|
+
p_dev = sub.add_parser("dev", help="run the agent locally with a task API")
|
|
28
|
+
p_dev.add_argument("path", nargs="?", default=".")
|
|
29
|
+
p_dev.add_argument("--port", type=int, default=8787)
|
|
30
|
+
p_dev.set_defaults(func=dev_cmd.cmd_dev)
|
|
31
|
+
|
|
32
|
+
p_verify = sub.add_parser("verify", help="verify a payment receipt offline")
|
|
33
|
+
p_verify.add_argument("path", help="path to a receipt JSON file")
|
|
34
|
+
p_verify.set_defaults(func=verify_cmd.cmd_verify)
|
|
35
|
+
|
|
36
|
+
p_pay = sub.add_parser("pay", help="submit a task, paying via x402 if the agent is priced")
|
|
37
|
+
p_pay.add_argument("api_url", help="agents base URL, e.g. https://agents.grains.run")
|
|
38
|
+
p_pay.add_argument("agent", help="agent name")
|
|
39
|
+
p_pay.add_argument("--key", help="hex-encoded payer private key (or set GRAINS_PAYER_KEY)")
|
|
40
|
+
p_pay.add_argument("--text", required=True, help="task text")
|
|
41
|
+
p_pay.add_argument("--caller-token", default=None, help="grains_ct_... caller token, if required")
|
|
42
|
+
p_pay.set_defaults(func=pay_cmd.cmd_pay)
|
|
43
|
+
|
|
44
|
+
return parser
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def main(argv: list[str] | None = None) -> int:
|
|
48
|
+
parser = build_parser()
|
|
49
|
+
args = parser.parse_args(argv)
|
|
50
|
+
return args.func(args)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
if __name__ == "__main__":
|
|
54
|
+
raise SystemExit(main())
|