@nylorun/cli 0.0.0-bootstrap → 0.1.1-beta

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/CHANGELOG.md ADDED
@@ -0,0 +1,24 @@
1
+ # @nylorun/cli
2
+
3
+ ## 0.1.1-beta
4
+
5
+ ### Patch Changes
6
+
7
+ - 2898d02: Extract shared definitions and contracts into core and local orchestration into
8
+ CLI. Harness becomes execution-only; the SDK no longer installs the engine and
9
+ Runtime no longer depends on the SDK. Author applications through agents and
10
+ install cli for the unchanged nylorun commands. See the package architecture and
11
+ migration guide. Cloud installs published packages from npm independently.
12
+ - Pin agents to the tested release.
13
+ - Pin runtime to the tested release.
14
+ - Updated dependencies [41e613c]
15
+ - Updated dependencies [2898d02]
16
+ - Updated dependencies
17
+ - Updated dependencies
18
+ - Updated dependencies
19
+ - @nylorun/agents@0.2.0-beta
20
+ - @nylorun/runtime@0.6.0-beta
21
+
22
+ ## 0.1.0-beta.1
23
+
24
+ Initial package extraction.
package/LICENSE ADDED
@@ -0,0 +1,192 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ Copyright 2026 Nylo
181
+
182
+ Licensed under the Apache License, Version 2.0 (the "License");
183
+ you may not use this file except in compliance with the License.
184
+ You may obtain a copy of the License at
185
+
186
+ http://www.apache.org/licenses/LICENSE-2.0
187
+
188
+ Unless required by applicable law or agreed to in writing, software
189
+ distributed under the License is distributed on an "AS IS" BASIS,
190
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
191
+ See the License for the specific language governing permissions and
192
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,26 @@
1
+ # @nylorun/cli
2
+
3
+ The local `nylorun` executable. Requires Node 24+.
4
+
5
+ ```sh
6
+ nylorun configure
7
+ nylorun dev
8
+ nylorun dev --no-studio
9
+ nylorun start
10
+ nylorun studio --runtime-url http://127.0.0.1:8787
11
+ ```
12
+
13
+ The CLI launches `@nylorun/runtime/server` in a child process, registers the
14
+ project's exported agents with the SDK, connects scoped customer executors and
15
+ optionally opens a project-installed `@nylorun/studio`. Runtime and executor
16
+ credentials remain separate. Configuration lives in the existing project files;
17
+ the SQLite database defaults to `.nylorun/runtime.sqlite`.
18
+
19
+ `dev` loads `agents/index.ts` using project-installed `tsx` and watches changes.
20
+ `start [entry]` defaults to `dist/agents/index.js` without Studio or watching.
21
+ Studio and `tsx` are optional development dependencies; the CLI is a production
22
+ dependency when the application's `start` script uses it.
23
+
24
+ Reusable provider configuration is imported from `@nylorun/runtime/configuration`;
25
+ interactive prompts and process supervision belong here. Neither runtime nor
26
+ harness depends on this package. See [package architecture](../docs/design/package-architecture.md).
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,103 @@
1
+ #!/usr/bin/env node
2
+ import { join } from "node:path";
3
+ import { pathToFileURL } from "node:url";
4
+ import { createRequire } from "node:module";
5
+ import { ConfigurationCancelled, configureProvider, } from "./model/configure.js";
6
+ import { loadProjectEnvironment } from "./environment.js";
7
+ import { develop } from "./dev.js";
8
+ const usage = `nylorun <configure|dev|start|studio>
9
+ dev [--no-studio] [--no-open]
10
+ start [entry]
11
+ configure
12
+ studio --runtime-url <http(s)-url> [--port <n>] [--no-open]`;
13
+ async function startStudio(agentServerUrl, open, port) {
14
+ let entry;
15
+ try {
16
+ entry = createRequire(join(process.cwd(), "package.json")).resolve("@nylorun/studio");
17
+ }
18
+ catch {
19
+ throw new Error("Install @nylorun/studio to use the Studio dashboard.");
20
+ }
21
+ const studio = await import(pathToFileURL(entry).href);
22
+ return studio.startStudio({
23
+ runtimeUrl: agentServerUrl,
24
+ serverKey: process.env.NYLORUN_SERVER_KEY ??
25
+ (await (await import("./project-runner.js")).localCredentials())
26
+ .serverKey,
27
+ open,
28
+ ...(port === undefined ? {} : { port }),
29
+ });
30
+ }
31
+ function parsePort(value) {
32
+ if (value === undefined)
33
+ return undefined;
34
+ const port = Number(value);
35
+ if (!Number.isInteger(port) || port < 1 || port > 65535)
36
+ throw new Error("--port must be an integer between 1 and 65535.");
37
+ return port;
38
+ }
39
+ async function main() {
40
+ const [command, ...args] = process.argv.slice(2);
41
+ if (!command || command === "--help" || command === "-h")
42
+ return void console.log(usage);
43
+ if (["configure", "dev", "start"].includes(command))
44
+ loadProjectEnvironment();
45
+ if (command === "start") {
46
+ if (args.length > 1 || args[0]?.startsWith("--"))
47
+ throw new Error(usage);
48
+ await (await import("./launcher.js")).start(args[0]);
49
+ return;
50
+ }
51
+ if (command === "dev") {
52
+ process.exitCode = await develop(args);
53
+ return;
54
+ }
55
+ if (command === "configure") {
56
+ if (args.length)
57
+ throw new Error(usage);
58
+ const controller = new AbortController();
59
+ const cancel = (signal) => controller.abort(new ConfigurationCancelled(signal));
60
+ process.once("SIGINT", () => cancel("SIGINT"));
61
+ process.once("SIGTERM", () => cancel("SIGTERM"));
62
+ await configureProvider({ signal: controller.signal });
63
+ return;
64
+ }
65
+ if (command !== "studio")
66
+ throw new Error(usage);
67
+ let agentUrl;
68
+ let port;
69
+ let open = true;
70
+ for (let index = 0; index < args.length; index += 1) {
71
+ const arg = args[index];
72
+ if (arg === "--runtime-url") {
73
+ if (agentUrl !== undefined)
74
+ throw new Error("--runtime-url may only be supplied once.");
75
+ agentUrl = args[++index];
76
+ if (!agentUrl || agentUrl.startsWith("--"))
77
+ throw new Error("--runtime-url requires a value.");
78
+ }
79
+ else if (arg === "--port") {
80
+ if (port !== undefined)
81
+ throw new Error("--port may only be supplied once.");
82
+ port = parsePort(args[++index]);
83
+ }
84
+ else if (arg === "--no-open" && open)
85
+ open = false;
86
+ else
87
+ throw new Error(usage);
88
+ }
89
+ if (!agentUrl)
90
+ throw new Error("--runtime-url is required.");
91
+ const dashboard = await startStudio(agentUrl, open, port);
92
+ console.log(`Studio on ${dashboard.address}`);
93
+ await new Promise((resolve, reject) => {
94
+ const close = () => void dashboard.close().then(resolve, reject);
95
+ process.once("SIGINT", close);
96
+ process.once("SIGTERM", close);
97
+ });
98
+ }
99
+ void main().catch((error) => {
100
+ console.error(error instanceof Error ? error.message : String(error));
101
+ process.exitCode =
102
+ error instanceof ConfigurationCancelled ? error.exitCode : 1;
103
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,5 @@
1
+ import { runProject } from "./project-runner.js";
2
+ await runProject("agents/index.ts", {
3
+ studio: !process.argv.includes("--no-studio"),
4
+ open: !process.argv.includes("--no-open"),
5
+ });
package/dist/dev.d.ts ADDED
@@ -0,0 +1 @@
1
+ export declare function develop(args: readonly string[]): Promise<number>;
package/dist/dev.js ADDED
@@ -0,0 +1,60 @@
1
+ import { spawn } from "node:child_process";
2
+ import { createRequire } from "node:module";
3
+ import { join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ export async function develop(args) {
6
+ if (new Set(args).size !== args.length ||
7
+ args.some((arg) => !["--no-studio", "--no-open"].includes(arg)))
8
+ throw new Error("Usage: nylorun dev [--no-studio] [--no-open]");
9
+ const port = Number(process.env.PORT ?? 8787);
10
+ if (!Number.isInteger(port) || port < 1 || port > 65535)
11
+ throw new Error("PORT must be between 1 and 65535");
12
+ const require = createRequire(join(process.cwd(), "package.json"));
13
+ let tsx;
14
+ try {
15
+ tsx = require.resolve("tsx/cli");
16
+ }
17
+ catch {
18
+ throw new Error("Install tsx to use nylorun dev");
19
+ }
20
+ if (!args.includes("--no-studio"))
21
+ try {
22
+ require.resolve("@nylorun/studio");
23
+ }
24
+ catch {
25
+ throw new Error("Install @nylorun/studio or use --no-studio");
26
+ }
27
+ const child = spawn(process.execPath, [
28
+ tsx,
29
+ "watch",
30
+ "--clear-screen=false",
31
+ fileURLToPath(new URL("./dev-entry.js", import.meta.url)),
32
+ ...args,
33
+ ],
34
+ // Deliver terminal shutdown once, through the supervisor, instead of twice through the terminal group.
35
+ {
36
+ stdio: "inherit",
37
+ env: process.env,
38
+ detached: process.platform !== "win32",
39
+ });
40
+ let stopping = false;
41
+ const stop = (signal) => {
42
+ if (stopping)
43
+ return;
44
+ stopping = true;
45
+ child.kill(signal);
46
+ };
47
+ const interrupt = () => stop("SIGINT"), terminate = () => stop("SIGTERM");
48
+ process.on("SIGINT", interrupt);
49
+ process.on("SIGTERM", terminate);
50
+ try {
51
+ return await new Promise((resolve, reject) => {
52
+ child.once("error", reject);
53
+ child.once("exit", (code, signal) => resolve(code ?? (signal === "SIGINT" ? 130 : 143)));
54
+ });
55
+ }
56
+ finally {
57
+ process.removeListener("SIGINT", interrupt);
58
+ process.removeListener("SIGTERM", terminate);
59
+ }
60
+ }
@@ -0,0 +1,2 @@
1
+ export declare function loadProjectEnvironment(root?: string): void;
2
+ export declare function saveEnvironment(root: string, updates: Record<string, string | undefined>, signal?: AbortSignal): Promise<void>;
@@ -0,0 +1,64 @@
1
+ import { readFileSync, statSync } from "node:fs";
2
+ import { writeFile, rename, rm } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { randomUUID } from "node:crypto";
5
+ import { loadEnvFile } from "node:process";
6
+ export function loadProjectEnvironment(root = process.cwd()) {
7
+ const file = join(root, ".env");
8
+ try {
9
+ if (statSync(file).isDirectory())
10
+ throw new Error("The .env directory must be migrated manually: back it up, create a .env file with MODEL_PROVIDER, MODEL and MODEL_PROVIDER_API_KEY, and move OAuth credentials to .nylorun/auth.json. See the Runtime migration guide.");
11
+ }
12
+ catch (error) {
13
+ if (error.code === "ENOENT")
14
+ return;
15
+ throw error;
16
+ }
17
+ loadEnvFile(file);
18
+ }
19
+ // Match complete dotenv assignments, including quoted multiline values.
20
+ const assignment = /^(?:export\s+)?([\w]+)[\t ]*=[\t ]*(?:"[^"]*"|'[^']*'|`[^`]*`|[^#\r\n]*)([^\r\n]*)(?:\r?\n|$)/gm;
21
+ export async function saveEnvironment(root, updates, signal) {
22
+ const file = join(root, ".env");
23
+ let contents = "";
24
+ try {
25
+ contents = readFileSync(file, "utf8");
26
+ }
27
+ catch (error) {
28
+ if (error.code !== "ENOENT")
29
+ throw error;
30
+ }
31
+ const encode = (value) => {
32
+ // Node's dotenv parser has no general quote-escaping syntax. Select a
33
+ // delimiter absent from the value rather than changing the credential.
34
+ for (const quote of ["'", '"', "`"]) {
35
+ if (!value.includes(quote) && !(quote === '"' && /\\[nr]/.test(value)))
36
+ return quote + value + quote;
37
+ }
38
+ throw new Error("This value contains all dotenv quote delimiters; set it through your process environment instead.");
39
+ };
40
+ const remaining = new Set(Object.keys(updates));
41
+ contents = contents.replace(assignment, (whole, key, suffix) => {
42
+ if (!(key in updates))
43
+ return whole;
44
+ if (!remaining.delete(key))
45
+ return "";
46
+ return updates[key] === undefined
47
+ ? ""
48
+ : `${key}=${encode(updates[key])}${suffix}\n`;
49
+ });
50
+ if (contents && !contents.endsWith("\n"))
51
+ contents += "\n";
52
+ for (const key of remaining)
53
+ if (updates[key] !== undefined)
54
+ contents += `${key}=${encode(updates[key])}\n`;
55
+ const temporary = join(root, `.env-${randomUUID()}.tmp`);
56
+ try {
57
+ await writeFile(temporary, contents, { mode: 0o600, signal });
58
+ signal?.throwIfAborted();
59
+ await rename(temporary, file);
60
+ }
61
+ finally {
62
+ await rm(temporary, { force: true });
63
+ }
64
+ }
@@ -0,0 +1 @@
1
+ export declare function start(entry?: string): Promise<void>;
@@ -0,0 +1,4 @@
1
+ import { runProject } from "./project-runner.js";
2
+ export async function start(entry = "dist/agents/index.js") {
3
+ await runProject(entry);
4
+ }
@@ -0,0 +1,12 @@
1
+ import type { Readable, Writable } from "node:stream";
2
+ export declare class ConfigurationCancelled extends Error {
3
+ readonly signal: "SIGINT" | "SIGTERM";
4
+ readonly exitCode: number;
5
+ constructor(signal: "SIGINT" | "SIGTERM");
6
+ }
7
+ export declare function configureProvider(options?: {
8
+ signal?: AbortSignal;
9
+ root?: string;
10
+ input?: Readable;
11
+ output?: Writable;
12
+ }): Promise<void>;
@@ -0,0 +1,155 @@
1
+ import { join } from "node:path";
2
+ import { createInterface } from "node:readline/promises";
3
+ import { saveEnvironment } from "../environment.js";
4
+ import { ProjectCredentialStore } from "@nylorun/runtime/configuration";
5
+ import { modelsFor } from "@nylorun/runtime/configuration";
6
+ export class ConfigurationCancelled extends Error {
7
+ signal;
8
+ exitCode;
9
+ constructor(signal) {
10
+ super(`Provider configuration cancelled (${signal}).`);
11
+ this.signal = signal;
12
+ this.exitCode = signal === "SIGINT" ? 130 : 143;
13
+ }
14
+ }
15
+ // Internal options also allow isolated prompt tests without changing process globals.
16
+ export async function configureProvider(options = {}) {
17
+ const root = options.root ?? process.cwd();
18
+ const output = options.output ?? process.stdout;
19
+ const controller = new AbortController();
20
+ const signal = controller.signal;
21
+ const forwardAbort = () => controller.abort(options.signal.reason);
22
+ options.signal?.throwIfAborted();
23
+ let enteredKey;
24
+ let enteredEnvironment = {};
25
+ const oauthStore = new ProjectCredentialStore(join(root, ".nylorun", "auth.json"), join(root, ".env", "auth.json"));
26
+ const store = {
27
+ read: (id) => oauthStore.read(id),
28
+ list: () => oauthStore.list(),
29
+ delete: (id) => oauthStore.delete(id),
30
+ async modify(id, fn) {
31
+ const next = await fn(await oauthStore.read(id));
32
+ if (next?.type === "api_key") {
33
+ if (next.key === "")
34
+ throw new Error("An API key is required.");
35
+ enteredKey = next.key;
36
+ enteredEnvironment = { ...next.env };
37
+ return next;
38
+ }
39
+ return oauthStore.modify(id, async () => next);
40
+ },
41
+ };
42
+ const models = modelsFor({ provider: "", model: "" }, store);
43
+ const providers = models.getProviders();
44
+ const prompt = createInterface({
45
+ input: options.input ?? process.stdin,
46
+ output,
47
+ });
48
+ const onInt = () => controller.abort(new ConfigurationCancelled("SIGINT"));
49
+ const onClose = () => controller.abort(new Error("Configuration input closed before setup completed."));
50
+ const closeOnAbort = () => prompt.close();
51
+ prompt.on("SIGINT", onInt);
52
+ prompt.on("close", onClose);
53
+ signal.addEventListener("abort", closeOnAbort, { once: true });
54
+ options.signal?.addEventListener("abort", forwardAbort, { once: true });
55
+ if (options.signal?.aborted)
56
+ forwardAbort();
57
+ async function question(message) {
58
+ signal.throwIfAborted();
59
+ return prompt.question(message, { signal });
60
+ }
61
+ try {
62
+ signal.throwIfAborted();
63
+ output.write("0. Custom OpenAI-compatible provider\n");
64
+ providers.forEach((provider, index) => output.write(`${index + 1}. ${provider.name} (${provider.id})\n`));
65
+ const choice = Number(await question("Choose a provider: "));
66
+ if (choice === 0) {
67
+ const baseUrl = (await question("OpenAI-compatible base URL: "))
68
+ .trim()
69
+ .replace(/\/$/, "");
70
+ const model = (await question("Model id: ")).trim();
71
+ if (!baseUrl || !model)
72
+ throw new Error("A base URL and model id are required.");
73
+ const selection = {
74
+ provider: "custom",
75
+ model,
76
+ custom: { baseUrl },
77
+ };
78
+ const customModels = modelsFor(selection, store);
79
+ if (!(await customModels.checkAuth("custom", { signal })))
80
+ await customModels.login("custom", "api_key", interaction());
81
+ await save(selection);
82
+ }
83
+ else {
84
+ const chosen = providers[choice - 1];
85
+ if (!chosen)
86
+ throw new Error("Choose a listed provider.");
87
+ const available = models.getModels(chosen.id);
88
+ available.forEach((model, index) => output.write(`${index + 1}. ${model.name} (${model.id})\n`));
89
+ const model = available[Number(await question("Choose a model: ")) - 1];
90
+ if (!model)
91
+ throw new Error("Choose a listed model.");
92
+ if (!(await models.checkAuth(chosen.id, { signal }))) {
93
+ let method = chosen.auth.apiKey
94
+ ? "api_key"
95
+ : "oauth";
96
+ if (chosen.auth.apiKey && chosen.auth.oauth) {
97
+ const answer = (await question("Choose authentication: 1. API key (default), 2. OAuth: ")).trim();
98
+ if (answer && !["1", "2"].includes(answer))
99
+ throw new Error("Choose authentication 1 or 2.");
100
+ if (answer === "2")
101
+ method = "oauth";
102
+ }
103
+ await models.login(chosen.id, method, interaction());
104
+ }
105
+ await save({ provider: chosen.id, model: model.id });
106
+ }
107
+ signal.throwIfAborted();
108
+ output.write("Provider configuration saved.\n");
109
+ }
110
+ catch (error) {
111
+ throw signal.aborted ? signal.reason : error;
112
+ }
113
+ finally {
114
+ options.signal?.removeEventListener("abort", forwardAbort);
115
+ signal.removeEventListener("abort", closeOnAbort);
116
+ prompt.removeListener("SIGINT", onInt);
117
+ prompt.removeListener("close", onClose);
118
+ prompt.close();
119
+ }
120
+ function interaction() {
121
+ return {
122
+ signal,
123
+ prompt: async (item) => {
124
+ if (item.type !== "select")
125
+ return question(item.message + ": ");
126
+ item.options.forEach((option, index) => output.write(`${index + 1}. ${option.label}\n`));
127
+ const answer = (await question(item.message + " ")).trim();
128
+ const option = item.options.find((option) => option.id === answer) ??
129
+ item.options[Number(answer) - 1];
130
+ if (!option)
131
+ throw new Error("Choose a listed authentication option.");
132
+ return option.id;
133
+ },
134
+ notify: (event) => {
135
+ output.write(("url" in event
136
+ ? event.url
137
+ : "verificationUri" in event
138
+ ? event.verificationUri
139
+ : event.message) + "\n");
140
+ },
141
+ };
142
+ }
143
+ async function save(selection) {
144
+ signal.throwIfAborted();
145
+ await saveEnvironment(root, {
146
+ ...enteredEnvironment,
147
+ MODEL_PROVIDER: selection.provider,
148
+ MODEL: selection.model,
149
+ MODEL_PROVIDER_BASE_URL: selection.custom?.baseUrl,
150
+ ...(enteredKey === undefined
151
+ ? {}
152
+ : { MODEL_PROVIDER_API_KEY: enteredKey }),
153
+ }, signal);
154
+ }
155
+ }
@@ -0,0 +1,8 @@
1
+ export declare function localCredentials(root?: string): Promise<{
2
+ serverKey: string;
3
+ executors: Record<string, string>;
4
+ }>;
5
+ export declare function runProject(entry: string, options?: {
6
+ studio?: boolean;
7
+ open?: boolean;
8
+ }): Promise<void>;
@@ -0,0 +1,165 @@
1
+ import { fork } from "node:child_process";
2
+ import { createRequire } from "node:module";
3
+ import { randomBytes } from "node:crypto";
4
+ import { mkdir, readFile, writeFile, chmod } from "node:fs/promises";
5
+ import { resolve, join } from "node:path";
6
+ import { fileURLToPath, pathToFileURL } from "node:url";
7
+ import { createClient, connectAgents, } from "@nylorun/agents";
8
+ import { modelSelection } from "@nylorun/runtime/configuration";
9
+ import { loadProjectEnvironment } from "./environment.js";
10
+ export async function localCredentials(root = process.cwd()) {
11
+ const directory = join(root, ".nylorun");
12
+ await mkdir(directory, { recursive: true, mode: 0o700 });
13
+ const path = join(directory, "local-credentials.json");
14
+ try {
15
+ const value = JSON.parse(await readFile(path, "utf8"));
16
+ if (typeof value.serverKey !== "string" || !value.executors)
17
+ throw new Error("Invalid local credentials");
18
+ await chmod(path, 0o600);
19
+ return value;
20
+ }
21
+ catch (error) {
22
+ if (error.code !== "ENOENT")
23
+ throw error;
24
+ const value = { serverKey: randomBytes(32).toString("hex"), executors: {} };
25
+ await writeFile(path, JSON.stringify(value), { mode: 0o600, flag: "wx" });
26
+ return value;
27
+ }
28
+ }
29
+ export async function runProject(entry, options = {}) {
30
+ loadProjectEnvironment();
31
+ if (process.env.NYLORUN_DEV_MODEL !== "fixture")
32
+ modelSelection();
33
+ const registry = await import(pathToFileURL(resolve(entry)).href);
34
+ if (!Array.isArray(registry.agents) || !registry.agents.length)
35
+ throw new Error(`${entry} must export a non-empty agents array`);
36
+ const agents = registry.agents;
37
+ const credentials = await localCredentials();
38
+ const version = process.env.NYLORUN_IMPLEMENTATION_VERSION ?? "dev";
39
+ const scopes = agents.map((agent) => {
40
+ const key = JSON.stringify([agent.id, agent.hash, version]);
41
+ const token = (credentials.executors[key] ??=
42
+ randomBytes(32).toString("hex"));
43
+ return {
44
+ token,
45
+ agentId: agent.id,
46
+ manifestHash: agent.hash,
47
+ implementationVersion: version,
48
+ };
49
+ });
50
+ await writeFile(join(process.cwd(), ".nylorun/local-credentials.json"), JSON.stringify(credentials), { mode: 0o600 });
51
+ const port = Number(process.env.PORT ?? 8787);
52
+ if (!Number.isInteger(port) || port < 1 || port > 65535)
53
+ throw new Error("PORT must be between 1 and 65535");
54
+ const url = `http://127.0.0.1:${port}`;
55
+ let child;
56
+ let studio;
57
+ const connections = [];
58
+ let stopping;
59
+ let intentionalStop = false;
60
+ const close = () => (stopping ??= (async () => {
61
+ await Promise.allSettled(connections.map((c) => c.close()));
62
+ await studio?.close().catch(() => { });
63
+ if (child?.exitCode === null && child.signalCode === null) {
64
+ child.kill("SIGTERM");
65
+ await new Promise((resolve) => {
66
+ const timer = setTimeout(() => child?.kill("SIGKILL"), 5000);
67
+ child.once("exit", () => {
68
+ clearTimeout(timer);
69
+ resolve();
70
+ });
71
+ });
72
+ }
73
+ for (const agent of agents)
74
+ await agent.close?.();
75
+ })());
76
+ const stop = () => {
77
+ intentionalStop = true;
78
+ void close().finally(() => {
79
+ process.exitCode = 0;
80
+ });
81
+ };
82
+ process.on("SIGINT", stop);
83
+ process.on("SIGTERM", stop);
84
+ try {
85
+ child = fork(createRequire(import.meta.url).resolve("@nylorun/runtime/server"), [], {
86
+ execArgv: [],
87
+ env: {
88
+ ...process.env,
89
+ HOST: "127.0.0.1",
90
+ PORT: String(port),
91
+ NYLORUN_PROJECT_PROVIDER: "1",
92
+ NYLORUN_SERVER_KEY: credentials.serverKey,
93
+ NYLORUN_EXECUTORS_JSON: JSON.stringify(scopes),
94
+ NYLORUN_SQLITE_PATH: process.env.NYLORUN_SQLITE_PATH ??
95
+ join(process.cwd(), ".nylorun/runtime.sqlite"),
96
+ },
97
+ stdio: ["ignore", "inherit", "inherit", "ipc"],
98
+ });
99
+ await new Promise((resolve, reject) => {
100
+ const timer = setTimeout(() => reject(new Error("Local Runtime did not start within 20 seconds")), 20000);
101
+ const onReady = (message) => {
102
+ if (message?.type === "ready") {
103
+ cleanup();
104
+ resolve();
105
+ }
106
+ };
107
+ const onExit = (code) => {
108
+ cleanup();
109
+ reject(new Error(`Local Runtime exited (${code})`));
110
+ };
111
+ const onError = (error) => {
112
+ cleanup();
113
+ reject(error);
114
+ };
115
+ const cleanup = () => {
116
+ clearTimeout(timer);
117
+ child.off("message", onReady);
118
+ child.off("exit", onExit);
119
+ child.off("error", onError);
120
+ };
121
+ child.on("message", onReady);
122
+ child.once("exit", onExit);
123
+ child.once("error", onError);
124
+ });
125
+ const client = createClient({ url, key: credentials.serverKey });
126
+ for (let index = 0; index < agents.length; index++) {
127
+ await client.saveAgent(agents[index], {
128
+ implementationVersion: version,
129
+ });
130
+ const connection = connectAgents({
131
+ agents: [agents[index]],
132
+ implementationVersion: version,
133
+ runtime: { url, key: scopes[index].token },
134
+ onError: (error) => console.error("Executor:", error instanceof Error ? error.message : error),
135
+ });
136
+ connections.push(connection);
137
+ await connection.ready;
138
+ }
139
+ if (options.studio) {
140
+ const modulePath = createRequire(join(process.cwd(), "package.json")).resolve("@nylorun/studio");
141
+ const module = await import(pathToFileURL(modulePath).href);
142
+ studio = await module.startStudio({
143
+ runtimeUrl: url,
144
+ serverKey: credentials.serverKey,
145
+ open: options.open !== false,
146
+ });
147
+ console.log(`Studio on ${studio.address}`);
148
+ }
149
+ console.log(`Local project ready at ${url}; ${agents.length} connected agent(s).`);
150
+ await new Promise((resolve) => {
151
+ child.once("exit", () => {
152
+ if (!intentionalStop && !stopping)
153
+ process.exitCode = 1;
154
+ resolve();
155
+ });
156
+ if (child.exitCode !== null)
157
+ resolve();
158
+ });
159
+ }
160
+ finally {
161
+ process.removeListener("SIGINT", stop);
162
+ process.removeListener("SIGTERM", stop);
163
+ await close();
164
+ }
165
+ }
package/package.json CHANGED
@@ -1,12 +1,45 @@
1
1
  {
2
2
  "name": "@nylorun/cli",
3
- "version": "0.0.0-bootstrap",
4
- "description": "Bootstrap placeholder for @nylorun/cli",
5
- "main": "index.js",
3
+ "version": "0.1.1-beta",
4
+ "type": "module",
5
+ "license": "Apache-2.0",
6
+ "description": "Nylorun local development CLI",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/nylorun/harness.git",
10
+ "directory": "cli"
11
+ },
12
+ "files": [
13
+ "dist",
14
+ "README.md",
15
+ "LICENSE",
16
+ "CHANGELOG.md"
17
+ ],
18
+ "publishConfig": {
19
+ "access": "public",
20
+ "provenance": true
21
+ },
22
+ "engines": {
23
+ "node": ">=24.0.0"
24
+ },
6
25
  "scripts": {
7
- "test": "echo \"Error: no test specified\" && exit 1"
26
+ "build": "npm run clean && node ../scripts/check-typescript-version.mjs && tsc -p tsconfig.json",
27
+ "clean": "node -e \"import('node:fs').then(({rmSync})=>rmSync('dist',{recursive:true,force:true}))\"",
28
+ "check": "npm run build && npm test && node scripts/check-package.mjs",
29
+ "test": "vitest run --passWithNoTests",
30
+ "prepack": "npm run build"
31
+ },
32
+ "dependencies": {
33
+ "@nylorun/agents": "0.2.0-beta",
34
+ "@nylorun/runtime": "0.6.0-beta",
35
+ "@earendil-works/pi-ai": "0.85.1"
36
+ },
37
+ "devDependencies": {
38
+ "typescript": "npm:@typescript/typescript6@^6.0.2",
39
+ "@types/node": "^26.5.0",
40
+ "vitest": "^5.0.0"
8
41
  },
9
- "keywords": [],
10
- "author": "",
11
- "license": "MIT"
42
+ "bin": {
43
+ "nylorun": "dist/cli.js"
44
+ }
12
45
  }
package/index.js DELETED
@@ -1 +0,0 @@
1
- export {}
package/publish.out DELETED
File without changes