nylorun 0.4.0-beta → 0.5.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.
@@ -1,47 +1,52 @@
1
1
  import { existsSync } from "node:fs";
2
- import { readdir, readFile, rename, writeFile } from "node:fs/promises";
2
+ import { mkdir, readdir, readFile, rename, rm, rmdir, writeFile } from "node:fs/promises";
3
3
  import { randomBytes } from "node:crypto";
4
4
  import { homedir } from "node:os";
5
- import { basename, join, resolve } from "node:path";
5
+ import { basename, join, resolve, sep } from "node:path";
6
6
  import { CliError } from "../errors.js";
7
7
  /**
8
- * The machine's local stacks (tenancy.md §6): one installation per stack, each with its own
9
- * Host root `~/.nylorun/stacks/<name>/`, Compose project `nylorun-<name>`, ports and volumes.
10
- * `~/.nylorun` itself held the single stack of older releases (the legacy stack).
8
+ * The machine's local Tenants (tenancy.md §6): one installation per Tenant, each with its own
9
+ * Host root `~/.nylorun/tenants/<name>/`, Compose project `nylorun-<name>`, ports and volumes.
11
10
  */
12
- /** A stack name: also part of its Compose project, so Compose's rules apply. */
13
- export const STACK_NAME = /^[a-z0-9][a-z0-9_-]*$/;
14
- /** `~/.nylorun`: the stacks, and the legacy stack's files. Tests pass another directory. */
11
+ /** The Tenant a command acts on outside a project when nothing names one. */
12
+ export const DEFAULT_TENANT = "default";
13
+ /** A Tenant name: also part of its Compose project, so Compose's rules apply. */
14
+ export const TENANT_NAME = /^[a-z0-9][a-z0-9_-]*$/;
15
+ /** `~/.nylorun`: the Tenants and the machine's settings. Tests pass another directory. */
15
16
  export function defaultNylorunRoot() {
16
17
  return resolve(join(homedir(), ".nylorun"));
17
18
  }
18
- export function stacksDir(base) {
19
- return join(base, "stacks");
19
+ export function tenantsDir(base) {
20
+ return join(base, "tenants");
20
21
  }
21
- export function stackRoot(base, name) {
22
- return join(stacksDir(base), name);
22
+ export function tenantRoot(base, name) {
23
+ return join(tenantsDir(base), name);
23
24
  }
24
- export function assertStackName(name, source) {
25
- if (!STACK_NAME.test(name))
25
+ export function assertTenantName(name, source) {
26
+ // A Tenant id, such as a NYLORUN_TENANT kept from an older release.
27
+ if (/^tn_/i.test(name))
28
+ throw new CliError(`${source} must be a Tenant's name, not a Tenant id: ${name}. "nylorun ls" lists the Tenants on this machine.`, 2);
29
+ if (!TENANT_NAME.test(name))
26
30
  throw new CliError(`${source} must be lowercase letters, digits, "-" or "_", starting with a letter or digit: ${name}`, 2);
27
31
  return name;
28
32
  }
29
- /** A directory name as a stack name: lowercased, other characters as `-`, trimmed. */
30
- export function sanitizeStackName(raw) {
33
+ /** A directory name as a Tenant name: lowercased, other characters as `-`, trimmed. */
34
+ export function sanitizeTenantName(raw) {
31
35
  const name = raw
32
36
  .toLowerCase()
33
37
  .replace(/[^a-z0-9_-]+/g, "-")
34
38
  .replace(/-{2,}/g, "-")
35
- .replace(/^[-_]+|[-_]+$/g, "");
36
- return name === "" ? "stack" : name;
39
+ .replace(/^[-_]+|[-_]+$/g, "")
40
+ .replace(/^tn_/, "tn-");
41
+ return name === "" ? "tenant" : name;
37
42
  }
38
- export function stackRecordPath(root) {
39
- return join(root, "stack.json");
43
+ export function tenantRecordPath(root) {
44
+ return join(root, "tenant.json");
40
45
  }
41
- export async function readStackRecord(root) {
46
+ export async function readTenantRecord(root) {
42
47
  try {
43
- const value = JSON.parse(await readFile(stackRecordPath(root), "utf8"));
44
- if (typeof value?.name !== "string" || !STACK_NAME.test(value.name))
48
+ const value = JSON.parse(await readFile(tenantRecordPath(root), "utf8"));
49
+ if (typeof value?.name !== "string" || !TENANT_NAME.test(value.name))
45
50
  return undefined;
46
51
  return {
47
52
  format: 1,
@@ -53,64 +58,93 @@ export async function readStackRecord(root) {
53
58
  return undefined;
54
59
  }
55
60
  }
56
- export async function writeStackRecord(root, record) {
57
- const path = stackRecordPath(root);
61
+ export async function writeTenantRecord(root, record) {
62
+ const path = tenantRecordPath(root);
58
63
  const temporary = `${path}.${randomBytes(8).toString("hex")}.tmp`;
59
64
  const body = { format: 1, name: record.name, ...(record.project ? { project: record.project } : {}) };
60
65
  await writeFile(temporary, `${JSON.stringify(body, null, 2)}\n`, { mode: 0o600 });
61
66
  await rename(temporary, path);
62
67
  }
63
- /** The stacks under `<base>/stacks`, by name. */
64
- export async function listStacks(base) {
68
+ /**
69
+ * The Tenants under `<base>/tenants`, by name: directories with a `tenant.json` (releases
70
+ * before 0.4 kept other directories there).
71
+ */
72
+ export async function listTenants(base) {
65
73
  let entries;
66
74
  try {
67
- entries = await readdir(stacksDir(base), { withFileTypes: true });
75
+ entries = await readdir(tenantsDir(base), { withFileTypes: true });
68
76
  }
69
77
  catch {
70
78
  return [];
71
79
  }
72
- const stacks = [];
80
+ const tenants = [];
73
81
  for (const entry of entries) {
74
- if (!entry.isDirectory() || !STACK_NAME.test(entry.name))
82
+ if (!entry.isDirectory() || !TENANT_NAME.test(entry.name))
75
83
  continue;
76
- const root = stackRoot(base, entry.name);
77
- const record = await readStackRecord(root);
78
- stacks.push({ name: entry.name, root, ...(record ? { record } : {}) });
84
+ const root = tenantRoot(base, entry.name);
85
+ const record = await readTenantRecord(root);
86
+ if (record)
87
+ tenants.push({ name: entry.name, root, record });
79
88
  }
80
- return stacks.sort((a, b) => a.name.localeCompare(b.name));
89
+ return tenants.sort((a, b) => a.name.localeCompare(b.name));
81
90
  }
82
91
  /**
83
- * The stack name for a project without a link: the directory's name, or the first `-2`,
84
- * `-3`, … suffix that no stack of another project directory holds. A stack this project
92
+ * The Tenant name for a project without a link: the directory's name, or the first `-2`,
93
+ * `-3`, … suffix that no Tenant of another project directory holds. A Tenant this project
85
94
  * directory created keeps its name.
86
95
  */
87
- export async function chooseStackName(base, projectDir) {
88
- const name = sanitizeStackName(basename(projectDir));
89
- const stacks = await listStacks(base);
96
+ export async function chooseTenantName(base, projectDir) {
97
+ const name = sanitizeTenantName(basename(projectDir));
98
+ const tenants = await listTenants(base);
90
99
  const candidate = new RegExp(`^${name}(?:-[0-9]+)?$`);
91
- const own = stacks.find((stack) => candidate.test(stack.name) && stack.record?.project === projectDir);
100
+ const own = tenants.find((tenant) => candidate.test(tenant.name) && tenant.record.project === projectDir);
92
101
  if (own)
93
102
  return own.name;
94
103
  for (let suffix = 1;; suffix += 1) {
95
104
  const next = suffix === 1 ? name : `${name}-${suffix}`;
96
- if (!existsSync(stackRoot(base, next)))
105
+ if (!existsSync(tenantRoot(base, next)))
97
106
  return next;
98
107
  }
99
108
  }
100
- export function legacyStack(base) {
101
- const compose = join(base, "stack", "compose.yaml");
102
- if (!existsSync(compose))
103
- return undefined;
104
- return { root: base, project: "nylorun", compose, env: join(base, "stack", ".env") };
109
+ /**
110
+ * Move the Host roots of nylorun 0.4 (`~/.nylorun/stacks/<name>/`) to `tenants/<name>/`, when
111
+ * that is free: `stack.json` becomes `tenant.json`, and `NYLORUN_STACK_NAME` becomes
112
+ * `NYLORUN_TENANT_NAME` in `docker/.env` (and `docker/compose.yaml`, until the next start
113
+ * rewrites it). `stacks/` goes when empty. They move rather than start fresh because Compose
114
+ * project names do not change: a fresh Host root under the same name would reuse the old
115
+ * volumes with new keys.
116
+ */
117
+ export async function moveStackRoots(base, err) {
118
+ const stacks = join(base, "stacks");
119
+ let names;
120
+ try {
121
+ names = (await readdir(stacks, { withFileTypes: true }))
122
+ .filter((entry) => entry.isDirectory() && TENANT_NAME.test(entry.name))
123
+ .map((entry) => entry.name);
124
+ }
125
+ catch {
126
+ return;
127
+ }
128
+ const moved = [];
129
+ for (const name of names.sort()) {
130
+ const root = tenantRoot(base, name);
131
+ if (existsSync(root))
132
+ continue;
133
+ await mkdir(tenantsDir(base), { recursive: true, mode: 0o700 });
134
+ await rename(join(stacks, name), root);
135
+ await rename(join(root, "stack.json"), tenantRecordPath(root)).catch(() => { });
136
+ for (const file of [join(root, "docker", ".env"), join(root, "docker", "compose.yaml")]) {
137
+ const text = await readFile(file, "utf8").catch(() => undefined);
138
+ if (text?.includes("NYLORUN_STACK_NAME"))
139
+ await writeFile(file, text.replaceAll("NYLORUN_STACK_NAME", "NYLORUN_TENANT_NAME"));
140
+ }
141
+ moved.push(name);
142
+ }
143
+ // A marker file of 0.4.
144
+ await rm(join(stacks, ".legacy-noted"), { force: true });
145
+ await rmdir(stacks).catch(() => { });
146
+ if (moved.length) {
147
+ const tilde = (path) => path.startsWith(homedir() + sep) ? `~${path.slice(homedir().length)}` : path;
148
+ err(`Moved Tenants ${moved.join(", ")} from ${tilde(stacks)} to ${tilde(tenantsDir(base))}.`);
149
+ }
105
150
  }
106
- /** What `nylorun legacy delete` removes from `~/.nylorun`: the old layout only, never `stacks/`. */
107
- export const LEGACY_ENTRIES = [
108
- "host.json",
109
- "host-credentials.json",
110
- "host-state.json",
111
- "stack",
112
- "tenants",
113
- "home",
114
- "tmp",
115
- "trash",
116
- ];
@@ -3,7 +3,7 @@ export type PinnedImage = "runtime" | "studio";
3
3
  /**
4
4
  * The version this CLI release pins for an image, from `cli/package.json`
5
5
  * `nylorun.runtime` or `nylorun.studio`: the tag of `ghcr.io/nylorun/<name>`
6
- * the stack runs unless `NYLORUN_RUNTIME_IMAGE` / `NYLORUN_STUDIO_IMAGE`
6
+ * a local Tenant runs unless `NYLORUN_RUNTIME_IMAGE` / `NYLORUN_STUDIO_IMAGE`
7
7
  * overrides it. The release tooling writes both pins.
8
8
  */
9
9
  export declare function pinnedVersion(name: PinnedImage): string;
@@ -9,7 +9,7 @@ function cliPackageJsonPath() {
9
9
  /**
10
10
  * The version this CLI release pins for an image, from `cli/package.json`
11
11
  * `nylorun.runtime` or `nylorun.studio`: the tag of `ghcr.io/nylorun/<name>`
12
- * the stack runs unless `NYLORUN_RUNTIME_IMAGE` / `NYLORUN_STUDIO_IMAGE`
12
+ * a local Tenant runs unless `NYLORUN_RUNTIME_IMAGE` / `NYLORUN_STUDIO_IMAGE`
13
13
  * overrides it. The release tooling writes both pins.
14
14
  */
15
15
  export function pinnedVersion(name) {
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Studio's anonymous usage analytics. Studio's dashboard reports page views,
3
+ * with every id replaced by `:id`, to this Google Analytics property unless the
4
+ * developer opted out. `nylorun start` decides and passes the id to the
5
+ * Studio container (`NYLORUN_STUDIO_ANALYTICS_ID`); Studio never decides itself.
6
+ */
7
+ export declare const STUDIO_ANALYTICS_ID = "G-K6RPDFH6Q6";
8
+ /** `~/.nylorun/telemetry.json`: the developer's choice, for every Tenant on the machine. */
9
+ export interface TelemetryFile {
10
+ format: 1;
11
+ /** False after `nylorun telemetry disable`; absent until a choice is made. */
12
+ enabled?: boolean;
13
+ /** When `nylorun start` showed the notice (ISO time); it is shown once. */
14
+ noticeShown?: string;
15
+ }
16
+ export type TelemetryDecision = Readonly<{
17
+ enabled: boolean;
18
+ reason: string;
19
+ }>;
20
+ export declare const TELEMETRY_NOTICE: string;
21
+ export declare function telemetryPath(nylorunRoot: string): string;
22
+ export declare function readTelemetry(nylorunRoot: string): Promise<TelemetryFile>;
23
+ export declare function writeTelemetry(nylorunRoot: string, file: TelemetryFile): Promise<void>;
24
+ /** On unless the environment or the developer's choice turns it off. */
25
+ export declare function telemetryDecision(env: Readonly<Record<string, string | undefined>>, file: TelemetryFile): TelemetryDecision;
26
+ /** `nylorun telemetry [status|enable|disable]`. */
27
+ export declare function telemetryCommand(args: readonly string[], context: {
28
+ nylorunRoot: string;
29
+ env: Readonly<Record<string, string | undefined>>;
30
+ out(line: string): void;
31
+ }): Promise<number>;
@@ -0,0 +1,79 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { CliError } from "./errors.js";
5
+ /**
6
+ * Studio's anonymous usage analytics. Studio's dashboard reports page views,
7
+ * with every id replaced by `:id`, to this Google Analytics property unless the
8
+ * developer opted out. `nylorun start` decides and passes the id to the
9
+ * Studio container (`NYLORUN_STUDIO_ANALYTICS_ID`); Studio never decides itself.
10
+ */
11
+ export const STUDIO_ANALYTICS_ID = "G-K6RPDFH6Q6";
12
+ export const TELEMETRY_NOTICE = [
13
+ "Studio collects anonymous usage data: which pages are opened, with every",
14
+ "Tenant, agent and session id removed. Nothing you send to agents is collected.",
15
+ 'Turn it off with "nylorun telemetry disable" or NYLORUN_TELEMETRY_DISABLED=1.',
16
+ "Learn more: https://github.com/nylorun/agents/blob/main/nylorun/README.md#telemetry",
17
+ ].join("\n");
18
+ export function telemetryPath(nylorunRoot) {
19
+ return join(nylorunRoot, "telemetry.json");
20
+ }
21
+ export async function readTelemetry(nylorunRoot) {
22
+ try {
23
+ const parsed = JSON.parse(await readFile(telemetryPath(nylorunRoot), "utf8"));
24
+ if (parsed && typeof parsed === "object") {
25
+ const { enabled, noticeShown } = parsed;
26
+ return {
27
+ format: 1,
28
+ ...(typeof enabled === "boolean" ? { enabled } : {}),
29
+ ...(typeof noticeShown === "string" ? { noticeShown } : {}),
30
+ };
31
+ }
32
+ }
33
+ catch {
34
+ /* missing or unreadable: no choice yet */
35
+ }
36
+ return { format: 1 };
37
+ }
38
+ export async function writeTelemetry(nylorunRoot, file) {
39
+ await mkdir(nylorunRoot, { recursive: true });
40
+ const path = telemetryPath(nylorunRoot);
41
+ const temporary = `${path}.${randomBytes(8).toString("hex")}.tmp`;
42
+ await writeFile(temporary, `${JSON.stringify(file, null, 2)}\n`);
43
+ await rename(temporary, path);
44
+ }
45
+ /** An environment flag is set unless it is empty, `0`, `false` or `no`. */
46
+ function flag(value) {
47
+ const trimmed = value?.trim() ?? "";
48
+ return trimmed !== "" && !/^(0|false|no)$/i.test(trimmed);
49
+ }
50
+ /** On unless the environment or the developer's choice turns it off. */
51
+ export function telemetryDecision(env, file) {
52
+ if (flag(env.NYLORUN_TELEMETRY_DISABLED))
53
+ return { enabled: false, reason: "NYLORUN_TELEMETRY_DISABLED is set" };
54
+ if (flag(env.DO_NOT_TRACK))
55
+ return { enabled: false, reason: "DO_NOT_TRACK is set" };
56
+ if (flag(env.CI))
57
+ return { enabled: false, reason: "CI is set" };
58
+ if (file.enabled === false)
59
+ return { enabled: false, reason: 'turned off with "nylorun telemetry disable"' };
60
+ return { enabled: true, reason: "on by default" };
61
+ }
62
+ const USAGE = "Usage: nylorun telemetry [status|enable|disable]";
63
+ /** `nylorun telemetry [status|enable|disable]`. */
64
+ export async function telemetryCommand(args, context) {
65
+ const [action = "status", ...rest] = args;
66
+ if (rest.length || !["status", "enable", "disable"].includes(action))
67
+ throw new CliError(USAGE, 2);
68
+ const file = await readTelemetry(context.nylorunRoot);
69
+ if (action !== "status") {
70
+ const enabled = action === "enable";
71
+ await writeTelemetry(context.nylorunRoot, { ...file, enabled });
72
+ context.out(`Studio telemetry ${enabled ? "enabled" : "disabled"}. Running Tenants pick this up on the next "nylorun start".`);
73
+ }
74
+ const decision = telemetryDecision(context.env, await readTelemetry(context.nylorunRoot));
75
+ context.out(`Studio telemetry is ${decision.enabled ? "on" : "off"} (${decision.reason}).`);
76
+ if (action === "status")
77
+ context.out(TELEMETRY_NOTICE);
78
+ return 0;
79
+ }
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "nylorun",
3
- "version": "0.4.0-beta",
3
+ "version": "0.5.0-beta",
4
4
  "type": "module",
5
5
  "license": "Apache-2.0",
6
- "description": "Set up and run the local Nylorun stack (Runtime and Studio) with Docker Compose",
6
+ "description": "Set up and run local Nylorun Tenants (Runtime and Studio) with Docker Compose",
7
7
  "repository": {
8
8
  "type": "git",
9
9
  "url": "git+https://github.com/nylorun/agents.git",
@@ -30,7 +30,7 @@
30
30
  "prepack": "npm run build"
31
31
  },
32
32
  "dependencies": {
33
- "@nylorun/core": "0.10.0-beta"
33
+ "@nylorun/core": "0.11.0-beta"
34
34
  },
35
35
  "devDependencies": {
36
36
  "typescript": "npm:@typescript/typescript6@^6.0.2",
@@ -41,7 +41,7 @@
41
41
  "nylorun": "dist/cli.js"
42
42
  },
43
43
  "nylorun": {
44
- "runtime": "0.15.0-beta",
45
- "studio": "0.15.0-beta"
44
+ "runtime": "0.15.1-beta",
45
+ "studio": "0.16.0-beta"
46
46
  }
47
47
  }