mercury-cli-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.
- mercury_cli_sdk-0.1.0/LICENSE +202 -0
- mercury_cli_sdk-0.1.0/PKG-INFO +161 -0
- mercury_cli_sdk-0.1.0/README.md +138 -0
- mercury_cli_sdk-0.1.0/build_backend.py +92 -0
- mercury_cli_sdk-0.1.0/pyproject.toml +32 -0
- mercury_cli_sdk-0.1.0/src/mercury_cli_sdk/__init__.py +14 -0
- mercury_cli_sdk-0.1.0/src/mercury_cli_sdk/client.py +538 -0
- mercury_cli_sdk-0.1.0/src/mercury_cli_sdk/errors.py +77 -0
- mercury_cli_sdk-0.1.0/src/mercury_cli_sdk/executable.py +90 -0
- mercury_cli_sdk-0.1.0/src/mercury_cli_sdk/framing.py +26 -0
- mercury_cli_sdk-0.1.0/src/mercury_cli_sdk/generated.py +1656 -0
- mercury_cli_sdk-0.1.0/src/mercury_cli_sdk/helpers.py +234 -0
- mercury_cli_sdk-0.1.0/src/mercury_cli_sdk/parse.py +219 -0
- mercury_cli_sdk-0.1.0/src/mercury_cli_sdk/py.typed +0 -0
- mercury_cli_sdk-0.1.0/src/mercury_cli_sdk/runner.py +489 -0
- mercury_cli_sdk-0.1.0/src/mercury_cli_sdk/structured.py +127 -0
- mercury_cli_sdk-0.1.0/src/mercury_cli_sdk/support.py +53 -0
- mercury_cli_sdk-0.1.0/src/mercury_cli_sdk/sync.py +168 -0
- mercury_cli_sdk-0.1.0/src/mercury_cli_sdk/testing.py +194 -0
- mercury_cli_sdk-0.1.0/src/mercury_cli_sdk/version.py +1 -0
|
@@ -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,161 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: mercury-cli-sdk
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Mercury CLI clients for Python: typed run streams, hosted sessions and zero-cost fixtures.
|
|
5
|
+
Requires-Python: >=3.11
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Keywords: mercury-cli,mercury
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Framework :: AsyncIO
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
19
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
20
|
+
Classifier: Typing :: Typed
|
|
21
|
+
Project-URL: Homepage, https://mercury-cli.ai
|
|
22
|
+
Project-URL: Repository, https://github.com/Whq02/MercuryCLI
|
|
23
|
+
|
|
24
|
+
# Mercury CLI SDK
|
|
25
|
+
|
|
26
|
+
`mercury-cli-sdk` 0.1.0 is a zero-runtime-dependency Python client for Mercury CLI, requiring Python 3.11 or later. Install Mercury separately and sign in through the CLI; the SDK uses its configuration and credentials. The package is Apache-2.0 and versioned separately from the CLI.
|
|
27
|
+
|
|
28
|
+
```sh
|
|
29
|
+
python -m pip install mercury-cli-sdk
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
On Windows run that as `py -3 -m pip install mercury-cli-sdk` (or with the full path of `python.exe`): the `python3` name there is often the Store stub, which answers with exit code 9009. If `python -m venv` fails because `ensurepip` is missing, install `python3-venv` (Debian and Ubuntu: `apt install python3-venv`), or create the environment with `--without-pip` and install into it from an interpreter that has pip: `python -m pip --python .venv/bin/python install mercury-cli-sdk`.
|
|
33
|
+
|
|
34
|
+
## Quickstart
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
from mercury_cli_sdk import run_sync
|
|
38
|
+
|
|
39
|
+
print(run_sync('Explain the README').outcome.get('answer'))
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
For asynchronous programs and streaming, use `run`.
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
import asyncio
|
|
46
|
+
from mercury_cli_sdk import run
|
|
47
|
+
|
|
48
|
+
async def main():
|
|
49
|
+
task = await run('Explain the README', partial=True)
|
|
50
|
+
async for row in task:
|
|
51
|
+
if row['type'] == 'text_delta':
|
|
52
|
+
print(row['text'], end='', flush=True)
|
|
53
|
+
result = await task.outcome
|
|
54
|
+
print(result['status'], result.get('answer'))
|
|
55
|
+
asyncio.run(main())
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
`run()` returns an async row iterator with listeners. Its `session`, `outcome` and `exit` are awaitable; `rows` retains received rows. Whole blocks arrive as `text`; `partial=True` also streams `text_delta`. `outcome` settles after the process exits and owned tool servers close. `run_sync` returns `RunResult(outcome, rows, exit)`. `connect_sync` returns a typed `SyncSession` with the same control methods and blocking row iteration. Use it as a context manager; host callbacks run on its background loop and must not call the synchronous wrapper recursively.
|
|
59
|
+
|
|
60
|
+
## Host a session
|
|
61
|
+
|
|
62
|
+
```python
|
|
63
|
+
import asyncio
|
|
64
|
+
from mercury_cli_sdk import connect
|
|
65
|
+
|
|
66
|
+
async def main():
|
|
67
|
+
async with await connect(on_permission_request=lambda ask, context: {'outcome': 'deny', 'message': 'Read-only host'}) as session:
|
|
68
|
+
print((await session.prompt('Inspect the tests'))['status'])
|
|
69
|
+
print((await session.prompt('Explain the result')).get('answer'))
|
|
70
|
+
print((await session.facts())['usage']['total_cost_usd'])
|
|
71
|
+
asyncio.run(main())
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
`prompt` awaits its own correlated turn. Only one prompt wait may be active; `steer(content, id=..., schema=...)` queues priority `now` and `follow_up(content, id=..., schema=...)` queues `later`; both keyword options are optional. `send_prompt`, `send_shell` and `send_note` expose ids and all priorities; `withdraw(id)` removes queued input, and a `prompt` waiting on it raises `MercuryError('prompt: withdrawn')`. Cancelling the awaiting task cancels the wait, not the turn; `interrupt()` ends the turn. A prompt sent while a turn is still running (after a timed-out or cancelled wait, for instance) is the CLI's to place: with no tool round left it waits and runs as the next turn, which `prompt` resolves with; at a tool-round boundary the CLI folds it into the running turn and marks its reply `in_reply_to` that prompt, and `prompt` resolves with that turn's outcome instead (a per-turn `schema` on a folded prompt is not applied). When that turn ends without any reply and the CLI's `facts` list the prompt neither queued nor in a turn, `prompt` raises within five seconds `MercuryError('prompt: turn N ended STATUS and the runner holds this prompt neither queued nor in a turn; …')` rather than waiting forever; `interrupt()` the running turn, or await its outcome row, before prompting again when you need a turn of its own. Typed `request(method, params, timeout=seconds)` and `notify` cover protocol 1, including pause, quiesce, leave, MCP and schedules. `timeout=None` disables its timer. `connect(timeout=seconds)` bounds a boot that never answers; cancelling the awaiting task ends the child too.
|
|
75
|
+
|
|
76
|
+
`on_permission_request` and `on_elicitation` receive `RequestContext` with `id` and a `cancelled` event; absent handlers deny and decline respectively. `on_read_text_file` and `on_write_text_file` route native file tools to host buffers and infer their capabilities. The equivalent `handlers` entries work too. Supplying all five `terminal/*` handlers infers terminal support; partial terminal sets do not. Explicit `capabilities` override inference.
|
|
77
|
+
|
|
78
|
+
### Checkpoints, warm workers and control
|
|
79
|
+
|
|
80
|
+
`connect` asks the CLI to capture file checkpoints (`file_checkpoints: true` on `initialize`); `checkpoints=False` opts out. The CLI answers with what it does: `session.file_checkpoints` (the `initialize` answer) and `(await session.facts())['file_checkpoints']` carry `capture` and `source`, where `initialize` means the request is honoured, `setting` that the CLI's file-checkpoint setting turned it off, `headless` that nothing asked, and `seat` or `interactive` name the CLI's own sessions; `facts` adds `restorable`, the user-message ids a rewind can return to. File checkpoints over `initialize` need Mercury 1.0.0-beta.41 or newer: an older runner answers no `file_checkpoints`, so `session.file_checkpoints` is `None`, `session.supports['file_checkpoints']` is False and `facts()['file_checkpoints']` reads `capture: False` with no `source`. `run` has no `initialize` and captures nothing. After any accepted prompt input, including `send_prompt`, `steer` and `follow_up`, `last_prompt_id` is its user-message id. Pass it to `rewind(user_message_id, 'both', dry_run=True)`, then omit `dry_run` to restore. Modes are `code`, `conversation` and `both`; the typed receipt reports changed files and removed conversation rows.
|
|
81
|
+
|
|
82
|
+
`prewarm(**options)` or `connect(warm=True)` returns an unclaimed runner. On `MercurySession` and `SyncSession`, `session.session_id` reflects `initialized['session_id']`: both are None until `claim(session_id=..., model=..., effort=..., mode=..., resume=...)` succeeds and updates them from the CLI's reply. Only `session_id` is required. Prompt input before a claim fails immediately with `MercuryError('session is unclaimed; call claim() before prompting')`. Warm workers reject boot-time identity flags; ordinary, resumed and continued sessions already have an identity. The unclaimed boot runs in the CLI's session-runner role, which withholds subagents and workflows unless the CLI setting `Crewmates while backgrounded` is on, offers the Contract tool and refuses `Sleep` beyond 300 seconds. `facts`, `rewind`, `stop_agent` and `resume_agent` return generated result types. Model, effort, permission mode and kit changes use `set_model`, `set_effort`, `set_mode` and `set_kit`.
|
|
83
|
+
|
|
84
|
+
## Inline tools and agents
|
|
85
|
+
|
|
86
|
+
```python
|
|
87
|
+
import asyncio
|
|
88
|
+
from mercury_cli_sdk import define_tool, run
|
|
89
|
+
|
|
90
|
+
async def main():
|
|
91
|
+
greeting = define_tool('greeting', 'Return a greeting', {}, lambda _: 'Hello')
|
|
92
|
+
task = await run('Use greeting to say hello', tools=[greeting])
|
|
93
|
+
result = await task.outcome
|
|
94
|
+
print(result['status'], result.get('answer'))
|
|
95
|
+
asyncio.run(main())
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
Both doors own the authenticated loopback MCP server for `tools`, close it on exit or failed startup, and merge it with `mcp`. Tool names `mcp__sdk-tools__<name>` are added to `allowed_tools` and existing inline custom-agent `tools` allowlists without mutating your options. `auto_allow_tools=False` keeps serving but leaves permission grants to you; explicit denials still apply. An unanswered headless ask produces `blocked`. `define_agent` validates definitions passed in `agent_defs`. `serve_tools(tools, name)` remains available for manually owned servers. Tool callbacks may accept a second `ToolContext` with a `cancelled` event for cooperative cancellation; keep the event loop running. `define_tool` accepts JSON Schema, a mapping such as `{'query': str, 'limit': int}`, or a TypedDict with NotRequired, Required and Annotated descriptions.
|
|
99
|
+
|
|
100
|
+
## Inputs, output schemas and launch options
|
|
101
|
+
|
|
102
|
+
A prompt accepts text, `list[InputBlock]` or an `AsyncIterable[str | InputRow]`. Block and iterable prompts automatically use input rows and close stdin when complete. `text_block(text)` builds text; `image_block(data, media_type)` accepts base64 text, bytes or `pathlib.Path`. For manual streaming use `input='rows'`, `send(row)` and `close_input()`. On the rows door the CLI writes nothing, not even `session`, until the first input row arrives, so `session`, `cancel` and `interrupt()` take effect once the first prompt is sent; `close_input()` on a run that sent no row ends it without an outcome. `outcome` is the final run outcome; listen to individual outcome rows for multi-turn input.
|
|
103
|
+
|
|
104
|
+
`structured_schema(json_schema, decode)` infers `TypedOutcome[T]` from the decoder when passed as `schema=` to `run`, `connect` or `session.prompt`; a `schema` also accepts a JSON Schema dictionary, JSON text or a schema file path. On `run` it is the `--schema` flag and shapes every turn; on `connect` it travels on `initialize` and as the `--schema` flag, so it shapes every turn of the session on every Mercury version; `prompt(content, schema=...)` sends that turn's schema on its prompt row and overrides the session's for that turn, so one session can ask for a different shape each turn, and a turn without one carries no `structured`. A per-turn schema needs Mercury 1.0.0-beta.41 or newer: an older runner ignores the field, so the package refuses it before sending with ``MercuryError('per-turn schema needs Mercury 1.0.0-beta.41 or newer; this runner is 1.0.0-beta.40 — run `mercury update`')``, and `session.supports['per_turn_schema']` beside `session.runner_version` says so in advance (`FEATURE_FLOORS` lists each floor; the version is read from the `initialize` answer, and an answer that already carries `file_checkpoints` counts as the newer wire). Where the runner honours the schema, Mercury holds the model to it and settles the turn with `structured`; a schema that is not a JSON Schema is refused before anything is sent — the package itself refuses an unknown `type`, non-object `properties` and the other keywords its reader indexes into (`schema_problem(schema)` returns the words), and the CLI refuses the rest with its own issue — so `run`, `prompt`, `steer`, `follow_up`, `send_prompt` or `connect` raises `MercurySchemaError` with the issue at path `schema` and `outcome` None, and no model turn is spent. A completed `structured` is decoded by the descriptor and read once more by the package (types, scalar constants/enums, object fields, array items, numeric ranges and string lengths), so a replayed fixture is held to the same shape; a mismatch raises `MercurySchemaError` with exact `issues` and the raw `outcome`. `validate_outcome` also validates recorded outcomes.
|
|
105
|
+
|
|
106
|
+
`RunOptions` includes `replay_to`, `restore_files`, `worktree`, `reasoning_mode`, `brief_file`, `brief_add_file` and `debug`. The keyword options of `run`, `run_sync`, `connect`, `connect_sync` and `prewarm` are typed by `RunKwargs` and `ConnectKwargs`, so a type checker reports a wrong name or value. `argv_of` previews flags; `extra_args` passes additional flags. Both doors accept an explicit executable or prefix array such as `mercury=['ssh', 'host', 'mercury']`. Otherwise discovery uses `MERCURY_BIN`; then the managed install, read as Mercury's own command reads it: `current.txt` under `MERCURY_VERSIONS_DIR`, else `versions` in the Mercury home (`MERCURY_CONFIG_DIR`, `MERCURY_HOME` or `~/.mercury`; `%USERPROFILE%\.mercury` on Windows), whose version directory's `mercury.mjs` is run on the Node runtime vendored beside it; then `mercury` on PATH; then the stable command the installer writes (`~/.local/bin/mercury`; `%LOCALAPPDATA%\Mercury\bin\mercury.cmd` on Windows) and `~/.mercury/bin/mercury`; then, on macOS and Linux, the Homebrew command (`$HOMEBREW_PREFIX/bin/mercury`, `/opt/homebrew/bin/mercury`, `/usr/local/bin/mercury`, `/home/linuxbrew/.linuxbrew/bin/mercury`), for a host launched with a stripped PATH (an empty PATH skips this rung). No shell is involved: Mercury's managed command (`mercury`, `mercury.cmd`, `mercury.ps1`) resolves to that bundle, the Homebrew wrapper to the keg's `mercury.mjs` on its vendored runtime, an npm-style `.cmd` shim to its JavaScript entry point, and a `mercury.cmd` beside a `mercury.mjs` to that bundle; any other command shim requires an explicit `[node, script]` array, and a managed command whose install is missing is refused with the pointer file it looked for. A relative executable with a slash (`./bin/mercury`) is resolved against `cwd`; on Windows the `env` keys are read without regard to case, so a copy of the environment spelled `Path` and `Pathext` still resolves. A `.mjs`, `.cjs` or `.js` executable such as a built `mercury.mjs` runs on `MERCURY_NODE` when set (one that names no executable file is refused by name, as the launcher refuses it), else the runtime bundled beside it under `vendor/node`, else `node` from PATH.
|
|
107
|
+
|
|
108
|
+
## Test without a model
|
|
109
|
+
|
|
110
|
+
```python
|
|
111
|
+
import asyncio
|
|
112
|
+
from mercury_cli_sdk import run
|
|
113
|
+
from mercury_cli_sdk.testing import start_fixture_server, fixture_session_row, fixture_outcome_row
|
|
114
|
+
|
|
115
|
+
async def main():
|
|
116
|
+
rows = [fixture_session_row(), fixture_outcome_row(answer='ok')]
|
|
117
|
+
async with await start_fixture_server({'rows': rows}) as fixture:
|
|
118
|
+
task = await run('test', mercury=fixture.mercury)
|
|
119
|
+
assert (await task.outcome)['answer'] == 'ok'
|
|
120
|
+
asyncio.run(main())
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
`fixture_turn(overrides, prompt_id)` builds a correlated turn/outcome pair. You can also replay `task.rows`. Fixtures validate rows and RPC replies before listening; `'validate': False` in the fixture dictionary is for deliberately malformed-wire tests. `methods` holds ordered `{ result, before?, after? }` or `{ error }` replies; before/after and `answers` contain RPC messages. `received` records inputs and `inputCount` delays replay. Missing methods return method-not-found. Fixtures use neither a CLI nor model credentials and do not simulate the CLI's internal behaviour.
|
|
124
|
+
|
|
125
|
+
## Rows, errors and cleanup
|
|
126
|
+
|
|
127
|
+
`parse_row`, `row_of`, `input_row_of` and `validate` use generated schemas. `is_main_thread` separates subagent rows. Unknown types become `unknown_row` with `original_type`, raw payload and envelope; known extra fields are preserved. Schema-version changes and malformed known rows are rejected.
|
|
128
|
+
|
|
129
|
+
Non-completed turns resolve their outcome status (including failed authentication); refusals throw `MercuryRefusal`. Other specific `MercuryError` subclasses are `MercuryUsageError`, `MercuryExitError`, `MercurySpawnError`, `MercuryWireError` and `MercurySchemaError`. Exit/usage errors preserve the door and exit receipt; RPC errors preserve code and data. Check status rather than only exit code.
|
|
130
|
+
|
|
131
|
+
`stderr` holds what the child has written to standard error so far, read as text with `\r\n` normalised to `\n` (a Windows child's line endings included) so `exit.stderr`, the handle and the chunks agree; `on_stderr` (or an `on('stderr', …)` listener, also on `SyncSession`) receives each chunk as it arrives, on both doors. `cancel=asyncio.Event()` interrupts a run when the event is set. `interrupt`, `terminate` and `kill` are synchronous (not awaited) and signal the child with SIGINT, SIGTERM and SIGKILL; the exit is awaited through `exit`. On Windows, which delivers no signal, they end the process the way Node's child_process does, and `exit.signal` names the one the package sent. An interrupt the package sent always settles the turn as an `interrupted` outcome: the CLI writes that row itself where SIGINT reaches it, and where the child ends by the signal before writing one the package completes the turn with an `interrupted` outcome row folded from the rows it received. A signal the package did not send, and `terminate` or `kill`, raise `MercuryExitError`. Close handles in finally or with `async with`; `close` ends stdin, escalates after five seconds to termination, and after ten to killing. Normal host exit sends SIGTERM to live children; an unhandled killing signal cannot run cleanup, so long-running hosts should handle SIGTERM and close sessions.
|
|
132
|
+
|
|
133
|
+
<!-- vocabulary:start -->
|
|
134
|
+
| Row | Required fields |
|
|
135
|
+
| --- | --- |
|
|
136
|
+
| `session` | `type`, `seq`, `timestamp`, `session_id`, `schema`, `version`, `cwd`, `model`, `mode`, `tools`, `mcp_servers`, `commands`, `agents`, `skills`, `extensions` |
|
|
137
|
+
| `turn` | `type`, `seq`, `timestamp`, `session_id`, `state`, `turn_id` |
|
|
138
|
+
| `text` | `type`, `seq`, `timestamp`, `session_id`, `message_id`, `block`, `text` |
|
|
139
|
+
| `reasoning` | `type`, `seq`, `timestamp`, `session_id`, `message_id`, `block`, `text` |
|
|
140
|
+
| `tool_call` | `type`, `seq`, `timestamp`, `session_id`, `call_id`, `tool`, `input`, `message_id`, `block` |
|
|
141
|
+
| `tool_result` | `type`, `seq`, `timestamp`, `session_id`, `call_id`, `status`, `output` |
|
|
142
|
+
| `tool_update` | `type`, `seq`, `timestamp`, `session_id`, `call_id`, `tick`, `source` |
|
|
143
|
+
| `step` | `type`, `seq`, `timestamp`, `session_id`, `message_id`, `model`, `usage` |
|
|
144
|
+
| `outcome` | `type`, `seq`, `timestamp`, `session_id`, `turn`, `schema`, `turn_id`, `status`, `steps`, `wall_ms`, `usage`, `models`, `denials` |
|
|
145
|
+
| `close` | `type`, `seq`, `timestamp`, `session_id`, `state` |
|
|
146
|
+
| `wait` | `type`, `seq`, `timestamp`, `session_id`, `state` |
|
|
147
|
+
| `heartbeat` | `type`, `seq`, `timestamp`, `session_id` |
|
|
148
|
+
| `compaction` | `type`, `seq`, `timestamp`, `session_id`, `state`, `trigger` |
|
|
149
|
+
| `mode` | `type`, `seq`, `timestamp`, `session_id`, `mode` |
|
|
150
|
+
| `rate_limit` | `type`, `seq`, `timestamp`, `session_id`, `status` |
|
|
151
|
+
| `task` | `type`, `seq`, `timestamp`, `session_id`, `state`, `task_id` |
|
|
152
|
+
| `notice` | `type`, `seq`, `timestamp`, `session_id`, `level`, `text` |
|
|
153
|
+
| `command_output` | `type`, `seq`, `timestamp`, `session_id`, `text` |
|
|
154
|
+
| `mission_updated` | `type`, `seq`, `timestamp`, `session_id` |
|
|
155
|
+
| `samples_updated` | `type`, `seq`, `timestamp`, `session_id` |
|
|
156
|
+
| `block_start` | `type`, `seq`, `timestamp`, `session_id`, `message_id`, `block`, `of` |
|
|
157
|
+
| `text_delta` | `type`, `seq`, `timestamp`, `session_id`, `message_id`, `block`, `text` |
|
|
158
|
+
| `reasoning_delta` | `type`, `seq`, `timestamp`, `session_id`, `message_id`, `block`, `text` |
|
|
159
|
+
| `tool_input_delta` | `type`, `seq`, `timestamp`, `session_id`, `message_id`, `block`, `json` |
|
|
160
|
+
| `retracted` | `type`, `seq`, `timestamp`, `session_id`, `message_id` |
|
|
161
|
+
<!-- vocabulary:end -->
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
# Mercury CLI SDK
|
|
2
|
+
|
|
3
|
+
`mercury-cli-sdk` 0.1.0 is a zero-runtime-dependency Python client for Mercury CLI, requiring Python 3.11 or later. Install Mercury separately and sign in through the CLI; the SDK uses its configuration and credentials. The package is Apache-2.0 and versioned separately from the CLI.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
python -m pip install mercury-cli-sdk
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
On Windows run that as `py -3 -m pip install mercury-cli-sdk` (or with the full path of `python.exe`): the `python3` name there is often the Store stub, which answers with exit code 9009. If `python -m venv` fails because `ensurepip` is missing, install `python3-venv` (Debian and Ubuntu: `apt install python3-venv`), or create the environment with `--without-pip` and install into it from an interpreter that has pip: `python -m pip --python .venv/bin/python install mercury-cli-sdk`.
|
|
10
|
+
|
|
11
|
+
## Quickstart
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
from mercury_cli_sdk import run_sync
|
|
15
|
+
|
|
16
|
+
print(run_sync('Explain the README').outcome.get('answer'))
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
For asynchronous programs and streaming, use `run`.
|
|
20
|
+
|
|
21
|
+
```python
|
|
22
|
+
import asyncio
|
|
23
|
+
from mercury_cli_sdk import run
|
|
24
|
+
|
|
25
|
+
async def main():
|
|
26
|
+
task = await run('Explain the README', partial=True)
|
|
27
|
+
async for row in task:
|
|
28
|
+
if row['type'] == 'text_delta':
|
|
29
|
+
print(row['text'], end='', flush=True)
|
|
30
|
+
result = await task.outcome
|
|
31
|
+
print(result['status'], result.get('answer'))
|
|
32
|
+
asyncio.run(main())
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
`run()` returns an async row iterator with listeners. Its `session`, `outcome` and `exit` are awaitable; `rows` retains received rows. Whole blocks arrive as `text`; `partial=True` also streams `text_delta`. `outcome` settles after the process exits and owned tool servers close. `run_sync` returns `RunResult(outcome, rows, exit)`. `connect_sync` returns a typed `SyncSession` with the same control methods and blocking row iteration. Use it as a context manager; host callbacks run on its background loop and must not call the synchronous wrapper recursively.
|
|
36
|
+
|
|
37
|
+
## Host a session
|
|
38
|
+
|
|
39
|
+
```python
|
|
40
|
+
import asyncio
|
|
41
|
+
from mercury_cli_sdk import connect
|
|
42
|
+
|
|
43
|
+
async def main():
|
|
44
|
+
async with await connect(on_permission_request=lambda ask, context: {'outcome': 'deny', 'message': 'Read-only host'}) as session:
|
|
45
|
+
print((await session.prompt('Inspect the tests'))['status'])
|
|
46
|
+
print((await session.prompt('Explain the result')).get('answer'))
|
|
47
|
+
print((await session.facts())['usage']['total_cost_usd'])
|
|
48
|
+
asyncio.run(main())
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
`prompt` awaits its own correlated turn. Only one prompt wait may be active; `steer(content, id=..., schema=...)` queues priority `now` and `follow_up(content, id=..., schema=...)` queues `later`; both keyword options are optional. `send_prompt`, `send_shell` and `send_note` expose ids and all priorities; `withdraw(id)` removes queued input, and a `prompt` waiting on it raises `MercuryError('prompt: withdrawn')`. Cancelling the awaiting task cancels the wait, not the turn; `interrupt()` ends the turn. A prompt sent while a turn is still running (after a timed-out or cancelled wait, for instance) is the CLI's to place: with no tool round left it waits and runs as the next turn, which `prompt` resolves with; at a tool-round boundary the CLI folds it into the running turn and marks its reply `in_reply_to` that prompt, and `prompt` resolves with that turn's outcome instead (a per-turn `schema` on a folded prompt is not applied). When that turn ends without any reply and the CLI's `facts` list the prompt neither queued nor in a turn, `prompt` raises within five seconds `MercuryError('prompt: turn N ended STATUS and the runner holds this prompt neither queued nor in a turn; …')` rather than waiting forever; `interrupt()` the running turn, or await its outcome row, before prompting again when you need a turn of its own. Typed `request(method, params, timeout=seconds)` and `notify` cover protocol 1, including pause, quiesce, leave, MCP and schedules. `timeout=None` disables its timer. `connect(timeout=seconds)` bounds a boot that never answers; cancelling the awaiting task ends the child too.
|
|
52
|
+
|
|
53
|
+
`on_permission_request` and `on_elicitation` receive `RequestContext` with `id` and a `cancelled` event; absent handlers deny and decline respectively. `on_read_text_file` and `on_write_text_file` route native file tools to host buffers and infer their capabilities. The equivalent `handlers` entries work too. Supplying all five `terminal/*` handlers infers terminal support; partial terminal sets do not. Explicit `capabilities` override inference.
|
|
54
|
+
|
|
55
|
+
### Checkpoints, warm workers and control
|
|
56
|
+
|
|
57
|
+
`connect` asks the CLI to capture file checkpoints (`file_checkpoints: true` on `initialize`); `checkpoints=False` opts out. The CLI answers with what it does: `session.file_checkpoints` (the `initialize` answer) and `(await session.facts())['file_checkpoints']` carry `capture` and `source`, where `initialize` means the request is honoured, `setting` that the CLI's file-checkpoint setting turned it off, `headless` that nothing asked, and `seat` or `interactive` name the CLI's own sessions; `facts` adds `restorable`, the user-message ids a rewind can return to. File checkpoints over `initialize` need Mercury 1.0.0-beta.41 or newer: an older runner answers no `file_checkpoints`, so `session.file_checkpoints` is `None`, `session.supports['file_checkpoints']` is False and `facts()['file_checkpoints']` reads `capture: False` with no `source`. `run` has no `initialize` and captures nothing. After any accepted prompt input, including `send_prompt`, `steer` and `follow_up`, `last_prompt_id` is its user-message id. Pass it to `rewind(user_message_id, 'both', dry_run=True)`, then omit `dry_run` to restore. Modes are `code`, `conversation` and `both`; the typed receipt reports changed files and removed conversation rows.
|
|
58
|
+
|
|
59
|
+
`prewarm(**options)` or `connect(warm=True)` returns an unclaimed runner. On `MercurySession` and `SyncSession`, `session.session_id` reflects `initialized['session_id']`: both are None until `claim(session_id=..., model=..., effort=..., mode=..., resume=...)` succeeds and updates them from the CLI's reply. Only `session_id` is required. Prompt input before a claim fails immediately with `MercuryError('session is unclaimed; call claim() before prompting')`. Warm workers reject boot-time identity flags; ordinary, resumed and continued sessions already have an identity. The unclaimed boot runs in the CLI's session-runner role, which withholds subagents and workflows unless the CLI setting `Crewmates while backgrounded` is on, offers the Contract tool and refuses `Sleep` beyond 300 seconds. `facts`, `rewind`, `stop_agent` and `resume_agent` return generated result types. Model, effort, permission mode and kit changes use `set_model`, `set_effort`, `set_mode` and `set_kit`.
|
|
60
|
+
|
|
61
|
+
## Inline tools and agents
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
import asyncio
|
|
65
|
+
from mercury_cli_sdk import define_tool, run
|
|
66
|
+
|
|
67
|
+
async def main():
|
|
68
|
+
greeting = define_tool('greeting', 'Return a greeting', {}, lambda _: 'Hello')
|
|
69
|
+
task = await run('Use greeting to say hello', tools=[greeting])
|
|
70
|
+
result = await task.outcome
|
|
71
|
+
print(result['status'], result.get('answer'))
|
|
72
|
+
asyncio.run(main())
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
Both doors own the authenticated loopback MCP server for `tools`, close it on exit or failed startup, and merge it with `mcp`. Tool names `mcp__sdk-tools__<name>` are added to `allowed_tools` and existing inline custom-agent `tools` allowlists without mutating your options. `auto_allow_tools=False` keeps serving but leaves permission grants to you; explicit denials still apply. An unanswered headless ask produces `blocked`. `define_agent` validates definitions passed in `agent_defs`. `serve_tools(tools, name)` remains available for manually owned servers. Tool callbacks may accept a second `ToolContext` with a `cancelled` event for cooperative cancellation; keep the event loop running. `define_tool` accepts JSON Schema, a mapping such as `{'query': str, 'limit': int}`, or a TypedDict with NotRequired, Required and Annotated descriptions.
|
|
76
|
+
|
|
77
|
+
## Inputs, output schemas and launch options
|
|
78
|
+
|
|
79
|
+
A prompt accepts text, `list[InputBlock]` or an `AsyncIterable[str | InputRow]`. Block and iterable prompts automatically use input rows and close stdin when complete. `text_block(text)` builds text; `image_block(data, media_type)` accepts base64 text, bytes or `pathlib.Path`. For manual streaming use `input='rows'`, `send(row)` and `close_input()`. On the rows door the CLI writes nothing, not even `session`, until the first input row arrives, so `session`, `cancel` and `interrupt()` take effect once the first prompt is sent; `close_input()` on a run that sent no row ends it without an outcome. `outcome` is the final run outcome; listen to individual outcome rows for multi-turn input.
|
|
80
|
+
|
|
81
|
+
`structured_schema(json_schema, decode)` infers `TypedOutcome[T]` from the decoder when passed as `schema=` to `run`, `connect` or `session.prompt`; a `schema` also accepts a JSON Schema dictionary, JSON text or a schema file path. On `run` it is the `--schema` flag and shapes every turn; on `connect` it travels on `initialize` and as the `--schema` flag, so it shapes every turn of the session on every Mercury version; `prompt(content, schema=...)` sends that turn's schema on its prompt row and overrides the session's for that turn, so one session can ask for a different shape each turn, and a turn without one carries no `structured`. A per-turn schema needs Mercury 1.0.0-beta.41 or newer: an older runner ignores the field, so the package refuses it before sending with ``MercuryError('per-turn schema needs Mercury 1.0.0-beta.41 or newer; this runner is 1.0.0-beta.40 — run `mercury update`')``, and `session.supports['per_turn_schema']` beside `session.runner_version` says so in advance (`FEATURE_FLOORS` lists each floor; the version is read from the `initialize` answer, and an answer that already carries `file_checkpoints` counts as the newer wire). Where the runner honours the schema, Mercury holds the model to it and settles the turn with `structured`; a schema that is not a JSON Schema is refused before anything is sent — the package itself refuses an unknown `type`, non-object `properties` and the other keywords its reader indexes into (`schema_problem(schema)` returns the words), and the CLI refuses the rest with its own issue — so `run`, `prompt`, `steer`, `follow_up`, `send_prompt` or `connect` raises `MercurySchemaError` with the issue at path `schema` and `outcome` None, and no model turn is spent. A completed `structured` is decoded by the descriptor and read once more by the package (types, scalar constants/enums, object fields, array items, numeric ranges and string lengths), so a replayed fixture is held to the same shape; a mismatch raises `MercurySchemaError` with exact `issues` and the raw `outcome`. `validate_outcome` also validates recorded outcomes.
|
|
82
|
+
|
|
83
|
+
`RunOptions` includes `replay_to`, `restore_files`, `worktree`, `reasoning_mode`, `brief_file`, `brief_add_file` and `debug`. The keyword options of `run`, `run_sync`, `connect`, `connect_sync` and `prewarm` are typed by `RunKwargs` and `ConnectKwargs`, so a type checker reports a wrong name or value. `argv_of` previews flags; `extra_args` passes additional flags. Both doors accept an explicit executable or prefix array such as `mercury=['ssh', 'host', 'mercury']`. Otherwise discovery uses `MERCURY_BIN`; then the managed install, read as Mercury's own command reads it: `current.txt` under `MERCURY_VERSIONS_DIR`, else `versions` in the Mercury home (`MERCURY_CONFIG_DIR`, `MERCURY_HOME` or `~/.mercury`; `%USERPROFILE%\.mercury` on Windows), whose version directory's `mercury.mjs` is run on the Node runtime vendored beside it; then `mercury` on PATH; then the stable command the installer writes (`~/.local/bin/mercury`; `%LOCALAPPDATA%\Mercury\bin\mercury.cmd` on Windows) and `~/.mercury/bin/mercury`; then, on macOS and Linux, the Homebrew command (`$HOMEBREW_PREFIX/bin/mercury`, `/opt/homebrew/bin/mercury`, `/usr/local/bin/mercury`, `/home/linuxbrew/.linuxbrew/bin/mercury`), for a host launched with a stripped PATH (an empty PATH skips this rung). No shell is involved: Mercury's managed command (`mercury`, `mercury.cmd`, `mercury.ps1`) resolves to that bundle, the Homebrew wrapper to the keg's `mercury.mjs` on its vendored runtime, an npm-style `.cmd` shim to its JavaScript entry point, and a `mercury.cmd` beside a `mercury.mjs` to that bundle; any other command shim requires an explicit `[node, script]` array, and a managed command whose install is missing is refused with the pointer file it looked for. A relative executable with a slash (`./bin/mercury`) is resolved against `cwd`; on Windows the `env` keys are read without regard to case, so a copy of the environment spelled `Path` and `Pathext` still resolves. A `.mjs`, `.cjs` or `.js` executable such as a built `mercury.mjs` runs on `MERCURY_NODE` when set (one that names no executable file is refused by name, as the launcher refuses it), else the runtime bundled beside it under `vendor/node`, else `node` from PATH.
|
|
84
|
+
|
|
85
|
+
## Test without a model
|
|
86
|
+
|
|
87
|
+
```python
|
|
88
|
+
import asyncio
|
|
89
|
+
from mercury_cli_sdk import run
|
|
90
|
+
from mercury_cli_sdk.testing import start_fixture_server, fixture_session_row, fixture_outcome_row
|
|
91
|
+
|
|
92
|
+
async def main():
|
|
93
|
+
rows = [fixture_session_row(), fixture_outcome_row(answer='ok')]
|
|
94
|
+
async with await start_fixture_server({'rows': rows}) as fixture:
|
|
95
|
+
task = await run('test', mercury=fixture.mercury)
|
|
96
|
+
assert (await task.outcome)['answer'] == 'ok'
|
|
97
|
+
asyncio.run(main())
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
`fixture_turn(overrides, prompt_id)` builds a correlated turn/outcome pair. You can also replay `task.rows`. Fixtures validate rows and RPC replies before listening; `'validate': False` in the fixture dictionary is for deliberately malformed-wire tests. `methods` holds ordered `{ result, before?, after? }` or `{ error }` replies; before/after and `answers` contain RPC messages. `received` records inputs and `inputCount` delays replay. Missing methods return method-not-found. Fixtures use neither a CLI nor model credentials and do not simulate the CLI's internal behaviour.
|
|
101
|
+
|
|
102
|
+
## Rows, errors and cleanup
|
|
103
|
+
|
|
104
|
+
`parse_row`, `row_of`, `input_row_of` and `validate` use generated schemas. `is_main_thread` separates subagent rows. Unknown types become `unknown_row` with `original_type`, raw payload and envelope; known extra fields are preserved. Schema-version changes and malformed known rows are rejected.
|
|
105
|
+
|
|
106
|
+
Non-completed turns resolve their outcome status (including failed authentication); refusals throw `MercuryRefusal`. Other specific `MercuryError` subclasses are `MercuryUsageError`, `MercuryExitError`, `MercurySpawnError`, `MercuryWireError` and `MercurySchemaError`. Exit/usage errors preserve the door and exit receipt; RPC errors preserve code and data. Check status rather than only exit code.
|
|
107
|
+
|
|
108
|
+
`stderr` holds what the child has written to standard error so far, read as text with `\r\n` normalised to `\n` (a Windows child's line endings included) so `exit.stderr`, the handle and the chunks agree; `on_stderr` (or an `on('stderr', …)` listener, also on `SyncSession`) receives each chunk as it arrives, on both doors. `cancel=asyncio.Event()` interrupts a run when the event is set. `interrupt`, `terminate` and `kill` are synchronous (not awaited) and signal the child with SIGINT, SIGTERM and SIGKILL; the exit is awaited through `exit`. On Windows, which delivers no signal, they end the process the way Node's child_process does, and `exit.signal` names the one the package sent. An interrupt the package sent always settles the turn as an `interrupted` outcome: the CLI writes that row itself where SIGINT reaches it, and where the child ends by the signal before writing one the package completes the turn with an `interrupted` outcome row folded from the rows it received. A signal the package did not send, and `terminate` or `kill`, raise `MercuryExitError`. Close handles in finally or with `async with`; `close` ends stdin, escalates after five seconds to termination, and after ten to killing. Normal host exit sends SIGTERM to live children; an unhandled killing signal cannot run cleanup, so long-running hosts should handle SIGTERM and close sessions.
|
|
109
|
+
|
|
110
|
+
<!-- vocabulary:start -->
|
|
111
|
+
| Row | Required fields |
|
|
112
|
+
| --- | --- |
|
|
113
|
+
| `session` | `type`, `seq`, `timestamp`, `session_id`, `schema`, `version`, `cwd`, `model`, `mode`, `tools`, `mcp_servers`, `commands`, `agents`, `skills`, `extensions` |
|
|
114
|
+
| `turn` | `type`, `seq`, `timestamp`, `session_id`, `state`, `turn_id` |
|
|
115
|
+
| `text` | `type`, `seq`, `timestamp`, `session_id`, `message_id`, `block`, `text` |
|
|
116
|
+
| `reasoning` | `type`, `seq`, `timestamp`, `session_id`, `message_id`, `block`, `text` |
|
|
117
|
+
| `tool_call` | `type`, `seq`, `timestamp`, `session_id`, `call_id`, `tool`, `input`, `message_id`, `block` |
|
|
118
|
+
| `tool_result` | `type`, `seq`, `timestamp`, `session_id`, `call_id`, `status`, `output` |
|
|
119
|
+
| `tool_update` | `type`, `seq`, `timestamp`, `session_id`, `call_id`, `tick`, `source` |
|
|
120
|
+
| `step` | `type`, `seq`, `timestamp`, `session_id`, `message_id`, `model`, `usage` |
|
|
121
|
+
| `outcome` | `type`, `seq`, `timestamp`, `session_id`, `turn`, `schema`, `turn_id`, `status`, `steps`, `wall_ms`, `usage`, `models`, `denials` |
|
|
122
|
+
| `close` | `type`, `seq`, `timestamp`, `session_id`, `state` |
|
|
123
|
+
| `wait` | `type`, `seq`, `timestamp`, `session_id`, `state` |
|
|
124
|
+
| `heartbeat` | `type`, `seq`, `timestamp`, `session_id` |
|
|
125
|
+
| `compaction` | `type`, `seq`, `timestamp`, `session_id`, `state`, `trigger` |
|
|
126
|
+
| `mode` | `type`, `seq`, `timestamp`, `session_id`, `mode` |
|
|
127
|
+
| `rate_limit` | `type`, `seq`, `timestamp`, `session_id`, `status` |
|
|
128
|
+
| `task` | `type`, `seq`, `timestamp`, `session_id`, `state`, `task_id` |
|
|
129
|
+
| `notice` | `type`, `seq`, `timestamp`, `session_id`, `level`, `text` |
|
|
130
|
+
| `command_output` | `type`, `seq`, `timestamp`, `session_id`, `text` |
|
|
131
|
+
| `mission_updated` | `type`, `seq`, `timestamp`, `session_id` |
|
|
132
|
+
| `samples_updated` | `type`, `seq`, `timestamp`, `session_id` |
|
|
133
|
+
| `block_start` | `type`, `seq`, `timestamp`, `session_id`, `message_id`, `block`, `of` |
|
|
134
|
+
| `text_delta` | `type`, `seq`, `timestamp`, `session_id`, `message_id`, `block`, `text` |
|
|
135
|
+
| `reasoning_delta` | `type`, `seq`, `timestamp`, `session_id`, `message_id`, `block`, `text` |
|
|
136
|
+
| `tool_input_delta` | `type`, `seq`, `timestamp`, `session_id`, `message_id`, `block`, `json` |
|
|
137
|
+
| `retracted` | `type`, `seq`, `timestamp`, `session_id`, `message_id` |
|
|
138
|
+
<!-- vocabulary:end -->
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
import base64
|
|
3
|
+
import csv
|
|
4
|
+
import hashlib
|
|
5
|
+
import io
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
import sys
|
|
8
|
+
import tarfile
|
|
9
|
+
import tomllib
|
|
10
|
+
import zipfile
|
|
11
|
+
|
|
12
|
+
ROOT = Path(__file__).resolve().parent
|
|
13
|
+
PROJECT = tomllib.loads((ROOT / 'pyproject.toml').read_text(encoding='utf-8'))['project']
|
|
14
|
+
STEM = PROJECT['name'].replace('-', '_') + '-' + PROJECT['version']
|
|
15
|
+
INFO = STEM + '.dist-info'
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def metadata() -> bytes:
|
|
19
|
+
fields = [('Metadata-Version', '2.4'), ('Name', PROJECT['name']), ('Version', PROJECT['version']), ('Summary', PROJECT['description']), ('Requires-Python', PROJECT['requires-python']), ('License-Expression', PROJECT['license']), ('License-File', 'LICENSE'), ('Keywords', ','.join(PROJECT['keywords'])), ('Description-Content-Type', 'text/markdown')]
|
|
20
|
+
fields.extend(('Classifier', c) for c in PROJECT['classifiers'])
|
|
21
|
+
fields.extend(('Project-URL', f'{k}, {v}') for k, v in PROJECT['urls'].items())
|
|
22
|
+
return ('\n'.join(f'{k}: {v}' for k, v in fields) + '\n\n' + (ROOT / 'README.md').read_text(encoding='utf-8')).encode()
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def get_requires_for_build_wheel(config_settings=None): return []
|
|
26
|
+
def get_requires_for_build_sdist(config_settings=None): return []
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def prepare_metadata_for_build_wheel(metadata_directory, config_settings=None):
|
|
30
|
+
target = Path(metadata_directory) / INFO
|
|
31
|
+
target.mkdir(parents=True, exist_ok=True)
|
|
32
|
+
(target / 'METADATA').write_bytes(metadata())
|
|
33
|
+
return INFO
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def build_wheel(wheel_directory, config_settings=None, metadata_directory=None):
|
|
37
|
+
files = {p.relative_to(ROOT / 'src').as_posix(): p.read_bytes() for p in sorted((ROOT / 'src').rglob('*')) if p.is_file() and (p.suffix == '.py' or p.name == 'py.typed')}
|
|
38
|
+
return _write_wheel(wheel_directory, files)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def build_editable(wheel_directory, config_settings=None, metadata_directory=None):
|
|
42
|
+
files = {STEM + '.pth': (str(ROOT / 'src') + '\n').encode('utf-8')}
|
|
43
|
+
return _write_wheel(wheel_directory, files)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
get_requires_for_build_editable = get_requires_for_build_wheel
|
|
47
|
+
prepare_metadata_for_build_editable = prepare_metadata_for_build_wheel
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _write_wheel(wheel_directory, files):
|
|
51
|
+
dest = Path(wheel_directory)
|
|
52
|
+
dest.mkdir(parents=True, exist_ok=True)
|
|
53
|
+
filename = STEM + '-py3-none-any.whl'
|
|
54
|
+
files[INFO + '/METADATA'] = metadata()
|
|
55
|
+
files[INFO + '/WHEEL'] = b'Wheel-Version: 1.0\nGenerator: mercury-cli-sdk\nRoot-Is-Purelib: true\nTag: py3-none-any\n'
|
|
56
|
+
files[INFO + '/licenses/LICENSE'] = (ROOT / 'LICENSE').read_bytes()
|
|
57
|
+
record = io.StringIO(newline='')
|
|
58
|
+
writer = csv.writer(record)
|
|
59
|
+
for name, data in files.items():
|
|
60
|
+
digest = base64.urlsafe_b64encode(hashlib.sha256(data).digest()).decode().rstrip('=')
|
|
61
|
+
writer.writerow([name, 'sha256=' + digest, len(data)])
|
|
62
|
+
writer.writerow([INFO + '/RECORD', '', ''])
|
|
63
|
+
files[INFO + '/RECORD'] = record.getvalue().encode()
|
|
64
|
+
with zipfile.ZipFile(dest / filename, 'w', zipfile.ZIP_DEFLATED) as archive:
|
|
65
|
+
for name, data in files.items(): archive.writestr(zipfile.ZipInfo(name, (2020, 1, 1, 0, 0, 0)), data)
|
|
66
|
+
return filename
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def build_sdist(sdist_directory, config_settings=None):
|
|
70
|
+
dest = Path(sdist_directory)
|
|
71
|
+
dest.mkdir(parents=True, exist_ok=True)
|
|
72
|
+
filename = STEM + '.tar.gz'
|
|
73
|
+
files = [ROOT / n for n in ('pyproject.toml', 'build_backend.py', 'README.md', 'LICENSE')]
|
|
74
|
+
files += [p for p in sorted((ROOT / 'src').rglob('*')) if p.is_file() and (p.suffix == '.py' or p.name == 'py.typed')]
|
|
75
|
+
with tarfile.open(dest / filename, 'w:gz') as archive:
|
|
76
|
+
for p in files:
|
|
77
|
+
data = p.read_bytes()
|
|
78
|
+
info = tarfile.TarInfo(STEM + '/' + p.relative_to(ROOT).as_posix())
|
|
79
|
+
info.size = len(data)
|
|
80
|
+
info.mode = 0o644
|
|
81
|
+
archive.addfile(info, io.BytesIO(data))
|
|
82
|
+
data = metadata()
|
|
83
|
+
info = tarfile.TarInfo(STEM + '/PKG-INFO')
|
|
84
|
+
info.size = len(data)
|
|
85
|
+
archive.addfile(info, io.BytesIO(data))
|
|
86
|
+
return filename
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
if __name__ == '__main__':
|
|
90
|
+
dest = sys.argv[1] if len(sys.argv) > 1 else str(ROOT / 'dist')
|
|
91
|
+
print(build_wheel(dest))
|
|
92
|
+
print(build_sdist(dest))
|