@nylorun/runtime 0.4.0-beta → 0.6.0-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.
Files changed (64) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/README.md +29 -47
  3. package/dist/adapters/media.d.ts +2 -18
  4. package/dist/adapters/media.js +2 -52
  5. package/dist/adapters/observe.js +1 -1
  6. package/dist/config.d.ts +17 -10
  7. package/dist/configuration.d.ts +3 -0
  8. package/dist/configuration.js +3 -0
  9. package/dist/contracts.d.ts +5 -166
  10. package/dist/core/main.js +40 -0
  11. package/dist/core/provider.d.ts +12 -0
  12. package/dist/core/provider.js +60 -0
  13. package/dist/core/runtime.d.ts +50 -0
  14. package/dist/core/runtime.js +877 -0
  15. package/dist/core/store.d.ts +16 -0
  16. package/dist/core/store.js +101 -0
  17. package/dist/index.d.ts +6 -11
  18. package/dist/index.js +4 -6
  19. package/dist/media.d.ts +29 -0
  20. package/dist/media.js +53 -0
  21. package/dist/model/defaults.d.ts +17 -0
  22. package/dist/model/defaults.js +21 -0
  23. package/dist/model/http-model.d.ts +12 -0
  24. package/dist/model/http-model.js +299 -0
  25. package/dist/model/pi-model.d.ts +2 -1
  26. package/dist/model/pi-model.js +52 -7
  27. package/dist/node/index.d.ts +5 -0
  28. package/dist/node/index.js +5 -0
  29. package/dist/node/local-sessions.d.ts +5 -0
  30. package/dist/node/local-sessions.js +174 -0
  31. package/dist/redact.d.ts +1 -0
  32. package/dist/redact.js +14 -0
  33. package/dist/server/ag-ui.d.ts +1 -1
  34. package/dist/server/delivery.d.ts +24 -0
  35. package/dist/server/delivery.js +107 -0
  36. package/dist/server/host.d.ts +50 -7
  37. package/dist/server/host.js +304 -307
  38. package/dist/session/api.d.ts +10 -0
  39. package/dist/session/api.js +15 -0
  40. package/dist/session/default.d.ts +5 -0
  41. package/dist/session/default.js +30 -0
  42. package/dist/session/handle.d.ts +27 -0
  43. package/dist/session/handle.js +199 -0
  44. package/dist/session/index.d.ts +2 -0
  45. package/dist/session/index.js +2 -0
  46. package/dist/sessions/host.d.ts +39 -0
  47. package/dist/sessions/host.js +359 -0
  48. package/dist/sessions/store.d.ts +41 -0
  49. package/dist/sessions/store.js +33 -0
  50. package/package.json +23 -12
  51. package/dist/adapters/journal.d.ts +0 -35
  52. package/dist/adapters/journal.js +0 -130
  53. package/dist/cli.d.ts +0 -2
  54. package/dist/cli.js +0 -100
  55. package/dist/dev-entry.js +0 -2
  56. package/dist/dev.d.ts +0 -2
  57. package/dist/dev.js +0 -126
  58. package/dist/environment.d.ts +0 -2
  59. package/dist/environment.js +0 -64
  60. package/dist/launcher.d.ts +0 -1
  61. package/dist/launcher.js +0 -28
  62. package/dist/model/configure.d.ts +0 -12
  63. package/dist/model/configure.js +0 -155
  64. /package/dist/{dev-entry.d.ts → core/main.d.ts} +0 -0
package/dist/cli.js DELETED
@@ -1,100 +0,0 @@
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 --agent-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
- agentServerUrl,
24
- open,
25
- ...(port === undefined ? {} : { port }),
26
- });
27
- }
28
- function parsePort(value) {
29
- if (value === undefined)
30
- return undefined;
31
- const port = Number(value);
32
- if (!Number.isInteger(port) || port < 1 || port > 65535)
33
- throw new Error("--port must be an integer between 1 and 65535.");
34
- return port;
35
- }
36
- async function main() {
37
- const [command, ...args] = process.argv.slice(2);
38
- if (!command || command === "--help" || command === "-h")
39
- return void console.log(usage);
40
- if (["configure", "dev", "start"].includes(command))
41
- loadProjectEnvironment();
42
- if (command === "start") {
43
- if (args.length > 1 || args[0]?.startsWith("--"))
44
- throw new Error(usage);
45
- await (await import("./launcher.js")).start(args[0]);
46
- return;
47
- }
48
- if (command === "dev") {
49
- process.exitCode = await develop(args);
50
- return;
51
- }
52
- if (command === "configure") {
53
- if (args.length)
54
- throw new Error(usage);
55
- const controller = new AbortController();
56
- const cancel = (signal) => controller.abort(new ConfigurationCancelled(signal));
57
- process.once("SIGINT", () => cancel("SIGINT"));
58
- process.once("SIGTERM", () => cancel("SIGTERM"));
59
- await configureProvider({ signal: controller.signal });
60
- return;
61
- }
62
- if (command !== "studio")
63
- throw new Error(usage);
64
- let agentUrl;
65
- let port;
66
- let open = true;
67
- for (let index = 0; index < args.length; index += 1) {
68
- const arg = args[index];
69
- if (arg === "--agent-url") {
70
- if (agentUrl !== undefined)
71
- throw new Error("--agent-url may only be supplied once.");
72
- agentUrl = args[++index];
73
- if (!agentUrl || agentUrl.startsWith("--"))
74
- throw new Error("--agent-url requires a value.");
75
- }
76
- else if (arg === "--port") {
77
- if (port !== undefined)
78
- throw new Error("--port may only be supplied once.");
79
- port = parsePort(args[++index]);
80
- }
81
- else if (arg === "--no-open" && open)
82
- open = false;
83
- else
84
- throw new Error(usage);
85
- }
86
- if (!agentUrl)
87
- throw new Error("--agent-url is required.");
88
- const dashboard = await startStudio(agentUrl, open, port);
89
- console.log(`Studio on ${dashboard.address}`);
90
- await new Promise((resolve, reject) => {
91
- const close = () => void dashboard.close().then(resolve, reject);
92
- process.once("SIGINT", close);
93
- process.once("SIGTERM", close);
94
- });
95
- }
96
- void main().catch((error) => {
97
- console.error(error instanceof Error ? error.message : String(error));
98
- process.exitCode =
99
- error instanceof ConfigurationCancelled ? error.exitCode : 1;
100
- });
package/dist/dev-entry.js DELETED
@@ -1,2 +0,0 @@
1
- import { start } from "./launcher.js";
2
- await start(process.argv[2] ?? "src/index.ts", true);
package/dist/dev.d.ts DELETED
@@ -1,2 +0,0 @@
1
- /** Runs project development tooling without copying a supervisor into each application. */
2
- export declare function develop(args: readonly string[]): Promise<number>;
package/dist/dev.js DELETED
@@ -1,126 +0,0 @@
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
- import { setTimeout as delay } from "node:timers/promises";
6
- /** Runs project development tooling without copying a supervisor into each application. */
7
- export async function develop(args) {
8
- const usage = "Usage: nylorun dev [--no-studio] [--no-open]";
9
- if (new Set(args).size !== args.length ||
10
- args.some((arg) => !["--no-studio", "--no-open"].includes(arg)))
11
- throw new Error(usage);
12
- const port = Number(process.env.PORT ?? "3000");
13
- if (!Number.isInteger(port) || port < 1 || port > 65535)
14
- throw new Error("PORT must be an integer between 1 and 65535.");
15
- const require = createRequire(join(process.cwd(), "package.json"));
16
- let tsx;
17
- try {
18
- tsx = require.resolve("tsx/cli");
19
- }
20
- catch {
21
- throw new Error("Install tsx in your project to use nylorun dev.");
22
- }
23
- if (!args.includes("--no-studio")) {
24
- try {
25
- require.resolve("@nylorun/studio");
26
- }
27
- catch {
28
- throw new Error("Install @nylorun/studio or use nylorun dev --no-studio.");
29
- }
30
- }
31
- const controller = new AbortController();
32
- const children = new Set();
33
- const exits = [];
34
- let result = 0;
35
- let force;
36
- const stop = (code, signal = "SIGTERM") => {
37
- if (controller.signal.aborted)
38
- return;
39
- result = code;
40
- controller.abort();
41
- for (const child of children)
42
- child.kill(signal);
43
- force = setTimeout(() => {
44
- for (const child of children)
45
- child.kill("SIGKILL");
46
- }, 5_000);
47
- force.unref();
48
- };
49
- const interrupt = () => stop(130, "SIGINT");
50
- const terminate = () => stop(143);
51
- process.once("SIGINT", interrupt);
52
- process.once("SIGTERM", terminate);
53
- const launch = (argv) => {
54
- const child = spawn(process.execPath, argv, {
55
- stdio: "inherit",
56
- env: { ...process.env, NYLORUN_DEV: "1" },
57
- });
58
- children.add(child);
59
- exits.push(new Promise((resolve) => {
60
- child.once("error", (error) => {
61
- console.error(`Could not start development process: ${error.message}`);
62
- stop(1);
63
- });
64
- child.once("close", (code, signal) => {
65
- children.delete(child);
66
- stop(code ?? (signal === "SIGINT" ? 130 : signal === "SIGTERM" ? 143 : 1));
67
- resolve();
68
- });
69
- }));
70
- };
71
- try {
72
- launch([
73
- tsx,
74
- "watch",
75
- fileURLToPath(new URL("./dev-entry.js", import.meta.url)),
76
- "src/index.ts",
77
- ]);
78
- if (!args.includes("--no-studio")) {
79
- const url = `http://127.0.0.1:${port}/agents/v1/agents`;
80
- const deadline = Date.now() + 20_000;
81
- let ready = false;
82
- while (!controller.signal.aborted && Date.now() < deadline) {
83
- try {
84
- const response = await fetch(url, {
85
- signal: AbortSignal.any([
86
- controller.signal,
87
- AbortSignal.timeout(500),
88
- ]),
89
- });
90
- ready = response.ok;
91
- await response.body?.cancel();
92
- if (ready)
93
- break;
94
- }
95
- catch {
96
- /* Watch mode may still be compiling or restarting the app. */
97
- }
98
- await delay(50, undefined, { signal: controller.signal }).catch(() => { });
99
- }
100
- if (!controller.signal.aborted) {
101
- if (!ready)
102
- throw new Error(`Application did not become ready at ${url} within 20 seconds.`);
103
- launch([
104
- fileURLToPath(new URL("./cli.js", import.meta.url)),
105
- "studio",
106
- "--agent-url",
107
- `http://localhost:${port}/agents`,
108
- ...(args.includes("--no-open") ? ["--no-open"] : []),
109
- ]);
110
- }
111
- }
112
- await Promise.all(exits);
113
- }
114
- catch (error) {
115
- stop(1);
116
- await Promise.all(exits);
117
- throw error;
118
- }
119
- finally {
120
- if (force !== undefined)
121
- clearTimeout(force);
122
- process.removeListener("SIGINT", interrupt);
123
- process.removeListener("SIGTERM", terminate);
124
- }
125
- return result;
126
- }
@@ -1,2 +0,0 @@
1
- export declare function loadProjectEnvironment(root?: string): void;
2
- export declare function saveEnvironment(root: string, updates: Record<string, string | undefined>, signal?: AbortSignal): Promise<void>;
@@ -1,64 +0,0 @@
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
- }
@@ -1 +0,0 @@
1
- export declare function start(entry?: string, development?: boolean): Promise<void>;
package/dist/launcher.js DELETED
@@ -1,28 +0,0 @@
1
- import { serve } from "@hono/node-server";
2
- import { resolve } from "node:path";
3
- import { pathToFileURL } from "node:url";
4
- import { loadProjectEnvironment } from "./environment.js";
5
- export async function start(entry = "dist/src/index.js", development = false) {
6
- loadProjectEnvironment();
7
- if (development)
8
- process.env.NYLORUN_DEV = "1";
9
- else
10
- delete process.env.NYLORUN_DEV;
11
- const port = Number(process.env.PORT ?? "3000");
12
- if (!Number.isInteger(port) || port < 1 || port > 65535)
13
- throw new Error("PORT must be an integer between 1 and 65535.");
14
- const { default: app } = await import(pathToFileURL(resolve(entry)).href);
15
- if (!app || typeof app.fetch !== "function")
16
- throw new Error(`${entry} must export a Hono application with 'export default app' and a callable fetch.`);
17
- const server = serve({ fetch: app.fetch.bind(app), port }, (info) => {
18
- console.log(`Server is running on http://localhost:${info.port}`);
19
- });
20
- const stop = () => {
21
- process.removeListener("SIGINT", stop);
22
- process.removeListener("SIGTERM", stop);
23
- server.close(() => process.exit(0));
24
- setTimeout(() => process.exit(0), 5_000).unref();
25
- };
26
- process.once("SIGINT", stop);
27
- process.once("SIGTERM", stop);
28
- }
@@ -1,12 +0,0 @@
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>;
@@ -1,155 +0,0 @@
1
- import { join } from "node:path";
2
- import { createInterface } from "node:readline/promises";
3
- import { saveEnvironment } from "../environment.js";
4
- import { ProjectCredentialStore } from "./auth-store.js";
5
- import { modelsFor } from "./models.js";
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
- }
File without changes