A personal assistant that lives on your desktop, remembers what matters, and can use your Mac for you.
TypeScript
fix: isolate the engine's HOME, protect the access token, refuse Claude subscription sign-in, and harden auth and sessions
Alan Buscaglia05000c83200c
diff --git a/README.md b/README.mdindex f1f37d2..c6e9530 100644--- a/README.md+++ b/README.md@@ -17,7 +17,7 @@ pnpm installpnpm dev # builds the UI and starts the daemon on http://127.0.0.1:4317```-The daemon prints a URL that already carries the access token. Open it in a browser.+On a terminal, the daemon prints a URL that already carries the access key; open it in a browser. When its output goes to a file (the desktop app's `~/.gentle-dot/daemon.log`, or `docker logs`), it prints the URL without the key and says where the key is: `~/.gentle-dot/token`.## Desktop app (macOS)@@ -33,7 +33,9 @@ The app puts the Dot on the desktop and an item in the menu bar, and `⌥ Space`## How it works-The daemon starts the agent (`gentle-shell --mode rpc`) as a child process and gives it the Gentle Dot identity. It restarts the agent if it crashes, reopening the same conversation, and translates its events into a small WebSocket protocol for the desktop and web interfaces. Conversations live in `~/.gentle-dot/sessions`; the access key is in `~/.gentle-dot/token`.+The daemon starts the agent (`gentle-shell --mode rpc`) as a child process and gives it the Gentle Dot identity. It restarts the agent if it crashes, reopening the same conversation, and translates its events into a small WebSocket protocol for the desktop and web interfaces. Conversations live in `~/.gentle-dot/sessions`; the access key is in `~/.gentle-dot/token`, and `~/.gentle-dot` is private to your user (mode 0700).++The assistant keeps to its own instance. The agent works in `~/.gentle-dot/workspace` (change it with `GENTLE_DOT_WORKSPACE` or `"workspace"` in `~/.gentle-dot/config.json`), and runs with its own home folder (`~/.gentle-dot/home`) and its own memory server (port 7438, `GENTLE_DOT_ENGRAM_PORT`), so it never writes to your own Gentle Shell, Pi, or Engram setup. It keeps `PATH` and reads your `~/.gitconfig` for your git identity.## Checks@@ -45,3 +47,9 @@ pnpm e2e # Playwright against the daemon with the fake agent```Tests tagged `@real-agent` start the real `gentle-shell`; they are skipped when it is not installed.++To check that a first start writes nothing outside the assistant's instance (it installs the engine's companion packages, so it needs internet access, `engram`, and `lsof`):++```bash+GENTLE_DOT_ISOLATION_PROBE=1 npx vitest run packages/daemon/test/isolation-probe.test.ts+```diff --git a/apps/desktop/src-tauri/src/daemon.rs b/apps/desktop/src-tauri/src/daemon.rsindex 5da0f79..dc662fc 100644--- a/apps/desktop/src-tauri/src/daemon.rs+++ b/apps/desktop/src-tauri/src/daemon.rs@@ -1,8 +1,10 @@//! Attaches to a running daemon or spawns one, and stops what it spawned.use crate::health::check_health;-use std::fs::{self, OpenOptions};-use std::path::PathBuf;+use std::fs::{self, File, OpenOptions};+use std::io;+use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt, PermissionsExt};+use std::path::{Path, PathBuf};use std::process::{Child, Command, Stdio};use std::sync::Mutex;use std::thread;@@ -36,6 +38,16 @@ pub fn launch_spec(env: impl Fn(&str) -> Option<String>, dev: bool) -> LaunchSpe}}+/// Opens `<data_dir>/daemon.log` for appending. The folder is 0700 and the log+/// 0600 (looser modes are repaired) because the daemon's output is private.+pub fn open_private_log(data_dir: &Path) -> io::Result<File> {+ fs::DirBuilder::new().recursive(true).mode(0o700).create(data_dir)?;+ fs::set_permissions(data_dir, fs::Permissions::from_mode(0o700))?;+ let log = OpenOptions::new().create(true).append(true).mode(0o600).open(data_dir.join("daemon.log"))?;+ log.set_permissions(fs::Permissions::from_mode(0o600))?;+ Ok(log)+}+/// Sends SIGTERM, waits up to `grace` for a clean exit, then kills.pub fn stop_child(child: &mut Child, grace: Duration) {if !matches!(child.try_wait(), Ok(None)) {@@ -117,12 +129,7 @@ impl Daemon {}}let spec = launch_spec(|key| std::env::var(key).ok(), cfg!(debug_assertions));- let _ = fs::create_dir_all(&self.data_dir);- let log = OpenOptions::new()- .create(true)- .append(true)- .open(self.data_dir.join("daemon.log"))- .map_err(|e| format!("cannot open daemon.log: {e}"))?;+ let log = open_private_log(&self.data_dir).map_err(|e| format!("cannot open daemon.log: {e}"))?;let child = Command::new(&spec.program).args(&spec.args).envs(spec.envs.iter().map(|(k, v)| (k, v)))@@ -201,6 +208,37 @@ mod tests {assert_eq!(env_value(&spec, "GENTLE_DOT_ALLOWED_ORIGINS"), Some(DEV_ALLOWED_ORIGINS));}+ fn scratch_dir(name: &str) -> PathBuf {+ let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();+ std::env::temp_dir().join(format!("gentle-dot-{name}-{}-{nanos}", std::process::id()))+ }++ fn mode_of(path: &Path) -> u32 {+ fs::metadata(path).unwrap().permissions().mode() & 0o777+ }++ #[test]+ fn daemon_log_is_private_when_created() {+ let dir = scratch_dir("log-new").join("data");+ open_private_log(&dir).unwrap();+ assert_eq!(mode_of(&dir), 0o700);+ assert_eq!(mode_of(&dir.join("daemon.log")), 0o600);+ }++ #[test]+ fn daemon_log_repairs_looser_modes() {+ let dir = scratch_dir("log-old");+ fs::create_dir_all(&dir).unwrap();+ fs::set_permissions(&dir, fs::Permissions::from_mode(0o755)).unwrap();+ fs::write(dir.join("daemon.log"), "old line\n").unwrap();+ fs::set_permissions(dir.join("daemon.log"), fs::Permissions::from_mode(0o644)).unwrap();+ use std::io::Write;+ writeln!(open_private_log(&dir).unwrap(), "new line").unwrap();+ assert_eq!(mode_of(&dir), 0o700);+ assert_eq!(mode_of(&dir.join("daemon.log")), 0o600);+ assert_eq!(fs::read_to_string(dir.join("daemon.log")).unwrap(), "old line\nnew line\n");+ }+#[test]fn stop_child_terminates_with_sigterm() {let mut child = Command::new("/bin/sleep").arg("30").spawn().unwrap();diff --git a/docs/deploy-vps.md b/docs/deploy-vps.mdindex 85c6970..3b76739 100644--- a/docs/deploy-vps.md+++ b/docs/deploy-vps.md@@ -53,7 +53,7 @@ EOFchmod 600 .env```-Fill in one model key. If you prefer to log in to a provider instead of using a key, do it once after step 4 with `docker compose run --rm gentle-dot gentle-shell`; the login is kept in the volume.+Fill in one model key, or leave both empty and sign in from the browser once Gentle Dot is open (step 6): open **Accounts**, or type `/login` in the chat, and choose a subscription or an API key. The sign-in is kept in the volume.For the Caddy option, also add `DOT_USER` and `DOT_PASSWORD_HASH`. Generate the hash with `docker run --rm caddy:2 caddy hash-password --plaintext 'your-password'`, and write every `$` as `$$`.@@ -62,10 +62,10 @@ For the Caddy option, also add `DOT_USER` and `DOT_PASSWORD_HASH`. Generate the```bashdocker compose up -d --buildcurl -s http://127.0.0.1:4317/health # {"ok":true,"agentState":"idle"}-docker compose logs gentle-dot | grep "Gentle Dot is running"+docker compose exec gentle-dot cat /home/dot/.gentle-dot/token```-The log line prints the URL with the access key, `http://127.0.0.1:4317/#token=…`. Keep the part after `#token=`; you will open it with your domain in step 6.+The last command prints the access key; you will open it with your domain in step 6. The logs never show it: `docker compose logs gentle-dot` only says where the key file is.### 5a. HostGator VPS (cPanel/WHM): Apache in front@@ -94,6 +94,8 @@ Caddy obtains the HTTPS certificate on its own and asks for the `DOT_USER` passwOpen `https://dot.example.com/#token=<your access key>`. The browser asks for the web server password first, then the page stores the access key and removes it from the address bar.+If you left the model keys empty in step 3, sign in now: open **Accounts** (or type `/login`), pick a subscription or an API key, and follow the steps on screen.+## Update, back up, roll back```bash@@ -113,14 +115,15 @@ Never run `docker compose down -v`: `-v` deletes the volume with your conversati| The page says the link is not valid | Wrong or old access key. Read it with `docker compose exec gentle-dot cat /home/dot/.gentle-dot/token`. || The page loads but never connects | The proxy does not forward WebSockets (enable `mod_proxy_wstunnel`), or `DOT_DOMAIN` does not match the address you opened, so the Origin check refuses it. || You want no usage metrics | The companion packages send anonymous usage metrics by default. Opt out with `docker compose exec gentle-dot gentle-ai telemetry disable`. |-| "The assistant is restarting" stays on | The agent cannot start; check `docker compose logs gentle-dot` for a missing model key or login. |+| "The assistant is restarting" stays on | The agent cannot start; check `docker compose logs gentle-dot` for the reason. |+| "Connect an AI account first" | No account is connected. Open **Accounts** (or type `/login`) and sign in, or add a model key to `.env` and run `docker compose up -d`. |## Video outline (about 2 minutes)1. "Gentle Dot runs on my Mac. Now let's put it on a HostGator VPS so I can use it from anywhere."2. Create the `dot` subdomain in DNS (step 1).3. `git clone` into `/opt/gentle-dot`, then create `.env` with the domain and the model key (steps 2–3).-4. `docker compose up -d --build`, then `curl` the health check (step 4).+4. `docker compose up -d --build`, `curl` the health check, and read the access key from the container (step 4).5. In WHM: run AutoSSL, add the password file, and drop in the Apache include (step 5a).-6. Open `https://dot.<domain>/#token=…` on a phone: same assistant, same memory.+6. Open `https://dot.<domain>/#token=…` on a phone, and sign in from **Accounts** if there is no model key: same assistant, same memory.7. Close with the safety rules: HTTPS, two locks, an isolated container.diff --git a/e2e/web.spec.ts b/e2e/web.spec.tsindex 4358a9f..2c8fcf3 100644--- a/e2e/web.spec.ts+++ b/e2e/web.spec.ts@@ -76,25 +76,43 @@ test("keeps the conversation after a page reload", async ({ page }) => {await expect(page.locator(".message-assistant").last()).toHaveText("Echo: remember this");});-test("opens accounts with /login and connects and disconnects an API key", async ({ page }) => {+test("opens accounts with /login, offers subscriptions without Claude, and connects an API key", async ({+ page,+}) => {await open(page);await say(page, "/login");const accounts = page.getByRole("region", { name: "Accounts" });await expect(accounts).toBeVisible();- await expect(accounts.getByRole("button", { name: /Sign in with .*Claude Pro\/Max/ })).toBeVisible();+ const useSubscription = accounts.getByRole("button", { name: /^Use a subscription/ });+ const useApiKey = accounts.getByRole("button", { name: /^Use an API key/ });+ await expect(useSubscription).toBeVisible();+ await expect(useApiKey).toBeVisible();++ await useSubscription.click();+ const subscriptions = accounts.getByRole("region", { name: "Use a subscription" });+ await expect(subscriptions.getByRole("button", { name: /^Sign in with .*ChatGPT/ }).first()).toBeVisible();+ // A Claude subscription cannot be used from here, so it is never offered.+ await expect(accounts.getByRole("button", { name: /Claude Pro\/Max/ })).toHaveCount(0);+ await accounts.getByRole("button", { name: "Back", exact: true }).click();++ await useApiKey.click();+ const apiKeys = accounts.getByRole("region", { name: "Use an API key" });await accounts.getByRole("searchbox", { name: "Search providers" }).fill("OpenAI");- const openai = accounts.getByRole("listitem").filter({ has: page.getByText("OpenAI", { exact: true }) });- await openai.getByRole("button", { name: "Use an API key" }).click();+ await apiKeys.getByRole("button", { name: "Use an API key for OpenAI" }).click();const key = accounts.getByLabel("Enter OpenAI API key");await expect(key).toHaveAttribute("type", "password");await key.fill("sk-e2e-not-real");await accounts.getByRole("button", { name: "Continue" }).click();await expect(accounts.getByRole("status")).toHaveText("Connected to OpenAI.");await accounts.getByRole("button", { name: "Back to accounts" }).click();- await accounts.getByRole("searchbox", { name: "Search providers" }).fill("OpenAI");- await expect(openai.getByText("Connected")).toBeVisible();- await openai.getByRole("button", { name: "Sign out" }).click();- await expect(openai.getByText("Connected")).toBeHidden();+ // Back to the API key list; connected accounts are listed on the first step.+ await accounts.getByRole("button", { name: "Back", exact: true }).click();+ const signOut = accounts+ .getByRole("region", { name: "Connected" })+ .getByRole("button", { name: "Sign out of OpenAI" });+ await expect(signOut).toBeVisible();+ await signOut.click();+ await expect(accounts.getByRole("button", { name: "Sign out of OpenAI" })).toHaveCount(0);await accounts.getByRole("button", { name: "Close accounts" }).click();await expect(page.getByRole("textbox", { name: "Message" })).toBeVisible();});diff --git a/packages/daemon/src/auth.ts b/packages/daemon/src/auth.tsindex fa8fa11..f953290 100644--- a/packages/daemon/src/auth.ts+++ b/packages/daemon/src/auth.ts@@ -76,6 +76,24 @@ export async function createModelAuthRuntime(agentHome: string, cwd: string): Prtype Emit = (payload: ServerPayload) => void;+/** Sign-in methods the assistant never offers: a Claude subscription cannot be used legally from here. */+const UNSUPPORTED_METHODS: Readonly<Record<string, AuthMethod>> = { anthropic: "oauth" };++const isUnsupported = (providerId: string, method: AuthMethod) =>+ Object.hasOwn(UNSUPPORTED_METHODS, providerId) && UNSUPPORTED_METHODS[providerId] === method;++/** Why a sign-in or sign-out did not start; `message` is safe to show. */+export type AuthRefusal = { code: "auth_busy" | "auth_unsupported" | "unknown_provider"; message: string };++const REFUSALS = {+ busy: { code: "auth_busy", message: "Another sign-in is in progress. Finish or cancel it first." },+ unsupported: {+ code: "auth_unsupported",+ message: "Signing in with a Claude subscription is not supported. Use an Anthropic API key instead.",+ },+ unknown: { code: "unknown_provider", message: "That account is not available." },+} as const satisfies Record<string, AuthRefusal>;+interface Flow {id: string;providerId: string;@@ -108,9 +126,10 @@ export class AuthManager {async providers(): Promise<AuthProvider[]> {const runtime = await this.options.runtime();return runtime.getProviders().flatMap((provider) => {+ const oauth = isUnsupported(provider.id, "oauth") ? undefined : provider.auth.oauth;const methods: AuthMethod[] = [];- if (provider.auth.oauth) methods.push("oauth");- if (provider.auth.apiKey) methods.push("api_key");+ if (oauth) methods.push("oauth");+ if (provider.auth.apiKey && !isUnsupported(provider.id, "api_key")) methods.push("api_key");if (methods.length === 0) return [];const status = runtime.getProviderAuthStatus(provider.id);const entry: AuthProvider = {@@ -119,15 +138,16 @@ export class AuthManager {methods,configured: status.configured,};- if (provider.auth.oauth) entry.oauthName = provider.auth.oauth.name;+ if (oauth) entry.oauthName = oauth.name;if (status.configured && status.source) entry.source = status.source;return [entry];});}- /** Starts a flow; returns false when another sign-in is already running. */- start(owner: object, providerId: string, method: AuthMethod, emit: Emit): boolean {- if (this.flow) return false;+ /** Starts a flow, or says why it did not start. */+ start(owner: object, providerId: string, method: AuthMethod, emit: Emit): AuthRefusal | undefined {+ if (isUnsupported(providerId, method)) return REFUSALS.unsupported;+ if (this.flow) return REFUSALS.busy;const flow: Flow = {id: randomUUID(),providerId,@@ -137,13 +157,13 @@ export class AuthManager {};this.flow = flow;void this.run(flow, method, emit);- return true;+ return undefined;}- /** Delivers the user's answer (or cancellation) to the waiting prompt. */- reply(flowId: string, answer: { value?: string; cancelled?: boolean }): boolean {+ /** Delivers the user's answer (or cancellation) to the prompt of a flow `owner` started. */+ reply(owner: object, flowId: string, answer: { value?: string; cancelled?: boolean }): boolean {const flow = this.flow;- if (!flow || flow.id !== flowId) return false;+ if (!flow || flow.id !== flowId || flow.owner !== owner) return false;if (answer.cancelled) {flow.controller.abort();return true;@@ -161,11 +181,20 @@ export class AuthManager {if (this.flow?.owner === owner) this.flow.controller.abort();}- async logout(providerId: string): Promise<void> {+ /** Signs out of a listed provider, or says why not. */+ async logout(providerId: string): Promise<AuthRefusal | undefined> {const runtime = await this.options.runtime();+ if (!runtime.getProviders().some((provider) => provider.id === providerId)) return REFUSALS.unknown;await runtime.logout(providerId);this.log(`signed out of ${providerId}`);this.onCredentialsChanged();+ return undefined;+ }++ /** True when at least one provider has a credential. */+ async hasAccount(): Promise<boolean> {+ const runtime = await this.options.runtime();+ return runtime.getProviders().some((provider) => runtime.getProviderAuthStatus(provider.id).configured);}private async run(flow: Flow, method: AuthMethod, emit: Emit): Promise<void> {diff --git a/packages/daemon/src/bridge.ts b/packages/daemon/src/bridge.tsindex 3a7d59e..b47403f 100644--- a/packages/daemon/src/bridge.ts+++ b/packages/daemon/src/bridge.ts@@ -111,17 +111,34 @@ export class DotBridge {await this.dispatch(client, message);} catch (error) {this.log(`command ${message.type} failed: ${(error as Error).message}`);- const unavailable = this.supervisor.state !== "ready";- this.deliver(client, {- type: "error",- code: unavailable ? "agent_unavailable" : "command_failed",- message: unavailable- ? "The assistant is restarting. Try again in a moment."- : "That did not work. Please try again.",- });+ if (this.supervisor.state !== "ready") {+ this.deliver(client, {+ type: "error",+ code: "agent_unavailable",+ message: "The assistant is restarting. Try again in a moment.",+ });+ } else if (message.type === "send" && !(await this.hasAccount())) {+ this.deliver(client, {+ type: "error",+ code: "no_account",+ message: "Connect an AI account first: open Accounts or type /login.",+ });+ } else {+ this.deliver(client, {+ type: "error",+ code: "command_failed",+ message: "That did not work. Please try again.",+ });+ }}}+ /** True when an account is connected, or when that cannot be told. */+ private async hasAccount(): Promise<boolean> {+ if (!this.options.auth) return true;+ return this.options.auth.hasAccount().catch(() => true);+ }+private async dispatch(client: BridgeClient, message: ClientMessage): Promise<void> {switch (message.type) {case "hello":@@ -207,21 +224,14 @@ export class DotBridge {await this.sendProviders(client);return;case "auth_login": {- const auth = this.requireAuth();- const started = auth.start(client, message.providerId, message.method, (payload) =>+ const refused = this.requireAuth().start(client, message.providerId, message.method, (payload) =>this.deliver(client, payload),);- if (!started) {- this.deliver(client, {- type: "error",- code: "auth_busy",- message: "Another sign-in is in progress. Finish or cancel it first.",- });- }+ if (refused) this.deliver(client, { type: "error", ...refused });return;}case "auth_reply":- if (!this.requireAuth().reply(message.flowId, message)) {+ if (!this.requireAuth().reply(client, message.flowId, message)) {this.deliver(client, {type: "error",code: "auth_flow_not_found",@@ -229,9 +239,11 @@ export class DotBridge {});}return;- case "auth_logout":- await this.requireAuth().logout(message.providerId);+ case "auth_logout": {+ const refused = await this.requireAuth().logout(message.providerId);+ if (refused) this.deliver(client, { type: "error", ...refused });return;+ }case "profiles_list":await this.sendProfiles(client);return;diff --git a/packages/daemon/src/cli.ts b/packages/daemon/src/cli.tsindex b10df40..3bbd809 100644--- a/packages/daemon/src/cli.ts+++ b/packages/daemon/src/cli.ts@@ -1,6 +1,6 @@#!/usr/bin/env nodeimport { loadConfig } from "./config.ts";-import { startDaemon } from "./daemon.ts";+import { startDaemon, startupMessage } from "./daemon.ts";const log = (line: string) => process.stderr.write(`${new Date().toISOString()} ${line}\n`);@@ -18,7 +18,7 @@ async function main(): Promise<void> {allowedOrigins: config.allowedOrigins,log,});- process.stdout.write(`Gentle Dot is running at ${daemon.url}\n`);+ process.stdout.write(`${startupMessage(daemon.url, config.dataDir, process.stdout.isTTY === true)}\n`);let closing = false;const shutdown = (signal: string) => {diff --git a/packages/daemon/src/config.ts b/packages/daemon/src/config.tsindex e8b45bf..a5d7aab 100644--- a/packages/daemon/src/config.ts+++ b/packages/daemon/src/config.ts@@ -87,8 +87,12 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): DotConfig {: parsePort(file.port ?? 4317, "config.json"),host: env.GENTLE_DOT_HOST ?? "127.0.0.1",dataDir,+ // The engine reads project settings from its workspace, so it is never the home folder by default.workspace: resolve(- expandHome(env.GENTLE_DOT_WORKSPACE ?? (typeof file.workspace === "string" ? file.workspace : "~")),+ expandHome(+ env.GENTLE_DOT_WORKSPACE ??+ (typeof file.workspace === "string" ? file.workspace : join(dataDir, "workspace")),+ ),),uiDir: resolve(env.GENTLE_DOT_UI_DIR ?? DEFAULT_UI_DIR),...agentConfig(env, dataDir),diff --git a/packages/daemon/src/conversations.ts b/packages/daemon/src/conversations.tsindex 338a644..6dfa45e 100644--- a/packages/daemon/src/conversations.ts+++ b/packages/daemon/src/conversations.ts@@ -1,4 +1,4 @@-import { closeSync, existsSync, openSync, readdirSync, readSync, statSync } from "node:fs";+import { closeSync, existsSync, openSync, readdirSync, readSync, realpathSync, statSync } from "node:fs";import { join, relative, resolve, sep } from "node:path";import type { Activity, ConversationSummary, HistoryMessage } from "@gentle-dot/protocol";import { describeTool, textOf } from "./presentation.ts";@@ -36,13 +36,18 @@ export function conversationIdOf(sessionDir: string, sessionFile: string): strinreturn relative(sessionDir, sessionFile).split(sep).join("/");}-/** Resolves a client-supplied id to a session file inside `sessionDir`, or undefined. */+/**+ * Resolves a client-supplied id to a session file inside `sessionDir`, or+ * undefined. Symlinks are followed before the check, so none can lead outside.+ */export function resolveConversation(sessionDir: string, id: string): string | undefined {if (!id.endsWith(".jsonl") || id.includes("\0")) return undefined;const root = resolve(sessionDir);const path = resolve(root, id);- if (!path.startsWith(root + sep)) return undefined;- return existsSync(path) && statSync(path).isFile() ? path : undefined;+ if (!path.startsWith(root + sep) || !existsSync(path)) return undefined;+ const real = realpathSync(path);+ if (!real.startsWith(realpathSync(root) + sep)) return undefined;+ return statSync(real).isFile() ? path : undefined;}function titleOf(path: string): string {diff --git a/packages/daemon/src/daemon.ts b/packages/daemon/src/daemon.tsindex 73ead06..e525d32 100644--- a/packages/daemon/src/daemon.ts+++ b/packages/daemon/src/daemon.ts@@ -1,5 +1,5 @@import { randomBytes, timingSafeEqual } from "node:crypto";-import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";+import { chmodSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";import { createServer, type IncomingMessage, type ServerResponse } from "node:http";import type { AddressInfo } from "node:net";import { extname, join, resolve, sep } from "node:path";@@ -7,6 +7,7 @@ import { type ClientMessage, CloseCode, PROTOCOL_VERSION, parseClientMessage } fimport { type WebSocket, WebSocketServer } from "ws";import { AuthManager, type AuthRuntime, createModelAuthRuntime, resolveAgentHome } from "./auth.ts";import { type BridgeClient, DotBridge } from "./bridge.ts";+import { ensurePrivateDir, isolatedAgentEnv } from "./isolation.ts";import { defaultImportPath, ProfileStore } from "./profiles.ts";import { AgentSupervisor } from "./supervisor.ts";import { identityArgs } from "./white-label.ts";@@ -55,11 +56,15 @@ const CONTENT_TYPES: Record<string, string> = {".woff2": "font/woff2",};-/** Reads the access token from `<dataDir>/token`, creating a random one (mode 0600) when absent. */+/**+ * Reads the access token from `<dataDir>/token`, creating a random one when+ * absent. The data folder is kept at 0700 and the token at 0600.+ */export function ensureToken(dataDir: string): string {- mkdirSync(dataDir, { recursive: true, mode: 0o700 });+ ensurePrivateDir(dataDir);const file = join(dataDir, "token");if (existsSync(file)) {+ chmodSync(file, 0o600);const existing = readFileSync(file, "utf8").trim();if (existing.length >= 32) return existing;}@@ -68,13 +73,25 @@ export function ensureToken(dataDir: string): string {return token;}+/**+ * The line printed at startup. The access key is shown only on an interactive+ * terminal; redirected output (a log file, `docker logs`) says where it is instead.+ */+export function startupMessage(url: string, dataDir: string, interactive: boolean): string {+ if (interactive) return `Gentle Dot is running at ${url}`;+ return `Gentle Dot is running at ${url.split("#")[0]} (the access key is in ${join(dataDir, "token")})`;+}+export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {const log = options.log ?? (() => {});const token = ensureToken(options.dataDir);- const agentEnv = { ...(options.agentEnv ?? process.env) };+ mkdirSync(options.workspace, { recursive: true, mode: 0o700 });+ let agentEnv = { ...(options.agentEnv ?? process.env) };const homeArgs: string[] = [];if (options.agentHome) {homeArgs.push("--home", options.agentHome);+ // The engine also writes under the home folder; it gets one of its own.+ agentEnv = isolatedAgentEnv(agentEnv, options.dataDir);agentEnv.GENTLE_PI_CONFIG_HOME = join(options.dataDir, "gentle-ai");}const supervisor = new AgentSupervisor({diff --git a/packages/daemon/src/isolation.ts b/packages/daemon/src/isolation.tsnew file mode 100644index 0000000..04ac196--- /dev/null+++ b/packages/daemon/src/isolation.ts@@ -0,0 +1,44 @@+import { chmodSync, existsSync, mkdirSync } from "node:fs";+import { homedir } from "node:os";+import { join } from "node:path";++/** Creates `path` with mode 0700, and tightens it to 0700 when it already exists. */+export function ensurePrivateDir(path: string): void {+ mkdirSync(path, { recursive: true, mode: 0o700 });+ chmodSync(path, 0o700);+}++/** Variables that could point the engine back at the user's own setup. */+const INHERITED_HOMES = ["PI_CODING_AGENT_DIR", "GENTLE_PI_AGENT_HOME", "GENTLE_SHELL_CONFIG", "ENGRAM_URL"];++/**+ * The assistant's own memory server port. Engram ties a server to the HOME+ * that started it and refuses one started from another HOME, so the user's+ * server (port 7437) can be used by neither side once the homes differ.+ */+export const ASSISTANT_ENGRAM_PORT = "7438";++/**+ * The engine's environment: its own HOME (`<dataDir>/home`, mode 0700) with+ * the XDG folders under it, because parts of the engine write to fixed places+ * under the home folder, and its own memory server port. PATH is kept, and so+ * is the user's git identity, through `GIT_CONFIG_GLOBAL` pointing at their+ * real `~/.gitconfig`. `GENTLE_DOT_ENGRAM_PORT` overrides the memory port.+ */+export function isolatedAgentEnv(base: NodeJS.ProcessEnv, dataDir: string): NodeJS.ProcessEnv {+ const home = join(dataDir, "home");+ ensurePrivateDir(home);+ const env: NodeJS.ProcessEnv = {+ ...base,+ HOME: home,+ XDG_CONFIG_HOME: join(home, ".config"),+ XDG_DATA_HOME: join(home, ".local", "share"),+ XDG_CACHE_HOME: join(home, ".cache"),+ XDG_STATE_HOME: join(home, ".local", "state"),+ ENGRAM_PORT: base.GENTLE_DOT_ENGRAM_PORT || ASSISTANT_ENGRAM_PORT,+ };+ for (const key of INHERITED_HOMES) delete env[key];+ const gitConfig = join(base.HOME || homedir(), ".gitconfig");+ if (!base.GIT_CONFIG_GLOBAL && existsSync(gitConfig)) env.GIT_CONFIG_GLOBAL = gitConfig;+ return env;+}diff --git a/packages/daemon/src/profiles.ts b/packages/daemon/src/profiles.tsindex a6f6ea2..888c8c9 100644--- a/packages/daemon/src/profiles.ts+++ b/packages/daemon/src/profiles.ts@@ -3,17 +3,19 @@ import {closeSync,constants,existsSync,+ fchmodSync,mkdirSync,openSync,readdirSync,readFileSync,+ realpathSync,renameSync,rmSync,statSync,writeFileSync,} from "node:fs";import { homedir } from "node:os";-import { basename, dirname, join } from "node:path";+import { basename, dirname, join, sep } from "node:path";import {type AuthProvider,isThinkingLevel,@@ -145,12 +147,14 @@ export function serializeProfilesFile(file: ProfilesFile): string {const jsonText = (value: unknown) => `${JSON.stringify(value, null, 2)}\n`;-/** Replaces a file through a sibling temp file (mode 0600) and a rename, so readers never see a partial file. */-export function writeFileAtomic(path: string, text: string): void {+/** Replaces a file through a sibling temp file (mode 0600 by default) and a rename, so readers never see a partial file. */+export function writeFileAtomic(path: string, text: string, mode = 0o600): void {mkdirSync(dirname(path), { recursive: true });const temporary = join(dirname(path), `.${basename(path)}.${randomUUID()}.tmp`);- const fd = openSync(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, 0o600);+ const fd = openSync(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, mode);try {+ // The process umask may have narrowed the creation mode.+ fchmodSync(fd, mode);writeFileSync(fd, text);} finally {closeSync(fd);@@ -171,6 +175,19 @@ function readText(path: string): string | undefined {}}+/** A file's text and permission bits, so it can be put back exactly; undefined when it does not exist. */+type Snapshot = { text: string; mode: number } | undefined;++function snapshot(path: string): Snapshot {+ const text = readText(path);+ return text === undefined ? undefined : { text, mode: statSync(path).mode & 0o777 };+}++function restore(path: string, saved: Snapshot): void {+ if (saved === undefined) rmSync(path, { force: true });+ else writeFileAtomic(path, saved.text, saved.mode);+}+/** Reads a JSON object file; missing is `{}`, anything else that is not an object throws `code`. */function readObject(path: string, code: ProfileErrorCode): Record<string, unknown> {const text = readText(path);@@ -339,31 +356,33 @@ export class ProfileStore {/*** Applies a profile the way the engine does: the active marker, then- * models.json, then subagents.json `model_profiles` (omitted agents cleared),- * then the main assistant's defaults in settings.json. Agent files are never- * rewritten. Any failure restores all four files. Returns the main assistant- * route when the profile sets its model.+ * models.json, then subagents.json `model_profiles` and the `model:` and+ * `thinking:` frontmatter of the assistant's own agent files (omitted agents+ * cleared), then the main assistant's defaults in settings.json. Any failure+ * restores every file with its mode. Returns the main assistant route when+ * the profile sets its model.*/apply(name: string): Promise<RoleRoute | undefined> {return this.enqueue(async () => {const file = this.read();const roles = requireExisting(file, name);const paths = [this.storePath, this.modelsPath, this.subagentsPath, this.settingsPath];- const before = paths.map(readText);+ const agents = ownAgentFiles(this.options.agentHome);+ const saved = new Map([...paths, ...agents.map((agent) => agent.path)].map((p) => [p, snapshot(p)]));try {writeFileAtomic(this.storePath, serializeProfilesFile({ ...file, active: name }));writeFileAtomic(this.modelsPath, jsonText(roles));this.writeAgentRoutes(roles);+ for (const agent of agents) {+ const next = updateFrontmatterRouting(agent.text, roles[agent.name]);+ if (next !== agent.text) writeFileAtomic(agent.path, next, agent.mode);+ }const orchestrator = roles[ORCHESTRATOR];if (!orchestrator?.model) return undefined;await this.writeOrchestrator(orchestrator);return { ...orchestrator };} catch (error) {- paths.forEach((path, i) => {- const text = before[i];- if (text === undefined) rmSync(path, { force: true });- else writeFileAtomic(path, text);- });+ for (const [path, before] of saved) restore(path, before);throw error;}});@@ -524,6 +543,81 @@ export function roleLabel(id: string): string {return label || "Helper";}+/** One agent file whose frontmatter routing the assistant may rewrite; `path` is its real path. */+interface AgentFile {+ path: string;+ name: string;+ text: string;+ mode: number;+}++/**+ * The agent files of the assistant's own engine home whose frontmatter routes+ * a model: top-level `.md` files in `<home>/agents` and `<home>/subagents`, named+ * the way the engine names them (`package.name` or `name`). A file whose real+ * path is anywhere else (a symlink, or a linked folder) is never included.+ */+function ownAgentFiles(agentHome: string): AgentFile[] {+ let home: string;+ try {+ home = realpathSync(agentHome);+ } catch {+ return [];+ }+ const files: AgentFile[] = [];+ for (const folder of ["agents", "subagents"]) {+ const dir = join(agentHome, folder);+ const allowed = join(home, folder) + sep;+ if (!existsSync(dir)) continue;+ for (const entry of readdirSync(dir).sort()) {+ if (!entry.toLowerCase().endsWith(".md") || entry.toLowerCase().endsWith(".chain.md")) continue;+ let path: string;+ try {+ path = realpathSync(join(dir, entry));+ } catch {+ continue;+ }+ if (!path.startsWith(allowed) || path.slice(allowed.length).includes(sep)) continue;+ const stat = statSync(path);+ const text = stat.isFile() ? readText(path) : undefined;+ const name = text === undefined ? undefined : engineAgentName(text);+ if (text === undefined || !name || name === ORCHESTRATOR || REVIEW_ROLES.includes(name)) continue;+ files.push({ path, name, text, mode: stat.mode & 0o777 });+ }+ }+ return files;+}++function engineAgentName(text: string): string | undefined {+ const name = /^name:\s*["']?([^"'\n]+)["']?\s*$/m.exec(text)?.[1]?.trim();+ if (!name) return undefined;+ const pkg = /^package:\s*["']?([^"'\n]+)["']?\s*$/m.exec(text)?.[1]?.trim();+ return pkg ? `${pkg}.${name}` : name;+}++/**+ * Sets or clears the top-level `model:` and `thinking:` frontmatter lines, as+ * the engine's `updateFrontmatterRouting` does (placed after `description:`,+ * or after the first line).+ */+export function updateFrontmatterRouting(content: string, route: RoleRoute | undefined): string {+ if (!content.startsWith("---\n")) return content;+ const end = content.indexOf("\n---", 4);+ if (end === -1) return content;+ const lines = content+ .slice(4, end)+ .split("\n")+ .filter((line) => !line.startsWith("model:") && !line.startsWith("thinking:"));+ const routing: string[] = [];+ if (route?.model) routing.push(`model: ${route.model}`);+ if (route?.thinking) routing.push(`thinking: ${route.thinking}`);+ if (routing.length > 0) {+ const description = lines.findIndex((line) => line.startsWith("description:"));+ lines.splice(description >= 0 ? description + 1 : Math.min(1, lines.length), 0, ...routing);+ }+ return `---\n${lines.join("\n")}${content.slice(end)}`;+}+/** Agent names the engine discovers in `<home>/agents` and `<home>/subagents` (top-level `.md`, frontmatter `name:`). */function agentNames(agentHome: string): string[] {const names: string[] = [];diff --git a/packages/daemon/src/supervisor.ts b/packages/daemon/src/supervisor.tsindex c973400..01ed5d2 100644--- a/packages/daemon/src/supervisor.ts+++ b/packages/daemon/src/supervisor.ts@@ -70,6 +70,8 @@ export class AgentSupervisor {private readonly pending = new Map<string, Pending>();private readonly listeners = new Set<(event: SupervisorEvent) => void>();private nextId = 0;+ /** Count of `agent_settled` records seen, to order them against prompt responses. */+ private settledRuns = 0;private attempts = 0;private spawnedAt = 0;private stopping = false;@@ -108,10 +110,13 @@ export class AgentSupervisor {/** Sends a command and resolves with its successful response. */async request(command: AgentRecord): Promise<RpcResponse> {if (this.state !== "ready") throw new Error("Agent is not ready");+ const settledBefore = this.settledRuns;const response = await this.rawRequest(command, this.options.requestTimeoutMs ?? 300_000);+ // The run may already have settled before this response was handled.if (command.type === "prompt" &&- (response.data as { disposition?: string } | undefined)?.disposition === "started"+ (response.data as { disposition?: string } | undefined)?.disposition === "started" &&+ this.settledRuns === settledBefore) {this.busy = true;}@@ -229,6 +234,7 @@ export class AgentSupervisor {}if (record.type === "agent_start") this.busy = true;if (record.type === "agent_settled") {+ this.settledRuns += 1;this.busy = false;void this.refreshSession().catch(() => {});}diff --git a/packages/daemon/test/auth.test.ts b/packages/daemon/test/auth.test.tsindex 8cabbdf..ffb0c34 100644--- a/packages/daemon/test/auth.test.ts+++ b/packages/daemon/test/auth.test.ts@@ -13,7 +13,7 @@ afterEach(async () => {await Promise.all(daemons.splice(0).map((d) => d.close()));});-async function setup() {+async function setup(env: NodeJS.ProcessEnv = process.env) {const fake = fakeAuthRuntime();const logs: string[] = [];const dataDir = tempDir();@@ -26,10 +26,15 @@ async function setup() {agentCommand: process.execPath,agentArgs: [FAKE_AGENT],backoffMs: [50],+ agentEnv: env,authRuntime: async () => fake.runtime,log: (line) => logs.push(line),});daemons.push(d);+ return { d, fake, logs, ...(await connect(d)), connect: () => connect(d) };+}++async function connect(d: DotDaemon) {const ws = new WebSocket(`ws://127.0.0.1:${d.port}/ws`);const messages: ServerMessage[] = [];ws.on("message", (data) => messages.push(JSON.parse(String(data)) as ServerMessage));@@ -48,7 +53,7 @@ async function setup() {),);}- return { d, fake, logs, ws, messages, send, find };+ return { ws, messages, send, find };}describe("sign-in", () => {@@ -57,18 +62,36 @@ describe("sign-in", () => {send({ type: "auth_list" });const list = await find("auth_providers");expect(list.providers).toEqual([+ // A Claude subscription is not offered: Anthropic signs in with an API key only.+ { id: "anthropic", name: "Anthropic", methods: ["api_key"], configured: false },+ { id: "openai", name: "OpenAI", methods: ["api_key"], configured: false },{- id: "anthropic",- name: "Anthropic",- methods: ["oauth", "api_key"],- oauthName: "Claude Pro/Max",+ id: "github-copilot",+ name: "GitHub Copilot",+ methods: ["oauth"],+ oauthName: "GitHub Copilot",configured: false,},- { id: "openai", name: "OpenAI", methods: ["api_key"], configured: false },]);expect(list.open).toBeUndefined();});+ it("refuses a Claude subscription sign-in without starting it", async () => {+ const { send, find, fake } = await setup();+ send({ type: "auth_login", providerId: "anthropic", method: "oauth" });+ const error = await find("error");+ expect(error).toMatchObject({+ code: "auth_unsupported",+ message: "Signing in with a Claude subscription is not supported. Use an Anthropic API key instead.",+ });+ await new Promise((resolve) => setTimeout(resolve, 50));+ expect(fake.state.logins).toEqual([]);+ // The refusal does not hold the single sign-in slot.+ send({ type: "auth_login", providerId: "anthropic", method: "api_key" });+ expect((await find("auth_prompt")).prompt.kind).toBe("secret");+ expect(fake.state.logins).toEqual(["anthropic:api_key"]);+ });+it("opens the accounts screen when the user types /login", async () => {const { send, find, messages } = await setup();send({ type: "send", text: "/login" });@@ -80,7 +103,7 @@ describe("sign-in", () => {it("runs a subscription sign-in: link, code prompt, success, refreshed status, and an agent restart", async () => {const { d, send, find } = await setup();const pid = d.supervisor.pid;- send({ type: "auth_login", providerId: "anthropic", method: "oauth" });+ send({ type: "auth_login", providerId: "github-copilot", method: "oauth" });const link = await find("auth_event", (m) => m.event.kind === "auth_url");expect(link.event).toEqual({kind: "auth_url",@@ -96,11 +119,11 @@ describe("sign-in", () => {});send({ type: "auth_reply", flowId: link.flowId, value: "good-code" });const done = await find("auth_done");- expect(done).toMatchObject({ ok: true, providerId: "anthropic", flowId: link.flowId });+ expect(done).toMatchObject({ ok: true, providerId: "github-copilot", flowId: link.flowId });const refreshed = await find("auth_providers", (m) =>- m.providers.some((p) => p.id === "anthropic" && p.configured),+ m.providers.some((p) => p.id === "github-copilot" && p.configured),);- expect(refreshed.providers.find((p) => p.id === "anthropic")?.source).toBe("stored");+ expect(refreshed.providers.find((p) => p.id === "github-copilot")?.source).toBe("stored");await waitFor(() => d.supervisor.pid !== pid && d.supervisor.state === "ready");});@@ -117,7 +140,7 @@ describe("sign-in", () => {it("reports a failed sign-in in plain words", async () => {const { send, find } = await setup();- send({ type: "auth_login", providerId: "anthropic", method: "oauth" });+ send({ type: "auth_login", providerId: "github-copilot", method: "oauth" });const prompt = await find("auth_prompt");send({ type: "auth_reply", flowId: prompt.prompt.flowId, value: "wrong" });const done = await find("auth_done");@@ -127,7 +150,7 @@ describe("sign-in", () => {it("cancels a sign-in and aborts the provider flow", async () => {const { send, find, fake } = await setup();- send({ type: "auth_login", providerId: "anthropic", method: "oauth" });+ send({ type: "auth_login", providerId: "github-copilot", method: "oauth" });const prompt = await find("auth_prompt");send({ type: "auth_reply", flowId: prompt.prompt.flowId, cancelled: true });const done = await find("auth_done");@@ -137,7 +160,7 @@ describe("sign-in", () => {it("runs one sign-in at a time", async () => {const { send, find } = await setup();- send({ type: "auth_login", providerId: "anthropic", method: "oauth" });+ send({ type: "auth_login", providerId: "github-copilot", method: "oauth" });await find("auth_prompt");send({ type: "auth_login", providerId: "openai", method: "api_key" });expect((await find("error")).code).toBe("auth_busy");@@ -145,12 +168,54 @@ describe("sign-in", () => {it("cancels the sign-in when its window disconnects", async () => {const { ws, find, fake } = await setup();- ws.send(JSON.stringify({ type: "auth_login", providerId: "anthropic", method: "oauth" }));+ ws.send(JSON.stringify({ type: "auth_login", providerId: "github-copilot", method: "oauth" }));await find("auth_prompt");ws.close();await waitFor(() => fake.state.aborted);});+ it("only answers a sign-in prompt from the window that started it", async () => {+ const { send, find, connect } = await setup();+ send({ type: "auth_login", providerId: "github-copilot", method: "oauth" });+ const prompt = await find("auth_prompt");+ const other = await connect();+ other.send({ type: "auth_reply", flowId: prompt.prompt.flowId, value: "good-code" });+ expect((await other.find("error")).code).toBe("auth_flow_not_found");+ other.send({ type: "auth_reply", flowId: prompt.prompt.flowId, cancelled: true });+ await waitFor(() => other.messages.filter((m) => m.type === "error").length === 2);+ send({ type: "auth_reply", flowId: prompt.prompt.flowId, value: "good-code" });+ expect(await find("auth_done")).toMatchObject({ ok: true, providerId: "github-copilot" });+ });++ it("refuses to sign out of an account that is not in the list", async () => {+ const { d, send, find, logs } = await setup();+ const pid = d.supervisor.pid;+ send({ type: "auth_logout", providerId: "../../etc" });+ expect(await find("error")).toMatchObject({+ code: "unknown_provider",+ message: "That account is not available.",+ });+ await new Promise((resolve) => setTimeout(resolve, 100));+ expect(d.supervisor.pid).toBe(pid);+ expect(logs.join("\n")).not.toContain("../../etc");+ });++ it("asks to connect an account when a message fails and none is connected", async () => {+ const { send, find, messages, fake } = await setup({ ...process.env, FAKE_AGENT_NO_MODEL: "1" });+ send({ type: "send", text: "hello" });+ expect(await find("error")).toMatchObject({+ code: "no_account",+ message: "Connect an AI account first: open Accounts or type /login.",+ });+ fake.configured.add("openai");+ send({ type: "send", text: "hello again" });+ await waitFor(() => messages.filter((m) => m.type === "error").length === 2);+ expect(messages.filter((m) => m.type === "error").at(-1)).toMatchObject({+ code: "command_failed",+ message: "That did not work. Please try again.",+ });+ });+it("signs out", async () => {const { send, find, fake } = await setup();fake.configured.add("openai");diff --git a/packages/daemon/test/cli.test.ts b/packages/daemon/test/cli.test.tsnew file mode 100644index 0000000..5bfa9ec--- /dev/null+++ b/packages/daemon/test/cli.test.ts@@ -0,0 +1,39 @@+import { spawn } from "node:child_process";+import { readFileSync, statSync } from "node:fs";+import { join } from "node:path";+import { fileURLToPath } from "node:url";+import { describe, expect, it } from "vitest";+import { FAKE_AGENT, tempDir, waitFor } from "./helpers.ts";++const CLI = fileURLToPath(new URL("../src/cli.ts", import.meta.url));++describe("gentle-dot command", () => {+ it("keeps the access key out of redirected output, such as a log file", async () => {+ const dataDir = join(tempDir(), "data");+ const child = spawn(process.execPath, [CLI], {+ env: {+ ...process.env,+ GENTLE_DOT_DATA_DIR: dataDir,+ GENTLE_DOT_PORT: "0",+ GENTLE_DOT_AGENT_BIN: process.execPath,+ GENTLE_DOT_AGENT_ARGS: JSON.stringify([FAKE_AGENT]),+ },+ stdio: ["ignore", "pipe", "pipe"],+ });+ let output = "";+ child.stdout.on("data", (chunk: Buffer) => {+ output += chunk.toString();+ });+ const exited = new Promise((resolve) => child.on("close", resolve));+ try {+ await waitFor(() => output.includes("Gentle Dot is running"), 15_000);+ } finally {+ child.kill("SIGTERM");+ await exited;+ }+ const token = readFileSync(join(dataDir, "token"), "utf8").trim();+ expect(output).not.toContain(token);+ expect(output).toContain(`the access key is in ${join(dataDir, "token")}`);+ expect(statSync(dataDir).mode & 0o777).toBe(0o700);+ });+});diff --git a/packages/daemon/test/config.test.ts b/packages/daemon/test/config.test.tsindex 86becda..8867bb4 100644--- a/packages/daemon/test/config.test.ts+++ b/packages/daemon/test/config.test.ts@@ -14,6 +14,8 @@ describe("loadConfig", () => {dataDir,agentCommand: process.execPath,agentHome: join(dataDir, "agent"),+ // Never the user's home: the engine reads project settings from its workspace.+ workspace: join(dataDir, "workspace"),});expect(config.agentArgs).toHaveLength(1);expect(config.agentArgs[0]).toMatch(/node_modules\/gentle-pi\/bin\/gentle-shell\.mjs$/);diff --git a/packages/daemon/test/conversations.test.ts b/packages/daemon/test/conversations.test.tsnew file mode 100644index 0000000..ffc5505--- /dev/null+++ b/packages/daemon/test/conversations.test.ts@@ -0,0 +1,27 @@+import { mkdirSync, symlinkSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import { describe, expect, it } from "vitest";+import { resolveConversation } from "../src/conversations.ts";+import { tempDir } from "./helpers.ts";++describe("resolveConversation", () => {+ it("resolves a session file inside the sessions folder", () => {+ const sessions = join(tempDir(), "sessions");+ mkdirSync(join(sessions, "nested"), { recursive: true });+ writeFileSync(join(sessions, "nested", "a.jsonl"), "");+ expect(resolveConversation(sessions, "nested/a.jsonl")).toBe(join(sessions, "nested", "a.jsonl"));+ expect(resolveConversation(sessions, "../a.jsonl")).toBeUndefined();+ });++ it("refuses a symlink that leads outside the sessions folder", () => {+ const root = tempDir();+ const sessions = join(root, "sessions");+ mkdirSync(join(root, "elsewhere"), { recursive: true });+ mkdirSync(sessions);+ writeFileSync(join(root, "elsewhere", "secret.jsonl"), "");+ symlinkSync(join(root, "elsewhere", "secret.jsonl"), join(sessions, "link.jsonl"));+ symlinkSync(join(root, "elsewhere"), join(sessions, "dir"));+ expect(resolveConversation(sessions, "link.jsonl")).toBeUndefined();+ expect(resolveConversation(sessions, "dir/secret.jsonl")).toBeUndefined();+ });+});diff --git a/packages/daemon/test/fake-auth-runtime.ts b/packages/daemon/test/fake-auth-runtime.tsindex dc1b4da..d8d5f2e 100644--- a/packages/daemon/test/fake-auth-runtime.ts+++ b/packages/daemon/test/fake-auth-runtime.ts@@ -2,10 +2,10 @@ import type { AuthRuntime } from "../src/auth.ts";type Interaction = Parameters<AuthRuntime["login"]>[2];-/** A stand-in for Pi's ModelRuntime: two providers and scripted sign-in flows. */+/** A stand-in for Pi's ModelRuntime: three providers and scripted sign-in flows. */export function fakeAuthRuntime() {const configured = new Set<string>();- const state = { aborted: false };+ const state = { aborted: false, logins: [] as string[] };const runtime: AuthRuntime = {getProviders: () => [{@@ -14,11 +14,13 @@ export function fakeAuthRuntime() {auth: { apiKey: { name: "API key" }, oauth: { name: "Claude Pro/Max" } },},{ id: "openai", name: "OpenAI", auth: { apiKey: { name: "API key" } } },+ { id: "github-copilot", name: "GitHub Copilot", auth: { oauth: { name: "GitHub Copilot" } } },{ id: "local", name: "Local", auth: {} },],getProviderAuthStatus: (id) =>configured.has(id) ? { configured: true, source: "stored" } : { configured: false },async login(id, type, interaction: Interaction) {+ state.logins.push(`${id}:${type}`);interaction.signal?.addEventListener("abort", () => {state.aborted = true;});diff --git a/packages/daemon/test/fixtures/fake-agent.ts b/packages/daemon/test/fixtures/fake-agent.tsindex 8d1a8ed..561a994 100644--- a/packages/daemon/test/fixtures/fake-agent.ts+++ b/packages/daemon/test/fixtures/fake-agent.ts@@ -7,12 +7,14 @@// "ask:confirm" asks a confirm dialog and echoes the answer// "hang" starts a run that only ends on abort// "crash" starts a run and exits with code 1+// "burst" answers and finishes the run in a single stdout write// The "noreply" command is never answered.// Environment:// FAKE_AGENT_ARGS_FILE write argv as JSON to this file// FAKE_AGENT_BRANDING emit branded startup UI records// FAKE_AGENT_ENV_FILE write selected environment variables as JSON to this file// FAKE_AGENT_COMMANDS_FILE append every model command (set_model, set_thinking_level) as JSONL+// FAKE_AGENT_NO_MODEL refuse every prompt, like an engine with no signed-in account// get_available_models lists MODELS; set_model and set_thinking_level change what// get_state reports, so tests can read the last values back.import { randomUUID } from "node:crypto";@@ -44,7 +46,24 @@ if (process.env.FAKE_AGENT_ARGS_FILE) writeFileSync(process.env.FAKE_AGENT_ARGS_if (process.env.FAKE_AGENT_ENV_FILE) {writeFileSync(process.env.FAKE_AGENT_ENV_FILE,- JSON.stringify({ GENTLE_PI_CONFIG_HOME: process.env.GENTLE_PI_CONFIG_HOME }),+ JSON.stringify(+ Object.fromEntries(+ [+ "GENTLE_PI_CONFIG_HOME",+ "HOME",+ "XDG_CONFIG_HOME",+ "XDG_DATA_HOME",+ "XDG_CACHE_HOME",+ "XDG_STATE_HOME",+ "GIT_CONFIG_GLOBAL",+ "PATH",+ "PI_CODING_AGENT_DIR",+ "GENTLE_SHELL_CONFIG",+ "ENGRAM_PORT",+ "ENGRAM_URL",+ ].map((key) => [key, process.env[key]]),+ ),+ ),);}const sessionDir = argValue("--session-dir") ?? join(process.cwd(), ".fake-sessions");@@ -55,6 +74,8 @@ let sessionFile = "";let messages: Message[] = [];let busy = false;let hanging: (() => void) | undefined;+/** Records collected for one stdout write while a "burst" prompt runs. */+let batch: string[] | undefined;const pendingUi = new Map<string, (rec: Rec) => void>();newSession();@@ -71,7 +92,8 @@ function recordCommand(rec: Rec): void {}function out(rec: Rec): void {- process.stdout.write(`${JSON.stringify(rec)}\n`);+ if (batch) batch.push(`${JSON.stringify(rec)}\n`);+ else process.stdout.write(`${JSON.stringify(rec)}\n`);}function newSession(): void {@@ -199,8 +221,14 @@ function handle(rec: Rec) {case "prompt": {if (busy && !rec.streamingBehavior) return respond(id, "prompt", undefined, "Agent is streaming");if (busy) return respond(id, "prompt", { disposition: "queued" });+ if (process.env.FAKE_AGENT_NO_MODEL) return respond(id, "prompt", undefined, "No model selected");+ if (rec.message === "burst") batch = [];respond(id, "prompt", { disposition: "started" });void run(String(rec.message));+ if (batch) {+ process.stdout.write(batch.join(""));+ batch = undefined;+ }return;}case "steer":diff --git a/packages/daemon/test/gateway.test.ts b/packages/daemon/test/gateway.test.tsindex aabd869..c27add2 100644--- a/packages/daemon/test/gateway.test.ts+++ b/packages/daemon/test/gateway.test.ts@@ -1,9 +1,9 @@-import { mkdirSync, readFileSync, writeFileSync } from "node:fs";+import { chmodSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";import { join } from "node:path";import type { ServerMessage } from "@gentle-dot/protocol";import { afterEach, describe, expect, it } from "vitest";import WebSocket from "ws";-import { type DotDaemon, startDaemon } from "../src/daemon.ts";+import { type DotDaemon, ensureToken, startDaemon, startupMessage } from "../src/daemon.ts";import { HIDDEN_NAMES } from "../src/white-label.ts";import { FAKE_AGENT, tempDir, waitFor } from "./helpers.ts";@@ -269,6 +269,73 @@ describe("own instance", () => {const env = JSON.parse(readFileSync(envFile, "utf8")) as Record<string, string>;expect(env.GENTLE_PI_CONFIG_HOME).toBe(join(dataDir, "gentle-ai"));});++ it("gives the agent its own HOME, XDG folders, and memory server, keeping PATH and the user's git identity", async () => {+ const scratch = tempDir();+ const realHome = join(scratch, "user");+ mkdirSync(realHome);+ writeFileSync(join(realHome, ".gitconfig"), "[user]\n\tname = Someone\n");+ const envFile = join(scratch, "env.json");+ const dataDir = tempDir();+ const d = await startDaemon({+ port: 0,+ host: "127.0.0.1",+ dataDir,+ workspace: join(dataDir, "workspace"),+ uiDir: dataDir,+ agentCommand: process.execPath,+ agentArgs: [FAKE_AGENT],+ agentHome: join(dataDir, "agent"),+ agentEnv: {+ ...process.env,+ HOME: realHome,+ XDG_CONFIG_HOME: join(realHome, ".config"),+ XDG_DATA_HOME: join(realHome, "data"),+ XDG_CACHE_HOME: join(realHome, "cache"),+ XDG_STATE_HOME: join(realHome, "state"),+ PI_CODING_AGENT_DIR: join(realHome, ".pi", "agent"),+ GENTLE_SHELL_CONFIG: join(realHome, ".gentle-shell", "config.json"),+ ENGRAM_URL: "http://127.0.0.1:7437",+ FAKE_AGENT_ENV_FILE: envFile,+ },+ });+ daemons.push(d);+ const env = JSON.parse(readFileSync(envFile, "utf8")) as Record<string, string | undefined>;+ const home = join(dataDir, "home");+ expect(env).toEqual({+ GENTLE_PI_CONFIG_HOME: join(dataDir, "gentle-ai"),+ HOME: home,+ XDG_CONFIG_HOME: join(home, ".config"),+ XDG_DATA_HOME: join(home, ".local", "share"),+ XDG_CACHE_HOME: join(home, ".cache"),+ XDG_STATE_HOME: join(home, ".local", "state"),+ GIT_CONFIG_GLOBAL: join(realHome, ".gitconfig"),+ PATH: process.env.PATH,+ // Engram ties a memory server to the HOME that started it, so the assistant runs its own.+ ENGRAM_PORT: "7438",+ });+ expect(statSync(home).mode & 0o777).toBe(0o700);+ expect(existsSync(join(dataDir, "workspace"))).toBe(true);+ });++ it("keeps the data folder and the access key private, repairing looser modes", () => {+ const dataDir = join(tempDir(), "data");+ mkdirSync(dataDir, { mode: 0o755 });+ chmodSync(dataDir, 0o755);+ writeFileSync(join(dataDir, "token"), `${"k".repeat(43)}\n`, { mode: 0o644 });+ chmodSync(join(dataDir, "token"), 0o644);+ expect(ensureToken(dataDir)).toBe("k".repeat(43));+ expect(statSync(dataDir).mode & 0o777).toBe(0o700);+ expect(statSync(join(dataDir, "token")).mode & 0o777).toBe(0o600);+ });++ it("shows the access key only on an interactive terminal", () => {+ const url = "http://127.0.0.1:4317/#token=secret-token";+ expect(startupMessage(url, "/data", true)).toBe(`Gentle Dot is running at ${url}`);+ const piped = startupMessage(url, "/data", false);+ expect(piped).not.toContain("secret-token");+ expect(piped).toBe("Gentle Dot is running at http://127.0.0.1:4317/ (the access key is in /data/token)");+ });});describe("white label", () => {diff --git a/packages/daemon/test/isolation-probe.test.ts b/packages/daemon/test/isolation-probe.test.tsnew file mode 100644index 0000000..b88a44b--- /dev/null+++ b/packages/daemon/test/isolation-probe.test.ts@@ -0,0 +1,111 @@+// @real-agent isolation probe: starts the daemon with the bundled engine for the+// first time under a seeded temporary HOME and checks that HOME is byte-identical+// afterwards, and that the engine's memory server belongs to the assistant's own+// home. Opt-in (it installs the engine's companion packages and needs internet+// access; it needs `engram` and `lsof` on PATH):+// GENTLE_DOT_ISOLATION_PROBE=1 npx vitest run packages/daemon/test/isolation-probe.test.ts+import { execFileSync, spawn } from "node:child_process";+import { createHash } from "node:crypto";+import { lstatSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";+import { join, relative } from "node:path";+import { fileURLToPath } from "node:url";+import { describe, expect, it } from "vitest";+import { tempDir, waitFor } from "./helpers.ts";++const CLI = fileURLToPath(new URL("../src/cli.ts", import.meta.url));+const ENGRAM_PORT = "17438";+const enabled = process.env.GENTLE_DOT_ISOLATION_PROBE === "1";++/** One hash over every path, type, mode, and file content under `root` (symlinks are not followed). */+function hashTree(root: string): string {+ const hash = createHash("sha256");+ const walk = (dir: string) => {+ for (const name of readdirSync(dir).sort()) {+ const path = join(dir, name);+ const stat = lstatSync(path);+ hash.update(`${relative(root, path)}\0${stat.mode}\0`);+ if (stat.isDirectory()) walk(path);+ else if (stat.isFile()) hash.update(readFileSync(path));+ }+ };+ walk(root);+ return hash.digest("hex");+}++function seed(home: string): void {+ const files: Record<string, string> = {+ ".gentle-shell/config.json": "{}\n",+ ".pi/agent/settings.json": '{ "theme": "dark" }\n',+ ".pi/gentle-ai/models.json": '{ "gentle-ai-worker": { "model": "seed/model" } }\n',+ ".gentle-ai/state.json": '{ "seed": true }\n',+ ".gitconfig": "[user]\n\tname = Seed User\n\temail = [email protected]\n",+ ".config/seed.txt": "xdg config\n",+ };+ for (const [path, text] of Object.entries(files)) {+ mkdirSync(join(home, path, ".."), { recursive: true });+ writeFileSync(join(home, path), text);+ }+}++describe.skipIf(!enabled)("@real-agent isolation probe", () => {+ it("leaves the user's HOME untouched on a first start", { timeout: 300_000 }, async () => {+ const home = tempDir();+ const dataDir = join(tempDir(), "data");+ seed(home);+ const before = hashTree(home);+ const child = spawn(process.execPath, [CLI], {+ env: {+ PATH: process.env.PATH,+ HOME: home,+ XDG_CONFIG_HOME: join(home, ".config"),+ XDG_DATA_HOME: join(home, ".local", "share"),+ XDG_CACHE_HOME: join(home, ".cache"),+ XDG_STATE_HOME: join(home, ".local", "state"),+ GENTLE_DOT_DATA_DIR: dataDir,+ GENTLE_DOT_PORT: "0",+ GENTLE_DOT_ENGRAM_PORT: ENGRAM_PORT,+ },+ stdio: ["ignore", "pipe", "pipe"],+ });+ let output = "";+ child.stdout.on("data", (chunk: Buffer) => {+ output += chunk.toString();+ });+ child.stderr.on("data", (chunk: Buffer) => {+ output += chunk.toString();+ });+ const exited = new Promise<number | null>((resolve) => child.on("close", resolve));+ await waitFor(() => /Gentle Dot is running|failed to start/.test(output), 240_000);+ const port = /127\.0\.0\.1:(\d+)/.exec(output)?.[1];+ const health = (await (await fetch(`http://127.0.0.1:${port}/health`)).json()) as { agentState: string };+ // The engine starts the assistant's own memory server when it loads.+ let memory: { instance_id?: string } | undefined;+ for (let i = 0; i < 60 && !memory; i++) {+ memory = await fetch(`http://127.0.0.1:${ENGRAM_PORT}/health`).then(+ (r) => r.json() as Promise<{ instance_id?: string }>,+ () => new Promise<undefined>((resolve) => setTimeout(resolve, 1000)),+ );+ }+ const ownId = execFileSync("engram", ["instance-id"], {+ env: { PATH: process.env.PATH, HOME: join(dataDir, "home") },+ })+ .toString()+ .trim();+ child.kill("SIGTERM");+ await exited;+ const memoryPid = execFileSync("lsof", ["-t", `-iTCP:${ENGRAM_PORT}`, "-sTCP:LISTEN"])+ .toString()+ .trim();+ if (/^\d+$/.test(memoryPid)) process.kill(Number(memoryPid), "SIGTERM");+ const after = hashTree(home);+ console.log(+ `HOME: ${home}\nagent state: ${health.agentState}\nHOME before: ${before}\nHOME after: ${after}`,+ );+ console.log(`memory server: ${memory?.instance_id}\nassistant home instance: ${ownId}`);+ console.log(output.slice(0, 4000));+ expect(health.agentState).toBe("idle");+ expect(memory?.instance_id).toBe(ownId);+ expect(output).not.toContain("#token=");+ expect(after).toBe(before);+ });+});diff --git a/packages/daemon/test/profiles-gateway.test.ts b/packages/daemon/test/profiles-gateway.test.tsindex 888762c..3cbf80e 100644--- a/packages/daemon/test/profiles-gateway.test.ts+++ b/packages/daemon/test/profiles-gateway.test.ts@@ -149,7 +149,9 @@ describe("profiles over the gateway", () => {defaultModel: "fake-fast",defaultThinkingLevel: "low",});- expect(readFileSync(agentFile, "utf8")).toBe("---\nname: gentle-ai-worker\n---\nWorker\n");+ expect(readFileSync(agentFile, "utf8")).toBe(+ "---\nname: gentle-ai-worker\nmodel: other/big\nthinking: high\n---\nWorker\n",+ );expect(commands()).toEqual([{ type: "set_model", provider: "fake", modelId: "fake-fast", busy: false },{ type: "set_thinking_level", level: "low", busy: false },diff --git a/packages/daemon/test/profiles.test.ts b/packages/daemon/test/profiles.test.tsindex c03f8e0..977188a 100644--- a/packages/daemon/test/profiles.test.ts+++ b/packages/daemon/test/profiles.test.ts@@ -1,10 +1,12 @@import {+ chmodSync,existsSync,mkdirSync,readdirSync,readFileSync,rmdirSync,statSync,+ symlinkSync,utimesSync,writeFileSync,} from "node:fs";@@ -216,11 +218,47 @@ describe("applying a profile", () => {defaultModel: "claude-opus-4",});expect(statSync(modelsPath).mode & 0o777).toBe(0o600);+ // The agent's own frontmatter follows the profile, as the engine's apply does.expect(readFileSync(agentFile, "utf8")).toBe(- "---\nname: gentle-ai-worker\nmodel: old/model\n---\nBody\n",+ "---\nname: gentle-ai-worker\nmodel: openai/gpt-5\nthinking: high\n---\nBody\n",);});+ it("clears the frontmatter routing of agents the profile omits, keeping each file's mode", async () => {+ const { store, agentHome } = setup();+ mkdirSync(join(agentHome, "agents"), { recursive: true });+ mkdirSync(join(agentHome, "subagents"), { recursive: true });+ const explore = join(agentHome, "agents", "explore.md");+ const helper = join(agentHome, "subagents", "helper.md");+ writeFileSync(+ explore,+ "---\nname: gentle-ai-explore\ndescription: d\nmodel: old/m\nthinking: low\n---\nB\n",+ );+ writeFileSync(helper, "---\nname: helper\npackage: kit\n---\nB\n");+ chmodSync(explore, 0o644);+ await store.save("p", { "kit.helper": { model: "x/y" } });+ await store.apply("p");+ expect(readFileSync(explore, "utf8")).toBe("---\nname: gentle-ai-explore\ndescription: d\n---\nB\n");+ expect(statSync(explore).mode & 0o777).toBe(0o644);+ expect(readFileSync(helper, "utf8")).toBe("---\nname: helper\nmodel: x/y\npackage: kit\n---\nB\n");+ });++ it("never writes an agent file whose real path is outside the assistant's agent folders", async () => {+ const { store, agentHome } = setup();+ const outside = join(agentHome, "..", "outside");+ mkdirSync(join(outside, "dir"), { recursive: true });+ mkdirSync(join(agentHome, "agents"), { recursive: true });+ const text = "---\nname: gentle-ai-worker\nmodel: old/model\n---\nB\n";+ writeFileSync(join(outside, "worker.md"), text);+ writeFileSync(join(outside, "dir", "explore.md"), text.replace("worker", "explore"));+ symlinkSync(join(outside, "worker.md"), join(agentHome, "agents", "worker.md"));+ symlinkSync(join(outside, "dir"), join(agentHome, "subagents"));+ await store.save("p", { "gentle-ai-worker": { model: "x/y" } });+ await store.apply("p");+ expect(readFileSync(join(outside, "worker.md"), "utf8")).toBe(text);+ expect(readFileSync(join(outside, "dir", "explore.md"), "utf8")).toBe(text.replace("worker", "explore"));+ });+it("sets the thinking level and drops model_profiles when the profile routes no agent", async () => {const { store, json, write, subagentsPath, settingsPath } = setup();write(subagentsPath, { model_profiles: { "gentle-ai-explore": { model: "old/explore" } } });@@ -243,19 +281,22 @@ describe("applying a profile", () => {expect(readFileSync(settingsPath, "utf8")).toBe(before);});- it("restores every file when a step fails", async () => {- const { store, profilesPath, modelsPath, subagentsPath, settingsPath } = setup();+ it("restores every file, its contents and its mode, when a step fails", async () => {+ const { store, agentHome, profilesPath, modelsPath, subagentsPath, settingsPath } = setup();+ const agentFile = join(agentHome, "agents", "worker.md");+ mkdirSync(join(agentHome, "agents"), { recursive: true });+ writeFileSync(agentFile, "---\nname: gentle-ai-worker\n---\nB\n");await store.save("a", { "gentle-ai-worker": { model: "x/a" } });await store.save("b", { orchestrator: { model: "x/b" }, "gentle-ai-worker": { model: "x/b" } });await store.apply("a");writeFileSync(settingsPath, "{not json");- const before = [profilesPath, modelsPath, subagentsPath, settingsPath].map((p) =>- readFileSync(p, "utf8"),- );+ const paths = [profilesPath, modelsPath, subagentsPath, settingsPath, agentFile];+ chmodSync(settingsPath, 0o644);+ chmodSync(subagentsPath, 0o644);+ chmodSync(agentFile, 0o640);+ const before = paths.map((p) => [readFileSync(p, "utf8"), statSync(p).mode & 0o777]);await expect(store.apply("b")).rejects.toMatchObject({ code: "settings_invalid" });- expect(- [profilesPath, modelsPath, subagentsPath, settingsPath].map((p) => readFileSync(p, "utf8")),- ).toEqual(before);+ expect(paths.map((p) => [readFileSync(p, "utf8"), statSync(p).mode & 0o777])).toEqual(before);});it("waits for the engine's settings lock and takes over a stale one", async () => {diff --git a/packages/daemon/test/supervisor.test.ts b/packages/daemon/test/supervisor.test.tsindex ce0bfa1..5e31410 100644--- a/packages/daemon/test/supervisor.test.ts+++ b/packages/daemon/test/supervisor.test.ts@@ -54,6 +54,14 @@ describe("AgentSupervisor", () => {expect(supervisor.busy).toBe(false);});+ it("is not left busy when the run settles before the prompt response is handled", async () => {+ const { supervisor, events } = track(fakeSupervisor());+ await supervisor.start();+ await supervisor.request({ type: "prompt", message: "burst" });+ expect(events.some((e) => e.type === "agent_settled")).toBe(true);+ expect(supervisor.busy).toBe(false);+ });+it("respawns after a crash, reopens the same conversation, and reports the interruption", async () => {const { supervisor, events } = track(fakeSupervisor());await supervisor.start();