A local-first multi-agent app development platform, built on PenguinHarness
feat(core,server): an Agent's penguin is the CLI of the harness that runs it (#658)
Yaowei Zheng4dc558f4e699
diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.mdindex 65905b58..e886476c 100644--- a/.github/CONTRIBUTING.md+++ b/.github/CONTRIBUTING.md@@ -42,6 +42,14 @@ skills/core output, the prestep also clears the web app's Vite dep cacheotherwise keep serving the browser the previous core. `dev:docs` / `dev:landing`run the install check only (`--install-only`).+The prestep also builds `packages/cli`, because a dev server hands the Agents it runs the+CLI of the checkout it was started from: it writes a launcher at `<root>/bin/penguin`+pointing at `packages/cli/dist/penguin.js` and puts that directory at the front of every+command's PATH. Nothing rebuilds that file while a dev server runs — `tsx watch` covers the+server's own sources only — so after editing the CLI, run+`pnpm --filter @prismshadow/penguin-cli build` (or restart `pnpm dev`) before asking an+Agent to use it.+One rule when bypassing the dev commands: **rebuild skills/core through pnpm, in thatorder** (`pnpm build`, or restart `pnpm dev`) — the workspace uses injected dependencies(`injectWorkspacePackages` in pnpm-workspace.yaml), so web/server consume snapshot copiesdiff --git a/.github/CONTRIBUTING.zh.md b/.github/CONTRIBUTING.zh.mdindex 46675742..716398b9 100644--- a/.github/CONTRIBUTING.zh.md+++ b/.github/CONTRIBUTING.zh.md@@ -37,6 +37,12 @@ BASE_PATH=/ pnpm build:site # 完全按 Pages 部署的方式组装落地页 +Vite 依赖缓存(`packages/web/node_modules/.vite`)——该缓存仅以 lockfile/配置为键,否则会继续把上一版 core 喂给浏览器。`dev:docs` / `dev:landing` 只跑安装检查(`--install-only`)。+该预处理步骤还会构建 `packages/cli`:开发版 server 会把它所在检出的 CLI 交给它运行的 Agent——在+`<root>/bin/penguin` 写下一个指向 `packages/cli/dist/penguin.js` 的启动脚本,并把该目录置于每条命令+PATH 的最前。dev server 运行期间没有任何东西会重建那个文件(`tsx watch` 只覆盖 server 自身的源码),+因此改完 CLI 源码后,要先跑 `pnpm --filter @prismshadow/penguin-cli build`(或重启 `pnpm dev`),+再让 Agent 去用它。+绕开 dev 命令时有一条规则:**通过 pnpm 重新构建 skills/core,并按此顺序**(`pnpm build`,或重启`pnpm dev`)——工作区使用注入式依赖(pnpm-workspace.yaml 中的 `injectWorkspacePackages`),因此web/server 消费的是快照副本,只有当该包的 `build` 脚本经由 pnpm 运行时才会重新同步diff --git a/changelog/unreleased/2026-09-09-agent-cli-on-path.md b/changelog/unreleased/2026-09-09-agent-cli-on-path.mdnew file mode 100644index 00000000..c8af9eb4--- /dev/null+++ b/changelog/unreleased/2026-09-09-agent-cli-on-path.md@@ -0,0 +1,18 @@+# An Agent's `penguin` is the harness running it++- **Date:** 2026-09-09+- **Type:** feature+- **Scope:** `core`, `server`, `desktop`, `tooling`, `docs`+- **PR:** [#658](https://github.com/Prism-Shadow/penguin-harness/pull/658)++[中文版](2026-09-09-agent-cli-on-path.zh.md)++Every command an Agent runs now finds this installation's own `penguin` first on its PATH. The server writes a launcher script into its data root at `<root>/bin/penguin` — it runs the CLI entry this installation was started from, on the server's own Node — and each Session puts that directory at the front of PATH for the commands it spawns. A command that asks the harness to do something reaches the harness it is running inside, rather than whatever version the machine happens to have installed globally.++## Details++- The CLI entry is `PENGUIN_CLI_ENTRY` when the environment carries one — `penguin server` / `penguin web` export their own entry, and the desktop shell now passes the app's bundled CLI to the server process it forks. Otherwise the server resolves the checkout it was loaded from, walking up to the directory holding `pnpm-workspace.yaml` and taking its `packages/cli/dist/penguin.js` when that file exists. The entry, or the fact that none was found, is named in one line at boot.+- The launcher is rewritten at every start, so an installation that moved is picked up by the next one. With no entry to point at, a launcher left by an earlier start is removed instead: one aimed at a path that is no longer there is worse than no `penguin` at all. `<root>/bin/penguin.cmd` is written alongside it on Windows, where commands may run in either `cmd`/PowerShell or the bundled bash.+- The directory is prepended twice, in the child environment and again as a statement in front of the command string (`export PATH=…` for Bourne-family shells, `$env:PATH = …` for PowerShell, `set "PATH=…"` for `cmd`). Commands run through a login shell, whose profile routinely rewrites PATH after the child environment was set; only the statement runs late enough to decide. Shells whose PATH syntax is neither of those — `fish`, or whatever `PENGUIN_SHELL` names — get the environment half alone. The command itself is otherwise untouched, exit status included, and the command a host lists for a background process is still the one the Agent wrote.+- Hook scripts get the same directories at the front of their PATH. They are spawned directly, with no shell, so the environment is all there is to set.+- `scripts/dev-prebuild.mjs` now builds `packages/cli` alongside `packages/core`, so a dev server has a current CLI to point at. Editing the CLI's sources still needs `pnpm --filter @prismshadow/penguin-cli build` — `tsx watch` does not rebuild it.diff --git a/changelog/unreleased/2026-09-09-agent-cli-on-path.zh.md b/changelog/unreleased/2026-09-09-agent-cli-on-path.zh.mdnew file mode 100644index 00000000..c2488163--- /dev/null+++ b/changelog/unreleased/2026-09-09-agent-cli-on-path.zh.md@@ -0,0 +1,18 @@+# Agent 的 `penguin` 就是正在运行它的那套 harness++- **Date:** 2026-09-09+- **Type:** feature+- **Scope:** `core`, `server`, `desktop`, `tooling`, `docs`+- **PR:** [#658](https://github.com/Prism-Shadow/penguin-harness/pull/658)++[English](2026-09-09-agent-cli-on-path.md)++Agent 执行的每一条命令,现在都会在 PATH 最前面先找到本安装自己的 `penguin`。服务端会在其数据根目录写下一个启动脚本 `<root>/bin/penguin`——它用服务端自己的 Node 运行本安装启动时所用的那个 CLI 入口——每个 Session 则把该目录置于它所派生命令的 PATH 最前。于是一条要求 harness 做事的命令,触达的就是它正运行其中的那套 harness,而不是机器上恰好全局安装的那个版本。++## 细节++- CLI 入口在环境中带有 `PENGUIN_CLI_ENTRY` 时即取该值——`penguin server` / `penguin web` 会导出自身入口,桌面外壳现在也会把应用内置的 CLI 传给它 fork 出的服务端进程。否则由服务端解析它被加载自的那个检出:向上走到存放 `pnpm-workspace.yaml` 的目录,若其 `packages/cli/dist/penguin.js` 存在则取之。启动时会用一行日志点名该入口,或说明未找到任何入口。+- 该启动脚本在每次启动时重写,因此安装位置的变动会在下次启动被跟上。没有可指向的入口时,则删除早先启动留下的脚本:指向一个已不存在的路径,比根本没有 `penguin` 更糟。在 Windows 上还会一并写出 `<root>/bin/penguin.cmd`——那里的命令既可能跑在 `cmd`/PowerShell 里,也可能跑在内置的 bash 里。+- 该目录被前置了两次:一次在子进程环境中,一次作为命令字符串前的一条语句(Bourne 系 shell 用 `export PATH=…`,PowerShell 用 `$env:PATH = …`,`cmd` 用 `set "PATH=…"`)。命令经由登录 shell 执行,而登录 profile 往往会在子进程环境设定之后重写 PATH;只有这条语句执行得足够晚,才真正说了算。PATH 语法不属于这三种的 shell——`fish`,或 `PENGUIN_SHELL` 所指的任何东西——只得到环境那一半。除此之外命令原样不动,退出状态亦然,宿主为后台进程列出的命令仍是 Agent 自己写的那一条。+- Hook 脚本的 PATH 最前面也会得到同样的目录。它们是被直接派生的,中间没有 shell,因此能设置的就只有环境。+- `scripts/dev-prebuild.mjs` 现在会与 `packages/core` 一同构建 `packages/cli`,好让开发版 server 有一个当前的 CLI 可指向。改动 CLI 源码后仍需 `pnpm --filter @prismshadow/penguin-cli build`——`tsx watch` 不会重建它。diff --git a/packages/core/src/agent.ts b/packages/core/src/agent.tsindex 53d33320..6e0b5c86 100644--- a/packages/core/src/agent.ts+++ b/packages/core/src/agent.ts@@ -126,6 +126,15 @@ export interface CreateAgentOptions {* standalone use).*/controlEnv?: (ctx: ControlEnvContext) => Record<string, string>;+ /**+ * Directories put at the FRONT of PATH for the command subprocesses — and the hook+ * scripts — of every Session this Agent creates or resumes, and of its subagents'+ * Sessions, which inherit the getter like `proxyEnv`. The Web server points it at the+ * shim directory holding its own `penguin`, so a command an Agent runs reaches the CLI+ * of the harness that is running it rather than whatever is installed globally. Re-read+ * at every spawn. Absent = PATH is untouched (SDK/CLI standalone use).+ */+ pathPrepend?: () => string[];}/** The Session coordinates a {@link CreateAgentOptions.controlEnv} policy is evaluated with. */@@ -280,7 +289,7 @@ export async function createAgent(opts: CreateAgentOptions = {}): Promise<Agent>init: {},});const projectConfig = await loadProjectConfig(state.root, state.projectId);- return new Agent(state, projectConfig, opts.proxyEnv, opts.controlEnv);+ return new Agent(state, projectConfig, opts.proxyEnv, opts.controlEnv, opts.pathPrepend);}export class Agent {@@ -291,6 +300,8 @@ export class Agent {private readonly proxyEnv?: () => ProxyEnvPolicy | null,/** See {@link CreateAgentOptions.controlEnv}; evaluated per Session with that Session's coordinates. */private readonly controlEnv?: (ctx: ControlEnvContext) => Record<string, string>,+ /** See {@link CreateAgentOptions.pathPrepend}; forwarded into every Session's Environment and hooks. */+ private readonly pathPrepend?: () => string[],) {}/**@@ -823,6 +834,7 @@ export class Agent {// child Session's own coordinates....(parentAgent.proxyEnv ? { proxyEnv: parentAgent.proxyEnv } : {}),...(parentAgent.controlEnv ? { controlEnv: parentAgent.controlEnv } : {}),+ ...(parentAgent.pathPrepend ? { pathPrepend: parentAgent.pathPrepend } : {}),}): parentAgent;// The child Session follows the PARENT Session, never the Project default: with the@@ -870,6 +882,7 @@ export class Agent {agentId,...(parentAgent.proxyEnv ? { proxyEnv: parentAgent.proxyEnv } : {}),...(parentAgent.controlEnv ? { controlEnv: parentAgent.controlEnv } : {}),+ ...(parentAgent.pathPrepend ? { pathPrepend: parentAgent.pathPrepend } : {}),});const childSession = await childAgent.resumeSession({ sessionId });return subagentHandleFor(childSession);@@ -1026,6 +1039,7 @@ export class Agent {}),}: {}),+ ...(this.pathPrepend ? { pathPrepend: this.pathPrepend } : {}),});// The tool_call_id uniqueness registry is shared by every context's LLM object: its@@ -1167,17 +1181,24 @@ export class Agent {this.state.projectId,this.state.agentId,);+ // Hook scripts get the same PATH front as commands do (see+ // CreateAgentOptions.pathPrepend). Only the environment half applies: a hook is run as+ // `node <script>` directly, with no shell and so no login profile to re-prepend+ // anything after it.+ const pathPrepend = this.pathPrepend;const stop = installed.flatMap((hook) =>- hook.stop.map((cmd) => scriptStopHook(hook.name, hook.dir, cmd.command, cmd.timeout)),+ hook.stop.map((cmd) =>+ scriptStopHook(hook.name, hook.dir, cmd.command, cmd.timeout, pathPrepend),+ ),);const preToolUse = installed.flatMap((hook) =>hook.pre_tool_use.map((cmd) =>- scriptPreToolUseHook(hook.name, hook.dir, cmd.command, cmd.timeout),+ scriptPreToolUseHook(hook.name, hook.dir, cmd.command, cmd.timeout, pathPrepend),),);const userPrompt = installed.flatMap((hook) =>hook.user_prompt.map((cmd) =>- scriptUserPromptHook(hook.name, hook.dir, cmd.command, cmd.timeout),+ scriptUserPromptHook(hook.name, hook.dir, cmd.command, cmd.timeout, pathPrepend),),);if (stop.length === 0 && preToolUse.length === 0 && userPrompt.length === 0) return undefined;diff --git a/packages/core/src/environment/environment.ts b/packages/core/src/environment/environment.tsindex 6afc85f8..93de10ff 100644--- a/packages/core/src/environment/environment.ts+++ b/packages/core/src/environment/environment.ts@@ -174,6 +174,7 @@ export class Environment implements EnvironmentInterface {...(config.vault !== undefined ? { vault: config.vault } : {}),...(config.proxyEnv !== undefined ? { proxyEnv: config.proxyEnv } : {}),...(config.controlEnv !== undefined ? { controlEnv: config.controlEnv } : {}),+ ...(config.pathPrepend !== undefined ? { pathPrepend: config.pathPrepend } : {}),});this.subagentSessions = new SubagentSessionManager();// Background-task liveness fans in from both registries and from the subagent run-statediff --git a/packages/core/src/environment/tools/command/index.ts b/packages/core/src/environment/tools/command/index.tsindex 62c3e464..f9fd39af 100644--- a/packages/core/src/environment/tools/command/index.ts+++ b/packages/core/src/environment/tools/command/index.ts@@ -5,6 +5,7 @@ export { CommandSessionManager } from "./session-manager.js";export { ManagedSession, isStopSignal, resultForExit } from "./session.js";export type { ProcessExit, SpawnOptions } from "./session.js";export { resolveShell, sessionShell } from "./shell.js";+export { pathPrependPrefix, prependPathEnv } from "./path-prepend.js";export type { ShellInvocation, ResolveShellOptions } from "./shell.js";export {DEFAULT_EXEC_YIELD_MS,diff --git a/packages/core/src/environment/tools/command/path-prepend.ts b/packages/core/src/environment/tools/command/path-prepend.tsnew file mode 100644index 00000000..2ec5fc2e--- /dev/null+++ b/packages/core/src/environment/tools/command/path-prepend.ts@@ -0,0 +1,78 @@+/**+ * Putting a directory at the FRONT of PATH for something the harness spawns.+ *+ * Two forms, because a command needs both. {@link prependPathEnv} writes the child's+ * environment, which is all a directly spawned process (a hook script) ever sees. A+ * command, though, runs through a LOGIN shell, and a login profile routinely prepends+ * `/opt/homebrew/bin` or `/usr/local/bin` to whatever PATH it inherited — so the+ * environment alone leaves the harness's directory behind whatever the profile put in+ * front of it. {@link pathPrependPrefix} is the statement that runs after the profile and+ * decides.+ *+ * Nothing here has an opinion about WHAT is prepended: the host supplies the directories+ * (see `EnvironmentConfig.pathPrepend`).+ */+import path from "node:path";++/**+ * `env` with `dirs` at the front of its PATH entry — a new object; the argument is not+ * touched. An empty list returns it unchanged.+ *+ * The existing entry's own spelling is reused rather than writing `PATH`: Windows resolves+ * environment names case-insensitively but stores the casing it was given, so an+ * environment carrying `Path` would end up with two entries differing only in case, and+ * which one the child reads is not ours to decide.+ */+export function prependPathEnv(env: NodeJS.ProcessEnv, dirs: readonly string[]): NodeJS.ProcessEnv {+ if (dirs.length === 0) return env;+ const key = Object.keys(env).find((name) => name.toUpperCase() === "PATH") ?? "PATH";+ const current = env[key];+ const prefix = dirs.join(path.delimiter);+ return {+ ...env,+ [key]:+ current === undefined || current === "" ? prefix : `${prefix}${path.delimiter}${current}`,+ };+}++/**+ * Shells that take a Bourne-style `export NAME=value`. Everything the POSIX resolver can+ * pick (see shell.ts) except `fish`, which spells the same thing `set -x` and would fail+ * the whole command on an `export`.+ */+const EXPORT_PATH_SHELLS = new Set(["bash", "sh", "zsh", "ksh", "ksh93", "mksh", "dash", "ash"]);++/** A string as one POSIX shell word: single-quoted, with each embedded quote spliced as `'\''`. */+function posixQuote(value: string): string {+ return `'${value.replaceAll("'", `'\\''`)}'`;+}++/** A string as a PowerShell single-quoted literal, where a quote is escaped by doubling it. */+function powerShellQuote(value: string): string {+ return `'${value.replaceAll("'", "''")}'`;+}++/**+ * The statement that puts `dirs` at the front of PATH for one command, written in the+ * syntax of the shell that will run it and ending in that shell's separator, so+ * `pathPrependPrefix(...) + cmd` is a command string with the original command still last+ * — untouched, and still the one whose exit status the shell reports.+ *+ * `""` for an empty list, and for any shell whose PATH syntax is not one of the three+ * below — `fish`, and whatever basename `PENGUIN_SHELL` names. A prefix in the wrong+ * dialect would not misconfigure PATH, it would fail every command, so an unrecognized+ * shell keeps the child-environment prepend and nothing more.+ */+export function pathPrependPrefix(shellName: string, dirs: readonly string[]): string {+ if (dirs.length === 0) return "";+ if (shellName === "pwsh" || shellName === "powershell") {+ const prefix = dirs.map((dir) => `${powerShellQuote(dir)} + ';' + `).join("");+ return `$env:PATH = ${prefix}$env:PATH; `;+ }+ // cmd offers no quoting: a `%` in a directory would be read as a variable reference and+ // expanded here. What that costs is a prefix naming the wrong directory, not a mangled+ // PATH — the `;%PATH%` tail is unaffected.+ if (shellName === "cmd") return `set "PATH=${dirs.join(";")};%PATH%" && `;+ if (!EXPORT_PATH_SHELLS.has(shellName)) return "";+ return `export PATH=${dirs.map(posixQuote).join(":")}:"$PATH"; `;+}diff --git a/packages/core/src/environment/tools/command/session-manager.ts b/packages/core/src/environment/tools/command/session-manager.tsindex 6ec9a67e..25a0b827 100644--- a/packages/core/src/environment/tools/command/session-manager.ts+++ b/packages/core/src/environment/tools/command/session-manager.ts@@ -11,6 +11,7 @@*/import { statSync } from "node:fs";import { ManagedSession } from "./session.js";+import { prependPathEnv } from "./path-prepend.js";import { BackgroundRegistry } from "../background/index.js";import type { ProxyEnvPolicy } from "../../../interfaces/index.js";@@ -210,6 +211,14 @@ export class CommandSessionManager {* A getter like `proxyEnv`, re-read at every spawn. Absent = nothing injected.*/private readonly controlEnv: (() => Record<string, string>) | undefined;+ /**+ * Directories the host puts at the front of PATH for every command (see+ * {@link EnvironmentConfig.pathPrepend}): the hosting server points this at the shim+ * directory holding its own `penguin`, so an Agent's `penguin` is the harness it is+ * running inside rather than whatever the machine has installed globally. A getter like+ * `proxyEnv`, re-read at every spawn. Absent, or returning nothing = untouched PATH.+ */+ private readonly pathPrepend: (() => string[]) | undefined;/** Single change listener (see onChange); null until the Environment subscribes. */private changeListener: (() => void) | null = null;@@ -217,10 +226,12 @@ export class CommandSessionManager {vault?: Record<string, string>;proxyEnv?: () => ProxyEnvPolicy | null;controlEnv?: () => Record<string, string>;+ pathPrepend?: () => string[];}) {this.vault = opts?.vault ?? {};this.proxyEnv = opts?.proxyEnv;this.controlEnv = opts?.controlEnv;+ this.pathPrepend = opts?.pathPrepend;this.registry.onChange(() => this.changeListener?.());}@@ -250,9 +261,17 @@ export class CommandSessionManager {throw new Error("command session manager disposed");}assertUsableCwd(opts.cwd);+ // The host's directories go onto the INHERITED PATH, before the vault is spread over+ // it below: a vault `PATH` is an explicit per-Agent decision and still replaces the+ // whole value, prepended directories included. The same list is handed to the session+ // so the command string can re-assert it after the login profile has run — that is the+ // half that actually decides which `penguin` a command resolves (see ManagedSession).+ const prepend = this.pathPrepend?.() ?? [];+ const hostEnv = prependPathEnv(hostEnvForChild(this.proxyEnv?.() ?? null), prepend);return new ManagedSession({cmd: opts.cmd,cwd: opts.cwd,+ ...(prepend.length > 0 ? { pathPrepend: prepend } : {}),// Spread order is priority: vault overrides host variables of the same name; the// host's control variables (controlEnv) override the vault — they are the hosting// server's own wiring (API URL/token, Session coordinates) and a vault entry must@@ -271,7 +290,7 @@ export class CommandSessionManager {// values rather than as surviving copies. Pinned by the "an explicit injection// layered after the strip wins" test.env: {- ...hostEnvForChild(this.proxyEnv?.() ?? null),+ ...hostEnv,...this.vault,...(this.controlEnv?.() ?? {}),...HARDENED_ENV,diff --git a/packages/core/src/environment/tools/command/session.ts b/packages/core/src/environment/tools/command/session.tsindex 58459906..d5550a90 100644--- a/packages/core/src/environment/tools/command/session.ts+++ b/packages/core/src/environment/tools/command/session.ts@@ -29,6 +29,7 @@ import { spawn, spawnSync, type ChildProcess } from "node:child_process";import type { ToolResult } from "../types.js";import { CappedTextBuffer, WakeSignal } from "../background/index.js";import { sessionShell } from "./shell.js";+import { pathPrependPrefix } from "./path-prepend.js";import { ServiceUrlScanner } from "./service-url.js";import { probeGroupListenPorts } from "./port-probe.js";@@ -71,6 +72,14 @@ export interface SpawnOptions {cwd: string;/** Child process environment variables (the caller has already injected hardening entries like PAGER/TERM). */env: NodeJS.ProcessEnv;+ /**+ * Directories to put at the front of PATH from INSIDE the shell, as a statement prefixed+ * to the command string (see {@link pathPrependPrefix}). The caller has already put them+ * at the front of `env`'s PATH; this is the half that survives a login profile+ * re-prepending its own directories. Absent or empty = no prefix, and the command string+ * is spawned exactly as given.+ */+ pathPrepend?: readonly string[];}export class ManagedSession {@@ -98,7 +107,11 @@ export class ManagedSession {this.cmd = opts.cmd;this.cwd = opts.cwd;const shell = sessionShell();- this.child = spawn(shell.command, [...shell.args, opts.cmd], {+ // `cmd` above keeps the command as the caller wrote it — it is what the host lists and+ // what the model is shown; only the string actually handed to the shell carries the+ // PATH statement in front of it.+ const prefix = pathPrependPrefix(shell.name, opts.pathPrepend ?? []);+ this.child = spawn(shell.command, [...shell.args, prefix + opts.cmd], {cwd: opts.cwd,env: opts.env,detached: SUPPORTS_PROCESS_GROUP, // Become the process-group leader, so the whole group can be signaleddiff --git a/packages/core/src/hooks/script-hook.ts b/packages/core/src/hooks/script-hook.tsindex abf97f1c..8a9373ac 100644--- a/packages/core/src/hooks/script-hook.ts+++ b/packages/core/src/hooks/script-hook.ts@@ -23,6 +23,7 @@*/import { spawn } from "node:child_process";import path from "node:path";+import { prependPathEnv } from "../environment/tools/command/path-prepend.js";import type { StopHook, StopHookInput, StopHookResult } from "./stop-hook.js";import type { PreToolUseHook, PreToolUseHookInput, PreToolUseHookResult } from "./tool-hook.js";import type { UserPromptHook, UserPromptHookInput, UserPromptHookResult } from "./prompt-hook.js";@@ -38,6 +39,13 @@ export interface RunHookScriptOptions {cwd?: string;timeoutS?: number;signal?: AbortSignal;+ /**+ * Directories put at the front of the script's PATH (see+ * {@link CreateAgentOptions.pathPrepend}), so a hook that shells out to `penguin` reaches+ * the harness running it. Only the environment is involved here: a hook is spawned as+ * `node <script>`, with no shell to re-order PATH afterwards.+ */+ pathPrepend?: readonly string[];}/**@@ -58,7 +66,7 @@ export async function runHookScript(// In the desktop app process.execPath is the Electron binary: without this flag the// spawn boots a whole Electron app (GPU process and all) instead of running the// script, and dies on machines where that fails. A plain Node execPath ignores it.- env: { ...process.env, ELECTRON_RUN_AS_NODE: "1" },+ env: prependPathEnv({ ...process.env, ELECTRON_RUN_AS_NODE: "1" }, opts.pathPrepend ?? []),});let stdout = "";let stderr = "";@@ -180,6 +188,7 @@ function scriptRunner(dir: string,command: string,timeoutS: number | undefined,+ pathPrepend: (() => string[]) | undefined,): (input: Record<string, unknown>, signal: AbortSignal | undefined) => Promise<unknown> {const script = path.resolve(dir, command);return (input, signal) =>@@ -187,6 +196,9 @@ function scriptRunner(cwd: dir,...(timeoutS !== undefined ? { timeoutS } : {}),...(signal ? { signal } : {}),+ // Re-read per call, like the command-spawn side: the host may point it somewhere else+ // without the Session being rebuilt.+ ...(pathPrepend ? { pathPrepend: pathPrepend() } : {}),});}@@ -196,8 +208,9 @@ export function scriptUserPromptHook(dir: string,command: string,timeoutS?: number,+ pathPrepend?: () => string[],): UserPromptHook {- const run = scriptRunner(dir, command, timeoutS);+ const run = scriptRunner(dir, command, timeoutS, pathPrepend);return {name,async run(input: UserPromptHookInput): Promise<UserPromptHookResult | undefined> {@@ -223,8 +236,9 @@ export function scriptPreToolUseHook(dir: string,command: string,timeoutS?: number,+ pathPrepend?: () => string[],): PreToolUseHook {- const run = scriptRunner(dir, command, timeoutS);+ const run = scriptRunner(dir, command, timeoutS, pathPrepend);return {name,async run(input: PreToolUseHookInput): Promise<PreToolUseHookResult | undefined> {@@ -251,8 +265,9 @@ export function scriptStopHook(dir: string,command: string,timeoutS?: number,+ pathPrepend?: () => string[],): StopHook {- const run = scriptRunner(dir, command, timeoutS);+ const run = scriptRunner(dir, command, timeoutS, pathPrepend);return {name,async run(input: StopHookInput): Promise<StopHookResult | undefined> {diff --git a/packages/core/src/interfaces/environment.ts b/packages/core/src/interfaces/environment.tsindex b22ad40c..75c0c928 100644--- a/packages/core/src/interfaces/environment.ts+++ b/packages/core/src/interfaces/environment.ts@@ -311,6 +311,17 @@ export interface EnvironmentConfig {* is injected (SDK/CLI standalone use).*/controlEnv?: () => Record<string, string>;+ /**+ * Directories put at the FRONT of PATH for exec_command / input_command subprocesses+ * (see {@link CreateAgentOptions.pathPrepend}). Applied in two places, because one is+ * not enough: onto the inherited PATH of the child environment — before the vault, so a+ * vault `PATH` still replaces the whole inherited value — and as a statement in front of+ * the command string, which is what survives a login profile rewriting PATH after the+ * child environment was set. The statement runs last, so these directories lead whatever+ * PATH the shell ended up with, a vault `PATH` included. Re-read at every spawn like+ * `proxyEnv`. Absent, or a getter returning nothing = PATH is untouched.+ */+ pathPrepend?: () => string[];}/**diff --git a/packages/core/test/exec-session.test.ts b/packages/core/test/exec-session.test.tsindex 4f17284f..3646ec6e 100644--- a/packages/core/test/exec-session.test.ts+++ b/packages/core/test/exec-session.test.ts@@ -2,7 +2,7 @@* Behavior tests for long-running command sessions (exec_command yield + input_command).*/import { afterEach, beforeEach, describe, expect, it } from "vitest";-import { mkdtemp, rm, writeFile } from "node:fs/promises";+import { chmod, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";import path from "node:path";import { Environment, ManagedSession } from "../src/environment/index.js";@@ -677,6 +677,91 @@ describe("controlEnv injects the host's harness-control variables into commands"});});+describe.skipIf(process.platform === "win32")(+ "pathPrepend puts the host's own directories in front of a command's PATH",+ () => {+ // The hosting server threads a pathPrepend getter through Environment ->+ // CommandSessionManager so a command an Agent runs reaches the harness's own `penguin`+ // rather than whatever the machine has installed globally.+ // A shell BUILTIN, deliberately: these cases run with PATH rewritten out from under+ // them (that is the subject), so a reader that has to be found on PATH would be+ // reporting on its own resolvability as much as on the value. `export` puts the same+ // string in the environment any child would inherit.+ const READ_PATH = 'echo "P=[$PATH]"';+ let shimDir: string;+ let prepend: string[];+ let prepared: Environment;++ beforeEach(async () => {+ shimDir = path.join(tmp, "shim");+ await mkdir(shimDir, { recursive: true });+ const script = path.join(shimDir, "penguin");+ await writeFile(script, "#!/bin/sh\necho harness-cli\n");+ await chmod(script, 0o755);+ prepend = [shimDir];+ prepared = new Environment({+ workspaceDir: tmp,+ toolConfig: sessionConfig(),+ pathPrepend: () => prepend,+ });+ });++ afterEach(() => prepared.dispose());++ it("a bare command name resolves the prepended directory's copy", async () => {+ const res = await runTool(prepared, "exec_command", { cmd: "penguin" });+ expect(res.output).toContain("harness-cli");+ });++ it("the directory is FIRST on the PATH the command sees", async () => {+ // Not merely present: commands run through a LOGIN shell, whose profile rewrites PATH+ // after the child environment was set (on a Debian-family box /etc/profile replaces it+ // outright). Being in front of whatever that left is the whole point.+ const res = await runTool(prepared, "exec_command", { cmd: READ_PATH });+ expect(res.output).toContain(`P=[${shimDir}${path.delimiter}`);+ });++ it("a vault PATH does not displace it", async () => {+ // The vault replaces the inherited PATH the harness prepared; the statement in front+ // of the command runs afterwards, so the harness's own directory leads either way.+ // (The value still has to carry the session shell, which is spawned by bare name+ // against this very PATH — a vault entry without one is an ENOENT before any of this,+ // long-standing behaviour of a vault PATH rather than anything prepending changes.+ // Nothing else has to be there: the command below is a builtin.)+ const vaultEnv = new Environment({+ workspaceDir: tmp,+ toolConfig: sessionConfig(),+ vault: { PATH: "/usr/bin:/bin" },+ pathPrepend: () => prepend,+ });+ try {+ const res = await runTool(vaultEnv, "exec_command", { cmd: READ_PATH });+ expect(res.output).toContain(`P=[${shimDir}${path.delimiter}`);+ } finally {+ vaultEnv.dispose();+ }+ });++ it("the getter is re-read at every spawn: nothing prepended, nothing added", async () => {+ prepend = [];+ const res = await runTool(prepared, "exec_command", { cmd: READ_PATH });+ expect(res.output).not.toContain(shimDir);+ prepend = [shimDir];+ expect((await runTool(prepared, "exec_command", { cmd: "penguin" })).output).toContain(+ "harness-cli",+ );+ });++ it("the command the host lists is the one the Agent wrote, without the PATH statement", async () => {+ const cmd = "sleep 5";+ await runTool(prepared, "exec_command", { cmd, yield_time_ms: 200 });+ const listed = prepared.listBackgroundCommands();+ expect(listed).toHaveLength(1);+ expect(listed[0]!.cmd).toBe(cmd);+ });+ },+);+describe("exec_command — a working directory that is not there", () => {// Node reports an unusable `cwd` as `spawn <shell> ENOENT`: the error names the COMMAND,// so a Workspace deleted under a live Session reads exactly like a missing shell. Thesediff --git a/packages/core/test/hooks.test.ts b/packages/core/test/hooks.test.tsindex becf1e7f..36585b7b 100644--- a/packages/core/test/hooks.test.ts+++ b/packages/core/test/hooks.test.ts@@ -162,6 +162,18 @@ describe("script hooks", () => {expect(await runHookScript(quiet, {})).toBeUndefined();});+ it("pathPrepend puts the host's directories at the front of the script's PATH", async () => {+ // A hook is spawned as `node <script>` — no shell, so nothing re-orders PATH after+ // this. It is the same directory commands get (the harness's own CLI shim), so a hook+ // that shells out to `penguin` reaches the harness running it.+ const readPath = await write("path.mjs", answering("{ path: process.env.PATH }"));+ const out = (await runHookScript(readPath, {}, { pathPrepend: ["/opt/penguin/bin"] })) as {+ path: string;+ };+ expect(out.path.startsWith(`/opt/penguin/bin${path.delimiter}`)).toBe(true);+ expect(out.path).toContain(process.env.PATH ?? "");+ });+it("a non-zero exit, non-JSON stdout, and a timeout each fail with a reason", async () => {const crash = await write("crash.mjs", 'process.stderr.write("kaboom\\n"); process.exit(3);\n');await expect(runHookScript(crash, {})).rejects.toThrow(/exit 3: kaboom/);diff --git a/packages/core/test/path-prepend.test.ts b/packages/core/test/path-prepend.test.tsnew file mode 100644index 00000000..a03338b7--- /dev/null+++ b/packages/core/test/path-prepend.test.ts@@ -0,0 +1,145 @@+/**+ * Unit tests for putting a directory at the front of PATH: the child-environment half+ * (pure), the per-shell command statement (pure), and one real `bash -lc` spawn proving the+ * statement actually decides which of two same-named executables a command resolves.+ */+import { afterAll, describe, expect, it } from "vitest";+import { spawnSync } from "node:child_process";+import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import path from "node:path";+import {+ pathPrependPrefix,+ prependPathEnv,+} from "../src/environment/tools/command/path-prepend.js";++describe("prependPathEnv", () => {+ it("puts the directories in front of the inherited PATH, in order", () => {+ const env = prependPathEnv({ PATH: "/usr/bin:/bin" }, ["/a", "/b"]);+ expect(env.PATH).toBe(`/a${path.delimiter}/b${path.delimiter}/usr/bin:/bin`);+ });++ it("does not touch the environment it was given", () => {+ const original = { PATH: "/usr/bin" };+ prependPathEnv(original, ["/a"]);+ expect(original.PATH).toBe("/usr/bin");+ });++ it("writes back through the entry's OWN spelling, so Windows does not end up with two", () => {+ // Windows resolves environment names case-insensitively but stores the casing it was+ // given: writing `PATH` beside an inherited `Path` would leave the child with two+ // entries and no say in which one it reads.+ const env = prependPathEnv({ Path: "C:\\Windows", SystemRoot: "C:\\Windows" }, ["C:\\shim"]);+ expect(env.Path).toBe(`C:\\shim${path.delimiter}C:\\Windows`);+ expect(env.PATH).toBeUndefined();+ });++ it("sets PATH when the environment carries none, or an empty one", () => {+ expect(prependPathEnv({}, ["/a"]).PATH).toBe("/a");+ expect(prependPathEnv({ PATH: "" }, ["/a"]).PATH).toBe("/a");+ });++ it("an empty list changes nothing", () => {+ expect(prependPathEnv({ PATH: "/usr/bin" }, []).PATH).toBe("/usr/bin");+ });+});++describe("pathPrependPrefix", () => {+ it("Bourne-family shells get an `export`, with the directory quoted", () => {+ for (const shell of ["bash", "sh", "zsh", "dash", "ksh", "ash", "mksh", "ksh93"]) {+ expect(pathPrependPrefix(shell, ["/opt/penguin/bin"]), shell).toBe(+ `export PATH='/opt/penguin/bin':"$PATH"; `,+ );+ }+ });++ it("several directories keep their order, each its own quoted word", () => {+ expect(pathPrependPrefix("bash", ["/a", "/b"])).toBe(`export PATH='/a':'/b':"$PATH"; `);+ });++ it("a quote in the directory cannot break out of the word", () => {+ expect(pathPrependPrefix("bash", ["/home/anne's/bin"])).toBe(+ `export PATH='/home/anne'\\''s/bin':"$PATH"; `,+ );+ });++ it("pwsh and powershell get an $env:PATH assignment with `;` as the separator", () => {+ for (const shell of ["pwsh", "powershell"]) {+ expect(pathPrependPrefix(shell, ["C:\\shim"]), shell).toBe(+ `$env:PATH = 'C:\\shim' + ';' + $env:PATH; `,+ );+ }+ // PowerShell escapes a quote inside a literal by doubling it.+ expect(pathPrependPrefix("pwsh", ["C:\\it's"])).toBe(+ `$env:PATH = 'C:\\it''s' + ';' + $env:PATH; `,+ );+ });++ it("cmd gets a `set` joined with && so the command still reports its own errorlevel", () => {+ expect(pathPrependPrefix("cmd", ["C:\\shim"])).toBe(`set "PATH=C:\\shim;%PATH%" && `);+ });++ it("a shell whose PATH syntax is not one of those gets nothing at all", () => {+ // fish has no `export`; an unrecognized PENGUIN_SHELL basename is anyone's guess. A+ // prefix in the wrong dialect would fail every command, so neither gets one — the+ // child-environment prepend still applies to both.+ expect(pathPrependPrefix("fish", ["/a"])).toBe("");+ expect(pathPrependPrefix("nu", ["/a"])).toBe("");+ });++ it("an empty list produces no prefix for any shell", () => {+ for (const shell of ["bash", "pwsh", "cmd", "fish"]) {+ expect(pathPrependPrefix(shell, []), shell).toBe("");+ }+ });+});++describe.skipIf(process.platform === "win32")(+ "the Bourne prefix decides which executable a command resolves",+ () => {+ const tmp = mkdtempSync(path.join(tmpdir(), "penguin-path-prepend-"));+ const shimDir = path.join(tmp, "shim");+ const globalDir = path.join(tmp, "global");++ for (const [dir, word] of [+ [shimDir, "shim"],+ [globalDir, "global"],+ ] as const) {+ mkdirSync(dir, { recursive: true });+ const script = path.join(dir, "penguin");+ writeFileSync(script, `#!/bin/sh\necho ${word}\nexit 7\n`);+ chmodSync(script, 0o755);+ }++ afterAll(() => rmSync(tmp, { recursive: true, force: true }));++ /** Runs `cmd` the way a command session does: the resolved shell, `-lc`, one string. */+ function run(cmd: string, dirs: string[]): { stdout: string; status: number | null } {+ const res = spawnSync("bash", ["-lc", pathPrependPrefix("bash", dirs) + cmd], {+ env: { ...process.env, PATH: `${globalDir}${path.delimiter}${process.env.PATH ?? ""}` },+ encoding: "utf8",+ });+ return { stdout: res.stdout, status: res.status };+ }++ it("the child environment alone does not decide it", () => {+ // `-lc` reads the login profile, which is free to rewrite PATH over whatever the+ // child environment carried — on a Debian-family box /etc/profile replaces it+ // outright, so the shim directory is not merely demoted, it is gone. Whatever the+ // profile did, what a bare command resolves is not the harness's copy.+ expect(run("penguin", []).stdout.trim()).not.toBe("shim");+ });++ it("with the prefix the prepended directory wins, however the profile left PATH", () => {+ expect(run("penguin", [shimDir]).stdout.trim()).toBe("shim");+ });++ it("the command's own stdout and exit status pass through untouched", () => {+ const res = run("penguin", [shimDir]);+ expect(res.stdout.trim()).toBe("shim");+ // The prefix is a statement, not a wrapper: the command is still last, so the shell+ // reports ITS status.+ expect(res.status).toBe(7);+ });+ },+);diff --git a/packages/desktop/src/launcher.ts b/packages/desktop/src/launcher.tsindex 876bddef..9db5860f 100644--- a/packages/desktop/src/launcher.ts+++ b/packages/desktop/src/launcher.ts@@ -9,10 +9,34 @@* working `penguin` command without any system Node installation. How bin/ reaches* PATH is per platform (see cli-install.ts and build/linux/*.tpl for the deb variant).*/+import path from "node:path";/** CLI bundle inside the app directory, emitted by tsup alongside the shell (asar off). */export const CLI_ENTRY_RELPATH = "dist/penguin.js";+/**+ * The CLI entry the embedded server should offer the Agents it runs — handed to it as+ * `PENGUIN_CLI_ENTRY`, which is what the server's `<root>/bin/penguin` shim execs (see the+ * server's services/cli-shim.ts). It is the same bundled entry the PATH launchers above+ * run, and it is passed explicitly because nothing else would carry it: the fork inherits+ * `process.env`, where the variable is deliberately absent — the login-shell import+ * excludes it precisely so a profile line written for a checkout cannot retarget an+ * installed app.+ *+ * An explicit `PENGUIN_CLI_ENTRY` in the launch environment still wins, as it does for+ * `PENGUIN_WEB_DIST`. A source run pins nothing: the app directory holds no bundled CLI+ * there, and the server's own fallback finds the checkout's `packages/cli/dist/penguin.js`.+ */+export function embeddedCliEntry(opts: {+ isPackaged: boolean;+ appPath: string;+ env: NodeJS.ProcessEnv;+}): string | null {+ const explicit = opts.env.PENGUIN_CLI_ENTRY?.trim();+ if (explicit) return explicit;+ return opts.isPackaged ? path.join(opts.appPath, ...CLI_ENTRY_RELPATH.split("/")) : null;+}+/*** Present in every launcher script below, and shipped unchanged in every desktop release* since 0.2.2 — which is what lets cli-link.ts recognise a `penguin` this app wrote,diff --git a/packages/desktop/src/main.ts b/packages/desktop/src/main.tsindex 9fdc2158..0e5da442 100644--- a/packages/desktop/src/main.ts+++ b/packages/desktop/src/main.ts@@ -34,6 +34,7 @@ import { app, BrowserWindow, dialog, shell } from "electron";import { resolveRoot } from "@prismshadow/penguin-core";import { liveServerLock } from "@prismshadow/penguin-server/lock";import { appIdentity, desktopDataRoot } from "./app-identity.js";+import { embeddedCliEntry } from "./launcher.js";import { webDistEntry, webDistFor } from "./web-dist.js";import { resolveWindowIcon } from "./app-icon.js";import { installCliCommand, ensureCliCommand, currentCliInstallKind } from "./cli-install.js";@@ -184,6 +185,11 @@ async function startServerAndWindow(dataRoot: string): Promise<void> {const started = await startEmbeddedServer({dataRoot,webDist,+ cliEntry: embeddedCliEntry({+ isPackaged: app.isPackaged,+ appPath: app.getAppPath(),+ env: process.env,+ }),portFile: path.join(app.getPath("userData"), "server-port"),preferredPortFile: path.join(app.getPath("userData"), "preferred-port"),log: (chunk) => process.stdout.write(`[server] ${chunk}`),diff --git a/packages/desktop/src/server-process.ts b/packages/desktop/src/server-process.tsindex 8a9e5fa9..e26ab2af 100644--- a/packages/desktop/src/server-process.ts+++ b/packages/desktop/src/server-process.ts@@ -10,6 +10,7 @@ import fs from "node:fs";import path from "node:path";import { app, utilityProcess } from "electron";import type { UtilityProcess } from "electron";+import { embeddedCliEntry } from "./launcher.js";import { osProxyEnv } from "./os-proxy.js";import { choosePort, readPreferredPort, rememberPreferredPort } from "./port-memory.js";import { appOriginFor, parsePortFile } from "./util.js";@@ -105,6 +106,11 @@ export async function startEmbeddedServer(opts: {dataRoot: string;/** Pinned web dist (packaged app), or null to leave it to the server's default lookup. */webDist: string | null;+ /**+ * Bundled CLI entry the server offers the Agents it runs (see launcher.ts's+ * embeddedCliEntry), or null to leave it to the server's own checkout lookup.+ */+ cliEntry: string | null;portFile: string;preferredPortFile: string;log: (chunk: string) => void;@@ -124,6 +130,7 @@ export async function startEmbeddedServer(opts: {...(await osProxyEnv()),PENGUIN_HOME: opts.dataRoot,...(opts.webDist !== null ? { PENGUIN_WEB_DIST: opts.webDist } : {}),+ ...(opts.cliEntry !== null ? { PENGUIN_CLI_ENTRY: opts.cliEntry } : {}),HOST: "127.0.0.1",PORT: String(requestedPort),PENGUIN_DESKTOP_TOKEN: token,diff --git a/packages/desktop/test/launcher.test.ts b/packages/desktop/test/launcher.test.tsindex 72babed0..3311a6e9 100644--- a/packages/desktop/test/launcher.test.ts+++ b/packages/desktop/test/launcher.test.ts@@ -9,6 +9,7 @@ import {appleScriptString,CLI_ENTRY_RELPATH,cliInstallKind,+ embeddedCliEntry,LAUNCHER_MARKER,LINUX_EXECUTABLE,MAC_EXECUTABLE,@@ -303,3 +304,30 @@ describe("packaged CLI", () => {expect(afterRemove).toContain("rm -f '/usr/bin/penguin'");});});++describe("embeddedCliEntry", () => {+ it("points a packaged app's server at the bundled CLI it also puts on PATH", () => {+ expect(embeddedCliEntry({ isPackaged: true, appPath: "/opt/app/resources/app", env: {} })).toBe(+ path.join("/opt/app/resources/app", ...CLI_ENTRY_RELPATH.split("/")),+ );+ });++ it("leaves a source run to the server's own checkout lookup", () => {+ // A checkout has no bundled CLI beside the shell; the server finds+ // packages/cli/dist/penguin.js by walking to the workspace root instead.+ expect(+ embeddedCliEntry({ isPackaged: false, appPath: "/src/packages/desktop", env: {} }),+ ).toBeNull();+ });++ it("an explicit PENGUIN_CLI_ENTRY wins in both forms; blank counts as unset", () => {+ for (const isPackaged of [true, false]) {+ expect(+ embeddedCliEntry({ isPackaged, appPath: "/x", env: { PENGUIN_CLI_ENTRY: "/srv/cli.js" } }),+ ).toBe("/srv/cli.js");+ }+ expect(+ embeddedCliEntry({ isPackaged: true, appPath: "/x", env: { PENGUIN_CLI_ENTRY: " " } }),+ ).toBe(path.join("/x", ...CLI_ENTRY_RELPATH.split("/")));+ });+});diff --git a/packages/docs/content/configuration.en.md b/packages/docs/content/configuration.en.mdindex aabb2a4b..6a217b4b 100644--- a/packages/docs/content/configuration.en.md+++ b/packages/docs/content/configuration.en.md@@ -22,8 +22,11 @@ The CLI and the server automatically load a `.env` file from the working directo| `PENGUIN_LANG` | CLI language (`en` / `zh`), set via `penguin config lang` | `en` || `PENGUIN_UPDATE_CHECK` | `off` disables the web app's new-release check (the server's only outbound internet call) | enabled || `PENGUIN_NO_LOGIN_SHELL_ENV` | Any non-empty value stops the desktop app from importing the login shell's environment on macOS/Linux GUI launches (see [Desktop quickstart](/quickstart-desktop)) | unset — the import runs, filling only variables the launch left unset |+| `PENGUIN_CLI_ENTRY` | The CLI entry script this installation offers the Agents it runs (see below) | set for you by `penguin server` / `penguin web` and by the desktop app; falls back to the checkout's own `packages/cli/dist/penguin.js` when the server was started from one |-These configure PenguinHarness itself, so `PORT`, `HOST`, `PENGUIN_WEB_DIST` and the internal `PENGUIN_CLI_ENTRY` are **removed from the environment of commands the Agent runs** — otherwise a dev server started by `exec_command` would read `PORT` and try to bind the port meant for PenguinHarness instead of choosing its own. The rest of the host environment passes through, with one further exception: `GIT_EDITOR`, `GIT_TERMINAL_PROMPT`, `TERM`, `NO_COLOR`, `PAGER` and `GIT_PAGER` are always forced to fixed values, so that a command cannot hang waiting on an editor, a credential prompt or a pager. The Agent's [vault](#vault) is applied on top of the host environment — setting `PORT` there does reach commands — but not on top of those six.+These configure PenguinHarness itself, so `PORT`, `HOST`, `PENGUIN_WEB_DIST` and `PENGUIN_CLI_ENTRY` are **removed from the environment of commands the Agent runs** — otherwise a dev server started by `exec_command` would read `PORT` and try to bind the port meant for PenguinHarness instead of choosing its own. The rest of the host environment passes through, with one further exception: `GIT_EDITOR`, `GIT_TERMINAL_PROMPT`, `TERM`, `NO_COLOR`, `PAGER` and `GIT_PAGER` are always forced to fixed values, so that a command cannot hang waiting on an editor, a credential prompt or a pager. The Agent's [vault](#vault) is applied on top of the host environment — setting `PORT` there does reach commands — but not on top of those six.++One thing travels the other way: **this installation's own `penguin` is first on the PATH of every command an Agent runs**. At startup the server writes a launcher script at `<root>/bin/penguin` — it runs the CLI entry named above, on the server's own Node — and puts that directory at the front of PATH for each command. So `penguin` inside a command is the harness the Agent is running in, whatever version happens to be installed globally on the machine. The directory is prepended inside the shell as well as in the environment, because commands run through a login shell whose profile routinely rewrites PATH afterwards; that also puts it ahead of a `PATH` set in the [vault](#vault), which otherwise replaces the inherited value outright. The launcher is rewritten at every start, so a moved installation is picked up by the next one, and when there is no entry to point at none is written and `penguin` resolves however it did before.`PENGUIN_PREVIEW_ORIGIN` must differ from the app's origin by **hostname**, not just port: cookies ignore ports, so a second port would still share the session cookie. Leave it unset for local use — the app is canonicalized onto `localhost` and previews are served from `127.0.0.1`, which needs no configuration and no DNS. Set it when the app is reached over a LAN address or a real domain; otherwise previews there fall back to a same-origin sandbox where `localStorage`, cookies and third-party embeds do not work. When you do set it on a real domain, keep the session cookie host-only (no `Domain=`), or a sibling subdomain shares it. An unparseable value is a startup error rather than a silent fallback.diff --git a/packages/docs/content/configuration.zh.md b/packages/docs/content/configuration.zh.mdindex eb4810f0..fc8a0a97 100644--- a/packages/docs/content/configuration.zh.md+++ b/packages/docs/content/configuration.zh.md@@ -22,8 +22,11 @@ CLI 与服务端启动时会自动加载工作目录下的 `.env` 文件。| `PENGUIN_LANG` | CLI 语言(`en` / `zh`),用 `penguin config lang` 设置 | `en` || `PENGUIN_UPDATE_CHECK` | 设为 `off` 关闭 Web 应用的新版本检查(服务端唯一的对外网络请求) | 开启 || `PENGUIN_NO_LOGIN_SHELL_ENV` | 任意非空值可禁止桌面版在 macOS/Linux 图形界面启动时导入登录 shell 环境变量(见[桌面版速上手](/quickstart-desktop)) | 未设置,导入开启,且只补启动环境中缺失的变量 |+| `PENGUIN_CLI_ENTRY` | 本安装提供给其所运行 Agent 的 CLI 入口脚本(见下文) | 由 `penguin server` / `penguin web` 与桌面版自动设置;若服务端从仓库检出启动,则回退到该检出的 `packages/cli/dist/penguin.js` |-这些变量配置的是 PenguinHarness 自身,因此 `PORT`、`HOST`、`PENGUIN_WEB_DIST` 以及内部使用的 `PENGUIN_CLI_ENTRY` **不会出现在 Agent 所执行命令的环境变量中**——否则 `exec_command` 启动的开发服务器会读到 `PORT`,去占用留给 PenguinHarness 的端口,而不是自己另选一个。宿主环境中的其余变量原样透传,但还有一处例外:`GIT_EDITOR`、`GIT_TERMINAL_PROMPT`、`TERM`、`NO_COLOR`、`PAGER`、`GIT_PAGER` 一律被固定值覆盖,以免命令因等待编辑器、凭证输入或分页器而挂起。Agent 的 [vault](#vault) 覆盖在宿主环境之上——在 vault 里设置 `PORT` 仍然可以送达命令——但覆盖不了这六个变量。+这些变量配置的是 PenguinHarness 自身,因此 `PORT`、`HOST`、`PENGUIN_WEB_DIST` 与 `PENGUIN_CLI_ENTRY` **不会出现在 Agent 所执行命令的环境变量中**——否则 `exec_command` 启动的开发服务器会读到 `PORT`,去占用留给 PenguinHarness 的端口,而不是自己另选一个。宿主环境中的其余变量原样透传,但还有一处例外:`GIT_EDITOR`、`GIT_TERMINAL_PROMPT`、`TERM`、`NO_COLOR`、`PAGER`、`GIT_PAGER` 一律被固定值覆盖,以免命令因等待编辑器、凭证输入或分页器而挂起。Agent 的 [vault](#vault) 覆盖在宿主环境之上——在 vault 里设置 `PORT` 仍然可以送达命令——但覆盖不了这六个变量。++有一样东西是反向流动的:**本安装自己的 `penguin` 会排在 Agent 所执行的每一条命令的 PATH 最前面**。服务端启动时会在 `<root>/bin/penguin` 写下一个启动脚本——它用服务端自己的 Node 运行上表所指的 CLI 入口——并把该目录置于每条命令 PATH 的最前。于是命令里的 `penguin` 就是该 Agent 正运行其中的这套 harness,而不是机器上全局安装的那个版本。该目录既写进子进程环境,也在 shell 内部再前置一次:命令经由登录 shell 执行,而登录 profile 往往会在子进程环境设定之后重写 PATH;这同时意味着它也排在 [vault](#vault) 中设置的 `PATH` 之前——而 vault 里的 `PATH` 本身是整体替换继承值的。该脚本在每次启动时重写,因此安装位置变动会在下次启动被跟上;没有可指向的入口时则不写,`penguin` 的解析与此前无异。`PENGUIN_PREVIEW_ORIGIN` 必须与应用源在**主机名**上不同,只换端口不行:Cookie 不区分端口,换端口仍然共用会话 Cookie。本地使用不必配置——App 固定在规范主机 `localhost`,预览用 `127.0.0.1`,既不需要配置也不需要 DNS。经 LAN 地址或真实域名访问时才需要设置,否则那里的预览会回退到同源沙箱,`localStorage`、Cookie 与第三方 embed 都不可用。在真实域名上设置时,会话 Cookie 必须保持 host-only(不带 `Domain=`),否则同注册域下的兄弟子域会共享它。取值无法解析时启动即报错,不会静默回退。diff --git a/packages/server/README.md b/packages/server/README.mdindex f38823c5..434640ba 100644--- a/packages/server/README.md+++ b/packages/server/README.md@@ -22,6 +22,7 @@ The full route tables and the SSE protocol are documented in the [Server API ref| `PENGUIN_WEB_DB` | SQLite file path | `<root>/web.db` || `PENGUIN_WEB_DIST` | Front-end build dir (static hosting + SPA fallback when present) | `../web/dist`, or the bundled `web-dist/` in the npm package || `PENGUIN_TRUST_PROXY` | Trust `x-forwarded-proto` (`1` to enable): it opens the hot-update network gate over proxied HTTPS and marks session cookies `Secure` — only behind a reverse proxy that sets/strips the header itself | unset (untrusted) |+| `PENGUIN_CLI_ENTRY` | CLI entry script offered to the Agents this server runs: it is written into `<root>/bin/penguin` and put at the front of every command's PATH | `penguin server\|web` and the desktop shell set it; otherwise the entry of the checkout this server was started from, when it has one |`.env` in the process cwd is loaded automatically.diff --git a/packages/server/src/app.ts b/packages/server/src/app.tsindex 07a712f2..777ce2a8 100644--- a/packages/server/src/app.ts+++ b/packages/server/src/app.ts@@ -43,6 +43,7 @@ import {RuntimeCapabilities,} from "./hmr/capabilities.js";import type { ProxyControl } from "./hmr/capabilities.js";+import { cliShimDir, ensureCliShim } from "./services/cli-shim.js";import { openDatabase } from "./db/database.js";import { MachinesRepo } from "./db/repos/machines.js";import { migrate } from "./db/migrations.js";@@ -332,6 +333,23 @@ export async function bootAppDeps(// when it cannot be persisted: the browser then simply never sweeps.ensureInstallId(config.root);+ // The `penguin` an Agent's commands resolve: this harness's own CLI, written into the+ // data root for every Session to put at the front of PATH (see services/cli-shim.ts).+ // Here rather than per App, for the same reason the two above are: it is a fact about+ // this PROCESS's installation, and a hot-pushed platform — compiled somewhere else+ // entirely — has no way to work out where the CLI it should point at lives.+ const shimLog = overrides.log ?? ((line: string) => console.log(line));+ const shim = ensureCliShim(config.root, config.cliEntry);+ if (shim.kind === "written") {+ shimLog(`Agent CLI: ${path.join(shim.dir, "penguin")} -> ${shim.entry}`);+ } else if (shim.kind === "absent") {+ shimLog(+ "Agent CLI: no CLI entry found; commands an Agent runs resolve `penguin` on their own PATH.",+ );+ } else {+ console.warn(`[server] could not write the penguin CLI shim: ${shim.reason}`);+ }+// The capability set buildAppDeps claims (see hmr/capabilities.ts) — every// entry must be in place before ensure() below performs the first boot. The interface// descriptor leads: it is what a bundle's handshake reads before trusting any of the rest.@@ -849,6 +867,14 @@ export function buildAppDeps(: (loopbackHostRoles(config.host)?.app ?? config.host);return `http://${host}:${config.port}`;};+ // The directory core puts at the FRONT of PATH for every command an Agent runs (and for+ // its hook scripts): the shim directory bootAppDeps wrote this harness's own `penguin`+ // into. Derived from the config rather than passed along, so the platform half needs no+ // new capability — and read for truth rather than for null, because a runtime older than+ // this field publishes a config without it and wrote no shim either: no field, no+ // directory, feature off, rather than a push declined over a PATH entry.+ const shimDir = config.cliEntry ? cliShimDir(config.root) : null;+ const pathPrepend = (): string[] => (shimDir === null ? [] : [shimDir]);const controlEnv = (ctx: ControlEnvContext): Record<string, string> => {const token = authService.localApiToken();return {@@ -939,7 +965,7 @@ export function buildAppDeps(channels,loader:overrides.loader ??- createCoreSessionLoader(config.root, sessionSources, { proxyEnv, controlEnv }),+ createCoreSessionLoader(config.root, sessionSources, { proxyEnv, controlEnv, pathPrepend }),sources: sessionSources,recorder,errors,@@ -1036,6 +1062,7 @@ export function buildAppDeps(traceIndex,proxyEnv,controlEnv,+ pathPrepend,// List rows carry the ENABLED channel's indicator (saved-but-dark configs stay off// the row); a point query per row keeps the repo out of the service. An unknown// stored channel reads as none (same defensive skip as the bridge and the routes).diff --git a/packages/server/src/config.ts b/packages/server/src/config.tsindex e6e43724..4aa3b932 100644--- a/packages/server/src/config.ts+++ b/packages/server/src/config.ts@@ -13,6 +13,7 @@ import fs from "node:fs";import path from "node:path";import { fileURLToPath } from "node:url";import { DEFAULT_SERVER_PORT, resolveRoot } from "@prismshadow/penguin-core";+import { checkoutCliEntry } from "./services/cli-shim.js";export interface ServerConfig {/** Local data root directory (shared with the SDK/CLI). */@@ -84,6 +85,20 @@ export interface ServerConfig {* cookies WITHOUT the `Secure` flag (auth/middleware.ts cookieOptions).*/trustProxy: boolean;+ /**+ * The CLI entry script this harness offers to the Agents it runs — the file the+ * `<root>/bin/penguin` shim execs (see services/cli-shim.ts). `PENGUIN_CLI_ENTRY` when+ * set: `penguin server|web` exports its own entry there, and the desktop shell passes+ * the bundled one to the server it forks. Otherwise the entry of the checkout this+ * server was started from, when it has a built one. Null = no CLI to offer, and no shim+ * is written.+ *+ * Related to but wider than the self-update endpoint's use of the same variable+ * (http/routes/version.ts), which accepts only an INSTALLED entry it can re-run as+ * `penguin update`: a checkout has no release to update to, but its CLI is exactly the+ * one an Agent working on that checkout should be running.+ */+ cliEntry: string | null;}const DAY_MS = 24 * 60 * 60 * 1000;@@ -102,6 +117,16 @@ function defaultWebDist(): string {return path.resolve(here, "..", "..", "web", "dist");}+/**+ * The CLI entry of the checkout this server module lives in, resolved from the module's+ * own location (`packages/server/src/…` under tsx, `packages/server/dist/…` when built,+ * the desktop shell's bundle in a source desktop run — all reached by the same walk to the+ * workspace root). Null outside a checkout, and null when its CLI has not been built.+ */+function defaultCliEntry(): string | null {+ return checkoutCliEntry(path.dirname(fileURLToPath(import.meta.url)));+}+/*** Validates PENGUIN_PREVIEW_ORIGIN into a bare origin, or throws. An unparseable value* is a hard failure rather than a silent fallback: falling back would quietly serve@@ -121,7 +146,7 @@ function normalizePreviewOrigin(raw: string | undefined): string | null {return url.origin;}-/** Parses server config from environment variables (PORT / HOST / PENGUIN_HOME / PENGUIN_WEB_DIST / PENGUIN_WEB_DB / PENGUIN_PREVIEW_ORIGIN / PENGUIN_SEED_ADMIN_PASSWORD / PENGUIN_DESKTOP_TOKEN / PENGUIN_PORT_FILE / PENGUIN_TRUST_PROXY). */+/** Parses server config from environment variables (PORT / HOST / PENGUIN_HOME / PENGUIN_WEB_DIST / PENGUIN_WEB_DB / PENGUIN_PREVIEW_ORIGIN / PENGUIN_SEED_ADMIN_PASSWORD / PENGUIN_DESKTOP_TOKEN / PENGUIN_PORT_FILE / PENGUIN_TRUST_PROXY / PENGUIN_CLI_ENTRY). */export function resolveServerConfig(env: NodeJS.ProcessEnv = process.env): ServerConfig {const root = env.PENGUIN_HOME ?? resolveRoot();// An empty PORT string is treated as unset (the common `.env` case of an empty@@ -152,5 +177,6 @@ export function resolveServerConfig(env: NodeJS.ProcessEnv = process.env): ServeportFile: env.PENGUIN_PORT_FILE?.trim() || null,trustProxy: env.PENGUIN_TRUST_PROXY === "1",supervised: env.PENGUIN_SUPERVISED === "1",+ cliEntry: env.PENGUIN_CLI_ENTRY?.trim() || defaultCliEntry(),};}diff --git a/packages/server/src/runtime/session-manager.ts b/packages/server/src/runtime/session-manager.tsindex 768f9ab6..5585ea9b 100644--- a/packages/server/src/runtime/session-manager.ts+++ b/packages/server/src/runtime/session-manager.ts@@ -222,7 +222,9 @@ export interface SessionLoader {* agent-command-subprocess policy: strip the proxy variables, inject the explicit proxy* address, or null = pass the environment through). `opts.controlEnv` threads the* harness-control injection the same way (the server's API URL/token plus the Session's- * coordinates; core evaluates it per Session — see CreateAgentOptions.controlEnv).+ * coordinates; core evaluates it per Session — see CreateAgentOptions.controlEnv), and+ * `opts.pathPrepend` the directories every command of a resumed Session finds at the front+ * of its PATH (the harness's own CLI shim — see CreateAgentOptions.pathPrepend).*/export function createCoreSessionLoader(root: string,@@ -230,6 +232,7 @@ export function createCoreSessionLoader(opts: {proxyEnv?: () => ProxyEnvPolicy | null;controlEnv?: (ctx: ControlEnvContext) => Record<string, string>;+ pathPrepend?: () => string[];} = {},): SessionLoader {return {@@ -240,6 +243,7 @@ export function createCoreSessionLoader(agentId: row.agentId,...(opts.proxyEnv ? { proxyEnv: opts.proxyEnv } : {}),...(opts.controlEnv ? { controlEnv: opts.controlEnv } : {}),+ ...(opts.pathPrepend ? { pathPrepend: opts.pathPrepend } : {}),});const located = await findLatestTraceFile(tracesDir(root, row.projectId, row.agentId),diff --git a/packages/server/src/services/cli-shim.ts b/packages/server/src/services/cli-shim.tsnew file mode 100644index 00000000..c66b8665--- /dev/null+++ b/packages/server/src/services/cli-shim.ts@@ -0,0 +1,145 @@+/**+ * The `penguin` a command an Agent runs should find: this harness's own CLI, written into+ * the data root as a launcher script that every Session then puts at the front of PATH.+ *+ * Without it, `penguin` resolves against whatever the machine has installed globally — on a+ * development box that is the desktop app's bundled release, several versions away from the+ * checkout the server was started from, so an Agent asking its own harness to do something+ * gets `unknown command` for anything added since. The shim closes that gap without asking+ * the Agent to know any paths.+ *+ * Two facts make the launcher rather than a symlink necessary. The entry is a `.js` file,+ * not an executable; and it has to run on the SERVER's interpreter, never on whatever `node`+ * the Agent's shell happens to resolve — under the desktop app that interpreter is the+ * Electron binary, which runs a script only with `ELECTRON_RUN_AS_NODE` set.+ *+ * Rewritten at every boot, so a moved checkout is picked up by the next start; while a+ * server is running, a dist that moved out from under it has already broken the server+ * itself. With no entry to point at, an existing shim is REMOVED — a launcher pointing at a+ * path that is no longer there is worse than no `penguin` at all.+ */+import fs from "node:fs";+import path from "node:path";++/** `<root>/bin`, the directory the shim is written to and the Session puts on PATH. */+export function cliShimDir(root: string): string {+ return path.join(root, "bin");+}++/** What one boot's `ensureCliShim` did, for the line the server logs about it. */+export type CliShimResult =+ | { kind: "written"; dir: string; entry: string }+ /** No entry to point at; a shim left by an earlier boot was removed. */+ | { kind: "absent" }+ | { kind: "failed"; reason: string };++export interface CliShimOptions {+ /** The interpreter the shim execs: this server's own. Default `process.execPath`. */+ execPath?: string;+ /**+ * Whether that interpreter is an Electron binary, which runs a plain script only with+ * `ELECTRON_RUN_AS_NODE=1` in the environment. Default: whether this process has one.+ */+ electron?: boolean;+ /** Default `process.platform`; decides whether the `.cmd` half is written. */+ platform?: NodeJS.Platform;+}++/** A string as one POSIX shell word: single-quoted, with each embedded quote spliced as `'\''`. */+function posixQuote(value: string): string {+ return `'${value.replaceAll("'", `'\\''`)}'`;+}++/**+ * `<dir>/penguin` — the shim for every POSIX shell, Git Bash on Windows included (which is+ * the shell commands run in there, see core's shell resolver). `"$@"` forwards the+ * arguments one word each, and `exec` leaves the CLI as the process whose exit status the+ * caller reads.+ */+export function posixShimScript(execPath: string, entry: string, electron: boolean): string {+ return [+ "#!/bin/sh",+ "# penguin CLI shim, rewritten by the PenguinHarness server at every start.",+ "# Runs the CLI of the harness that serves this data root, on that server's own runtime.",+ ...(electron ? ["export ELECTRON_RUN_AS_NODE=1"] : []),+ `exec ${posixQuote(execPath)} ${posixQuote(entry)} "$@"`,+ "",+ ].join("\n");+}++/**+ * `<dir>\penguin.cmd` — the same shim for `cmd` and PowerShell. CRLF on purpose: cmd.exe is+ * unreliable with bare-LF scripts.+ */+export function windowsShimScript(execPath: string, entry: string, electron: boolean): string {+ return [+ "@echo off",+ "rem penguin CLI shim, rewritten by the PenguinHarness server at every start.",+ "rem Runs the CLI of the harness that serves this data root, on that server's own runtime.",+ "setlocal",+ ...(electron ? ['set "ELECTRON_RUN_AS_NODE=1"'] : []),+ `"${execPath}" "${entry}" %*`,+ "exit /b %errorlevel%",+ "",+ ].join("\r\n");+}++/**+ * The CLI entry of the checkout this module was loaded from, or null when there is none.+ *+ * Walks up from `fromDir` to the directory holding `pnpm-workspace.yaml` — the workspace+ * root — rather than counting `..` segments, because the depth differs between a `tsx` run+ * (`packages/server/src/…`), a built one (`packages/server/dist/…`) and the desktop shell's+ * single-file bundle. Outside a checkout (an npm install, a packaged app) the walk reaches+ * the filesystem root and answers null, and so does a workspace that simply has not built+ * its CLI: a shim is only ever written for a file that is actually there.+ */+export function checkoutCliEntry(fromDir: string): string | null {+ let dir = path.resolve(fromDir);+ for (;;) {+ if (fs.existsSync(path.join(dir, "pnpm-workspace.yaml"))) {+ const entry = path.join(dir, "packages", "cli", "dist", "penguin.js");+ return fs.existsSync(entry) ? entry : null;+ }+ const parent = path.dirname(dir);+ if (parent === dir) return null;+ dir = parent;+ }+}++/**+ * Writes (or removes) this data root's `penguin` shim. Never throws: a data root that+ * cannot be written is reported as a failure and leaves the server running — an Agent then+ * falls back to whatever `penguin` the machine has, which is where it started.+ */+export function ensureCliShim(+ root: string,+ entry: string | null,+ opts: CliShimOptions = {},+): CliShimResult {+ const dir = cliShimDir(root);+ const posix = path.join(dir, "penguin");+ const windows = path.join(dir, "penguin.cmd");+ try {+ if (entry === null) {+ // Both spellings, whatever this platform is: a data root is portable, and the stale+ // one to remove may have been written by a boot on the other OS.+ fs.rmSync(posix, { force: true });+ fs.rmSync(windows, { force: true });+ return { kind: "absent" };+ }+ const execPath = opts.execPath ?? process.execPath;+ const electron = opts.electron ?? process.versions.electron !== undefined;+ fs.mkdirSync(dir, { recursive: true });+ fs.writeFileSync(posix, posixShimScript(execPath, entry, electron), { mode: 0o755 });+ // Explicit: writeFileSync applies `mode` only when it creates the file, so a shim+ // rewritten over an earlier one would keep whatever bits that one had.+ fs.chmodSync(posix, 0o755);+ if ((opts.platform ?? process.platform) === "win32") {+ fs.writeFileSync(windows, windowsShimScript(execPath, entry, electron));+ }+ return { kind: "written", dir, entry };+ } catch (err) {+ return { kind: "failed", reason: err instanceof Error ? err.message : String(err) };+ }+}diff --git a/packages/server/src/services/session-service.ts b/packages/server/src/services/session-service.tsindex 3deb7e23..0b79177d 100644--- a/packages/server/src/services/session-service.ts+++ b/packages/server/src/services/session-service.ts@@ -66,6 +66,11 @@ export interface SessionServiceDeps {* agents can drive the harness back through the CLI/API.*/controlEnv?: (ctx: ControlEnvContext) => Record<string, string>;+ /**+ * PATH threading (same getter the session loader passes): the shim directory holding+ * this harness's own `penguin`, put in front of every command an Agent runs.+ */+ pathPrepend?: () => string[];/*** The channel of the Session's ENABLED messaging binding, or null when none is enabled* (SessionInfo.messagingChannel, the sidebar row's per-channel indicator — saved-but-@@ -353,6 +358,7 @@ export class SessionService {agentId: args.agentId,...(this.deps.proxyEnv ? { proxyEnv: this.deps.proxyEnv } : {}),...(this.deps.controlEnv ? { controlEnv: this.deps.controlEnv } : {}),+ ...(this.deps.pathPrepend ? { pathPrepend: this.deps.pathPrepend } : {}),});let session;try {diff --git a/packages/server/test/cli-shim.test.ts b/packages/server/test/cli-shim.test.tsnew file mode 100644index 00000000..04afff03--- /dev/null+++ b/packages/server/test/cli-shim.test.ts@@ -0,0 +1,178 @@+/**+ * The `<root>/bin/penguin` shim a boot writes so an Agent's commands reach this harness's+ * own CLI: what goes into the launcher scripts, when they are removed again, and how the+ * checkout fallback finds an entry to point at.+ */+import { afterEach, describe, expect, it } from "vitest";+import fs from "node:fs";+import path from "node:path";+import {+ checkoutCliEntry,+ cliShimDir,+ ensureCliShim,+ posixShimScript,+ windowsShimScript,+} from "../src/services/cli-shim.js";+import { makeTempRoot } from "./helpers.js";++const roots: string[] = [];++async function tempRoot(): Promise<string> {+ const root = await makeTempRoot();+ roots.push(root);+ return root;+}++afterEach(async () => {+ while (roots.length > 0) {+ await fs.promises.rm(roots.pop()!, { recursive: true, force: true, maxRetries: 10 });+ }+});++describe("the launcher scripts", () => {+ it("exec the server's own interpreter on the entry, forwarding every argument", () => {+ const script = posixShimScript("/usr/bin/node", "/repo/packages/cli/dist/penguin.js", false);+ expect(script.startsWith("#!/bin/sh\n")).toBe(true);+ expect(script).toContain(`exec '/usr/bin/node' '/repo/packages/cli/dist/penguin.js' "$@"`);+ expect(script).not.toContain("ELECTRON_RUN_AS_NODE");+ });++ it("set ELECTRON_RUN_AS_NODE when the interpreter is an Electron binary", () => {+ // Under the desktop app the server IS Electron: without the flag the shim would boot a+ // second copy of the app instead of running the CLI.+ const script = posixShimScript("/Applications/P.app/Contents/MacOS/P", "/app/penguin.js", true);+ expect(script).toContain("export ELECTRON_RUN_AS_NODE=1");+ expect(script.indexOf("ELECTRON_RUN_AS_NODE")).toBeLessThan(script.indexOf("exec "));+ });++ it("quote a path that carries a shell metacharacter", () => {+ const script = posixShimScript("/usr/bin/node", "/home/anne's data/penguin.js", false);+ expect(script).toContain(`'/home/anne'\\''s data/penguin.js'`);+ });++ it("the Windows half is CRLF and forwards %* with the errorlevel", () => {+ const script = windowsShimScript("C:\\node.exe", "C:\\app\\penguin.js", false);+ expect(script.startsWith("@echo off\r\n")).toBe(true);+ expect(script).toContain(`"C:\\node.exe" "C:\\app\\penguin.js" %*`);+ expect(script).toContain("exit /b %errorlevel%");+ expect(script.includes("\n\r")).toBe(false);+ });+});++/**+ * POSIX permission bits are a POSIX fact: on win32 `chmod` only toggles the read-only+ * attribute and `stat().mode` never reports an execute bit, so an `x`-bit assertion there+ * says nothing about either the code or the platform. What the shim CONTAINS is asserted+ * everywhere; whether it is marked executable is asserted where the mark exists.+ */+const POSIX_MODES = process.platform !== "win32";++describe("ensureCliShim", () => {+ it("writes an executable shim into <root>/bin and reports what it wrote", async () => {+ const root = await tempRoot();+ const result = ensureCliShim(root, "/repo/packages/cli/dist/penguin.js", {+ execPath: "/usr/bin/node",+ electron: false,+ platform: "linux",+ });+ expect(result).toEqual({+ kind: "written",+ dir: cliShimDir(root),+ entry: "/repo/packages/cli/dist/penguin.js",+ });+ const shim = path.join(root, "bin", "penguin");+ expect(fs.readFileSync(shim, "utf8")).toContain("/repo/packages/cli/dist/penguin.js");+ // The whole point is that a shell can run it.+ if (POSIX_MODES) expect(fs.statSync(shim).mode & 0o111).toBe(0o111);+ });++ it("rewrites a shim left by an earlier boot, executable bit included", async () => {+ const root = await tempRoot();+ const opts = { execPath: "/usr/bin/node", electron: false, platform: "linux" } as const;+ ensureCliShim(root, "/old/penguin.js", opts);+ const shim = path.join(root, "bin", "penguin");+ // A checkout that moved, and a mode someone else narrowed: writeFileSync applies its+ // `mode` only when it creates the file, so the rewrite has to chmod as well.+ if (POSIX_MODES) fs.chmodSync(shim, 0o600);+ ensureCliShim(root, "/new/penguin.js", opts);+ expect(fs.readFileSync(shim, "utf8")).toContain("/new/penguin.js");+ expect(fs.readFileSync(shim, "utf8")).not.toContain("/old/penguin.js");+ if (POSIX_MODES) expect(fs.statSync(shim).mode & 0o111).toBe(0o111);+ });++ it("writes the .cmd half only on Windows, and removes both when there is no entry", async () => {+ const root = await tempRoot();+ const posix = path.join(root, "bin", "penguin");+ const windows = path.join(root, "bin", "penguin.cmd");++ ensureCliShim(root, "/repo/penguin.js", {+ execPath: "/usr/bin/node",+ electron: false,+ platform: "linux",+ });+ expect(fs.existsSync(windows)).toBe(false);++ ensureCliShim(root, "C:\\repo\\penguin.js", {+ execPath: "C:\\node.exe",+ electron: false,+ platform: "win32",+ });+ expect(fs.existsSync(windows)).toBe(true);++ // No entry to point at: a launcher aimed at a path that is no longer there is worse+ // than no `penguin` at all — and both spellings go, whichever OS wrote them.+ expect(ensureCliShim(root, null)).toEqual({ kind: "absent" });+ expect(fs.existsSync(posix)).toBe(false);+ expect(fs.existsSync(windows)).toBe(false);+ });++ it("reports a root it cannot write instead of taking the server down", async () => {+ const root = await tempRoot();+ // A FILE where the bin directory would go: mkdir fails, and so would every write.+ fs.writeFileSync(path.join(root, "bin"), "not a directory");+ const result = ensureCliShim(root, "/repo/penguin.js", {+ execPath: "/usr/bin/node",+ electron: false,+ platform: "linux",+ });+ expect(result.kind).toBe("failed");+ });++ it("removing a shim that was never written is not an error", async () => {+ const root = await tempRoot();+ expect(ensureCliShim(root, null)).toEqual({ kind: "absent" });+ });+});++describe("checkoutCliEntry", () => {+ it("walks up to the workspace root and names its built CLI entry", async () => {+ const repo = await tempRoot();+ fs.writeFileSync(path.join(repo, "pnpm-workspace.yaml"), "packages:\n - packages/*\n");+ const entry = path.join(repo, "packages", "cli", "dist", "penguin.js");+ fs.mkdirSync(path.dirname(entry), { recursive: true });+ fs.writeFileSync(entry, "#!/usr/bin/env node\n");++ // The depth differs per run shape — src under tsx, dist when built, a bundle under the+ // desktop shell — which is why the walk looks for the workspace file rather than+ // counting `..` segments.+ for (const from of [+ path.join(repo, "packages", "server", "src", "services"),+ path.join(repo, "packages", "server", "dist"),+ path.join(repo, "packages", "desktop", "dist"),+ ]) {+ fs.mkdirSync(from, { recursive: true });+ expect(checkoutCliEntry(from), from).toBe(entry);+ }+ });++ it("answers null for a workspace whose CLI has not been built", async () => {+ const repo = await tempRoot();+ fs.writeFileSync(path.join(repo, "pnpm-workspace.yaml"), "packages:\n - packages/*\n");+ expect(checkoutCliEntry(repo)).toBeNull();+ });++ it("answers null outside a checkout, having walked to the filesystem root", async () => {+ const notARepo = await tempRoot();+ expect(checkoutCliEntry(notARepo)).toBeNull();+ });+});diff --git a/packages/server/test/config.test.ts b/packages/server/test/config.test.tsindex eeb9fffe..3f48a81f 100644--- a/packages/server/test/config.test.ts+++ b/packages/server/test/config.test.ts@@ -9,6 +9,7 @@* PENGUIN_SEED_ADMIN_PASSWORD: unset/empty/whitespace → null (random seed password).*/import { describe, expect, it } from "vitest";+import path from "node:path";import { resolveServerConfig } from "../src/config.js";const base = { PENGUIN_HOME: "/tmp/penguin-config-test" };@@ -70,3 +71,21 @@ describe("resolveServerConfig: PENGUIN_SEED_ADMIN_PASSWORD parsing", () => {).toBe("penguin-9999");});});++describe("resolveServerConfig: PENGUIN_CLI_ENTRY parsing", () => {+ it("a value is kept trimmed — it is what the <root>/bin/penguin shim execs", () => {+ expect(+ resolveServerConfig({ ...base, PENGUIN_CLI_ENTRY: " /opt/penguin/dist/penguin.js " })+ .cliEntry,+ ).toBe("/opt/penguin/dist/penguin.js");+ });++ it("empty/whitespace falls through to the checkout lookup, like unset", () => {+ // What the lookup finds depends on whether this checkout has built its CLI, so the+ // claim here is only that a blank value is not treated as an entry (see cli-shim.test.ts+ // for checkoutCliEntry itself).+ const blank = resolveServerConfig({ ...base, PENGUIN_CLI_ENTRY: " " }).cliEntry;+ expect(blank).toBe(resolveServerConfig({ ...base }).cliEntry);+ expect(blank === null || blank.endsWith(`${path.sep}penguin.js`)).toBe(true);+ });+});diff --git a/packages/server/test/helpers.ts b/packages/server/test/helpers.tsindex 4bb2222e..535e7bd4 100644--- a/packages/server/test/helpers.ts+++ b/packages/server/test/helpers.ts@@ -58,6 +58,9 @@ export function testConfig(root: string): ServerConfig {portFile: null,trustProxy: false,supervised: false,+ // No CLI to offer: nothing is written into the temp root, and no directory is put on+ // the PATH of whatever a test's Agent runs.+ cliEntry: null,};}diff --git a/scripts/dev-prebuild.mjs b/scripts/dev-prebuild.mjsindex 1d7c8454..1023145f 100644--- a/scripts/dev-prebuild.mjs+++ b/scripts/dev-prebuild.mjs@@ -1,7 +1,10 @@#!/usr/bin/env node/**- * Serialized dev prestep: ensure dependencies are installed, then build the workspace deps- * the dev servers consume (skills, core).+ * Serialized dev prestep: ensure dependencies are installed, then build what the dev+ * servers consume: packages/core, and packages/cli for the `penguin` a dev server hands the+ * Agents it runs (it writes a shim at `<root>/bin/penguin` pointing at+ * `packages/cli/dist/penguin.js`, so that file has to exist and be current when the server+ * starts — `tsx watch` never rebuilds it).** dev:server and dev:web must build packages/core before starting* (never start on stale deps — see the 2026-07-17 design changelog entry), and every dev@@ -25,7 +28,7 @@* re-invocation (from packages/server's dev script) is a no-op. The window is* deliberately tiny so a human edit-then-restart cycle always rebuilds.*- * Usage: `node scripts/dev-prebuild.mjs` (install + build skills/core) or+ * Usage: `node scripts/dev-prebuild.mjs` (install + build core/cli) or* `node scripts/dev-prebuild.mjs --install-only` (dev:docs / dev:landing — no workspace* deps to build, but installs must still be current).*/@@ -211,10 +214,12 @@ try {refreshViteCache();exitCode = 0;} else {- console.log("[dev-prebuild] building core...");+ console.log("[dev-prebuild] building core and the CLI...");+ // One pnpm invocation, so the two run in dependency order: the CLI bundle inlines+ // core, and core has to be rebuilt first for it to inline the current one.const res = spawnSync("pnpm",- ["--filter", "@prismshadow/penguin-core", "build"],+ ["--filter", "@prismshadow/penguin-core", "--filter", "@prismshadow/penguin-cli", "build"],// shell on Windows: pnpm is a .cmd shim there (see ensureInstalled).{ cwd: ROOT, stdio: "inherit", shell: process.platform === "win32" },);