nagent 1.0.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.
@@ -0,0 +1,4 @@
1
+ dist/
2
+ build/
3
+ *.egg-info/
4
+ __pycache__/
nagent-1.0.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 PWIN Technologies Pvt Ltd
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
nagent-1.0.0/PKG-INFO ADDED
@@ -0,0 +1,60 @@
1
+ Metadata-Version: 2.5
2
+ Name: nagent
3
+ Version: 1.0.0
4
+ Summary: Run your Nagent agents from Python: a thin client over the Nagent REST API.
5
+ Project-URL: Homepage, https://nagent.ai/developers
6
+ Project-URL: Source, https://github.com/PWIN-Technologies-Pvt-Ltd/nagent-website/tree/staging/packages/nagent-python
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Keywords: agents,ai,api,mcp,nagent,sdk
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Typing :: Typed
13
+ Requires-Python: >=3.9
14
+ Description-Content-Type: text/markdown
15
+
16
+ # nagent
17
+
18
+ Run your Nagent agents from Python. A thin client over the Nagent REST API
19
+ (`/api/v1`), standard library only, Python 3.9 and later.
20
+
21
+ ```bash
22
+ pip install nagent
23
+ ```
24
+
25
+ Create an API key in Nagent at Settings, API & MCP
26
+ (https://nagent.ai/admin/settings/api) and set it as `NAGENT_API_KEY`.
27
+
28
+ ```python
29
+ import os
30
+ from nagent import Nagent
31
+
32
+ nagent = Nagent(api_key=os.environ["NAGENT_API_KEY"])
33
+
34
+ # A finished run
35
+ run = nagent.runs.create("nora", input="Research retail-1.example")
36
+ print(run["status"], run["output"])
37
+
38
+ # A long run: accepted at once, then waited on
39
+ accepted = nagent.runs.create("nora", input="Audit retail-1.example", wait=False)
40
+ run = nagent.runs.wait(accepted["id"])
41
+
42
+ # A conversation: the same session_id carries the earlier turns
43
+ nagent.runs.create("nora", input="And their competitors?", session_id="crm-4711")
44
+
45
+ # Approvals, every page
46
+ for approval in nagent.approvals.iter():
47
+ print(approval["id"], approval["action"])
48
+ ```
49
+
50
+ Verify a webhook delivery with the raw body:
51
+
52
+ ```python
53
+ from nagent import verify_webhook
54
+
55
+ ok = verify_webhook(os.environ["NAGENT_WEBHOOK_SECRET"], request.headers, request.get_data())
56
+ ```
57
+
58
+ Every method maps to one operation in `/api/v1/openapi.json`. Errors raise
59
+ `NagentError` with `status`, `code`, the problem document and the request
60
+ id. Full reference: https://nagent.ai/developers
nagent-1.0.0/README.md ADDED
@@ -0,0 +1,45 @@
1
+ # nagent
2
+
3
+ Run your Nagent agents from Python. A thin client over the Nagent REST API
4
+ (`/api/v1`), standard library only, Python 3.9 and later.
5
+
6
+ ```bash
7
+ pip install nagent
8
+ ```
9
+
10
+ Create an API key in Nagent at Settings, API & MCP
11
+ (https://nagent.ai/admin/settings/api) and set it as `NAGENT_API_KEY`.
12
+
13
+ ```python
14
+ import os
15
+ from nagent import Nagent
16
+
17
+ nagent = Nagent(api_key=os.environ["NAGENT_API_KEY"])
18
+
19
+ # A finished run
20
+ run = nagent.runs.create("nora", input="Research retail-1.example")
21
+ print(run["status"], run["output"])
22
+
23
+ # A long run: accepted at once, then waited on
24
+ accepted = nagent.runs.create("nora", input="Audit retail-1.example", wait=False)
25
+ run = nagent.runs.wait(accepted["id"])
26
+
27
+ # A conversation: the same session_id carries the earlier turns
28
+ nagent.runs.create("nora", input="And their competitors?", session_id="crm-4711")
29
+
30
+ # Approvals, every page
31
+ for approval in nagent.approvals.iter():
32
+ print(approval["id"], approval["action"])
33
+ ```
34
+
35
+ Verify a webhook delivery with the raw body:
36
+
37
+ ```python
38
+ from nagent import verify_webhook
39
+
40
+ ok = verify_webhook(os.environ["NAGENT_WEBHOOK_SECRET"], request.headers, request.get_data())
41
+ ```
42
+
43
+ Every method maps to one operation in `/api/v1/openapi.json`. Errors raise
44
+ `NagentError` with `status`, `code`, the problem document and the request
45
+ id. Full reference: https://nagent.ai/developers
@@ -0,0 +1,26 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.24"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "nagent"
7
+ version = "1.0.0"
8
+ description = "Run your Nagent agents from Python: a thin client over the Nagent REST API."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.9"
13
+ dependencies = []
14
+ keywords = ["nagent", "agents", "ai", "mcp", "api", "sdk"]
15
+ classifiers = [
16
+ "Programming Language :: Python :: 3",
17
+ "Operating System :: OS Independent",
18
+ "Typing :: Typed",
19
+ ]
20
+
21
+ [project.urls]
22
+ Homepage = "https://nagent.ai/developers"
23
+ Source = "https://github.com/PWIN-Technologies-Pvt-Ltd/nagent-website/tree/staging/packages/nagent-python"
24
+
25
+ [tool.hatch.build.targets.wheel]
26
+ packages = ["src/nagent"]
@@ -0,0 +1,13 @@
1
+ """Run your Nagent agents from Python.
2
+
3
+ A thin client over the Nagent REST API (/api/v1). Standard library only.
4
+ Each method is one operation in /api/v1/openapi.json, named by its
5
+ operationId in a comment; a test in the main repository fails when they
6
+ drift.
7
+ """
8
+
9
+ from .client import Nagent, NagentError
10
+ from .webhooks import verify_webhook
11
+
12
+ __all__ = ["Nagent", "NagentError", "verify_webhook"]
13
+ __version__ = "1.0.0"
@@ -0,0 +1,175 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import time
5
+ import urllib.error
6
+ import urllib.parse
7
+ import urllib.request
8
+ from typing import Any, Callable, Dict, Iterator, Optional
9
+
10
+ Json = Dict[str, Any]
11
+
12
+
13
+ class NagentError(Exception):
14
+ """A call the API refused, with its RFC 9457 problem document."""
15
+
16
+ def __init__(self, problem: Json, request_id: Optional[str]):
17
+ title = problem.get("title") or "Request failed"
18
+ detail = problem.get("detail")
19
+ super().__init__(f"{title}: {detail}" if detail else title)
20
+ self.problem = problem
21
+ self.status: int = int(problem.get("status") or 0)
22
+ self.code: str = str(problem.get("type", "")).rsplit("#", 1)[-1]
23
+ self.request_id = request_id
24
+
25
+
26
+ Transport = Callable[[str, str, Dict[str, str], Optional[bytes], float], "tuple[int, Dict[str, str], bytes]"]
27
+
28
+
29
+ def _urllib_transport(method: str, url: str, headers: Dict[str, str], body: Optional[bytes], timeout: float):
30
+ req = urllib.request.Request(url, data=body, headers=headers, method=method)
31
+ try:
32
+ with urllib.request.urlopen(req, timeout=timeout) as res:
33
+ return res.status, {k.lower(): v for k, v in res.headers.items()}, res.read()
34
+ except urllib.error.HTTPError as e:
35
+ return e.code, {k.lower(): v for k, v in e.headers.items()}, e.read()
36
+
37
+
38
+ class Nagent:
39
+ """A client for one API key.
40
+
41
+ >>> nagent = Nagent(api_key=os.environ["NAGENT_API_KEY"])
42
+ >>> run = nagent.runs.create("nora", input="Research retail-1.example")
43
+ """
44
+
45
+ def __init__(self, api_key: str, base_url: str = "https://nagent.ai", timeout: float = 310.0, transport: Optional[Transport] = None):
46
+ self._key = api_key
47
+ self._base = base_url.rstrip("/") + "/api/v1"
48
+ self._timeout = timeout
49
+ self._transport = transport or _urllib_transport
50
+ self.agents = _Agents(self)
51
+ self.runs = _Runs(self)
52
+ self.approvals = _Approvals(self)
53
+ self.webhooks = _Webhooks(self)
54
+
55
+ def _call(self, method: str, path: str, body: Any = None, headers: Optional[Dict[str, str]] = None, raw: bool = False) -> Any:
56
+ h = {"Authorization": f"Bearer {self._key}", "Accept": "application/json", "User-Agent": "nagent-python/1.0.0"}
57
+ data = None
58
+ if body is not None:
59
+ h["Content-Type"] = "application/json"
60
+ data = json.dumps(body).encode()
61
+ h.update(headers or {})
62
+ status, res_headers, payload = self._transport(method, self._base + path, h, data, self._timeout)
63
+ if status >= 400:
64
+ try:
65
+ problem = json.loads(payload.decode() or "{}")
66
+ except ValueError:
67
+ problem = {"title": "HTTP error", "status": status}
68
+ problem.setdefault("status", status)
69
+ raise NagentError(problem, res_headers.get("x-request-id"))
70
+ text = payload.decode()
71
+ return text if raw else (json.loads(text) if text else None)
72
+
73
+
74
+ def _q(value: str) -> str:
75
+ return urllib.parse.quote(value, safe="")
76
+
77
+
78
+ class _Agents:
79
+ def __init__(self, c: Nagent):
80
+ self._c = c
81
+
82
+ def list(self) -> list:
83
+ """listAgents"""
84
+ return self._c._call("GET", "/agents")["data"]
85
+
86
+ def get(self, key: str) -> Json:
87
+ """getAgent"""
88
+ return self._c._call("GET", f"/agents/{_q(key)}")
89
+
90
+ def markdown(self, key: str) -> str:
91
+ """getAgentMarkdown"""
92
+ return self._c._call("GET", f"/agents/{_q(key)}/agent.md", raw=True)
93
+
94
+
95
+ class _Runs:
96
+ def __init__(self, c: Nagent):
97
+ self._c = c
98
+
99
+ def create(self, agent: str, input: str, session_id: Optional[str] = None, metadata: Optional[Dict[str, str]] = None,
100
+ idempotency_key: Optional[str] = None, wait: bool = True) -> Json:
101
+ """createRun. With wait=False the run comes back running (Prefer: respond-async)."""
102
+ body: Json = {"input": input}
103
+ if session_id is not None:
104
+ body["sessionId"] = session_id
105
+ if metadata is not None:
106
+ body["metadata"] = metadata
107
+ headers: Dict[str, str] = {}
108
+ if idempotency_key:
109
+ headers["Idempotency-Key"] = idempotency_key
110
+ if not wait:
111
+ headers["Prefer"] = "respond-async"
112
+ return self._c._call("POST", f"/agents/{_q(agent)}/runs", body, headers)
113
+
114
+ def get(self, run_id: str) -> Json:
115
+ """getRun"""
116
+ return self._c._call("GET", f"/runs/{_q(run_id)}")
117
+
118
+ def events(self, run_id: str) -> str:
119
+ """getRunEvents"""
120
+ return self._c._call("GET", f"/runs/{_q(run_id)}/events", raw=True)
121
+
122
+ def wait(self, run_id: str, timeout: float = 600.0, interval: float = 3.0, sleep: Callable[[float], None] = time.sleep) -> Json:
123
+ """Read a run until it is no longer running."""
124
+ deadline = time.monotonic() + timeout
125
+ while True:
126
+ run = self.get(run_id)
127
+ if run.get("status") != "running" or time.monotonic() >= deadline:
128
+ return run
129
+ sleep(interval)
130
+
131
+
132
+ class _Approvals:
133
+ def __init__(self, c: Nagent):
134
+ self._c = c
135
+
136
+ def list(self, status: str = "pending", limit: int = 25, cursor: Optional[str] = None) -> Json:
137
+ """listApprovals: one page, newest first, with hasMore and nextCursor."""
138
+ q = {"status": status, "limit": str(limit)}
139
+ if cursor:
140
+ q["cursor"] = cursor
141
+ return self._c._call("GET", "/approvals?" + urllib.parse.urlencode(q))
142
+
143
+ def iter(self, status: str = "pending", page_size: int = 100) -> Iterator[Json]:
144
+ """Every approval, page after page."""
145
+ cursor: Optional[str] = None
146
+ while True:
147
+ page = self.list(status=status, limit=page_size, cursor=cursor)
148
+ yield from page["data"]
149
+ if not page.get("hasMore") or not page.get("nextCursor"):
150
+ return
151
+ cursor = page["nextCursor"]
152
+
153
+ def decide(self, approval_id: str, decision: str, note: Optional[str] = None) -> Any:
154
+ """decideApproval: decision is "approve" or "reject"."""
155
+ body: Json = {"decision": decision}
156
+ if note is not None:
157
+ body["note"] = note
158
+ return self._c._call("POST", f"/approvals/{_q(approval_id)}/decide", body)
159
+
160
+
161
+ class _Webhooks:
162
+ def __init__(self, c: Nagent):
163
+ self._c = c
164
+
165
+ def list(self) -> list:
166
+ """listWebhooks"""
167
+ return self._c._call("GET", "/webhooks")["data"]
168
+
169
+ def create(self, url: str, events: list) -> Json:
170
+ """createWebhook: the response carries the signing secret, once."""
171
+ return self._c._call("POST", "/webhooks", {"url": url, "events": events})
172
+
173
+ def delete(self, endpoint_id: str) -> Json:
174
+ """deleteWebhook"""
175
+ return self._c._call("DELETE", f"/webhooks/{_q(endpoint_id)}")
File without changes
@@ -0,0 +1,38 @@
1
+ from __future__ import annotations
2
+
3
+ import base64
4
+ import hashlib
5
+ import hmac
6
+ import time
7
+ from typing import Mapping, Optional, Union
8
+
9
+
10
+ def verify_webhook(secret: str, headers: Mapping[str, str], body: Union[bytes, str], now: Optional[float] = None, tolerance: int = 300) -> bool:
11
+ """Whether a delivery is Nagent's.
12
+
13
+ Standard Webhooks: HMAC-SHA256 over "id.timestamp.body" with the
14
+ endpoint's whsec_ secret, within five minutes. Pass the raw body, before
15
+ any JSON parsing.
16
+ """
17
+ h = {k.lower(): v for k, v in headers.items()}
18
+ msg_id = h.get("webhook-id", "")
19
+ try:
20
+ ts = int(h.get("webhook-timestamp", ""))
21
+ except ValueError:
22
+ return False
23
+ if not msg_id or abs((time.time() if now is None else now) - ts) > tolerance:
24
+ return False
25
+ raw = body.encode() if isinstance(body, str) else body
26
+ key = base64.b64decode(secret[6:] if secret.startswith("whsec_") else secret)
27
+ expected = hmac.new(key, f"{msg_id}.{ts}.".encode() + raw, hashlib.sha256).digest()
28
+ for entry in h.get("webhook-signature", "").split():
29
+ version, _, sig = entry.partition(",")
30
+ if version != "v1" or not sig:
31
+ continue
32
+ try:
33
+ got = base64.b64decode(sig)
34
+ except ValueError:
35
+ continue
36
+ if hmac.compare_digest(got, expected):
37
+ return True
38
+ return False
@@ -0,0 +1,79 @@
1
+ import base64
2
+ import hashlib
3
+ import hmac
4
+ import json
5
+ import os
6
+ import sys
7
+ import time
8
+ import unittest
9
+
10
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))
11
+
12
+ from nagent import Nagent, NagentError, verify_webhook # noqa: E402
13
+
14
+
15
+ class Fake:
16
+ def __init__(self, replies):
17
+ self.replies = list(replies)
18
+ self.calls = []
19
+
20
+ def __call__(self, method, url, headers, body, timeout):
21
+ self.calls.append({"method": method, "url": url, "headers": headers, "body": json.loads(body) if body else None})
22
+ status, payload, headers_out = self.replies.pop(0)
23
+ return status, headers_out, (payload if isinstance(payload, bytes) else json.dumps(payload).encode())
24
+
25
+
26
+ def client(*replies):
27
+ fake = Fake([(r[0], r[1], r[2] if len(r) > 2 else {}) for r in replies])
28
+ return Nagent(api_key="nag_test_x", base_url="https://nagent.ai/", transport=fake), fake
29
+
30
+
31
+ class ClientTest(unittest.TestCase):
32
+ def test_runs_an_agent_with_session_and_metadata(self):
33
+ n, fake = client((200, {"id": "r1", "status": "completed", "output": "Done."}))
34
+ run = n.runs.create("nora", input="go", session_id="s1", metadata={"ticket": "T-1"}, idempotency_key="k1")
35
+ self.assertEqual(run["output"], "Done.")
36
+ call = fake.calls[0]
37
+ self.assertEqual((call["method"], call["url"]), ("POST", "https://nagent.ai/api/v1/agents/nora/runs"))
38
+ self.assertEqual(call["headers"]["Authorization"], "Bearer nag_test_x")
39
+ self.assertEqual(call["headers"]["Idempotency-Key"], "k1")
40
+ self.assertNotIn("Prefer", call["headers"])
41
+ self.assertEqual(call["body"], {"input": "go", "sessionId": "s1", "metadata": {"ticket": "T-1"}})
42
+
43
+ def test_async_run_and_wait(self):
44
+ n, fake = client((202, {"id": "r1", "status": "running"}), (200, {"id": "r1", "status": "running"}), (200, {"id": "r1", "status": "completed"}))
45
+ accepted = n.runs.create("nora", input="go", wait=False)
46
+ self.assertEqual(fake.calls[0]["headers"]["Prefer"], "respond-async")
47
+ run = n.runs.wait(accepted["id"], sleep=lambda s: None)
48
+ self.assertEqual(run["status"], "completed")
49
+ self.assertEqual(len(fake.calls), 3)
50
+
51
+ def test_iterates_every_page_of_approvals(self):
52
+ n, fake = client((200, {"data": [{"id": "a"}], "hasMore": True, "nextCursor": "c1"}), (200, {"data": [{"id": "b"}], "hasMore": False, "nextCursor": None}))
53
+ self.assertEqual([a["id"] for a in n.approvals.iter()], ["a", "b"])
54
+ self.assertIn("cursor=c1", fake.calls[1]["url"])
55
+
56
+ def test_raises_the_problem_document(self):
57
+ n, _ = client((404, {"type": "https://nagent.ai/developers/errors#agent-not-found", "title": "Agent not found", "status": 404}, {"x-request-id": "req_9"}))
58
+ with self.assertRaises(NagentError) as e:
59
+ n.agents.get("missing")
60
+ self.assertEqual((e.exception.status, e.exception.code, e.exception.request_id), (404, "agent-not-found", "req_9"))
61
+
62
+
63
+ class WebhookTest(unittest.TestCase):
64
+ def sign(self, secret, msg_id, ts, body):
65
+ key = base64.b64decode(secret[6:])
66
+ return "v1," + base64.b64encode(hmac.new(key, f"{msg_id}.{ts}.{body}".encode(), hashlib.sha256).digest()).decode()
67
+
68
+ def test_verifies_and_refuses(self):
69
+ secret = "whsec_" + base64.b64encode(b"k" * 32).decode()
70
+ ts = int(time.time())
71
+ body = '{"type":"run.completed"}'
72
+ headers = {"webhook-id": "msg_1", "webhook-timestamp": str(ts), "webhook-signature": self.sign(secret, "msg_1", ts, body)}
73
+ self.assertTrue(verify_webhook(secret, headers, body))
74
+ self.assertFalse(verify_webhook(secret, headers, body + " "))
75
+ self.assertFalse(verify_webhook(secret, headers, body, now=ts + 600))
76
+
77
+
78
+ if __name__ == "__main__":
79
+ unittest.main()