Skip to content

A personal assistant that lives on your desktop, remembers what matters, and can use your Mac for you.

TypeScript

feat(daemon): bring subagents back behind the connector proxy

Alan Buscagliae9869d4495b7
diff --git a/README.md b/README.md
index 5805f2e..7aec5a2 100644
--- a/README.md
+++ b/README.md
@@ -149,9 +149,9 @@ A small Node daemon starts the agent engine (Gentle Shell, `gentle-shell --mode
## Security status
-What already holds: computer control's grant, panic stop, blocklist, rate limit, and risky-action confirmations are enforced by the desktop app, not the agent, and the agent's processes do not inherit the app's macOS permissions. Connectors are reached only through the assistant's own proxy, which hides what their mode does not allow. Approving a connector's action and changing a connector (its mode, connecting, removing, importing) happen only in the desktop app that started the assistant, in native dialogs, over a private channel the agent cannot open; in the browser those controls are read-only. Credentials are typed in the app, never in the chat. On macOS, connector tokens, client secrets, and sign-ins live in the Keychain, in items the signed app creates, and reach the assistant only in memory over that private channel; they are never written to a file, and tokens from older versions move there once. Without the app, connectors that need a token stop working instead of falling back to a file. The connector settings file is signed with a key kept in the Keychain: if anything changes it while Gentle Dot is closed, the app sets it aside at the next start, starts with no connectors, and tells you.
+What already holds: computer control's grant, panic stop, blocklist, rate limit, and risky-action confirmations are enforced by the desktop app, not the agent, and the agent's processes do not inherit the app's macOS permissions. Connectors are reached only through the assistant's own proxy, which hides what their mode does not allow, and that holds for its subagents too: they are back on, reach connectors through the same proxy and approvals, and run with the same file checks as the assistant (set `GENTLE_DOT_SUBAGENTS=off` to turn them off). Approving a connector's action and changing a connector (its mode, connecting, removing, importing) happen only in the desktop app that started the assistant, in native dialogs, over a private channel the agent cannot open; in the browser those controls are read-only. Credentials are typed in the app, never in the chat. On macOS, connector tokens, client secrets, and sign-ins live in the Keychain, in items the signed app creates, and reach the assistant only in memory over that private channel; they are never written to a file, and tokens from older versions move there once. Without the app, connectors that need a token stop working instead of falling back to a file. The connector settings file is signed with a key kept in the Keychain: if anything changes it while Gentle Dot is closed, the app sets it aside at the next start, starts with no connectors, and tells you.
-What does not yet: the agent has a shell, and its shell commands are checked on a best-effort basis only. Started without the app (from a terminal, or in the browser-only setup), the assistant cannot check that signature and loads the settings as they are, with token-based connectors locked. The app cannot yet tell its own Keychain items from ones another program of yours planted. On Linux, tokens go to the system keyring, which any program of yours can read while it is unlocked, and that path is not yet verified on a Linux desktop.
+What does not yet: the agent has a shell, and its shell commands (and its subagents') are checked on a best-effort basis only. Started without the app (from a terminal, or in the browser-only setup), the assistant cannot check that signature and loads the settings as they are, with token-based connectors locked. The app cannot yet tell its own Keychain items from ones another program of yours planted. On Linux, tokens go to the system keyring, which any program of yours can read while it is unlocked, and that path is not yet verified on a Linux desktop.
<div align="right"><a href="#top">Back to top</a></div>
diff --git a/docs/design.md b/docs/design.md
index d5bad80..5319333 100644
--- a/docs/design.md
+++ b/docs/design.md
@@ -9,7 +9,7 @@ Status: design for local development. The VPS deployment is documented, not perf
Goals:
- One assistant, always on, reachable from the desktop (floating Dot, menu bar, global shortcut) and from a web page.
-- The agent behaves exactly like Gentle Shell: same tools, ODD workflow, skills, and Engram memory. Subagents are off until S25 (their child engines do not load the connector approval guard; §4, Connectors).
+- The agent behaves exactly like Gentle Shell: same tools, ODD workflow, skills, Engram memory, and subagents. Subagents reach connectors only through the daemon's MCP proxy, like the engine itself, and load the approval guard too (S25.4; §4, Connectors).
- The user never sees Gentle Shell: no Gentle branding, commands, or terminal in the product surface.
- Everything runs locally first; the same daemon can later run on a VPS (HostGator) with Docker.
@@ -63,7 +63,7 @@ docs/ design, deployment guide, security checklist
- Spawns the bundled engine (`node <gentle-pi>/bin/gentle-shell.mjs --home <dataDir>/agent --mode rpc --session-dir <dataDir>/sessions --append-system-prompt <identity file>`) with `cwd` = the assistant's own workspace, `<dataDir>/workspace`, so the engine never reads a `.pi` project config from the user's home. A custom `workspace` (config or `GENTLE_DOT_WORKSPACE`) is never used as `cwd` and nothing is written there; it is passed as one more `--append-system-prompt` text: "The user's preferred working folder is <path>. Use absolute paths there unless told otherwise."
- Engine home (S35.3, #13): gentle-shell runs its first-run setup (the companion packages) only in a `--home` it created: one that did not exist, or that holds its marker `.gentle-shell-home`. The daemon writes `auth.json` and `mcp.json` there before the engine's first start, so at every start, before writing anything there, it writes that marker into the default `<dataDir>/agent` in gentle-shell's own format (`{"createdBy":"gentle-shell","version":"<gentle-pi version>"}`; gentle-shell only checks that the file exists) unless one is already there. A clean install then runs the setup, and an install left without it recovers on the next start. A home chosen with `GENTLE_DOT_AGENT_HOME` is never marked. Because the folder exists before the engine runs, gentle-shell's own bootstrap (the TUI's `tuiMode` and theme in `settings.json`) is skipped; RPC mode uses neither.
-- Isolation (S12): the child runs with its own `HOME=<dataDir>/home` (0700) and `XDG_CONFIG_HOME`, `XDG_DATA_HOME`, `XDG_CACHE_HOME`, and `XDG_STATE_HOME` under it, plus `GENTLE_PI_CONFIG_HOME=<dataDir>/gentle-ai`. `PATH` is kept, and `GIT_CONFIG_GLOBAL` points at the user's real `~/.gitconfig` when it exists, to keep their git identity. Inherited `PI_CODING_AGENT_DIR`, `GENTLE_PI_AGENT_HOME`, and `GENTLE_SHELL_CONFIG` are removed. `GENTLE_PI_AGENTS=0` turns Gentle Shell's subagents off (no `subagent_*` or `orchestrator_*` tools) until S25. The engine's first run otherwise writes into the real `~` (`~/.gentle-shell`, `~/.pi/agent/pi-pretty`, `~/.gentle-ai`), which `--home` alone does not prevent.
+- Isolation (S12): the child runs with its own `HOME=<dataDir>/home` (0700) and `XDG_CONFIG_HOME`, `XDG_DATA_HOME`, `XDG_CACHE_HOME`, and `XDG_STATE_HOME` under it, plus `GENTLE_PI_CONFIG_HOME=<dataDir>/gentle-ai`. `PATH` is kept, and `GIT_CONFIG_GLOBAL` points at the user's real `~/.gitconfig` when it exists, to keep their git identity. Inherited `PI_CODING_AGENT_DIR`, `GENTLE_PI_AGENT_HOME`, and `GENTLE_SHELL_CONFIG` are removed, and so are a parent subagent run's variables (`GENTLE_PI_AGENTS_CHILD`, `GENTLE_PI_AGENTS_OWNED_IPC`, `GENTLE_PI_AGENTS_PARENT_PERMISSION_FD`) and `GENTLE_PI_AGENTS_PI` (a command line the engine's children would run instead of the engine). `GENTLE_PI_AGENTS=1` turns Gentle Shell's subagents on (`subagent_*` and `orchestrator_*` tools) whatever the user's own setting; `GENTLE_DOT_SUBAGENTS=off` (or `0`, `false`) gives `GENTLE_PI_AGENTS=0` instead (§4, Connectors, Subagents). The engine's first run otherwise writes into the real `~` (`~/.gentle-shell`, `~/.pi/agent/pi-pretty`, `~/.gentle-ai`), which `--home` alone does not prevent.
- Memory (S23): the engine uses the user's global Engram, always in the project `gentle-dot`. The memory plugin accepts a server only when `engram instance-id` (read from the Engram data folder, by default `$HOME/.engram`) matches the server's `/health` `instance_id`, so the child gets `ENGRAM_DATA_DIR=<real ~/.engram>` (the inherited `ENGRAM_DATA_DIR` when set; override `GENTLE_DOT_ENGRAM_DATA_DIR`) and keeps the user's own `ENGRAM_PORT` and `ENGRAM_URL` (default server 7437). If the global Engram is not running, the plugin starts it with that data folder, as Gentle Shell does. The project comes from Engram's per-folder setting: the daemon writes `<dataDir>/workspace/.engram/config.json` (`{"project_name":"gentle-dot"}`) at every start, and Engram reads it before any other detection (source `config`). The plugin has no per-client project override (`ENGRAM_PROJECT` only applies to the Engram process itself, which is the user's shared server). Memories the assistant saved earlier in its private memory (`<dataDir>/home/.engram`) are not moved. `GENTLE_DOT_ENGRAM=private` restores a private memory: no `ENGRAM_DATA_DIR`, `ENGRAM_URL` removed, `ENGRAM_PORT=7438` (override `GENTLE_DOT_ENGRAM_PORT`), data under `<dataDir>/home/.engram`. The memory server the engine starts there outlives the engine, so when nothing listened on the private port as the daemon started, the daemon stops it when it closes: the PID listening on that port (`lsof`), only when its `/health` `instance_id` matches `<dataDir>/home/.engram/.instance-id`.
- Connectors (S18): before every spawn (first start, restart, respawn) the supervisor's `prepareSpawn` hook puts back the connector files from the daemon's in-memory state (§4, Connectors), then points `mcp.json` at the daemon's MCP proxy with a fresh key for this launch (S25.4; the previous key stops working), then hands the approval guard its policy, also from memory, in the child's environment (`GENTLE_DOT_CONNECTOR_POLICY`, JSON: the turned-on connectors, their modes and curated read-only tools, which of them the proxy fronts (`proxied`), and the protected files). The engine cannot change its own environment, so the policy cannot be edited by the assistant. The assistant's own engine loads the guard with `-e packages/daemon/src/extensions/approval-guard.ts` (TypeScript loads as is).
- Parses stdout with strict LF framing on a byte stream. Never Node `readline` (it splits on U+2028/U+2029, which are valid inside JSON).
@@ -151,9 +151,9 @@ Every daemon message carries `seq` (monotonic per connection) so the UI can dete
- App channel (S25.1–S25.3, `packages/daemon/src/app-channel.ts`, `apps/desktop/src-tauri/src/app_channel.rs`): when the desktop app spawns the daemon it creates a connected pair of Unix sockets and puts one end on the daemon's fd 3 (posix_spawn `adddup2` on macOS, with `POSIX_SPAWN_CLOEXEC_DEFAULT` closing every other descriptor; a `pre_exec` `dup2` on Linux); it keeps the other. The connection is the authentication: nothing is written to a file or an environment variable, and nothing listens. The daemon (`cli.ts`) opens fd 3 before it spawns anything, only when it is a socket and not Node's own IPC channel, and first checks that a child spawned the daemon's way would not hold it (a probe child compares the socket's identity on its fd 3); if one would, it closes it and runs without a channel. On macOS, libuv spawns with `POSIX_SPAWN_CLOEXEC_DEFAULT`, so the engine, stdio servers, and sign-in commands never get it (`app-channel-fd.test.ts`); Node cannot mark an inherited descriptor close-on-exec, which is why the probe checks rather than assumes. Frames are line-delimited JSON (`{"kind":"request","id","method","params"}`, `{"kind":"response","id","result"|"error"}`), each side numbering its own requests. The app sends `command {clientId, message}`, `computer_register {url, token}`, and `computer_unregister`; the daemon sends `approve` with `{connector, action, preview: [{name, value}], title?, summary?}` and gets `{approved}`, and the secret requests `secret_get {id}` (`{secret}` or `null`), `secret_put {id, secret}`, `secret_delete {id}` (`{deleted}`), and `secret_list` (`{ids}`). The app answers on worker threads: approvals with T23b's `approvals` (one native dialog at a time, Decline the default, 120 s timeout), secrets from `secure_store` with ids checked (`check_id`), refusals that never repeat a value, and nothing logged; a malformed request, a dialog that fails, or the channel closing refuses. A frame longer than 1 MiB closes the channel on either side, and a closed channel stops the daemon (below), so neither side sends one: an oversized request fails before it is written (a daemon approval is then refused), and an oversized answer goes out as an error. Lifetime (S35.2): a daemon launched with a channel stops when it closes, as on SIGTERM (engine, memory, and the connectors' servers stopped, then the process exits), whether the app quit, crashed, or was killed, since the kernel closes the app's end in every case; it stops listening first, so a relaunched app starts a daemon of its own. A daemon started without a channel keeps running until it is stopped.
- Privileged messages (S25.2, `APP_COMMANDS` in the protocol): `connector_connect`, `connector_signin`, `connector_setup`, `connector_disconnect`, `connector_remove`, `connector_mode`, `connector_draft_reply` approving, `connector_import`, `computer_register`, and `computer_unregister` are refused on the WebSocket (`error app_required`, "Open the Gentle Dot app to change connectors.") whoever sends them, the access key notwithstanding (L49). The desktop panel sends them with the `connector_command` Tauri command, which the app forwards over the channel with the panel's `clientId` (from `ready`; it only routes the sign-in steps and refusals to that window and authorizes nothing by itself). Every other message stays on the WebSocket: chat, history, accounts, profiles, models, uploads, `connectors_list`, `connectors_scan`, sign-in answers (`auth_reply`, owner-checked), and declining a draft. Changes that widen access are confirmed natively even though the app sent them: switching to "Read and send", connecting or setting up a connector that is off, approving a draft, and importing (each with what it adds); declining sends the window `error declined` and changes nothing. Narrowing (read only, disconnecting, removing) and signing in again need no dialog. Without a channel (a daemon started from a terminal such as `pnpm dev`, the web, a VPS until T23h) these messages and every approval fail closed. Approvals the daemon asks show in every window as an `ask` with `method: "app"` ("Waiting for your answer in the Gentle Dot app."); `ui_response` to it is refused.
- Approval guard (`packages/daemon/src/extensions/approval-guard.ts`, `tool_call` hook, nested calls included): the tools of a connector the proxy fronts (`proxied` in the policy: turned on and set up) pass, since the proxy filters them and asks itself; a card here would ask twice. A turned-off connector is not in `proxied` or the approved list, so its tools stay blocked here as well. For any other connector tool: it runs without asking only when it declares `readOnlyHint: true` AND it is on the curated list. Anything else asks through `ctx.ui.confirm`: an ask card ("Allow Notion to create pages?") with every argument, key fields first, up to 8,000 characters (beyond that it says "(truncated, N more characters)"), shown in a scrollable block. It is blocked when declined, when no one can answer, or when the connector is "Read only". A server outside the policy is blocked; without a valid policy every connector call asks.
-- Credential and control files: `<agentHome>/auth.json`, `mcp-auth.json` (where it was before the proxy), `models.json` (it can hold API keys), `mcp.json`, the old sign-in home `<dataDir>/connector-signin` with its `mcp.json` and `mcp-auth.json` (gone after the migration, still protected in case they appear again), `<dataDir>/connectors.json`, `<dataDir>/token`, and the guard itself. The file tools (`read`, `write`, `edit`, `grep`, `find`, `ls`) are blocked on them by resolved path (any spelling, `@` prefix, case, symlink, or hard link), and `grep` also on any folder that contains one. Commands (`bash`) are blocked when, with quotes, backslashes, and string concatenation removed, they name one of those files (any case; a pattern such as `mcp-a*` counts), the data folder `.gentle-dot`, `PI_CODING_AGENT_DIR`, `security find-generic-password` (or other keychain reads), or `mcp add|login|logout|remove`. The command check is best effort, not a security boundary: the assistant runs as the user with a shell, so a command can always build a name the check does not see. The in-memory connector state above does not depend on it, and stage 2 (S25) moves tokens out of the engine's reach.
+- Credential and control files: `<agentHome>/auth.json`, `mcp-auth.json` (where it was before the proxy), `models.json` (it can hold API keys), `mcp.json`, the old sign-in home `<dataDir>/connector-signin` with its `mcp.json` and `mcp-auth.json` (gone after the migration, still protected in case they appear again), `<dataDir>/connectors.json`, `<dataDir>/token`, the guard itself, and the file that loads it into subagents (`<agentHome>/extensions/gentle-dot-child-guard.ts`, below). The file tools (`read`, `write`, `edit`, `grep`, `find`, `ls`) are blocked on them by resolved path (any spelling, `@` prefix, case, symlink, or hard link), and `grep` also on any folder that contains one. Commands (`bash`) are blocked when, with quotes, backslashes, and string concatenation removed, they name one of those files (any case; a pattern such as `mcp-a*` counts), the data folder `.gentle-dot`, `PI_CODING_AGENT_DIR`, `security find-generic-password` (or other keychain reads), or `mcp add|login|logout|remove`. The command check is best effort, not a security boundary: the assistant runs as the user with a shell, so a command can always build a name the check does not see. The in-memory connector state above does not depend on it, and stage 2 (S25) moves tokens out of the engine's reach.
- Stage 2 integrity (S25.6, Integrity above) covers the user's own servers too: the signature is over the whole record, so a file edited while the daemon is not running cannot add a server that runs a command, turn it on, claim an `origin`, change its command, arguments, URL, env, headers, `enabled`, or `mode`, or plant a secret reference (L117 A1) without being set aside at the next start with the app. Without the app it is still loaded, but connectors that need a secret are locked there.
-- Subagents are off in the assistant's engine (`GENTLE_PI_AGENTS=0`, §3): Gentle Shell's subagent child engines get only its own child extensions, not the approval guard, so a child could run connector tools or read credentials unchecked. Turning them back on needs S25 (enforcement in the daemon) or forwarding the guard to child engines. With the proxy (S25.4) a child's connector calls are filtered and approved by the daemon too; subagents stay off until T23f checks the rest (credential reads, a real-engine probe).
+- Subagents (S25.4, T23f; `packages/daemon/src/child-guard.ts`): they are on (`GENTLE_PI_AGENTS=1`, §3; `GENTLE_DOT_SUBAGENTS=off` turns them off). A subagent is a child engine that gentle-pi starts as `pi --mode rpc` (`lib/agents-runner.ts` `childArguments`) with the engine's environment (`PI_CODING_AGENT_DIR` is the assistant's engine home, plus the guard's policy) and without `--no-extensions`. So it reads the same `<agentHome>/mcp.json`: connectors only as proxy entries with the current launch's key, where the daemon filters by mode, refuses hidden tools, and asks in the app's native dialog before every sending action, whoever calls; and the computer helper at the app's address with its key, where the app's own session grant and confirmations apply. A child also loads gentle-pi's two child extensions (`child-context.ts`, `child-safety.ts`) and whatever it discovers in the engine home, never the engine's `-e`, and gentle-pi offers no setting for extra child extensions (its `GENTLE_PI_AGENTS_PI` override splits on spaces, and the app's paths have them). The daemon therefore keeps `<agentHome>/extensions/gentle-dot-child-guard.ts`, which imports the guard from the daemon's own install (a path fixed when the daemon writes it, never one from the environment) and runs it only when `GENTLE_PI_AGENTS_CHILD=1` and the daemon's policy variable are both set: inert in the main engine (which already has the guard) and in any engine Gentle Dot did not start that shares the home. It is written (0600) at every engine start, checked with the connector files (a change or removal is put back, logged, and reported like one to `mcp.json`; an `extensions` folder that became a link loses the link, never its target), and protected like the guard. If it cannot be put in place (the folder's place holds a file, or the file's place a folder), that is logged once and the engine starts with `GENTLE_PI_AGENTS=0`. In a child the guard blocks the credential and control files and the connector commands as in the engine; it registers no `propose_connector`, because a child's status updates go to its parent engine, never to the daemon, so a draft could not reach the user. The proxy and the native approvals stay the boundary; the guard in children is defense in depth, with the guard's own limits (the agent's shell can change files between the daemon's checks, add an `index.ts` or ignore file to that folder, or turn the file off in `settings.json`), the same reach the engine's shell already has (S25, refined in L109). `subagent-probe.test.ts` (opt-in, `GENTLE_DOT_SUBAGENT_PROBE=1`, offline) runs the real engine with gentle-pi's subagents: the child's read of `mcp.json` is refused by the guard, a read-only Notion search goes through the proxy without asking, creating a page waits for the app's answer, and the computer helper is reached with its key.
### Switching and history races (S21)
@@ -374,4 +374,4 @@ On launch, the app checks `GET /health`. If the daemon does not answer, the app
All keys are optional. `workspace` is the user's preferred working folder: the engine is told about it but always runs in `<dataDir>/workspace`. Changing the shortcut in Settings rewrites `shortcut` and keeps every other key.
-Environment overrides: `GENTLE_DOT_AGENT_HOME` (default `~/.gentle-dot/agent`), `GENTLE_DOT_ENGRAM_DATA_DIR` (default: the user's Engram data folder), `GENTLE_DOT_ENGRAM` (`private` for a memory of the assistant's own), `GENTLE_DOT_ENGRAM_PORT` (private memory only, default `7438`), `GENTLE_DOT_PORT`, `GENTLE_DOT_HOST` (default `127.0.0.1`; `0.0.0.0` only inside a container), `GENTLE_DOT_DATA_DIR`, `GENTLE_DOT_WORKSPACE`, `GENTLE_DOT_UI_DIR`, `GENTLE_DOT_AGENT_BIN`, `GENTLE_DOT_AGENT_ARGS` (JSON array), `GENTLE_DOT_ALLOWED_ORIGINS` (JSON array), `GENTLE_DOT_CONVERSATIONS` (`1` turns the conversations list on), `GENTLE_DOT_ROTATE_BYTES` (default 20 MB), `GENTLE_DOT_ROTATE_COMPACTIONS` (default 10), `GENTLE_DOT_HISTORY_PAGE` (default 100).
+Environment overrides: `GENTLE_DOT_AGENT_HOME` (default `~/.gentle-dot/agent`), `GENTLE_DOT_ENGRAM_DATA_DIR` (default: the user's Engram data folder), `GENTLE_DOT_ENGRAM` (`private` for a memory of the assistant's own), `GENTLE_DOT_ENGRAM_PORT` (private memory only, default `7438`), `GENTLE_DOT_SUBAGENTS` (`off` turns the engine's subagents off), `GENTLE_DOT_PORT`, `GENTLE_DOT_HOST` (default `127.0.0.1`; `0.0.0.0` only inside a container), `GENTLE_DOT_DATA_DIR`, `GENTLE_DOT_WORKSPACE`, `GENTLE_DOT_UI_DIR`, `GENTLE_DOT_AGENT_BIN`, `GENTLE_DOT_AGENT_ARGS` (JSON array), `GENTLE_DOT_ALLOWED_ORIGINS` (JSON array), `GENTLE_DOT_CONVERSATIONS` (`1` turns the conversations list on), `GENTLE_DOT_ROTATE_BYTES` (default 20 MB), `GENTLE_DOT_ROTATE_COMPACTIONS` (default 10), `GENTLE_DOT_HISTORY_PAGE` (default 100).
diff --git a/packages/daemon/src/child-guard.ts b/packages/daemon/src/child-guard.ts
new file mode 100644
index 0000000..63a5768
--- /dev/null
+++ b/packages/daemon/src/child-guard.ts
@@ -0,0 +1,33 @@
+import { join } from "node:path";
+import { POLICY_ENV } from "./extensions/approval-guard.ts";
+
+/**
+ * The approval guard for subagents (S25.4). Gentle Shell's subagents are child engines (`pi --mode
+ * rpc`) that load only their own child extensions plus the extensions they discover in the engine's
+ * home, never the `-e` the assistant's engine gets. So the daemon puts this file in that home's
+ * `extensions` folder: it loads the guard in a child of the assistant's engine and does nothing
+ * anywhere else (the main engine already has the guard, and an engine Gentle Dot did not start has
+ * no policy from the daemon). It imports the guard from the daemon's own install, never from a
+ * path the environment names. Defense in depth only: the proxy and the app's native approvals are
+ * the boundary, and the agent's shell can change files between the daemon's checks.
+ */
+export const CHILD_GUARD_NAME = "gentle-dot-child-guard.ts";
+
+/** Where the engine's child engines find the file: `<agentHome>/extensions/`. */
+export function childGuardFile(agentHome: string): string {
+ return join(agentHome, "extensions", CHILD_GUARD_NAME);
+}
+
+/** The file's text, importing the guard at `guardPath`. */
+export function childGuardText(guardPath: string): string {
+ return [
+ "// Written by Gentle Dot at every engine start and put back when changed. It loads the approval",
+ "// guard into the subagents of the assistant's engine; anywhere else it does nothing.",
+ `import guard from ${JSON.stringify(guardPath)};`,
+ "",
+ "export default function gentleDotChildGuard(pi: Parameters<typeof guard>[0]): void {",
+ `\tif (process.env.GENTLE_PI_AGENTS_CHILD === "1" && process.env.${POLICY_ENV} !== undefined) guard(pi, { subagent: true });`,
+ "}",
+ "",
+ ].join("\n");
+}
diff --git a/packages/daemon/src/connectors.ts b/packages/daemon/src/connectors.ts
index c66fc5b..bb91ffc 100644
--- a/packages/daemon/src/connectors.ts
+++ b/packages/daemon/src/connectors.ts
@@ -15,7 +15,7 @@ import {
} from "node:fs";
import { createRequire } from "node:module";
import { homedir } from "node:os";
-import { join } from "node:path";
+import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import type { McpOAuthState } from "@earendil-works/pi-mcp/oauth";
import type {
@@ -27,6 +27,7 @@ import type {
ServerPayload,
} from "@gentle-dot/protocol";
import { MAX_CONNECTOR_DRAFTS } from "@gentle-dot/protocol";
+import { childGuardFile, childGuardText } from "./child-guard.ts";
import { resolveRecord, resolveValue, storedSignIn } from "./connector-credentials.ts";
import { type ScannedServer, scanClientConfigs, valueNotes } from "./connector-import.ts";
import {
@@ -625,6 +626,11 @@ export interface ConnectorStoreOptions {
workspace?: string;
/** The approval guard's own file, protected like the connector files. */
guardPath?: string;
+ /**
+ * Keeps the file that loads the guard (`guardPath`) into the engine's subagents in the engine's
+ * extensions folder, written and put back like `mcp.json` and protected like the guard (S25.4).
+ */
+ childGuard?: boolean;
log?: (line: string) => void;
}
@@ -691,12 +697,20 @@ export class ConnectorStore {
/** Sign-in files that appeared after the move and were reported. */
private readonly reported = new Set<string>();
private watchers: FSWatcher[] = [];
+ /** Set once a child guard that cannot be written was reported, so the checks every second stay quiet. */
+ private childGuardReported = false;
private readonly options: ConnectorStoreOptions;
+ /** The file that loads the guard into the engine's subagents, when the store keeps one. */
+ readonly childGuard: { file: string; text: string } | undefined;
constructor(options: ConnectorStoreOptions) {
this.options = options;
this.file = join(options.dataDir, "connectors.json");
this.mcpFile = join(options.agentHome, "mcp.json");
+ this.childGuard =
+ options.childGuard && options.guardPath
+ ? { file: childGuardFile(options.agentHome), text: childGuardText(options.guardPath) }
+ : undefined;
this.signinHome = join(options.dataDir, "connector-signin");
this.signinMcpFile = join(this.signinHome, "mcp.json");
this.authFile = join(this.signinHome, "mcp-auth.json");
@@ -1027,6 +1041,7 @@ export class ConnectorStore {
writePrivate(file, text);
changed.push(file);
}
+ if (this.enforceChildGuard()) changed.push(this.childGuard?.file ?? "");
if (this.removeProjectConfig()) changed.push("the workspace's .pi/mcp.json");
this.reportPlanted();
if (changed.length === 0 || !report) return changed.length > 0;
@@ -1103,6 +1118,7 @@ export class ConnectorStore {
this.file,
join(this.options.dataDir, "token"),
...(this.options.guardPath ? [this.options.guardPath] : []),
+ ...(this.childGuard ? [this.childGuard.file] : []),
],
...(this.computer ? { builtin: [COMPUTER_ID] } : {}),
};
@@ -1421,6 +1437,40 @@ export class ConnectorStore {
} catch {}
}
+ /** True when the engine's subagents will load the guard: its file is in place, in a real folder. */
+ childGuardReady(): boolean {
+ if (!this.childGuard) return false;
+ const { file, text } = this.childGuard;
+ return (
+ isFolder(dirname(file)) && lstatOrUndefined(file)?.isFile() === true && readOrUndefined(file) === text
+ );
+ }
+
+ /**
+ * Writes the child guard's file when it differs or is missing; true when it did. An extensions
+ * folder that is a link loses the link, never what it points to. When the folder or the file's
+ * place holds something else, that is reported once and left alone, and the engine starts with
+ * subagents off ({@link childGuardReady}).
+ */
+ private enforceChildGuard(): boolean {
+ if (!this.childGuard || this.childGuardReady()) return false;
+ const { file, text } = this.childGuard;
+ const folder = dirname(file);
+ if (lstatOrUndefined(folder)?.isSymbolicLink()) unlinkSync(folder);
+ const inFolder = lstatOrUndefined(folder);
+ const inPlace = inFolder && lstatOrUndefined(file);
+ if ((inFolder && !inFolder.isDirectory()) || inPlace?.isDirectory()) {
+ if (!this.childGuardReported)
+ this.options.log?.(`the subagents' approval guard cannot be written to ${file}`);
+ this.childGuardReported = true;
+ return false;
+ }
+ this.childGuardReported = false;
+ mkdirSync(folder, { recursive: true, mode: 0o700 });
+ writePrivate(file, text);
+ return true;
+ }
+
/** Removes `<workspace>/.pi/mcp.json`; a `.pi` that is a link loses the link, never what it points to. */
private removeProjectConfig(): boolean {
if (!this.options.workspace) return false;
diff --git a/packages/daemon/src/daemon.ts b/packages/daemon/src/daemon.ts
index d873819..02850b3 100644
--- a/packages/daemon/src/daemon.ts
+++ b/packages/daemon/src/daemon.ts
@@ -178,6 +178,8 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {
agentHome,
workspace: options.workspace,
guardPath: APPROVAL_GUARD,
+ // The assistant's own engine: its subagents load the guard from its extensions folder (S25.4).
+ ...(options.agentHome ? { childGuard: true } : {}),
env: agentEnv,
secrets: new AppSecretSource(app),
log,
@@ -217,10 +219,16 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {
// mcp.json is read when a session starts: put back anything not approved, and hand the guard
// its policy from the daemon's memory, never from the files.
// The proxy's key changes with every launch (after the check, so a change is still reported).
+ // Subagents start only with the guard in place for them; otherwise this launch has none.
prepareSpawn: () => {
connectors.enforce();
connectorStore.setProxy({ url: `http://127.0.0.1:${port}/mcp`, key: proxy.rotateKey() });
- return policyEnv(connectorStore);
+ const env = policyEnv(connectorStore);
+ if (options.agentHome && agentEnv.GENTLE_PI_AGENTS !== "0" && !connectorStore.childGuardReady()) {
+ log("subagents are off for this engine start: their approval guard is not in place");
+ env.GENTLE_PI_AGENTS = "0";
+ }
+ return env;
},
// The first start in a new home installs the engine's companion packages.
...(options.agentHome ? { startTimeoutMs: 180_000 } : {}),
diff --git a/packages/daemon/src/extensions/approval-guard.ts b/packages/daemon/src/extensions/approval-guard.ts
index f9d97d8..7c89df6 100644
--- a/packages/daemon/src/extensions/approval-guard.ts
+++ b/packages/daemon/src/extensions/approval-guard.ts
@@ -30,6 +30,8 @@
* status update on the engine's own output (`ctx.ui.setStatus`), which only the daemon reads, and the
* model hears only that the user will review it. The daemon shows the draft as a card and adds it
* only after the user approves; secrets are typed in the app, never in the chat.
+ * Subagents of the engine load this guard too, through a file the daemon keeps in the engine's
+ * extensions folder (`child-guard.ts`), but get no `propose_connector`.
* This file has no dependencies besides Node, so the engine loads it as is.
*/
import { realpathSync, statSync } from "node:fs";
@@ -439,7 +441,8 @@ function fileId(path: string): string | undefined {
}
}
-export default function approvalGuard(pi: ExtensionAPI): void {
+/** `subagent`: loaded into a subagent's child engine by the daemon's file for it (`child-guard.ts`). */
+export default function approvalGuard(pi: ExtensionAPI, options: { subagent?: boolean } = {}): void {
const parsed = parsePolicy(process.env[POLICY_ENV]);
const agentDir = process.env.PI_CODING_AGENT_DIR;
const fallback = agentDir
@@ -447,14 +450,17 @@ export default function approvalGuard(pi: ExtensionAPI): void {
: [];
const policy: ConnectorPolicy = parsed ?? { protectedPaths: fallback };
- pi.registerTool({
- ...PROPOSE_TOOL,
- promptGuidelines: [...PROPOSE_TOOL.promptGuidelines],
- parameters: PROPOSE_TOOL.parameters as never,
- async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
- return { content: [{ type: "text", text: proposeConnector(params, ctx) }], details: {} };
- },
- });
+ // A subagent's status updates go to its parent engine, never to the daemon, so its drafts could
+ // not reach the user: subagents get no propose_connector (S25.4).
+ if (!options.subagent)
+ pi.registerTool({
+ ...PROPOSE_TOOL,
+ promptGuidelines: [...PROPOSE_TOOL.promptGuidelines],
+ parameters: PROPOSE_TOOL.parameters as never,
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
+ return { content: [{ type: "text", text: proposeConnector(params, ctx) }], details: {} };
+ },
+ });
// Each model call carries only the last computer screenshot (S24.10).
pi.on("context", (event) => ({ messages: pruneScreenshots(event.messages) }));
diff --git a/packages/daemon/src/isolation.ts b/packages/daemon/src/isolation.ts
index 3b7d99d..561fd50 100644
--- a/packages/daemon/src/isolation.ts
+++ b/packages/daemon/src/isolation.ts
@@ -64,6 +64,24 @@ export function claimEngineHome(agentHome: string, log: (line: string) => void =
/** 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"];
+/**
+ * What a subagent run sets for its child engines (gentle-pi `lib/agents-runner.ts`), and the command
+ * line those children would run instead of the engine. The assistant's engine is never a child, and
+ * its children run the same engine as it does.
+ */
+const SUBAGENT_VARIABLES = [
+ "GENTLE_PI_AGENTS_CHILD",
+ "GENTLE_PI_AGENTS_OWNED_IPC",
+ "GENTLE_PI_AGENTS_PARENT_PERMISSION_FD",
+ "GENTLE_PI_AGENTS_PI",
+];
+
+/** Subagents are on unless `GENTLE_DOT_SUBAGENTS` is `off`, `0`, or `false`. */
+export function subagentsEnabled(base: NodeJS.ProcessEnv): boolean {
+ const value = base.GENTLE_DOT_SUBAGENTS?.trim().toLowerCase();
+ return !(value === "off" || value === "0" || value === "false");
+}
+
/** The memory project every memory the assistant saves or searches belongs to. */
export const MEMORY_PROJECT = "gentle-dot";
@@ -94,7 +112,8 @@ export function ensureMemoryProject(workspace: string): void {
* user's server. The user's own `ENGRAM_PORT` and `ENGRAM_URL` are kept.
* `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.
+ * Subagents are on (`GENTLE_PI_AGENTS=1`) unless `GENTLE_DOT_SUBAGENTS=off`: their child engines
+ * reach connectors only through the daemon's proxy, like the engine itself (S25.4).
*
* Without a `TMPDIR` (the installed app's launch on Linux), the engine gets a
* private one under its home: it caches compiled extensions in the temporary
@@ -115,7 +134,7 @@ export function isolatedAgentEnv(base: NodeJS.ProcessEnv, dataDir: string): Node
XDG_CACHE_HOME: join(home, ".cache"),
XDG_STATE_HOME: join(home, ".local", "state"),
};
- for (const key of INHERITED_HOMES) delete env[key];
+ for (const key of [...INHERITED_HOMES, ...SUBAGENT_VARIABLES]) delete env[key];
if (!base.TMPDIR) {
env.TMPDIR = join(home, ".cache", "tmp");
ensurePrivateDir(env.TMPDIR);
@@ -125,9 +144,8 @@ export function isolatedAgentEnv(base: NodeJS.ProcessEnv, dataDir: string): Node
const rest = (base.PATH ?? "").split(delimiter).filter((part) => part && part !== bin);
env.PATH = [bin, ...rest].join(delimiter);
}
- // Subagent child engines do not load the approval guard, so subagents stay off until the
- // daemon enforces connectors itself (S25).
- env.GENTLE_PI_AGENTS = "0";
+ // The user's own Gentle Shell setting is not the assistant's.
+ env.GENTLE_PI_AGENTS = subagentsEnabled(base) ? "1" : "0";
if (base.GENTLE_DOT_ENGRAM === "private") {
env.ENGRAM_PORT = base.GENTLE_DOT_ENGRAM_PORT || PRIVATE_ENGRAM_PORT;
delete env.ENGRAM_URL;
diff --git a/packages/daemon/test/child-guard.test.ts b/packages/daemon/test/child-guard.test.ts
new file mode 100644
index 0000000..a3cfa00
--- /dev/null
+++ b/packages/daemon/test/child-guard.test.ts
@@ -0,0 +1,160 @@
+// Subagents behind the proxy (S25.4, T23f): the assistant's engine runs with subagents on, and its
+// subagent child engines load the approval guard through a small file in the engine's own
+// extensions folder, which they discover on their own. That file does nothing in the main engine
+// (it loads the guard with `-e`) or in any engine Gentle Dot did not start, and the daemon writes it
+// at every engine start and puts it back when it changes. The proxy and the native approvals stay
+// the boundary; the guard in children is defense in depth.
+import { existsSync, lstatSync, mkdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+import { APPROVAL_GUARD } from "../src/connectors.ts";
+import { type DotDaemon, startDaemon } from "../src/daemon.ts";
+import { type ConnectorPolicy, POLICY_ENV, PROPOSE_TOOL } from "../src/extensions/approval-guard.ts";
+import { FAKE_AGENT, tempDir, waitFor } from "./helpers.ts";
+
+const SHIM = "gentle-dot-child-guard.ts";
+
+const daemons: DotDaemon[] = [];
+const savedEnv = { ...process.env };
+afterEach(async () => {
+ await Promise.all(daemons.splice(0).map((d) => d.close()));
+ for (const key of Object.keys(process.env)) if (!(key in savedEnv)) delete process.env[key];
+ Object.assign(process.env, savedEnv);
+});
+
+async function start(options: { env?: NodeJS.ProcessEnv; before?: (agentHome: string) => void } = {}) {
+ const scratch = tempDir();
+ const dataDir = tempDir();
+ const agentHome = join(dataDir, "agent");
+ options.before?.(agentHome);
+ const envFile = join(scratch, "env.json");
+ const lines: string[] = [];
+ 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,
+ agentEnv: { PATH: process.env.PATH, HOME: scratch, ...options.env, FAKE_AGENT_ENV_FILE: envFile },
+ log: (line) => lines.push(line),
+ });
+ daemons.push(d);
+ const env = () => JSON.parse(readFileSync(envFile, "utf8")) as Record<string, string | undefined>;
+ return { d, dataDir, agentHome, shim: join(agentHome, "extensions", SHIM), env, lines };
+}
+
+/** What an extension registered when the engine called it. */
+function fakePi() {
+ const tools: string[] = [];
+ const handlers = new Map<string, (event: unknown, ctx: unknown) => unknown>();
+ const pi = {
+ registerTool: (tool: { name: string }) => tools.push(tool.name),
+ on: (event: string, handler: (event: unknown, ctx: unknown) => unknown) => handlers.set(event, handler),
+ getAllTools: () => [],
+ };
+ return { pi, tools, handlers };
+}
+
+/** Loads the file the daemon wrote, as an engine would, and runs it with `env` as the engine's environment (read when it runs). */
+async function runShim(shim: string, env: NodeJS.ProcessEnv) {
+ const { default: extension } = (await import(shim)) as {
+ default: (pi: unknown) => void;
+ };
+ for (const key of ["GENTLE_PI_AGENTS_CHILD", POLICY_ENV]) delete process.env[key];
+ Object.assign(process.env, env);
+ const fake = fakePi();
+ extension(fake.pi);
+ return fake;
+}
+
+describe("subagents in the assistant's engine (S25.4)", () => {
+ it("starts the engine with subagents on and the child guard in its extensions folder", async () => {
+ const { env, shim } = await start({ env: { GENTLE_PI_AGENTS: "0" } });
+ expect(env().GENTLE_PI_AGENTS).toBe("1");
+ // The guard comes from the daemon's own install, never from a path in the environment.
+ expect(readFileSync(shim, "utf8")).toContain(`import guard from ${JSON.stringify(APPROVAL_GUARD)};`);
+ expect(lstatSync(shim).mode & 0o777).toBe(0o600);
+ });
+
+ it("keeps subagents off with GENTLE_DOT_SUBAGENTS=off", async () => {
+ const { env } = await start({ env: { GENTLE_DOT_SUBAGENTS: "off" } });
+ expect(env().GENTLE_PI_AGENTS).toBe("0");
+ });
+
+ it("protects the child guard's file like the guard's own", async () => {
+ const { env, shim } = await start();
+ const policy = JSON.parse(env()[POLICY_ENV] ?? "{}") as ConnectorPolicy;
+ expect(policy.protectedPaths).toContain(shim);
+ expect(policy.protectedPaths).toContain(APPROVAL_GUARD);
+ });
+
+ it("is inert in the main engine and in engines Gentle Dot did not start; a child of the assistant's engine gets the guard", async () => {
+ const { env, shim } = await start();
+ const policy = env()[POLICY_ENV] ?? "";
+ // The main engine already loads the guard with -e: no second copy.
+ const main = await runShim(shim, { [POLICY_ENV]: policy });
+ expect(main.tools).toEqual([]);
+ expect(main.handlers.size).toBe(0);
+ // A subagent of some other engine sharing this home (no policy from the daemon).
+ const foreign = await runShim(shim, { GENTLE_PI_AGENTS_CHILD: "1" });
+ expect(foreign.tools).toEqual([]);
+ expect(foreign.handlers.size).toBe(0);
+
+ const child = await runShim(shim, { GENTLE_PI_AGENTS_CHILD: "1", [POLICY_ENV]: policy });
+ const toolCall = child.handlers.get("tool_call");
+ expect(toolCall).toBeDefined();
+ const mcpJson = JSON.parse(policy).protectedPaths[0] as string;
+ expect(
+ await toolCall?.({ toolName: "read", input: { path: mcpJson } }, { cwd: "/", hasUI: true }),
+ ).toMatchObject({
+ block: true,
+ });
+ expect(
+ await toolCall?.({ toolName: "bash", input: { command: `cat ${shim}` } }, { cwd: "/" }),
+ ).toMatchObject({
+ block: true,
+ });
+ // A child's drafts could never reach the app (its status goes to the parent engine, not the
+ // daemon), so it has no propose_connector at all.
+ expect(child.tools).not.toContain(PROPOSE_TOOL.name);
+ });
+
+ it("puts the child guard back when it changes or disappears while running, and says so", async () => {
+ const { shim, lines } = await start();
+ const original = readFileSync(shim, "utf8");
+ writeFileSync(shim, "export default function () {}\n");
+ await waitFor(() => readFileSync(shim, "utf8") === original, 5000);
+ rmSync(shim);
+ await waitFor(() => existsSync(shim) && readFileSync(shim, "utf8") === original, 5000);
+ expect(
+ lines.filter((line) => line.includes("put back") && line.includes(shim)).length,
+ ).toBeGreaterThanOrEqual(2);
+ });
+
+ it("replaces an extensions folder that became a link, never touching where it points", async () => {
+ const { agentHome, shim } = await start();
+ const original = readFileSync(shim, "utf8");
+ const elsewhere = tempDir();
+ writeFileSync(join(elsewhere, "keep.txt"), "mine\n");
+ rmSync(join(agentHome, "extensions"), { recursive: true });
+ symlinkSync(elsewhere, join(agentHome, "extensions"));
+ await waitFor(() => !lstatSync(join(agentHome, "extensions")).isSymbolicLink(), 5000);
+ await waitFor(() => existsSync(shim) && readFileSync(shim, "utf8") === original, 5000);
+ expect(readFileSync(join(elsewhere, "keep.txt"), "utf8")).toBe("mine\n");
+ expect(existsSync(join(elsewhere, SHIM))).toBe(false);
+ });
+
+ it("starts the engine with subagents off when the child guard cannot be put in place", async () => {
+ const { env, lines } = await start({
+ before: (agentHome) => {
+ mkdirSync(agentHome, { recursive: true });
+ writeFileSync(join(agentHome, "extensions"), "not a folder\n");
+ },
+ });
+ expect(env().GENTLE_PI_AGENTS).toBe("0");
+ expect(lines.some((line) => /subagents are off/i.test(line))).toBe(true);
+ });
+});
diff --git a/packages/daemon/test/connector-probe.test.ts b/packages/daemon/test/connector-probe.test.ts
index dd9a524..8eb03c4 100644
--- a/packages/daemon/test/connector-probe.test.ts
+++ b/packages/daemon/test/connector-probe.test.ts
@@ -235,9 +235,9 @@ describe.skipIf(!enabled)("@real-agent connector probe", () => {
});
expect(summary.projectMcpJson).toBe(false);
expect(summary.toasts).toContain("A change to your connectors was blocked.");
- // A1: subagents are off until S25 (their child engines do not load the approval guard).
+ // Subagents are back behind the proxy (S25.4, T23f; subagent-probe.test.ts checks their children).
expect(summary.toolsOffered).toContain("bash");
- expect(summary.subagentTools).toEqual([]);
+ expect(summary.subagentTools).toContain("subagent_run");
} finally {
if (child.exitCode === null) child.kill("SIGTERM");
await exited;
diff --git a/packages/daemon/test/fixtures/engine-launcher.ts b/packages/daemon/test/fixtures/engine-launcher.ts
new file mode 100644
index 0000000..74c8637
--- /dev/null
+++ b/packages/daemon/test/fixtures/engine-launcher.ts
@@ -0,0 +1,21 @@
+// Starts the bundled engine for the subagent probe the way gentle-shell starts it in the assistant's
+// home (`PI_CODING_AGENT_DIR` and `GENTLE_PI_AGENT_HOME` at `--home`, gentle-pi loaded with `-e`),
+// without gentle-shell's first-run setup, which needs the network. Only gentle-pi's subagents
+// extension is loaded. Usage (the daemon appends `--home`, `--mode rpc`, and the rest):
+// node engine-launcher.ts <pi cli.js> <gentle-agents.ts> --home <dir> ...
+import { spawn } from "node:child_process";
+
+const [cli, agents, ...rest] = process.argv.slice(2);
+const at = rest.indexOf("--home");
+const home = at >= 0 ? rest[at + 1] : undefined;
+if (!cli || !agents || !home) {
+ process.stderr.write("usage: engine-launcher.ts <pi cli.js> <gentle-agents.ts> --home <dir> ...\n");
+ process.exit(2);
+}
+rest.splice(at, 2);
+const child = spawn(process.execPath, [cli, "-e", agents, ...rest], {
+ stdio: "inherit",
+ env: { ...process.env, PI_CODING_AGENT_DIR: home, GENTLE_PI_AGENT_HOME: home },
+});
+for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"] as const) process.on(signal, () => child.kill(signal));
+child.on("exit", (code, signal) => process.exit(code ?? (signal ? 1 : 0)));
diff --git a/packages/daemon/test/fixtures/fake-agent.ts b/packages/daemon/test/fixtures/fake-agent.ts
index 675232e..fab9bd9 100644
--- a/packages/daemon/test/fixtures/fake-agent.ts
+++ b/packages/daemon/test/fixtures/fake-agent.ts
@@ -100,6 +100,7 @@ if (process.env.FAKE_AGENT_ENV_FILE) {
"ENGRAM_URL",
"ENGRAM_DATA_DIR",
"GENTLE_DOT_CONNECTOR_POLICY",
+ "GENTLE_PI_AGENTS",
].map((key) => [key, process.env[key]]),
),
),
diff --git a/packages/daemon/test/gateway.test.ts b/packages/daemon/test/gateway.test.ts
index 67535e4..ef20bff 100644
--- a/packages/daemon/test/gateway.test.ts
+++ b/packages/daemon/test/gateway.test.ts
@@ -536,6 +536,8 @@ describe("own instance", () => {
ENGRAM_URL: "http://127.0.0.1:7437",
// The approval guard's policy: no connector is on yet.
GENTLE_DOT_CONNECTOR_POLICY: expect.stringContaining('"connectors":{}'),
+ // Subagents on, behind the proxy and with the guard (S25.4).
+ GENTLE_PI_AGENTS: "1",
});
expect(statSync(home).mode & 0o777).toBe(0o700);
expect(existsSync(join(dataDir, "workspace"))).toBe(true);
diff --git a/packages/daemon/test/isolation.test.ts b/packages/daemon/test/isolation.test.ts
index 10b6547..120ec46 100644
--- a/packages/daemon/test/isolation.test.ts
+++ b/packages/daemon/test/isolation.test.ts
@@ -86,12 +86,42 @@ describe("isolatedAgentEnv memory", () => {
});
describe("isolatedAgentEnv subagents", () => {
- it("turns the engine's subagents off until S25, whatever the user's environment says", () => {
- expect(isolatedAgentEnv({ HOME: tempDir() }, tempDir()).GENTLE_PI_AGENTS).toBe("0");
- expect(isolatedAgentEnv({ HOME: tempDir(), GENTLE_PI_AGENTS: "1" }, tempDir()).GENTLE_PI_AGENTS).toBe(
- "0",
+ it("turns the engine's subagents on, whatever the user's own Gentle Shell setting says (S25.4)", () => {
+ expect(isolatedAgentEnv({ HOME: tempDir() }, tempDir()).GENTLE_PI_AGENTS).toBe("1");
+ expect(isolatedAgentEnv({ HOME: tempDir(), GENTLE_PI_AGENTS: "0" }, tempDir()).GENTLE_PI_AGENTS).toBe(
+ "1",
);
});
+
+ it("keeps them off with GENTLE_DOT_SUBAGENTS=off (or 0, false)", () => {
+ for (const value of ["off", "0", "false", " OFF "])
+ expect(
+ isolatedAgentEnv({ HOME: tempDir(), GENTLE_DOT_SUBAGENTS: value }, tempDir()).GENTLE_PI_AGENTS,
+ ).toBe("0");
+ expect(
+ isolatedAgentEnv({ HOME: tempDir(), GENTLE_DOT_SUBAGENTS: "on" }, tempDir()).GENTLE_PI_AGENTS,
+ ).toBe("1");
+ });
+
+ it("never passes on a parent run's subagent markers or a command line for its children", () => {
+ const env = isolatedAgentEnv(
+ {
+ HOME: tempDir(),
+ GENTLE_PI_AGENTS_CHILD: "1",
+ GENTLE_PI_AGENTS_OWNED_IPC: "1-abc",
+ GENTLE_PI_AGENTS_PARENT_PERMISSION_FD: "3",
+ GENTLE_PI_AGENTS_PI: "/bin/sh -c other",
+ },
+ tempDir(),
+ );
+ for (const key of [
+ "GENTLE_PI_AGENTS_CHILD",
+ "GENTLE_PI_AGENTS_OWNED_IPC",
+ "GENTLE_PI_AGENTS_PARENT_PERMISSION_FD",
+ "GENTLE_PI_AGENTS_PI",
+ ])
+ expect(env[key]).toBeUndefined();
+ });
});
describe("isolatedAgentEnv temporary folder", () => {
diff --git a/packages/daemon/test/subagent-probe.test.ts b/packages/daemon/test/subagent-probe.test.ts
new file mode 100644
index 0000000..7736624
--- /dev/null
+++ b/packages/daemon/test/subagent-probe.test.ts
@@ -0,0 +1,335 @@
+// @real-agent subagent probe (S25.4, T23f): the daemon with the bundled engine and gentle-pi's real
+// subagents (see fixtures/engine-launcher.ts), a stand-in model (OpenAI-compatible, 127.0.0.1), a
+// stand-in for Notion's server behind the daemon's proxy, and the fake desktop app answering the
+// native approvals. The model makes the engine run a subagent; in its own child engine the subagent
+// tries to read the engine's mcp.json, searches Notion (read only), creates a page (sending), and
+// takes a screenshot through the desktop app's computer helper.
+// The child's read must be refused by the approval guard it loads from the engine's extensions
+// folder, the search must go through the proxy without asking, and the page must wait for the app's
+// answer; the helper is reached at the app's own address with its key. Temporary HOME and data folders; no network, accounts, or Engram.
+// Opt-in (it runs the real engine and a child engine; about a minute):
+// GENTLE_DOT_SUBAGENT_PROBE=1 npx vitest run packages/daemon/test/subagent-probe.test.ts
+import { mkdirSync, writeFileSync } from "node:fs";
+import { createServer, type Server } from "node:http";
+import { type AddressInfo, createServer as createNetServer } from "node:net";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { StreamableHttpTransport, type Tool } from "@earendil-works/pi-mcp";
+import type { ServerMessage } from "@gentle-dot/protocol";
+import { afterEach, describe, expect, it } from "vitest";
+import WebSocket from "ws";
+import { bundledGentleShell } from "../src/config.ts";
+import { bundledMcpCli } from "../src/connectors.ts";
+import { type DotDaemon, startDaemon } from "../src/daemon.ts";
+import { PROPOSE_TOOL } from "../src/extensions/approval-guard.ts";
+import { fakeApp, sendLikeThePanel } from "./fake-app.ts";
+import { fakeAuthRuntime } from "./fake-auth-runtime.ts";
+import { oauthOptions } from "./fake-oauth.ts";
+import { tempDir, waitFor } from "./helpers.ts";
+
+const enabled = process.env.GENTLE_DOT_SUBAGENT_PROBE === "1";
+const LAUNCHER = fileURLToPath(new URL("./fixtures/engine-launcher.ts", import.meta.url));
+const CHILD_MARK = "GENTLE-DOT-PROBE-CHILD";
+
+const NOTION_TOOLS: Tool[] = [
+ { name: "notion-search", inputSchema: { type: "object" }, annotations: { readOnlyHint: true } },
+ { name: "notion-create-pages", inputSchema: { type: "object" } },
+];
+/** The desktop app's computer helper (S24): it checks its own key and asks the user itself. */
+const COMPUTER_TOOLS: Tool[] = [{ name: "screenshot", inputSchema: { type: "object" } }];
+const COMPUTER_KEY = "probe-helper-key-0123456789";
+
+type Rec = Record<string, unknown>;
+const closers: (() => Promise<unknown>)[] = [];
+const daemons: DotDaemon[] = [];
+afterEach(async () => {
+ await Promise.all(closers.splice(0).map((close) => close().catch(() => undefined)));
+ await Promise.all(daemons.splice(0).map((d) => d.close()));
+});
+
+async function listen(server: Server): Promise<number> {
+ await new Promise<void>((done) => server.listen(0, "127.0.0.1", done));
+ closers.push(() => new Promise((done) => server.close(done)));
+ return (server.address() as AddressInfo).port;
+}
+
+function freePort(): Promise<number> {
+ return new Promise((resolve) => {
+ const server = createNetServer();
+ server.listen(0, "127.0.0.1", () => {
+ const { port } = server.address() as AddressInfo;
+ server.close(() => resolve(port));
+ });
+ });
+}
+
+/** An MCP server over plain JSON and HTTP, recording each tools/call and the key it came with. */
+async function fakeMcp(name: string, tools: Tool[]) {
+ const calls: string[] = [];
+ const keys: (string | undefined)[] = [];
+ const port = await listen(
+ createServer((req, res) => {
+ let body = "";
+ req.on("data", (chunk: Buffer) => {
+ body += chunk.toString("utf8");
+ });
+ req.on("end", () => {
+ if (req.method !== "POST") {
+ res.writeHead(405).end();
+ return;
+ }
+ const message = JSON.parse(body) as { id?: number; method: string; params?: Rec };
+ if (message.id === undefined) {
+ res.writeHead(202).end();
+ return;
+ }
+ if (message.method === "tools/call") {
+ calls.push(String(message.params?.name));
+ keys.push(req.headers.authorization);
+ }
+ const result =
+ message.method === "initialize"
+ ? {
+ protocolVersion: message.params?.protocolVersion,
+ capabilities: { tools: {} },
+ serverInfo: { name, version: "1" },
+ }
+ : message.method === "tools/list"
+ ? { tools }
+ : { content: [{ type: "text", text: `${name} ran ${String(message.params?.name)}` }] };
+ res.writeHead(200, { "content-type": "application/json" });
+ res.end(JSON.stringify({ jsonrpc: "2.0", id: message.id, result }));
+ });
+ }),
+ );
+ return { url: `http://127.0.0.1:${port}/mcp`, calls, keys };
+}
+
+interface ModelRequest {
+ tools?: { function?: { name?: string } }[];
+ messages?: { role: string; content?: unknown; tool_call_id?: string }[];
+}
+
+/**
+ * The stand-in model. The parent engine (it has `subagent_run`) delegates once. The child engine (its
+ * system prompt has the probe agent's mark) reads mcp.json, searches Notion, creates a page, then
+ * answers. Records the tools each side was offered and the results the child saw.
+ */
+async function fakeModel(mcpJson: string) {
+ const seen = { parentTools: [] as string[][], childTools: [] as string[][], childResults: [] as string[] };
+ const port = await listen(
+ createServer((req, res) => {
+ let body = "";
+ req.on("data", (chunk: Buffer) => {
+ body += chunk.toString("utf8");
+ });
+ req.on("end", () => {
+ const request = JSON.parse(body) as ModelRequest;
+ const tools = (request.tools ?? []).map((tool) => tool.function?.name ?? "");
+ const messages = request.messages ?? [];
+ const text = (content: unknown) =>
+ typeof content === "string" ? content : JSON.stringify(content ?? "");
+ const child = messages.some((m) => m.role === "system" && text(m.content).includes(CHILD_MARK));
+ const results = messages.filter((m) => m.role === "tool");
+ res.writeHead(200, { "Content-Type": "text/event-stream" });
+ const chunk = (delta: Rec, finish: string | null) =>
+ res.write(
+ `data: ${JSON.stringify({ id: "c", object: "chat.completion.chunk", created: 0, model: "fake-model", choices: [{ index: 0, delta, finish_reason: finish }] })}\n\n`,
+ );
+ const call = (name: string, args: Rec) => {
+ chunk(
+ {
+ role: "assistant",
+ tool_calls: [
+ {
+ index: 0,
+ id: `call_${results.length}`,
+ type: "function",
+ function: { name, arguments: JSON.stringify(args) },
+ },
+ ],
+ },
+ null,
+ );
+ chunk({}, "tool_calls");
+ };
+ const say = (content: string) => {
+ chunk({ role: "assistant", content }, null);
+ chunk({}, "stop");
+ };
+ if (child) {
+ seen.childTools.push(tools);
+ seen.childResults = results.map((m) => text(m.content));
+ const steps: [string, Rec][] = [
+ ["read", { path: mcpJson }],
+ ["mcp__notion__notion_search", { query: "plans" }],
+ ["mcp__notion__notion_create_pages", { title: "Plan", parent: "Team space" }],
+ ["mcp__computer__screenshot", {}],
+ ];
+ const next = steps[results.length];
+ if (next) call(next[0], next[1]);
+ else say("child done");
+ } else {
+ seen.parentTools.push(tools);
+ if (results.length === 0 && tools.includes("subagent_run"))
+ call("subagent_run", {
+ agent: "probe",
+ task: "Use Notion.",
+ label: "probe notion",
+ mode: "task",
+ });
+ else say(results.length === 0 ? "no subagents" : "parent done");
+ }
+ res.end("data: [DONE]\n\n");
+ });
+ }),
+ );
+ return { port, seen };
+}
+
+describe.skipIf(!enabled)("@real-agent subagent probe", () => {
+ it("a subagent reaches Notion only through the proxy, waits for the app before sending, and runs with the guard", {
+ timeout: 300_000,
+ }, async () => {
+ const agentsExtension = join(dirname(bundledGentleShell()), "..", "extensions", "gentle-agents.ts");
+ const dataDir = tempDir();
+ const home = tempDir();
+ const agentHome = join(dataDir, "agent");
+ const mcpJson = join(agentHome, "mcp.json");
+ mkdirSync(join(agentHome, "agents"), { recursive: true });
+ const model = await fakeModel(mcpJson);
+ writeFileSync(
+ join(agentHome, "models.json"),
+ JSON.stringify({
+ providers: {
+ fakeprov: {
+ baseUrl: `http://127.0.0.1:${model.port}/v1`,
+ api: "openai-completions",
+ apiKey: "not-a-key",
+ models: [{ id: "fake-model" }],
+ },
+ },
+ }),
+ );
+ writeFileSync(
+ join(agentHome, "settings.json"),
+ JSON.stringify({ defaultProvider: "fakeprov", defaultModel: "fake-model" }),
+ );
+ writeFileSync(
+ join(agentHome, "agents", "probe.md"),
+ `---\nname: probe\ndescription: Probe subagent\n---\nYou are the probe subagent (${CHILD_MARK}).\n`,
+ );
+ const notion = await fakeMcp("notion", NOTION_TOOLS);
+ const computer = await fakeMcp("computer", COMPUTER_TOOLS);
+ const app = fakeApp([], "allow");
+ const lines: string[] = [];
+ const engramPort = String(await freePort());
+ const d = await startDaemon({
+ port: 0,
+ host: "127.0.0.1",
+ dataDir,
+ workspace: join(dataDir, "workspace"),
+ uiDir: dataDir,
+ agentCommand: process.execPath,
+ agentArgs: [LAUNCHER, bundledMcpCli().args[0] ?? "", agentsExtension],
+ agentHome,
+ // No memory plugin is loaded; were one started, it would get a private port and data folder.
+ agentEnv: {
+ PATH: process.env.PATH,
+ HOME: home,
+ GENTLE_DOT_ENGRAM: "private",
+ GENTLE_DOT_ENGRAM_PORT: engramPort,
+ GENTLE_AI_TELEMETRY: "0",
+ },
+ authRuntime: async () => fakeAuthRuntime().runtime,
+ connectorOAuth: oauthOptions(true),
+ connectorTransport: (_connector, credentials) =>
+ new StreamableHttpTransport({
+ url: notion.url,
+ ...(credentials.headers ? { headers: credentials.headers } : {}),
+ ...(credentials.authProvider ? { authProvider: credentials.authProvider } : {}),
+ openGetStream: false,
+ }),
+ appChannel: app.daemonEnd,
+ log: (line) => lines.push(line),
+ });
+ daemons.push(d);
+ try {
+ await waitFor(() => d.supervisor.state === "ready", 120_000);
+ 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));
+ await new Promise((resolve) => ws.on("open", resolve));
+ closers.push(async () => ws.close());
+ ws.send(JSON.stringify({ type: "hello", token: d.token, protocol: 1 }));
+ const ready = await waitFor(() => messages.find((m) => m.type === "ready"));
+ const clientId = ready.type === "ready" ? (ready.clientId ?? "") : "";
+ const send = sendLikeThePanel(
+ app,
+ () => clientId,
+ (m) => ws.send(JSON.stringify(m)),
+ );
+ // The app registers its computer helper; Notion is connected and set to read and send, each
+ // confirmed in the app. Each change restarts the engine.
+ let pid = d.supervisor.pid;
+ await app.request("computer_register", { url: computer.url, token: COMPUTER_KEY });
+ await waitFor(() => d.supervisor.pid !== pid && d.supervisor.state === "ready", 120_000);
+ pid = d.supervisor.pid;
+ send({ type: "connector_connect", connectorId: "notion" });
+ await waitFor(() => messages.find((m) => m.type === "auth_done" && m.ok), 30_000);
+ await waitFor(() => d.supervisor.pid !== pid && d.supervisor.state === "ready", 120_000);
+ pid = d.supervisor.pid;
+ send({ type: "connector_mode", connectorId: "notion", mode: "read_write" });
+ await waitFor(() => d.supervisor.pid !== pid && d.supervisor.state === "ready", 120_000);
+ const asked = app.asked.length;
+
+ // The page waits in the app's dialog until the user answers there.
+ app.answer("hold");
+ ws.send(JSON.stringify({ type: "send", text: "Ask the probe subagent to use Notion." }));
+ await waitFor(() => app.asked.length > asked, 120_000);
+ expect(app.asked[asked]).toMatchObject({ connector: "Notion", action: "create pages" });
+ expect(notion.calls).toEqual(["notion-search"]);
+ await new Promise((resolve) => setTimeout(resolve, 1000));
+ expect(notion.calls).toEqual(["notion-search"]);
+ app.release(true);
+ await waitFor(() => notion.calls.includes("notion-create-pages"), 30_000);
+ await waitFor(() => computer.calls.includes("screenshot"), 30_000);
+ await waitFor(() => model.seen.parentTools.length >= 2 && d.bridge.agentState === "idle", 120_000);
+
+ const summary = {
+ notionCalls: notion.calls,
+ computerCalls: computer.calls,
+ approvals: app.asked.slice(asked),
+ parentTools: [...new Set(model.seen.parentTools.flat())].sort(),
+ childTools: [...new Set(model.seen.childTools.flat())].sort(),
+ childResults: model.seen.childResults,
+ };
+ console.log(`subagent probe:\n${JSON.stringify(summary, null, 2)}`);
+ // The parent engine offers subagents and the guard's tool, once.
+ expect(summary.parentTools).toContain("subagent_run");
+ expect(model.seen.parentTools[0]?.filter((name) => name === PROPOSE_TOOL.name)).toHaveLength(1);
+ // The child engine got Notion's proxied tools, and no propose_connector.
+ expect(summary.childTools).toEqual(
+ expect.arrayContaining([
+ "read",
+ "mcp__notion__notion_search",
+ "mcp__notion__notion_create_pages",
+ "mcp__computer__screenshot",
+ ]),
+ );
+ expect(summary.childTools).not.toContain(PROPOSE_TOOL.name);
+ // The guard in the child refused the read of mcp.json; Notion ran each action once.
+ expect(summary.childResults[0]).toContain("private sign-ins or settings");
+ expect(summary.childResults[1]).toContain("notion ran notion-search");
+ expect(summary.childResults[2]).toContain("notion ran notion-create-pages");
+ // The child reached the app's own helper with its key, so the helper's grant applies (S24).
+ expect(summary.childResults[3]).toContain("computer ran screenshot");
+ expect(computer.keys).toEqual([`Bearer ${COMPUTER_KEY}`]);
+ expect(summary.notionCalls).toEqual(["notion-search", "notion-create-pages"]);
+ expect(summary.approvals).toHaveLength(1);
+ expect(lines.join("\n")).not.toMatch(/subagents are off/);
+ } finally {
+ console.log(lines.slice(-40).join("\n"));
+ }
+ });
+});