lmnr-cli 0.1.0-alpha.0

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.
package/LICENSE ADDED
@@ -0,0 +1,75 @@
1
+
2
+
3
+ Apache License
4
+ Version 2.0, January 2004
5
+ http://www.apache.org/licenses/
6
+
7
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
+
9
+ 1. Definitions.
10
+
11
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
16
+
17
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
18
+
19
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
20
+
21
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
22
+
23
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
24
+
25
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
26
+
27
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
28
+
29
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
30
+
31
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
32
+
33
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
34
+
35
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
36
+
37
+ You must give any other recipients of the Work or Derivative Works a copy of this License; and
38
+ You must cause any modified files to carry prominent notices stating that You changed the files; and
39
+ You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
40
+ If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
41
+
42
+ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
43
+
44
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
45
+
46
+ 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
47
+
48
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
49
+
50
+ 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
51
+
52
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
53
+
54
+ END OF TERMS AND CONDITIONS
55
+
56
+
57
+ APPENDIX: How to apply the Apache License to your work
58
+
59
+ Include a copy of the Apache License, typically in a file called LICENSE, in your work, and consider also including a NOTICE file that references the License.
60
+
61
+ To apply the Apache License to specific files in your work, attach the following boilerplate declaration, replacing the fields enclosed by brackets "[]" with your own identifying information. (Don't include the brackets!) Enclose the text in the appropriate comment syntax for the file format. We also recommend that you include a file or class name and description of purpose on the same "printed page" as the copyright notice for easier identification within third-party archives.
62
+
63
+ Copyright 2024 LMNR AI, Inc.
64
+
65
+ Licensed under the Apache License, Version 2.0 (the "License");
66
+ you may not use this file except in compliance with the License.
67
+ You may obtain a copy of the License at
68
+
69
+ http://www.apache.org/licenses/LICENSE-2.0
70
+
71
+ Unless required by applicable law or agreed to in writing, software
72
+ distributed under the License is distributed on an "AS IS" BASIS,
73
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
74
+ See the License for the specific language governing permissions and
75
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,409 @@
1
+ # lmnr-cli
2
+
3
+ Language-agnostic CLI for Laminar AI rollout debugging.
4
+
5
+ ## Overview
6
+
7
+ The Laminar CLI is a pure orchestrator that coordinates rollout debugging sessions between your code and the Laminar backend. It is designed to be completely language-agnostic, delegating language-specific execution to worker processes.
8
+
9
+ ## Installation
10
+
11
+ ```bash
12
+ # Run directly with npx
13
+ npx lmnr-cli@latest dev agent.ts
14
+
15
+ # Or install globally
16
+ npm install -g lmnr-cli
17
+ lmnr-cli dev agent.ts
18
+ ```
19
+
20
+ ## Usage
21
+
22
+ ```bash
23
+ lmnr-cli dev [file] [options]
24
+ # OR
25
+ lmnr-cli dev -m <python-module> [options]
26
+ ```
27
+
28
+ ### Options
29
+
30
+ - `-m, --python-module <module>` - Python module path (e.g., `src.myfile`)
31
+ - `--function <name>` - Specific function to serve (if multiple rollout functions found)
32
+ - `--project-api-key <key>` - Project API key (or set `LMNR_PROJECT_API_KEY` env variable)
33
+ - `--base-url <url>` - Base URL for the Laminar API (default: https://api.lmnr.ai)
34
+ - `--port <port>` - Port for the Laminar API (default: 443)
35
+ - `--grpc-port <port>` - Port for the Laminar gRPC backend (default: 8443)
36
+ - `--frontend-port <port>` - Port for the Laminar frontend (default: 5667)
37
+ - `--external-packages <packages...>` - [ADVANCED] Packages to pass as external to esbuild
38
+ - `--dynamic-imports-to-skip <modules...>` - [ADVANCED] Dynamic imports to skip
39
+ - `--command <command>` - [ADVANCED] Custom worker command (e.g., `python3`, `node`)
40
+ - `--command-args <args...>` - [ADVANCED] Arguments for the custom command
41
+
42
+ ### Examples
43
+
44
+ ```bash
45
+ # TypeScript
46
+ npx lmnr-cli@latest dev agent.ts
47
+
48
+ # JavaScript (extracts parameter names at runtime)
49
+ npx lmnr-cli@latest dev agent.js
50
+
51
+ # Python - Script mode
52
+ npx lmnr-cli@latest dev agent.py
53
+
54
+ # Python - Module mode
55
+ npx lmnr-cli@latest dev -m src.agent
56
+ ```
57
+
58
+ ## Architecture
59
+
60
+ The CLI orchestrates three components:
61
+
62
+ 1. **SSE Client**: Connects to Laminar backend and receives run events
63
+ 2. **Cache Server**: Local HTTP server (port 35667) that provides cached spans to workers
64
+ 3. **Worker Process**: Language-specific subprocess that executes your code
65
+
66
+ ```
67
+ ┌─────────────────┐
68
+ │ Laminar API │
69
+ └────────┬────────┘
70
+ │ SSE
71
+
72
+ ┌────────▼────────┐ ┌──────────────┐
73
+ │ CLI Process │◄────►│ Cache Server │
74
+ │ (Orchestrator) │ │ (HTTP:35667)│
75
+ └────────┬────────┘ └──────▲───────┘
76
+ │ │
77
+ │ spawn │ HTTP
78
+ │ │
79
+ ┌────────▼────────┐ ┌──────┴───────┐
80
+ │ Worker Process │─────►│ Your Code │
81
+ │ (TS/Python/etc) │ │ (agent.ts) │
82
+ └─────────────────┘ └──────────────┘
83
+ ```
84
+
85
+ ## Worker Protocol
86
+
87
+ The CLI communicates with workers using a simple JSON protocol over stdin/stdout.
88
+
89
+ ### Input (via stdin)
90
+
91
+ The CLI sends a single JSON line to the worker's stdin containing the configuration:
92
+
93
+ ```typescript
94
+ {
95
+ filePath: string; // Path to the file to execute
96
+ functionName?: string; // Specific function to run
97
+ args: Record<string, any> | any[]; // Arguments for the function
98
+ env: Record<string, string>; // Environment variables
99
+ cacheServerPort: number; // Port of the cache server
100
+ baseUrl: string; // Laminar API base URL
101
+ projectApiKey?: string; // Project API key
102
+ httpPort: number; // HTTP port for Laminar API
103
+ grpcPort: number; // gRPC port for Laminar API
104
+ externalPackages?: string[]; // External packages (TS-specific)
105
+ dynamicImportsToSkip?: string[]; // Dynamic imports to skip (TS-specific)
106
+ }
107
+ ```
108
+
109
+ ### Output (via stdout)
110
+
111
+ Workers send messages prefixed with `__LMNR_WORKER__:` to stdout:
112
+
113
+ #### Log Message
114
+ ```typescript
115
+ {
116
+ type: 'log';
117
+ level: 'info' | 'debug' | 'error' | 'warn';
118
+ message: string;
119
+ }
120
+ ```
121
+
122
+ #### Result Message
123
+ ```typescript
124
+ {
125
+ type: 'result';
126
+ data: any; // Function return value
127
+ }
128
+ ```
129
+
130
+ #### Error Message
131
+ ```typescript
132
+ {
133
+ type: 'error';
134
+ error: string; // Error message
135
+ stack?: string; // Stack trace
136
+ }
137
+ ```
138
+
139
+ ### User Output
140
+
141
+ Any stdout without the `__LMNR_WORKER__:` prefix is considered user output (e.g., `console.log()`) and passed through transparently.
142
+
143
+ ### Environment Variables
144
+
145
+ The CLI sets these environment variables for the worker:
146
+
147
+ - `LMNR_ROLLOUT_SESSION_ID`: Session ID for this rollout run
148
+ - `LMNR_ROLLOUT_STATE_SERVER_ADDRESS`: Cache server URL (http://localhost:35667)
149
+
150
+ ### Cache Server API
151
+
152
+ Workers can query the cache server for cached spans:
153
+
154
+ **Endpoint**: `POST /cached`
155
+
156
+ **Request**:
157
+ ```json
158
+ {
159
+ "path": "string", // Span path
160
+ "index": number // Span index
161
+ }
162
+ ```
163
+
164
+ **Response**:
165
+ ```json
166
+ {
167
+ "span": {
168
+ "name": "string",
169
+ "input": "string", // JSON string
170
+ "output": "string", // JSON string
171
+ "attributes": {} // Parsed attributes
172
+ },
173
+ "pathToCount": {
174
+ "path1": 5,
175
+ "path2": 3
176
+ },
177
+ "overrides": {
178
+ "spanName": {
179
+ "system": "string or array",
180
+ "tools": [{
181
+ "name": "string",
182
+ "description": "string",
183
+ "parameters": {}
184
+ }]
185
+ }
186
+ }
187
+ }
188
+ ```
189
+
190
+ ## Implementing a Worker
191
+
192
+ To support a new language, implement a worker that:
193
+
194
+ 1. Reads JSON configuration from stdin
195
+ 2. Sets environment variables from `config.env`
196
+ 3. Loads and executes the specified function
197
+ 4. Initializes your SDK's tracing (reads `LMNR_ROLLOUT_STATE_SERVER_ADDRESS`)
198
+ 5. Sends protocol messages to stdout (prefixed with `__LMNR_WORKER__:`)
199
+ 6. Exits with code 0 on success, non-zero on failure
200
+
201
+ ### Example: TypeScript Worker
202
+
203
+ The TypeScript worker is included in `@lmnr-ai/lmnr`:
204
+
205
+ ```typescript
206
+ // Read config from stdin
207
+ const config = JSON.parse(await readStdin());
208
+
209
+ // Set environment variables
210
+ for (const [key, value] of Object.entries(config.env)) {
211
+ process.env[key] = value;
212
+ }
213
+
214
+ // Initialize SDK
215
+ Laminar.initialize({
216
+ baseUrl: config.baseUrl,
217
+ projectApiKey: config.projectApiKey,
218
+ // ...
219
+ });
220
+
221
+ // Load and execute function
222
+ const module = require(config.filePath);
223
+ const result = await module[config.functionName](...config.args);
224
+
225
+ // Send result
226
+ sendMessage({ type: 'result', data: result });
227
+
228
+ // Exit successfully
229
+ process.exit(0);
230
+ ```
231
+
232
+ ### Example: Python Worker (Future)
233
+
234
+ ```python
235
+ # python -m lmnr.cli.worker
236
+
237
+ import json
238
+ import sys
239
+ import os
240
+
241
+ # Read config from stdin
242
+ config = json.loads(sys.stdin.readline())
243
+
244
+ # Set environment variables
245
+ for key, value in config['env'].items():
246
+ os.environ[key] = value
247
+
248
+ # Initialize SDK
249
+ import lmnr
250
+ lmnr.initialize(
251
+ base_url=config['baseUrl'],
252
+ project_api_key=config['projectApiKey'],
253
+ )
254
+
255
+ # Load and execute function
256
+ module = __import__(config['filePath'])
257
+ result = getattr(module, config['functionName'])(*config['args'])
258
+
259
+ # Send result
260
+ send_message({'type': 'result', 'data': result})
261
+
262
+ # Exit successfully
263
+ sys.exit(0)
264
+ ```
265
+
266
+ ## Default Worker Resolution
267
+
268
+ The CLI automatically resolves workers based on file extension:
269
+
270
+ | Extension | Worker Command |
271
+ |-----------|----------------|
272
+ | `.ts`, `.tsx` | `node @lmnr-ai/lmnr/dist/cli/worker.cjs` |
273
+ | `.js`, `.mjs`, `.cjs` | `node @lmnr-ai/lmnr/dist/cli/worker.cjs` |
274
+ | `.py` | `python3 -m lmnr.cli.worker` |
275
+
276
+ Custom workers can be specified with `--command` and `--command-args`.
277
+
278
+ ## Python Language Support
279
+
280
+ ### Metadata Discovery
281
+
282
+ The CLI needs to discover function metadata (name and parameters) to provide a rich UI experience. For Python files, this is done by calling the `lmnr` Python package.
283
+
284
+ #### Required Command Interface
285
+
286
+ The Python `lmnr` package must implement the following CLI command:
287
+
288
+ ```bash
289
+ lmnr discover --file <filepath> [--function <name>]
290
+ # OR
291
+ lmnr discover --module <module> [--function <name>]
292
+ ```
293
+
294
+ **Arguments:**
295
+
296
+ - `--file <filepath>`: Path to the Python file containing rollout functions (script mode)
297
+ - `--module <module>`: Python module path like `src.myfile` (module mode)
298
+ - `--function <name>`: (Optional) Specific function name to discover. If omitted, discover all.
299
+
300
+ **Note:** Exactly one of `--file` or `--module` must be provided.
301
+
302
+ **Output Format (JSON to stdout):**
303
+
304
+ ```json
305
+ {
306
+ "name": "my_agent",
307
+ "params": [
308
+ {
309
+ "name": "query",
310
+ "type": "string"
311
+ },
312
+ {
313
+ "name": "max_tokens",
314
+ "type": "number"
315
+ }
316
+ ]
317
+ }
318
+ ```
319
+
320
+ **Exit Codes:**
321
+
322
+ - `0`: Success
323
+ - Non-zero: Error (stderr contains error message)
324
+
325
+ #### Python Execution Modes
326
+
327
+ Python code can be executed in two modes, affecting how imports work:
328
+
329
+ **Script Mode (default):**
330
+
331
+ ```bash
332
+ npx lmnr-cli dev src/myfile.py
333
+ # Internally executes as: python src/myfile.py
334
+ # Discovery uses: lmnr discover --file src/myfile.py
335
+ ```
336
+
337
+ - Works with relative imports: `from .utils import helper`
338
+ - File is executed as a script
339
+ - Best for standalone files and simple packages
340
+
341
+ **Module Mode:**
342
+
343
+ ```bash
344
+ npx lmnr-cli dev -m src.myfile
345
+ # Internally executes as: python -m src.myfile
346
+ # Discovery uses: lmnr discover --module src.myfile
347
+ ```
348
+
349
+ - Requires absolute imports: `from src.utils import helper`
350
+ - Module is executed via Python's `-m` flag
351
+ - Best for packages with complex import structures
352
+ - Requires proper `__init__.py` files in package directories
353
+
354
+ **Examples:**
355
+
356
+ ```bash
357
+ # Script mode - use file path with relative imports
358
+ npx lmnr-cli dev agents/customer_support.py
359
+
360
+ # Module mode - use module syntax with absolute imports
361
+ npx lmnr-cli dev -m agents.customer_support
362
+
363
+ # Specify a particular function
364
+ npx lmnr-cli dev -m agents.customer_support --function run_agent
365
+ ```
366
+
367
+ ### Python Worker Requirements
368
+
369
+ The Python `lmnr` package must implement a worker that executes rollout functions:
370
+
371
+ ```bash
372
+ python -m lmnr.cli.worker
373
+ ```
374
+
375
+ The worker should:
376
+
377
+ 1. Read JSON configuration from stdin containing either `filePath` (script mode) or `modulePath` (module mode)
378
+ 2. Set environment variables from config
379
+ 3. Initialize the `lmnr` SDK
380
+ 4. Load and execute the specified function based on the mode
381
+ 5. Send protocol messages to stdout (see [Worker Protocol](#worker-protocol))
382
+ 6. Exit with appropriate code
383
+
384
+ **Worker Configuration:**
385
+
386
+ The CLI will pass either:
387
+ - `filePath`: Path to Python file (script mode)
388
+ - `modulePath`: Python module path (module mode)
389
+
390
+ The worker must detect which field is present and execute accordingly.
391
+
392
+ See the [Worker Protocol](#worker-protocol) section for detailed communication protocol.
393
+
394
+ ## Development
395
+
396
+ ```bash
397
+ # Install dependencies
398
+ pnpm install
399
+
400
+ # Build
401
+ pnpm build
402
+
403
+ # Run locally
404
+ node dist/index.cjs dev examples/agent.ts
405
+ ```
406
+
407
+ ## License
408
+
409
+ Apache-2.0