marona-cli 1.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Blessing Nyuwani
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,230 @@
1
+ Metadata-Version: 2.4
2
+ Name: marona-cli
3
+ Version: 1.0.1
4
+ Summary: Marona command line tools for Agents, Hub capabilities and MCP development.
5
+ Author: Blessing Nyuwani
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://www.marona.ai
8
+ Project-URL: Documentation, https://platform.marona.ai/docs
9
+ Requires-Python: >=3.10
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Requires-Dist: marona<3,>=2.12.2
13
+ Requires-Dist: keyring<26,>=25
14
+ Provides-Extra: dev
15
+ Requires-Dist: pytest<9,>=8; extra == "dev"
16
+ Requires-Dist: build<2,>=1.2; extra == "dev"
17
+ Requires-Dist: ruff<1,>=0.14; extra == "dev"
18
+ Dynamic: license-file
19
+
20
+ # Marona CLI
21
+
22
+ Author: **Blessing Nyuwani**.
23
+
24
+ The Python command line client for Marona Agents, Hub capabilities, protocol
25
+ sessions and MCP development. It uses the official `marona` SDK for execution.
26
+ Source lives in this repository at `clients/cli`; it is not a separate service.
27
+
28
+ ## Install
29
+
30
+ Python 3.10 or later. Install in a virtual environment:
31
+
32
+ ```sh
33
+ python3 -m venv .venv-cli
34
+ . .venv-cli/bin/activate
35
+ python -m pip install --upgrade marona-cli
36
+ marona --help
37
+ marona version
38
+ ```
39
+
40
+ The CLI package is `marona-cli` 1.0.1. Installation also installs the required
41
+ Python SDK 2.12.2 or later. No repository checkout is needed.
42
+
43
+ For an isolated command available anywhere, use one of:
44
+
45
+ ```sh
46
+ pipx install --include-deps marona-cli
47
+ # Or:
48
+ uv tool install --with-executables-from marona marona-cli
49
+ ```
50
+
51
+ On Windows, activate the virtual environment with `.venv-cli\\Scripts\\Activate.ps1`
52
+ instead of the shell activation command above. Each developer authenticates with
53
+ their own Marona key using `marona auth login` or `MARONA_API_KEY`.
54
+
55
+ The SDK owns the existing `marona` launcher and delegates to this package when
56
+ installed. This avoids two packages overwriting the same executable. SDK-only
57
+ installations retain their existing `version`, `build`, `publish` and `deploy`
58
+ commands. `marona-cli` and `python -m marona_cli` also invoke the full CLI.
59
+
60
+ ## Credentials and settings
61
+
62
+ Set `MARONA_API_KEY` in your shell/CI secret environment, or run:
63
+
64
+ ```sh
65
+ marona auth login
66
+ marona auth status --verify
67
+ marona config set --model marona/auto --user-id developer-123
68
+ marona config show
69
+ marona doctor
70
+ ```
71
+
72
+ Login reads a hidden prompt, verifies access with a read-only runtime request,
73
+ and stores the key in macOS Keychain, Windows Credential Locker, Secret Service
74
+ or KWallet. It never falls back to a plaintext credential file. Headless hosts
75
+ can use environment variables; a secret manager may pipe to `auth login
76
+ --key-stdin` when an OS store is available. `auth logout` removes the stored
77
+ credential for the current profile/endpoints; it cannot unset your parent
78
+ shell's environment variable. Platform operations also accept
79
+ `MARONA_DEVELOPER_TOKEN` for an authenticated developer session.
80
+
81
+ Profiles hold only runtime URL, platform URL, model and user identity. Defaults
82
+ are `https://edge.marona.ai`, `https://platform.marona.ai/api`, and `marona/auto`.
83
+ Settings resolve in this order: command flags, environment, profile, defaults.
84
+ Use `--profile staging` or `MARONA_PROFILE` to select a profile. Supported
85
+ environment settings are `MARONA_RUNTIME_URL`, `MARONA_PLATFORM_URL`,
86
+ `MARONA_MODEL`, and `MARONA_USER_ID`. The settings file is
87
+ `$XDG_CONFIG_HOME/marona/config.json` (normally `~/.config/marona/config.json`),
88
+ or `%APPDATA%/marona/config.json` on Windows. Override with `MARONA_CONFIG_FILE`.
89
+ Stored keys are bound to both endpoints and the profile, so changing an
90
+ endpoint does not send a previously saved credential to a different server.
91
+
92
+ ## Agents
93
+
94
+ ```sh
95
+ marona run 'Explain the BCI workflow'
96
+ marona run --stream 'Explain the BCI workflow'
97
+ marona chat --session-id my-conversation
98
+ marona run --app documents 'Find the project guide'
99
+ marona apps --search documents --limit 20
100
+ marona tools --app documents
101
+ printf '%s' 'Explain this briefly' | marona run
102
+ ```
103
+
104
+ `chat` streams by default. `/new` creates a fresh session; `/exit`, EOF and Ctrl+C
105
+ end it. New runs use unique session IDs, written to stderr. Pass `--session-id`
106
+ to continue a conversation. Apps attach through `client.hub.connect`; the CLI
107
+ does not bypass runtime permissions, approvals, service authentication or tool
108
+ policies. Without `--app`, an inline Agent has no Hub tools attached.
109
+
110
+ For structured output, tools, A2A, B2A, D2A or other protocols, keep an ordinary
111
+ SDK `Agent` in your own `agent.py`:
112
+
113
+ ```python
114
+ from marona import Agent
115
+ from pydantic import BaseModel, ConfigDict
116
+
117
+
118
+ class Answer(BaseModel):
119
+ model_config = ConfigDict(extra="forbid")
120
+ text: str
121
+
122
+
123
+ agent = Agent(
124
+ name="Project Assistant",
125
+ model="marona/auto",
126
+ instructions="Answer clearly and concisely.",
127
+ output_type=Answer,
128
+ output_schema_strict=True,
129
+ )
130
+ ```
131
+
132
+ ```sh
133
+ marona run --agent agent:agent --json 'Explain the workflow'
134
+ marona chat --agent agent:agent
135
+ marona run --agent agent:agent --input-json - < input.json
136
+ ```
137
+
138
+ `--agent` imports and executes the named Python module. Use only trusted local
139
+ code. The SDK client exists before import, so the Agent binds to that client.
140
+ Instructions, model, tools, schemas and protocol definitions in the imported
141
+ Agent remain authoritative. `--input-json` passes standard SDK structured or
142
+ multimodal input; a prompt can also be supplied directly or piped as text.
143
+ Inputs are bounded to 4 MiB. Text/JSON output is UTF-8 and terminal controls are
144
+ removed from human output.
145
+
146
+ ## Realtime protocols
147
+
148
+ Configure `Agent(protocols=[...])` normally in `agent.py`, including your B2A
149
+ provider or D2A device. The CLI uses the SDK's `Runner.connect` directly:
150
+
151
+ ```sh
152
+ marona connect --agent agent:agent --user-id user-123 --session-id session-123
153
+ marona connect --agent agent:agent --protocol b2a --user-id user-123 \
154
+ --input-json signal.json --signal
155
+ marona connect --agent agent:agent --protocol d2a --user-id user-123 \
156
+ --input-json message.json
157
+ marona protocol validate b2a message.json
158
+ marona protocol validate d2a - < message.json
159
+ ```
160
+
161
+ `connect` emits SDK events as newline-delimited JSON and stays open until Ctrl+C
162
+ or the SDK closes the session. It can send one optional initial message/signal
163
+ and receive provider streams. It does not impose the one-response timeout on a
164
+ persistent session. `run --agent ... --input-json ...` produces one complete
165
+ protocol result. Protocol validation runs locally without credentials or network
166
+ calls. The CLI does not invent message fields or neural/device behavior. Native
167
+ audio-device playback is not supplied by this terminal client; use the existing
168
+ media SDK adapters for speaker/microphone integration.
169
+
170
+ ## MCP projects and hosting
171
+
172
+ ```sh
173
+ marona init agent my-agent
174
+ marona init mcp greeting-tools
175
+ cd greeting-tools
176
+ marona mcp serve server:server
177
+ marona mcp serve server:server --transport stdio
178
+ marona publish --registration registration.json
179
+ marona deploy --app-id APP_ID --source-url https://github.com/OWNER/REPO \
180
+ --branch main --secret-env MCP_API_KEY
181
+ marona deployments list --app-id APP_ID
182
+ marona deployments get --app-id APP_ID --deployment-id DEPLOYMENT_ID
183
+ ```
184
+
185
+ Generated projects contain direct SDK objects, one requirements file, a
186
+ Dockerfile and short instructions. Existing directories are never overwritten.
187
+ Their only runtime dependency is the published `marona==2.12.1` SDK. Generated
188
+ Agents run with `python main.py 'Hello'` and MCP servers with `python server.py`.
189
+ Both Dockerfiles run Python directly; neither needs the CLI or an unpublished
190
+ package to build or run. The full CLI remains an optional development tool.
191
+ `mcp serve` defaults to loopback. Configure your service's allowed hosts,
192
+ origins and authentication when exposing HTTP. `publish` registers an App;
193
+ only `--submit` additionally submits it for review. `deploy` creates a hosted
194
+ deployment and may incur hosting charges. It defaults to branch `main`.
195
+ Private repository access must already be configured in Marona Platform; the
196
+ CLI does not upload your GitHub credentials or repository contents.
197
+
198
+ For an offline Python tool, implement the SDK's portable callable contract in
199
+ `marona_offline.py`, then build it with
200
+ `marona build --target python --source . --output dist/tools.zip`.
201
+ This packages only the entrypoint module by default. Use `--include` for each
202
+ additional module or asset; review explicit includes before distributing an
203
+ archive. `--target wasm` packages an existing WebAssembly binary. Building a
204
+ portable tool and deploying an HTTP MCP server are separate operations.
205
+
206
+ ## Automation and errors
207
+
208
+ `--json` gives one JSON object for a completed run, or one event per line for
209
+ streaming. Informational messages and errors go to stderr. Commands perform no
210
+ automatic retries, so a network failure never silently repeats a tool/action.
211
+
212
+ Exit codes: `0` success, `1` execution failure, `2` invalid configuration/input,
213
+ `3` runtime/authentication/network error, `4` authorization or approval required,
214
+ `130` interrupted. `doctor` is local; use `auth status --verify` for a network
215
+ check. Credentials and response bodies are omitted from transport errors.
216
+
217
+ ## Develop and release
218
+
219
+ ```sh
220
+ python -m pip install -e './clients/python' -e './clients/cli[dev]'
221
+ python -m pytest clients/cli/tests
222
+ python -m ruff check --config clients/cli/pyproject.toml clients/cli
223
+ python -m build clients/cli
224
+ ```
225
+
226
+ The CI matrix covers Python 3.10/3.13 on Linux, macOS and Windows and builds both packages.
227
+ Release the SDK dispatcher first, then the CLI. Publication workflows require
228
+ the current `main` revision. The CLI workflow must have a PyPI trusted publisher
229
+ configured for `marona-cli`. Both package workflows support a temporary isolated
230
+ runner with the same trusted identity when hosted runners are unavailable.
@@ -0,0 +1,211 @@
1
+ # Marona CLI
2
+
3
+ Author: **Blessing Nyuwani**.
4
+
5
+ The Python command line client for Marona Agents, Hub capabilities, protocol
6
+ sessions and MCP development. It uses the official `marona` SDK for execution.
7
+ Source lives in this repository at `clients/cli`; it is not a separate service.
8
+
9
+ ## Install
10
+
11
+ Python 3.10 or later. Install in a virtual environment:
12
+
13
+ ```sh
14
+ python3 -m venv .venv-cli
15
+ . .venv-cli/bin/activate
16
+ python -m pip install --upgrade marona-cli
17
+ marona --help
18
+ marona version
19
+ ```
20
+
21
+ The CLI package is `marona-cli` 1.0.1. Installation also installs the required
22
+ Python SDK 2.12.2 or later. No repository checkout is needed.
23
+
24
+ For an isolated command available anywhere, use one of:
25
+
26
+ ```sh
27
+ pipx install --include-deps marona-cli
28
+ # Or:
29
+ uv tool install --with-executables-from marona marona-cli
30
+ ```
31
+
32
+ On Windows, activate the virtual environment with `.venv-cli\\Scripts\\Activate.ps1`
33
+ instead of the shell activation command above. Each developer authenticates with
34
+ their own Marona key using `marona auth login` or `MARONA_API_KEY`.
35
+
36
+ The SDK owns the existing `marona` launcher and delegates to this package when
37
+ installed. This avoids two packages overwriting the same executable. SDK-only
38
+ installations retain their existing `version`, `build`, `publish` and `deploy`
39
+ commands. `marona-cli` and `python -m marona_cli` also invoke the full CLI.
40
+
41
+ ## Credentials and settings
42
+
43
+ Set `MARONA_API_KEY` in your shell/CI secret environment, or run:
44
+
45
+ ```sh
46
+ marona auth login
47
+ marona auth status --verify
48
+ marona config set --model marona/auto --user-id developer-123
49
+ marona config show
50
+ marona doctor
51
+ ```
52
+
53
+ Login reads a hidden prompt, verifies access with a read-only runtime request,
54
+ and stores the key in macOS Keychain, Windows Credential Locker, Secret Service
55
+ or KWallet. It never falls back to a plaintext credential file. Headless hosts
56
+ can use environment variables; a secret manager may pipe to `auth login
57
+ --key-stdin` when an OS store is available. `auth logout` removes the stored
58
+ credential for the current profile/endpoints; it cannot unset your parent
59
+ shell's environment variable. Platform operations also accept
60
+ `MARONA_DEVELOPER_TOKEN` for an authenticated developer session.
61
+
62
+ Profiles hold only runtime URL, platform URL, model and user identity. Defaults
63
+ are `https://edge.marona.ai`, `https://platform.marona.ai/api`, and `marona/auto`.
64
+ Settings resolve in this order: command flags, environment, profile, defaults.
65
+ Use `--profile staging` or `MARONA_PROFILE` to select a profile. Supported
66
+ environment settings are `MARONA_RUNTIME_URL`, `MARONA_PLATFORM_URL`,
67
+ `MARONA_MODEL`, and `MARONA_USER_ID`. The settings file is
68
+ `$XDG_CONFIG_HOME/marona/config.json` (normally `~/.config/marona/config.json`),
69
+ or `%APPDATA%/marona/config.json` on Windows. Override with `MARONA_CONFIG_FILE`.
70
+ Stored keys are bound to both endpoints and the profile, so changing an
71
+ endpoint does not send a previously saved credential to a different server.
72
+
73
+ ## Agents
74
+
75
+ ```sh
76
+ marona run 'Explain the BCI workflow'
77
+ marona run --stream 'Explain the BCI workflow'
78
+ marona chat --session-id my-conversation
79
+ marona run --app documents 'Find the project guide'
80
+ marona apps --search documents --limit 20
81
+ marona tools --app documents
82
+ printf '%s' 'Explain this briefly' | marona run
83
+ ```
84
+
85
+ `chat` streams by default. `/new` creates a fresh session; `/exit`, EOF and Ctrl+C
86
+ end it. New runs use unique session IDs, written to stderr. Pass `--session-id`
87
+ to continue a conversation. Apps attach through `client.hub.connect`; the CLI
88
+ does not bypass runtime permissions, approvals, service authentication or tool
89
+ policies. Without `--app`, an inline Agent has no Hub tools attached.
90
+
91
+ For structured output, tools, A2A, B2A, D2A or other protocols, keep an ordinary
92
+ SDK `Agent` in your own `agent.py`:
93
+
94
+ ```python
95
+ from marona import Agent
96
+ from pydantic import BaseModel, ConfigDict
97
+
98
+
99
+ class Answer(BaseModel):
100
+ model_config = ConfigDict(extra="forbid")
101
+ text: str
102
+
103
+
104
+ agent = Agent(
105
+ name="Project Assistant",
106
+ model="marona/auto",
107
+ instructions="Answer clearly and concisely.",
108
+ output_type=Answer,
109
+ output_schema_strict=True,
110
+ )
111
+ ```
112
+
113
+ ```sh
114
+ marona run --agent agent:agent --json 'Explain the workflow'
115
+ marona chat --agent agent:agent
116
+ marona run --agent agent:agent --input-json - < input.json
117
+ ```
118
+
119
+ `--agent` imports and executes the named Python module. Use only trusted local
120
+ code. The SDK client exists before import, so the Agent binds to that client.
121
+ Instructions, model, tools, schemas and protocol definitions in the imported
122
+ Agent remain authoritative. `--input-json` passes standard SDK structured or
123
+ multimodal input; a prompt can also be supplied directly or piped as text.
124
+ Inputs are bounded to 4 MiB. Text/JSON output is UTF-8 and terminal controls are
125
+ removed from human output.
126
+
127
+ ## Realtime protocols
128
+
129
+ Configure `Agent(protocols=[...])` normally in `agent.py`, including your B2A
130
+ provider or D2A device. The CLI uses the SDK's `Runner.connect` directly:
131
+
132
+ ```sh
133
+ marona connect --agent agent:agent --user-id user-123 --session-id session-123
134
+ marona connect --agent agent:agent --protocol b2a --user-id user-123 \
135
+ --input-json signal.json --signal
136
+ marona connect --agent agent:agent --protocol d2a --user-id user-123 \
137
+ --input-json message.json
138
+ marona protocol validate b2a message.json
139
+ marona protocol validate d2a - < message.json
140
+ ```
141
+
142
+ `connect` emits SDK events as newline-delimited JSON and stays open until Ctrl+C
143
+ or the SDK closes the session. It can send one optional initial message/signal
144
+ and receive provider streams. It does not impose the one-response timeout on a
145
+ persistent session. `run --agent ... --input-json ...` produces one complete
146
+ protocol result. Protocol validation runs locally without credentials or network
147
+ calls. The CLI does not invent message fields or neural/device behavior. Native
148
+ audio-device playback is not supplied by this terminal client; use the existing
149
+ media SDK adapters for speaker/microphone integration.
150
+
151
+ ## MCP projects and hosting
152
+
153
+ ```sh
154
+ marona init agent my-agent
155
+ marona init mcp greeting-tools
156
+ cd greeting-tools
157
+ marona mcp serve server:server
158
+ marona mcp serve server:server --transport stdio
159
+ marona publish --registration registration.json
160
+ marona deploy --app-id APP_ID --source-url https://github.com/OWNER/REPO \
161
+ --branch main --secret-env MCP_API_KEY
162
+ marona deployments list --app-id APP_ID
163
+ marona deployments get --app-id APP_ID --deployment-id DEPLOYMENT_ID
164
+ ```
165
+
166
+ Generated projects contain direct SDK objects, one requirements file, a
167
+ Dockerfile and short instructions. Existing directories are never overwritten.
168
+ Their only runtime dependency is the published `marona==2.12.1` SDK. Generated
169
+ Agents run with `python main.py 'Hello'` and MCP servers with `python server.py`.
170
+ Both Dockerfiles run Python directly; neither needs the CLI or an unpublished
171
+ package to build or run. The full CLI remains an optional development tool.
172
+ `mcp serve` defaults to loopback. Configure your service's allowed hosts,
173
+ origins and authentication when exposing HTTP. `publish` registers an App;
174
+ only `--submit` additionally submits it for review. `deploy` creates a hosted
175
+ deployment and may incur hosting charges. It defaults to branch `main`.
176
+ Private repository access must already be configured in Marona Platform; the
177
+ CLI does not upload your GitHub credentials or repository contents.
178
+
179
+ For an offline Python tool, implement the SDK's portable callable contract in
180
+ `marona_offline.py`, then build it with
181
+ `marona build --target python --source . --output dist/tools.zip`.
182
+ This packages only the entrypoint module by default. Use `--include` for each
183
+ additional module or asset; review explicit includes before distributing an
184
+ archive. `--target wasm` packages an existing WebAssembly binary. Building a
185
+ portable tool and deploying an HTTP MCP server are separate operations.
186
+
187
+ ## Automation and errors
188
+
189
+ `--json` gives one JSON object for a completed run, or one event per line for
190
+ streaming. Informational messages and errors go to stderr. Commands perform no
191
+ automatic retries, so a network failure never silently repeats a tool/action.
192
+
193
+ Exit codes: `0` success, `1` execution failure, `2` invalid configuration/input,
194
+ `3` runtime/authentication/network error, `4` authorization or approval required,
195
+ `130` interrupted. `doctor` is local; use `auth status --verify` for a network
196
+ check. Credentials and response bodies are omitted from transport errors.
197
+
198
+ ## Develop and release
199
+
200
+ ```sh
201
+ python -m pip install -e './clients/python' -e './clients/cli[dev]'
202
+ python -m pytest clients/cli/tests
203
+ python -m ruff check --config clients/cli/pyproject.toml clients/cli
204
+ python -m build clients/cli
205
+ ```
206
+
207
+ The CI matrix covers Python 3.10/3.13 on Linux, macOS and Windows and builds both packages.
208
+ Release the SDK dispatcher first, then the CLI. Publication workflows require
209
+ the current `main` revision. The CLI workflow must have a PyPI trusted publisher
210
+ configured for `marona-cli`. Both package workflows support a temporary isolated
211
+ runner with the same trusted identity when hosted runners are unavailable.
@@ -0,0 +1,3 @@
1
+ """Marona's command line client. Author: Blessing Nyuwani."""
2
+
3
+ __version__ = "1.0.1"
@@ -0,0 +1,3 @@
1
+ from .main import main
2
+
3
+ main()
@@ -0,0 +1,190 @@
1
+ """Agent execution delegates to the SDK, including tool and protocol governance."""
2
+
3
+ import asyncio
4
+ import importlib
5
+ import json
6
+ import sys
7
+ import uuid
8
+ from pathlib import Path
9
+
10
+ from marona import Agent, Marona, Runner
11
+
12
+ from .auth import api_key
13
+ from .config import config_path
14
+ from .output import emit, notice, plain
15
+
16
+ MAX_INPUT = 4 * 1024 * 1024
17
+
18
+
19
+ def read_input(location: str) -> str:
20
+ if location == "-":
21
+ value = sys.stdin.read(MAX_INPUT + 1)
22
+ else:
23
+ with Path(location).open(encoding="utf-8") as handle:
24
+ value = handle.read(MAX_INPUT + 1)
25
+ if len(value.encode("utf-8")) > MAX_INPUT:
26
+ raise ValueError("Input exceeds 4 MiB")
27
+ return value
28
+
29
+
30
+ def load_object(reference: str):
31
+ module, separator, attribute = reference.partition(":")
32
+ if not separator or not module or not attribute.isidentifier():
33
+ raise ValueError("Use a trusted Python import reference such as agent:agent")
34
+ # Only an explicitly requested module is imported. No automatic discovery.
35
+ sys.path.insert(0, str(Path.cwd()))
36
+ try:
37
+ return getattr(importlib.import_module(module), attribute)
38
+ finally:
39
+ sys.path.pop(0)
40
+
41
+
42
+ def make_client(config, *, credential=None):
43
+ directory = config_path().parent / "state" / config.credential_id
44
+ directory.mkdir(mode=0o700, parents=True, exist_ok=True)
45
+ return Marona(
46
+ api_key=credential or api_key(config),
47
+ base_url=config.runtime_url,
48
+ hub_url=config.platform_url,
49
+ cache_path=directory / "cache.sqlite",
50
+ data_dir=directory,
51
+ )
52
+
53
+
54
+ def make_agent(args, config, client):
55
+ if args.agent:
56
+ if args.app or args.instructions:
57
+ raise ValueError(
58
+ "Configure tools and instructions in the imported Agent, rather than combining --agent with --app/--instructions"
59
+ )
60
+ agent = load_object(args.agent)
61
+ if not isinstance(agent, Agent):
62
+ raise ValueError("The selected Python object is not a marona.Agent")
63
+ return agent
64
+ return Agent(
65
+ name="Marona CLI Agent",
66
+ model=config.model,
67
+ instructions=args.instructions or "Answer clearly and concisely.",
68
+ tools=client.hub.connect(apps=args.app) if args.app else None,
69
+ )
70
+
71
+
72
+ def result_data(result, session_id):
73
+ return {
74
+ "output": plain(result.output),
75
+ "session_id": session_id,
76
+ "agent": result.active_agent.name,
77
+ "usage": result.usage,
78
+ "trace_id": result.trace_id,
79
+ "protocol": result.protocol,
80
+ "feedback": plain(result.feedback),
81
+ }
82
+
83
+
84
+ async def run_turn(args, config, agent, value, session_id):
85
+ options = {
86
+ "user_id": config.user_id,
87
+ "session_id": session_id,
88
+ "timeout_ms": args.timeout * 1000,
89
+ }
90
+ if agent.protocols or agent.b2a is not None:
91
+ if not config.user_id:
92
+ raise ValueError("Protocol execution requires --user-id or MARONA_USER_ID")
93
+ if args.stream:
94
+ raise ValueError(
95
+ "Use marona connect for realtime protocol events, or run without --stream for a complete protocol result"
96
+ )
97
+ if args.stream:
98
+ if args.protocol:
99
+ raise ValueError("--protocol requires a configured Agent and marona connect")
100
+ wrote_delta = False
101
+ async for event in Runner.stream(agent, value, **options):
102
+ if args.json:
103
+ emit(event, json_mode=True)
104
+ elif event.delta is not None:
105
+ emit(event.delta, end="")
106
+ wrote_delta = True
107
+ elif event.type == "run.completed" and not wrote_delta:
108
+ emit(event.output, end="")
109
+ if not args.json:
110
+ emit("")
111
+ else:
112
+ result = await Runner.run(agent, value, protocol=args.protocol, **options)
113
+ emit(result_data(result, session_id) if args.json else result.output, json_mode=args.json)
114
+
115
+
116
+ async def execute(args, config):
117
+ session_id = args.session_id or str(uuid.uuid4())
118
+ notice(f"Session: {session_id}")
119
+ if args.command == "chat" and not sys.stdin.isatty():
120
+ raise ValueError("Interactive chat requires a terminal; pipe input to marona run instead")
121
+ async with make_client(config) as client:
122
+ agent = make_agent(args, config, client)
123
+ if args.command == "chat":
124
+ notice("Type /exit to finish or /new to start a fresh session.")
125
+ while True:
126
+ try:
127
+ print("You: ", file=sys.stderr, end="", flush=True)
128
+ value = input()
129
+ except EOFError:
130
+ break
131
+ if value.strip() == "/exit":
132
+ break
133
+ if value.strip() == "/new":
134
+ session_id = str(uuid.uuid4())
135
+ notice(f"Session: {session_id}")
136
+ elif value.strip():
137
+ await run_turn(args, config, agent, value, session_id)
138
+ else:
139
+ if args.input_json:
140
+ value = json.loads(read_input(args.input_json))
141
+ if not isinstance(value, (dict, list)):
142
+ raise ValueError("JSON input must be an object or an array")
143
+ else:
144
+ value = (
145
+ args.prompt
146
+ if args.prompt is not None
147
+ else read_input("-")
148
+ if not sys.stdin.isatty()
149
+ else ""
150
+ )
151
+ if not value.strip():
152
+ raise ValueError("Provide a prompt, pipe text, or use --input-json")
153
+ await run_turn(args, config, agent, value, session_id)
154
+
155
+
156
+ async def connect(args, config):
157
+ if not config.user_id:
158
+ raise ValueError("Protocol sessions require --user-id or MARONA_USER_ID")
159
+ session_id = args.session_id or str(uuid.uuid4())
160
+ notice(f"Session: {session_id}")
161
+ async with make_client(config) as client:
162
+ agent = make_agent(args, config, client)
163
+ async with await Runner.connect(
164
+ agent, user_id=config.user_id, session_id=session_id, protocol=args.protocol
165
+ ) as session:
166
+
167
+ async def receive():
168
+ async for event in session:
169
+ emit(event, json_mode=True)
170
+
171
+ # Receiving is continuous; sending one input does not end the session.
172
+ receiver = asyncio.create_task(receive())
173
+ try:
174
+ if args.input_json:
175
+ value = json.loads(read_input(args.input_json))
176
+ if args.signal:
177
+ send = getattr(session, "send_signal", None)
178
+ if send is None:
179
+ raise ValueError(
180
+ "The selected protocol session does not accept neural signals"
181
+ )
182
+ await send(value)
183
+ else:
184
+ await session.send(value)
185
+ elif args.signal:
186
+ raise ValueError("--signal requires --input-json")
187
+ await receiver
188
+ finally:
189
+ receiver.cancel()
190
+ await asyncio.gather(receiver, return_exceptions=True)