A local-first multi-agent app development platform, built on PenguinHarness
refactor(desktop): pack dependencies before bundling (#335)
Myriad-Dreaminfe4d681605f4
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex f13b4d2f..e993b52b 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -155,11 +155,6 @@ jobs:- run: pnpm build- # Stage the self-contained app tree (packages/desktop/stage/app) that- # electron-builder packages — the same explicit step desktop-build.yml runs.- - name: Stage the app tree- run: node packages/desktop/scripts/stage.mjs-- name: Build unpacked runtimeenv:CSC_IDENTITY_AUTO_DISCOVERY: "false"@@ -172,8 +167,8 @@ jobs:if-no-files-found: error# Each OS produces exactly one of these unpacked trees.path: |- packages/desktop/stage/out/linux-unpacked- packages/desktop/stage/out/win-unpacked- packages/desktop/stage/out/mac- packages/desktop/stage/out/mac-arm64- packages/desktop/stage/out/mac-x64+ packages/desktop/out/linux-unpacked+ packages/desktop/out/win-unpacked+ packages/desktop/out/mac+ packages/desktop/out/mac-arm64+ packages/desktop/out/mac-x64diff --git a/.github/workflows/desktop-build.yml b/.github/workflows/desktop-build.ymlindex 42e012bd..158b96da 100644--- a/.github/workflows/desktop-build.yml+++ b/.github/workflows/desktop-build.yml@@ -1,7 +1,7 @@# Desktop packages: Electron installers for the desktop shell.#-# Reusable three-OS matrix: stage the pnpm-deploy app tree, run electron-builder, and-# upload the installers as workflow artifacts named desktop-<OS>. release.yml calls this+# Reusable three-OS matrix: build the workspace, run electron-builder, and upload the+# installers as workflow artifacts named desktop-<OS>. release.yml calls this# BEFORE creating the Release — assets are immutable once published, so the desktop# installers must exist at creation time. workflow_dispatch runs it standalone as a dry# run on any branch.@@ -139,9 +139,6 @@ jobs:- run: pnpm -r build- - name: Stage the app directory- run: node packages/desktop/scripts/stage.mjs-# Windows carries MinGit under resources/git so the packaged agent shell has the# same deterministic POSIX bash as the npm package (release.yml bundles the# identical MinGit into the CLI win-x64 zip; the shell advertises it as@@ -153,7 +150,7 @@ jobs:mingit="MinGit-$MINGIT_VERSION-64-bit.zip"curl -fsSL -o "$mingit" \"https://github.com/git-for-windows/git/releases/download/$MINGIT_TAG/$mingit"- unzip -q "$mingit" -d packages/desktop/stage/minigit+ unzip -q "$mingit" -d packages/desktop/build/minigit- name: Prepare macOS signing credentialsif: runner.os == 'macOS'@@ -289,7 +286,7 @@ jobs:$ErrorActionPreference = "Stop"$publisher = "RushRush Network Technology Ltd"- $outDir = "packages/desktop/stage/out"+ $outDir = "packages/desktop/out"$installer = Join-Path $outDir "penguin-desktop-win32-x64.exe"$latest = Join-Path $outDir "latest.yml"$blockmap = "$installer.blockmap"@@ -353,7 +350,7 @@ jobs:set -euo pipefailshopt -s nullglob- dmgs=(packages/desktop/stage/out/*.dmg)+ dmgs=(packages/desktop/out/*.dmg)if ((${#dmgs[@]} == 0)); thenecho "::error title=Missing macOS DMG::No DMG files were produced."exit 1@@ -381,7 +378,7 @@ jobs:run: |set -euo pipefail- metadata="packages/desktop/stage/out/latest-mac.yml"+ metadata="packages/desktop/out/latest-mac.yml"if [[ ! -f "$metadata" ]]; thenecho "::error title=Missing macOS update metadata::$metadata was not produced."exit 1@@ -390,7 +387,7 @@ jobs:node <<'NODE'const fs = require("node:fs");- const metadata = "packages/desktop/stage/out/latest-mac.yml";+ const metadata = "packages/desktop/out/latest-mac.yml";const text = fs.readFileSync(metadata, "utf8");const lines = text.split(/\r?\n/);const output = [];@@ -453,8 +450,8 @@ jobs:set -euo pipefailapps=(- packages/desktop/stage/out/mac-arm64/PenguinHarness.app- packages/desktop/stage/out/mac/PenguinHarness.app+ packages/desktop/out/mac-arm64/PenguinHarness.app+ packages/desktop/out/mac/PenguinHarness.app)for app in "${apps[@]}"; doif [[ ! -d "$app" ]]; then@@ -473,7 +470,7 @@ jobs:doneshopt -s nullglob- dmgs=(packages/desktop/stage/out/*.dmg)+ dmgs=(packages/desktop/out/*.dmg)if ((${#dmgs[@]} == 0)); thenecho "::error title=Missing macOS DMG::No DMG files were produced."exit 1@@ -493,13 +490,13 @@ jobs:name: desktop-${{ runner.os }}if-no-files-found: errorpath: |- packages/desktop/stage/out/penguin-desktop-*.AppImage- packages/desktop/stage/out/penguin-desktop-*.deb- packages/desktop/stage/out/penguin-desktop-*.dmg- packages/desktop/stage/out/penguin-desktop-*.zip- packages/desktop/stage/out/penguin-desktop-*.exe+ packages/desktop/out/penguin-desktop-*.AppImage+ packages/desktop/out/penguin-desktop-*.deb+ packages/desktop/out/penguin-desktop-*.dmg+ packages/desktop/out/penguin-desktop-*.zip+ packages/desktop/out/penguin-desktop-*.exe# Update metadata: electron-updater reads latest*.yml from the Release, and# the blockmaps are what make differential downloads possible. Without these# the installers ship but nothing can auto-update.- packages/desktop/stage/out/latest*.yml- packages/desktop/stage/out/*.blockmap+ packages/desktop/out/latest*.yml+ packages/desktop/out/*.blockmapdiff --git a/.prettierignore b/.prettierignoreindex 67c523fb..2fc9749a 100644--- a/.prettierignore+++ b/.prettierignore@@ -3,6 +3,11 @@ node_modules/dist/pnpm-lock.yaml+# desktop build output: the installers electron-builder writes, and the assets+# scripts/build-assets.mjs copies in beside them (formatted in their own packages)+packages/desktop/out/+packages/desktop/skills/+# docs-only area (mostly Chinese; not machine-formatted)specs/*.mddiff --git a/changelog/unreleased/2026-08-18-desktop-bundled-packaging.md b/changelog/unreleased/2026-08-18-desktop-bundled-packaging.mdnew file mode 100644index 00000000..49930de7--- /dev/null+++ b/changelog/unreleased/2026-08-18-desktop-bundled-packaging.md@@ -0,0 +1,37 @@+# Desktop installers are built from bundles, not an assembled dependency tree++- **Date:** 2026-08-18+- **Type:** refactor+- **Scope:** `desktop`, `cli`, `ci`++[中文版](2026-08-18-desktop-bundled-packaging.zh.md)++The desktop app stopped shipping a `node_modules` tree. `pnpm build` now emits the shell, the+server and the CLI as three self-contained bundles in `packages/desktop/dist/`, and+`electron-builder.yml` lists exactly what goes inside an installer — replacing+`scripts/stage.mjs`, which assembled the app directory with `pnpm deploy --prod`, pruned it,+rewrote its `package.json` and copied assets into it by hand.++## Details++- `tsup.config.ts` bundles `src/main.ts`, the server package's entry and the CLI's entry, each+ into one file with no shared chunks. `electron` stays external — its npm package is a shim+ that reads the binary's path from disk. The `createRequire` banner `scripts/deploy.mjs` uses+ for hot-update bundles is applied here too, so bundled CommonJS dependencies keep working.+- The shell forks `dist/server.js` from the app path in both a source run and a packaged app,+ so the two run the same artifact. The `penguin` launchers point at `dist/penguin.js`, and the+ AppImage bootstrap derives its path segments from the same constant.+- `scripts/build-assets.mjs` writes the three non-JavaScript outputs `pnpm build` owes the app:+ the skill library beside `dist/`, where the bundled reader's package-relative lookup finds it;+ the runtime window icon into `dist/`; and the `bin/` launcher scripts.+- The web assets are mapped in by electron-builder at pack time. Installers no longer carry+ source maps.+- The app directory that ships shrank from 128 MB to 29 MB.+- MinGit is downloaded into `packages/desktop/build/minigit`, and electron-builder writes its+ output to `packages/desktop/out/`.++## Compatibility++`penguin update` from a desktop install used to be treated as a global npm install and offered+an `npm install -g` command, which installed a second, unrelated copy of the CLI. It now+reports that the CLI ships inside the desktop app and is replaced when the app updates.diff --git a/changelog/unreleased/2026-08-18-desktop-bundled-packaging.zh.md b/changelog/unreleased/2026-08-18-desktop-bundled-packaging.zh.mdnew file mode 100644index 00000000..eb7d76b9--- /dev/null+++ b/changelog/unreleased/2026-08-18-desktop-bundled-packaging.zh.md@@ -0,0 +1,29 @@+# 桌面安装包改由打包产物构建,不再自行组装依赖树++- **Date:** 2026-08-18+- **Type:** refactor+- **Scope:** `desktop`, `cli`, `ci`++[English](2026-08-18-desktop-bundled-packaging.md)++桌面应用不再随包分发 `node_modules` 树。`pnpm build` 现在把外壳、服务端与 CLI 各自打成一个自包含产物,输出到+`packages/desktop/dist/`,安装包里装什么则完全由 `electron-builder.yml` 声明——取代了 `scripts/stage.mjs`:它用+`pnpm deploy --prod` 组装出应用目录,再手工裁剪、改写其 `package.json` 并把资源逐个拷进去。++## 细节++- `tsup.config.ts` 分别打包 `src/main.ts`、服务端包的入口与 CLI 的入口,每个产物独立成一个文件,不共享 chunk。+ `electron` 保持 external——它的 npm 包只是一个从磁盘读取二进制路径的 shim。`scripts/deploy.mjs` 为热更新产物+ 使用的 `createRequire` banner 在这里同样启用,被打包进来的 CommonJS 依赖因此照常工作。+- 无论源码运行还是打包后的应用,外壳都按应用路径 fork `dist/server.js`,两者运行的是同一份产物。`penguin` 启动脚本+ 指向 `dist/penguin.js`,AppImage 的引导代码也由同一个常量推导出路径片段。+- `scripts/build-assets.mjs` 负责 `pnpm build` 该产出的三样非 JavaScript 内容:技能库放在 `dist/` 旁边,正好是被打包的+ 读取逻辑按包相对路径查找的位置;运行时窗口图标放入 `dist/`;以及 `bin/` 下的启动脚本。+- 前端资源由 electron-builder 在打包时映射进来。安装包不再携带 source map。+- 随安装包分发的应用目录从 128 MB 降到 29 MB。+- MinGit 改为下载到 `packages/desktop/build/minigit`,electron-builder 的输出目录改为 `packages/desktop/out/`。++## 兼容性++在桌面安装中执行 `penguin update`,过去会被判定为 npm 全局安装并给出 `npm install -g` 命令,而那会装出第二份互不相干的+CLI。现在它会说明该 CLI 随桌面应用分发,并在应用更新时一并替换。diff --git a/packages/cli/src/commands/update.ts b/packages/cli/src/commands/update.tsindex c1e288d0..2f9fbca2 100644--- a/packages/cli/src/commands/update.ts+++ b/packages/cli/src/commands/update.ts@@ -99,7 +99,7 @@ export interface InstallerCandidate {type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;/** How this copy of the CLI was installed, which decides how it can be upgraded. */-export type InstallKind = "tarball" | "npm" | "source" | "unknown";+export type InstallKind = "tarball" | "npm" | "source" | "desktop" | "unknown";export interface InstallInfo {kind: InstallKind;@@ -123,6 +123,8 @@ function segments(p: string): string[] {* Pure and shape-based on purpose: it touches neither the filesystem nor the environment beyond* what is passed in, so every branch is unit-testable. The three layouts are unambiguous:*+ * - desktop app — the CLI bundled into the PenguinHarness desktop app, which runs it on the+ * app's own Electron runtime as Node and updates it with the app;* - source checkout — `…/packages/cli/{src,dist}/index.{ts,js}` (also how a `pnpm link`-ed dev* build looks once the bin symlink is resolved);* - npm global — the path runs through `node_modules/@prismshadow/penguin-cli/`;@@ -131,7 +133,11 @@ function segments(p: string): string[] {* Order matters: a checkout is checked first so a repo that happens to live under a directory* called `lib` cannot be mistaken for an install.*/-export function detectInstall(modulePath: string): InstallInfo {+export function detectInstall(modulePath: string, runtime?: { electron: boolean }): InstallInfo {+ // The desktop app has no npm layout to match: it ships one bundled CLI file and is the only+ // form that runs on Electron, so the runtime answers this before any path shape does.+ if (runtime?.electron === true) return { kind: "desktop" };+const parts = segments(modulePath);const sep = modulePath.includes("\\") && !modulePath.includes("/") ? "\\" : path.sep;const join = (upto: number) => {@@ -473,6 +479,7 @@ export type UpdatePlan =| { action: "report"; current: string; target: string; comparison: number }| { action: "up-to-date"; current: string }| { action: "refuse"; reason: "source" }+ | { action: "refuse"; reason: "desktop" }| { action: "refuse"; reason: "unknown-install"; modulePath: string }| { action: "refuse"; reason: "unknown-manager"; globalRoot: string; target: string }| { action: "refuse"; reason: "windows-global"; command: string }@@ -509,6 +516,7 @@ export function planUpdate(input: {if (comparison === 0) return { action: "up-to-date", current };if (install.kind === "source") return { action: "refuse", reason: "source" };+ if (install.kind === "desktop") return { action: "refuse", reason: "desktop" };if (install.kind === "unknown")return { action: "refuse", reason: "unknown-install", modulePath: input.modulePath };@@ -535,6 +543,8 @@ function refusalMessage(plan: Extract<UpdatePlan, { action: "refuse" }>, t: Messswitch (plan.reason) {case "source":return t.update.sourceCheckout();+ case "desktop":+ return t.update.desktopApp();case "unknown-install":return t.update.unknownInstall(plan.modulePath);case "unknown-manager":@@ -565,7 +575,7 @@ export function registerUpdateCommand(program: Command, t: Messages): void {current,target,...(opts.check !== undefined ? { check: opts.check } : {}),- install: detectInstall(modulePath),+ install: detectInstall(modulePath, { electron: process.versions.electron !== undefined }),modulePath,platform: process.platform,defaultInstallDir,diff --git a/packages/cli/src/i18n.ts b/packages/cli/src/i18n.tsindex d8733aa8..c9c0fb37 100644--- a/packages/cli/src/i18n.ts+++ b/packages/cli/src/i18n.ts@@ -133,6 +133,8 @@ export interface Messages {failed(): string;/** Running from a source checkout: refuse, because overwriting a working tree destroys work. */sourceCheckout(): string;+ /** Bundled into the desktop app: refuse, because the app updates itself. */+ desktopApp(): string;unknownInstall(modulePath: string): string;/** A global install whose package manager could not be identified: print the command, never guess. */npmUnknownManager(globalRoot: string, target: string): string;@@ -460,6 +462,8 @@ const en: Messages = {failed: () => "Upgrade failed; the previous install was left in place where possible.",sourceCheckout: () =>"This penguin runs from a source checkout, so there is nothing to download — update it with `git pull` and rebuild (`pnpm install && pnpm -r build`).",+ desktopApp: () =>+ "This penguin ships inside the PenguinHarness desktop app and is replaced when the app updates — check for updates from the application menu.",unknownInstall: (modulePath) =>`Cannot tell how this penguin was installed (running from ${modulePath}), so it will not be replaced. Re-install with the official installer, or upgrade with the package manager you used.`,npmUnknownManager: (globalRoot, target) =>@@ -730,6 +734,8 @@ const zh: Messages = {failed: () => "升级失败;在可能的情况下已保留原有安装。",sourceCheckout: () =>"当前 penguin 运行自源码检出,无需下载——请用 `git pull` 更新并重新构建(`pnpm install && pnpm -r build`)。",+ desktopApp: () =>+ "当前 penguin 随 PenguinHarness 桌面应用一同分发,会在应用更新时一并替换——请从应用菜单检查更新。",unknownInstall: (modulePath) =>`无法判断当前 penguin 的安装方式(运行自 ${modulePath}),因此不会替换它。请用官方安装脚本重新安装,或用你当初使用的包管理器升级。`,npmUnknownManager: (globalRoot, target) =>diff --git a/packages/desktop/.gitignore b/packages/desktop/.gitignoreindex 943f77ba..508d1baa 100644--- a/packages/desktop/.gitignore+++ b/packages/desktop/.gitignore@@ -1 +1,3 @@-stage/+bin/+out/+skills/diff --git a/packages/desktop/build/minigit/.gitkeep b/packages/desktop/build/minigit/.gitkeepnew file mode 100644index 00000000..e69de29bdiff --git a/packages/desktop/electron-builder.yml b/packages/desktop/electron-builder.ymlindex e435a2b4..39a58279 100644--- a/packages/desktop/electron-builder.yml+++ b/packages/desktop/electron-builder.yml@@ -1,8 +1,9 @@# electron-builder config for the desktop shell installers.#-# The app directory is the pnpm-deploy staging tree assembled by scripts/stage.mjs —-# a portable, self-contained node_modules (workspace packages materialized) plus the-# shell bundle and the server's web-dist.+# The app directory is this package itself: `pnpm build` emits self-contained bundles of+# the shell, the server and the CLI into dist/ (see tsup.config.ts), so the app has no+# runtime dependencies and electron-builder ships no node_modules — `files` below is the+# complete description of what goes inside an installer.## asar is off on purpose: the shell forks the server as a child process, the skill# library reads its .md files from disk, and agent commands spawn real shells — plain@@ -24,11 +25,29 @@ publish:owner: Prism-Shadowrepo: penguin-harnessdirectories:- app: stage/app- output: stage/out+ output: out+# Everything the app runs, and nothing else. The two mapped entries are the assets the+# bundled server looks up relative to its own location: `skills/` is written next to dist/+# by scripts/build-assets.mjs (a source run needs it there too), while web-dist comes+# straight from the web package — no build order between the two packages guarantees it+# exists before this one builds, but it always does by the time anything is packed.+files:+ - dist/**/*+ - "!dist/**/*.map"+ - bin/**/*+ - skills/**/*+ - package.json+ - from: ../web/dist+ to: web-dist+# The app's own metadata, which the workspace package.json cannot carry: deb and AppImage+# derive package and executable names from `name`, where "@prismshadow/…" is invalid, and+# fpm refuses to build without a homepage. The name also decides the app data directory, so+# it stays what installed apps already use.+extraMetadata:+ name: penguin-harness-desktop+ homepage: https://github.com/Prism-Shadow/penguin-harnessasar: false-# The staged tree is complete and has no native modules; a rebuild would only fail-# against the pruned package.json.+# Nothing to rebuild: the app ships no node_modules and no native modules.npmRebuild: falsenodeGypRebuild: false@@ -75,11 +94,12 @@ win:target:- target: nsisarch: [x64]- # MinGit, downloaded by the CI job into stage/minigit (empty for local non-Windows- # builds): lands under resources/git, and the shell advertises git/usr/bin/sh.exe as+ # MinGit, downloaded by the CI job into build/minigit (empty for local non-Windows+ # builds, hence the committed .gitkeep — an extraResources source must always exist):+ # lands under resources/git, and the shell advertises git/usr/bin/sh.exe as# PENGUIN_BUNDLED_SHELL so the agent shell behaves like the npm-installed package.extraResources:- - from: stage/minigit+ - from: build/minigitto: gitnsis:@@ -90,7 +110,8 @@ linux:# Pre-rendered freedesktop icon set (scripts/render-icon.mjs): a directory of NxN.png# files is used as-is for AppImage/deb, no conversion step.icon: build/icons- # The scoped package name is not a valid executable file name.+ # Pinned rather than derived from the app name, which the deb postinst templates also+ # interpolate (build/linux/*.tpl).executableName: penguin-harness# ${arch} expands to each Linux target's own convention — x86_64 for AppImage, amd64# for deb — so the published names are penguin-desktop-linux-x86_64.AppImage and@@ -107,7 +128,7 @@ linux:deb:# Extended copies of electron-builder's default scripts (overriding REPLACES them):- # they additionally create/remove the /usr/bin/penguin symlink to the staged CLI+ # they additionally create/remove the /usr/bin/penguin symlink to the bundled CLI# launcher (resources/app/bin/penguin), so a deb install gets the `penguin` command# on PATH without the in-app install flow the other formats use.afterInstall: build/linux/after-install.tpldiff --git a/packages/desktop/package.json b/packages/desktop/package.jsonindex e313c1fe..970414dc 100644--- a/packages/desktop/package.json+++ b/packages/desktop/package.json@@ -6,28 +6,25 @@"description": "PenguinHarness desktop app: Electron shell running @prismshadow/penguin-server as a utilityProcess, window on http://localhost (same-origin HTTP/SSE, no private IPC).","main": "dist/main.js","scripts": {- "build": "tsup",+ "build": "tsup && node scripts/build-assets.mjs","typecheck": "tsc --noEmit -p tsconfig.json","test": "vitest run --passWithNoTests","start": "node scripts/preflight.mjs && electron .",- "stage": "node scripts/stage.mjs",- "pack": "node scripts/stage.mjs && electron-builder",- "pack:linux": "node scripts/stage.mjs && electron-builder --linux",- "pack:mac": "node scripts/stage.mjs && electron-builder --mac",- "pack:win": "node scripts/stage.mjs && electron-builder --win"+ "pack": "electron-builder",+ "pack:linux": "electron-builder --linux",+ "pack:mac": "electron-builder --mac",+ "pack:win": "electron-builder --win"},- "dependencies": {+ "devDependencies": {"@prismshadow/penguin-cli": "workspace:*","@prismshadow/penguin-core": "workspace:*","@prismshadow/penguin-server": "workspace:*",- "electron-updater": "^6.8.9"- },- "devDependencies": {"@types/node": "^24.0.0","electron": "^43.2.0",+ "electron-builder": "^26.0.12",+ "electron-updater": "^6.8.9","tsup": "^8.3.0","typescript": "^5.6.0",- "vitest": "^3.2.6",- "electron-builder": "^26.0.12"+ "vitest": "^3.2.6"}}diff --git a/packages/desktop/scripts/build-assets.mjs b/packages/desktop/scripts/build-assets.mjsnew file mode 100644index 00000000..7ad11fa2--- /dev/null+++ b/packages/desktop/scripts/build-assets.mjs@@ -0,0 +1,55 @@+/**+ * Build outputs that are not JavaScript, written next to the tsup bundles by `pnpm build`.+ *+ * What goes into an installer is decided declaratively in electron-builder.yml; this script+ * only produces this package's own artifacts, in the one layout that serves both a source run+ * and a packaged app:+ *+ * - `skills/` — the shipped skill library. @prismshadow/penguin-skills reads its SKILL.md+ * files from `<its package root>/skills`, and bundling puts the reader in `dist/`, so the+ * copy lands where that same package-relative lookup finds it. (The server's web-dist+ * lookup works the same way and is satisfied by electron-builder's file mapping when+ * packaging; a source run falls back to packages/web/dist on its own.)+ * - `dist/icon.png` — the runtime window icon, read app-path-relative (see src/app-icon.ts).+ * build/ is electron-builder's buildResources directory and does not ship inside the app.+ * - `bin/penguin`, `bin/penguin.cmd` — the CLI launchers, whose script text lives in+ * src/launcher.ts so it is unit-tested with the rest of the shell.+ *+ * Run from anywhere (after tsup); all paths derive from this file's location.+ */+import fs from "node:fs";+import path from "node:path";+import { fileURLToPath, pathToFileURL } from "node:url";++const pkgDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");+const distDir = path.join(pkgDir, "dist");++const launcherModule = path.join(distDir, "launcher.js");+if (!fs.existsSync(launcherModule)) {+ console.error("[build-assets] dist/launcher.js is missing — run `tsup` first.");+ process.exit(1);+}++const skillsSrc = path.resolve(pkgDir, "..", "skills", "skills");+const skillsDest = path.join(pkgDir, "skills");+fs.rmSync(skillsDest, { recursive: true, force: true });+fs.cpSync(skillsSrc, skillsDest, { recursive: true });++const iconSrc = path.join(pkgDir, "build", "icon.png");+if (!fs.existsSync(iconSrc)) {+ console.error("[build-assets] build/icon.png is missing — run `node scripts/render-icon.mjs`.");+ process.exit(1);+}+fs.copyFileSync(iconSrc, path.join(distDir, "icon.png"));++const { posixLauncherScript, windowsLauncherScript } = await import(+ pathToFileURL(launcherModule).href+);+const binDir = path.join(pkgDir, "bin");+fs.mkdirSync(binDir, { recursive: true });+fs.writeFileSync(path.join(binDir, "penguin"), posixLauncherScript(), { mode: 0o755 });+// Explicit chmod: the mode option only applies when writeFileSync creates the file.+fs.chmodSync(path.join(binDir, "penguin"), 0o755);+fs.writeFileSync(path.join(binDir, "penguin.cmd"), windowsLauncherScript());++console.log("[build-assets] done: skills/, dist/icon.png, bin/");diff --git a/packages/desktop/scripts/preflight.mjs b/packages/desktop/scripts/preflight.mjsindex 60f4cb06..df615412 100644--- a/packages/desktop/scripts/preflight.mjs+++ b/packages/desktop/scripts/preflight.mjs@@ -1,9 +1,8 @@/*** Dev preflight for `pnpm --dir packages/desktop start` (and the root `pnpm desktop`):* verify everything a source run needs, and fail with the actual fix instead of a bare- * ERR_MODULE_NOT_FOUND. The classic trap: this package's node_modules holds pnpm- * *injected copies* of the workspace packages, which only sync while building THROUGH- * pnpm — a stale copy surfaces as `Cannot find module …/penguin-server/dist/lock.js`.+ * ENOENT from the utilityProcess fork or an empty skill library. A source run loads the+ * same bundles a packaged app does, so all of them have to exist first.*/import { createRequire } from "node:module";import fs from "node:fs";@@ -17,13 +16,12 @@ const problems = [];for (const [what, rel] of [["the desktop shell build", "dist/main.js"],- ["the injected server copy", "node_modules/@prismshadow/penguin-server/dist/lock.js"],+ ["the embedded server bundle", "dist/server.js"],+ ["the skill library copy", "skills"],["the web frontend build", "../web/dist/index.html"],]) {if (!fs.existsSync(path.join(pkgDir, rel))) {- problems.push(- `Missing ${what} (${rel}). Run \`pnpm -r build\` at the repo root — builds through pnpm also sync the injected workspace copies under node_modules.`,- );+ problems.push(`Missing ${what} (${rel}). Run \`pnpm -r build\` at the repo root.`);}}diff --git a/packages/desktop/scripts/stage.mjs b/packages/desktop/scripts/stage.mjsdeleted file mode 100644index 5332c99e..00000000--- a/packages/desktop/scripts/stage.mjs+++ /dev/null@@ -1,124 +0,0 @@-/**- * Assemble the self-contained app directory electron-builder packs (stage/app).- *- * `pnpm deploy --prod` materializes this package plus its production dependency tree —- * including the workspace packages (@prismshadow/penguin-cli among them, so the staged- * node_modules carries cli + server + core + skills) — into a portable directory whose- * symlinks all stay inside it (verified: the server boots from the deploy dir as-is).- * On top of that:- * - prune dev files (sources, configs) so only dist/, node_modules/ and package.json ship;- * - copy the web build to `node_modules/@prismshadow/penguin-server/web-dist`, the npm- * package layout the server's static-hosting lookup checks first;- * - copy build/icon.png into the app dir (the runtime window icon, see src/app-icon.ts);- * - generate the `penguin` CLI launchers into `bin/` (POSIX + Windows, see- * src/launcher.ts): they run the bundled CLI on the app's Electron runtime as Node;- * - ensure `stage/minigit` exists (may be empty): the Windows CI job downloads MinGit- * into it, and electron-builder's win extraResources entry must always have a source.- *- * Run from anywhere (after `pnpm -r build`); all paths derive from this file's location.- */-import { execFileSync } from "node:child_process";-import fs from "node:fs";-import path from "node:path";-import { fileURLToPath, pathToFileURL } from "node:url";--const pkgDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");-const repoRoot = path.resolve(pkgDir, "..", "..");-const stageDir = path.join(pkgDir, "stage");-const appDir = path.join(stageDir, "app");--fs.rmSync(stageDir, { recursive: true, force: true });-fs.mkdirSync(stageDir, { recursive: true });--console.log("[stage] pnpm deploy --prod → stage/app");-// Scrub inherited npm_config_* vars: when this script runs under `pnpm run`, they leak-// into the child pnpm and derail its argument parsing.-const env = Object.fromEntries(- Object.entries(process.env).filter(([k]) => !k.toLowerCase().startsWith("npm_config_")),-);-// Windows: pnpm is pnpm.cmd, which Node only spawns through a shell (and .cmd spawning-// without one is blocked since the CVE-2024-27980 hardening). With a shell, args are-// joined verbatim, so quote them — appDir may contain spaces.-const isWindows = process.platform === "win32";-const deployArgs = ["--filter", "@prismshadow/penguin-desktop", "deploy", "--prod", appDir];-execFileSync(- isWindows ? "pnpm.cmd" : "pnpm",- isWindows ? deployArgs.map((a) => `"${a}"`) : deployArgs,- { cwd: repoRoot, stdio: "inherit", env, shell: isWindows },-);--// Keep only what the packaged app runs.-const keep = new Set(["dist", "node_modules", "package.json"]);-for (const entry of fs.readdirSync(appDir)) {- if (!keep.has(entry)) fs.rmSync(path.join(appDir, entry), { recursive: true, force: true });-}--// Strip scripts and devDependencies from the staged package.json but KEEP the-// dependencies pnpm deploy wrote: electron-builder's node-module collector walks them-// to decide what ships — with no dependencies it falls back to scanning the PROJECT-// directory's node_modules (the injected copies, which lack web-dist) and rebuilds the-// wrong tree.-const stagedPkgPath = path.join(appDir, "package.json");-const stagedPkg = JSON.parse(fs.readFileSync(stagedPkgPath, "utf8"));-delete stagedPkg.scripts;-delete stagedPkg.devDependencies;-stagedPkg.private = true;-// Unscoped name: deb/AppImage internals derive package and executable names from it,-// and "@prismshadow/…" is invalid there. The app-root name plays no role in module-// resolution, so the packaged name can differ from the workspace package name.-stagedPkg.name = "penguin-harness-desktop";-// fpm (deb) refuses to build without a homepage.-stagedPkg.homepage = "https://github.com/Prism-Shadow/penguin-harness";-fs.writeFileSync(stagedPkgPath, JSON.stringify(stagedPkg, null, 2) + "\n");--const webDist = path.join(repoRoot, "packages", "web", "dist");-if (!fs.existsSync(path.join(webDist, "index.html"))) {- console.error("[stage] packages/web/dist is missing — run `pnpm -r build` first.");- process.exit(1);-}-// The @prismshadow/penguin-server entry is a symlink into .pnpm; copying THROUGH it-// lands the files in the real package dir, which is exactly where the server looks.-const serverPkg = path.join(appDir, "node_modules", "@prismshadow", "penguin-server");-fs.cpSync(webDist, path.join(serverPkg, "web-dist"), { recursive: true, dereference: true });--// The shell forks the server by this exact path, and the CLI launchers point at the-// CLI entry: verify both landed in the deploy tree before packing.-const launcherModule = path.join(pkgDir, "dist", "launcher.js");-for (const [what, file] of [- ["server entry", path.join(serverPkg, "dist", "index.js")],- [- "CLI entry",- path.join(appDir, "node_modules", "@prismshadow", "penguin-cli", "dist", "penguin.js"),- ],- ["launcher generator (dist/launcher.js)", launcherModule],-]) {- if (!fs.existsSync(file)) {- console.error(`[stage] missing ${what} (${file}) — run \`pnpm -r build\` first.`);- process.exit(1);- }-}--// Runtime window icon: same app-dir-relative location as the dev run (build/icon.png),-// so src/app-icon.ts resolves it identically in both layouts.-const iconSrc = path.join(pkgDir, "build", "icon.png");-if (!fs.existsSync(iconSrc)) {- console.error("[stage] build/icon.png is missing — run `node scripts/render-icon.mjs`.");- process.exit(1);-}-fs.mkdirSync(path.join(appDir, "build"), { recursive: true });-fs.copyFileSync(iconSrc, path.join(appDir, "build", "icon.png"));--// CLI launchers (bin/penguin, bin/penguin.cmd): generated, not committed — the script-// text lives in src/launcher.ts so it is unit-tested with the rest of the shell.-const { posixLauncherScript, windowsLauncherScript } = await import(- pathToFileURL(launcherModule).href-);-const binDir = path.join(appDir, "bin");-fs.mkdirSync(binDir, { recursive: true });-fs.writeFileSync(path.join(binDir, "penguin"), posixLauncherScript(), { mode: 0o755 });-fs.chmodSync(path.join(binDir, "penguin"), 0o755);-fs.writeFileSync(path.join(binDir, "penguin.cmd"), windowsLauncherScript());--fs.mkdirSync(path.join(stageDir, "minigit"), { recursive: true });--console.log("[stage] done:", appDir);diff --git a/packages/desktop/src/app-icon.ts b/packages/desktop/src/app-icon.tsindex 79e58ea9..9ac8d294 100644--- a/packages/desktop/src/app-icon.ts+++ b/packages/desktop/src/app-icon.ts@@ -3,16 +3,17 @@** Only Linux (and Windows dev runs) need it: a packaged Windows app gets its taskbar* icon from the exe resources electron-builder embeds, and macOS ignores BrowserWindow- * icons entirely (the Dock icon comes from the bundle's icns). The PNG lives at- * build/icon.png both in the source package (committed, rendered by- * scripts/render-icon.mjs) and in the staged app directory (copied by scripts/stage.mjs),- * so the same app-path-relative lookup serves dev and packaged runs.+ * icons entirely (the Dock icon comes from the bundle's icns). The committed master is+ * build/icon.png (rendered by scripts/render-icon.mjs), which is electron-builder's+ * buildResources directory and does not ship inside the app; scripts/build-assets.mjs+ * copies it into dist/, so the same app-path-relative lookup serves both a source run and+ * a packaged app.*/import fs from "node:fs";import path from "node:path";-/** Window icon location relative to the app directory (dev package dir / staged app dir). */-export const WINDOW_ICON_RELPATH = ["build", "icon.png"];+/** Window icon location relative to the app directory (the package dir for a source run). */+export const WINDOW_ICON_RELPATH = ["dist", "icon.png"];/** The window-icon path for a platform, or null where window icons are not used (macOS). */export function windowIconPathFor(appPath: string, platform: NodeJS.Platform): string | null {diff --git a/packages/desktop/src/cli-install.ts b/packages/desktop/src/cli-install.tsindex 7070320d..579fcfe3 100644--- a/packages/desktop/src/cli-install.ts+++ b/packages/desktop/src/cli-install.ts@@ -27,7 +27,7 @@ import type { CliInstallKind } from "./launcher.js";const execFileAsync = promisify(execFile);-/** The staged launcher directory inside the packaged app. */+/** The launcher directory inside the packaged app. */function binDir(): string {return path.join(app.getAppPath(), "bin");}diff --git a/packages/desktop/src/launcher.ts b/packages/desktop/src/launcher.tsindex 4f9ac951..309baa1f 100644--- a/packages/desktop/src/launcher.ts+++ b/packages/desktop/src/launcher.ts@@ -1,8 +1,8 @@/*** CLI launcher generation and PATH plumbing — pure helpers, no Electron imports, so- * they unit-test under plain vitest AND load in plain node: scripts/stage.mjs imports- * the built dist/launcher.js at stage time to write the launcher scripts into the- * packaged app directory's bin/.+ * they unit-test under plain vitest AND load in plain node: scripts/build-assets.mjs+ * imports the built dist/launcher.js to write the launcher scripts into this package's+ * bin/, which electron-builder then ships inside the app directory.** The launchers run the bundled @prismshadow/penguin-cli on the app's own Electron* runtime as Node (ELECTRON_RUN_AS_NODE), so an installed desktop app provides a@@ -10,8 +10,8 @@* PATH is per platform (see cli-install.ts and build/linux/*.tpl for the deb variant).*/-/** CLI entry inside the staged app directory (pnpm-deploy layout, asar off). */-export const CLI_ENTRY_RELPATH = "node_modules/@prismshadow/penguin-cli/dist/penguin.js";+/** CLI bundle inside the app directory, emitted by tsup alongside the shell (asar off). */+export const CLI_ENTRY_RELPATH = "dist/penguin.js";/*** Platform executable names, fixed by electron-builder.yml: productName PenguinHarness@@ -22,7 +22,7 @@ export const WIN_EXECUTABLE = "PenguinHarness.exe";export const LINUX_EXECUTABLE = "penguin-harness";/**- * POSIX launcher, staged as `<app>/bin/penguin` (chmod 755). Resolves its own real+ * POSIX launcher, written to `<app>/bin/penguin` (chmod 755). Resolves its own real* location first (PATH exposure is a symlink on macOS/deb), then finds the Electron* executable at the platform's fixed position relative to the app directory:* - macOS: app dir is `<bundle>/Contents/Resources/app` → `../../MacOS/PenguinHarness`@@ -30,7 +30,7 @@ export const LINUX_EXECUTABLE = "penguin-harness";*/export function posixLauncherScript(): string {return `#!/bin/sh-# penguin CLI launcher (generated by packages/desktop/scripts/stage.mjs).+# penguin CLI launcher (generated by packages/desktop/scripts/build-assets.mjs).# Runs the bundled penguin CLI on this app's Electron runtime as Node# (ELECTRON_RUN_AS_NODE=1) - no system Node installation required.@@ -64,7 +64,7 @@ exit 1}/**- * Windows launcher, staged as `<app>\\bin\\penguin.cmd`. `%~dp0` is this script's+ * Windows launcher, written to `<app>\\bin\\penguin.cmd`. `%~dp0` is this script's* directory (with a trailing backslash): the exe sits three levels up* (bin -> app -> resources -> install root), the CLI entry one level up in the app dir.* CRLF line endings on purpose - cmd.exe is unreliable with bare LF scripts.@@ -72,7 +72,7 @@ exit 1export function windowsLauncherScript(): string {return ["@echo off",- "rem penguin CLI launcher (generated by packages/desktop/scripts/stage.mjs).",+ "rem penguin CLI launcher (generated by packages/desktop/scripts/build-assets.mjs).","rem Runs the bundled penguin CLI on this app's Electron runtime as Node.","setlocal",'set "ELECTRON_RUN_AS_NODE=1"',@@ -88,15 +88,16 @@ export function windowsLauncherScript(): string {* binary inside the AppImage mount, resources/app sits next to it), splices it into* argv[1] so `node -e` argv ([execPath, ...args]) becomes the [execPath, entry, ...args]* shape the CLI's argv parsing expects, then imports the (ESM) entry. Must not contain- * single quotes: the wrapper embeds it in a single-quoted shell string.+ * single quotes: the wrapper embeds it in a single-quoted shell string, so the path+ * segments are emitted with JSON.stringify rather than spelled out.*/export function appImageBootstrapJs(): string {+ const segments = CLI_ENTRY_RELPATH.split("/")+ .map((segment) => JSON.stringify(segment))+ .join(",");return ('const path=require("path");' +- 'const cli=path.join(path.dirname(process.execPath),"resources","app",' +- // Same entry CLI_ENTRY_RELPATH names — "index.js" here was left behind by b77ddea- // ("two bins, no router"), which renamed the CLI entry to penguin.js.- '"node_modules","@prismshadow","penguin-cli","dist","penguin.js");' ++ `const cli=path.join(path.dirname(process.execPath),"resources","app",${segments});` +"process.argv.splice(1,0,cli);" +"import(cli).catch((err)=>{console.error(err);process.exit(1);});");@@ -162,8 +163,8 @@ export function mergeWindowsUserPath(export type CliInstallKind = "darwin" | "windows" | "appimage";/**- * Whether (and how) this run can install the `penguin` command onto PATH. Dev runs have- * no staged bin/; deb installs already ship a /usr/bin symlink from their postinst+ * Whether (and how) this run can install the `penguin` command onto PATH. A source run has+ * no installed app to point at; deb installs already ship a /usr/bin symlink from their postinst* script (build/linux/after-install.tpl), so only the AppImage form qualifies on Linux* (recognized by the APPIMAGE env var its runtime sets).*/diff --git a/packages/desktop/src/server-process.ts b/packages/desktop/src/server-process.tsindex 44439b98..6504af02 100644--- a/packages/desktop/src/server-process.ts+++ b/packages/desktop/src/server-process.ts@@ -8,7 +8,6 @@import { randomBytes } from "node:crypto";import fs from "node:fs";import path from "node:path";-import { fileURLToPath } from "node:url";import { app, utilityProcess } from "electron";import type { UtilityProcess } from "electron";import { osProxyEnv } from "./os-proxy.js";@@ -34,22 +33,13 @@ function delay(ms: number): Promise<void> {}/**- * The server package's entry file — forked by path. Packaged builds ship the staged- * pnpm-deploy tree inside the app directory (asar is off, see electron-builder.yml),- * so the path is a plain file; dev runs resolve through this package's node_modules.+ * The server bundle — forked by path. tsup emits @prismshadow/penguin-server as one+ * self-contained file in this package's dist/, so a source run and a packaged app fork the+ * same artifact from the same app-path-relative location (asar is off, see+ * electron-builder.yml, so it is a plain file either way).*/function serverEntryPath(): string {- if (app.isPackaged) {- return path.join(- app.getAppPath(),- "node_modules",- "@prismshadow",- "penguin-server",- "dist",- "index.js",- );- }- return fileURLToPath(import.meta.resolve("@prismshadow/penguin-server"));+ return path.join(app.getAppPath(), "dist", "server.js");}/**diff --git a/packages/desktop/test/app-icon.test.ts b/packages/desktop/test/app-icon.test.tsindex d1431078..babb6e9f 100644--- a/packages/desktop/test/app-icon.test.ts+++ b/packages/desktop/test/app-icon.test.ts@@ -10,7 +10,7 @@ describe("windowIconPathFor", () => {expect(windowIconPathFor("/app", "darwin")).toBeNull();});- it("resolves build/icon.png inside the app dir on Linux and Windows", () => {+ it("resolves dist/icon.png inside the app dir on Linux and Windows", () => {expect(windowIconPathFor("/app", "linux")).toBe(path.join("/app", ...WINDOW_ICON_RELPATH));expect(windowIconPathFor("C:\\app", "win32")).toBe(path.join("C:\\app", ...WINDOW_ICON_RELPATH),@@ -23,16 +23,17 @@ describe("resolveWindowIcon", () => {afterAll(() => fs.rmSync(tmp, { recursive: true, force: true }));it("returns the path only when the file exists", () => {+ const iconPath = path.join(tmp, ...WINDOW_ICON_RELPATH);expect(resolveWindowIcon(tmp, "linux")).toBeNull();- fs.mkdirSync(path.join(tmp, "build"), { recursive: true });- fs.writeFileSync(path.join(tmp, "build", "icon.png"), "png");- expect(resolveWindowIcon(tmp, "linux")).toBe(path.join(tmp, "build", "icon.png"));+ fs.mkdirSync(path.dirname(iconPath), { recursive: true });+ fs.writeFileSync(iconPath, "png");+ expect(resolveWindowIcon(tmp, "linux")).toBe(iconPath);expect(resolveWindowIcon(tmp, "darwin")).toBeNull();});- it("the committed source icon resolves for a dev run of this package", () => {+ it("has a committed master for scripts/build-assets.mjs to copy into the app dir", () => {const pkgDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");- expect(resolveWindowIcon(pkgDir, "linux")).toBe(path.join(pkgDir, "build", "icon.png"));+ expect(fs.existsSync(path.join(pkgDir, "build", "icon.png"))).toBe(true);});});diff --git a/packages/desktop/tsup.config.ts b/packages/desktop/tsup.config.tsindex ae599615..21542500 100644--- a/packages/desktop/tsup.config.ts+++ b/packages/desktop/tsup.config.ts@@ -1,16 +1,39 @@import { defineConfig } from "tsup";+/**+ * Four self-contained bundles, no shared chunks: the shell itself, the server it forks as a+ * utilityProcess, the CLI its bin/ launchers start on the app's Electron runtime, and+ * launcher.ts, which scripts/build-assets.mjs imports (plain node, no Electron) to write+ * those launcher scripts. Because everything is bundled, the packaged app has no runtime+ * dependencies and ships no node_modules at all.+ *+ * The server and the CLI are bundled from their own packages' build output, so the app runs+ * exactly what an `npm install` of those packages would, linked into one file each.+ */export default defineConfig({- // launcher.ts is a second entry on purpose: scripts/stage.mjs imports dist/launcher.js- // at stage time (plain node, no Electron) to generate the CLI launcher scripts.- entry: ["src/main.ts", "src/launcher.ts"],+ entry: {+ main: "src/main.ts",+ launcher: "src/launcher.ts",+ server: "../server/dist/index.js",+ penguin: "../cli/dist/penguin.js",+ },format: ["esm"],target: "node22",platform: "node",clean: true,+ // Generated for a source run; electron-builder.yml keeps the .map files out of installers,+ // where they would roughly triple what these bundles add.sourcemap: true,- // `electron` is a runtime builtin inside the Electron main process; the workspace- // packages stay external so the server entry keeps its own file identity (the shell- // forks it as a child by path) and lock.js resolves from node_modules.- external: ["electron", "@prismshadow/penguin-server", "@prismshadow/penguin-core"],+ splitting: false,+ // Several bundled CJS dependencies (yaml, tar, smol-toml, commander, agenthub) call a bare+ // `require(...)` inside their own wrapper, which esbuild's ESM output otherwise routes to a+ // shim that always throws. Same banner scripts/deploy.mjs uses for the hot-update bundles.+ banner: {+ js: 'import { createRequire as __penguinCreateRequire } from "node:module"; const require = __penguinCreateRequire(import.meta.url);',+ },+ // `electron` is a runtime builtin inside the Electron main process, and its npm package is+ // only a shim that reads the binary's path from disk — bundling that shim is what a bare+ // `noExternal: [/.*/]` gets you. Everything else is bundled by default: tsup externalizes+ // this package's `dependencies`, and it deliberately declares none.+ external: ["electron"],});diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 4a54b6ea..dab4af07 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -136,7 +136,7 @@ importers:version: 4.4.3packages/desktop:- dependencies:+ devDependencies:'@prismshadow/penguin-cli':specifier: workspace:*version: file:packages/cli([email protected])@@ -146,10 +146,6 @@ importers:'@prismshadow/penguin-server':specifier: workspace:*version: link:../server- electron-updater:- specifier: ^6.8.9- version: 6.8.9([email protected])- devDependencies:'@types/node':specifier: ^24.0.0version: 24.13.3@@ -159,6 +155,9 @@ importers:electron-builder:specifier: ^26.0.12version: 26.15.3([email protected])([email protected])+ electron-updater:+ specifier: ^6.8.9+ version: 6.8.9([email protected])tsup:specifier: ^8.3.0version: 8.5.1([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])