A personal assistant that lives on your desktop, remembers what matters, and can use your Mac for you.
TypeScript
feat(daemon): build a relocatable runtime daemon and resolve Engram
Alan Buscagliaea5227331cac
diff --git a/packages/daemon/package.json b/packages/daemon/package.jsonindex 967ea7b..b530381 100644--- a/packages/daemon/package.json+++ b/packages/daemon/package.json@@ -6,6 +6,9 @@"bin": {"gentle-dot": "./src/cli.ts"},+ "scripts": {+ "build:runtime": "node scripts/build-runtime.ts"+ },"dependencies": {"@earendil-works/pi-ai": "1.0.4","@earendil-works/pi-coding-agent": "1.0.4",@@ -15,6 +18,7 @@"ws": "^8.22.0"},"devDependencies": {- "@types/ws": "^8.18.2"+ "@types/ws": "^8.18.2",+ "esbuild": "0.28.2"}}diff --git a/packages/daemon/scripts/build-runtime.ts b/packages/daemon/scripts/build-runtime.tsnew file mode 100644index 0000000..0cb6246--- /dev/null+++ b/packages/daemon/scripts/build-runtime.ts@@ -0,0 +1,12 @@+// Builds the daemon part of the installed runtime: `build:runtime -- --out <runtime folder>`.+import { resolve } from "node:path";+import { buildRuntime } from "../src/runtime-build.ts";++const args = process.argv.slice(2).filter((arg) => arg !== "--");+const out = args[args.indexOf("--out") + 1];+if (!args.includes("--out") || !out) {+ process.stderr.write("usage: build-runtime --out <dir>\n");+ process.exit(2);+}+// pnpm runs the script in the package folder; a relative path is the caller's.+await buildRuntime(resolve(process.env.INIT_CWD ?? process.cwd(), out));diff --git a/packages/daemon/src/cli.ts b/packages/daemon/src/cli.tsindex 06e2a8a..798d8df 100644--- a/packages/daemon/src/cli.ts+++ b/packages/daemon/src/cli.ts@@ -1,9 +1,36 @@#!/usr/bin/env node+import { existsSync } from "node:fs";+import { fileURLToPath } from "node:url";import { loadConfig } from "./config.ts";+import { APPROVAL_GUARD, bundledMcpCli } from "./connectors.ts";import { startDaemon, startupMessage } from "./daemon.ts";+import { resolveEngramBin, runtimeDir } from "./runtime.ts";+import { IDENTITY_SOURCE } from "./white-label.ts";const log = (line: string) => process.stderr.write(`${new Date().toISOString()} ${line}\n`);+/**+ * `--self-check`: resolves the files the daemon runs on, without starting anything or+ * using the network, prints them as JSON, and exits 1 when one is missing.+ */+function selfCheck(): void {+ const config = loadConfig();+ const runtime = runtimeDir();+ const report = {+ runtime,+ uiDir: config.uiDir,+ gentleShell: config.agentArgs[0],+ engineCli: bundledMcpCli().args[0],+ approvalGuard: APPROVAL_GUARD,+ identity: fileURLToPath(IDENTITY_SOURCE),+ engramBin: runtime ? resolveEngramBin(process.env, runtime) : undefined,+ };+ const required = [report.gentleShell, report.engineCli, report.approvalGuard, report.identity];+ const ok = required.every((path) => path !== undefined && existsSync(path));+ process.stdout.write(`${JSON.stringify({ ok, ...report }, null, 2)}\n`);+ process.exit(ok ? 0 : 1);+}+async function main(): Promise<void> {const config = loadConfig();const daemon = await startDaemon({@@ -35,6 +62,8 @@ async function main(): Promise<void> {process.on("SIGTERM", () => shutdown("SIGTERM"));}+if (process.argv.includes("--self-check")) selfCheck();+main().catch((error: Error) => {log(`failed to start: ${error.message}`);process.exit(1);diff --git a/packages/daemon/src/config.ts b/packages/daemon/src/config.tsindex b7e1205..468c564 100644--- a/packages/daemon/src/config.ts+++ b/packages/daemon/src/config.ts@@ -3,6 +3,7 @@ import { createRequire } from "node:module";import { homedir } from "node:os";import { join, resolve } from "node:path";import { fileURLToPath } from "node:url";+import { runtimeDir, runtimeModules } from "./runtime.ts";export interface DotConfig {port: number;@@ -22,8 +23,17 @@ export interface DotConfig {const DEFAULT_UI_DIR = fileURLToPath(new URL("../../ui/dist/app", import.meta.url));-/** Path of the Gentle Shell launcher bundled with the daemon (the `gentle-pi` dependency). */-export function bundledGentleShell(): string {+/**+ * Path of the Gentle Shell launcher bundled with the daemon (the `gentle-pi` dependency),+ * from the runtime's `node_modules` in an installed app.+ */+export function bundledGentleShell(env: NodeJS.ProcessEnv = process.env): string {+ const runtime = runtimeDir(env);+ if (runtime) {+ const bin = join(runtimeModules(runtime), "gentle-pi", "bin", "gentle-shell.mjs");+ if (existsSync(bin)) return bin;+ throw new Error(`The bundled assistant engine is missing from ${runtimeModules(runtime)}.`);+ }const require = createRequire(import.meta.url);for (const dir of require.resolve.paths("gentle-pi") ?? []) {const bin = join(dir, "gentle-pi", "bin", "gentle-shell.mjs");@@ -32,6 +42,12 @@ export function bundledGentleShell(): string {throw new Error("The bundled assistant engine is missing. Run `pnpm install`.");}+/** The web UI: the runtime's `ui/` in an installed app, the UI package's build otherwise. */+function uiDirOf(env: NodeJS.ProcessEnv): string {+ const runtime = runtimeDir(env);+ return runtime ? join(runtime, "ui") : DEFAULT_UI_DIR;+}+function expandHome(path: string): string {return path === "~" || path.startsWith("~/") ? join(homedir(), path.slice(1)) : path;}@@ -77,7 +93,7 @@ function agentConfig(env: NodeJS.ProcessEnv, dataDir: string) {agentHome: undefined,};if (env.GENTLE_DOT_AGENT_BIN) return { agentCommand: env.GENTLE_DOT_AGENT_BIN, agentArgs: [], agentHome };- return { agentCommand: process.execPath, agentArgs: [bundledGentleShell()], agentHome };+ return { agentCommand: process.execPath, agentArgs: [bundledGentleShell(env)], agentHome };}/** Resolves configuration from environment variables, then `~/.gentle-dot/config.json`, then defaults. */@@ -98,7 +114,7 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): DotConfig {dataDir,workspace,preferredFolder: preferredFolder === workspace ? undefined : preferredFolder,- uiDir: resolve(env.GENTLE_DOT_UI_DIR ?? DEFAULT_UI_DIR),+ uiDir: resolve(env.GENTLE_DOT_UI_DIR ?? uiDirOf(env)),...agentConfig(env, dataDir),allowedOrigins: parseList(env.GENTLE_DOT_ALLOWED_ORIGINS, "GENTLE_DOT_ALLOWED_ORIGINS"),};diff --git a/packages/daemon/src/connectors.ts b/packages/daemon/src/connectors.tsindex 8127a8a..cc70208 100644--- a/packages/daemon/src/connectors.ts+++ b/packages/daemon/src/connectors.ts@@ -26,6 +26,7 @@ import type {import { MAX_CONNECTOR_DRAFTS } from "@gentle-dot/protocol";import { type ScannedServer, scanClientConfigs, valueNotes } from "./connector-import.ts";import { type ConnectorPolicy, draftSecretProblem, POLICY_ENV } from "./extensions/approval-guard.ts";+import { runtimeDir, runtimeModules } from "./runtime.ts";/** A value the user types in the app (a token, client credentials); kept only in the assistant's private state. */export interface SetupField {@@ -798,8 +799,21 @@ export interface McpCli {args: string[];}-/** The command line of the engine bundled with the daemon (`pi-coding-agent`). */-export function bundledMcpCli(): McpCli {+/** The command line of the engine bundled with the daemon (`pi-coding-agent`), from the runtime in an installed app. */+export function bundledMcpCli(env: NodeJS.ProcessEnv = process.env): McpCli {+ const runtime = runtimeDir(env);+ if (runtime) {+ const cli = join(+ runtimeModules(runtime),+ "@earendil-works",+ "pi-coding-agent",+ "dist",+ "bundle",+ "cli.js",+ );+ if (existsSync(cli)) return { command: process.execPath, args: [cli] };+ throw new Error(`The bundled assistant engine is missing from ${runtimeModules(runtime)}.`);+ }const require = createRequire(import.meta.url);for (const dir of require.resolve.paths("@earendil-works/pi-coding-agent") ?? []) {const cli = join(dir, "@earendil-works", "pi-coding-agent", "dist", "bundle", "cli.js");diff --git a/packages/daemon/src/isolation.ts b/packages/daemon/src/isolation.tsindex eaa8bb8..c3da26c 100644--- a/packages/daemon/src/isolation.ts+++ b/packages/daemon/src/isolation.ts@@ -3,12 +3,16 @@ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "nimport { createRequire } from "node:module";import { homedir } from "node:os";import { delimiter, join } from "node:path";+import { resolveEngramBin, runtimeDir } from "./runtime.ts";/*** The folder with the `pi` executable bundled with the daemon. The engine's- * first-run setup needs `pi` on PATH, and a clean machine has none.+ * first-run setup needs `pi` on PATH, and a clean machine has none. An installed+ * app carries a relocatable `pi` in `<runtime>/bin`; pnpm's shim is not relocatable.*/-function bundledBinDir(): string | undefined {+function bundledBinDir(base: NodeJS.ProcessEnv): string | undefined {+ const runtime = runtimeDir(base);+ if (runtime) return join(runtime, "bin");const require = createRequire(import.meta.url);for (const dir of require.resolve.paths("@earendil-works/pi-coding-agent") ?? []) {const bin = join(dir, ".bin");@@ -57,6 +61,9 @@ export function ensureMemoryProject(workspace: string): void {* `GENTLE_DOT_ENGRAM=private` instead runs a memory of its own under the* engine's home, on port 7438 (`GENTLE_DOT_ENGRAM_PORT` overrides it).* Subagents are off (`GENTLE_PI_AGENTS=0`) until S25.+ *+ * An installed app (`GENTLE_DOT_RUNTIME`) also names the Engram binary+ * (`ENGRAM_BIN`, see `resolveEngramBin`), since its PATH has no user folders.*/export function isolatedAgentEnv(base: NodeJS.ProcessEnv, dataDir: string): NodeJS.ProcessEnv {const home = join(dataDir, "home");@@ -71,7 +78,7 @@ export function isolatedAgentEnv(base: NodeJS.ProcessEnv, dataDir: string): NodeXDG_STATE_HOME: join(home, ".local", "state"),};for (const key of INHERITED_HOMES) delete env[key];- const bin = bundledBinDir();+ const bin = bundledBinDir(base);if (bin) {const rest = (base.PATH ?? "").split(delimiter).filter((part) => part && part !== bin);env.PATH = [bin, ...rest].join(delimiter);@@ -87,6 +94,8 @@ export function isolatedAgentEnv(base: NodeJS.ProcessEnv, dataDir: string): Nodeenv.ENGRAM_DATA_DIR =base.GENTLE_DOT_ENGRAM_DATA_DIR || base.ENGRAM_DATA_DIR || join(realHome, ".engram");}+ const runtime = runtimeDir(base);+ if (runtime) env.ENGRAM_BIN = resolveEngramBin(base, runtime, { home: realHome });const gitConfig = join(realHome, ".gitconfig");if (!base.GIT_CONFIG_GLOBAL && existsSync(gitConfig)) env.GIT_CONFIG_GLOBAL = gitConfig;return env;diff --git a/packages/daemon/src/runtime-build.ts b/packages/daemon/src/runtime-build.tsnew file mode 100644index 0000000..3e4126b--- /dev/null+++ b/packages/daemon/src/runtime-build.ts@@ -0,0 +1,98 @@+import { chmodSync, copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";+import { createRequire } from "node:module";+import { join } from "node:path";+import { fileURLToPath } from "node:url";+import { build } from "esbuild";++const PACKAGE = fileURLToPath(new URL("..", import.meta.url));+const LOCKFILE = join(PACKAGE, "..", "..", "pnpm-lock.yaml");+const IMPORTER = "packages/daemon";++/**+ * The exact versions pnpm installed for the daemon's own dependencies, read from+ * the `importers` section of the lockfile; workspace links are left out.+ */+export function lockedDependencies(+ lockfile: string = readFileSync(LOCKFILE, "utf8"),+): Record<string, string> {+ const versions: Record<string, string> = {};+ let section: "importer" | "dependencies" | undefined;+ let name: string | undefined;+ for (const line of lockfile.split("\n")) {+ if (/^ {2}\S/.test(line)) section = line.trim() === `${IMPORTER}:` ? "importer" : undefined;+ else if (section && /^ {4}\S/.test(line))+ section = line.trim() === "dependencies:" ? "dependencies" : "importer";+ else if (section === "dependencies" && /^ {6}\S/.test(line))+ name = line.trim().slice(0, -1).replace(/^'|'$/g, "");+ else if (section === "dependencies" && name && /^ {8}version: /.test(line)) {+ const version = line.trim().slice("version: ".length).split("(")[0] ?? "";+ if (!version.startsWith("link:")) versions[name] = version;+ }+ }+ if (Object.keys(versions).length === 0) throw new Error(`No ${IMPORTER} dependencies in the lockfile.`);+ return versions;+}++/** A `pi` command that runs the runtime's own Node on the engine, from wherever the runtime folder is. */+export function piWrapper(engineEntry: string): string {+ return `#!/bin/sh+# The engine's \`pi\` command for an installed Gentle Dot runtime (generated by build:runtime).+self=$0+while [ -L "$self" ]; do+ link=$(readlink "$self")+ case $link in+ /*) self=$link ;;+ *) self=$(dirname "$self")/$link ;;+ esac+done+runtime=$(CDPATH= cd -- "$(dirname -- "$self")/.." && pwd -P) || exit 1+exec "$runtime/node/bin/node" "$runtime/daemon/node_modules/${engineEntry}" "$@"+`;+}++/** The engine's `pi` entry inside `node_modules`, from its package's `bin` (its exports hide `package.json`). */+function engineEntry(): string {+ const engine = join("@earendil-works", "pi-coding-agent");+ const require = createRequire(join(PACKAGE, "package.json"));+ for (const dir of require.resolve.paths(engine) ?? []) {+ const manifest = join(dir, engine, "package.json");+ if (!existsSync(manifest)) continue;+ const bin = (JSON.parse(readFileSync(manifest, "utf8")) as { bin?: Record<string, string> }).bin?.pi;+ if (!bin) throw new Error("The engine package has no `pi` command.");+ return `@earendil-works/pi-coding-agent/${bin.replace(/^\.\//, "")}`;+ }+ throw new Error("The assistant engine is missing. Run `pnpm install`.");+}++/**+ * Builds the daemon part of the installed runtime into `outDir`: `daemon/cli.mjs`+ * (the daemon and the protocol bundled; the engine and `ws` external), the files it+ * finds next to itself, a `package.json` for a flat install of the external+ * dependencies, and `bin/pi`. Nothing is installed.+ */+export async function buildRuntime(outDir: string): Promise<void> {+ const daemon = join(outDir, "daemon");+ mkdirSync(join(daemon, "extensions"), { recursive: true });+ mkdirSync(join(outDir, "bin"), { recursive: true });+ const dependencies = lockedDependencies();+ await build({+ entryPoints: [join(PACKAGE, "src", "cli.ts")],+ outfile: join(daemon, "cli.mjs"),+ bundle: true,+ platform: "node",+ format: "esm",+ target: "node24",+ external: Object.keys(dependencies),+ logLevel: "error",+ });+ chmodSync(join(daemon, "cli.mjs"), 0o755);+ // The bundle finds these through `import.meta.url`, as the sources do in `src/`.+ copyFileSync(join(PACKAGE, "src", "identity.md"), join(daemon, "identity.md"));+ copyFileSync(+ join(PACKAGE, "src", "extensions", "approval-guard.ts"),+ join(daemon, "extensions", "approval-guard.ts"),+ );+ const manifest = { name: "gentle-dot-runtime", private: true, type: "module", dependencies };+ writeFileSync(join(daemon, "package.json"), `${JSON.stringify(manifest, null, "\t")}\n`);+ writeFileSync(join(outDir, "bin", "pi"), piWrapper(engineEntry()), { mode: 0o755 });+}diff --git a/packages/daemon/src/runtime.ts b/packages/daemon/src/runtime.tsnew file mode 100644index 0000000..fb7523c--- /dev/null+++ b/packages/daemon/src/runtime.ts@@ -0,0 +1,74 @@+import { execFileSync } from "node:child_process";+import { accessSync, constants, statSync } from "node:fs";+import { homedir } from "node:os";+import { isAbsolute, join, resolve } from "node:path";++/**+ * The installed app's runtime folder (`GENTLE_DOT_RUNTIME`), or undefined in a+ * source checkout. It holds `node/`, `bin/` (`engram`, `pi`),+ * `daemon/` (this bundle and its `node_modules/`) and `ui/`.+ */+export function runtimeDir(env: NodeJS.ProcessEnv = process.env): string | undefined {+ return env.GENTLE_DOT_RUNTIME ? resolve(env.GENTLE_DOT_RUNTIME) : undefined;+}++/** The runtime's flat install of the daemon's external dependencies. */+export function runtimeModules(runtime: string): string {+ return join(runtime, "daemon", "node_modules");+}++/** Where a user's own Engram usually lives, after the login PATH. */+export function engramKnownDirs(home: string): string[] {+ return [join(home, "go", "bin"), "/opt/homebrew/bin", "/usr/local/bin", join(home, ".local", "bin")];+}++const SYSTEM_PATH = "/usr/bin:/bin:/usr/sbin:/sbin";++function isExecutableFile(path: string): boolean {+ try {+ accessSync(path, constants.X_OK);+ return statSync(path).isFile();+ } catch {+ return false;+ }+}++/**+ * The `engram` the user's login shell finds. The app starts with a fixed PATH,+ * so the shell builds the user's own from their profile, starting from the system one.+ */+function loginShellEngram(env: NodeJS.ProcessEnv, home: string): string | undefined {+ try {+ const output = execFileSync(env.SHELL || "/bin/sh", ["-l", "-c", "command -v engram"], {+ env: { ...env, HOME: home, PATH: SYSTEM_PATH },+ encoding: "utf8",+ stdio: ["ignore", "pipe", "ignore"],+ timeout: 5000,+ });+ const found = output.trim().split("\n").at(-1)?.trim() ?? "";+ return isAbsolute(found) && isExecutableFile(found) ? found : undefined;+ } catch {+ return undefined;+ }+}++/**+ * The Engram binary of an installed app: `ENGRAM_BIN`, then an `engram` on the+ * user's login PATH or in the usual folders, so the user's own version keeps+ * serving `~/.engram`, and only then the one the runtime carries.+ */+export function resolveEngramBin(+ env: NodeJS.ProcessEnv,+ runtime: string,+ options: { home?: string; knownDirs?: string[] } = {},+): string {+ if (env.ENGRAM_BIN) return env.ENGRAM_BIN;+ const home = options.home ?? (env.HOME || homedir());+ const fromLogin = loginShellEngram(env, home);+ if (fromLogin) return fromLogin;+ for (const dir of options.knownDirs ?? engramKnownDirs(home)) {+ const bin = join(dir, "engram");+ if (isExecutableFile(bin)) return bin;+ }+ return join(runtime, "bin", "engram");+}diff --git a/packages/daemon/src/white-label.ts b/packages/daemon/src/white-label.tsindex 836d869..e062645 100644--- a/packages/daemon/src/white-label.ts+++ b/packages/daemon/src/white-label.ts@@ -45,7 +45,7 @@ export function isBlockedInput(text: string): boolean {return /^\s*\/gentle:/i.test(text);}-const IDENTITY_SOURCE = new URL("./identity.md", import.meta.url);+export const IDENTITY_SOURCE = new URL("./identity.md", import.meta.url);/** Writes the identity prompt to `<dataDir>/identity.md` and returns the agent arguments that load it. */export function identityArgs(dataDir: string): string[] {diff --git a/packages/daemon/test/runtime-build.test.ts b/packages/daemon/test/runtime-build.test.tsnew file mode 100644index 0000000..022a442--- /dev/null+++ b/packages/daemon/test/runtime-build.test.ts@@ -0,0 +1,129 @@+import { spawnSync } from "node:child_process";+import {+ copyFileSync,+ existsSync,+ mkdirSync,+ readdirSync,+ readFileSync,+ realpathSync,+ statSync,+ symlinkSync,+ writeFileSync,+} from "node:fs";+import { join } from "node:path";+import { fileURLToPath } from "node:url";+import { beforeAll, describe, expect, it } from "vitest";+import { tempDir } from "./helpers.ts";++const PACKAGE = fileURLToPath(new URL("..", import.meta.url));+const BUILD = join(PACKAGE, "scripts", "build-runtime.ts");+const ENGINE_CLI = join("@earendil-works", "pi-coding-agent", "dist", "bundle", "cli.js");++let out: string;++beforeAll(() => {+ out = tempDir();+ const build = spawnSync(process.execPath, [BUILD, "--out", out], { encoding: "utf8" });+ expect(build.stderr).toBe("");+ expect(build.status).toBe(0);+}, 60_000);++function listFiles(dir: string, prefix = ""): string[] {+ return readdirSync(dir, { withFileTypes: true }).flatMap((entry) =>+ entry.isDirectory()+ ? listFiles(join(dir, entry.name), `${prefix}${entry.name}/`)+ : [`${prefix}${entry.name}`],+ );+}++describe("build:runtime", () => {+ it("emits the daemon part of the runtime layout, without node_modules", () => {+ expect(listFiles(out).sort()).toEqual([+ "bin/pi",+ "daemon/cli.mjs",+ "daemon/extensions/approval-guard.ts",+ "daemon/identity.md",+ "daemon/package.json",+ ]);+ expect(readFileSync(join(out, "daemon", "identity.md"), "utf8")).toBe(+ readFileSync(join(PACKAGE, "src", "identity.md"), "utf8"),+ );+ expect(readFileSync(join(out, "daemon", "extensions", "approval-guard.ts"), "utf8")).toBe(+ readFileSync(join(PACKAGE, "src", "extensions", "approval-guard.ts"), "utf8"),+ );+ });++ it("bundles the protocol and leaves the engine and ws external", () => {+ const bundle = readFileSync(join(out, "daemon", "cli.mjs"), "utf8");+ expect(bundle.startsWith("#!/usr/bin/env node\n")).toBe(true);+ expect(bundle).not.toContain("@gentle-dot/protocol");+ expect(bundle).toMatch(/from "ws"/);+ expect(bundle).toContain('import("@earendil-works/pi-coding-agent")');+ });++ it("lists the external dependencies with the lockfile's exact versions", () => {+ const manifest = JSON.parse(readFileSync(join(out, "daemon", "package.json"), "utf8"));+ expect(manifest).toMatchObject({ private: true, type: "module" });+ expect(manifest.dependencies).toEqual({+ "@earendil-works/pi-ai": "1.0.4",+ "@earendil-works/pi-coding-agent": "1.0.4",+ "@earendil-works/pi-tui": "1.0.4",+ "gentle-pi": "4.0.0",+ ws: "8.22.0",+ });+ });++ it("runs its self-check from the output with the engine resolved inside it", () => {+ symlinkSync(join(PACKAGE, "node_modules"), join(out, "daemon", "node_modules"));+ const check = spawnSync(process.execPath, [join(out, "daemon", "cli.mjs"), "--self-check"], {+ encoding: "utf8",+ env: {+ PATH: "/usr/bin:/bin",+ HOME: tempDir(),+ GENTLE_DOT_DATA_DIR: tempDir(),+ GENTLE_DOT_RUNTIME: out,+ ENGRAM_BIN: "/x/engram",+ },+ });+ expect(check.stderr).toBe("");+ expect(check.status).toBe(0);+ const report = JSON.parse(check.stdout);+ const real = realpathSync(out);+ expect(report).toMatchObject({+ ok: true,+ runtime: out,+ uiDir: join(out, "ui"),+ gentleShell: join(out, "daemon", "node_modules", "gentle-pi", "bin", "gentle-shell.mjs"),+ engineCli: join(out, "daemon", "node_modules", ENGINE_CLI),+ engramBin: "/x/engram",+ });+ expect(realpathSync(report.approvalGuard)).toBe(join(real, "daemon", "extensions", "approval-guard.ts"));+ expect(realpathSync(report.identity)).toBe(join(real, "daemon", "identity.md"));+ });++ it("emits a `pi` wrapper that runs the runtime's node and engine wherever the runtime is", () => {+ expect(statSync(join(out, "bin", "pi")).mode & 0o111).toBe(0o111);+ const moved = tempDir();+ mkdirSync(join(moved, "bin"));+ mkdirSync(join(moved, "node", "bin"), { recursive: true });+ copyFileSync(join(out, "bin", "pi"), join(moved, "bin", "pi"));+ writeFileSync(join(moved, "node", "bin", "node"), '#!/bin/sh\nprintf "%s\\n" "$0" "$@"\n', {+ mode: 0o755,+ });+ const linked = join(tempDir(), "pi");+ symlinkSync(join(moved, "bin", "pi"), linked);+ const real = realpathSync(moved);+ for (const entry of [join(moved, "bin", "pi"), linked]) {+ const run = spawnSync(entry, ["--version", "a b"], { encoding: "utf8" });+ expect(run.status).toBe(0);+ expect(run.stdout.split("\n")).toEqual([+ join(real, "node", "bin", "node"),+ join(real, "daemon", "node_modules", ENGINE_CLI),+ "--version",+ "a b",+ "",+ ]);+ }+ expect(existsSync(join(PACKAGE, "node_modules", ENGINE_CLI))).toBe(true);+ });+});diff --git a/packages/daemon/test/runtime.test.ts b/packages/daemon/test/runtime.test.tsnew file mode 100644index 0000000..6964e88--- /dev/null+++ b/packages/daemon/test/runtime.test.ts@@ -0,0 +1,138 @@+import { chmodSync, mkdirSync, writeFileSync } from "node:fs";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";+import { describe, expect, it } from "vitest";+import { loadConfig } from "../src/config.ts";+import { bundledMcpCli } from "../src/connectors.ts";+import { isolatedAgentEnv } from "../src/isolation.ts";+import { resolveEngramBin } from "../src/runtime.ts";+import { tempDir } from "./helpers.ts";++const PACKAGE = fileURLToPath(new URL("..", import.meta.url));+const ENGINE_CLI = join("@earendil-works", "pi-coding-agent", "dist", "bundle", "cli.js");++function touch(path: string, content = "", mode = 0o644): string {+ mkdirSync(dirname(path), { recursive: true });+ writeFileSync(path, content);+ chmodSync(path, mode);+ return path;+}++/** An installed runtime folder (S29.5) with the engine files the daemon looks for. */+function fakeRuntime(): string {+ const runtime = tempDir();+ const modules = join(runtime, "daemon", "node_modules");+ touch(join(modules, "gentle-pi", "bin", "gentle-shell.mjs"));+ touch(join(modules, ENGINE_CLI));+ mkdirSync(join(runtime, "bin"), { recursive: true });+ return runtime;+}++/** A login shell that answers `command -v engram` with `answer`, or fails when it is undefined. */+function fakeShell(answer: string | undefined): string {+ const body = answer === undefined ? "exit 1" : `echo "Welcome"\necho "${answer}"`;+ return touch(join(tempDir(), "shell"), `#!/bin/sh\n${body}\n`, 0o755);+}++describe("installed runtime (GENTLE_DOT_RUNTIME)", () => {+ it("serves the runtime's web UI, and GENTLE_DOT_UI_DIR still wins", () => {+ const runtime = fakeRuntime();+ const dataDir = tempDir();+ expect(loadConfig({ GENTLE_DOT_DATA_DIR: dataDir, GENTLE_DOT_RUNTIME: runtime }).uiDir).toBe(+ join(runtime, "ui"),+ );+ expect(+ loadConfig({ GENTLE_DOT_DATA_DIR: dataDir, GENTLE_DOT_RUNTIME: runtime, GENTLE_DOT_UI_DIR: "/ui" })+ .uiDir,+ ).toBe("/ui");+ });++ it("runs the launcher and the engine's command line from the runtime's node_modules", () => {+ const runtime = fakeRuntime();+ const modules = join(runtime, "daemon", "node_modules");+ const config = loadConfig({ GENTLE_DOT_DATA_DIR: tempDir(), GENTLE_DOT_RUNTIME: runtime });+ expect(config.agentCommand).toBe(process.execPath);+ expect(config.agentArgs).toEqual([join(modules, "gentle-pi", "bin", "gentle-shell.mjs")]);+ expect(bundledMcpCli({ GENTLE_DOT_RUNTIME: runtime })).toEqual({+ command: process.execPath,+ args: [join(modules, ENGINE_CLI)],+ });+ });++ it("never falls back to the build machine's engine when the runtime lacks it", () => {+ const runtime = tempDir();+ expect(() => loadConfig({ GENTLE_DOT_DATA_DIR: tempDir(), GENTLE_DOT_RUNTIME: runtime })).toThrow(+ join(runtime, "daemon", "node_modules"),+ );+ expect(() => bundledMcpCli({ GENTLE_DOT_RUNTIME: runtime })).toThrow("assistant engine is missing");+ });++ it("puts the runtime's `pi` first on the engine's PATH, never the pnpm one", () => {+ const runtime = fakeRuntime();+ const base = {+ PATH: "/usr/bin:/bin",+ HOME: tempDir(),+ GENTLE_DOT_RUNTIME: runtime,+ ENGRAM_BIN: "/x/engram",+ };+ const env = isolatedAgentEnv(base, tempDir());+ expect(env.PATH).toBe([join(runtime, "bin"), "/usr/bin", "/bin"].join(":"));+ const again = isolatedAgentEnv({ ...base, PATH: env.PATH }, tempDir());+ expect(again.PATH).toBe(env.PATH);+ });++ it("passes the user's ENGRAM_BIN to the engine and keeps the global memory", () => {+ const realHome = tempDir();+ const env = isolatedAgentEnv(+ { PATH: "/bin", HOME: realHome, GENTLE_DOT_RUNTIME: fakeRuntime(), ENGRAM_BIN: "/x/engram" },+ tempDir(),+ );+ expect(env).toMatchObject({ ENGRAM_BIN: "/x/engram", ENGRAM_DATA_DIR: join(realHome, ".engram") });+ });++ it("finds the user's Engram through the login shell before the bundled one", () => {+ const runtime = fakeRuntime();+ const userEngram = touch(join(tempDir(), "engram"), "", 0o755);+ const env = isolatedAgentEnv(+ { PATH: "/bin", HOME: tempDir(), GENTLE_DOT_RUNTIME: runtime, SHELL: fakeShell(userEngram) },+ tempDir(),+ );+ expect(env.ENGRAM_BIN).toBe(userEngram);+ });+});++describe("resolveEngramBin", () => {+ it("prefers ENGRAM_BIN, then the login PATH, then the known folders, then the runtime's own", () => {+ const runtime = fakeRuntime();+ const home = tempDir();+ const known = tempDir();+ const loginEngram = touch(join(tempDir(), "engram"), "", 0o755);+ const failing = fakeShell(undefined);+ const options = { home, knownDirs: [join(home, "missing"), known] };+ expect(resolveEngramBin({ ENGRAM_BIN: "/x/engram", SHELL: failing }, runtime, options)).toBe("/x/engram");+ expect(resolveEngramBin({ SHELL: fakeShell(loginEngram) }, runtime, options)).toBe(loginEngram);+ expect(resolveEngramBin({ SHELL: failing }, runtime, options)).toBe(join(runtime, "bin", "engram"));+ const knownEngram = touch(join(known, "engram"), "", 0o755);+ expect(resolveEngramBin({ SHELL: failing }, runtime, options)).toBe(knownEngram);+ // A login shell answer that is not an executable file is ignored.+ expect(resolveEngramBin({ SHELL: fakeShell("/nowhere/engram") }, runtime, options)).toBe(knownEngram);+ });++ it("looks in ~/go/bin, Homebrew, /usr/local/bin and ~/.local/bin by default", () => {+ const home = tempDir();+ const userEngram = touch(join(home, "go", "bin", "engram"), "", 0o755);+ expect(resolveEngramBin({ SHELL: fakeShell(undefined) }, fakeRuntime(), { home })).toBe(userEngram);+ });+});++describe("source checkout (no GENTLE_DOT_RUNTIME)", () => {+ it("keeps the workspace UI, the pnpm engine, the pnpm `pi`, and no ENGRAM_BIN", () => {+ const config = loadConfig({ GENTLE_DOT_DATA_DIR: tempDir() });+ expect(config.uiDir).toBe(join(PACKAGE, "..", "ui", "dist", "app"));+ expect(config.agentArgs).toEqual([join(PACKAGE, "node_modules", "gentle-pi", "bin", "gentle-shell.mjs")]);+ expect(bundledMcpCli({}).args).toEqual([join(PACKAGE, "node_modules", ENGINE_CLI)]);+ const env = isolatedAgentEnv({ PATH: "/usr/bin:/bin", HOME: tempDir() }, tempDir());+ expect(env.PATH).toBe([join(PACKAGE, "node_modules", ".bin"), "/usr/bin", "/bin"].join(":"));+ expect(env.ENGRAM_BIN).toBeUndefined();+ });+});diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex cd4d949..b12b022 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -54,6 +54,9 @@ importers:'@types/ws':specifier: ^8.18.2version: 8.18.2+ esbuild:+ specifier: 0.28.2+ version: 0.28.2packages/protocol: {}