unitares-sdk 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.
Files changed (39) hide show
  1. unitares_sdk-0.1.0/LICENSE +190 -0
  2. unitares_sdk-0.1.0/PKG-INFO +196 -0
  3. unitares_sdk-0.1.0/README.md +168 -0
  4. unitares_sdk-0.1.0/pyproject.toml +46 -0
  5. unitares_sdk-0.1.0/setup.cfg +4 -0
  6. unitares_sdk-0.1.0/src/unitares_sdk/__init__.py +78 -0
  7. unitares_sdk-0.1.0/src/unitares_sdk/_substrate.py +223 -0
  8. unitares_sdk-0.1.0/src/unitares_sdk/agent.py +651 -0
  9. unitares_sdk-0.1.0/src/unitares_sdk/client.py +811 -0
  10. unitares_sdk-0.1.0/src/unitares_sdk/errors.py +168 -0
  11. unitares_sdk-0.1.0/src/unitares_sdk/lease_plane/__init__.py +80 -0
  12. unitares_sdk-0.1.0/src/unitares_sdk/lease_plane/advisory.py +479 -0
  13. unitares_sdk-0.1.0/src/unitares_sdk/lease_plane/canonical.py +121 -0
  14. unitares_sdk-0.1.0/src/unitares_sdk/lease_plane/canonicalize.py +220 -0
  15. unitares_sdk-0.1.0/src/unitares_sdk/lease_plane/client.py +806 -0
  16. unitares_sdk-0.1.0/src/unitares_sdk/lease_plane/models.py +369 -0
  17. unitares_sdk-0.1.0/src/unitares_sdk/lease_plane/reclaim.py +147 -0
  18. unitares_sdk-0.1.0/src/unitares_sdk/models.py +185 -0
  19. unitares_sdk-0.1.0/src/unitares_sdk/py.typed +0 -0
  20. unitares_sdk-0.1.0/src/unitares_sdk/sync_client.py +542 -0
  21. unitares_sdk-0.1.0/src/unitares_sdk/utils.py +321 -0
  22. unitares_sdk-0.1.0/src/unitares_sdk.egg-info/PKG-INFO +196 -0
  23. unitares_sdk-0.1.0/src/unitares_sdk.egg-info/SOURCES.txt +37 -0
  24. unitares_sdk-0.1.0/src/unitares_sdk.egg-info/dependency_links.txt +1 -0
  25. unitares_sdk-0.1.0/src/unitares_sdk.egg-info/requires.txt +7 -0
  26. unitares_sdk-0.1.0/src/unitares_sdk.egg-info/top_level.txt +1 -0
  27. unitares_sdk-0.1.0/tests/test_agent.py +1253 -0
  28. unitares_sdk-0.1.0/tests/test_canonical_vectors.py +57 -0
  29. unitares_sdk-0.1.0/tests/test_client.py +862 -0
  30. unitares_sdk-0.1.0/tests/test_client_connect_resilience.py +180 -0
  31. unitares_sdk-0.1.0/tests/test_client_uds.py +141 -0
  32. unitares_sdk-0.1.0/tests/test_effect_grant_mint.py +145 -0
  33. unitares_sdk-0.1.0/tests/test_governed_file_write.py +107 -0
  34. unitares_sdk-0.1.0/tests/test_models.py +349 -0
  35. unitares_sdk-0.1.0/tests/test_refuse_fresh_onboard.py +99 -0
  36. unitares_sdk-0.1.0/tests/test_retry_503.py +214 -0
  37. unitares_sdk-0.1.0/tests/test_substrate_emission.py +441 -0
  38. unitares_sdk-0.1.0/tests/test_sync_client.py +329 -0
  39. unitares_sdk-0.1.0/tests/test_utils.py +309 -0
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to the Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the Work
90
+ or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2025-2026 Kenny Wang (CIRWEL Systems)
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
@@ -0,0 +1,196 @@
1
+ Metadata-Version: 2.4
2
+ Name: unitares-sdk
3
+ Version: 0.1.0
4
+ Summary: Agent SDK for UNITARES governance — check-in loop, EISV state, identity anchors, and lease-plane client for long-lived AI agents
5
+ Author: cirwel
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/cirwel/unitares
8
+ Project-URL: Documentation, https://github.com/cirwel/unitares/blob/master/agents/sdk/README.md
9
+ Project-URL: Source, https://github.com/cirwel/unitares
10
+ Project-URL: Issues, https://github.com/cirwel/unitares/issues
11
+ Keywords: ai-agents,governance,mcp,multi-agent-systems,observability
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
17
+ Classifier: Topic :: System :: Monitoring
18
+ Requires-Python: >=3.12
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: httpx<1.0.0,>=0.27.0
22
+ Requires-Dist: mcp<2.0.0,>=1.26.0
23
+ Requires-Dist: pydantic<3.0.0,>=2.0.0
24
+ Provides-Extra: dev
25
+ Requires-Dist: pytest<10.0.0,>=7.4.0; extra == "dev"
26
+ Requires-Dist: pytest-asyncio<2.0.0,>=0.21.0; extra == "dev"
27
+ Dynamic: license-file
28
+
29
+ # unitares-sdk
30
+
31
+ Build your own Unitares resident agent. A resident is a long-running (or
32
+ scheduled) process that checks in to governance, carries an EISV state
33
+ vector, and participates in the shared knowledge graph. Vigil, Sentinel,
34
+ and Chronicler are reference implementations.
35
+
36
+ ## Install
37
+
38
+ ```bash
39
+ pip install unitares-sdk
40
+ ```
41
+
42
+ To install the SDK as it shipped with a specific server release, use the Git
43
+ URL instead:
44
+
45
+ ```bash
46
+ pip install "unitares-sdk @ git+https://github.com/cirwel/unitares@v2.17.0#subdirectory=agents/sdk"
47
+ ```
48
+
49
+ Replace `@v2.17.0` with another server release tag only after checking the
50
+ [compatibility map](https://github.com/cirwel/unitares/blob/master/COMPATIBILITY.md).
51
+ Pin a commit SHA when reproducing a specific development build.
52
+
53
+ Or from a checkout of the [unitares repo](https://github.com/cirwel/unitares):
54
+
55
+ ```bash
56
+ pip install -e agents/sdk
57
+ ```
58
+
59
+ > **Releases are tag-driven.** Pushing an `sdk-v*` tag whose version matches
60
+ > `version` in `pyproject.toml` runs `.github/workflows/publish-sdk.yml`, which
61
+ > builds and uploads via PyPI Trusted Publishing — OIDC, no API token. The SDK
62
+ > carries its own version series, independent of the server's. See the
63
+ > [release process](https://github.com/cirwel/unitares/blob/master/docs/operations/RELEASE_PROCESS.md).
64
+
65
+ Links in this file are absolute on purpose: `pyproject.toml` uses it as the
66
+ package `readme`, so PyPI renders it outside the repo and relative paths 404.
67
+
68
+ The package is standalone — it talks to a UNITARES server over MCP/REST and
69
+ never needs the server codebase importable. Fully typed (`py.typed`).
70
+
71
+ ## The 30-line resident
72
+
73
+ ```python
74
+ from pathlib import Path
75
+ from unitares_sdk.agent import CycleResult, GovernanceAgent
76
+ from unitares_sdk.client import GovernanceClient
77
+
78
+
79
+ class MyResident(GovernanceAgent):
80
+ def __init__(self):
81
+ super().__init__(
82
+ name="MyResident",
83
+ mcp_url="http://127.0.0.1:8767/mcp/",
84
+ persistent=True, # protects from auto-archive
85
+ refuse_fresh_onboard=True, # explicit bootstrap required
86
+ cycle_timeout_seconds=60.0, # hard cap on one cycle
87
+ log_file=Path("/tmp/my_resident.log"),
88
+ max_log_lines=10_000,
89
+ )
90
+
91
+ async def run_cycle(self, client: GovernanceClient) -> CycleResult | None:
92
+ # Do your work here. Return a CycleResult to trigger a check-in,
93
+ # or None to skip (useful for "nothing to do this tick" paths).
94
+ count = await self.do_scan(client)
95
+ if count == 0:
96
+ return None
97
+ return CycleResult(
98
+ summary=f"scanned {count} items",
99
+ complexity=0.2,
100
+ confidence=0.9,
101
+ )
102
+
103
+
104
+ if __name__ == "__main__":
105
+ import asyncio
106
+ asyncio.run(MyResident().run_forever(interval=60))
107
+ ```
108
+
109
+ First run: `UNITARES_FIRST_RUN=1 python my_resident.py` — this mints
110
+ the identity and stores its UUID anchor at
111
+ `~/.unitares/anchors/myresident.json`. Every subsequent run resumes
112
+ that anchor automatically. Never delete anchors: if you do, set
113
+ `UNITARES_FIRST_RUN=1` again to re-bootstrap (you will get a new UUID).
114
+
115
+ ## Extension points
116
+
117
+ The base class handles MCP connect, identity resolve, check-in,
118
+ heartbeat, log rotation, state persistence, and graceful shutdown.
119
+ Override these to extend behavior:
120
+
121
+ | Hook | When | Signature | Return |
122
+ |---|---|---|---|
123
+ | `run_cycle(client)` | Each iteration. The only required override. | `(client) -> CycleResult \| None` | `CycleResult` or `None` |
124
+ | `on_after_checkin(client, checkin_result, cycle_result)` | After each check-in, even on pause/reject. Use for EISV logging, coherence tracking, state writes that need the server response. | All three args typed via `unitares_sdk.models`. | `None` |
125
+ | `on_verdict_pause(client, checkin_result, cycle_result)` | When the server returns a `pause` verdict. Use for self-recovery. | Same arg signature as `on_after_checkin` for consistency. | `True` to retry the check-in once; `False` to let `VerdictError` propagate. |
126
+
127
+ Hook exceptions are logged and swallowed — a broken hook cannot take
128
+ down a cycle. `asyncio.CancelledError` always propagates.
129
+
130
+ Do **not** override `_ensure_identity`, `_handle_cycle_result`, or
131
+ `_send_heartbeat` — those are load-bearing and change across versions.
132
+
133
+ ## Constructor reference
134
+
135
+ | Parameter | Type | Default | Purpose |
136
+ |---|---|---|---|
137
+ | `name` | `str` | required | Agent display name; drives anchor path (`~/.unitares/anchors/<name_lower>.json`). |
138
+ | `mcp_url` | `str` | `http://127.0.0.1:8767/mcp/` | Governance MCP endpoint. |
139
+ | `persistent` | `bool` | `False` | Stamp the `persistent` + `autonomous` tags on fresh onboard. Set `True` for long-running residents. |
140
+ | `refuse_fresh_onboard` | `bool` | `False` | Require `UNITARES_FIRST_RUN=1` to mint a new identity. Set `True` to prevent silent ghost-forks. |
141
+ | `cycle_timeout_seconds` | `float \| None` | `None` | Hard cap on a single `run_once` / `run_forever` iteration. MCP's anyio task group can hang on `session.initialize` if the server flakes — use 60–120s. |
142
+ | `log_file` | `Path \| None` | `None` | Log file to auto-trim after each cycle (in both `run_once` and `run_forever`, in a `finally` block so it fires on error and timeout too). Leave unset if launchd / logrotate owns rotation. |
143
+ | `max_log_lines` | `int` | `10_000` | Trim threshold for `log_file`. |
144
+ | `state_dir` | `Path \| None` | `<repo>/data/<name_lower>` | Default directory for state persistence. Used when `state_file` is not set. |
145
+ | `state_file` | `Path \| None` | `None` | Explicit cross-cycle state path. Takes precedence over `state_dir / "state.json"` when set. |
146
+ | `parent_agent_id` | `str \| None` | `None` | Forked-from UUID. Forwards to server on fresh onboard. |
147
+ | `spawn_reason` | `str \| None` | `None` | Registered values: `subagent`, `dialectic_reviewer`, `dispatch`, `compaction`, `explicit`, `new_session`. Unknown values are accepted but receive no live-parent exemption. |
148
+
149
+ ## Lifecycle shapes
150
+
151
+ - **Daemon:** `asyncio.run(agent.run_forever(interval=60))` — loops
152
+ forever with heartbeats when idle. Reference:
153
+ `agents/sentinel/agent.py`.
154
+ - **Scheduled:** `asyncio.run(agent.run_once())` under launchd /
155
+ systemd cron. References: `agents/chronicler/agent.py`,
156
+ `agents/vigil/agent.py`.
157
+
158
+ Both shapes respect `cycle_timeout_seconds` and auto-trim `log_file`.
159
+
160
+ ## State persistence
161
+
162
+ - `self.save_state(d: dict)` and `self.load_state() -> dict` let your
163
+ `run_cycle` carry data across iterations. Writes are atomic
164
+ (`os.replace`).
165
+ - Non-JSON-serializable values (e.g. `datetime`, `Path`) are coerced
166
+ to their `str()` representation on save rather than raising
167
+ `TypeError`. You get a lossy round-trip, not a silent state-write
168
+ failure.
169
+
170
+ ## Identity rules
171
+
172
+ 1. The agent's first MCP call (`onboard` or `identity`) is the sole
173
+ source of identity. Do not set identity out-of-band.
174
+ 2. UUID is the ground truth. `client_session_id` and
175
+ `continuity_token` are cache keys for ephemeral clients; residents
176
+ don't need them.
177
+ 3. Anchors live at `~/.unitares/anchors/<name_lower>.json`. One
178
+ anchor per host per role. The file contains `agent_uuid` and is
179
+ written atomically.
180
+ 4. Never silent-swap an identity. If the anchor is missing and
181
+ `refuse_fresh_onboard=True`, `_ensure_identity` raises
182
+ `IdentityBootstrapRefused` — the operator must explicitly set
183
+ `UNITARES_FIRST_RUN=1` once to mint a new one.
184
+
185
+ ## Not in the SDK (on purpose)
186
+
187
+ - `agents/common/findings.py` and `agents/common/config.py` are
188
+ internal to the reference residents in this repo. If you need
189
+ findings-posting in your own resident, vendor the helper or POST to
190
+ `/api/findings` yourself — the REST contract is the public surface.
191
+ - The violation taxonomy is server-owned vocabulary
192
+ (`src/violation_taxonomy.yaml`); consume it via the `/v1/taxonomy`
193
+ endpoint rather than importing server code.
194
+ - Watcher (`agents/watcher/agent.py`) uses a different execution
195
+ model (sync, hook-driven, one-shot per tool-use event) and does not
196
+ subclass `GovernanceAgent`.
@@ -0,0 +1,168 @@
1
+ # unitares-sdk
2
+
3
+ Build your own Unitares resident agent. A resident is a long-running (or
4
+ scheduled) process that checks in to governance, carries an EISV state
5
+ vector, and participates in the shared knowledge graph. Vigil, Sentinel,
6
+ and Chronicler are reference implementations.
7
+
8
+ ## Install
9
+
10
+ ```bash
11
+ pip install unitares-sdk
12
+ ```
13
+
14
+ To install the SDK as it shipped with a specific server release, use the Git
15
+ URL instead:
16
+
17
+ ```bash
18
+ pip install "unitares-sdk @ git+https://github.com/cirwel/unitares@v2.17.0#subdirectory=agents/sdk"
19
+ ```
20
+
21
+ Replace `@v2.17.0` with another server release tag only after checking the
22
+ [compatibility map](https://github.com/cirwel/unitares/blob/master/COMPATIBILITY.md).
23
+ Pin a commit SHA when reproducing a specific development build.
24
+
25
+ Or from a checkout of the [unitares repo](https://github.com/cirwel/unitares):
26
+
27
+ ```bash
28
+ pip install -e agents/sdk
29
+ ```
30
+
31
+ > **Releases are tag-driven.** Pushing an `sdk-v*` tag whose version matches
32
+ > `version` in `pyproject.toml` runs `.github/workflows/publish-sdk.yml`, which
33
+ > builds and uploads via PyPI Trusted Publishing — OIDC, no API token. The SDK
34
+ > carries its own version series, independent of the server's. See the
35
+ > [release process](https://github.com/cirwel/unitares/blob/master/docs/operations/RELEASE_PROCESS.md).
36
+
37
+ Links in this file are absolute on purpose: `pyproject.toml` uses it as the
38
+ package `readme`, so PyPI renders it outside the repo and relative paths 404.
39
+
40
+ The package is standalone — it talks to a UNITARES server over MCP/REST and
41
+ never needs the server codebase importable. Fully typed (`py.typed`).
42
+
43
+ ## The 30-line resident
44
+
45
+ ```python
46
+ from pathlib import Path
47
+ from unitares_sdk.agent import CycleResult, GovernanceAgent
48
+ from unitares_sdk.client import GovernanceClient
49
+
50
+
51
+ class MyResident(GovernanceAgent):
52
+ def __init__(self):
53
+ super().__init__(
54
+ name="MyResident",
55
+ mcp_url="http://127.0.0.1:8767/mcp/",
56
+ persistent=True, # protects from auto-archive
57
+ refuse_fresh_onboard=True, # explicit bootstrap required
58
+ cycle_timeout_seconds=60.0, # hard cap on one cycle
59
+ log_file=Path("/tmp/my_resident.log"),
60
+ max_log_lines=10_000,
61
+ )
62
+
63
+ async def run_cycle(self, client: GovernanceClient) -> CycleResult | None:
64
+ # Do your work here. Return a CycleResult to trigger a check-in,
65
+ # or None to skip (useful for "nothing to do this tick" paths).
66
+ count = await self.do_scan(client)
67
+ if count == 0:
68
+ return None
69
+ return CycleResult(
70
+ summary=f"scanned {count} items",
71
+ complexity=0.2,
72
+ confidence=0.9,
73
+ )
74
+
75
+
76
+ if __name__ == "__main__":
77
+ import asyncio
78
+ asyncio.run(MyResident().run_forever(interval=60))
79
+ ```
80
+
81
+ First run: `UNITARES_FIRST_RUN=1 python my_resident.py` — this mints
82
+ the identity and stores its UUID anchor at
83
+ `~/.unitares/anchors/myresident.json`. Every subsequent run resumes
84
+ that anchor automatically. Never delete anchors: if you do, set
85
+ `UNITARES_FIRST_RUN=1` again to re-bootstrap (you will get a new UUID).
86
+
87
+ ## Extension points
88
+
89
+ The base class handles MCP connect, identity resolve, check-in,
90
+ heartbeat, log rotation, state persistence, and graceful shutdown.
91
+ Override these to extend behavior:
92
+
93
+ | Hook | When | Signature | Return |
94
+ |---|---|---|---|
95
+ | `run_cycle(client)` | Each iteration. The only required override. | `(client) -> CycleResult \| None` | `CycleResult` or `None` |
96
+ | `on_after_checkin(client, checkin_result, cycle_result)` | After each check-in, even on pause/reject. Use for EISV logging, coherence tracking, state writes that need the server response. | All three args typed via `unitares_sdk.models`. | `None` |
97
+ | `on_verdict_pause(client, checkin_result, cycle_result)` | When the server returns a `pause` verdict. Use for self-recovery. | Same arg signature as `on_after_checkin` for consistency. | `True` to retry the check-in once; `False` to let `VerdictError` propagate. |
98
+
99
+ Hook exceptions are logged and swallowed — a broken hook cannot take
100
+ down a cycle. `asyncio.CancelledError` always propagates.
101
+
102
+ Do **not** override `_ensure_identity`, `_handle_cycle_result`, or
103
+ `_send_heartbeat` — those are load-bearing and change across versions.
104
+
105
+ ## Constructor reference
106
+
107
+ | Parameter | Type | Default | Purpose |
108
+ |---|---|---|---|
109
+ | `name` | `str` | required | Agent display name; drives anchor path (`~/.unitares/anchors/<name_lower>.json`). |
110
+ | `mcp_url` | `str` | `http://127.0.0.1:8767/mcp/` | Governance MCP endpoint. |
111
+ | `persistent` | `bool` | `False` | Stamp the `persistent` + `autonomous` tags on fresh onboard. Set `True` for long-running residents. |
112
+ | `refuse_fresh_onboard` | `bool` | `False` | Require `UNITARES_FIRST_RUN=1` to mint a new identity. Set `True` to prevent silent ghost-forks. |
113
+ | `cycle_timeout_seconds` | `float \| None` | `None` | Hard cap on a single `run_once` / `run_forever` iteration. MCP's anyio task group can hang on `session.initialize` if the server flakes — use 60–120s. |
114
+ | `log_file` | `Path \| None` | `None` | Log file to auto-trim after each cycle (in both `run_once` and `run_forever`, in a `finally` block so it fires on error and timeout too). Leave unset if launchd / logrotate owns rotation. |
115
+ | `max_log_lines` | `int` | `10_000` | Trim threshold for `log_file`. |
116
+ | `state_dir` | `Path \| None` | `<repo>/data/<name_lower>` | Default directory for state persistence. Used when `state_file` is not set. |
117
+ | `state_file` | `Path \| None` | `None` | Explicit cross-cycle state path. Takes precedence over `state_dir / "state.json"` when set. |
118
+ | `parent_agent_id` | `str \| None` | `None` | Forked-from UUID. Forwards to server on fresh onboard. |
119
+ | `spawn_reason` | `str \| None` | `None` | Registered values: `subagent`, `dialectic_reviewer`, `dispatch`, `compaction`, `explicit`, `new_session`. Unknown values are accepted but receive no live-parent exemption. |
120
+
121
+ ## Lifecycle shapes
122
+
123
+ - **Daemon:** `asyncio.run(agent.run_forever(interval=60))` — loops
124
+ forever with heartbeats when idle. Reference:
125
+ `agents/sentinel/agent.py`.
126
+ - **Scheduled:** `asyncio.run(agent.run_once())` under launchd /
127
+ systemd cron. References: `agents/chronicler/agent.py`,
128
+ `agents/vigil/agent.py`.
129
+
130
+ Both shapes respect `cycle_timeout_seconds` and auto-trim `log_file`.
131
+
132
+ ## State persistence
133
+
134
+ - `self.save_state(d: dict)` and `self.load_state() -> dict` let your
135
+ `run_cycle` carry data across iterations. Writes are atomic
136
+ (`os.replace`).
137
+ - Non-JSON-serializable values (e.g. `datetime`, `Path`) are coerced
138
+ to their `str()` representation on save rather than raising
139
+ `TypeError`. You get a lossy round-trip, not a silent state-write
140
+ failure.
141
+
142
+ ## Identity rules
143
+
144
+ 1. The agent's first MCP call (`onboard` or `identity`) is the sole
145
+ source of identity. Do not set identity out-of-band.
146
+ 2. UUID is the ground truth. `client_session_id` and
147
+ `continuity_token` are cache keys for ephemeral clients; residents
148
+ don't need them.
149
+ 3. Anchors live at `~/.unitares/anchors/<name_lower>.json`. One
150
+ anchor per host per role. The file contains `agent_uuid` and is
151
+ written atomically.
152
+ 4. Never silent-swap an identity. If the anchor is missing and
153
+ `refuse_fresh_onboard=True`, `_ensure_identity` raises
154
+ `IdentityBootstrapRefused` — the operator must explicitly set
155
+ `UNITARES_FIRST_RUN=1` once to mint a new one.
156
+
157
+ ## Not in the SDK (on purpose)
158
+
159
+ - `agents/common/findings.py` and `agents/common/config.py` are
160
+ internal to the reference residents in this repo. If you need
161
+ findings-posting in your own resident, vendor the helper or POST to
162
+ `/api/findings` yourself — the REST contract is the public surface.
163
+ - The violation taxonomy is server-owned vocabulary
164
+ (`src/violation_taxonomy.yaml`); consume it via the `/v1/taxonomy`
165
+ endpoint rather than importing server code.
166
+ - Watcher (`agents/watcher/agent.py`) uses a different execution
167
+ model (sync, hook-driven, one-shot per tool-use event) and does not
168
+ subclass `GovernanceAgent`.
@@ -0,0 +1,46 @@
1
+ [build-system]
2
+ # >=77 for PEP 639 (SPDX `license` string + `license-files`).
3
+ requires = ["setuptools>=77.0"]
4
+ build-backend = "setuptools.build_meta"
5
+
6
+ [project]
7
+ name = "unitares-sdk"
8
+ version = "0.1.0"
9
+ description = "Agent SDK for UNITARES governance — check-in loop, EISV state, identity anchors, and lease-plane client for long-lived AI agents"
10
+ readme = "README.md"
11
+ license = "Apache-2.0"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "cirwel" }]
14
+ keywords = ["ai-agents", "governance", "mcp", "multi-agent-systems", "observability"]
15
+ classifiers = [
16
+ "Development Status :: 4 - Beta",
17
+ "Intended Audience :: Developers",
18
+ "Programming Language :: Python :: 3.12",
19
+ "Programming Language :: Python :: 3.13",
20
+ "Topic :: Software Development :: Libraries :: Python Modules",
21
+ "Topic :: System :: Monitoring",
22
+ ]
23
+ requires-python = ">=3.12"
24
+ dependencies = [
25
+ "httpx>=0.27.0,<1.0.0",
26
+ "mcp>=1.26.0,<2.0.0",
27
+ "pydantic>=2.0.0,<3.0.0",
28
+ ]
29
+
30
+ [project.optional-dependencies]
31
+ dev = [
32
+ "pytest>=7.4.0,<10.0.0",
33
+ "pytest-asyncio>=0.21.0,<2.0.0",
34
+ ]
35
+
36
+ [project.urls]
37
+ Homepage = "https://github.com/cirwel/unitares"
38
+ Documentation = "https://github.com/cirwel/unitares/blob/master/agents/sdk/README.md"
39
+ Source = "https://github.com/cirwel/unitares"
40
+ Issues = "https://github.com/cirwel/unitares/issues"
41
+
42
+ [tool.setuptools.packages.find]
43
+ where = ["src"]
44
+
45
+ [tool.setuptools.package-data]
46
+ unitares_sdk = ["py.typed"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+