mycelium-cli 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. mycelium_cli-0.1.0/PKG-INFO +239 -0
  2. mycelium_cli-0.1.0/README.md +229 -0
  3. mycelium_cli-0.1.0/mycelium_cli/__init__.py +1 -0
  4. mycelium_cli-0.1.0/mycelium_cli/commands/__init__.py +1 -0
  5. mycelium_cli-0.1.0/mycelium_cli/commands/agent.py +70 -0
  6. mycelium_cli-0.1.0/mycelium_cli/commands/call.py +96 -0
  7. mycelium_cli-0.1.0/mycelium_cli/commands/check.py +21 -0
  8. mycelium_cli-0.1.0/mycelium_cli/commands/compile.py +59 -0
  9. mycelium_cli-0.1.0/mycelium_cli/commands/deploy.py +140 -0
  10. mycelium_cli-0.1.0/mycelium_cli/commands/discover.py +67 -0
  11. mycelium_cli-0.1.0/mycelium_cli/commands/doctor.py +106 -0
  12. mycelium_cli-0.1.0/mycelium_cli/commands/events.py +116 -0
  13. mycelium_cli-0.1.0/mycelium_cli/commands/fund.py +63 -0
  14. mycelium_cli-0.1.0/mycelium_cli/commands/init.py +188 -0
  15. mycelium_cli-0.1.0/mycelium_cli/commands/newwallet.py +61 -0
  16. mycelium_cli-0.1.0/mycelium_cli/commands/pay.py +83 -0
  17. mycelium_cli-0.1.0/mycelium_cli/commands/register.py +59 -0
  18. mycelium_cli-0.1.0/mycelium_cli/commands/resolve.py +54 -0
  19. mycelium_cli-0.1.0/mycelium_cli/commands/run.py +33 -0
  20. mycelium_cli-0.1.0/mycelium_cli/commands/status.py +127 -0
  21. mycelium_cli-0.1.0/mycelium_cli/commands/test.py +72 -0
  22. mycelium_cli-0.1.0/mycelium_cli/config.py +47 -0
  23. mycelium_cli-0.1.0/mycelium_cli/main.py +298 -0
  24. mycelium_cli-0.1.0/mycelium_cli.egg-info/PKG-INFO +239 -0
  25. mycelium_cli-0.1.0/mycelium_cli.egg-info/SOURCES.txt +31 -0
  26. mycelium_cli-0.1.0/mycelium_cli.egg-info/dependency_links.txt +1 -0
  27. mycelium_cli-0.1.0/mycelium_cli.egg-info/entry_points.txt +2 -0
  28. mycelium_cli-0.1.0/mycelium_cli.egg-info/requires.txt +3 -0
  29. mycelium_cli-0.1.0/mycelium_cli.egg-info/top_level.txt +1 -0
  30. mycelium_cli-0.1.0/pyproject.toml +21 -0
  31. mycelium_cli-0.1.0/setup.cfg +4 -0
  32. mycelium_cli-0.1.0/tests/test_agent.py +35 -0
  33. mycelium_cli-0.1.0/tests/test_cli.py +97 -0
@@ -0,0 +1,239 @@
1
+ Metadata-Version: 2.4
2
+ Name: mycelium-cli
3
+ Version: 0.1.0
4
+ Summary: Mycelium CLI — init, newwallet, compile, deploy, register
5
+ Requires-Python: >=3.10
6
+ Description-Content-Type: text/markdown
7
+ Requires-Dist: typer>=0.9
8
+ Requires-Dist: tomli-w>=1.0
9
+ Requires-Dist: stellar-sdk<15,>=14
10
+
11
+ # Mycelium CLI
12
+
13
+ The Mycelium CLI (`mycelium` command-line tool) is the developer command center for the Mycelium framework. It provides interactive scaffolding, local wallet/keypair management, contract checking and compilation, Soroban blockchain deployments, agent directory registration in the Hive registry, and execution runners for autonomous agent loops.
14
+
15
+ ---
16
+
17
+ ## 🚀 Installation & Setup
18
+
19
+ Install the CLI toolchain directly from PyPI (packaged within `mycelium-cli` or bundled inside the parent `mycelium-stellar` wrapper):
20
+
21
+ ```bash
22
+ pip install mycelium-cli
23
+ ```
24
+
25
+ Verify that the installation was successful by running:
26
+ ```bash
27
+ mycelium --help
28
+ ```
29
+
30
+ ---
31
+
32
+ ## ⚙️ Configuration Reference (`mycelium.toml`)
33
+
34
+ All Mycelium CLI operations run relative to a project root containing a `mycelium.toml` file. This configuration serves as the single source of truth for the local agent and its corresponding on-chain contract.
35
+
36
+ ```toml
37
+ [project]
38
+ name = "sentinel_agent"
39
+ version = "0.1.0"
40
+ author = "Developer"
41
+
42
+ [agent]
43
+ framework = "gemini" # Options: "langgraph" | "gemini" | "anthropic" | "custom"
44
+ model = "gemini-2.0-flash" # Target LLM model string
45
+ unique_name = "sentinel_alpha" # Alphanumeric agent registry name
46
+
47
+ [onchain]
48
+ source_contract = "contract.py" # Path to smart contract source file
49
+ target_wasm = "build/contract.wasm" # Output binary path
50
+ network = "testnet" # Default ledger target: "testnet" | "mainnet"
51
+ contract_id = "CC..." # Automatically populated after deployment
52
+ wallet_public_key = "GD..." # Automatically populated after deployment
53
+
54
+ [registry]
55
+ hive_registry_address = "CCQ..." # Hex contract address of the Hive Registry
56
+ service_endpoint = "https://agent.sentinel.mycelium.sh" # Agent API URL
57
+ capabilities = ["data-analysis", "stellar-arbitrage"] # List of capability tags
58
+ ```
59
+
60
+ ---
61
+
62
+ ## 🛠️ Complete CLI Command Reference
63
+
64
+ ### 1. `mycelium init`
65
+ Scaffolds a new Mycelium project from scratch. It launches an interactive setup wizard that prompts you for project properties.
66
+
67
+ * **Syntax**:
68
+ ```bash
69
+ mycelium init <project_name> [options]
70
+ ```
71
+ * **Interactive Wizard Options**:
72
+ - **AI Core Framework**: Select from `langgraph`, `gemini`, `anthropic`, or `custom`.
73
+ - **Target LLM Model**: Pick from recommended defaults or input a custom string.
74
+ - **Unique Name**: Choose a registry name (regex validated against `^[a-zA-Z0-9_]{3,30}$`).
75
+ * **Flags**:
76
+ - `--yes` / `-y`: Skip all interactive questions and initialize using standard default configurations.
77
+ - `--force` / `-f`: Overwrite the destination directory if it already exists.
78
+
79
+ ### 2. `mycelium newwallet`
80
+ Generates a new secure Stellar keypair (Ed25519) and saves it to `.mycelium/wallet.json`.
81
+
82
+ * **Syntax**:
83
+ ```bash
84
+ mycelium newwallet [options]
85
+ ```
86
+ * **Security Details**:
87
+ - The secret seed is encrypted at rest using PBKDF2-HMAC-SHA256 (600,000 iterations) + AES-256-GCM.
88
+ - Prompts securely for an encryption passphrase.
89
+ - Filesystem permissions on `.mycelium/wallet.json` are automatically restricted to `0600` (read/write by owner only).
90
+ * **Flags**:
91
+ - `--passphrase <text>`: Provide the encryption passphrase directly (convenient for automated environments).
92
+ - `--force`: Force generation, overwriting any existing wallet configuration.
93
+
94
+ ### 3. `mycelium compile`
95
+ Parses and compiles a Python-DSL contract file into a WebAssembly contract binary.
96
+
97
+ * **Syntax**:
98
+ ```bash
99
+ mycelium compile [source_file] [options]
100
+ ```
101
+ * **Flags**:
102
+ - `--output <path>` / `-o <path>`: Specify the output WASM file path (defaults to `build/contract.wasm`).
103
+ - `--optimize`: Enable maximum optimization passes (release profile, targeting size reduction).
104
+
105
+ ### 4. `mycelium check`
106
+ Performs static evaluation and type verification on a contract script without generating a WASM binary. Useful for checking syntax in IDEs, git pre-commit hooks, or CI pipelines.
107
+
108
+ * **Syntax**:
109
+ ```bash
110
+ mycelium check [source_file]
111
+ ```
112
+
113
+ ### 5. `mycelium deploy`
114
+ Deploys the compiled WASM binary directly to Stellar/Soroban.
115
+
116
+ * **Syntax**:
117
+ ```bash
118
+ mycelium deploy [options]
119
+ ```
120
+ * **Behaviors**:
121
+ - **Testnet**: Checks the balance. If the balance is zero, the CLI automatically requests funds from the Stellar Friendbot API, waits for ledger confirmation, and broadcasts the deployment transaction.
122
+ - **Mainnet**: Asserts the wallet has a minimum balance of `5 XLM` (to satisfy reserves). If insufficient, it halts with an error and displays the public key.
123
+ - On success, updates `contract_id` and `wallet_public_key` in `mycelium.toml`.
124
+ * **Flags**:
125
+ - `--network <name>`: Override the network target (`testnet` or `mainnet`).
126
+ - `--wasm <path>`: Override the WASM file path to deploy.
127
+
128
+ ### 6. `mycelium register`
129
+ Submits a signed transaction to the global Hive Registry mapping your agent's configuration parameters.
130
+
131
+ * **Syntax**:
132
+ ```bash
133
+ mycelium register [options]
134
+ ```
135
+ * **Details**:
136
+ - Packages the agent name, service endpoint, public address, and the SHA-256 hash of capability tags.
137
+ - Verifies that local keys match the owner keys if updating an existing registration.
138
+
139
+ ### 7. `mycelium status`
140
+ Displays the comprehensive deployment and configuration status of the active project in a single screen.
141
+
142
+ * **Syntax**:
143
+ ```bash
144
+ mycelium status
145
+ ```
146
+ * **Output Fields**:
147
+ - **Wallet Address**: G-address extracted from local wallet config.
148
+ - **Wallet Balance**: Balance retrieved from Horizon RPC.
149
+ - **Network**: Deployed target network passphrase identifier.
150
+ - **Contract Deployment**: Verification status of the contract ID on the ledger.
151
+ - **Registry Entry**: Name verification, registration state, reputation score, and API endpoint details.
152
+
153
+ ### 8. `mycelium fund`
154
+ Explicitly requests Friendbot funding for the agent's wallet. Used to top up testnet gas balances.
155
+
156
+ * **Syntax**:
157
+ ```bash
158
+ mycelium fund [options]
159
+ ```
160
+ * **Flags**:
161
+ - `--amount <number>`: Request a specific amount (if supported by network node limits).
162
+
163
+ ### 9. `mycelium call`
164
+ Invokes an on-chain contract function directly from your terminal.
165
+
166
+ * **Syntax**:
167
+ ```bash
168
+ mycelium call <function_name> [args...] [options]
169
+ ```
170
+ * **Details**:
171
+ - Automatically maps plain argument strings to the correct Soroban type based on the contract specification.
172
+ * **Flags**:
173
+ - `--read-only`: Execute as a simulate-only view invocation (free, does not require passphrase or signature).
174
+ - `--contract <id>`: Override the target contract ID.
175
+
176
+ ### 10. `mycelium resolve`
177
+ Queries the on-chain Hive Registry to resolve details of another agent by its name.
178
+
179
+ * **Syntax**:
180
+ ```bash
181
+ mycelium resolve <agent_name>
182
+ ```
183
+
184
+ ### 11. `mycelium pay`
185
+ Triggers an agent-to-agent XLM settlement payment. It resolves the destination agent's wallet address from the registry.
186
+
187
+ * **Syntax**:
188
+ ```bash
189
+ mycelium pay <recipient_name_or_address> <amount_xlm>
190
+ ```
191
+
192
+ ### 12. `mycelium events` / `mycelium logs`
193
+ Streams on-chain event topics emitted by the agent's smart contract.
194
+
195
+ * **Syntax**:
196
+ ```bash
197
+ mycelium events [options]
198
+ ```
199
+ * **Flags**:
200
+ - `--contract <id>`: Override the contract ID to monitor.
201
+ - `--start-ledger <number>`: Begin streaming historical events from a specific ledger sequence.
202
+
203
+ ### 13. `mycelium doctor`
204
+ Runs a suite of sanity checks to verify the state of your local toolchain:
205
+ 1. Asserts `stellar-cli` is present on your system path.
206
+ 2. Checks if local cargo/wasm targets are properly configured.
207
+ 3. Tests network connectivity and latency to Horizon and Soroban RPC nodes.
208
+ 4. Identifies version mismatches and prints corrective shell actions.
209
+
210
+ * **Syntax**:
211
+ ```bash
212
+ mycelium doctor
213
+ ```
214
+
215
+ ### 14. `mycelium run`
216
+ Spins up the agent's execution loop (`agent.py`) in your terminal, pre-loading context configurations, wallet files, and contract IDs from the project directory.
217
+
218
+ * **Syntax**:
219
+ ```bash
220
+ mycelium run [options]
221
+ ```
222
+ * **Flags**:
223
+ - `--steps <number>`: Limit the maximum number of steps the LLM loop is permitted to run.
224
+
225
+ ### 15. `mycelium test`
226
+ Performs a simulation dry-run of the agent loop. It intercepts all state-changing contract calls, executes them via simulation, logs estimated resource fees, and returns without signing or broadcasting transactions.
227
+
228
+ * **Syntax**:
229
+ ```bash
230
+ mycelium test
231
+ ```
232
+
233
+ ---
234
+
235
+ ## 🔐 Environment Variables
236
+
237
+ * `MYCELIUM_DECRYPT_KEY`: Set this env variable to bypass interactive wallet decryption password prompts. Essential for CI/CD and non-interactive workflows.
238
+ * `MYCELIUM_CONTRACT_ID`: Override default contract target.
239
+ * `STELLAR_NETWORK`: Overrides default network selection (`testnet` / `mainnet`).
@@ -0,0 +1,229 @@
1
+ # Mycelium CLI
2
+
3
+ The Mycelium CLI (`mycelium` command-line tool) is the developer command center for the Mycelium framework. It provides interactive scaffolding, local wallet/keypair management, contract checking and compilation, Soroban blockchain deployments, agent directory registration in the Hive registry, and execution runners for autonomous agent loops.
4
+
5
+ ---
6
+
7
+ ## 🚀 Installation & Setup
8
+
9
+ Install the CLI toolchain directly from PyPI (packaged within `mycelium-cli` or bundled inside the parent `mycelium-stellar` wrapper):
10
+
11
+ ```bash
12
+ pip install mycelium-cli
13
+ ```
14
+
15
+ Verify that the installation was successful by running:
16
+ ```bash
17
+ mycelium --help
18
+ ```
19
+
20
+ ---
21
+
22
+ ## ⚙️ Configuration Reference (`mycelium.toml`)
23
+
24
+ All Mycelium CLI operations run relative to a project root containing a `mycelium.toml` file. This configuration serves as the single source of truth for the local agent and its corresponding on-chain contract.
25
+
26
+ ```toml
27
+ [project]
28
+ name = "sentinel_agent"
29
+ version = "0.1.0"
30
+ author = "Developer"
31
+
32
+ [agent]
33
+ framework = "gemini" # Options: "langgraph" | "gemini" | "anthropic" | "custom"
34
+ model = "gemini-2.0-flash" # Target LLM model string
35
+ unique_name = "sentinel_alpha" # Alphanumeric agent registry name
36
+
37
+ [onchain]
38
+ source_contract = "contract.py" # Path to smart contract source file
39
+ target_wasm = "build/contract.wasm" # Output binary path
40
+ network = "testnet" # Default ledger target: "testnet" | "mainnet"
41
+ contract_id = "CC..." # Automatically populated after deployment
42
+ wallet_public_key = "GD..." # Automatically populated after deployment
43
+
44
+ [registry]
45
+ hive_registry_address = "CCQ..." # Hex contract address of the Hive Registry
46
+ service_endpoint = "https://agent.sentinel.mycelium.sh" # Agent API URL
47
+ capabilities = ["data-analysis", "stellar-arbitrage"] # List of capability tags
48
+ ```
49
+
50
+ ---
51
+
52
+ ## 🛠️ Complete CLI Command Reference
53
+
54
+ ### 1. `mycelium init`
55
+ Scaffolds a new Mycelium project from scratch. It launches an interactive setup wizard that prompts you for project properties.
56
+
57
+ * **Syntax**:
58
+ ```bash
59
+ mycelium init <project_name> [options]
60
+ ```
61
+ * **Interactive Wizard Options**:
62
+ - **AI Core Framework**: Select from `langgraph`, `gemini`, `anthropic`, or `custom`.
63
+ - **Target LLM Model**: Pick from recommended defaults or input a custom string.
64
+ - **Unique Name**: Choose a registry name (regex validated against `^[a-zA-Z0-9_]{3,30}$`).
65
+ * **Flags**:
66
+ - `--yes` / `-y`: Skip all interactive questions and initialize using standard default configurations.
67
+ - `--force` / `-f`: Overwrite the destination directory if it already exists.
68
+
69
+ ### 2. `mycelium newwallet`
70
+ Generates a new secure Stellar keypair (Ed25519) and saves it to `.mycelium/wallet.json`.
71
+
72
+ * **Syntax**:
73
+ ```bash
74
+ mycelium newwallet [options]
75
+ ```
76
+ * **Security Details**:
77
+ - The secret seed is encrypted at rest using PBKDF2-HMAC-SHA256 (600,000 iterations) + AES-256-GCM.
78
+ - Prompts securely for an encryption passphrase.
79
+ - Filesystem permissions on `.mycelium/wallet.json` are automatically restricted to `0600` (read/write by owner only).
80
+ * **Flags**:
81
+ - `--passphrase <text>`: Provide the encryption passphrase directly (convenient for automated environments).
82
+ - `--force`: Force generation, overwriting any existing wallet configuration.
83
+
84
+ ### 3. `mycelium compile`
85
+ Parses and compiles a Python-DSL contract file into a WebAssembly contract binary.
86
+
87
+ * **Syntax**:
88
+ ```bash
89
+ mycelium compile [source_file] [options]
90
+ ```
91
+ * **Flags**:
92
+ - `--output <path>` / `-o <path>`: Specify the output WASM file path (defaults to `build/contract.wasm`).
93
+ - `--optimize`: Enable maximum optimization passes (release profile, targeting size reduction).
94
+
95
+ ### 4. `mycelium check`
96
+ Performs static evaluation and type verification on a contract script without generating a WASM binary. Useful for checking syntax in IDEs, git pre-commit hooks, or CI pipelines.
97
+
98
+ * **Syntax**:
99
+ ```bash
100
+ mycelium check [source_file]
101
+ ```
102
+
103
+ ### 5. `mycelium deploy`
104
+ Deploys the compiled WASM binary directly to Stellar/Soroban.
105
+
106
+ * **Syntax**:
107
+ ```bash
108
+ mycelium deploy [options]
109
+ ```
110
+ * **Behaviors**:
111
+ - **Testnet**: Checks the balance. If the balance is zero, the CLI automatically requests funds from the Stellar Friendbot API, waits for ledger confirmation, and broadcasts the deployment transaction.
112
+ - **Mainnet**: Asserts the wallet has a minimum balance of `5 XLM` (to satisfy reserves). If insufficient, it halts with an error and displays the public key.
113
+ - On success, updates `contract_id` and `wallet_public_key` in `mycelium.toml`.
114
+ * **Flags**:
115
+ - `--network <name>`: Override the network target (`testnet` or `mainnet`).
116
+ - `--wasm <path>`: Override the WASM file path to deploy.
117
+
118
+ ### 6. `mycelium register`
119
+ Submits a signed transaction to the global Hive Registry mapping your agent's configuration parameters.
120
+
121
+ * **Syntax**:
122
+ ```bash
123
+ mycelium register [options]
124
+ ```
125
+ * **Details**:
126
+ - Packages the agent name, service endpoint, public address, and the SHA-256 hash of capability tags.
127
+ - Verifies that local keys match the owner keys if updating an existing registration.
128
+
129
+ ### 7. `mycelium status`
130
+ Displays the comprehensive deployment and configuration status of the active project in a single screen.
131
+
132
+ * **Syntax**:
133
+ ```bash
134
+ mycelium status
135
+ ```
136
+ * **Output Fields**:
137
+ - **Wallet Address**: G-address extracted from local wallet config.
138
+ - **Wallet Balance**: Balance retrieved from Horizon RPC.
139
+ - **Network**: Deployed target network passphrase identifier.
140
+ - **Contract Deployment**: Verification status of the contract ID on the ledger.
141
+ - **Registry Entry**: Name verification, registration state, reputation score, and API endpoint details.
142
+
143
+ ### 8. `mycelium fund`
144
+ Explicitly requests Friendbot funding for the agent's wallet. Used to top up testnet gas balances.
145
+
146
+ * **Syntax**:
147
+ ```bash
148
+ mycelium fund [options]
149
+ ```
150
+ * **Flags**:
151
+ - `--amount <number>`: Request a specific amount (if supported by network node limits).
152
+
153
+ ### 9. `mycelium call`
154
+ Invokes an on-chain contract function directly from your terminal.
155
+
156
+ * **Syntax**:
157
+ ```bash
158
+ mycelium call <function_name> [args...] [options]
159
+ ```
160
+ * **Details**:
161
+ - Automatically maps plain argument strings to the correct Soroban type based on the contract specification.
162
+ * **Flags**:
163
+ - `--read-only`: Execute as a simulate-only view invocation (free, does not require passphrase or signature).
164
+ - `--contract <id>`: Override the target contract ID.
165
+
166
+ ### 10. `mycelium resolve`
167
+ Queries the on-chain Hive Registry to resolve details of another agent by its name.
168
+
169
+ * **Syntax**:
170
+ ```bash
171
+ mycelium resolve <agent_name>
172
+ ```
173
+
174
+ ### 11. `mycelium pay`
175
+ Triggers an agent-to-agent XLM settlement payment. It resolves the destination agent's wallet address from the registry.
176
+
177
+ * **Syntax**:
178
+ ```bash
179
+ mycelium pay <recipient_name_or_address> <amount_xlm>
180
+ ```
181
+
182
+ ### 12. `mycelium events` / `mycelium logs`
183
+ Streams on-chain event topics emitted by the agent's smart contract.
184
+
185
+ * **Syntax**:
186
+ ```bash
187
+ mycelium events [options]
188
+ ```
189
+ * **Flags**:
190
+ - `--contract <id>`: Override the contract ID to monitor.
191
+ - `--start-ledger <number>`: Begin streaming historical events from a specific ledger sequence.
192
+
193
+ ### 13. `mycelium doctor`
194
+ Runs a suite of sanity checks to verify the state of your local toolchain:
195
+ 1. Asserts `stellar-cli` is present on your system path.
196
+ 2. Checks if local cargo/wasm targets are properly configured.
197
+ 3. Tests network connectivity and latency to Horizon and Soroban RPC nodes.
198
+ 4. Identifies version mismatches and prints corrective shell actions.
199
+
200
+ * **Syntax**:
201
+ ```bash
202
+ mycelium doctor
203
+ ```
204
+
205
+ ### 14. `mycelium run`
206
+ Spins up the agent's execution loop (`agent.py`) in your terminal, pre-loading context configurations, wallet files, and contract IDs from the project directory.
207
+
208
+ * **Syntax**:
209
+ ```bash
210
+ mycelium run [options]
211
+ ```
212
+ * **Flags**:
213
+ - `--steps <number>`: Limit the maximum number of steps the LLM loop is permitted to run.
214
+
215
+ ### 15. `mycelium test`
216
+ Performs a simulation dry-run of the agent loop. It intercepts all state-changing contract calls, executes them via simulation, logs estimated resource fees, and returns without signing or broadcasting transactions.
217
+
218
+ * **Syntax**:
219
+ ```bash
220
+ mycelium test
221
+ ```
222
+
223
+ ---
224
+
225
+ ## 🔐 Environment Variables
226
+
227
+ * `MYCELIUM_DECRYPT_KEY`: Set this env variable to bypass interactive wallet decryption password prompts. Essential for CI/CD and non-interactive workflows.
228
+ * `MYCELIUM_CONTRACT_ID`: Override default contract target.
229
+ * `STELLAR_NETWORK`: Overrides default network selection (`testnet` / `mainnet`).
@@ -0,0 +1 @@
1
+ # Mycelium CLI Package
@@ -0,0 +1 @@
1
+ # CLI subcommands package
@@ -0,0 +1,70 @@
1
+ """
2
+ `mycelium agent` — run a Mycelium agent runtime script.
3
+
4
+ Loads the developer's agent script (e.g. the scaffolded `agent.py`) as a module
5
+ and runs it, binding the on-chain contract id into the environment as
6
+ `MYCELIUM_CONTRACT_ID` so the script (and any `AgentContext` it builds) can read
7
+ it. If the script exposes a `main()` callable it is invoked; otherwise importing
8
+ the module is treated as running it (top-level code executes on import).
9
+ """
10
+
11
+ import importlib.util
12
+ import os
13
+ import sys
14
+
15
+
16
+ def _load_dotenv(path: str) -> None:
17
+ """Minimal .env loader: sets KEY=VALUE pairs into os.environ if not already set."""
18
+ if not os.path.exists(path):
19
+ return
20
+ with open(path, "r") as f:
21
+ for line in f:
22
+ line = line.strip()
23
+ if not line or line.startswith("#") or "=" not in line:
24
+ continue
25
+ key, _, value = line.partition("=")
26
+ key = key.strip()
27
+ if key.startswith("export "):
28
+ key = key[len("export "):].strip()
29
+ value = value.strip()
30
+ # Strip a single pair of matching surrounding quotes.
31
+ if len(value) >= 2 and value[0] == value[-1] and value[0] in ("'", '"'):
32
+ value = value[1:-1]
33
+ os.environ.setdefault(key, value)
34
+
35
+
36
+ def run_agent(file_path: str, contract_id: str):
37
+ if not os.path.exists(file_path):
38
+ print(f"Error: agent runtime file {file_path} not found.")
39
+ sys.exit(1)
40
+
41
+ print(f"[Agent] Loading runtime script: {file_path}")
42
+ print(f"[Agent] Bound to on-chain contract: {contract_id}")
43
+
44
+ # Expose the bound contract id to the agent script and any SDK it constructs.
45
+ os.environ["MYCELIUM_CONTRACT_ID"] = contract_id
46
+
47
+ # Load a sibling .env (written by `mycelium init` with the provider API key)
48
+ # so the agent can authenticate without the key being hard-coded in source.
49
+ _load_dotenv(os.path.join(os.path.dirname(os.path.abspath(file_path)), ".env"))
50
+
51
+ module_name = os.path.splitext(os.path.basename(file_path))[0]
52
+ spec = importlib.util.spec_from_file_location(module_name, file_path)
53
+ if spec is None or spec.loader is None:
54
+ print(f"Error: could not load {file_path} as a Python module.")
55
+ sys.exit(1)
56
+ module = importlib.util.module_from_spec(spec)
57
+ # Make the script's own directory importable (so it can import sibling files).
58
+ sys.path.insert(0, os.path.dirname(os.path.abspath(file_path)) or ".")
59
+
60
+ try:
61
+ spec.loader.exec_module(module)
62
+ if hasattr(module, "main") and callable(module.main):
63
+ print("[Agent] Running main()...")
64
+ module.main()
65
+ print("[Agent] Runtime finished.")
66
+ except KeyboardInterrupt:
67
+ print("\n[Agent] Execution halted by user request.")
68
+ except Exception as e:
69
+ print(f"❌ Agent runtime error: {e}")
70
+ sys.exit(1)
@@ -0,0 +1,96 @@
1
+ """
2
+ `mycelium call <fn> [args...]` — invoke a deployed contract function from the CLI.
3
+
4
+ By default the call is read-only (simulated, no signature, no fee) — perfect for
5
+ views and getters. Pass `--send` to sign and submit a state-changing transaction,
6
+ which loads the project wallet and prompts for its passphrase.
7
+
8
+ Argument widths are marshalled automatically from the contract spec (fetched
9
+ once from RPC), so `mycelium call add 40` "just works" — no U64() wrapper needed.
10
+ String tokens are interpreted as ints/bools/addresses where unambiguous and left
11
+ as strings otherwise.
12
+ """
13
+
14
+ import sys
15
+ from typing import Any, List, Optional
16
+
17
+ from mycelium_cli.config import get_value
18
+
19
+ DEFAULT_WALLET_PATH = ".mycelium/wallet.json"
20
+
21
+
22
+ def _parse_arg(token: str) -> Any:
23
+ """Best-effort coerce a CLI string token into a Python value.
24
+
25
+ Integers and bools are recognised; addresses/symbols/strings are left as
26
+ strings (AgentContext + the contract spec marshal them to the right SCVal).
27
+ Prefix a value with `s:` to force it to stay a string (e.g. `s:42`).
28
+ """
29
+ if token.startswith("s:"):
30
+ return token[2:]
31
+ low = token.lower()
32
+ if low == "true":
33
+ return True
34
+ if low == "false":
35
+ return False
36
+ try:
37
+ return int(token)
38
+ except ValueError:
39
+ return token
40
+
41
+
42
+ def run_call(
43
+ function_name: str,
44
+ args: Optional[List[str]] = None,
45
+ contract: Optional[str] = None,
46
+ network: Optional[str] = None,
47
+ send: bool = False,
48
+ wallet_path: str = DEFAULT_WALLET_PATH,
49
+ passphrase: Optional[str] = None,
50
+ ) -> Any:
51
+ from mycelium_sdk import AgentContext
52
+
53
+ network = network or get_value("onchain", "network", "testnet")
54
+ contract = contract or get_value("onchain", "contract_id")
55
+ if not contract:
56
+ print(
57
+ "Error: no contract id. Pass --contract C..., or run inside a project "
58
+ "whose mycelium.toml has [onchain].contract_id (after `mycelium deploy`)."
59
+ )
60
+ sys.exit(1)
61
+
62
+ parsed = [_parse_arg(a) for a in (args or [])]
63
+
64
+ if send:
65
+ import os
66
+
67
+ if not os.path.exists(wallet_path):
68
+ print(f"Error: wallet {wallet_path} not found. Run `mycelium newwallet` first.")
69
+ sys.exit(1)
70
+ context = AgentContext(
71
+ keypair_path=wallet_path, network_type=network, passphrase=passphrase
72
+ )
73
+ else:
74
+ context = AgentContext.read_only(network_type=network)
75
+
76
+ print(
77
+ f"[call] {function_name}({', '.join(map(repr, parsed))}) on {contract} "
78
+ f"({'send' if send else 'read-only'})..."
79
+ )
80
+ try:
81
+ result = context.call_contract(
82
+ contract, function_name, parsed, read_only=not send
83
+ )
84
+ except Exception as e:
85
+ print(f"❌ Call failed: {e}")
86
+ sys.exit(1)
87
+
88
+ if send:
89
+ # call_contract returns a TxResult for state-changing calls.
90
+ tx_hash = getattr(result, "hash", None)
91
+ ret = getattr(result, "return_value", result)
92
+ print(f"✓ Submitted. Tx: {tx_hash}")
93
+ print(f" return: {ret}")
94
+ else:
95
+ print(f"✓ {result}")
96
+ return result
@@ -0,0 +1,21 @@
1
+ import os
2
+ import sys
3
+ from mycelium_compiler.parser import parse_source
4
+ from mycelium_compiler.validator import validate_ast
5
+
6
+ def run_check(file_path: str):
7
+ print(f"Checking AST rules and type constraints for: {file_path}")
8
+ if not os.path.exists(file_path):
9
+ print(f"Error: File {file_path} not found.")
10
+ sys.exit(1)
11
+
12
+ with open(file_path, "r") as f:
13
+ source_code = f.read()
14
+
15
+ try:
16
+ visitor = parse_source(source_code)
17
+ validate_ast(visitor)
18
+ print("✓ All validation checks passed successfully!")
19
+ except Exception as e:
20
+ print(f"❌ Validation failed: {e}")
21
+ sys.exit(1)