marona-cli 1.0.1__py3-none-any.whl

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.
marona_cli/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """Marona's command line client. Author: Blessing Nyuwani."""
2
+
3
+ __version__ = "1.0.1"
marona_cli/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .main import main
2
+
3
+ main()
marona_cli/agents.py ADDED
@@ -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)
marona_cli/auth.py ADDED
@@ -0,0 +1,60 @@
1
+ """Credentials in environment variables or the operating system credential store."""
2
+
3
+ import os
4
+
5
+ import keyring
6
+ from keyring.errors import KeyringError, PasswordDeleteError
7
+
8
+ from .config import Settings
9
+
10
+ SERVICE = "ai.marona.cli"
11
+ SECURE_BACKENDS = {
12
+ "keyring.backends.macOS",
13
+ "keyring.backends.Windows",
14
+ "keyring.backends.SecretService",
15
+ "keyring.backends.kwallet",
16
+ }
17
+
18
+
19
+ def credential_store():
20
+ backend = keyring.get_keyring()
21
+ candidates = getattr(backend, "backends", [backend])
22
+ for candidate in candidates:
23
+ if type(candidate).__module__ in SECURE_BACKENDS and candidate.priority > 0:
24
+ return candidate
25
+ raise ValueError(
26
+ "No supported OS credential store. Set MARONA_API_KEY instead; no plaintext fallback is used."
27
+ )
28
+
29
+
30
+ def stored_key(config: Settings) -> str | None:
31
+ try:
32
+ return credential_store().get_password(SERVICE, config.credential_id)
33
+ except (KeyringError, ValueError):
34
+ return None
35
+
36
+
37
+ def api_key(config: Settings, *, platform: bool = False) -> str:
38
+ value = (
39
+ (os.getenv("MARONA_DEVELOPER_TOKEN") if platform else None)
40
+ or os.getenv("MARONA_API_KEY")
41
+ or stored_key(config)
42
+ )
43
+ if not value:
44
+ raise ValueError(
45
+ "Set MARONA_API_KEY or run marona auth login. Platform commands also accept MARONA_DEVELOPER_TOKEN."
46
+ )
47
+ return value
48
+
49
+
50
+ def save_key(config: Settings, value: str) -> None:
51
+ if not value.strip() or any(c.isspace() for c in value):
52
+ raise ValueError("The developer key cannot be empty or contain whitespace")
53
+ credential_store().set_password(SERVICE, config.credential_id, value)
54
+
55
+
56
+ def delete_key(config: Settings) -> None:
57
+ try:
58
+ credential_store().delete_password(SERVICE, config.credential_id)
59
+ except PasswordDeleteError:
60
+ pass
marona_cli/config.py ADDED
@@ -0,0 +1,133 @@
1
+ """Explicit profiles containing settings only; credentials never enter JSON."""
2
+
3
+ import hashlib
4
+ import json
5
+ import os
6
+ import re
7
+ import sys
8
+ import tempfile
9
+ from dataclasses import dataclass
10
+ from pathlib import Path
11
+ from urllib.parse import urlsplit
12
+
13
+ FIELDS = {"runtime_url", "platform_url", "model", "user_id"}
14
+ DEFAULTS = {
15
+ "runtime_url": "https://edge.marona.ai",
16
+ "platform_url": "https://platform.marona.ai/api",
17
+ "model": "marona/auto",
18
+ }
19
+ ENVIRONMENT = {
20
+ "runtime_url": "MARONA_RUNTIME_URL",
21
+ "platform_url": "MARONA_PLATFORM_URL",
22
+ "model": "MARONA_MODEL",
23
+ "user_id": "MARONA_USER_ID",
24
+ }
25
+
26
+
27
+ def endpoint(value: str) -> str:
28
+ url = urlsplit(value)
29
+ if (
30
+ (
31
+ url.scheme != "https"
32
+ and not (url.scheme == "http" and url.hostname in {"localhost", "127.0.0.1", "::1"})
33
+ )
34
+ or not url.hostname
35
+ or url.username
36
+ or url.password
37
+ or url.query
38
+ or url.fragment
39
+ ):
40
+ raise ValueError(
41
+ "Use an HTTPS endpoint, or HTTP on loopback, without credentials or query parameters"
42
+ )
43
+ _ = url.port
44
+ return value.rstrip("/")
45
+
46
+
47
+ def config_path() -> Path:
48
+ override = os.getenv("MARONA_CONFIG_FILE")
49
+ if override:
50
+ return Path(override).expanduser()
51
+ if sys.platform == "win32":
52
+ root = Path(os.getenv("APPDATA", str(Path.home() / "AppData/Roaming")))
53
+ else:
54
+ root = Path(os.getenv("XDG_CONFIG_HOME", str(Path.home() / ".config")))
55
+ return root / "marona" / "config.json"
56
+
57
+
58
+ def read_profiles() -> dict:
59
+ path = config_path()
60
+ if not path.exists():
61
+ return {"version": 1, "profiles": {}}
62
+ if path.stat().st_size > 65536:
63
+ raise ValueError("CLI configuration exceeds 64 KiB")
64
+ data = json.loads(path.read_text(encoding="utf-8"))
65
+ if (
66
+ not isinstance(data, dict)
67
+ or data.get("version") != 1
68
+ or not isinstance(data.get("profiles"), dict)
69
+ ):
70
+ raise ValueError("Invalid CLI configuration: expected version 1 and profiles")
71
+ for values in data["profiles"].values():
72
+ if (
73
+ not isinstance(values, dict)
74
+ or set(values) - FIELDS
75
+ or not all(isinstance(v, str) for v in values.values())
76
+ ):
77
+ raise ValueError(
78
+ "Profiles may contain only runtime_url, platform_url, model and user_id strings"
79
+ )
80
+ return data
81
+
82
+
83
+ @dataclass(frozen=True)
84
+ class Settings:
85
+ profile: str
86
+ runtime_url: str
87
+ platform_url: str
88
+ model: str
89
+ user_id: str | None = None
90
+
91
+ @property
92
+ def credential_id(self) -> str:
93
+ return hashlib.sha256(
94
+ f"{self.profile}\n{self.runtime_url}\n{self.platform_url}".encode()
95
+ ).hexdigest()
96
+
97
+
98
+ def settings(args) -> Settings:
99
+ profile = getattr(args, "profile", None) or os.getenv("MARONA_PROFILE", "default")
100
+ if not re.fullmatch(r"[A-Za-z0-9_.-]{1,64}", profile):
101
+ raise ValueError(
102
+ "Profile names use letters, digits, dots, underscores and hyphens (1–64 characters)"
103
+ )
104
+ values = {**DEFAULTS, **read_profiles()["profiles"].get(profile, {})}
105
+ for name, env in ENVIRONMENT.items():
106
+ value = getattr(args, name, None) or os.getenv(env)
107
+ if value:
108
+ values[name] = value
109
+ values["runtime_url"] = endpoint(values["runtime_url"])
110
+ values["platform_url"] = endpoint(values["platform_url"])
111
+ if not values["model"].startswith("marona/") or len(values["model"]) <= 7:
112
+ raise ValueError("Model must be a registered marona/<alias>")
113
+ return Settings(profile=profile, **values)
114
+
115
+
116
+ def save_profile(value: Settings) -> None:
117
+ data = read_profiles()
118
+ data["profiles"][value.profile] = {
119
+ name: getattr(value, name) for name in sorted(FIELDS) if getattr(value, name) is not None
120
+ }
121
+ path = config_path()
122
+ path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
123
+ fd, temporary = tempfile.mkstemp(prefix=".config-", dir=path.parent)
124
+ try:
125
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
126
+ json.dump(data, handle, indent=2)
127
+ handle.write("\n")
128
+ handle.flush()
129
+ os.fsync(handle.fileno())
130
+ os.replace(temporary, path)
131
+ finally:
132
+ if os.path.exists(temporary):
133
+ os.unlink(temporary)
marona_cli/main.py ADDED
@@ -0,0 +1,186 @@
1
+ """One process, one explicit command; the SDK owns all runtime execution."""
2
+
3
+ import asyncio
4
+ import getpass
5
+ import json
6
+ import os
7
+ import sys
8
+
9
+ import httpx
10
+ import marona
11
+ from keyring.errors import KeyringError
12
+
13
+ from . import __version__, agents, auth, mcp, projects
14
+ from .config import config_path, save_profile, settings
15
+ from .output import emit, notice
16
+ from .parser import parser
17
+
18
+
19
+ async def dispatch(args):
20
+ versions = {"cli": __version__, "sdk": marona.__version__}
21
+ if args.command == "version" or (args.command is None and args.version):
22
+ emit(
23
+ versions if args.json else f"Marona CLI {__version__} (SDK {marona.__version__})",
24
+ json_mode=args.json,
25
+ )
26
+ return
27
+ if args.command == "init":
28
+ projects.initialize(args)
29
+ return
30
+ if args.command == "mcp":
31
+ # MCPServer.run owns its event loop. main dispatches this synchronously.
32
+ raise RuntimeError("MCP serving must use the synchronous dispatcher")
33
+ if args.command == "build":
34
+ mcp.build(args)
35
+ return
36
+ if args.command == "protocol":
37
+ mcp.validate_message(args)
38
+ return
39
+ config = settings(args)
40
+ if args.command == "config":
41
+ if args.action == "set":
42
+ save_profile(config)
43
+ emit({"path": str(config_path()), "settings": config}, json_mode=True)
44
+ elif args.command == "auth":
45
+ if args.action == "login":
46
+ if args.key_stdin:
47
+ value = sys.stdin.readline(8193).strip()
48
+ elif sys.stdin.isatty():
49
+ value = getpass.getpass("Marona developer key: ")
50
+ else:
51
+ raise ValueError("Use --key-stdin to read a credential from a pipe")
52
+ if len(value) > 8192:
53
+ raise ValueError("Developer key exceeds limit")
54
+ if not value or any(c.isspace() for c in value):
55
+ raise ValueError("The developer key cannot be empty or contain whitespace")
56
+ async with agents.make_client(config, credential=value) as client:
57
+ await client.apps.list_async(limit=1)
58
+ auth.save_key(config, value)
59
+ emit(
60
+ {"authenticated": True, "profile": config.profile, "storage": "OS credential store"}
61
+ )
62
+ elif args.action == "logout":
63
+ auth.delete_key(config)
64
+ emit(
65
+ {
66
+ "removed_stored_key": True,
67
+ "environment_key_present": bool(os.getenv("MARONA_API_KEY")),
68
+ }
69
+ )
70
+ else:
71
+ configured = bool(os.getenv("MARONA_API_KEY") or auth.stored_key(config))
72
+ if args.verify:
73
+ async with agents.make_client(config) as client:
74
+ await client.apps.list_async(limit=1)
75
+ emit(
76
+ {"profile": config.profile, "configured": configured, "verified": bool(args.verify)}
77
+ )
78
+ elif args.command == "doctor":
79
+ emit(
80
+ {
81
+ **versions,
82
+ "python": sys.version.split()[0],
83
+ "settings": config,
84
+ "credential_configured": bool(
85
+ os.getenv("MARONA_API_KEY") or auth.stored_key(config)
86
+ ),
87
+ "network_checked": False,
88
+ },
89
+ json_mode=True,
90
+ )
91
+ elif args.command in {"run", "chat"}:
92
+ await agents.execute(args, config)
93
+ elif args.command == "connect":
94
+ await agents.connect(args, config)
95
+ elif args.command in {"apps", "tools"}:
96
+ async with agents.make_client(config) as client:
97
+ if args.command == "apps":
98
+ result = await client.apps.list_async(
99
+ user_id=config.user_id, limit=args.limit, cursor=args.cursor, search=args.search
100
+ )
101
+ else:
102
+ result = await client.hub.connect(apps=args.app).list_capabilities_async()
103
+ emit(result, json_mode=True)
104
+ else:
105
+ if args.command == "deployments" and args.action == "get" and not args.deployment_id:
106
+ raise ValueError("deployments get requires --deployment-id")
107
+ if args.command == "deploy" and args.monthly_price_cents < 0:
108
+ raise ValueError("Monthly price must be nonnegative")
109
+ await mcp.platform(args, config)
110
+
111
+
112
+ def main(argv=None):
113
+ cli = parser()
114
+ args = cli.parse_args(argv)
115
+ if not hasattr(args, "json"):
116
+ args.json = False
117
+ if not args.command and not args.version:
118
+ cli.print_help()
119
+ return
120
+ try:
121
+ if args.command == "mcp":
122
+ mcp.serve(args)
123
+ else:
124
+ asyncio.run(dispatch(args))
125
+ except BrokenPipeError:
126
+ # Do not print a traceback if a consumer such as head closes stdout.
127
+ with open(os.devnull, "w") as sink:
128
+ os.dup2(sink.fileno(), sys.stdout.fileno())
129
+ raise SystemExit(0)
130
+ except KeyboardInterrupt:
131
+ notice("Cancelled.")
132
+ raise SystemExit(130)
133
+ except (
134
+ marona.MaronaApprovalRequired,
135
+ marona.MaronaPermissionRequired,
136
+ marona.MaronaServiceConnectionRequired,
137
+ ) as exc:
138
+ _error(
139
+ args,
140
+ "action_required",
141
+ f"{type(exc).__name__}: complete the required authorization in Marona Platform; no action was retried",
142
+ 4,
143
+ )
144
+ except marona.EdgeRuntimeError as exc:
145
+ _error(
146
+ args,
147
+ getattr(exc, "code", "runtime_error"),
148
+ f"Marona rejected the request (HTTP {exc.status_code or 'unknown'}). Check your key, model access, credits and permissions.",
149
+ 3,
150
+ )
151
+ except httpx.HTTPStatusError as exc:
152
+ _error(
153
+ args,
154
+ "http_error",
155
+ f"Service returned HTTP {exc.response.status_code}; no request was retried",
156
+ 3,
157
+ )
158
+ except (httpx.RequestError, TimeoutError, asyncio.TimeoutError):
159
+ _error(args, "connection_error", "Request failed or timed out; no request was retried", 3)
160
+ except KeyringError:
161
+ _error(
162
+ args,
163
+ "credential_store_error",
164
+ "OS credential store unavailable. Set MARONA_API_KEY for this process instead.",
165
+ 2,
166
+ )
167
+ except (ValueError, TypeError, OSError, ImportError, AttributeError) as exc:
168
+ _error(args, "configuration_error", str(exc), 2)
169
+ except Exception as exc: # noqa: BLE001 -- CLI boundary hides arbitrary user-module secrets.
170
+ _error(
171
+ args,
172
+ "execution_error",
173
+ f"Execution failed: {type(exc).__name__}. No action was retried.",
174
+ 1,
175
+ )
176
+
177
+
178
+ def _error(args, code, message, status):
179
+ for name in ("MARONA_API_KEY", "MARONA_DEVELOPER_TOKEN"):
180
+ if os.getenv(name):
181
+ message = message.replace(os.environ[name], "[redacted]")
182
+ if args.json:
183
+ notice(json.dumps({"error": {"code": code, "message": message}}))
184
+ else:
185
+ notice(f"Error: {message}")
186
+ raise SystemExit(status)