Skip to content

An open-source, self-hosted system for apps built with web technologies.

Publish PhreshOS system

zohayrslileh22da836a6c1b
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
new file mode 100644
index 0000000..d9ed8f3
--- /dev/null
+++ b/.github/workflows/release.yml
@@ -0,0 +1,30 @@
+name: Release
+
+on:
+ push:
+ tags:
+ - "v*"
+
+permissions:
+ contents: write
+
+jobs:
+ release:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: oven-sh/setup-bun@v2
+ with:
+ bun-version: 1.3.14
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 24
+ - run: bun install --frozen-lockfile
+ - run: bun run verify
+ - name: Match tag to manifest
+ run: node -e 'const version = require("./package.json").version; if (process.argv[1] !== `v${version}`) throw new Error(`Tag ${process.argv[1]} does not match version ${version}`)' "$GITHUB_REF_NAME"
+ - run: bun run pack
+ - name: Publish verified distribution
+ run: gh release create "$GITHUB_REF_NAME" ./*.zip ./*.zip.sha256 --verify-tag --generate-notes
+ env:
+ GH_TOKEN: ${{ github.token }}
diff --git a/.github/workflows/verify.yml b/.github/workflows/verify.yml
new file mode 100644
index 0000000..abd70ad
--- /dev/null
+++ b/.github/workflows/verify.yml
@@ -0,0 +1,24 @@
+name: Verify
+
+on:
+ pull_request:
+ push:
+ branches:
+ - main
+
+permissions:
+ contents: read
+
+jobs:
+ verify:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: oven-sh/setup-bun@v2
+ with:
+ bun-version: 1.3.14
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 24
+ - run: bun install --frozen-lockfile
+ - run: bun run verify
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..30e4ccb
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,39 @@
+# dependencies (bun install)
+node_modules
+
+# output
+out
+dist
+*.tgz
+/*.zip
+/*.zip.sha256
+
+# code coverage
+coverage
+*.lcov
+
+# logs
+logs
+_.log
+report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
+
+# dotenv environment variable files
+.env
+.env.development.local
+.env.test.local
+.env.production.local
+.env.local
+
+# caches
+.eslintcache
+.cache
+*.tsbuildinfo
+
+# IntelliJ based IDEs
+.idea
+
+# Finder (MacOS) folder config
+.DS_Store
+
+# storage
+/storage/
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 0000000..04231c0
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,33 @@
+# Contributing
+
+The system repository owns the authoritative PhreshOS runtime: server state,
+the desktop that represents it, local Program intake, persistence boundaries,
+and Process management.
+
+## Development
+
+Install the pinned toolchain and verify the repository:
+
+```sh
+bun install --frozen-lockfile
+bun run verify
+```
+
+`verify` type-checks the source and exercises the actual release archive from a
+temporary installation; CI also boots it and requests the desktop. Changes to
+production dependencies, assets, startup, or build layout must preserve that
+standalone path.
+
+Consume other PhreshOS components only through published releases. Do not add
+workspace ranges, sibling paths, source aliases into another checkout, Git
+submodules, or assumptions about an enclosing directory.
+
+Runtime state must remain outside version control. Tests and development runs
+must use isolated storage and clean up every process and temporary resource they
+create.
+
+## Pull requests
+
+Explain which system-owned behavior the change serves, include focused proof
+for new behavior, update public documentation when the contract changes, and
+keep each pull request focused on one coherent change.
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..c4f1835
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,19 @@
+Copyright (c) 2026 Zohayr SLILEH
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..cdedb4c
--- /dev/null
+++ b/README.md
@@ -0,0 +1,83 @@
+# PhreshOS
+
+The authoritative PhreshOS runtime: its server, browser desktop, local Program
+intake, persistence boundaries, and Process management.
+
+## Distribution
+
+PhreshOS is distributed as a built archive from the official
+[`PhreshOS/system`](https://github.com/PhreshOS/system) GitHub Releases. It is
+not an npm package. The `phresh` CLI owns installation and service lifecycle:
+
+```sh
+phresh system install
+phresh system status
+```
+
+The bootstrap installs the CLI; `phresh system install` selects and verifies a
+compatible system release, installs its production dependencies, and registers
+the service. A production installation needs Node.js, but it never needs Bun,
+TypeScript, Vite, or this source checkout.
+
+The `0.x` line remains under active testing. The lifecycle commands and public
+release channel are being prepared and are not yet the way this transitional
+workspace starts the system.
+
+## Development
+
+Install the pinned toolchain and verify the complete repository:
+
+```sh
+bun install --frozen-lockfile
+bun run verify
+```
+
+Run a development instance with:
+
+```sh
+bun run dev
+```
+
+Development stores its isolated state in `storage/`, unless `PHRESHOS_HOME`
+names another absolute directory. Production always uses the real per-user
+`~/.phreshos` directory and does not consume that development override. The
+public port defaults to `4300`; `PHRESHOS_PORT` accepts any integer from 1
+through 65535.
+
+Neither variable is required. Runtime storage—including credentials, private
+keys, databases, logs, installed Programs, and uploaded files—must never enter
+the repository.
+
+## Build and release artifact
+
+```sh
+bun run build
+bun run pack
+```
+
+`build` produces a Node.js server and static desktop under `dist/`. `pack`
+places that build and its non-bundled assets in `phreshos@<version>.zip`. The
+adjacent `.sha256` file lets the CLI verify the integrity of the downloaded
+archive. The archive contains no TypeScript source, development tooling,
+repository state, or runtime storage.
+
+`bun run verify` type-checks the source, creates the exact distribution archive,
+extracts it into a temporary installation, installs only its declared production
+dependencies, and validates its Node.js entrypoint. On the clean CI runner it
+also boots that installation and requests the desktop. This is the release
+boundary: a successful source build alone is insufficient.
+
+## Repository boundary
+
+This repository owns the real system state and the desktop representation of
+that state. Shared vocabulary comes only from published `@phreshos/core`; shared
+Program-facing materials come only from published `@phreshos/react-ui`. It does
+not import sibling repository source or depend on an enclosing workspace.
+
+The CLI owns acquisition, installation, updates, and operating-system service
+integration. SDK repositories own Program-facing contracts. Those concerns do
+not move into the system merely because they integrate with it.
+
+## License
+
+Licensed under the [MIT License](LICENSE). Copyright 2026 Zohayr SLILEH.
diff --git a/SECURITY.md b/SECURITY.md
new file mode 100644
index 0000000..2fd5981
--- /dev/null
+++ b/SECURITY.md
@@ -0,0 +1,8 @@
+# Security
+
+Please do not disclose a suspected vulnerability in a public issue.
+
+Use GitHub's private vulnerability reporting for the `PhreshOS/system`
+repository. Include the affected version, the smallest reproduction available,
+the impact you observed, and any suggested mitigation. Reports are assessed
+against the latest published release.
diff --git a/assets/bundled/logo.png b/assets/bundled/logo.png
new file mode 100644
index 0000000..09391ce
Binary files /dev/null and b/assets/bundled/logo.png differ
diff --git a/assets/bundled/wallpaper.jpg b/assets/bundled/wallpaper.jpg
new file mode 100644
index 0000000..fe10736
Binary files /dev/null and b/assets/bundled/wallpaper.jpg differ
diff --git a/assets/default-icon.png b/assets/default-icon.png
new file mode 100644
index 0000000..09391ce
Binary files /dev/null and b/assets/default-icon.png differ
diff --git a/bun.lock b/bun.lock
new file mode 100644
index 0000000..d4b12e2
--- /dev/null
+++ b/bun.lock
@@ -0,0 +1,532 @@
+{
+ "lockfileVersion": 1,
+ "configVersion": 1,
+ "workspaces": {
+ "": {
+ "name": "phreshos",
+ "dependencies": {
+ "@fontsource/roboto": "^5.3.0",
+ "@hono/node-server": "^2.1.1",
+ "cfonts": "^3.3.1",
+ "get-port": "^7.2.0",
+ "gsap": "^3.15.0",
+ "hono": "^4.13.2",
+ "keyv": "^5.6.0",
+ "lz-string": "^1.5.0",
+ "node-rsa": "^2.0.0",
+ "react": "^19.2.8",
+ "react-dom": "^19.2.8",
+ "sharp": "^0.35.3",
+ "superjson": "^2.2.6",
+ "uuid": "^14.0.1",
+ "ws": "^8.21.3",
+ "zod": "^4.4.3",
+ },
+ "devDependencies": {
+ "@babel/core": "^7.29.7",
+ "@babel/plugin-proposal-decorators": "^7.29.7",
+ "@phreshos/core": "^0.1.1",
+ "@phreshos/react-ui": "^0.1.0",
+ "@rolldown/plugin-babel": "^0.2.3",
+ "@tailwindcss/vite": "^4.3.3",
+ "@types/adm-zip": "^0.5.8",
+ "@types/node": "^25.9.5",
+ "@types/react": "^19.2.18",
+ "@types/react-dom": "^19.2.4",
+ "@types/ws": "^8.18.1",
+ "@vitejs/plugin-react": "^6.0.5",
+ "adm-zip": "^0.6.0",
+ "babel-plugin-react-compiler": "^1.0.0",
+ "tailwindcss": "^4.3.3",
+ "tsx": "^4.23.12",
+ "typescript": "^6.0.3",
+ "vite": "^8.2.1",
+ },
+ },
+ },
+ "packages": {
+ "@babel/code-frame": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.29.7", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw=="],
+
+ "@babel/compat-data": ["@babel/[email protected]", "", {}, "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg=="],
+
+ "@babel/core": ["@babel/[email protected]", "", { "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/generator": "^7.29.7", "@babel/helper-compilation-targets": "^7.29.7", "@babel/helper-module-transforms": "^7.29.7", "@babel/helpers": "^7.29.7", "@babel/parser": "^7.29.7", "@babel/template": "^7.29.7", "@babel/traverse": "^7.29.7", "@babel/types": "^7.29.7", "@jridgewell/remapping": "^2.3.5", "convert-source-map": "^2.0.0", "debug": "^4.1.0", "gensync": "^1.0.0-beta.2", "json5": "^2.2.3", "semver": "^6.3.1" } }, "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA=="],
+
+ "@babel/generator": ["@babel/[email protected]", "", { "dependencies": { "@babel/parser": "^7.29.8", "@babel/types": "^7.29.8", "@jridgewell/gen-mapping": "^0.3.12", "@jridgewell/trace-mapping": "^0.3.28", "jsesc": "^3.0.2" } }, "sha512-gZbepsdh3WDtgZKWL+vTPh71LSBrm/Y4/QDZBVCcYfmeTEEuoOYwlSy+G1StfJg+/Zy550u/3TATbm7qDbbMtg=="],
+
+ "@babel/helper-annotate-as-pure": ["@babel/[email protected]", "", { "dependencies": { "@babel/types": "^7.29.7" } }, "sha512-OoK6239jHPuSQOoS0kfTVKn0b/rVTk0seKq4Gd2UMLtmOVLjDC0ki3e+c90Trqv2gMfvJFqkiljrr568+qddiw=="],
+
+ "@babel/helper-compilation-targets": ["@babel/[email protected]", "", { "dependencies": { "@babel/compat-data": "^7.29.7", "@babel/helper-validator-option": "^7.29.7", "browserslist": "^4.24.0", "lru-cache": "^5.1.1", "semver": "^6.3.1" } }, "sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g=="],
+
+ "@babel/helper-create-class-features-plugin": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-annotate-as-pure": "^7.29.7", "@babel/helper-member-expression-to-functions": "^7.29.7", "@babel/helper-optimise-call-expression": "^7.29.7", "@babel/helper-replace-supers": "^7.29.7", "@babel/helper-skip-transparent-expression-wrappers": "^7.29.7", "@babel/traverse": "^7.29.7", "semver": "^6.3.1" }, "peerDependencies": { "@babel/core": "^7.0.0" } }, "sha512-IY3ZD9Tmooqr3TUhc3DUWxiuo8xx1DWLhd5M7hQ+ZWJamqM2BbalrBJb2MisSLoYorOj75U03qULCxQTY9r3hg=="],
+
+ "@babel/helper-globals": ["@babel/[email protected]", "", {}, "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA=="],
+
+ "@babel/helper-member-expression-to-functions": ["@babel/[email protected]", "", { "dependencies": { "@babel/traverse": "^7.29.7", "@babel/types": "^7.29.7" } }, "sha512-j+7JYmk1JYDtACIGj0QJqqWZjoUpMoEikQGADMaHgCMCSDqd2+P32rfcibUNrGOMWrlzK1WJBdxrB3JJQZwWtg=="],
+
+ "@babel/helper-module-imports": ["@babel/[email protected]", "", { "dependencies": { "@babel/traverse": "^7.29.7", "@babel/types": "^7.29.7" } }, "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g=="],
+
+ "@babel/helper-module-transforms": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-module-imports": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7", "@babel/traverse": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0" } }, "sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg=="],
+
+ "@babel/helper-optimise-call-expression": ["@babel/[email protected]", "", { "dependencies": { "@babel/types": "^7.29.7" } }, "sha512-+kmGVjcT9RGYzoDwdwEqEvGgKe3BYq+O1iGzjFubaNgZHwYHP6lsF2Yghf4kEuv9BV7tYDZ913aBW9am6YKong=="],
+
+ "@babel/helper-plugin-utils": ["@babel/[email protected]", "", {}, "sha512-G7sHYigPY17oO5SYWnfD/0MTBwVR781S/JI643e/JhUYgVgWE/61SoW3NH9KWUKyKq5LVh3npif99Wkt6j86Jw=="],
+
+ "@babel/helper-replace-supers": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-member-expression-to-functions": "^7.29.7", "@babel/helper-optimise-call-expression": "^7.29.7", "@babel/traverse": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0" } }, "sha512-atfGXWSeCiF4DnKZIfmJfQRkSw9b9gNNXR1kqKjbhG4pGYCOnkp8OcTB8E3NXjBu8NpheSnOeNKz8KT7UNFTmQ=="],
+
+ "@babel/helper-skip-transparent-expression-wrappers": ["@babel/[email protected]", "", { "dependencies": { "@babel/traverse": "^7.29.7", "@babel/types": "^7.29.7" } }, "sha512-brcMGQaVzIeUb+6/bs1Av0f8YuNNjKY2JyvfRCsFuFsdKccEQ5Ges2y74D74NZ1Rz8lKJ9ksJkfqwQFJ/iNEyQ=="],
+
+ "@babel/helper-string-parser": ["@babel/[email protected]", "", {}, "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw=="],
+
+ "@babel/helper-validator-identifier": ["@babel/[email protected]", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="],
+
+ "@babel/helper-validator-option": ["@babel/[email protected]", "", {}, "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw=="],
+
+ "@babel/helpers": ["@babel/[email protected]", "", { "dependencies": { "@babel/template": "^7.29.7", "@babel/types": "^7.29.7" } }, "sha512-1k2lAGRMfHTcwuNYcCNUmaUffmQv8KWMfh2iJUUeRlwlwH4FdNG7mfPI10NPfLHJFThE4Tyr4mv7kTNZOiPuBg=="],
+
+ "@babel/parser": ["@babel/[email protected]", "", { "dependencies": { "@babel/types": "^7.29.8" }, "bin": "./bin/babel-parser.js" }, "sha512-E8lTAYNB1KW+FH+VGJuZM1ioAx2E6oVlvQFRrf5P8ZZmsiJXYAD9vTFV7yyEURNzgh1dFqMZuO6tUwcARbqFCA=="],
+
+ "@babel/plugin-proposal-decorators": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-create-class-features-plugin": "^7.29.7", "@babel/helper-plugin-utils": "^7.29.7", "@babel/plugin-syntax-decorators": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-EtU0Hi3GvrTqD56xKmZvV/uCXK2ZbwVNPNLAquVItcAZpUhkXwWlo3Fmj0c2LxgSf2I8IDULeAepwNP1OefLXg=="],
+
+ "@babel/plugin-syntax-decorators": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-9MTTLbF39X6sqM92JPEsoI7++26hjZvzkxKZy64aMhWLH2mPkJ/Q3AV4QLmls3R14FpSpkOwQQfUh962JGQxxg=="],
+
+ "@babel/template": ["@babel/[email protected]", "", { "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/parser": "^7.29.7", "@babel/types": "^7.29.7" } }, "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg=="],
+
+ "@babel/traverse": ["@babel/[email protected]", "", { "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/generator": "^7.29.8", "@babel/helper-globals": "^7.29.7", "@babel/parser": "^7.29.8", "@babel/template": "^7.29.7", "@babel/types": "^7.29.8", "debug": "^4.3.1" } }, "sha512-I5z7H3bf/41ktsNVLtpN0wAa336HkqIHQ5BuPLEhTkt1jVSyZpeNKIzTgEWmlxjdg81R0IgUCcaE+Ok3NvrfZg=="],
+
+ "@babel/types": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg=="],
+
+ "@emnapi/runtime": ["@emnapi/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA=="],
+
+ "@esbuild/aix-ppc64": ["@esbuild/[email protected]", "", { "os": "aix", "cpu": "ppc64" }, "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ=="],
+
+ "@esbuild/android-arm": ["@esbuild/[email protected]", "", { "os": "android", "cpu": "arm" }, "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg=="],
+
+ "@esbuild/android-arm64": ["@esbuild/[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A=="],
+
+ "@esbuild/android-x64": ["@esbuild/[email protected]", "", { "os": "android", "cpu": "x64" }, "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q=="],
+
+ "@esbuild/darwin-arm64": ["@esbuild/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw=="],
+
+ "@esbuild/darwin-x64": ["@esbuild/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw=="],
+
+ "@esbuild/freebsd-arm64": ["@esbuild/[email protected]", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw=="],
+
+ "@esbuild/freebsd-x64": ["@esbuild/[email protected]", "", { "os": "freebsd", "cpu": "x64" }, "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg=="],
+
+ "@esbuild/linux-arm": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "arm" }, "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w=="],
+
+ "@esbuild/linux-arm64": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug=="],
+
+ "@esbuild/linux-ia32": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "ia32" }, "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ=="],
+
+ "@esbuild/linux-loong64": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "none" }, "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ=="],
+
+ "@esbuild/linux-mips64el": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "none" }, "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA=="],
+
+ "@esbuild/linux-ppc64": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "ppc64" }, "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ=="],
+
+ "@esbuild/linux-riscv64": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "none" }, "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA=="],
+
+ "@esbuild/linux-s390x": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "s390x" }, "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg=="],
+
+ "@esbuild/linux-x64": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ=="],
+
+ "@esbuild/netbsd-arm64": ["@esbuild/[email protected]", "", { "os": "none", "cpu": "arm64" }, "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw=="],
+
+ "@esbuild/netbsd-x64": ["@esbuild/[email protected]", "", { "os": "none", "cpu": "x64" }, "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw=="],
+
+ "@esbuild/openbsd-arm64": ["@esbuild/[email protected]", "", { "os": "openbsd", "cpu": "arm64" }, "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ=="],
+
+ "@esbuild/openbsd-x64": ["@esbuild/[email protected]", "", { "os": "openbsd", "cpu": "x64" }, "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw=="],
+
+ "@esbuild/openharmony-arm64": ["@esbuild/[email protected]", "", { "os": "none", "cpu": "arm64" }, "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q=="],
+
+ "@esbuild/sunos-x64": ["@esbuild/[email protected]", "", { "os": "sunos", "cpu": "x64" }, "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g=="],
+
+ "@esbuild/win32-arm64": ["@esbuild/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ=="],
+
+ "@esbuild/win32-ia32": ["@esbuild/[email protected]", "", { "os": "win32", "cpu": "ia32" }, "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA=="],
+
+ "@esbuild/win32-x64": ["@esbuild/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g=="],
+
+ "@fontsource/roboto": ["@fontsource/[email protected]", "", {}, "sha512-BapRJOWYP+LZ21zp+wBQjfpPYKRoxc4LspJ/RLuI+HSMBD5u/X4O+ESDrSvEqDSy0rAl7GwBJ+09mdc16cVQ1Q=="],
+
+ "@hono/node-server": ["@hono/[email protected]", "", { "peerDependencies": { "hono": "^4" } }, "sha512-ELuehkj5VCBdgEw9zs+ivkKwyzzUCSQuE96YmiPvn1ECBoZCczbFXJLeEGMTYjphP6gydh4pHMqEYPVMYUVgQg=="],
+
+ "@img/colour": ["@img/[email protected]", "", {}, "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ=="],
+
+ "@img/sharp-darwin-arm64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-arm64": "1.3.2" }, "os": "darwin", "cpu": "arm64" }, "sha512-RMnFX7YQsMoh7lWfcM4NEHHymBX/rLuKNPVM84XE9ONPcaSCDgE7CHIHpSgPcO2xcRthgBy1HfNO319mwhIAkg=="],
+
+ "@img/sharp-darwin-x64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-x64": "1.3.2" }, "os": "darwin", "cpu": "x64" }, "sha512-Xo+5uFBtLN0BKqieTxiFzFPQAUlBbbH5iBKyRX/z1JrbnYsHTfKJnUfL8+p2TPXr1pXqao4eeL4Rl144uDpK9w=="],
+
+ "@img/sharp-freebsd-wasm32": ["@img/[email protected]", "", { "dependencies": { "@img/sharp-wasm32": "0.35.3" }, "os": "freebsd" }, "sha512-lUxcqWIj2wMQ9BrwNjngcr1gWUr5xgaGThBRqPPalIC2n67Cqj1uPh8NnA/ZhAg8hUbKl+kVHKwgUIwe6ZYPrg=="],
+
+ "@img/sharp-libvips-darwin-arm64": ["@img/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-9J6ypZFpQBj4YnePGoq/S38w6nz+vqg5WZLrLGY4YuSemdMq47GMLBPO42MzwdGwpg/agZ7xzZcFHa48xlywfg=="],
+
+ "@img/sharp-libvips-darwin-x64": ["@img/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-m2pW1n6cns9VaubNwsZ+c3CRYjxNQWgJ5gPlnL1nbBcpkBvFm6SCFN5o0psFHI8w9n11NKhFkeEDns98tiqbEw=="],
+
+ "@img/sharp-libvips-linux-arm": ["@img/[email protected]", "", { "os": "linux", "cpu": "arm" }, "sha512-1eMLzy92I4J6rmi4mAT8yC3HxOtniyGELlzGbNMLLeqe052ahFQ0h6LFq+lh5DsDIdYViIDst08abvSbcEdLXQ=="],
+
+ "@img/sharp-libvips-linux-arm64": ["@img/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-dqVSFynCox4C/J8kT16V7SIFAns0IjgLwkvYT7p8LQVmJ5OS5b6tI9IGflxTeuBS//zXeFIUbwt5dwxyZ17cnA=="],
+
+ "@img/sharp-libvips-linux-ppc64": ["@img/[email protected]", "", { "os": "linux", "cpu": "ppc64" }, "sha512-3z0NHDxD6n5I9gc05U1eW1AyRm+Gznzq3naMrthPNqE6oYykcogW0l/jfpJdjYnuNl8R7yI9pNbE1XiUeyq0Aw=="],
+
+ "@img/sharp-libvips-linux-riscv64": ["@img/[email protected]", "", { "os": "linux", "cpu": "none" }, "sha512-bsb4rI+NldGOsXuej2r8OdSS8+zXDVaCWxyWrcv6kneTOlgAHtZABRzBBCwdsPiD90J4myNJuHpg6kA20ImW/w=="],
+
+ "@img/sharp-libvips-linux-s390x": ["@img/[email protected]", "", { "os": "linux", "cpu": "s390x" }, "sha512-/ABshyj8gCpyIrNXnHn4LorDJ0HHm1VhXPBlxZ8zAtfVPAaSafXPGn+sUSIRiwaSBy0mmFjSjiXI5mkcwdChKQ=="],
+
+ "@img/sharp-libvips-linux-x64": ["@img/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-ITPEtgffGJ0S6G9dRyw/366tJQqFRcHWPHhC+Stpg3Z8AEMrDrTr2lhdz4f/Y/HMbRh//7Z5mBzEpVdi62Oc3w=="],
+
+ "@img/sharp-libvips-linuxmusl-arm64": ["@img/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-zE9EdiUzUmg5mDT5a1rk5fYJ6GWPloTwWBYDS14naqHsL+EaMpDj1AWnpLgh3u0YCORv2Tt50wrcrpYqkP97Kw=="],
+
+ "@img/sharp-libvips-linuxmusl-x64": ["@img/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-m0lrLiUt+lBYnCFr8qV/65yMR4E/c7/wf78I5eKTdkEakFAlZ9QlzEM3QIhhAwVeUhLAHLcCq7a7Vszq/oFNZQ=="],
+
+ "@img/sharp-linux-arm": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm": "1.3.2" }, "os": "linux", "cpu": "arm" }, "sha512-affVWCTLooy8TSxbDx2qkzuDeaWLNVBA+P//FNBirHsXpP2fuBhk5AuboYUnrDnzoXes8GFjpTx0SBFOCRg+FA=="],
+
+ "@img/sharp-linux-arm64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm64": "1.3.2" }, "os": "linux", "cpu": "arm64" }, "sha512-QgKDspHPnrU+GQ55XPhGwyhC8acLVOOSyAvo1oVfFmrIXLkDNmGWzAfDZ4xK8oSA1qBQrALcHX0G5UZni/SuFQ=="],
+
+ "@img/sharp-linux-ppc64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-ppc64": "1.3.2" }, "os": "linux", "cpu": "ppc64" }, "sha512-sMd8rDxmpLOwv/7N44klFjOD5DUO7FLdjiXDI0hoxYaf7Ar262dQIEkosE98bps+5HPLtp/EvNqeqQtOycP/IA=="],
+
+ "@img/sharp-linux-riscv64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-riscv64": "1.3.2" }, "os": "linux", "cpu": "none" }, "sha512-0Eob78yjlYPfL5vMNWAW55l3R9Y6BQS/gOfe0ZcP9mEz9ohhKSt4im1hayiknXgf8AWrFqMvJcKIdmLmEe7yeQ=="],
+
+ "@img/sharp-linux-s390x": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-s390x": "1.3.2" }, "os": "linux", "cpu": "s390x" }, "sha512-KgAxQ0DxpNOq1rG2t5cgTgShJFGSuU7XO45cqC+1NVOuZnP6tlgZRuSYOfNupGkHID0o3cJOsw4DVeJpMovcGw=="],
+
+ "@img/sharp-linux-x64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-x64": "1.3.2" }, "os": "linux", "cpu": "x64" }, "sha512-8pqvxubL2PGdhlPy6GLqzDYMUjyRmKAwKHYKixpdJYBUK7PJ0C029XdsnpFIdgRZG68fZiGdHVWcKPvtiPB4cA=="],
+
+ "@img/sharp-linuxmusl-arm64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-arm64": "1.3.2" }, "os": "linux", "cpu": "arm64" }, "sha512-Vz0iQjzzcSX3HCbfwFfCSG/9SCIqyO0mH2sXyiHaAYfBk0cRsCWXRyQYX0ovCK/PAQBbTzQ0dsPQHh5MAFL59w=="],
+
+ "@img/sharp-linuxmusl-x64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-x64": "1.3.2" }, "os": "linux", "cpu": "x64" }, "sha512-6O1NPKcDVj9QEdg7Hx549EX8U0rp6yXQERqru6yRN7fGBn32UvIRJUlWnk+8xDCiG76hXVBbX82NZ/ZKr0euIg=="],
+
+ "@img/sharp-wasm32": ["@img/[email protected]", "", { "dependencies": { "@emnapi/runtime": "^1.11.1" } }, "sha512-cZ0XkcYGpHZkqW6iCkqTcmUC0CD9DhD5d/qeZlZkfRBn6GnHniZXLUo5+9xw8Iv76YE6LQFN9YNBlKREcCG76w=="],
+
+ "@img/sharp-webcontainers-wasm32": ["@img/[email protected]", "", { "dependencies": { "@img/sharp-wasm32": "0.35.3" }, "cpu": "none" }, "sha512-2rnq7bX3NzeR2T4YWgz8qiG4h3TSdMe+vN1iQXpJleSJ3SM5zQ8Fy2SyyXAWlbxpEZ2Y+Z4u1BePgJEYbSy80Q=="],
+
+ "@img/sharp-win32-arm64": ["@img/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-4bPwFdMbeC4JQ8L8LOyWp6nsHcboP5fxkp6iPOXz2Vg49R42TuMs2whkJ5OAP4/Ul035qOzy0AecOF9VOscn4w=="],
+
+ "@img/sharp-win32-ia32": ["@img/[email protected]", "", { "os": "win32", "cpu": "ia32" }, "sha512-r53mXsBN6lFUDiST764SvgwUdHAqM4rPAiDzAmf4fLoB6X/rkfyTrLCg6+g17wJJiCmB3JYgHuUldCWUIRFSXw=="],
+
+ "@img/sharp-win32-x64": ["@img/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-D4y1vNeZrIIJCN+uHaWVtH86B+aCrdMYYjicy9pXHvbGZeGYLLSd3wdVuC37FxVXlU1ARsk84eKWfWMXGYEqvA=="],
+
+ "@internationalized/date": ["@internationalized/[email protected]", "", { "dependencies": { "@swc/helpers": "^0.5.0" } }, "sha512-fuLX+3ZKLsxI73y8b01EG/WjHb6gE6weCqlfawPO27kBWGMh9G1yH6Csv1uU7/cac9H2GHmOMt6CjmuQ1aia4Q=="],
+
+ "@internationalized/number": ["@internationalized/[email protected]", "", { "dependencies": { "@swc/helpers": "^0.5.0" } }, "sha512-3ji1fcrT+FPAK86UqEhB/psHixYo6niWPJtt7+qRaYFynt/BaJG8GhAPimtWUpEiVSTq8ZM8L5psMxGquiB/Vg=="],
+
+ "@internationalized/string": ["@internationalized/[email protected]", "", { "dependencies": { "@swc/helpers": "^0.5.0" } }, "sha512-PDx6//vHSpRnHfxqMqto11zQvhsaU74O3mKv2F/0eicGZcl9NLjQmGlbHz/LsJh5tLKp4A4L7ZVTzN1/MmMTvA=="],
+
+ "@jridgewell/gen-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.0", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA=="],
+
+ "@jridgewell/remapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ=="],
+
+ "@jridgewell/resolve-uri": ["@jridgewell/[email protected]", "", {}, "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw=="],
+
+ "@jridgewell/sourcemap-codec": ["@jridgewell/[email protected]", "", {}, "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og=="],
+
+ "@jridgewell/trace-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],
+
+ "@keyv/serialize": ["@keyv/[email protected]", "", {}, "sha512-dXn3FZhPv0US+7dtJsIi2R+c7qWYiReoEh5zUntWCf4oSpMNib8FDhSoed6m3QyZdx5hK7iLFkYk3rNxwt8vTA=="],
+
+ "@noble/hashes": ["@noble/[email protected]", "", {}, "sha512-oN+QwyX7VSHotibwubG3kpzbwKrfnyR6OOO+3Nk/53ADL7FmgHHz4TgrbaYKvvOw09u6QTx0oiH1cNCIOuN0CQ=="],
+
+ "@oxc-project/types": ["@oxc-project/[email protected]", "", {}, "sha512-nuhZIOLuI6TFQ32I/WnUx+SCPY7SdSKwgnFHydAuoS1+Z4BRcaP+RRJmGzl9lw+0OFF7UmaESf7KQRXaNLHypg=="],
+
+ "@phreshos/core": ["@phreshos/[email protected]", "", {}, "sha512-R+4KkGJ/VjPAOLwkQfmTiEE//PPs8JUuxEefhH7c0XVRgs1UjEnfoEZMxp+f9hVxlSM4RGmURaqvubJk3BuqUA=="],
+
+ "@phreshos/react-ui": ["@phreshos/[email protected]", "", { "dependencies": { "react-aria-components": "^1.20.0" }, "peerDependencies": { "@phreshos/core": "^0.1.1", "react": "^19.2.0", "react-dom": "^19.2.0" } }, "sha512-3ipOna2nSUn7vzL74CAwnpdaVJtyq7z6dPM0bPiEYafv3+nTrwtC3+otdScM1gfj+9kUfjn1YA0LmcBuuNOp6w=="],
+
+ "@react-types/shared": ["@react-types/[email protected]", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1" } }, "sha512-AzsuD9OfxTOZMMvTRhlN3oHBwOmFN7tDh27LzqmHt4+uOgPhJT7ZM7/kVs/8/o0WxayMUIk3hBmCFRHv1FUoag=="],
+
+ "@rolldown/binding-android-arm64": ["@rolldown/[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-jHC2cnyKz5xU2fhECtFl8OZ83cYNt13GZQD+0uMJ/X3o+ijmd56okHhTUwxVSHPx1IRVIJEZ1/1pPzeLCU6XKA=="],
+
+ "@rolldown/binding-darwin-arm64": ["@rolldown/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-Dc5mPD8F5F/FS8i01syd7FTF6yB2fVthH/TRkjwJkzUK6EpoxHtqvZQP5Zwq80/5z19TWYHIg1KOHboCgVx/aQ=="],
+
+ "@rolldown/binding-darwin-x64": ["@rolldown/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-fpDm4oBo6SqLvWUYCmFhdde3U9KH2fRNNMeAnAPAIwxRL345xutL0EtEUcuoxsoazdJGv/MuDBQHlCDrtbvqOg=="],
+
+ "@rolldown/binding-freebsd-x64": ["@rolldown/[email protected]", "", { "os": "freebsd", "cpu": "x64" }, "sha512-rSJoreDE/HoIzoaib6MTp5jQtCTdMHKIvItAKT/ImS6Y6Ww76oUaeMyp4Vc/fAgd/ehji068IxetHXAnqUwN9A=="],
+
+ "@rolldown/binding-linux-arm-gnueabihf": ["@rolldown/[email protected]", "", { "os": "linux", "cpu": "arm" }, "sha512-/jm8OGHgn7oGaJu3i/qZI9spUGcJ+y/lk43ttQ/iO1tOd9NissG6o97bighBCiL+BKRngmcDuR6ikfwYdJmVuQ=="],
+
+ "@rolldown/binding-linux-arm64-gnu": ["@rolldown/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-tIP06BeD9EqvECBrPZ+sqdPlYrT+aYaAiu1wYziVx5elRK/ftm33JxVDy2bXGbr6J0CrtirCkR87/X5a2euEng=="],
+
+ "@rolldown/binding-linux-arm64-musl": ["@rolldown/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-Ql1Q0EQqVThvn9VAVlwNzsUvbSFtCMGjLpRRi4pk5i7NZZ4n5ISiLMjHYtus4VQ2PvkSw24zyaCVsiS+sXPj1w=="],
+
+ "@rolldown/binding-linux-ppc64-gnu": ["@rolldown/[email protected]", "", { "os": "linux", "cpu": "ppc64" }, "sha512-GjbjXD4XXfN19D0LZNbmiCBUoDiRACsYHr0yaIbbn8aFsXjHZifcYqu/W5Er5X2X990WjHXFrxarn5chzItorQ=="],
+
+ "@rolldown/binding-linux-s390x-gnu": ["@rolldown/[email protected]", "", { "os": "linux", "cpu": "s390x" }, "sha512-p5WR0NOwaRmJ/B1b6IjEFLLivwEsf3PrdBIhRbhTCQisbo2SvHHpG4ELB/+FgQNnB88LTOF86upmJmbvZdQ2lw=="],
+
+ "@rolldown/binding-linux-x64-gnu": ["@rolldown/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-4/GyVjmhR+Tc6HLJvwc1sOhPqAZtySiSMesOZyX6JQ5XBxoTDEMKQzvo07NIK6nTon/SivlZqvhzvuVBNQhObQ=="],
+
+ "@rolldown/binding-linux-x64-musl": ["@rolldown/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-l9eeLsCNvPpmSXUej0etw/J1eqV0Jj1D5G/xG6YTijmE6dkv6E2QezgWbTfQk63v952DPqrjOCoiqxq7Bw0YUQ=="],
+
+ "@rolldown/binding-openharmony-arm64": ["@rolldown/[email protected]", "", { "os": "none", "cpu": "arm64" }, "sha512-e0F355MSTMm3+UOqtV3L24gFUp2N5m1f8L/7d56deik6va+AXdrt9F8LbzGpeWGWRbZEDq4m8NVnJDeBtf9DZg=="],
+
+ "@rolldown/binding-win32-arm64-msvc": ["@rolldown/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-AWLi0uBRYh6QlE7OKhiz+phZC0qwtij2QZmhmOdsLdFn64m7oMpooE9ICE3lhm9xMb4SpDo2WbHcxX1iFLFtqw=="],
+
+ "@rolldown/binding-win32-x64-msvc": ["@rolldown/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-UwSDJOg3dqCAejWdxclJjCsh3Qq4vLYMDxmyHqo1btz3stK2VqgwNd3mm5tuIwzSlGIQ/1H9Hr+Zn09mrezNqQ=="],
+
+ "@rolldown/plugin-babel": ["@rolldown/[email protected]", "", { "dependencies": { "picomatch": "^4.0.4" }, "peerDependencies": { "@babel/core": "^7.29.0 || ^8.0.0-rc.1", "@babel/plugin-transform-runtime": "^7.29.0 || ^8.0.0-rc.1", "@babel/runtime": "^7.27.0 || ^8.0.0-rc.1", "rolldown": "^1.0.0-rc.5", "vite": "^8.0.0" }, "optionalPeers": ["@babel/plugin-transform-runtime", "@babel/runtime", "vite"] }, "sha512-+zEk16yGlz1F9STiRr6uG9hmIXb6nprjLczV/htGptYuLoCuxb+itZ03RKCEeOhBpDDd1NU7qF6x1VLMUp62bw=="],
+
+ "@rolldown/pluginutils": ["@rolldown/[email protected]", "", {}, "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw=="],
+
+ "@swc/helpers": ["@swc/[email protected]", "", { "dependencies": { "tslib": "^2.8.0" } }, "sha512-5lSsMOTXURePglDfvuAQUqkGek9Hg2kksOYay2m0+XR++b2NWYL/4sWyuvVBIs8oKnJaxkdi9whaL/sqN13afw=="],
+
+ "@tailwindcss/node": ["@tailwindcss/[email protected]", "", { "dependencies": { "@jridgewell/remapping": "^2.3.5", "enhanced-resolve": "^5.24.1", "jiti": "^2.7.0", "lightningcss": "1.32.0", "magic-string": "^0.30.21", "source-map-js": "^1.2.1", "tailwindcss": "4.3.3" } }, "sha512-/T8IKEsf9VTU6tLjgC7+sv2mOPtQxzE2jMw7u4Tt40Tx+QSZxpzh95/H6cMKoja9XuW7iMdLJYBB0o9G1CaAgg=="],
+
+ "@tailwindcss/oxide": ["@tailwindcss/[email protected]", "", { "optionalDependencies": { "@tailwindcss/oxide-android-arm64": "4.3.3", "@tailwindcss/oxide-darwin-arm64": "4.3.3", "@tailwindcss/oxide-darwin-x64": "4.3.3", "@tailwindcss/oxide-freebsd-x64": "4.3.3", "@tailwindcss/oxide-linux-arm-gnueabihf": "4.3.3", "@tailwindcss/oxide-linux-arm64-gnu": "4.3.3", "@tailwindcss/oxide-linux-arm64-musl": "4.3.3", "@tailwindcss/oxide-linux-x64-gnu": "4.3.3", "@tailwindcss/oxide-linux-x64-musl": "4.3.3", "@tailwindcss/oxide-wasm32-wasi": "4.3.3", "@tailwindcss/oxide-win32-arm64-msvc": "4.3.3", "@tailwindcss/oxide-win32-x64-msvc": "4.3.3" } }, "sha512-krXjAikiaFSPaK/FkAQT5UTx3VormQaiZ5hBFlJZ9UFQGB/rwg1MZIhHAG9smMQRTdyJxP6Qt5MwMtdyU5FWrA=="],
+
+ "@tailwindcss/oxide-android-arm64": ["@tailwindcss/[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-Y85A2gmPSkl5Ve5qR86GL4HT509cFqQh1aes9p3sSkyTPwt0Pppf3GkwGe4JPACcRYjgJIEhQgM6dBClnr0NYw=="],
+
+ "@tailwindcss/oxide-darwin-arm64": ["@tailwindcss/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-BiaWatpBcERQFDlOjRDpIVXuFK5PJez5SA4JMg6VYZdBYU+qKfV/vqjcIs+IYmtitf1xYQZTwXvU/8y4lfZUGw=="],
+
+ "@tailwindcss/oxide-darwin-x64": ["@tailwindcss/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-fAeUqfV5ndhxRwai8cXGzdLvul9utWOmeTkv69unv4ZXixjn61Z+p9lCWdwOwA3TYboG3BwdVuN/RDjhBRl0mw=="],
+
+ "@tailwindcss/oxide-freebsd-x64": ["@tailwindcss/[email protected]", "", { "os": "freebsd", "cpu": "x64" }, "sha512-iyf5bV6+wnAlflVeEy7R25dupxTNECZN5QMI0qNT6eT+EgaGdZcKhGkr5SdoaWiLJ3spLqIY9VCeSGrwmtg4kw=="],
+
+ "@tailwindcss/oxide-linux-arm-gnueabihf": ["@tailwindcss/[email protected]", "", { "os": "linux", "cpu": "arm" }, "sha512-aAYUprJAJQWWbRrPvtjdroZ56Md+JM8pMiopS6xGEwDfLhqj+2ver2p4nU4Mb3CRqcMmNBjo8KkUgcxhkzVQGQ=="],
+
+ "@tailwindcss/oxide-linux-arm64-gnu": ["@tailwindcss/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-nDxldcEENOxZRzC2uu9jrutZdAAQtb+8WWDCSnWL1zvBk1+FN+x6MtDViPB5AJMfttVCUhehGWus3XBPgatM/w=="],
+
+ "@tailwindcss/oxide-linux-arm64-musl": ["@tailwindcss/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-Md44bD6veX/PC5iyF8cDVnw4HBIANZepRZZ7a8DQOvkfo5WUBwcp6iAuCUz23u+4SUkhJlD3eL7hNdW8ezd/kA=="],
+
+ "@tailwindcss/oxide-linux-x64-gnu": ["@tailwindcss/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-tx7us1muwOKAKWao2v/GaafFeQboE6aj88vC6ziN2NCGcRm8gWUhwjzg+YdVB1e4boAtdtma4L43onunI6NS4w=="],
+
+ "@tailwindcss/oxide-linux-x64-musl": ["@tailwindcss/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-SJxX60smvHgasZoBy11dX6YRjXJFovwWBoedhbQPOBzgFWBHGB+TVPWB9BxzR7TTxU8FQZAI2AyiNCMzFm8Img=="],
+
+ "@tailwindcss/oxide-wasm32-wasi": ["@tailwindcss/[email protected]", "", { "dependencies": { "@emnapi/core": "^1.11.1", "@emnapi/runtime": "^1.11.1", "@emnapi/wasi-threads": "^1.2.2", "@napi-rs/wasm-runtime": "^1.1.4", "@tybys/wasm-util": "^0.10.2", "tslib": "^2.8.1" }, "cpu": "none" }, "sha512-jx1+rPhY/5Ympkktd656HBWEBLxP7dH06losBLjjf5vgCODXvi9KhtftWcMIwTFIDqBr7cRnQkdLnAG+IOlGvQ=="],
+
+ "@tailwindcss/oxide-win32-arm64-msvc": ["@tailwindcss/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-3rc292Ca2ceK6Ulcc/bAVnTs/3nDtoPhyEKlgPv+yQJQi/JS/AMJlqzxvlDacL1nekbrcf6bTqp/jV4qgnPxNQ=="],
+
+ "@tailwindcss/oxide-win32-x64-msvc": ["@tailwindcss/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-yJ0pwIVc/nYeGoV02WtsN8KYyLQv7kyI2wDnkezyJlGGjkd4QLwDGAwl47YpPJeuI0M0ObaXGSPjvWDPeTPggw=="],
+
+ "@tailwindcss/vite": ["@tailwindcss/[email protected]", "", { "dependencies": { "@tailwindcss/node": "4.3.3", "@tailwindcss/oxide": "4.3.3", "tailwindcss": "4.3.3" }, "peerDependencies": { "vite": "^5.2.0 || ^6 || ^7 || ^8" } }, "sha512-yYU8cogLeSh/ms2jh8Fj7jaba/EWa7Ja6GoUqYZaraEuCI5YS6ms6ObZgjjedm+jm6XZjdNRWBpPP6Z86oOxcw=="],
+
+ "@types/adm-zip": ["@types/[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-RVVH7QvZYbN+ihqZ4kX/dMiowf6o+Jk1fNwiSdx0NahBJLU787zkULhGhJM8mf/obmLGmgdMM0bXsQTmyfbR7Q=="],
+
+ "@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": ">=7.24.0 <7.24.7" } }, "sha512-OScDchr2fwuUmWdf4kZ9h7PcJiYDVInhJizG/biAq3cAvqwYktuy/TYGGdZNMtNTFUP7rnb0NU4TUdm82kt4Rg=="],
+
+ "@types/react": ["@types/[email protected]", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-AnzbBERsrLKtk2XSfTbYRLjQPdy116Sty4q+T+Bp3IC4l6jNBvreVPAHmpq9qhXQM7CXZPjLVmGMw9sy+hxQ3w=="],
+
+ "@types/react-dom": ["@types/[email protected]", "", { "peerDependencies": { "@types/react": "^19.2.0" } }, "sha512-Bsc+QHgp+P/F02XDzNCY9jnZNCUuLki36KT7VKrTXXLdHf+vHMNZnW1rVu5DNW/rCK+fya3DATySbLM4yhtKUw=="],
+
+ "@types/ws": ["@types/[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg=="],
+
+ "@vitejs/plugin-react": ["@vitejs/[email protected]", "", { "dependencies": { "@rolldown/pluginutils": "^1.0.1" }, "peerDependencies": { "@rolldown/plugin-babel": "^0.1.7 || ^0.2.0", "babel-plugin-react-compiler": "^1.0.0", "vite": "^8.0.0" }, "optionalPeers": ["@rolldown/plugin-babel", "babel-plugin-react-compiler"] }, "sha512-BOVzne/NL162sMdResB25mUv+vWMF5NoAjNf09TeGlE7ZpszZWSD3winycicLJw72yeVsoCn/2kOhEuCvEShMA=="],
+
+ "adm-zip": ["[email protected]", "", {}, "sha512-XleryMhbuksdKtofnWZ9Sk+4CUTbms4Mb/EU32SZwToAyZ5RgVos/ki8n+yr0LWHOGKuakbXTuuYNHLQjhddgg=="],
+
+ "aria-hidden": ["[email protected]", "", { "dependencies": { "tslib": "^2.0.0" } }, "sha512-ik3ZgC9dY/lYVVM++OISsaYDeg1tb0VtP5uL3ouh1koGOaUMDPpbFIei4JkFimWUFPn90sbMNMXQAIVOlnYKJA=="],
+
+ "babel-plugin-react-compiler": ["[email protected]", "", { "dependencies": { "@babel/types": "^7.26.0" } }, "sha512-Ixm8tFfoKKIPYdCCKYTsqv+Fd4IJ0DQqMyEimo+pxUOMUR9cVPlwTrFt9Avu+3cb6Zp3mAzl+t1MrG2fxxKsxw=="],
+
+ "baseline-browser-mapping": ["[email protected]", "", { "bin": { "baseline-browser-mapping": "dist/cli.cjs" } }, "sha512-FwMjJJ7HnyZpWe+oWxegG0fezZyBZUagI5LZEoO3GCbtbKNwRfMH9Ue5d5v01PNePBy1QSfPSDTTeVL0Hb9EzA=="],
+
+ "browserslist": ["[email protected]", "", { "dependencies": { "baseline-browser-mapping": "^2.11.12", "caniuse-lite": "^1.0.30001809", "electron-to-chromium": "^1.5.402", "node-releases": "^2.0.53", "update-browserslist-db": "^1.3.0" }, "bin": { "browserslist": "cli.js" } }, "sha512-V2NpofLblG64mfOtSgDhOJESZEGogzDMBv/q+W6oc4LXWP/q75eOXoOaaOu1EOadB9U4Bwx/e0yzbvwKH8zalA=="],
+
+ "caniuse-lite": ["[email protected]", "", {}, "sha512-xxWVywk6a6Arlk+hymeycyn/VgqEfLDxupvhH/xiY5SJ/18kmi9o6MiO320DCUzypORHLtvh0I4i04tUhCNHNQ=="],
+
+ "cfonts": ["[email protected]", "", { "dependencies": { "supports-color": "^8", "window-size": "^1" }, "bin": { "cfonts": "bin/index.js" } }, "sha512-ZGEmN3W9mViWEDjsuPo4nK4h39sfh6YtoneFYp9WLPI/rw8BaSSrfQC6jkrGW3JMvV3ZnExJB/AEqXc/nHYxkw=="],
+
+ "client-only": ["[email protected]", "", {}, "sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA=="],
+
+ "clsx": ["[email protected]", "", {}, "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA=="],
+
+ "convert-source-map": ["[email protected]", "", {}, "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg=="],
+
+ "copy-anything": ["[email protected]", "", { "dependencies": { "is-what": "^5.2.0" } }, "sha512-7Vv6asjS4gMOuILabD3l739tsaxFQmC+a7pLZm02zyvs8p977bL3zEgq3yDk5rn9B0PbYgIv++jmHcuUab4RhA=="],
+
+ "csstype": ["[email protected]", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="],
+
+ "debug": ["[email protected]", "", { "dependencies": { "ms": "^2.1.3" }, "peerDependencies": { "supports-color": "*" }, "optionalPeers": ["supports-color"] }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="],
+
+ "define-property": ["[email protected]", "", { "dependencies": { "is-descriptor": "^1.0.0" } }, "sha512-cZTYKFWspt9jZsMscWo8sc/5lbPC9Q0N5nBLgb+Yd915iL3udB1uFgS3B8YCx66UVHq018DAVFoee7x+gxggeA=="],
+
+ "detect-libc": ["[email protected]", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="],
+
+ "electron-to-chromium": ["[email protected]", "", {}, "sha512-ChI4N44d0B4A6C8prnNjMOaGgE59fUyEVYcRYm2XEXIjMbbvF5i9UL1cblDbpGqiU0uS8FE8UcKxqZqTXdmzbQ=="],
+
+ "enhanced-resolve": ["[email protected]", "", { "dependencies": { "graceful-fs": "^4.2.4", "tapable": "^2.3.3" } }, "sha512-L1l8TNvomm6UVW5B253AGxQagSQr+vGwhMlrrfRS2qmhx46AMpMVJKQYLvWYbysTMY8VoicOvzHzoHMbyzB+4A=="],
+
+ "esbuild": ["[email protected]", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.28.2", "@esbuild/android-arm": "0.28.2", "@esbuild/android-arm64": "0.28.2", "@esbuild/android-x64": "0.28.2", "@esbuild/darwin-arm64": "0.28.2", "@esbuild/darwin-x64": "0.28.2", "@esbuild/freebsd-arm64": "0.28.2", "@esbuild/freebsd-x64": "0.28.2", "@esbuild/linux-arm": "0.28.2", "@esbuild/linux-arm64": "0.28.2", "@esbuild/linux-ia32": "0.28.2", "@esbuild/linux-loong64": "0.28.2", "@esbuild/linux-mips64el": "0.28.2", "@esbuild/linux-ppc64": "0.28.2", "@esbuild/linux-riscv64": "0.28.2", "@esbuild/linux-s390x": "0.28.2", "@esbuild/linux-x64": "0.28.2", "@esbuild/netbsd-arm64": "0.28.2", "@esbuild/netbsd-x64": "0.28.2", "@esbuild/openbsd-arm64": "0.28.2", "@esbuild/openbsd-x64": "0.28.2", "@esbuild/openharmony-arm64": "0.28.2", "@esbuild/sunos-x64": "0.28.2", "@esbuild/win32-arm64": "0.28.2", "@esbuild/win32-ia32": "0.28.2", "@esbuild/win32-x64": "0.28.2" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA=="],
+
+ "escalade": ["[email protected]", "", {}, "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA=="],
+
+ "fdir": ["[email protected]", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="],
+
+ "fsevents": ["[email protected]", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
+
+ "function-bind": ["[email protected]", "", {}, "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA=="],
+
+ "gensync": ["[email protected]", "", {}, "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg=="],
+
+ "get-port": ["[email protected]", "", {}, "sha512-afP4W205ONCuMoPBqcR6PSXnzX35KTcJygfJfcp+QY+uwm3p20p1YczWXhlICIzGMCxYBQcySEcOgsJcrkyobg=="],
+
+ "graceful-fs": ["[email protected]", "", {}, "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ=="],
+
+ "gsap": ["[email protected]", "", {}, "sha512-dMW4CWBTUK1AEEDeZc1g4xpPGIrSf9fJF960qbTZmN/QwZIWY5wgliS6JWl9/25fpTGJrMRtSjGtOmPnfjZB+A=="],
+
+ "has-flag": ["[email protected]", "", {}, "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ=="],
+
+ "hasown": ["[email protected]", "", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A=="],
+
+ "hono": ["[email protected]", "", {}, "sha512-r8AO2mYHoLxSHkgafNeC/BXyb2vWRxD3jem4Ts+ptav8oTG5FIRifAjuJEmZI4bSvvc2ns0GxmIYiZnHqN3mMw=="],
+
+ "is-accessor-descriptor": ["[email protected]", "", { "dependencies": { "hasown": "^2.0.3" } }, "sha512-AIbwAcazqP3R65dGvqk1V+a+vE5Fg1yu/ZKMOiBWSUIXXiwQkYmXQcVa2O0nh0tSDKDFKxG2mY7dB1Sr4hEP1g=="],
+
+ "is-buffer": ["[email protected]", "", {}, "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w=="],
+
+ "is-data-descriptor": ["[email protected]", "", { "dependencies": { "hasown": "^2.0.0" } }, "sha512-bc4NlCDiCr28U4aEsQ3Qs2491gVq4V8G7MQyws968ImqjKuYtTJXrl7Vq7jsN7Ly/C3xj5KWFrY7sHNeDkAzXw=="],
+
+ "is-descriptor": ["[email protected]", "", { "dependencies": { "is-accessor-descriptor": "^1.0.2", "is-data-descriptor": "^1.0.1" } }, "sha512-bv5z95W0dDtLfKwDfkTNxaRxmISBD3eQBKJeVxv2AQ7MjuUnDNG7cIQqvFtMOUYhsILWHhMayWdoGqNqYYYjww=="],
+
+ "is-number": ["[email protected]", "", { "dependencies": { "kind-of": "^3.0.2" } }, "sha512-4cboCqIpliH+mAvFNegjZQ4kgKc3ZUhQVr3HvWbSh5q3WH2v82ct+T2Y1hdU5Gdtorx/cLifQjqCbL7bpznLTg=="],
+
+ "is-what": ["[email protected]", "", {}, "sha512-oG7cgbmg5kLYae2N5IVd3jm2s+vldjxJzK1pcu9LfpGuQ93MQSzo0okvRna+7y5ifrD+20FE8FvjusyGaz14fw=="],
+
+ "jiti": ["[email protected]", "", { "bin": { "jiti": "lib/jiti-cli.mjs" } }, "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ=="],
+
+ "js-tokens": ["[email protected]", "", {}, "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="],
+
+ "jsesc": ["[email protected]", "", { "bin": { "jsesc": "bin/jsesc" } }, "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA=="],
+
+ "json5": ["[email protected]", "", { "bin": { "json5": "lib/cli.js" } }, "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg=="],
+
+ "keyv": ["[email protected]", "", { "dependencies": { "@keyv/serialize": "^1.1.1" } }, "sha512-CYDD3SOtsHtyXeEORYRx2qBtpDJFjRTGXUtmNEMGyzYOKj1TE3tycdlho7kA1Ufx9OYWZzg52QFBGALTirzDSw=="],
+
+ "kind-of": ["[email protected]", "", { "dependencies": { "is-buffer": "^1.1.5" } }, "sha512-NOW9QQXMoZGg/oqnVNoNTTIFEIid1627WCffUBJEdMxYApq7mNE7CpzucIPc+ZQg25Phej7IJSmX3hO+oblOtQ=="],
+
+ "lightningcss": ["[email protected]", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.33.0", "lightningcss-darwin-arm64": "1.33.0", "lightningcss-darwin-x64": "1.33.0", "lightningcss-freebsd-x64": "1.33.0", "lightningcss-linux-arm-gnueabihf": "1.33.0", "lightningcss-linux-arm64-gnu": "1.33.0", "lightningcss-linux-arm64-musl": "1.33.0", "lightningcss-linux-x64-gnu": "1.33.0", "lightningcss-linux-x64-musl": "1.33.0", "lightningcss-win32-arm64-msvc": "1.33.0", "lightningcss-win32-x64-msvc": "1.33.0" } }, "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA=="],
+
+ "lightningcss-android-arm64": ["[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg=="],
+
+ "lightningcss-darwin-arm64": ["[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg=="],
+
+ "lightningcss-darwin-x64": ["[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ=="],
+
+ "lightningcss-freebsd-x64": ["[email protected]", "", { "os": "freebsd", "cpu": "x64" }, "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg=="],
+
+ "lightningcss-linux-arm-gnueabihf": ["[email protected]", "", { "os": "linux", "cpu": "arm" }, "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ=="],
+
+ "lightningcss-linux-arm64-gnu": ["[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg=="],
+
+ "lightningcss-linux-arm64-musl": ["[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ=="],
+
+ "lightningcss-linux-x64-gnu": ["[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg=="],
+
+ "lightningcss-linux-x64-musl": ["[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw=="],
+
+ "lightningcss-win32-arm64-msvc": ["[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA=="],
+
+ "lightningcss-win32-x64-msvc": ["[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA=="],
+
+ "lru-cache": ["[email protected]", "", { "dependencies": { "yallist": "^3.0.2" } }, "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w=="],
+
+ "lz-string": ["[email protected]", "", { "bin": { "lz-string": "bin/bin.js" } }, "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ=="],
+
+ "magic-string": ["[email protected]", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="],
+
+ "ms": ["[email protected]", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],
+
+ "nanoid": ["[email protected]", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w=="],
+
+ "node-releases": ["[email protected]", "", {}, "sha512-D9UOmYG3UH1V+ENW56t5QXBwJw1YEY18ruVeus89Rw+SyIgjPkCO84bRzO3uNIYosJbNwiabWVn48o3uJLjxFQ=="],
+
+ "node-rsa": ["[email protected]", "", { "dependencies": { "@noble/hashes": "^2.2.0" } }, "sha512-7yfzccmBd5rm7pALJf709tPwLL987WvdT7LC/QK5Oxa5S2aabdBPjxRDxhWKkbfCc9/FiC82lwSc+ulGZHH44g=="],
+
+ "picocolors": ["[email protected]", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="],
+
+ "picomatch": ["[email protected]", "", {}, "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A=="],
+
+ "postcss": ["[email protected]", "", { "dependencies": { "nanoid": "^3.3.17", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-u82N74LFzG8ca+dD8puPnplTXoGH4fTPpVGuIbt36G3qvNlkvfD0lEAZSxaly3KX8TS/L1A1gsCEmvKmBcVbkQ=="],
+
+ "react": ["[email protected]", "", {}, "sha512-PWaYA1L/q9u2u7xYQi+Y3L3Yfnie7XyLeaJICV1MGD6LprsBxcAqGjYyr0eY3p+QdsA+x/Irkt4Qif8D63+Sbw=="],
+
+ "react-aria": ["[email protected]", "", { "dependencies": { "@internationalized/date": "^3.12.3", "@internationalized/number": "^3.6.7", "@internationalized/string": "^3.2.10", "@react-types/shared": "^3.36.1", "@swc/helpers": "^0.5.0", "aria-hidden": "^1.2.3", "clsx": "^2.0.0", "react-stately": "3.49.0", "use-sync-external-store": "^1.6.0" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1", "react-dom": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1" } }, "sha512-AyWLw0XR38cFPwBu/ErgGaVrc5dupLEKmRlMXTGvFKOtbaGRQ2+yQJkjVhpdHhoRhU4+G+tJDFeHDTS8tK3bfQ=="],
+
+ "react-aria-components": ["[email protected]", "", { "dependencies": { "@internationalized/date": "^3.12.3", "@internationalized/string": "^3.2.10", "@react-types/shared": "^3.36.1", "@swc/helpers": "^0.5.0", "client-only": "^0.0.1", "react-aria": "3.51.0", "react-stately": "3.49.0" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1", "react-dom": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1" } }, "sha512-BMbpIgoV9aELeBrB0Y120NgoigHb5OdcJwc+4e7uSnbTbamea6lo+gqcc4LAxzMaK3Jf+7LI1oCDE6yANsmxIQ=="],
+
+ "react-dom": ["[email protected]", "", { "dependencies": { "scheduler": "^0.27.0" }, "peerDependencies": { "react": "^19.2.8" } }, "sha512-rVprimfGBG3DR+Tq0IQG2DT5PxKth1WIGDmj5yPmlzr4YBe7uyE+Du4oVqTDXZSHGGGXRtTJEGSSePyQCMBglQ=="],
+
+ "react-stately": ["[email protected]", "", { "dependencies": { "@internationalized/date": "^3.12.3", "@internationalized/number": "^3.6.7", "@internationalized/string": "^3.2.10", "@react-types/shared": "^3.36.1", "@swc/helpers": "^0.5.0", "use-sync-external-store": "^1.6.0" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1" } }, "sha512-13iNq2KzBrRAzxRc+n53hgROfIistiYY/sPtIhCw1qUB7/kmo+X1xEU2uiS5zcCIrc55AUPwoHqOIIpKWSwB9A=="],
+
+ "rolldown": ["[email protected]", "", { "dependencies": { "@oxc-project/types": "=0.144.0", "@rolldown/pluginutils": "^1.0.0" }, "optionalDependencies": { "@rolldown/binding-android-arm64": "1.2.4", "@rolldown/binding-darwin-arm64": "1.2.4", "@rolldown/binding-darwin-x64": "1.2.4", "@rolldown/binding-freebsd-x64": "1.2.4", "@rolldown/binding-linux-arm-gnueabihf": "1.2.4", "@rolldown/binding-linux-arm64-gnu": "1.2.4", "@rolldown/binding-linux-arm64-musl": "1.2.4", "@rolldown/binding-linux-ppc64-gnu": "1.2.4", "@rolldown/binding-linux-s390x-gnu": "1.2.4", "@rolldown/binding-linux-x64-gnu": "1.2.4", "@rolldown/binding-linux-x64-musl": "1.2.4", "@rolldown/binding-openharmony-arm64": "1.2.4", "@rolldown/binding-win32-arm64-msvc": "1.2.4", "@rolldown/binding-win32-x64-msvc": "1.2.4" }, "bin": { "rolldown": "./bin/cli.mjs" } }, "sha512-rSr7irW0K7QRWzjdJXqZowkcRdDtjRduh43rBltnVKd0VFq839l1lJoDvGJb6gl7+4rTTCrPWu+YfujUL8Ug7w=="],
+
+ "scheduler": ["[email protected]", "", {}, "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q=="],
+
+ "semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],
+
+ "sharp": ["[email protected]", "", { "dependencies": { "@img/colour": "^1.1.0", "detect-libc": "^2.1.2", "semver": "^7.8.5" }, "optionalDependencies": { "@img/sharp-darwin-arm64": "0.35.3", "@img/sharp-darwin-x64": "0.35.3", "@img/sharp-freebsd-wasm32": "0.35.3", "@img/sharp-libvips-darwin-arm64": "1.3.2", "@img/sharp-libvips-darwin-x64": "1.3.2", "@img/sharp-libvips-linux-arm": "1.3.2", "@img/sharp-libvips-linux-arm64": "1.3.2", "@img/sharp-libvips-linux-ppc64": "1.3.2", "@img/sharp-libvips-linux-riscv64": "1.3.2", "@img/sharp-libvips-linux-s390x": "1.3.2", "@img/sharp-libvips-linux-x64": "1.3.2", "@img/sharp-libvips-linuxmusl-arm64": "1.3.2", "@img/sharp-libvips-linuxmusl-x64": "1.3.2", "@img/sharp-linux-arm": "0.35.3", "@img/sharp-linux-arm64": "0.35.3", "@img/sharp-linux-ppc64": "0.35.3", "@img/sharp-linux-riscv64": "0.35.3", "@img/sharp-linux-s390x": "0.35.3", "@img/sharp-linux-x64": "0.35.3", "@img/sharp-linuxmusl-arm64": "0.35.3", "@img/sharp-linuxmusl-x64": "0.35.3", "@img/sharp-webcontainers-wasm32": "0.35.3", "@img/sharp-win32-arm64": "0.35.3", "@img/sharp-win32-ia32": "0.35.3", "@img/sharp-win32-x64": "0.35.3" }, "peerDependencies": { "@types/node": "*" }, "optionalPeers": ["@types/node"] }, "sha512-ej0zVHuZGHCiABXcNxeYhpRnPNPAcvbG8RMdBAhDAxLKkCRVSpK3Iyu7qbqw3JMzoj0REeM6f3tJLtVwl0023Q=="],
+
+ "source-map-js": ["[email protected]", "", {}, "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="],
+
+ "superjson": ["[email protected]", "", { "dependencies": { "copy-anything": "^4" } }, "sha512-H+ue8Zo4vJmV2nRjpx86P35lzwDT3nItnIsocgumgr0hHMQ+ZGq5vrERg9kJBo5AWGmxZDhzDo+WVIJqkB0cGA=="],
+
+ "supports-color": ["[email protected]", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q=="],
+
+ "tailwindcss": ["[email protected]", "", {}, "sha512-gOhV3P7ufE62QDGg1zVaTgCR+EtPv92k2nIhVcVKcLmxT1sUBsQGhnZj175j+MqRt4zLF7ic+sCYjfhxMxj7YQ=="],
+
+ "tapable": ["[email protected]", "", {}, "sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A=="],
+
+ "tinyglobby": ["[email protected]", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.4" } }, "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g=="],
+
+ "tslib": ["[email protected]", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],
+
+ "tsx": ["[email protected]", "", { "dependencies": { "esbuild": "~0.28.0" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "bin": { "tsx": "dist/cli.mjs" } }, "sha512-FDf4L4sYzKtzWYhU/Xm0AQFdTjdIxNo9ElTf2mxXM6k8YMHXzYUe4yODVaXP4V9uMFbVg8c0qyBccK2OOxb45Q=="],
+
+ "typescript": ["[email protected]", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw=="],
+
+ "undici-types": ["[email protected]", "", {}, "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg=="],
+
+ "update-browserslist-db": ["[email protected]", "", { "dependencies": { "escalade": "^3.2.0", "picocolors": "^1.1.1" }, "peerDependencies": { "browserslist": ">= 4.21.0" }, "bin": { "update-browserslist-db": "cli.js" } }, "sha512-ZZ61DsRsOnakl74HAmp3oSN4aXUmEWXf+i/yv0h7tIBfICc3VdrFErQKUUKPgu3AMsTUMbcongALEN4l6GSUrQ=="],
+
+ "use-sync-external-store": ["[email protected]", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w=="],
+
+ "uuid": ["[email protected]", "", { "bin": { "uuid": "dist-node/bin/uuid" } }, "sha512-6ZxzVpzDXDa3bJWaHilVayA+BH/1zmxCJoVgvmqJnid/gPoKHxUrS/aC/T6LGQtNHT+XHG9fXPJB4d+IrU30Ew=="],
+
+ "vite": ["[email protected]", "", { "dependencies": { "lightningcss": "^1.33.0", "picomatch": "^4.0.5", "postcss": "^8.5.25", "rolldown": "~1.2.1", "tinyglobby": "^0.2.17" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "@vitejs/devtools": "^0.4.0", "esbuild": "^0.27.0 || ^0.28.0", "jiti": ">=1.21.0", "less": "^4.0.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "@vitejs/devtools", "esbuild", "jiti", "less", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-EU/eS7BH3XROHh2YnBefjM6DBKA6ZeMZEYQbj7NLWg5wHYlhB8B/Mayd5XsgWq+NFYccDOTemRpdETWR6Ka/lw=="],
+
+ "window-size": ["[email protected]", "", { "dependencies": { "define-property": "^1.0.0", "is-number": "^3.0.0" }, "bin": { "window-size": "cli.js" } }, "sha512-5D/9vujkmVQ7pSmc0SCBmHXbkv6eaHwXEx65MywhmUMsI8sGqJ972APq1lotfcwMKPFLuCFfL8xGHLIp7jaBmA=="],
+
+ "ws": ["[email protected]", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw=="],
+
+ "yallist": ["[email protected]", "", {}, "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g=="],
+
+ "zod": ["[email protected]", "", {}, "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ=="],
+
+ "@tailwindcss/node/lightningcss": ["[email protected]", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.32.0", "lightningcss-darwin-arm64": "1.32.0", "lightningcss-darwin-x64": "1.32.0", "lightningcss-freebsd-x64": "1.32.0", "lightningcss-linux-arm-gnueabihf": "1.32.0", "lightningcss-linux-arm64-gnu": "1.32.0", "lightningcss-linux-arm64-musl": "1.32.0", "lightningcss-linux-x64-gnu": "1.32.0", "lightningcss-linux-x64-musl": "1.32.0", "lightningcss-win32-arm64-msvc": "1.32.0", "lightningcss-win32-x64-msvc": "1.32.0" } }, "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ=="],
+
+ "@tailwindcss/oxide-wasm32-wasi/@emnapi/core": ["@emnapi/[email protected]", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.3", "tslib": "^2.4.0" }, "bundled": true }, "sha512-zLpS5asjEb7lq8jYLq37N6XKaE41DIexlY1rF/z4/tIl3wo13Sqm28fRyfIsKZD+NZ8mM5RoKkpW/rBcuoSZSg=="],
+
+ "@tailwindcss/oxide-wasm32-wasi/@emnapi/runtime": ["@emnapi/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" }, "bundled": true }, "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA=="],
+
+ "@tailwindcss/oxide-wasm32-wasi/@emnapi/wasi-threads": ["@emnapi/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" }, "bundled": true }, "sha512-ELEBe8PsLvvJ6QMr0zLt8ffvOHW/dc1m3CEzNMg7aJUv3bMaoDtw2TXyDAwkYBuroxxuHEwhRTLJSe5sya547g=="],
+
+ "@tailwindcss/oxide-wasm32-wasi/@napi-rs/wasm-runtime": ["@napi-rs/[email protected]", "", { "dependencies": { "@tybys/wasm-util": "^0.10.3" }, "peerDependencies": { "@emnapi/core": "^1.7.1 || ^2.0.0-alpha.4", "@emnapi/runtime": "^1.7.1 || ^2.0.0-alpha.4" }, "bundled": true }, "sha512-UMduMbqO5s5zF2NkNacMT/yK5Y5QiKvWr2+50bzIIxFDwVJ2h49b+oyjaCGPhJxd2/gC2x39EHv/gHVuu36x2Q=="],
+
+ "@tailwindcss/oxide-wasm32-wasi/@tybys/wasm-util": ["@tybys/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" }, "bundled": true }, "sha512-F3fo1MYrRJYL3zER0OUOmkutjr1Vp23m7OsSgp7nq4SP6OqX6C/56XFIPAl5bt3zaBRjmW7SGz3u/6LwFpYcOg=="],
+
+ "@tailwindcss/oxide-wasm32-wasi/tslib": ["[email protected]", "", { "bundled": true }, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],
+
+ "sharp/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA=="],
+
+ "@tailwindcss/node/lightningcss/lightningcss-android-arm64": ["[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg=="],
+
+ "@tailwindcss/node/lightningcss/lightningcss-darwin-arm64": ["[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ=="],
+
+ "@tailwindcss/node/lightningcss/lightningcss-darwin-x64": ["[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w=="],
+
+ "@tailwindcss/node/lightningcss/lightningcss-freebsd-x64": ["[email protected]", "", { "os": "freebsd", "cpu": "x64" }, "sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig=="],
+
+ "@tailwindcss/node/lightningcss/lightningcss-linux-arm-gnueabihf": ["[email protected]", "", { "os": "linux", "cpu": "arm" }, "sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw=="],
+
+ "@tailwindcss/node/lightningcss/lightningcss-linux-arm64-gnu": ["[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ=="],
+
+ "@tailwindcss/node/lightningcss/lightningcss-linux-arm64-musl": ["[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg=="],
+
+ "@tailwindcss/node/lightningcss/lightningcss-linux-x64-gnu": ["[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA=="],
+
+ "@tailwindcss/node/lightningcss/lightningcss-linux-x64-musl": ["[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg=="],
+
+ "@tailwindcss/node/lightningcss/lightningcss-win32-arm64-msvc": ["[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw=="],
+
+ "@tailwindcss/node/lightningcss/lightningcss-win32-x64-msvc": ["[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q=="],
+ }
+}
diff --git a/package.json b/package.json
new file mode 100644
index 0000000..9872560
--- /dev/null
+++ b/package.json
@@ -0,0 +1,71 @@
+{
+ "name": "phreshos",
+ "displayName": "PhreshOS",
+ "version": "0.1.0",
+ "description": "The PhreshOS server, desktop, and authoritative system runtime.",
+ "type": "module",
+ "private": true,
+ "author": "Zohayr SLILEH",
+ "license": "MIT",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/PhreshOS/system.git"
+ },
+ "bugs": {
+ "url": "https://github.com/PhreshOS/system/issues"
+ },
+ "homepage": "https://github.com/PhreshOS/system#readme",
+ "keywords": [
+ "phreshos",
+ "operating-system",
+ "web-desktop"
+ ],
+ "scripts": {
+ "clean": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\"",
+ "check": "tsc --noEmit",
+ "dev": "node --import tsx source/dev.ts",
+ "build": "node --import tsx source/build.ts",
+ "start": "node --run build && node dist/server/main.js",
+ "pack": "node --run build && node --import tsx source/pack.ts",
+ "verify:distribution": "node scripts/verify-distribution.mjs",
+ "verify": "node --run check && node --run verify:distribution"
+ },
+ "dependencies": {
+ "@fontsource/roboto": "^5.3.0",
+ "@hono/node-server": "^2.1.1",
+ "cfonts": "^3.3.1",
+ "get-port": "^7.2.0",
+ "gsap": "^3.15.0",
+ "hono": "^4.13.2",
+ "keyv": "^5.6.0",
+ "lz-string": "^1.5.0",
+ "node-rsa": "^2.0.0",
+ "react": "^19.2.8",
+ "react-dom": "^19.2.8",
+ "sharp": "^0.35.3",
+ "superjson": "^2.2.6",
+ "uuid": "^14.0.1",
+ "ws": "^8.21.3",
+ "zod": "^4.4.3"
+ },
+ "devDependencies": {
+ "@babel/core": "^7.29.7",
+ "@babel/plugin-proposal-decorators": "^7.29.7",
+ "@phreshos/core": "^0.1.1",
+ "@phreshos/react-ui": "^0.1.0",
+ "@rolldown/plugin-babel": "^0.2.3",
+ "@tailwindcss/vite": "^4.3.3",
+ "@types/adm-zip": "^0.5.8",
+ "@types/node": "^25.9.5",
+ "@types/react": "^19.2.18",
+ "@types/react-dom": "^19.2.4",
+ "@types/ws": "^8.18.1",
+ "@vitejs/plugin-react": "^6.0.5",
+ "adm-zip": "^0.6.0",
+ "babel-plugin-react-compiler": "^1.0.0",
+ "tailwindcss": "^4.3.3",
+ "tsx": "^4.23.12",
+ "typescript": "^6.0.3",
+ "vite": "^8.2.1"
+ }
+}
diff --git a/scripts/verify-distribution.mjs b/scripts/verify-distribution.mjs
new file mode 100644
index 0000000..9353cb5
--- /dev/null
+++ b/scripts/verify-distribution.mjs
@@ -0,0 +1,138 @@
+import assert from "node:assert/strict"
+import { execFileSync, spawn } from "node:child_process"
+import { createHash } from "node:crypto"
+import { mkdtempSync, mkdirSync, readFileSync, rmSync } from "node:fs"
+import { createServer } from "node:net"
+import { tmpdir } from "node:os"
+import { dirname, join, resolve } from "node:path"
+import { fileURLToPath } from "node:url"
+import AdmZip from "adm-zip"
+import manifest from "../package.json" with { type: "json" }
+
+const repository = resolve(dirname(fileURLToPath(import.meta.url)), "..")
+const temporary = mkdtempSync(join(tmpdir(), "system-distribution-"))
+const archive = join(repository, `${manifest.name}@${manifest.version}.zip`)
+const checksum = `${archive}.sha256`
+const installation = join(temporary, "installation")
+const npm = process.platform === "win32" ? "npm.cmd" : "npm"
+const portVariable = `${manifest.name.replace(/[^a-zA-Z0-9]+/g, "_").replace(/^_+|_+$/g, "").toUpperCase()}_PORT`
+
+let runtime
+
+try {
+ execFileSync(
+ process.execPath,
+ ["--run", "pack"],
+ { cwd: repository, stdio: "inherit" }
+ )
+
+ const zip = new AdmZip(archive)
+ const expectedChecksum = readFileSync(checksum, "utf8").trim()
+ const actualChecksum = createHash("sha256").update(readFileSync(archive)).digest("hex")
+
+ assert.equal(expectedChecksum, `${actualChecksum} ${archive.slice(repository.length + 1)}`)
+
+ const paths = new Set(zip.getEntries().filter(entry => !entry.isDirectory).map(entry => entry.entryName))
+
+ for (const required of [
+ "package.json",
+ "server/main.js",
+ "client/index.html",
+ "assets/default-icon.png"
+ ]) {
+ assert(paths.has(required), `the distribution has no ${required}`)
+ }
+
+ for (const path of paths) {
+ assert(!path.startsWith("source/"), `TypeScript source entered the distribution: ${path}`)
+ assert(!path.startsWith("storage/"), `runtime storage entered the distribution: ${path}`)
+ assert(!path.startsWith("node_modules/"), `development dependencies entered the distribution: ${path}`)
+ assert(!path.startsWith(".git"), `repository state entered the distribution: ${path}`)
+ }
+
+ mkdirSync(installation)
+ zip.extractAllTo(installation)
+
+ const installedManifest = JSON.parse(readFileSync(join(installation, "package.json"), "utf8"))
+
+ assert.deepEqual(installedManifest.scripts, { start: "node server/main.js" })
+ assert.deepEqual(
+ installedManifest.dependencies,
+ Object.fromEntries(["cfonts", "sharp"].map(name => [name, manifest.dependencies[name]]))
+ )
+
+ execFileSync(
+ npm,
+ ["install", "--omit=dev", "--no-audit", "--no-fund", "--no-package-lock"],
+ { cwd: installation, stdio: "inherit" }
+ )
+
+ execFileSync(process.execPath, ["--check", "server/main.js"], { cwd: installation })
+
+ if (process.env.CI === "true") await boot(installation)
+} finally {
+ if (runtime && runtime.exitCode === null) {
+ runtime.kill()
+ await new Promise(resolve => runtime.once("exit", resolve))
+ }
+
+ rmSync(archive, { force: true })
+ rmSync(checksum, { force: true })
+ rmSync(temporary, { recursive: true, force: true })
+}
+
+async function availablePort() {
+ const server = createServer()
+
+ await new Promise((resolve, reject) => {
+ server.once("error", reject)
+ server.listen(0, "127.0.0.1", resolve)
+ })
+
+ const address = server.address()
+
+ assert(address && typeof address === "object")
+
+ await new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve()))
+
+ return address.port
+}
+
+async function boot(directory) {
+ const port = await availablePort()
+ const output = []
+
+ runtime = spawn(process.execPath, ["server/main.js"], {
+ cwd: directory,
+ env: { ...process.env, [portVariable]: String(port) },
+ stdio: ["ignore", "pipe", "pipe"]
+ })
+
+ runtime.stdout.on("data", data => output.push(data.toString()))
+ runtime.stderr.on("data", data => output.push(data.toString()))
+
+ await waitForDesktop(port, runtime, output)
+}
+
+async function waitForDesktop(port, child, output) {
+ const deadline = Date.now() + 20_000
+ const url = `http://localhost:${port}/`
+
+ while (Date.now() < deadline) {
+ if (child.exitCode !== null) throw new Error(`the installed system exited before serving the desktop\n${output.join("")}`)
+
+ try {
+ const response = await fetch(url)
+ const body = await response.text()
+
+ assert.equal(response.status, 200)
+ assert.match(body, /<html/i)
+
+ return
+ } catch {
+ await new Promise(resolve => setTimeout(resolve, 100))
+ }
+ }
+
+ throw new Error(`the installed system did not serve the desktop\n${output.join("")}`)
+}
diff --git a/source/build.ts b/source/build.ts
new file mode 100644
index 0000000..67c3f36
--- /dev/null
+++ b/source/build.ts
@@ -0,0 +1,25 @@
+import { externalDependencies } from "@/vite.server"
+import { rm, writeFile } from "node:fs/promises"
+import packageConfig from "@/package.json"
+import { build } from "vite"
+
+const dependencies: Partial<typeof packageConfig.dependencies> = {}
+
+await rm("dist", { recursive: true, force: true })
+
+for (const externalDependency of externalDependencies) {
+
+ dependencies[externalDependency] = packageConfig.dependencies[externalDependency]
+}
+
+await build({ configFile: "vite.server.ts" })
+
+await build({ configFile: "vite.client.ts" })
+
+await writeFile("dist/package.json", JSON.stringify({
+ type: "module",
+ scripts: {
+ start: "node server/main.js"
+ },
+ dependencies
+}))
diff --git a/source/client/core/application.ts b/source/client/core/application.ts
new file mode 100644
index 0000000..dd0ff44
--- /dev/null
+++ b/source/client/core/application.ts
@@ -0,0 +1,247 @@
+import ClientLink from "@libs/the-link/plugins/client-link/client-link"
+import { type ProxyOutcome, type ProxyRequest, type ProxyResponse, proxyMediaType } from "@server/core/protocol/proxy"
+import { storageMediaType, type StorageRequest } from "@server/core/protocol/storage"
+import { frame, frameBlob, unframe } from "@libs/framing"
+import superjson from "@libs/superjson"
+import LZString from "lz-string"
+
+export default class Application {
+
+ public readonly name: string
+
+ public readonly displayName: string
+
+ public readonly version: string
+
+ public readonly doors: Doors
+
+ public readonly clientLink: ClientLink
+
+ public constructor(name: string, displayName: string, version: string, doors: Doors) {
+
+ this.name = name
+
+ this.displayName = displayName
+
+ this.version = version
+
+ this.doors = doors
+
+ this.clientLink = new ClientLink(this.doors.link)
+
+ this.clientLink.setSerialize(data => LZString.compressToBase64(superjson.stringify(data)))
+
+ this.clientLink.setDeserialize(data => superjson.parse(LZString.decompressFromBase64(data)))
+ }
+
+ // A finite browser body keeps its length, so HTTP/1 can stream it from its
+ // native backing store. A genuinely open stream is staged by `post` below:
+ // browsers refuse unknown-length streaming requests over HTTP/1 before the
+ // server ever sees them. Authorization belongs to the desktop and is added
+ // here, never exposed to the pane.
+ public async serve(content: ClientBody, description: ServedValue, authorization: string, signal?: AbortSignal): Promise<ServedFile> {
+
+ const headers: Record<string, string> = {
+
+ authorization,
+
+ "content-disposition": `attachment; filename="value.${description.extension}"`,
+
+ "content-type": description.type
+ }
+
+ const response = await this.post(this.doors.uploads, content, headers, signal)
+
+ if (!response.ok) throw new Error(await response.text())
+
+ return await response.json()
+ }
+
+ /** Carry an unrestricted request through the desktop's authorized proxy. */
+ public async proxy(request: ProxyRequest, body: ClientBody | null, authorization: string, signal?: AbortSignal): Promise<ProxiedResponse> {
+
+ const response = await this.post(
+
+ this.doors.proxy,
+
+ framedBody(request, body),
+
+ {
+
+ authorization,
+
+ "content-type": proxyMediaType
+ },
+
+ signal
+ )
+
+ if (!response.ok) throw new Error(await response.text())
+
+ const framed = await unframe<ProxyOutcome>(response.body)
+
+ if ("error" in framed.metadata) {
+
+ await framed.body.cancel().catch(() => undefined)
+
+ const exception = new Error(framed.metadata.error.message)
+
+ exception.name = framed.metadata.error.name
+
+ throw exception
+ }
+
+ if (!framed.metadata.response.body) await framed.body.cancel().catch(() => undefined)
+
+ return {
+
+ ...framed.metadata.response,
+
+ body: framed.metadata.response.body ? framed.body : null
+ }
+ }
+
+ public async storageStream(request: Omit<StorageRequest, "operation">, authorization: string, signal?: AbortSignal) {
+
+ const response = await this.storage({ ...request, operation: "stream" }, null, authorization, signal)
+
+ if (!response.body) throw new Error("The storage response has no body")
+
+ return response.body
+ }
+
+ public async storageWrite(request: Omit<StorageRequest, "operation">, body: ClientBody, authorization: string, signal?: AbortSignal) {
+
+ await this.storage({ ...request, operation: "write" }, body, authorization, signal)
+ }
+
+ private async storage(request: StorageRequest, body: ClientBody | null, authorization: string, signal?: AbortSignal) {
+
+ const response = await this.post(
+
+ this.doors.storage,
+
+ framedBody(request, body),
+
+ {
+
+ authorization,
+
+ "content-type": storageMediaType
+ },
+
+ signal
+ )
+
+ if (!response.ok) throw new Error(await response.text())
+
+ return response
+ }
+
+ private async post(url: string, source: ClientBody, headers: HeadersInit, signal?: AbortSignal) {
+
+ const prepared = await finite(source, signal)
+
+ try {
+
+ return await fetch(url, { method: "POST", headers, body: prepared.body, signal })
+ }
+
+ finally { await prepared.remove() }
+ }
+}
+
+function framedBody<Metadata>(metadata: Metadata, body: ClientBody | null) {
+
+ return body instanceof ReadableStream ? frame(metadata, body) : frameBlob(metadata, body)
+}
+
+async function finite(source: ClientBody, signal?: AbortSignal): Promise<PreparedBody> {
+
+ if (source instanceof Blob) return { body: source, remove: async () => undefined }
+
+ const storage = navigator.storage as (StorageManager & { getDirectory?: () => Promise<FileSystemDirectoryHandle> }) | undefined
+
+ // Origin-private storage keeps an unknown stream off the JavaScript heap
+ // while giving fetch a finite File whose length HTTP/1 can carry.
+ if (storage?.getDirectory) {
+
+ const root = await storage.getDirectory()
+
+ const name = `.request-${crypto.randomUUID()}`
+
+ try {
+
+ const handle = await root.getFileHandle(name, { create: true })
+
+ await source.pipeTo(await handle.createWritable(), { signal })
+
+ return {
+
+ body: await handle.getFile(),
+
+ remove: () => root.removeEntry(name).catch(() => undefined)
+ }
+ }
+
+ catch (exception) {
+
+ await root.removeEntry(name).catch(() => undefined)
+
+ throw exception
+ }
+ }
+
+ // Older engines may not expose origin-private files. A Blob still gives
+ // the request a known length and preserves behavior, though the engine
+ // chooses whether its backing store is memory or disk. Pipe explicitly so
+ // aborting also cancels an open source instead of leaving staging pending.
+ const chunks: BlobPart[] = []
+
+ await source.pipeTo(new WritableStream({ write: chunk => { chunks.push(new Uint8Array(chunk)) } }), { signal })
+
+ return { body: new Blob(chunks), remove: async () => undefined }
+}
+
+export type ProxiedResponse = Omit<ProxyResponse, "body"> & { body: ReadableStream<Uint8Array> | null }
+
+export type ClientBody = Blob | ReadableStream<Uint8Array>
+
+interface PreparedBody {
+
+ body: Blob
+
+ remove: () => Promise<void>
+}
+
+export interface ServedFile {
+
+ file: string
+
+ type: string | null
+
+ size: number
+
+ time: number
+}
+
+export interface ServedValue {
+
+ extension: string
+
+ type: string
+}
+
+/** Server-view doors required by the client core transport. */
+export interface Doors {
+
+ link: string
+
+ proxy: string
+
+ storage: string
+
+ uploads: string
+
+ program: string
+}
diff --git a/source/client/core/link-manager/auth-manager/auth-manager.ts b/source/client/core/link-manager/auth-manager/auth-manager.ts
new file mode 100644
index 0000000..e38eaf4
--- /dev/null
+++ b/source/client/core/link-manager/auth-manager/auth-manager.ts
@@ -0,0 +1,83 @@
+import { TransmittedAuthManager } from "@server/core/link-manager/auth-manager/auth-manager"
+import { Intercept } from "@libs/the-link/decorators/escript"
+import ProcessManager from "./process-manager/process-manager"
+import ProgramManager from "./program-manager/program-manager"
+import DialogManager from "./dialog-manager"
+import TheLink from "@libs/the-link/the-link"
+import LinkManager from "../link-manager"
+import { type PermissionDecision, type PermissionName, type ThemeProperties } from "@phreshos/core"
+
+export default class AuthManager extends TheLink {
+
+ public readonly linkManager: LinkManager
+
+ public readonly authorization: string
+
+ public readonly programManager: ProgramManager
+
+ public readonly processManager: ProcessManager
+
+ public readonly dialogManager: DialogManager
+
+ public constructor(linkManager: LinkManager, authorization: string, payload: TransmittedAuthManager) {
+
+ super()
+
+ this.linkManager = linkManager
+
+ this.authorization = authorization
+
+ this.connectTo(this.linkManager, "/auth")
+
+ this.programManager = new ProgramManager(this, payload.programManager)
+
+ this.processManager = new ProcessManager(this, payload.processManager)
+
+ this.dialogManager = new DialogManager(this, payload.dialogManager)
+ }
+
+ @Intercept("outbound")
+ protected authenticate(...values: unknown[]) {
+
+ return [this.authorization, ...values]
+ }
+
+ /** Emit one authorized private fact without creating a response path. */
+ public emit(event: string, ...values: unknown[]) {
+
+ this.linkManager.emitToSession(`/auth${event}`, this.authorization, ...values)
+ }
+
+ /** Replace the authoritative system Theme. */
+ public async updateTheme(theme: ThemeProperties) {
+
+ await this.$outbound.publish("/theme", theme)
+ }
+
+ /** Reads one effective permission for the structurally identified Process. */
+ public async permissionGranted(process: string, permission: PermissionName): Promise<PermissionDecision> {
+
+ return await this.$outbound.publishFirst("/permission/granted", process, permission) as PermissionDecision
+ }
+
+ /** Requests one permission until the iframe boundary cancels or authority decides. */
+ public async requestPermission(process: string, permission: PermissionName, signal: AbortSignal): Promise<PermissionDecision> {
+
+ const request = crypto.randomUUID()
+
+ const cancel = () => { this.$outbound.publish("/permission/cancel", request, process).catch(() => undefined) }
+
+ if (signal.aborted) return null
+
+ signal.addEventListener("abort", cancel, { once: true })
+
+ try { return await this.$outbound.publishFirst("/permission/request", request, process, permission) as PermissionDecision }
+
+ finally { signal.removeEventListener("abort", cancel) }
+ }
+
+ public disconnect() {
+
+ this.disconnectFrom(this.linkManager, "/auth")
+ }
+}
diff --git a/source/client/core/link-manager/auth-manager/dialog-manager.ts b/source/client/core/link-manager/auth-manager/dialog-manager.ts
new file mode 100644
index 0000000..f6f8b39
--- /dev/null
+++ b/source/client/core/link-manager/auth-manager/dialog-manager.ts
@@ -0,0 +1,60 @@
+import { type PermissionChoice, type SystemDialog, type TransmittedDialogManager } from "@server/core/dialog-manager"
+import { Publish, Subscribe } from "@libs/the-link/decorators/escript"
+import TheLink from "@libs/the-link/the-link"
+import AuthManager from "./auth-manager"
+
+/** Synchronized desktop counterpart of the authoritative system-dialog queue. */
+export default class DialogManager extends TheLink {
+
+ public readonly authManager: AuthManager
+
+ public readonly dialogs: Map<string, SystemDialog>
+
+ public constructor(authManager: AuthManager, payload: TransmittedDialogManager) {
+
+ super()
+
+ this.authManager = authManager
+
+ this.dialogs = new Map(payload.dialogs)
+
+ this.connectTo(this.authManager, "/dialog")
+ }
+
+ public list() {
+
+ return [...this.dialogs.values()]
+ }
+
+ public async acknowledge(identity: string) {
+
+ await this.$outbound.publish("/acknowledge", identity)
+ }
+
+ public async resolvePermission(identity: string, choice: PermissionChoice) {
+
+ await this.$outbound.publish("/resolve-permission", identity, choice)
+ }
+
+ @Subscribe("/created")
+ @Publish("/dialogs", "inbound")
+ protected async created(dialog: SystemDialog | null) {
+
+ if (!dialog) return
+
+ this.dialogs.set(dialog.identity, dialog)
+
+ return this.list()
+ }
+
+ @Subscribe("/removed")
+ @Publish("/dialogs", "inbound")
+ protected async removed(identity: string | null) {
+
+ if (!identity) return
+
+ this.dialogs.delete(identity)
+
+ return this.list()
+ }
+}
diff --git a/source/client/core/link-manager/auth-manager/process-manager/client-state.ts b/source/client/core/link-manager/auth-manager/process-manager/client-state.ts
new file mode 100644
index 0000000..de9007e
--- /dev/null
+++ b/source/client/core/link-manager/auth-manager/process-manager/client-state.ts
@@ -0,0 +1,14 @@
+import { type TransmittedProcess } from "@server/core/link-manager/auth-manager/process-manager/process"
+import ProcessManager from "./process-manager"
+import Window from "./window"
+
+/** One desktop counterpart of the server-authoritative client state. */
+export default class ClientState {
+
+ public readonly window: Window
+
+ public constructor(processManager: ProcessManager, process: string, payload: NonNullable<TransmittedProcess["client"]>) {
+
+ this.window = new Window(processManager, process, payload.window)
+ }
+}
diff --git a/source/client/core/link-manager/auth-manager/process-manager/process-manager.ts b/source/client/core/link-manager/auth-manager/process-manager/process-manager.ts
new file mode 100644
index 0000000..63c79dc
--- /dev/null
+++ b/source/client/core/link-manager/auth-manager/process-manager/process-manager.ts
@@ -0,0 +1,298 @@
+import { TransmittedProcessManager } from "@server/core/link-manager/auth-manager/process-manager/process-manager"
+import { TransmittedProcess } from "@server/core/link-manager/auth-manager/process-manager/process"
+import { TransmittedWindow } from "@server/core/link-manager/auth-manager/process-manager/window"
+import { Publish, Subscribe } from "@libs/the-link/decorators/escript"
+import TheLink from "@libs/the-link/the-link"
+import AuthManager from "../auth-manager"
+import Process from "./process"
+import { type LaunchClient } from "@server/core/link-manager/auth-manager/program-manager/program-manager"
+import { type TrafficKind } from "@server/core/link-manager/auth-manager/process-manager/process-traffic"
+import { isPermissionName } from "@phreshos/core"
+
+/**
+ * The peer of the core's processes: born holding them from the
+ * transmitted payload, and following every echo. Each process is one
+ * long-lived instance for its whole life — echoes mutate it in place, so
+ * a window keeps the element it was mounted on.
+ *
+ * After every change the derived list is re-emitted on this tunnel:
+ * notification is the link, and a representation subscribes to the event
+ * rather than to the object.
+ */
+export default class ProcessManager extends TheLink {
+
+ public readonly authManager: AuthManager
+
+ public readonly processes = new Map<string, Process>()
+
+ public constructor(authManager: AuthManager, payload: TransmittedProcessManager) {
+
+ super()
+
+ this.authManager = authManager
+
+ for (const [identity, process] of payload.processes) this.processes.set(identity, new Process(this, process))
+
+ this.connectTo(this.authManager, "/process")
+ }
+
+ private list() {
+
+ return [...this.processes.values()]
+ }
+
+ // The structural frame gate supplies `source`; Program code supplies only
+ // the target and payload.
+ public async publish(source: string, identity: string, which: "server" | "client", values: unknown[]) {
+
+ await this.$outbound.publish("/send", source, identity, which, values)
+ }
+
+ /** Emit outward from the structurally identified Client Endpoint. */
+ public async emit(source: string, event: string, payload: unknown) {
+
+ await this.$outbound.publish("/emit", source, event, payload)
+ }
+
+ // Handed on, not awaited. Whoever asked is holding the question by
+ // its own name and will recognise the answer when it arrives.
+ public async askOf(source: string, identity: string, values: unknown[]) {
+
+ await this.$outbound.publish("/frame/ask", source, identity, values)
+ }
+
+ public async cancel(source: string, question: string) {
+
+ await this.$outbound.publish("/frame/cancel", source, question)
+ }
+
+ // A frame document owns its forwarding interests. The opaque owner is
+ // minted by this desktop session; the server adds the session from the
+ // connection itself, so neither coordinate comes from program code.
+ public async ownFrame(pane: string, owner: string) {
+
+ await this.$outbound.publish("/frame/own", pane, owner)
+ }
+
+ public async releaseFrame(pane: string, owner: string) {
+
+ await this.$outbound.publish("/frame/release", pane, owner)
+ }
+
+ /** Register one live Channel interest for this exact frame document. */
+ public subscribeFrame(pane: string, owner: string, subscription: string, kind: TrafficKind, event: string | null) {
+
+ return this.$outbound.publish("/frame/subscribe", pane, owner, subscription, kind, event)
+ }
+
+ public unsubscribeFrame(pane: string, owner: string, subscription: string) {
+
+ return this.$outbound.publish("/frame/unsubscribe", pane, owner, subscription)
+ }
+
+ public async observe(pane: string, owner: string, subscription: string, target: HandleAddress, half: "server" | "client", kind: TrafficKind, event: string | null, reportImpossible: boolean) {
+
+ await this.$outbound.publish("/frame/observe", pane, owner, subscription, target, half, kind, event, reportImpossible)
+ }
+
+ public async unobserve(pane: string, owner: string, subscription: string) {
+
+ await this.$outbound.publish("/frame/unobserve", pane, owner, subscription)
+ }
+
+ public async follow(pane: string, owner: string, subscription: string, target: HandleAddress, half: "server" | "client", event: string | null, reportImpossible: boolean) {
+
+ await this.$outbound.publish("/frame/follow", pane, owner, subscription, target, half, event, reportImpossible)
+ }
+
+ public async unfollow(pane: string, owner: string, subscription: string) {
+
+ await this.$outbound.publish("/frame/unfollow", pane, owner, subscription)
+ }
+
+ // Private endpoint output. This deliberately bypasses the ordinary
+ // request/response forwarding road: logs have no answer and no failure.
+ public log(pane: string, kind: string, content: string) {
+
+ this.authManager.emit("/process/frame/log", pane, kind, content)
+ }
+
+ public async exitAll(program: string, asker: string) {
+
+ return await this.$outbound.publishFirst("/exit-all", program, asker) as string[]
+ }
+
+ public async startEndpoint(identity: string, which: "server" | "client", overrides?: LaunchClient) {
+
+ await this.$outbound.publish("/endpoint/start", identity, which, overrides)
+ }
+
+ public async stopEndpoint(identity: string, which: "server" | "client") {
+
+ await this.$outbound.publish("/endpoint/stop", identity, which)
+ }
+
+ @Subscribe("/permission")
+ protected async permissionChanged(identity: unknown, permission: unknown, decision: unknown) {
+
+ if (typeof identity !== "string" || !isPermissionName(permission) || (decision !== true && decision !== false && decision !== null)) return
+
+ await this.$inbound.publish("/permission-changed", identity, permission, decision)
+ }
+
+ /** Announces a locally changed counterpart to desktop representations. */
+ public async changed() {
+
+ await this.$inbound.publish("/processes", this.list())
+ }
+
+ // Any window change arrives in one shape: the process it belongs to,
+ // and the window whole.
+ private followed(payload: { identity: string, window: TransmittedWindow } | null, surfaceChanged = false) {
+
+ if (!payload) return
+
+ this.processes.get(payload.identity)?.client?.window.follow(payload.window, surfaceChanged)
+
+ return this.list()
+ }
+
+ @Subscribe("/created")
+ @Publish("/processes", "inbound")
+ protected async createdHandle(payload: TransmittedProcess | null) {
+
+ if (!payload) return
+
+ this.processes.set(payload.identity, new Process(this, payload))
+
+ return this.list()
+ }
+
+ // A child's runtime reached its kit. Reflected onto the record so a
+ // session's copy is as true as the host's, and offered to that
+ // program's panes so a window can wait for its own half.
+ @Subscribe("/server-ready")
+ @Publish("/processes", "inbound")
+ protected async serverReadyHandle(identity: string | null) {
+
+ if (!identity) return
+
+ const process = this.processes.get(identity)
+
+ if (!process) return
+
+ if (process.server) process.server.ready = true
+
+ return this.list()
+ }
+
+ @Subscribe("/server-start")
+ @Publish("/processes", "inbound")
+ protected async serverStartHandle(identity: string | null, _payload: TransmittedProcess | null) {
+
+ if (!identity) return
+
+ this.processes.get(identity)?.serverStarted()
+
+ return this.list()
+ }
+
+ @Subscribe("/server-stop")
+ @Publish("/processes", "inbound")
+ protected async serverStopHandle(identity: string | null, _payload: TransmittedProcess | null) {
+
+ if (!identity) return
+
+ this.processes.get(identity)?.serverStopped()
+
+ return this.list()
+ }
+
+ @Subscribe("/client-start")
+ @Publish("/processes", "inbound")
+ protected async clientStartHandle(identity: string | null, payload: TransmittedProcess | null) {
+
+ if (!identity || !payload) return
+
+ this.processes.get(identity)?.clientStarted(payload)
+
+ return this.list()
+ }
+
+ @Subscribe("/client-stop")
+ @Publish("/processes", "inbound")
+ protected async clientStopHandle(identity: string | null, _payload: TransmittedProcess | null) {
+
+ if (!identity) return
+
+ this.processes.get(identity)?.clientStopped()
+
+ return this.list()
+ }
+
+ @Subscribe("/exited")
+ @Publish("/processes", "inbound")
+ protected async exitedHandle(payload: TransmittedProcess | null) {
+
+ if (!payload) return
+
+ this.processes.delete(payload.identity)
+
+ return this.list()
+ }
+
+ @Subscribe("/move")
+ @Publish("/processes", "inbound")
+ protected async moveHandle(payload: { identity: string, window: TransmittedWindow } | null) {
+
+ return this.followed(payload)
+ }
+
+ @Subscribe("/resize")
+ @Publish("/processes", "inbound")
+ protected async resizeHandle(payload: { identity: string, window: TransmittedWindow } | null) {
+
+ return this.followed(payload)
+ }
+
+ @Subscribe("/raise")
+ @Publish("/processes", "inbound")
+ protected async raiseHandle(payload: { identity: string, window: TransmittedWindow } | null) {
+
+ return this.followed(payload)
+ }
+
+ @Subscribe("/change-title")
+ @Publish("/processes", "inbound")
+ protected async changeTitleHandle(payload: { identity: string, window: TransmittedWindow } | null) {
+
+ return this.followed(payload)
+ }
+
+ @Subscribe("/minimize")
+ @Publish("/processes", "inbound")
+ protected async minimizeHandle(payload: { identity: string, window: TransmittedWindow } | null) {
+
+ return this.followed(payload)
+ }
+
+ @Subscribe("/surface")
+ @Publish("/processes", "inbound")
+ protected async surfaceHandle(payload: { identity: string, window: TransmittedWindow } | null) {
+
+ return this.followed(payload, true)
+ }
+
+ @Subscribe("/end-end")
+ protected async endEndHandle(identity: string, json: string) {
+
+ this.$inbound.publish("/pane", identity, json).catch(() => undefined)
+ }
+}
+
+interface HandleAddress {
+
+ identity: string
+
+ reference: string
+}
diff --git a/source/client/core/link-manager/auth-manager/process-manager/process.ts b/source/client/core/link-manager/auth-manager/process-manager/process.ts
new file mode 100644
index 0000000..2c2fe2d
--- /dev/null
+++ b/source/client/core/link-manager/auth-manager/process-manager/process.ts
@@ -0,0 +1,119 @@
+import { TransmittedProcess } from "@server/core/link-manager/auth-manager/process-manager/process"
+import ProcessManager from "./process-manager"
+import ClientState from "./client-state"
+
+/**
+ * A running instance, as this side holds it: rebuilt from what the core
+ * transmitted. Its client state owns the Window counterpart while that state
+ * is live. Every act is a request; the truth answers with an echo.
+ */
+export default class Process {
+
+ public readonly processManager: ProcessManager
+
+ public readonly identity: string
+
+ /** Opaque identity of this one Process entity. */
+ public readonly reference: string
+
+ public readonly name: string | null
+
+ public readonly program: string
+
+ // Private hosting address from the trusted core payload. It never
+ // crosses into a framed program's SDK record.
+ public readonly assetId: string
+
+ // A real date on this side: the link carries dates rather than
+ // stringifying them.
+ public readonly startedAt: Date
+
+ // Current live endpoint state mirrored from the authoritative host.
+ public server: { ready: boolean } | null
+
+ public client: ClientState | null
+
+ // Retained only as an address. The pane gate verifies that the parent is
+ // still live before an SDK handle may resolve it.
+ public readonly parent: ProcessRecord | null
+
+ // What its launch said, carried for its whole life.
+ public readonly options: Record<string, string>
+
+ public constructor(processManager: ProcessManager, payload: TransmittedProcess) {
+
+ this.processManager = processManager
+
+ this.identity = payload.identity
+
+ this.reference = payload.reference
+
+ this.name = payload.name
+
+ this.program = payload.program
+
+ this.assetId = payload.assetId
+
+ this.startedAt = payload.startedAt
+
+ this.server = payload.server
+
+ this.client = payload.client ? new ClientState(processManager, payload.identity, payload.client) : null
+
+ this.parent = payload.parent
+
+ this.options = payload.options
+
+ }
+
+ // Ending is asked for; the process leaves when its exit echoes.
+ public async stop() {
+
+ await this.processManager.$outbound.publish("/stop", this.identity)
+ }
+
+ // The program's own words, to its other half.
+ public async endEnd(...args: unknown[]) {
+
+ await this.processManager.$outbound.publish("/frame/end-end", this.identity, JSON.stringify(args))
+ }
+
+ public serverStarted() {
+
+ this.server = { ready: false }
+ }
+
+ public serverStopped() {
+
+ this.server = null
+ }
+
+ public clientStarted(payload: TransmittedProcess) {
+
+ if (payload.client) this.client = new ClientState(this.processManager, this.identity, payload.client)
+ }
+
+ public clientStopped() {
+
+ this.client = null
+ }
+}
+
+export interface ProcessRecord {
+
+ readonly reference: string
+
+ readonly identity: string
+
+ readonly name: string | null
+
+ readonly program: string
+
+ readonly options: Record<string, string>
+
+ readonly startedAt: Date
+
+ readonly server: Record<string, never> | null
+
+ readonly client: Record<string, never> | null
+}
diff --git a/source/client/core/link-manager/auth-manager/process-manager/window.ts b/source/client/core/link-manager/auth-manager/process-manager/window.ts
new file mode 100644
index 0000000..fd6b124
--- /dev/null
+++ b/source/client/core/link-manager/auth-manager/process-manager/window.ts
@@ -0,0 +1,168 @@
+import { type TransmittedWindow, type Position, type Size } from "@server/core/link-manager/auth-manager/process-manager/window"
+import { isRelativeValue, type WindowLayer, type WindowSurfaceSettings } from "@phreshos/core"
+import ProcessManager from "./process-manager"
+
+/**
+ * How a process is shown, as this side holds it. The values are the core's
+ * own — pixels or linear expressions of relative and pixel terms — and every
+ * operation is a request: the truth changes on the server and the echo lands
+ * back here, so a window never moves because a session wished it.
+ *
+ * Its own instance, rebuilt from what crossed. It shares no code with
+ * the core's window; they are alike because they are the same idea.
+ */
+export default class Window {
+
+ public readonly processManager: ProcessManager
+
+ public readonly process: string
+
+ public position: Position
+
+ public size: Size
+
+ public depth: number
+
+ public minimized: boolean
+
+ // Authoritative host material echoed from the server. The revision is
+ // desktop-local delivery knowledge: zero marks an initial snapshot, while
+ // later values let rendering animate only live changes.
+ public surface: WindowSurfaceSettings | null
+
+ public surfaceRevision = 0
+
+ // What is shown on it, born from its program when the window was
+ // made. Not looked up again: how a thing is shown is not a fact
+ // about whether its program is installed. Changeable, because the
+ // window owns it.
+ public title: string
+
+ public url: string | null
+
+ // The authoritative runtime layer, including the system-only wallpaper.
+ public layer: WindowLayer
+
+ // Which of the half's own pages the frame opens on.
+ public location: string
+
+ public constructor(processManager: ProcessManager, process: string, payload: TransmittedWindow) {
+
+ this.title = payload.title
+
+ this.layer = payload.layer
+
+ this.location = payload.location
+
+ this.url = payload.url
+
+ this.processManager = processManager
+
+ this.process = process
+
+ this.position = payload.position
+
+ this.size = payload.size
+
+ this.depth = payload.depth
+
+ this.minimized = payload.minimized
+
+ this.surface = payload.surface
+ }
+
+ // What the echo carries, applied whole: one shape for any change.
+ public follow(payload: TransmittedWindow, surfaceChanged = false) {
+
+ this.title = payload.title
+
+ this.url = payload.url
+
+ this.layer = payload.layer
+
+ this.location = payload.location
+
+ this.position = payload.position
+
+ this.size = payload.size
+
+ this.depth = payload.depth
+
+ this.minimized = payload.minimized
+
+ if (surfaceChanged) {
+
+ this.surface = payload.surface
+
+ this.surfaceRevision += 1
+ }
+ }
+
+ // A local geometry change is a draft held by this desktop. It redraws
+ // through ProcessManager but says nothing through `$outbound`; the normal
+ // move and resize methods remain the only roads to the authoritative host.
+ public localMove(position: Position) {
+
+ validate(position.x, "x")
+
+ validate(position.y, "y")
+
+ this.position = position
+ }
+
+ public localResize(size: Size) {
+
+ validate(size.width, "width")
+
+ validate(size.height, "height")
+
+ this.size = size
+ }
+
+ public async setSurface(settings: WindowSurfaceSettings) {
+
+ await this.processManager.$outbound.publish("/surface", this.process, settings)
+ }
+
+ public async removeSurface() {
+
+ await this.processManager.$outbound.publish("/surface", this.process, null)
+ }
+
+ public async move(position: Position) {
+
+ await this.processManager.$outbound.publish("/move", this.process, position)
+ }
+
+ public async resize(size: Size) {
+
+ await this.processManager.$outbound.publish("/resize", this.process, size)
+ }
+
+ public async changeTitle(title: string) {
+
+ await this.processManager.$outbound.publish("/change-title", this.process, title)
+ }
+
+ // To the front of its own layer, and nothing else. A hidden window
+ // raised stays hidden and appears at its new place in the order when
+ // it is shown.
+ public async raise() {
+
+ await this.processManager.$outbound.publish("/raise", this.process)
+ }
+
+ public async minimize(minimized: boolean) {
+
+ await this.processManager.$outbound.publish("/minimize", this.process, minimized)
+ }
+}
+
+function validate(value: number | string, name: string) {
+
+ if (isRelativeValue(value)) return
+
+ throw new Error(`${name} must be a finite pixel number or a relative expression such as "50% + 10"`)
+}
+
+export type { Position, Size }
diff --git a/source/client/core/link-manager/auth-manager/program-manager/program-manager.ts b/source/client/core/link-manager/auth-manager/program-manager/program-manager.ts
new file mode 100644
index 0000000..b10652d
--- /dev/null
+++ b/source/client/core/link-manager/auth-manager/program-manager/program-manager.ts
@@ -0,0 +1,143 @@
+import { Launch, TransmittedProgramManager } from "@server/core/link-manager/auth-manager/program-manager/program-manager"
+import { HostedEntry } from "@server/core/link-manager/auth-manager/program-manager/entry"
+import { Publish, Subscribe } from "@libs/the-link/decorators/escript"
+import TheLink from "@libs/the-link/the-link"
+import AuthManager from "../auth-manager"
+import Program from "./program"
+import { type ProgramIconSize } from "@phreshos/core"
+
+/**
+ * The peer of the core's programs: born holding them from the
+ * transmitted payload, following what arrives and what is forgotten,
+ * and re-emitting the derived list on its own tunnel.
+ *
+ * Keyed by the program's public identity. A display name addresses
+ * nothing and may be shared.
+ *
+ * The trusted desktop may install, uninstall, or forget a Program only
+ * after deriving that Program from a frame. These methods take the
+ * already-resolved subject; no client-provided identity is forwarded.
+ */
+export default class ProgramManager extends TheLink {
+
+ public readonly authManager: AuthManager
+
+ public readonly programs = new Map<string, Program>()
+
+ public constructor(authManager: AuthManager, payload: TransmittedProgramManager) {
+
+ super()
+
+ this.authManager = authManager
+
+ for (const [identity, entry] of payload.programs) this.programs.set(identity, new Program(this, entry))
+
+ this.connectTo(this.authManager, "/program")
+ }
+
+ // A store's five controls, asked of the core. The desktop answers a
+ // pane's store words with this, so a client half means the same
+ // thing by them as a server half does — one implementation, two
+ // roads to it.
+ public async store(identity: string, operation: string, key: string, value?: unknown, ttl?: number) {
+
+ return await this.$outbound.publishFirst("/store", identity, operation, key, value, ttl)
+ }
+
+ // Another instance of a program. Which program is the desktop's to
+ // decide before it asks — from the frame, for a pane; from the list,
+ // for its own controls.
+ public async createProcess(identity: string, launch: Launch = {}, parent?: string) {
+
+ return await this.$outbound.publishFirst("/create-process", identity, launch, parent) as string
+ }
+
+ public async install(identity: string, asker: string) {
+
+ return await this.$outbound.publishFirst("/install-program", identity, asker)
+ }
+
+ public async uninstall(identity: string, everything: boolean, asker: string) {
+
+ return await this.$outbound.publishFirst("/uninstall-program", identity, everything, asker)
+ }
+
+ public async forget(identity: string, asker: string) {
+
+ return await this.$outbound.publishFirst("/forget-program", identity, asker)
+ }
+
+ // One of a Program's metadata operations, asked of the core. Byte
+ // content takes the storage door instead of the serialized link.
+ public async area(identity: string, area: "data" | "cache", operation: string, args: unknown[]) {
+
+ return await this.$outbound.publishFirst("/area", identity, area, operation, args)
+ }
+
+ // What a program has said, asked of the core. Read-only there, so
+ // nothing on this side has to decide what a query means.
+ public async logs(identity: string, sql: string, values: unknown[]) {
+
+ return await this.$outbound.publishFirst("/logs", identity, sql, values)
+ }
+
+ // A program's own database, asked of the core.
+ public async database(identity: string, sql: string, values: unknown[]) {
+
+ return await this.$outbound.publishFirst("/database", identity, sql, values)
+ }
+
+ // Requested on demand rather than carried in the desktop's incomplete
+ // Program record. The server remains authoritative for the document.
+ public async apiDocs(identity: string) {
+
+ return await this.$outbound.publishFirst("/api-docs", identity) as string | null
+ }
+
+ /** Request one rendered icon from the authoritative server Program. */
+ public async icon(identity: string, size: ProgramIconSize) {
+
+ return await this.$outbound.publishFirst("/icon", identity, size) as number[]
+ }
+
+ @Subscribe("/install")
+ @Publish("/programs", "inbound")
+ protected async installed(payload: HostedEntry | null) {
+
+ return this.arrived(payload)
+ }
+
+ private arrived(payload: HostedEntry | null) {
+
+ if (!payload) return
+
+ this.programs.set(payload.identity, new Program(this, payload))
+
+ return [...this.programs.values()]
+ }
+
+ @Subscribe("/create")
+ @Publish("/programs", "inbound")
+ protected async created(payload: HostedEntry | null) {
+
+ return this.arrived(payload)
+ }
+
+ @Subscribe("/uninstall")
+ @Publish("/programs", "inbound")
+ protected async uninstalled(payload: HostedEntry | null) {
+
+ return this.arrived(payload)
+ }
+
+ @Subscribe("/forget")
+ @Publish("/programs", "inbound")
+ protected async forgotten(identity: string | null) {
+
+ if (!identity) return
+
+ this.programs.delete(identity)
+
+ return [...this.programs.values()]
+ }
+}
diff --git a/source/client/core/link-manager/auth-manager/program-manager/program.ts b/source/client/core/link-manager/auth-manager/program-manager/program.ts
new file mode 100644
index 0000000..e2d84dc
--- /dev/null
+++ b/source/client/core/link-manager/auth-manager/program-manager/program.ts
@@ -0,0 +1,80 @@
+import { HostedEntry } from "@server/core/link-manager/auth-manager/program-manager/entry"
+import { Launch } from "@server/core/link-manager/auth-manager/program-manager/program-manager"
+import ProgramManager from "./program-manager"
+
+/**
+ * A program this session knows about, rebuilt from what the core
+ * transmitted. What it holds is what a program says of itself and what
+ * is needed to draw it — never a path, because this side has no disk
+ * and where the machine put things is not a program's own word.
+ *
+ * Running it is a request; the process appears when its start echoes.
+ */
+export default class Program {
+
+ public readonly programManager: ProgramManager
+
+ public readonly identity: string
+
+ /** Opaque identity of this runtime Program entity. */
+ public readonly reference: string
+
+ public readonly installed: boolean
+
+ public readonly assetId: string
+
+ public readonly name: string
+
+ public readonly version: string | null
+
+ public readonly description: string | null
+
+ public readonly server: HostedEntry["server"]
+
+ public readonly client: HostedEntry["client"]
+
+ public constructor(programManager: ProgramManager, payload: HostedEntry) {
+
+ this.programManager = programManager
+
+ this.identity = payload.identity
+
+ this.reference = payload.reference
+
+ this.installed = payload.installed
+
+ this.assetId = payload.assetId
+
+ this.name = payload.name
+
+ this.version = payload.version
+
+ this.description = payload.description
+
+ this.server = payload.server
+
+ this.client = payload.client
+ }
+
+ public async createProcess(launch: Launch = {}) {
+
+ await this.programManager.$outbound.publish("/create-process", this.identity, launch)
+ }
+
+ public async install(asker: string) {
+
+ await this.programManager.install(this.identity, asker)
+ }
+
+ // False removes only installed program files. True removes everything
+ // owned by the system and forgets the runtime Program.
+ public async uninstall(everything = false, asker = "") {
+
+ await this.programManager.uninstall(this.identity, everything, asker)
+ }
+
+ public async forget(asker: string) {
+
+ await this.programManager.forget(this.identity, asker)
+ }
+}
diff --git a/source/client/core/link-manager/link-manager.ts b/source/client/core/link-manager/link-manager.ts
new file mode 100644
index 0000000..406dfb0
--- /dev/null
+++ b/source/client/core/link-manager/link-manager.ts
@@ -0,0 +1,87 @@
+import { TransmittedAuthManager } from "@server/core/link-manager/auth-manager/auth-manager"
+import { TransmittedLinkManager } from "@server/core/link-manager/link-manager"
+import { type AuthenticationState } from "@server/core/authentication/authentication"
+import { type RegistrationResponse } from "@server/core/link-manager/link-manager"
+import { type ThemeProperties } from "@phreshos/core"
+import { Forward } from "@libs/the-link/decorators/escript"
+import TheLink from "@libs/the-link/the-link"
+import Property from "@libs/the-link/property"
+import Application from "../application"
+import { v4 as uuidv4 } from "uuid"
+import { type Outcome, unwrap } from "@server/core/outcome"
+
+export default class LinkManager extends TheLink {
+
+ public readonly application: Application
+
+ public readonly sourceLink: TheLink
+
+ public readonly connectionIdentity: string
+
+ /** Immediate public Theme value and its future synchronized updates. */
+ public readonly theme: Property<ThemeProperties>
+
+ /** Immediate public sign-in wallpaper filename and future updates. */
+ public readonly signInWallpaper: Property<string | null>
+
+ /** Immediate public desktop file wallpaper and future updates. */
+ public readonly desktopWallpaper: Property<string | null>
+
+ public constructor(application: Application, sourceLink: TheLink, payload: TransmittedLinkManager, connectionIdentity: string) {
+
+ super()
+
+ this.application = application
+
+ this.sourceLink = sourceLink
+
+ this.connectionIdentity = connectionIdentity
+
+ this.subscribeTo(this.sourceLink)
+
+ this.theme = Property.consumer(this, payload.theme.key, payload.theme.value)
+
+ this.signInWallpaper = Property.consumer(this, payload.signInWallpaper.key, payload.signInWallpaper.value)
+
+ this.desktopWallpaper = Property.consumer(this, payload.desktopWallpaper.key, payload.desktopWallpaper.value)
+ }
+
+ @Forward("outbound")
+ public async forwardToSession(event: string, ...values: unknown[]) {
+
+ const responseUuid = uuidv4()
+
+ await this.sourceLink.$outbound.publish(event, responseUuid, ...values)
+
+ const response = await this.sourceLink.$inbound.waitFirst<Outcome<unknown[]>>(responseUuid)
+
+ return unwrap(response)
+ }
+
+ // A transport emission with no response address. Used for private facts
+ // whose producer must never wait for, retry, or observe host handling.
+ public emitToSession(event: string, ...values: unknown[]) {
+
+ this.sourceLink.$outbound.publish(event, null, ...values).catch(() => undefined)
+ }
+
+ public async authenticationState() {
+
+ return await this.$outbound.publishFirst<AuthenticationState>("/owner/state")
+ }
+
+ public async register(username: string, password: string) {
+
+ return await this.$outbound.publishFirst<RegistrationResponse>("/owner/register", username, password)
+ }
+
+ public async signIn(username: string, password: string) {
+
+ return await this.$outbound.publishFirst<string | false>("/owner/sign-in", username, password)
+ }
+
+ public async sessionAuthenticate(authorization: string | null) {
+
+ return await this.$outbound.publishFirst<[string, TransmittedAuthManager] | false>("/session-authenticate", this.connectionIdentity, authorization)
+ }
+}
diff --git a/source/client/dec.d.ts b/source/client/dec.d.ts
new file mode 100644
index 0000000..151aa68
--- /dev/null
+++ b/source/client/dec.d.ts
@@ -0,0 +1 @@
+/// <reference types="vite/client" />
\ No newline at end of file
diff --git a/source/client/index.html b/source/client/index.html
new file mode 100644
index 0000000..93c799a
--- /dev/null
+++ b/source/client/index.html
@@ -0,0 +1,13 @@
+<!DOCTYPE html>
+<html lang="en">
+
+<head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <script type="module" src="./main.ts"></script>
+</head>
+
+<body>
+</body>
+
+</html>
\ No newline at end of file
diff --git a/source/client/main.ts b/source/client/main.ts
new file mode 100644
index 0000000..acb3671
--- /dev/null
+++ b/source/client/main.ts
@@ -0,0 +1,5 @@
+import { displayName, name, version } from "@/package.json"
+import doors from "@server/view/doors"
+import view from "./view/view"
+
+view({ name, displayName, version, document, doors })
diff --git a/source/client/view/appearance/appearance.css b/source/client/view/appearance/appearance.css
new file mode 100644
index 0000000..72e382a
--- /dev/null
+++ b/source/client/view/appearance/appearance.css
@@ -0,0 +1,43 @@
+
+@import "tailwindcss";
+
+@import "@fontsource/roboto";
+
+@theme {
+
+ --font-roboto: "Roboto", sans-serif;
+
+ --text-window-title: 0.8125rem;
+
+ --text-taskbar-label: 0.6875rem;
+
+ --text-taskbar-status: 0.625rem;
+
+ --spacing-taskbar: 3.125rem;
+
+ --shadow-taskbar: 0 20px 40px -16px rgba(12, 30, 60, 0.45);
+
+ --shadow-taskbar-control: inset 0 1px 0 rgba(255, 255, 255, 0.8);
+
+ --shadow-taskbar-item: inset 0 1px 0 rgba(255, 255, 255, 0.7);
+
+ --shadow-taskbar-item-active: inset 0 1px 0 rgba(255, 255, 255, 0.95), 0 5px 12px -5px rgba(12, 46, 88, 0.5);
+
+ --shadow-taskbar-indicator: 0 0 7px rgba(14, 165, 233, 0.9);
+
+ --shadow-taskbar-separator: 1px 0 0 rgba(30, 64, 100, 0.12);
+
+ --shadow-launcher-icon: inset 0 1px 0 rgba(255, 255, 255, 0.8), 0 6px 14px -8px rgba(12, 46, 88, 0.55);
+
+ --shadow-window-active: 0 24px 48px rgba(12, 30, 60, 0.4), 0 8px 20px -8px rgba(56, 189, 248, 0.35);
+
+ --shadow-window-inactive: 0 14px 28px rgba(12, 30, 60, 0.28), 0 8px 20px -8px rgba(56, 189, 248, 0);
+
+ --shadow-window-controls: inset 0 1px 0 rgba(255, 255, 255, 0.9), 0 1px 2px rgba(12, 46, 88, 0.15);
+
+ --shadow-window-content: inset 0 0 0 1px rgba(255, 255, 255, 0.45);
+
+ --shadow-snap-preview: inset 0 1px 0 rgba(255, 255, 255, 0.6), inset 0 0 0 1px rgba(255, 255, 255, 0.25);
+
+ --text-shadow-chrome: 0 1px 0 rgba(255, 255, 255, 0.8);
+}
diff --git a/source/client/view/appearance/appearance.tsx b/source/client/view/appearance/appearance.tsx
new file mode 100644
index 0000000..ade9b63
--- /dev/null
+++ b/source/client/view/appearance/appearance.tsx
@@ -0,0 +1,28 @@
+import ReducedMotion from "@libs/react-motion"
+import { standardTheme } from "@phreshos/core"
+import { ReactNode } from "react"
+import "./appearance.css"
+
+export default function ({ children, reducedMotion }: AppearanceProps) {
+
+ return <ReducedMotion reduced={reducedMotion}>
+
+ <div className="relative isolate grid h-dvh overflow-hidden font-roboto" style={{ backgroundColor: standardTheme.background }}>
+
+ <div className="relative grid min-h-0">
+
+ {children}
+
+ </div>
+
+ </div>
+
+ </ReducedMotion>
+}
+
+interface AppearanceProps {
+
+ children: ReactNode
+
+ reducedMotion?: boolean
+}
diff --git a/source/client/view/appearance/surface-presence.ts b/source/client/view/appearance/surface-presence.ts
new file mode 100644
index 0000000..9f7cbaf
--- /dev/null
+++ b/source/client/view/appearance/surface-presence.ts
@@ -0,0 +1,42 @@
+import gsap from "gsap"
+
+const entered = { scale: 1, y: 0 }
+
+const entering = { scale: 0.92, y: 14 }
+
+/** Establish the first frame before a glass surface becomes visible. */
+export function prepareSurfaceEntrance(surface: HTMLElement | null, reducedMotion: boolean) {
+
+ if (!surface) return
+
+ gsap.killTweensOf(surface)
+
+ gsap.set(surface, reducedMotion ? entered : entering)
+}
+
+/** Give every system glass surface the same entrance motion. */
+export function enterSurface(surface: HTMLElement | null, reducedMotion: boolean) {
+
+ if (!surface) return null
+
+ gsap.killTweensOf(surface)
+
+ if (reducedMotion) {
+
+ gsap.set(surface, entered)
+
+ return null
+ }
+
+ return gsap.to(surface, { ...entered, duration: 0.24, ease: "back.out(1.6)" })
+}
+
+/** Stop presence motion and leave the surface ready for its next entrance. */
+export function restSurface(surface: HTMLElement | null) {
+
+ if (!surface) return
+
+ gsap.killTweensOf(surface)
+
+ gsap.set(surface, entered)
+}
diff --git a/source/client/view/components/alert.tsx b/source/client/view/components/alert.tsx
new file mode 100644
index 0000000..0e1198b
--- /dev/null
+++ b/source/client/view/components/alert.tsx
@@ -0,0 +1,6 @@
+import { ComponentProps } from "react"
+
+export default function ({ className, ...props }: ComponentProps<"div">) {
+
+ return <div role="alert" className={`rounded border px-3 py-2 ${className ?? ""}`} {...props} />
+}
diff --git a/source/client/view/components/loading.tsx b/source/client/view/components/loading.tsx
new file mode 100644
index 0000000..0083991
--- /dev/null
+++ b/source/client/view/components/loading.tsx
@@ -0,0 +1,21 @@
+import { type ComponentProps } from "react"
+import Spinner from "./spinner"
+
+/** The shared treatment for content obscured by an unresolved system state. */
+export const obscuredBackground = "bg-white/10 backdrop-blur-md"
+
+/** A loading surface that keeps the content behind it softly obscured. */
+export default function ({ className, ...props }: ComponentProps<"div">) {
+
+ return <div
+
+ className={`absolute inset-0 z-10 grid rounded-[inherit] ${obscuredBackground} ${className ?? ""}`}
+
+ {...props}
+
+ >
+
+ <Spinner className="m-auto size-6 text-slate-700" />
+
+ </div>
+}
diff --git a/source/client/view/components/spinner.tsx b/source/client/view/components/spinner.tsx
new file mode 100644
index 0000000..00be9ae
--- /dev/null
+++ b/source/client/view/components/spinner.tsx
@@ -0,0 +1,21 @@
+import { ComponentProps } from "react"
+import { useReducedMotion } from "@libs/react-motion"
+
+export default function ({ className, children, ...props }: ComponentProps<"div">) {
+
+ const reducedMotion = useReducedMotion()
+
+ return <div
+
+ role="status"
+
+ className={`rounded-full border-2 border-current border-t-transparent ${reducedMotion ? "" : "animate-spin"} ${className ?? ""}`}
+
+ {...props}
+
+ >
+
+ {children ?? <span className="sr-only">Loading</span>}
+
+ </div>
+}
diff --git a/source/client/view/components/wallpaper.tsx b/source/client/view/components/wallpaper.tsx
new file mode 100644
index 0000000..a18eb05
--- /dev/null
+++ b/source/client/view/components/wallpaper.tsx
@@ -0,0 +1,137 @@
+import bundledWallpaper from "@/assets/bundled/wallpaper.jpg"
+import { ApplicationContext } from "../contexts"
+import { useMemo, useState, type ReactNode } from "react"
+import Loading from "./loading"
+
+type WallpaperSource = Readonly<{
+ key: string
+ source: string
+ html: boolean
+}>
+
+/**
+ * Displays only a completely loaded wallpaper source.
+ *
+ * A filename asks for a new served wallpaper, `null` explicitly selects the
+ * bundled wallpaper, and `undefined` retains the displayed source while a
+ * different wallpaper owner prepares its representation.
+ */
+export function WallpaperBackground({ file, visible = true, onReady }: WallpaperBackgroundProps) {
+
+ const application = ApplicationContext.useValue()
+
+ const desired = useMemo<WallpaperSource | null>(() => {
+
+ if (file === undefined) return null
+
+ return file === null
+ ? { key: "bundled", source: bundledWallpaper, html: false }
+ : {
+ key: `file:${file}`,
+ source: `${application.doors.uploads}/${encodeURIComponent(file)}`,
+ html: /\.html?$/i.test(file)
+ }
+
+ }, [application.doors.uploads, file])
+
+ const [displayed, setDisplayed] = useState<WallpaperSource | null>(null)
+
+ const sources = desired && desired.key !== displayed?.key
+
+ ? displayed ? [displayed, desired] : [desired]
+
+ : displayed ? [displayed] : desired ? [desired] : []
+
+ function loaded(source: WallpaperSource) {
+
+ if (source.key !== desired?.key) return
+
+ setDisplayed(source)
+
+ onReady?.()
+ }
+
+ return <>{sources.map(source => <WallpaperLayer
+
+ key={source.key}
+
+ source={source}
+
+ visible={visible && source.key === displayed?.key}
+
+ onLoad={() => loaded(source)}
+
+ />)}</>
+}
+
+function WallpaperLayer({ source, visible, onLoad }: { source: WallpaperSource, visible: boolean, onLoad: () => void }) {
+
+ if (source.html) return <iframe
+
+ src={source.source}
+
+ title="Wallpaper"
+
+ sandbox="allow-scripts"
+
+ className={`absolute inset-0 size-full border-0 ${visible ? "" : "pointer-events-none opacity-0"}`}
+
+ onLoad={onLoad}
+
+ />
+
+ return <>
+
+ <div
+
+ aria-hidden="true"
+
+ className={`pointer-events-none absolute inset-0 bg-cover bg-center bg-no-repeat ${visible ? "" : "opacity-0"}`}
+
+ style={{ backgroundImage: `url(${source.source})` }}
+
+ />
+
+ {!visible && <img
+
+ src={source.source}
+
+ alt=""
+
+ className="hidden"
+
+ onLoad={onLoad}
+
+ />}
+
+ </>
+}
+
+/** A complete surface whose content sits above one file-backed wallpaper. */
+export function WallpaperStage({ file, children }: { file: string | null, children: ReactNode }) {
+
+ const [ready, setReady] = useState(false)
+
+ return <div className="relative isolate grid min-h-0">
+
+ <WallpaperBackground file={file} onReady={() => setReady(true)} />
+
+ <div className="relative z-1 grid min-h-0">
+
+ {children}
+
+ </div>
+
+ {!ready && <Loading />}
+
+ </div>
+}
+
+interface WallpaperBackgroundProps {
+
+ file: string | null | undefined
+
+ visible?: boolean
+
+ onReady?: () => void
+}
diff --git a/source/client/view/contexts.ts b/source/client/view/contexts.ts
new file mode 100644
index 0000000..28aff8e
--- /dev/null
+++ b/source/client/view/contexts.ts
@@ -0,0 +1,11 @@
+import AuthManager from "@client/core/link-manager/auth-manager/auth-manager"
+import LinkManager from "@client/core/link-manager/link-manager"
+import Application from "@client/core/application"
+import ReactContext from "@libs/react-context"
+
+/** React's view-level adapters for the client core objects it consumes. */
+export const ApplicationContext = new ReactContext<Application>()
+
+export const LinkManagerContext = new ReactContext<LinkManager>()
+
+export const AuthManagerContext = new ReactContext<AuthManager>()
diff --git a/source/client/view/desktop/client-host/announcements.ts b/source/client/view/desktop/client-host/announcements.ts
new file mode 100644
index 0000000..411166e
--- /dev/null
+++ b/source/client/view/desktop/client-host/announcements.ts
@@ -0,0 +1,213 @@
+import { type default as AuthManager } from "@client/core/link-manager/auth-manager/auth-manager"
+import { type HostedEntry } from "@server/core/link-manager/auth-manager/program-manager/entry"
+import ReactTunnel from "@libs/the-link/plugins/react-helper/react-tunnel"
+import { useCallback } from "react"
+import ClientProcessBoundary from "./client-process-boundary"
+import ClientTraffic from "./client-traffic"
+import { AuthManagerContext } from "../../contexts"
+import { sdkProcess } from "./sdk-records"
+
+/**
+ * Host facts routed to the client Process boundaries that may represent them.
+ *
+ * Structural isolation is decided here: a pane can be offered only facts about
+ * itself and its own Program. The boundary joins a desktop-local `the-link`
+ * route only after its endpoint subscribes, so an uninterested boundary is not
+ * entered at all. Eligibility and interest are separate decisions, and neither
+ * is inferred by application code.
+ *
+ * Three kinds are eligible. A pane's **own Program's windows** — relayed
+ * exactly as the system said them, because the system is what decided a
+ * window moved or took focus and a second opinion here would be a second
+ * answer. Its **own Program's** processes coming and going,
+ * so a client half that can list its instances can also know when the
+ * list changed without polling for it. And a **process ending**, to the
+ * panes that could be holding that process — which is every pane of its
+ * program, since a pane can hold no other.
+ *
+ * Nothing about another program is routed to anyone, at any point.
+ *
+ * A server half reaches the same facts through its own subscribed host routes;
+ * the desktop does not reinterpret them.
+ */
+export default function useAnnouncements(panes: Map<string, ClientProcessBoundary>, traffic: ClientTraffic) {
+
+ const authManager = AuthManagerContext.useValue()
+
+ // Two tunnels, because there are two managers and each carries its
+ // own words. A subscription put on the wrong one is silent forever
+ // and looks exactly like a subscription that is simply never
+ // triggered — which is what happened to `/uninstall`, added next to
+ // its neighbours without checking they travelled the same road.
+ const processes = ReactTunnel.useFactory(authManager.processManager.$inbound)
+
+ const programs = ReactTunnel.useFactory(authManager.programManager.$inbound)
+
+ const announce = useCallback(function (identity: string, route: string, ...args: unknown[]) {
+
+ traffic.emit(identity, route, ...args).catch(() => undefined)
+
+ }, [traffic])
+
+ const post = useCallback(function (offers: Offer[]) {
+
+ for (const [pane, ...message] of offers) announce(pane, ...message)
+
+ }, [announce])
+
+ processes.useSubscribe("/created", useCallback((...results: unknown[]) => {
+
+ const [payload] = results as [ExitedProcess | null]
+
+ if (payload) post(created(authManager, whose(authManager, panes), payload))
+
+ }, [post, authManager, panes]))
+
+ processes.useSubscribe("/exited", useCallback((...results: unknown[]) => {
+
+ const [process, code, signal] = results as [ExitedProcess | null, number | null, string | null]
+
+ if (process) post(exited(authManager, whose(authManager, panes), process, code, signal))
+
+ }, [post, authManager, panes]))
+
+ const changed = useCallback((event: EndpointEvent, endpointKind: EndpointKind, results: unknown[]) => {
+
+ const [identity, payload] = results as [string | null, ExitedProcess | null]
+
+ if (identity && payload) post(endpoint(authManager, whose(authManager, panes), event, endpointKind, payload))
+
+ }, [post, authManager, panes])
+
+ processes.useSubscribe("/server-start", useCallback((...results: unknown[]) => changed("endpointStart", "server", results), [changed]))
+
+ processes.useSubscribe("/server-stop", useCallback((...results: unknown[]) => changed("endpointStop", "server", results), [changed]))
+
+ processes.useSubscribe("/client-start", useCallback((...results: unknown[]) => changed("endpointStart", "client", results), [changed]))
+
+ processes.useSubscribe("/client-stop", useCallback((...results: unknown[]) => changed("endpointStop", "client", results), [changed]))
+
+ // A program leaving the list, said to the windows of that program.
+ //
+ // A pane outlives its own program's removal — uninstalling ends
+ // nothing that is running — so there is something left to hear it,
+ // and this is the only way one could learn that what it is a face of
+ // is no longer on the machine.
+ programs.useSubscribe("/uninstall", useCallback((...results: unknown[]) => {
+
+ const [program, everythingRemoved] = results as [HostedEntry, boolean]
+
+ post(uninstalled(whose(authManager, panes), program, everythingRemoved === true))
+
+ }, [post, authManager, panes]))
+
+ // Everything a window says, relayed whole to subscribed panes allowed to
+ // hold that Client: every pane of its Program, and no pane outside it.
+ // The system decided what happened and to which Client; this decides
+ // neither again.
+ processes.useSubscribe("/said", useCallback((...results: unknown[]) => {
+
+ const [identity, event, value] = results as [string, string, unknown]
+
+ const target = authManager.processManager.processes.get(identity)
+
+ if (!target) return
+
+ const eligible = whose(authManager, panes)
+ .filter(([, program]) => program === target.program)
+ .map(([pane]) => [pane, "host-end", event, target.reference, value] as Offer)
+
+ post(eligible)
+
+ }, [post, authManager, panes]))
+}
+
+// ── What is routed, and to whom ──────────────────────────────────────
+//
+// Kept out of the hook because this is the part with a rule in it. The
+// hook posts what these decide; these decide it from what the desktop
+// already holds, and from nothing any pane said. A pane cannot ask to be
+// in one of these lists, which is the isolation as a structure rather
+// than as a check.
+
+// Each pane, and the program it is a face of.
+export function whose(authManager: AuthManager, panes: Map<string, unknown>) {
+
+ return [...panes.keys()].map(pane => [pane, authManager.processManager.processes.get(pane)?.program] as const)
+}
+
+// The subject leads, exactly as it does on the core's own announcement,
+// so a kit's `Program` filters on it without either side agreeing to
+// anything extra.
+export function created(authManager: AuthManager, panes: readonly (readonly [string, string | undefined])[], process: ExitedProcess): Offer[] {
+
+ const program = authManager.programManager.programs.get(process.program)
+
+ if (!program) return []
+
+ return panes.filter(([, identity]) => identity === process.program).map(([pane]) => [pane, "host-end", "processCreate", program.reference, record(authManager, process)])
+}
+
+// One ending, said to two subjects. A program watching its instances
+// wants the first; whoever holds this one process wants the second.
+export function exited(authManager: AuthManager, panes: readonly (readonly [string, string | undefined])[], process: ExitedProcess, code: number | null, signal: string | null): Offer[] {
+
+ // The subject leads both, and what follows is the thing the event is
+ // about — the process itself rather than an identity a listener would
+ // have to look up. It is already gone, which is what `exited()`
+ // answers and why holding it is legitimate.
+ //
+ // Built here from what the ending carried, because the record was
+ // dropped before this was sent — which is why the ending carries
+ // when it started at all. A listener handed a process must be handed
+ // the whole of one.
+ return panes.filter(([, shown]) => shown === process.program).flatMap(([pane]) => [
+
+ [pane, "host-end", "processExit", owner(authManager, process).reference, record(authManager, process), code, signal],
+
+ [pane, "process-host", "exit", process.reference, code, signal]
+
+ ] as Offer[])
+}
+
+export function endpoint(authManager: AuthManager, panes: readonly (readonly [string, string | undefined])[], event: EndpointEvent, endpointKind: EndpointKind, process: ExitedProcess): Offer[] {
+
+ const processRecord = record(authManager, process)
+
+ return panes.filter(([, shown]) => shown === process.program).flatMap(([pane]) => [
+
+ [pane, "host-end", event, owner(authManager, process).reference, processRecord, endpointKind],
+
+ [pane, "process-host", event, process.reference, processRecord, endpointKind]
+
+ ] as Offer[])
+}
+
+function record(authManager: AuthManager, process: ExitedProcess) {
+
+ return sdkProcess(process, owner(authManager, process))
+}
+
+function owner(authManager: AuthManager, process: ExitedProcess) {
+
+ const program = authManager.programManager.programs.get(process.program)
+
+ if (!program) throw new Error("The desktop does not know this program")
+
+ return program
+}
+
+// A program left the installed state, routed to its panes and no others.
+// What comes with it is whether everything the system owned went too.
+export function uninstalled(panes: readonly (readonly [string, string | undefined])[], program: { identity: string, reference: string }, everythingRemoved: boolean): Offer[] {
+
+ return panes.filter(([, shown]) => shown === program.identity).map(([pane]) => [pane, "host-end", "uninstall", program.reference, everythingRemoved])
+}
+
+type ExitedProcess = { reference: string, identity: string, program: string, startedAt: Date, name: string | null, options: Record<string, string>, server: { ready: boolean } | null, client: { window: unknown } | null }
+
+type EndpointEvent = "endpointStart" | "endpointStop"
+
+type EndpointKind = "server" | "client"
+
+export type Offer = [pane: string, route: string, ...message: unknown[]]
diff --git a/source/client/view/desktop/client-host/client-host.ts b/source/client/view/desktop/client-host/client-host.ts
new file mode 100644
index 0000000..e1aee4c
--- /dev/null
+++ b/source/client/view/desktop/client-host/client-host.ts
@@ -0,0 +1,306 @@
+import ReactTunnel from "@libs/the-link/plugins/react-helper/react-tunnel"
+import { type WindowLayer } from "@phreshos/core"
+import useAnnouncements from "./announcements"
+import { type Space } from "./host"
+import DesktopPointer from "./pointer"
+import ClientProcessBoundary from "./client-process-boundary"
+import ClientTraffic from "./client-traffic"
+import { type RefObject, useCallback, useEffect, useLayoutEffect, useRef, useState } from "react"
+import { AuthManagerContext } from "../../contexts"
+import { isPermissionName } from "@phreshos/core"
+
+/**
+ * The browser boundary between a program pane and the desktop that hosts it.
+ * It owns frame messages and the measured surfaces those frames inhabit;
+ * neither fact participates in rendering.
+ */
+export default function useClientHost(desktop: RefObject<HTMLDivElement | null>, sources: Map<string, HTMLIFrameElement | null>) {
+
+ const authManager = AuthManagerContext.useValue()
+
+ const windowSurfaceRef = useRef<HTMLElement>(null)
+
+ const frameOwners = useRef(new Map<string, string>())
+
+ const frameTasks = useRef(new Map<string, Promise<void>>())
+
+ const boundaries = useRef(new Map<string, ClientProcessBoundary>())
+
+ const [pointer] = useState(() => new DesktopPointer(desktop))
+
+ const [traffic] = useState(() => new ClientTraffic())
+
+ const [windowSurfaceSize, setWindowSurfaceSize] = useState<SurfaceSize>({ width: 0, height: 0 })
+
+ // Read by the gate at the moment a pane asks, so the answer is
+ // never a render behind.
+ const latest = useRef<Record<WindowLayer, Space>>({
+
+ under: { width: 0, height: 0 },
+
+ window: { width: 0, height: 0 },
+
+ over: { width: 0, height: 0 },
+
+ wallpaper: { width: 0, height: 0 }
+ })
+
+ useLayoutEffect(function () {
+
+ if (!desktop.current || !windowSurfaceRef.current) return
+
+ function measure(entry: ResizeObserverEntry): Space {
+
+ return { width: Math.round(entry.contentRect.width), height: Math.round(entry.contentRect.height) }
+ }
+
+ function announce(layer: WindowLayer, now: Space) {
+
+ latest.current[layer] = now
+
+ // Announcements leave directly from the measurement. The
+ // ordinary surface also participates in rendering because its
+ // windows resolve which painted edges touch its boundaries.
+ if (!now.width) return
+
+ for (const identity of sources.keys()) {
+
+ if (authManager.processManager.processes.get(identity)?.client?.window.layer !== layer) continue
+
+ traffic.emit(identity, "host-surface", "resize", now).catch(() => undefined)
+ }
+ }
+
+ function rememberWindowSurfaceSize({ width, height }: SurfaceSize) {
+
+ setWindowSurfaceSize(current => current.width === width && current.height === height ? current : { width, height })
+ }
+
+ const initial = windowSurfaceRef.current.getBoundingClientRect()
+
+ rememberWindowSurfaceSize(initial)
+
+ const viewportObserver = new ResizeObserver(function ([entry]) {
+
+ const now = measure(entry)
+
+ announce("under", now)
+
+ announce("over", now)
+
+ announce("wallpaper", now)
+ })
+
+ const windowObserver = new ResizeObserver(function ([entry]) {
+
+ rememberWindowSurfaceSize(entry.contentRect)
+
+ announce("window", measure(entry))
+ })
+
+ viewportObserver.observe(desktop.current)
+
+ windowObserver.observe(windowSurfaceRef.current)
+
+ return function () {
+
+ viewportObserver.disconnect()
+
+ windowObserver.disconnect()
+ }
+
+ }, [authManager, desktop, sources, traffic])
+
+ useAnnouncements(boundaries.current, traffic)
+
+ useEffect(() => pointer.listen(), [pointer])
+
+ // The process-to-interface leg rides the same tunnel the echoes
+ // land on: an end-end arrives as (identity, json) and is posted into
+ // its pane in its envelope. The op's own echo shares the event name
+ // with a null payload — the type guard tells them apart.
+ const inbound = ReactTunnel.useFactory(authManager.processManager.$inbound)
+
+ inbound.useSubscribe("/end-end", useCallback((...results: unknown[]) => {
+
+ const [identity, json] = results
+
+ if (typeof identity !== "string" || typeof json !== "string") return
+
+ const values = JSON.parse(json) as unknown[]
+
+ if ((values[0] === "answer" || values[0] === "wait") && typeof values[1] === "string") boundaries.current.get(identity)?.deliver("end-end", ...values).catch(() => undefined)
+
+ else traffic.emit(identity, "end-end", ...values).catch(() => undefined)
+
+ }, [sources, traffic]))
+
+ // A held Process observes through a separate envelope. The core has
+ // already targeted the subscribing process; this desktop offers the
+ // copy only to that process's frame, and never puts it on end-end.
+ // Observed publications and request answering remain separate routes.
+ inbound.useSubscribe("/observed", useCallback((...results: unknown[]) => {
+
+ const [observer, owner, subscription, json] = results
+
+ if (typeof observer !== "string" || typeof owner !== "string" || typeof subscription !== "string" || typeof json !== "string") return
+
+ if (frameOwners.current.get(observer) !== owner) return
+
+ traffic.emit(observer, "observed", subscription, ...JSON.parse(json) as unknown[]).catch(() => undefined)
+
+ }, [sources, traffic]))
+
+ // Destinationless Endpoint events use their own route and therefore never
+ // appear in directed traffic observations.
+ inbound.useSubscribe("/emitted", useCallback((...results: unknown[]) => {
+
+ const [observer, owner, subscription, json] = results
+
+ if (typeof observer !== "string" || typeof owner !== "string" || typeof subscription !== "string" || typeof json !== "string") return
+
+ if (frameOwners.current.get(observer) !== owner) return
+
+ traffic.emit(observer, "emitted", subscription, ...JSON.parse(json) as unknown[]).catch(() => undefined)
+
+ }, [sources, traffic]))
+
+ inbound.useSubscribe("/impossible", useCallback((...results: unknown[]) => {
+
+ const [observer, owner, subscription, reason] = results
+
+ if (typeof observer !== "string" || typeof owner !== "string" || typeof subscription !== "string" || typeof reason !== "string") return
+
+ if (frameOwners.current.get(observer) !== owner) return
+
+ boundaries.current.get(observer)?.impossible(subscription, reason)
+
+ }, [sources]))
+
+ inbound.useSubscribe("/client-stop", useCallback((...results: unknown[]) => {
+
+ const [identity] = results
+
+ if (typeof identity !== "string") return
+
+ boundaries.current.get(identity)?.release().catch(() => undefined)
+
+ boundaries.current.delete(identity)
+
+ sources.delete(identity)
+
+ }, [sources]))
+
+ inbound.useSubscribe("/permission-changed", useCallback((...results: unknown[]) => {
+
+ const [identity, permission, decision] = results
+
+ if (typeof identity !== "string" || !isPermissionName(permission) || (decision !== true && decision !== false && decision !== null)) return
+
+ boundaries.current.get(identity)?.permissionChanged(permission, decision)
+
+ }, []))
+
+ const frame = useCallback(function (identity: string, element: HTMLIFrameElement | null) {
+
+ if (element) {
+
+ sources.set(identity, element)
+
+ boundaries.current.get(identity)?.release().catch(() => undefined)
+
+ boundaries.current.set(identity, new ClientProcessBoundary(identity, element, authManager, layer => latest.current[layer], pointer, traffic))
+
+ return
+ }
+
+ sources.delete(identity)
+
+ const boundary = boundaries.current.get(identity)
+
+ boundaries.current.delete(identity)
+
+ frameOwners.current.delete(identity)
+
+ boundary?.release().catch(() => undefined)
+
+ }, [authManager, pointer, sources, traffic])
+
+ const frameLoaded = useCallback(function (identity: string, element: HTMLIFrameElement) {
+
+ const previous = frameTasks.current.get(identity) ?? Promise.resolve()
+
+ const task = previous.catch(() => undefined).then(async function () {
+
+ if (sources.get(identity) !== element) return
+
+ const owner = crypto.randomUUID()
+
+ frameOwners.current.set(identity, owner)
+
+ try {
+
+ const boundary = boundaries.current.get(identity)
+
+ if (!boundary || boundary.element !== element) return
+
+ await boundary.own(owner)
+
+ if (sources.get(identity) !== element || frameOwners.current.get(identity) !== owner) {
+
+ await boundary.release()
+
+ return
+ }
+
+ }
+
+ catch (error) { console.error(error) }
+ })
+
+ frameTasks.current.set(identity, task)
+
+ task.finally(() => { if (frameTasks.current.get(identity) === task) frameTasks.current.delete(identity) }).catch(() => undefined)
+
+ }, [authManager, pointer, sources])
+
+ // The interface wall: an iframe's end-end relays to its process's
+ // other end; its end-host terminates here, handled by the desktop —
+ // the interface's host. Args cross The Link as standard JSON in a
+ // plain string — The Link's serialization never shapes a payload.
+ // A cached iframe may begin executing before passive effects run. Install
+ // its boundary listener during the commit, before the browser can run it,
+ // so the document's first explicit request cannot disappear.
+ useLayoutEffect(function () {
+
+ function onMessage(event: MessageEvent) {
+
+ if (!Array.isArray(event.data)) return
+
+ for (const boundary of boundaries.current.values()) {
+
+ const source = boundary.element
+
+ if (source?.contentWindow !== event.source) continue
+
+ boundary.receive(event.data)
+
+ return
+ }
+ }
+
+ window.addEventListener("message", onMessage)
+
+ return () => window.removeEventListener("message", onMessage)
+
+ }, [authManager, pointer, sources])
+
+ return { windowSurfaceRef, windowSurfaceSize, frame, frameLoaded }
+}
+
+export interface SurfaceSize {
+
+ width: number
+
+ height: number
+}
diff --git a/source/client/view/desktop/client-host/client-process-boundary.ts b/source/client/view/desktop/client-host/client-process-boundary.ts
new file mode 100644
index 0000000..8109a11
--- /dev/null
+++ b/source/client/view/desktop/client-host/client-process-boundary.ts
@@ -0,0 +1,876 @@
+import AuthManager from "@client/core/link-manager/auth-manager/auth-manager"
+import { type WindowLayer } from "@phreshos/core"
+import TheLink from "@libs/the-link/the-link"
+import host, { type Space, TransferredAnswer } from "./host"
+import { type PointerHost } from "./pointer"
+import ClientTraffic from "./client-traffic"
+import { failed, succeeded } from "@server/core/outcome"
+import { type TrafficKind } from "@server/core/link-manager/auth-manager/process-manager/process-traffic"
+import { isPermissionName, type PermissionName } from "@phreshos/core"
+
+/** The desktop boundary around one iframe execution endpoint. */
+export default class ClientProcessBoundary extends TheLink {
+
+ public readonly pane: string
+
+ public readonly element: HTMLIFrameElement
+
+ private readonly authManager: AuthManager
+
+ private readonly space: (layer: WindowLayer) => Space
+
+ private readonly pointer: PointerHost
+
+ private readonly traffic: ClientTraffic
+
+ private readonly subscriptions = new Map<string, EndpointSubscription>()
+
+ private readonly blockedSubscriptions = new Map<string, EndpointSubscription>()
+
+ private readonly expected = new Set<string>()
+
+ private readonly requests = new Map<string, () => void>()
+
+ private readonly waiting = new Map<string, WaitingQuestion[]>()
+
+ private readonly trafficSubscriptions = new Map<string, TrafficSubscription>()
+
+ private readonly themeSubscriptions = new Set<string>()
+
+ private stopTheme: (() => void) | null = null
+
+ private readonly trafficDeliveries = new WeakSet<object>()
+
+ // A document can begin executing before its iframe load event gives the
+ // desktop a server-host lease. Keep those endpoint envelopes at the near
+ // boundary; once the lease exists they follow the same path as later ones.
+ private readonly pending = new Array<unknown[]>()
+
+ private pointerStop: (() => void) | null = null
+
+ private pointerPosition: { x: number, y: number } | null = null
+
+ private owner: string | null = null
+
+ private leased: string | null = null
+
+ private document: string | null = null
+
+ public constructor(pane: string, element: HTMLIFrameElement, authManager: AuthManager, space: (layer: WindowLayer) => Space, pointer: PointerHost, traffic: ClientTraffic) {
+
+ super()
+
+ this.pane = pane
+
+ this.element = element
+
+ this.authManager = authManager
+
+ this.space = space
+
+ this.pointer = pointer
+
+ this.traffic = traffic
+
+ this.$outbound.forwardTo((route, ...values) => {
+
+ this.element.contentWindow?.postMessage([route, ...values], "*")
+ })
+ }
+
+ public async own(owner: string) {
+
+ await this.authManager.processManager.ownFrame(this.pane, owner)
+
+ this.owner = owner
+
+ this.leased = owner
+
+ for (const [subscription, description] of this.subscriptions) {
+
+ if (directSubscription(description)) this.authManager.processManager.subscribeFrame(this.pane, owner, subscription, description.kind, description.event).catch(() => undefined)
+ }
+
+ const pending = this.pending.splice(0)
+
+ for (const message of pending) this.receive(message)
+ }
+
+ public async release() {
+
+ const owner = this.leased
+
+ this.owner = null
+
+ this.leased = null
+
+ this.document = null
+
+ this.resetEndpoint()
+
+ this.pending.length = 0
+
+ if (owner) await this.authManager.processManager.releaseFrame(this.pane, owner)
+ }
+
+ /** Receive one envelope from the iframe endpoint. */
+ public receive(message: unknown[]) {
+
+ const [route, ...values] = message
+
+ if (route === "boundary") {
+
+ this.control(values)
+
+ return
+ }
+
+ // The SDK reconstructs `current` from this boundary's own Process so
+ // `current.server` is the exact handle at `current.process().server`.
+ // A module may request that essential self-description before its
+ // document reaches the iframe load event that establishes a forwarding
+ // lease. It is safe to answer here: this boundary already owns `pane`,
+ // and the request contains no selectable subject or outside authority.
+ if (!this.owner && route === "end-host" && values[0] === "wait" && typeof values[1] === "string" && values[2] === "process") {
+
+ this.request(values[1], values.slice(2))
+
+ return
+ }
+
+ if (!this.owner) {
+
+ this.pending.push(message)
+
+ return
+ }
+
+ if (route === "end-end") {
+
+ const asking = values[0] === "wait" && typeof values[1] === "string" ? values[1] : null
+
+ if (asking) this.requests.set(asking, () => {
+
+ this.authManager.processManager.cancel(this.pane, asking).catch(() => undefined)
+ })
+
+ this.authManager.processManager.processes.get(this.pane)?.endEnd(...values).catch((error: Error) => {
+
+ if (asking) {
+
+ this.requests.delete(asking)
+
+ if (typeof values[2] === "string" && typeof values[3] === "string") this.deliver("end-end", "answer", asking, values[2], values[3], failed(error)).catch(() => undefined)
+ }
+ })
+
+ return
+ }
+
+ if (route !== "end-host") return
+
+ if (values[0] === "wait" && typeof values[1] === "string") {
+
+ this.request(values[1], values.slice(2))
+
+ return
+ }
+
+ if (values[0] === "ask" && typeof values[1] === "string" && typeof values[3] === "string") {
+
+ const question = values[3]
+
+ this.requests.set(question, () => {
+
+ this.authManager.processManager.cancel(this.pane, question).catch(() => undefined)
+ })
+ }
+
+ if (values[0] === "pointerSample") {
+
+ this.samplePointer(values[1], values[2])
+
+ return
+ }
+
+ host(this.authManager, this.pane, this.space, () => this.owner, this.pointer)(values[0], ...values.slice(1)).catch((error: Error) => {
+
+ if (values[0] === "observe" && typeof values[1] === "string" && values[6] === true) {
+
+ this.impossible(values[1], error.message)
+
+ return
+ }
+
+ if (values[0] === "follow" && typeof values[1] === "string" && values[5] === true) {
+
+ this.impossible(values[1], error.message)
+
+ return
+ }
+
+ })
+ }
+
+ /** Deliver one routed envelope only when this endpoint requested it. */
+ public async deliver(route: string, ...values: unknown[]) {
+
+ if (values[0] === "answer" && typeof values[1] === "string") {
+
+ if (!this.expected.has(values[1])) return
+
+ this.requests.delete(values[1])
+
+ await this.$outbound.publish(route, ...values)
+
+ return
+ }
+
+ const question = values[0] === "wait" && typeof values[1] === "string" ? values[1] : null
+
+ const eventIndex = question && route === "end-end" ? 3 : 2
+
+ const event = String(question ? values[eventIndex] : values[0])
+
+ const payload = question ? values.slice(eventIndex + 1) : values.slice(1)
+
+ const kind: TrafficKind = question ? "ask" : "publish"
+
+ if (this.accepts(kind, route, event, payload)) {
+
+ await this.$outbound.publish(route, ...values)
+
+ return
+ }
+
+ if (!question) return
+
+ const key = `${route}:${event}`
+
+ const waiting = this.waiting.get(key) ?? []
+
+ waiting.push({ route, values, question })
+
+ this.waiting.set(key, waiting)
+ }
+
+ public post(route: string, values: unknown[], transfer: Transferable[] = []) {
+
+ this.element.contentWindow?.postMessage([route, ...values], "*", transfer)
+ }
+
+ public impossible(subscription: string, reason: string) {
+
+ this.$outbound.publish("boundary", "impossible", subscription, reason).catch(() => undefined)
+ }
+
+ private control(values: unknown[]) {
+
+ const [operation, ...args] = values
+
+ if (operation === "document") {
+
+ if (typeof args[0] !== "string" || args[0] === this.document) return
+
+ this.document = args[0]
+
+ this.resetEndpoint()
+
+ // The new document cannot use the previous document's forwarding
+ // lease while its own lease is still being established.
+ this.owner = null
+
+ return
+ }
+
+ if (operation === "log") {
+
+ if (typeof args[0] !== "string" || typeof args[1] !== "string") return
+
+ // The iframe supplies only what it said. This boundary supplies
+ // the Process identity, so program code has no route for naming a
+ // different owner, and logging itself has no response path.
+ this.authManager.processManager.log(this.pane, args[0], args[1])
+
+ return
+ }
+
+ if (operation === "subscribe") {
+
+ const [subscription, kind, route, event, subject, reportImpossible] = args
+
+ if (typeof subscription !== "string" || !isTrafficKind(kind) || typeof route !== "string") return
+
+ if (event !== null && typeof event !== "string") return
+
+ if (subject !== null && typeof subject !== "string") return
+
+ if (reportImpossible === true && route === "end-end") {
+
+ const process = this.authManager.processManager.processes.get(this.pane)
+
+ const program = process && this.authManager.programManager.programs.get(process.program)
+
+ if (!process || !program?.server) {
+
+ this.impossible(subscription, process ? "This program declared no server half" : "The process no longer exists")
+
+ return
+ }
+ }
+
+ this.removeSubscription(subscription)
+
+ const description = { kind, route, event, subject }
+
+ if (pointerSubscription(description)) {
+
+ this.blockedSubscriptions.set(subscription, description)
+
+ this.authManager.permissionGranted(this.pane, "pointer").then(decision => {
+
+ if (decision === true) this.allowSubscription(subscription)
+ }).catch(() => undefined)
+
+ return
+ }
+
+ this.subscriptions.set(subscription, description)
+
+ if (!themeSubscription(description)) this.addTraffic(kind, route, event)
+
+ if (this.owner && directSubscription(description)) this.authManager.processManager.subscribeFrame(this.pane, this.owner, subscription, kind, event).catch(() => undefined)
+
+ if (themeSubscription(description)) {
+
+ this.themeSubscriptions.add(subscription)
+
+ if (!this.stopTheme) this.stopTheme = this.authManager.linkManager.theme.tunnel.subscribe("change", (theme: unknown) => {
+
+ this.deliver("host-theme", "change", theme).catch(() => undefined)
+ })
+
+ }
+
+ if (kind === "ask") this.releaseWaiting(route, event)
+
+ this.updatePointer()
+
+ return
+ }
+
+ if (operation === "unsubscribe") {
+
+ if (typeof args[0] === "string") this.removeSubscription(args[0])
+
+ this.updatePointer()
+
+ return
+ }
+
+ if (operation === "expect") {
+
+ if (typeof args[0] === "string") this.expected.add(args[0])
+
+ return
+ }
+
+ if (operation === "forget") {
+
+ if (typeof args[0] !== "string") return
+
+ const question = args[0]
+
+ this.expected.delete(question)
+
+ this.requests.get(question)?.()
+
+ this.requests.delete(question)
+
+ this.forgetWaiting(question)
+
+ this.forgetPending(question)
+ }
+ }
+
+ private request(question: string, args: unknown[]) {
+
+ if (!this.expected.has(question)) return
+
+ if (args[0] === "wait-ready") {
+
+ this.waitReady(question, args[1], args[2] === true)
+
+ return
+ }
+
+ if (args[0] === "permission-request") {
+
+ if (!isPermissionName(args[1])) {
+
+ this.deliver("host-end", "answer", question, failed(new Error(`The system does not know the permission "${String(args[1])}"`))).catch(() => undefined)
+
+ return
+ }
+
+ const controller = new AbortController()
+
+ this.answerRequest(
+
+ question,
+
+ this.authManager.requestPermission(this.pane, args[1], controller.signal).then(decision => [decision]),
+
+ () => controller.abort()
+ )
+
+ return
+ }
+
+ this.answerRequest(question, host(this.authManager, this.pane, this.space, () => this.owner, this.pointer)(args[0], ...args.slice(1)))
+ }
+
+ private answerRequest(question: string, operation: Promise<unknown[] | TransferredAnswer>, cancel: () => void = () => undefined) {
+
+ let active = true
+
+ this.requests.set(question, () => {
+
+ if (!active) return
+
+ active = false
+
+ cancel()
+ })
+
+ operation.then(
+
+ answer => {
+
+ if (!active || !this.expected.has(question)) return
+
+ this.requests.delete(question)
+
+ const transferred = answer instanceof TransferredAnswer ? answer : null
+
+ if (transferred) this.post("host-end", ["answer", question, succeeded(transferred.result)], transferred.transfer)
+
+ else this.deliver("host-end", "answer", question, succeeded(answer)).catch(() => undefined)
+ },
+
+ (error: Error) => {
+
+ if (!active || !this.expected.has(question)) return
+
+ this.requests.delete(question)
+
+ this.deliver("host-end", "answer", question, failed(error)).catch(() => undefined)
+ }
+ )
+ }
+
+ private waitReady(question: string, target: unknown, requireCurrentIncarnation: boolean) {
+
+ const mine = this.authManager.processManager.processes.get(this.pane)
+
+ const process = target === undefined || target === null
+ ? mine
+ : isHandleAddress(target)
+ ? this.authManager.processManager.processes.get(target.identity)
+ : undefined
+
+ if (!mine || !process || mine.program !== process.program || (isHandleAddress(target) && process.reference !== target.reference)) {
+
+ this.deliver("host-end", "answer", question, failed(new Error("The desktop does not know this process"))).catch(() => undefined)
+
+ return
+ }
+
+ const program = this.authManager.programManager.programs.get(process.program)
+
+ if (!program?.server) {
+
+ this.deliver("host-end", "answer", question, failed(new Error("This program declared no server half"))).catch(() => undefined)
+
+ return
+ }
+
+ if (requireCurrentIncarnation && !process.server) {
+
+ this.deliver("host-end", "answer", question, failed(new Error("This process has no live server endpoint"))).catch(() => undefined)
+
+ return
+ }
+
+ if (process.server?.ready) {
+
+ this.deliver("host-end", "answer", question, succeeded([])).catch(() => undefined)
+
+ return
+ }
+
+ let active = true
+
+ const stopReady = this.authManager.processManager.$inbound.subscribe("/server-ready", (identity: unknown) => {
+
+ if (!active || identity !== process.identity || this.authManager.processManager.processes.get(process.identity) !== process || !this.expected.has(question)) return
+
+ stop()
+
+ this.requests.delete(question)
+
+ this.deliver("host-end", "answer", question, succeeded([])).catch(() => undefined)
+ })
+
+ const stopExit = this.authManager.processManager.$inbound.subscribe("/exited", (payload: unknown) => {
+
+ if (!active || !payload || typeof payload !== "object" || (payload as { reference?: unknown }).reference !== process.reference) return
+
+ stop()
+
+ this.requests.delete(question)
+
+ this.deliver("host-end", "answer", question, failed(new Error("The process ended before its server became ready"))).catch(() => undefined)
+ })
+
+ const stopServer = requireCurrentIncarnation
+ ? this.authManager.processManager.$inbound.subscribe("/server-stop", (identity: unknown) => {
+
+ if (!active || identity !== process.identity || this.authManager.processManager.processes.get(process.identity) !== process) return
+
+ stop()
+
+ this.requests.delete(question)
+
+ this.deliver("host-end", "answer", question, failed(new Error("The server endpoint stopped before becoming ready"))).catch(() => undefined)
+ })
+ : () => undefined
+
+ const stop = () => {
+
+ if (!active) return
+
+ active = false
+
+ stopReady()
+
+ stopExit()
+
+ stopServer()
+ }
+
+ this.requests.set(question, stop)
+ }
+
+ private accepts(kind: TrafficKind, route: string, event: string, payload: unknown[]) {
+
+ for (const subscription of this.subscriptions.values()) {
+
+ if (subscription.kind !== kind || subscription.route !== route) continue
+
+ if (subscription.event !== null && subscription.event !== event) continue
+
+ if (subscription.subject !== null && payload[0] !== subscription.subject) continue
+
+ return true
+ }
+
+ return false
+ }
+
+ private addTraffic(kind: TrafficKind, route: string, event: string | null) {
+
+ const key = JSON.stringify([kind, route, event])
+
+ const current = this.trafficSubscriptions.get(key)
+
+ if (current) {
+
+ current.count++
+
+ return
+ }
+
+ const stop = this.traffic.observe(this.pane, route, kind, event, (delivery, ...values) => {
+
+ if (this.trafficDeliveries.has(delivery)) return
+
+ this.trafficDeliveries.add(delivery)
+
+ this.deliver(route, ...values).catch(() => undefined)
+ })
+
+ this.trafficSubscriptions.set(key, { count: 1, stop })
+ }
+
+ private removeSubscription(subscription: string) {
+
+ this.blockedSubscriptions.delete(subscription)
+
+ const existing = this.subscriptions.get(subscription)
+
+ if (!existing) return
+
+ if (this.owner && directSubscription(existing)) this.authManager.processManager.unsubscribeFrame(this.pane, this.owner, subscription).catch(() => undefined)
+
+ this.subscriptions.delete(subscription)
+
+ if (this.themeSubscriptions.delete(subscription) && this.themeSubscriptions.size === 0) {
+
+ this.stopTheme?.()
+
+ this.stopTheme = null
+ }
+
+ const key = JSON.stringify([existing.kind, existing.route, existing.event])
+
+ const traffic = this.trafficSubscriptions.get(key)
+
+ if (!traffic) return
+
+ traffic.count--
+
+ if (traffic.count > 0) return
+
+ traffic.stop()
+
+ this.trafficSubscriptions.delete(key)
+ }
+
+ private allowSubscription(subscription: string) {
+
+ const description = this.blockedSubscriptions.get(subscription)
+
+ if (!description) return
+
+ this.blockedSubscriptions.delete(subscription)
+
+ this.subscriptions.set(subscription, description)
+
+ this.updatePointer()
+ }
+
+ /** Applies an authoritative effective-decision change to guarded subscriptions. */
+ public permissionChanged(permission: PermissionName, decision: boolean | null) {
+
+ if (permission !== "pointer") return
+
+ if (decision === true) {
+
+ for (const subscription of [...this.blockedSubscriptions.keys()]) this.allowSubscription(subscription)
+
+ return
+ }
+
+ for (const [subscription, description] of [...this.subscriptions]) {
+
+ if (!pointerSubscription(description)) continue
+
+ this.removeSubscription(subscription)
+
+ this.blockedSubscriptions.set(subscription, description)
+ }
+
+ this.updatePointer()
+ }
+
+ private releaseWaiting(route: string, event: string | null) {
+
+ for (const [key, waiting] of this.waiting) {
+
+ if (!key.startsWith(`${route}:`)) continue
+
+ const remaining: WaitingQuestion[] = []
+
+ for (const held of waiting) {
+
+ const eventIndex = held.route === "end-end" ? 3 : 2
+
+ const word = String(held.values[eventIndex])
+
+ const payload = held.values.slice(eventIndex + 1)
+
+ if ((event === null || event === word) && this.accepts("ask", route, word, payload)) this.$outbound.publish(held.route, ...held.values).catch(() => undefined)
+
+ else remaining.push(held)
+ }
+
+ if (remaining.length) this.waiting.set(key, remaining)
+
+ else this.waiting.delete(key)
+ }
+ }
+
+ private forgetWaiting(question: string) {
+
+ for (const [key, waiting] of this.waiting) {
+
+ const remaining = waiting.filter(held => held.question !== question)
+
+ if (remaining.length) this.waiting.set(key, remaining)
+
+ else this.waiting.delete(key)
+ }
+ }
+
+ private forgetPending(question: string) {
+
+ const remaining = this.pending.filter(message => {
+
+ const [route, operation] = message
+
+ if ((route === "end-end" || route === "end-host") && operation === "wait") return message[2] !== question
+
+ if (route === "end-host" && operation === "ask") return message[4] !== question
+
+ return true
+ })
+
+ this.pending.splice(0, this.pending.length, ...remaining)
+ }
+
+ private resetEndpoint() {
+
+ for (const stop of this.requests.values()) stop()
+
+ this.pointerStop?.()
+
+ this.requests.clear()
+
+ this.pointerStop = null
+
+ this.pointerPosition = null
+
+ if (this.owner) for (const [subscription, description] of this.subscriptions) {
+
+ if (directSubscription(description)) this.authManager.processManager.unsubscribeFrame(this.pane, this.owner, subscription).catch(() => undefined)
+ }
+
+ this.subscriptions.clear()
+
+ this.blockedSubscriptions.clear()
+
+ this.themeSubscriptions.clear()
+
+ this.stopTheme?.()
+
+ this.stopTheme = null
+
+ for (const { stop } of this.trafficSubscriptions.values()) stop()
+
+ this.trafficSubscriptions.clear()
+
+ this.expected.clear()
+
+ this.waiting.clear()
+
+ this.pending.length = 0
+ }
+
+ private updatePointer() {
+
+ const wanted = [...this.subscriptions.values()].some(pointerSubscription)
+
+ if (!wanted) {
+
+ this.pointerStop?.()
+
+ this.pointerStop = null
+
+ this.pointerPosition = null
+
+ return
+ }
+
+ if (this.pointerStop) return
+
+ this.pointerPosition = this.pointer.position()
+
+ this.pointerStop = this.pointer.$inbound.subscribe("move", (position: unknown) => {
+
+ if (!isPointerPosition(position)) return
+
+ this.pointerPosition = position
+
+ this.deliver("host-pointer", "move", position).catch(() => undefined)
+ })
+ }
+
+ // Pointer movement inside a sandboxed iframe does not bubble into the
+ // desktop document. Advance the last desktop-space position retained by
+ // this boundary, never a frame-relative coordinate.
+ private samplePointer(movementX: unknown, movementY: unknown) {
+
+ const position = this.pointerPosition
+
+ if (!position || typeof movementX !== "number" || typeof movementY !== "number" || !Number.isFinite(movementX) || !Number.isFinite(movementY)) return
+
+ const next = { x: position.x + Number(movementX), y: position.y + Number(movementY) }
+
+ this.pointerPosition = next
+
+ this.deliver("host-pointer", "move", next).catch(() => undefined)
+ }
+}
+
+function isPointerPosition(value: unknown): value is { x: number, y: number } {
+
+ if (!value || typeof value !== "object") return false
+
+ const position = value as { x?: unknown, y?: unknown }
+
+ return typeof position.x === "number" && typeof position.y === "number"
+}
+
+interface EndpointSubscription {
+
+ kind: TrafficKind
+
+ route: string
+
+ event: string | null
+
+ subject: string | null
+}
+
+function pointerSubscription(subscription: EndpointSubscription) {
+
+ return subscription.kind === "publish" && subscription.route === "host-pointer" && (subscription.event === null || subscription.event === "move")
+}
+
+function themeSubscription(subscription: EndpointSubscription) {
+
+ return subscription.kind === "publish" && subscription.route === "host-theme" && (subscription.event === null || subscription.event === "change")
+}
+
+function directSubscription(subscription: EndpointSubscription) {
+
+ return subscription.route === "end-end" && subscription.kind === "publish"
+}
+
+function isTrafficKind(value: unknown): value is TrafficKind {
+
+ return value === "publish" || value === "ask" || value === "answer"
+}
+
+function isHandleAddress(value: unknown): value is { identity: string, reference: string } {
+
+ return typeof value === "object" && value !== null && "identity" in value && "reference" in value
+ && typeof value.identity === "string" && typeof value.reference === "string"
+}
+
+interface WaitingQuestion {
+
+ route: string
+
+ values: unknown[]
+
+ question: string
+}
+
+interface TrafficSubscription {
+
+ count: number
+
+ stop: () => void
+}
diff --git a/source/client/view/desktop/client-host/client-traffic.ts b/source/client/view/desktop/client-host/client-traffic.ts
new file mode 100644
index 0000000..5dcc03f
--- /dev/null
+++ b/source/client/view/desktop/client-host/client-traffic.ts
@@ -0,0 +1,42 @@
+import TheLink from "@libs/the-link/the-link"
+import { type TrafficKind } from "@server/core/link-manager/auth-manager/process-manager/process-traffic"
+
+/** Desktop-local traffic routed only to subscribed client Process boundaries. */
+export default class ClientTraffic extends TheLink {
+
+ public emit(pane: string, route: string, ...values: unknown[]) {
+
+ const asking = values[0] === "wait"
+
+ const kind: TrafficKind = asking ? "ask" : "publish"
+
+ const eventIndex = route === "end-end" ? 3 : 2
+
+ const event = asking && typeof values[eventIndex] === "string" ? values[eventIndex] : values[0]
+
+ if (typeof event !== "string") return Promise.resolve([])
+
+ return this.$inbound.publish(this.event(pane, route, kind, event), {}, ...values)
+ }
+
+ public observe(pane: string, route: string, kind: TrafficKind, event: string | null, subscriber: Subscriber) {
+
+ const prefix = this.prefix(pane, route, kind)
+
+ if (event !== null) return this.$inbound.subscribe(prefix + encodeURIComponent(event), (delivery, ...values) => subscriber(delivery as object, ...values))
+
+ return this.$inbound.forwardTo((_event, delivery, ...values) => subscriber(delivery as object, ...values), prefix)
+ }
+
+ private prefix(pane: string, route: string, kind: TrafficKind) {
+
+ return `${encodeURIComponent(pane)}/${encodeURIComponent(route)}/${kind}/`
+ }
+
+ private event(pane: string, route: string, kind: TrafficKind, event: string) {
+
+ return this.prefix(pane, route, kind) + encodeURIComponent(event)
+ }
+}
+
+type Subscriber = (delivery: object, ...values: unknown[]) => unknown
diff --git a/source/client/view/desktop/client-host/host.ts b/source/client/view/desktop/client-host/host.ts
new file mode 100644
index 0000000..2ee33fc
--- /dev/null
+++ b/source/client/view/desktop/client-host/host.ts
@@ -0,0 +1,896 @@
+import { type WindowLayer } from "@phreshos/core"
+import { type Launch } from "@server/core/link-manager/auth-manager/program-manager/program-manager"
+import { type ProxyRequest } from "@server/core/protocol/proxy"
+import AuthManager from "@client/core/link-manager/auth-manager/auth-manager"
+import { type ClientBody, type ProxiedResponse, type ServedValue } from "@client/core/application"
+import { type PointerHost } from "./pointer"
+import { type TrafficKind } from "@server/core/link-manager/auth-manager/process-manager/process-traffic"
+import { sdkProcess, sdkProgram } from "./sdk-records"
+import { isPermissionName, type ProgramIconSize } from "@phreshos/core"
+
+/** A host answer whose stream must be transferred rather than cloned. */
+export class TransferredAnswer {
+
+ public constructor(public readonly result: unknown[], public readonly transfer: Transferable[]) { }
+}
+
+// The space windows are laid out in, as this desktop has it. Pixels,
+// because a program asking has already decided that shares will not
+// answer what it needs.
+export interface Space {
+
+ width: number
+
+ height: number
+}
+
+/**
+ * The desktop's vocabulary: what a client half may ask of the interface
+ * that frames it.
+ *
+ * A client half has the capabilities a server half has, narrowed to a
+ * world containing exactly one program — its own. That is the boundary
+ * between programs: there is no word here that could name another one.
+ * It is not a claim of network confinement — `fetch` deliberately reaches
+ * arbitrary URLs, but carries neither a Program subject nor the desktop's
+ * authorization.
+ *
+ * Program operations take no subject at all: the frame a message arrived
+ * in decides which program is meant, and what was asked is discarded.
+ * Operations on a Process handle name a sibling and all go through
+ * `sibling`, the one place a process identity from a pane is measured.
+ *
+ * A server half is the other thing and deliberately so: it runs
+ * arbitrary code already, so vocabulary costs it nothing.
+ *
+ * Answers cross to a sandboxed frame by structured clone, which carries
+ * no prototypes and refuses functions — so every word answers with plain
+ * values built here, never with an instance the desktop holds.
+ */
+export default function host(authManager: AuthManager, pane: string, space: (layer: WindowLayer) => Space, frameOwner: () => string | null, pointer: PointerHost) {
+
+ const { processManager, programManager } = authManager
+
+ function process() {
+
+ const found = processManager.processes.get(pane)
+
+ if (!found) throw new Error("The desktop does not know this process")
+
+ return found
+ }
+
+ // The gate.
+ //
+ // Program words resolve their subject from the frame and discard
+ // what was asked, which is why their isolation needs nothing checked:
+ // there is nothing to get wrong. Process-handle words take an
+ // identity — a sibling this program is running — and that identity
+ // is the first subject this side accepts from a pane.
+ //
+ // So it is measured, once, here: an identity a pane names must belong to
+ // a process of the program that pane is a face of. A stranger's is
+ // refused whether or not it exists, because whether it exists is
+ // itself something a pane may not learn.
+ function related(named: unknown) {
+
+ if (!isHandleAddress(named)) return null
+
+ const found = processManager.processes.get(named.identity)
+
+ return found?.reference === named.reference && found.program === process().program ? found : null
+ }
+
+ function sibling(named: unknown) {
+
+ const found = related(named)
+
+ if (!found) throw new Error("The desktop does not know this process")
+
+ return found
+ }
+
+ function window(named: unknown) {
+
+ const found = sibling(named).client?.window
+
+ if (!found) throw new Error("This process has no live client endpoint")
+
+ return found
+ }
+
+ function mutableWindow(named: unknown) {
+
+ const found = window(named)
+
+ if (found.layer === "wallpaper") throw new Error("A wallpaper Window is managed by the system")
+
+ return found
+ }
+
+ function declared(found: ReturnType<typeof process>, half: "server" | "client") {
+
+ return (programManager.programs.get(found.program)?.[half] ?? null) !== null
+ }
+
+ function owner(found: ReturnType<typeof process> | NonNullable<ReturnType<typeof process>["parent"]>) {
+
+ const program = programManager.programs.get(found.program)
+
+ if (!program) throw new Error("The desktop does not know this program")
+
+ return program
+ }
+
+ // One process record on every road. Nullable values carry the resolved
+ // shape as data; the SDK turns them into permanent addressed ends whose
+ // exists() reads the latest fact. A frame receives structured data,
+ // never the desktop's mutable record.
+ function record(found: ReturnType<typeof process> | NonNullable<ReturnType<typeof process>["parent"]>) {
+
+ return sdkProcess(found, owner(found))
+ }
+
+ // Which window is topmost *of its own layer*, worked out the way the
+ // desktop draws it: the shown one in that layer with the greatest
+ // depth. A pane is told whether that is itself and nothing more, so
+ // it learns no other window exists.
+ //
+ // This read across every layer until the layers existed, and the day
+ // they did it began answering `false` to a window a person was
+ // typing in because something in `over` had a larger number. Three
+ // places now work this out — here, the core, and the desktop — and
+ // all three read depth within one layer.
+ function front(layer: WindowLayer) {
+
+ let best: string | null = null
+
+ let depth = -Infinity
+
+ for (const entry of processManager.processes.values()) {
+
+ const window = entry.client?.window
+
+ if (!window || window.layer === "wallpaper" || window.minimized || window.layer !== layer || window.depth <= depth) continue
+
+ best = entry.identity
+
+ depth = window.depth
+ }
+
+ return best
+ }
+
+ return async function answer(word: unknown, ...args: unknown[]) {
+
+ if (word === "permission-granted") {
+
+ if (!isPermissionName(args[0])) throw new Error(`The system does not know the permission "${String(args[0])}"`)
+
+ return [await authManager.permissionGranted(pane, args[0])]
+ }
+
+ // When it started is a fact about this process, which a pane may
+ // already ask everything else about — it was missing on this side
+ // only because it was added on the other.
+ if (word === "process") return [record(process())]
+
+ if (word === "theme") return [authManager.linkManager.theme.value]
+
+ if (word === "exists") {
+
+ const target = args[1] === undefined ? process() : sibling(args[1])
+
+ if (args[0] === "server") return [target.server !== null]
+
+ if (args[0] === "client") return [target.client !== null]
+
+ throw new Error("A Process endpoint is server or client")
+ }
+
+ if (word === "start-endpoint") {
+
+ const target = args[0] === undefined ? process() : sibling(args[0])
+
+ if (args[1] !== "server" && args[1] !== "client") throw new Error("A Process endpoint is server or client")
+
+ await processManager.startEndpoint(target.identity, args[1], args[2] as never)
+
+ return [target.identity]
+ }
+
+ if (word === "stop-endpoint") {
+
+ const target = args[0] === undefined ? process() : sibling(args[0])
+
+ if (args[1] !== "server" && args[1] !== "client") throw new Error("A Process endpoint is server or client")
+
+ await processManager.stopEndpoint(target.identity, args[1])
+
+ return [target.identity]
+ }
+
+ if (word === "stop-current") {
+
+ await processManager.stopEndpoint(process().identity, "client")
+
+ return []
+ }
+
+ // A pane may receive a parent only inside the one program it is
+ // already a face of. No parent and a cross-program parent are
+ // the same `null`, so the relationship cannot reveal a stranger.
+ if (word === "parent") {
+
+ const target = args[0] === undefined ? process() : sibling(args[0])
+
+ const address = target.parent
+
+ if (!address) return [null]
+
+ const parent = processManager.processes.get(address.identity)
+
+ if (!parent || parent.reference !== address.reference) throw new Error("The parent Process no longer exists")
+
+ return [parent.program === process().program ? record(parent) : null]
+ }
+
+ // Whether a process a pane holds has ended.
+ //
+ // The one word here that answers about a process the desktop
+ // does not know, because that absence is its subject — and the
+ // one that does not go through `sibling`, because refusing would
+ // answer the question it exists for. It stays inside the same
+ // boundary by giving a stranger the same answer as a ghost: a
+ // pane may not learn that another program's process exists, so
+ // as far as one is concerned, it does not.
+ if (word === "exited") {
+
+ if (!isHandleAddress(args[0])) throw new Error("The boundary returned an invalid Process handle")
+
+ const found = processManager.processes.get(args[0].identity)
+
+ return [!found || found.reference !== args[0].reference || found.program !== process().program]
+ }
+
+ // Every instance of this pane's program, this one among them: a
+ // program's two halves must not disagree about how many of it
+ // are running. Nothing is named — the program is the frame's.
+ if (word === "processes") {
+
+ return [[...processManager.processes.values()].filter(entry => entry.program === process().program).map(record)]
+ }
+
+ // One process of this program by immutable identity or by its
+ // living program-local name. An exact identity always wins.
+ if (word === "program-process") {
+
+ const wanted = String(args[1])
+
+ const identified = processManager.processes.get(wanted)
+
+ if (identified?.program === process().program) return [record(identified)]
+
+ const named = [...processManager.processes.values()].find(entry => entry.program === process().program && entry.name === wanted)
+
+ return [named ? record(named) : null]
+ }
+
+ // Another instance of this pane's own program. The identity comes
+ // from the frame, so this word can start nothing else.
+ // The whole record, not the identity alone: a record invented at the
+ // kit's end knows only what the caller could already have
+ // guessed, which is how the process a program starts was the one
+ // process that did not know when it started.
+ if (word === "create-process") {
+
+ const started = await programManager.createProcess(process().program, args[1] as Launch, process().identity)
+
+ const startedRecord = processManager.processes.get(started)
+
+ if (!startedRecord) throw new Error("The desktop does not know this process")
+
+ return [record(startedRecord)]
+ }
+
+ // Every instance ended, the asker last. One implementation on the
+ // core serves this and a server half both.
+ if (word === "exit-all") return [await processManager.exitAll(process().program, pane)]
+
+ if (word === "observe") {
+
+ const half = args[2]
+
+ const kind = args[3]
+
+ const reportImpossible = args[5] === true
+
+ if (half !== "server" && half !== "client") throw new Error(`A process has no "${String(half)}" end`)
+
+ if (!isTrafficKind(kind)) throw new Error(`The host does not know the traffic kind "${String(kind)}"`)
+
+ const owner = frameOwner()
+
+ const target = args[1] === null ? process() : related(args[1])
+
+ // Callback subscriptions are synchronous and remain silent when
+ // their source is unavailable. waitFor() and events() identify
+ // themselves as fallible, giving their boundary a real rejection
+ // path when this synchronized Process record proves impossibility.
+ if (!owner || !target) {
+
+ if (reportImpossible) throw new Error("The desktop does not know this process")
+
+ return []
+ }
+
+ if (!declared(target, half)) {
+
+ if (reportImpossible) throw new Error(`This program declared no ${half} half`)
+
+ return []
+ }
+
+ const event = args[4]
+
+ if (event !== null && typeof event !== "string") return []
+
+ await processManager.observe(pane, owner, String(args[0]), address(target), half, kind, event, reportImpossible)
+
+ return []
+ }
+
+ if (word === "unobserve") {
+
+ const owner = frameOwner()
+
+ if (owner) await processManager.unobserve(pane, owner, String(args[0]))
+
+ return []
+ }
+
+ if (word === "follow") {
+
+ const half = args[2]
+
+ const reportImpossible = args[4] === true
+
+ if (half !== "server" && half !== "client") throw new Error(`A process has no "${String(half)}" end`)
+
+ const frame = frameOwner()
+
+ const target = args[1] === null ? process() : related(args[1])
+
+ if (!frame || !target) {
+
+ if (reportImpossible) throw new Error("The desktop does not know this process")
+
+ return []
+ }
+
+ if (!declared(target, half)) {
+
+ if (reportImpossible) throw new Error(`This program declared no ${half} half`)
+
+ return []
+ }
+
+ const event = args[3]
+
+ if (event !== null && typeof event !== "string") return []
+
+ await processManager.follow(pane, frame, String(args[0]), address(target), half, event, reportImpossible)
+
+ return []
+ }
+
+ if (word === "unfollow") {
+
+ const frame = frameOwner()
+
+ if (frame) await processManager.unfollow(pane, frame, String(args[0]))
+
+ return []
+ }
+
+ // Destinationless emission. The source comes from the frame boundary,
+ // so Program code cannot speak as a sibling or another Program.
+ if (word === "emit") {
+
+ if (typeof args[0] !== "string") return []
+
+ await processManager.emit(pane, args[0], args[1])
+
+ return []
+ }
+
+ // Into one end of a sibling's channel, and asking its server end.
+ // `sibling` is what makes the name safe; everything after it is
+ // the same act a server half performs.
+ if (word === "send") {
+
+ if (args[1] !== "server" && args[1] !== "client") throw new Error(`A process has no "${String(args[1])}" end`)
+
+ await processManager.publish(pane, sibling(args[0]).identity, args[1], args.slice(2))
+
+ return []
+ }
+
+ // Forwarded, and that is all. The pane wrote its own address
+ // into the question and holds its own deadline; this side has
+ // nothing to wait for and nothing to answer with.
+ if (word === "ask") {
+
+ if (args[1] !== "server") throw new Error("Only a server end can be asked — a client end has no one answerer")
+
+ await processManager.askOf(pane, sibling(args[0]).identity, args.slice(2))
+
+ return []
+ }
+
+ // What a launch said. An explicit subject is a held sibling; the
+ // empty subject used by `current.option()` is this frame's Process.
+ // The latter is resolved here rather than named by program code,
+ // exactly like every other `current` operation on this side.
+ if (word === "option") {
+
+ const found = args[0] === undefined ? process() : sibling(args[0])
+
+ return [found.options[String(args[1])]]
+ }
+
+ // What this pane's program says it is. Never a path: a client
+ // half has no disk, and where the machine put things is not a
+ // program's own word about itself.
+
+ if (word === "program") {
+
+ const program = programManager.programs.get(process().program)
+
+ if (!program) throw new Error("The desktop does not know this program")
+
+ // What it declared about its window comes too — the same
+ // kind of fact as its name, and what a window needs to know
+ // how large another instance of itself would open.
+ return [sdkProgram(program)]
+ }
+
+ // Requested content, not synchronized metadata. The frame supplies no
+ // Program identity: its owning Process is the structural authority,
+ // and the desktop asks the server for that Program's canonical text.
+ if (word === "api-docs") return [await programManager.apiDocs(process().program)]
+
+ // Icon bytes are requested only when this frame asks. The frame cannot
+ // provide an identity; its owning Process determines the Program.
+ if (word === "icon") return [await programManager.icon(process().program, args[0] as ProgramIconSize)]
+
+ // Whether this pane's Program is installed, and the operations
+ // that remove or forget it. Every subject is derived from the
+ // frame; no identity supplied by the pane crosses this gate.
+ //
+ // **No `fork` or `install`.** Both lay out a Program and belong to
+ // the server side; neither is a capability of a client face.
+ if (word === "installed") {
+
+ const program = programManager.programs.get(process().program)
+
+ return [program?.installed === true]
+ }
+
+ if (word === "uninstall") {
+
+ const program = programManager.programs.get(process().program)
+
+ if (!program) throw new Error("The desktop does not know this program")
+
+ return [await program.uninstall(args[1] === true, pane)]
+ }
+
+ if (word === "forget") {
+
+ const program = programManager.programs.get(process().program)
+
+ if (!program) throw new Error("The desktop does not know this program")
+
+ return [await program.forget(pane)]
+ }
+
+ // How this pane is shown. Not `depth`: that is how the desktop
+ // works out which window is at the front of its layer, and a
+ // value that can be read but never acted on is a mechanism
+ // rather than an answer. It is told `front`, which is what depth
+ // was being used to ask.
+ if (word === "window") {
+
+ const shown = window(args[0] ?? address(process()))
+
+ return [{
+
+ title: shown.title,
+
+ position: shown.position,
+
+ size: shown.size,
+
+ minimized: shown.minimized,
+
+ front: front(shown.layer) === pane,
+
+ // Which layer it lives in, and which of its own pages it
+ // was opened at. Both are the system's answers about
+ // this window: a launch may put the same program in a
+ // different layer or at a different page, so a program
+ // cannot read either off its own description.
+ layer: shown.layer,
+
+ location: shown.location,
+
+ surface: shown.surface
+ }]
+ }
+
+ if (word === "move") {
+
+ await mutableWindow(args[0]).move(args[1] as never)
+
+ return [pane]
+ }
+
+ if (word === "localMove") {
+
+ mutableWindow(args[0]).localMove(args[1] as never)
+
+ await processManager.changed()
+
+ return []
+ }
+
+ if (word === "resize") {
+
+ await mutableWindow(args[0]).resize(args[1] as never)
+
+ return [pane]
+ }
+
+ if (word === "localResize") {
+
+ mutableWindow(args[0]).localResize(args[1] as never)
+
+ await processManager.changed()
+
+ return []
+ }
+
+ if (word === "surfaceSet") {
+
+ await window(args[0]).setSurface(args[1] === undefined ? {} : args[1] as never)
+
+ return [pane]
+ }
+
+ if (word === "surfaceRemove") {
+
+ await window(args[0]).removeSurface()
+
+ return [pane]
+ }
+
+ if (word === "changeTitle") {
+
+ await mutableWindow(args[0]).changeTitle(String(args[1] ?? ""))
+
+ return [pane]
+ }
+
+ if (word === "raise") {
+
+ await mutableWindow(args[0]).raise()
+
+ return [pane]
+ }
+
+ if (word === "minimize") {
+
+ await mutableWindow(args[0]).minimize(args[1] !== false)
+
+ return [pane]
+ }
+
+ if (word === "exit") {
+
+ await sibling(args[0]).stop()
+
+ return [pane]
+ }
+
+ // This program's own store. The question names whose, as it does
+ // on the other side, and the answer ignores it: whose is resolved
+ // from the frame, never from what was asked. The application store
+ // has no generic host road at all.
+ if (word === "store") {
+
+ const [, operation, key, value, ttl] = args as [unknown, string, string, unknown, number | undefined]
+
+ return [await programManager.store(process().program, operation, key, value, ttl)]
+ }
+
+ // This program's places. Metadata operations remain ordinary values;
+ // file content takes the storage door so its bytes never enter The
+ // Link's serialization. The pane names neither a Program nor an
+ // authorization: this frame resolves to a Process, and that Process
+ // resolves to the Program whose area is opened.
+ if (word === "data" || word === "cache") {
+
+ const area: "data" | "cache" = word === "data" ? "data" : "cache"
+
+ const operation = String(args[1])
+
+ if (operation === "path" || operation === "resolve") throw new Error(`A client half is not told where its ${word} is`)
+
+ if (operation === "stream" || operation === "write") {
+
+ const joins = args[2]
+
+ if (!Array.isArray(joins) || joins.some(join => typeof join !== "string")) throw new Error("A storage path is a list of names")
+
+ const { control, controller } = cancellation(args[4], operation)
+
+ const request = { program: process().program, area, path: joins }
+
+ try {
+
+ if (operation === "write") {
+
+ if (!clientBody(args[3])) throw new Error("Writing takes bytes")
+
+ await authManager.linkManager.application.storageWrite(request, args[3], authManager.authorization, controller.signal)
+
+ control.close()
+
+ return []
+ }
+
+ const body = controlled(
+
+ await authManager.linkManager.application.storageStream(request, authManager.authorization, controller.signal),
+
+ controller,
+
+ control
+ )
+
+ return new TransferredAnswer([body], [body])
+ }
+
+ catch (exception) {
+
+ control.close()
+
+ throw exception
+ }
+ }
+
+ return [await programManager.area(process().program, word, operation, args.slice(2))]
+ }
+
+ // What this program has said. Whose, as everywhere here, is the
+ // frame's rather than the question's — so a window reads its own
+ // program's output and has no way to name another's.
+ //
+ // Nothing refuses a query that would write, because the
+ // connection behind it cannot: a pane's SQL reaches a read-only
+ // database, which is the same thing a server half's reaches.
+ if (word === "logs") {
+
+ return [await programManager.logs(process().program, String(args[1]), Array.isArray(args[2]) ? args[2] : [])]
+ }
+
+ // This program's own database. Whose is the frame's, as
+ // everywhere here, so a window reads and writes its own and has
+ // no way to name another's.
+ if (word === "database") {
+
+ return [await programManager.database(process().program, String(args[1]), Array.isArray(args[2]) ? args[2] : [])]
+ }
+
+ // How large this pane's own layer workspace is. The Window chooses
+ // the layer structurally; client code cannot inspect another layer.
+ // Ordinary windows use the desktop workspace, while bare layers use
+ // the browser viewport.
+ //
+ // The desktop's own answer, never the machine's: the same
+ // program may be shown in three sessions on three screens, so
+ // there is no one size to give a server half — which is why this
+ // word is only on this side and why the core does not hold it.
+ //
+ // The desktop gutter is private layout state. It never crosses into
+ // a Program endpoint as part of the surface value.
+ if (word === "surface") {
+
+ const shown = process().client?.window
+
+ if (!shown) throw new Error("This process has no live client endpoint")
+
+ return [space(shown.layer)]
+ }
+
+ // Coordinates use the same desktop display core as window geometry.
+ // Before this session has observed a pointer movement there is no
+ // position to invent, so the initial answer is null.
+ if (word === "pointer") {
+
+ if (await authManager.permissionGranted(pane, "pointer") !== true) throw new Error("Permission \"pointer\" is not granted")
+
+ return [pointer.position()]
+ }
+
+ // A pane normalizes any writable value before it reaches the frame wall:
+ // finite bytes retain their native Blob and an open stream is transferred.
+ // The desktop sends either through its authorized uploads door and returns
+ // only the served file's description.
+ if (word === "serve") {
+
+ if (!clientBody(args[0])) throw new Error("Serving takes bytes")
+
+ const description = args[1] as Partial<ServedValue> | null
+
+ if (!description || typeof description.type !== "string" || typeof description.extension !== "string" || !/^[a-z0-9]+$/.test(description.extension)) {
+
+ throw new Error("Serving takes a value description")
+ }
+
+ const { control, controller } = cancellation(args[2], "serve")
+
+ try {
+
+ const served = await authManager.linkManager.application.serve(
+
+ args[0],
+
+ { extension: description.extension, type: description.type },
+
+ authManager.authorization,
+
+ controller.signal
+ )
+
+ control.close()
+
+ return [served]
+ }
+
+ catch (exception) {
+
+ control.close()
+
+ throw exception
+ }
+ }
+
+ // The proxy is the desktop's authorized door, not this Process's.
+ // The pane provides only the target request and its body; the desktop's
+ // authorization is supplied here and never becomes a transmitted value.
+ if (word === "fetch") {
+
+ const { control, controller } = cancellation(args[2], "fetch")
+
+ let response: ProxiedResponse
+
+ try {
+
+ response = await authManager.linkManager.application.proxy(
+
+ args[0] as ProxyRequest,
+
+ args[1] as ClientBody | null,
+
+ authManager.authorization,
+
+ controller.signal
+ )
+ }
+
+ catch (exception) {
+
+ control.close()
+
+ throw exception
+ }
+
+ const body = response.body ? controlled(response.body, controller, control) : null
+
+ if (!body) control.close()
+
+ return new TransferredAnswer([{ ...response, body }], body ? [body] : [])
+ }
+
+ throw new Error(`The desktop does not know the word "${String(word)}"`)
+ }
+}
+
+function isTrafficKind(value: unknown): value is TrafficKind {
+
+ return value === "publish" || value === "ask" || value === "answer"
+}
+
+interface HandleAddress {
+
+ identity: string
+
+ reference: string
+}
+
+function address(process: { identity: string, reference: string }): HandleAddress {
+
+ return { identity: process.identity, reference: process.reference }
+}
+
+function isHandleAddress(value: unknown): value is HandleAddress {
+
+ return typeof value === "object" && value !== null && "identity" in value && "reference" in value
+ && typeof value.identity === "string" && typeof value.reference === "string"
+}
+
+function clientBody(value: unknown): value is ClientBody {
+
+ return value instanceof Blob || value instanceof ReadableStream
+}
+
+function cancellation(value: unknown, operation: string) {
+
+ if (!(value instanceof MessagePort)) throw new Error(`${operation} needs a cancellation channel`)
+
+ const controller = new AbortController()
+
+ value.addEventListener("message", () => controller.abort(), { once: true })
+
+ value.start()
+
+ return { control: value, controller }
+}
+
+function controlled(body: ReadableStream<Uint8Array>, controller: AbortController, control: MessagePort) {
+
+ const reader = body.getReader()
+
+ function close() {
+
+ control.close()
+ }
+
+ return new ReadableStream<Uint8Array>({
+
+ async pull(stream) {
+
+ try {
+
+ const next = await reader.read()
+
+ if (next.done) {
+
+ close()
+
+ stream.close()
+ }
+
+ else stream.enqueue(next.value)
+ }
+
+ catch (exception) {
+
+ close()
+
+ stream.error(exception)
+ }
+ },
+
+ async cancel(reason) {
+
+ controller.abort(reason)
+
+ close()
+
+ await reader.cancel(reason)
+ }
+ })
+}
diff --git a/source/client/view/desktop/client-host/pointer.ts b/source/client/view/desktop/client-host/pointer.ts
new file mode 100644
index 0000000..3a0d5c5
--- /dev/null
+++ b/source/client/view/desktop/client-host/pointer.ts
@@ -0,0 +1,66 @@
+import { type RefObject } from "react"
+import TheLink from "@libs/the-link/the-link"
+
+/**
+ * Pointer state belongs to one desktop session. Programs may observe it,
+ * but they neither own the listener nor receive another frame's lease.
+ */
+export default class DesktopPointer extends TheLink implements PointerHost {
+
+ private latest: PointerPosition | null = null
+
+ public constructor(private readonly desktop: RefObject<HTMLDivElement | null>) {
+
+ super()
+ }
+
+ public listen() {
+
+ const desktop = this.desktop.current
+
+ if (!desktop) return () => undefined
+
+ const move = (event: PointerEvent) => {
+
+ const bounds = desktop.getBoundingClientRect()
+
+ const position = {
+
+ x: event.clientX - bounds.left,
+
+ y: event.clientY - bounds.top
+ }
+
+ this.latest = position
+
+ this.$inbound.publish("move", position).catch(() => undefined)
+ }
+
+ desktop.addEventListener("pointermove", move)
+
+ return () => {
+
+ desktop.removeEventListener("pointermove", move)
+ }
+ }
+
+ public position() {
+
+ return this.latest
+ }
+
+}
+
+export interface PointerPosition {
+
+ x: number
+
+ y: number
+}
+
+export interface PointerHost {
+
+ position(): PointerPosition | null
+
+ readonly $inbound: TheLink["$inbound"]
+}
diff --git a/source/client/view/desktop/client-host/sdk-records.ts b/source/client/view/desktop/client-host/sdk-records.ts
new file mode 100644
index 0000000..d7af9d4
--- /dev/null
+++ b/source/client/view/desktop/client-host/sdk-records.ts
@@ -0,0 +1,66 @@
+import type Program from "@client/core/link-manager/auth-manager/program-manager/program"
+
+export interface SdkProcessSource {
+
+ reference: string
+
+ identity: string
+
+ name: string | null
+
+ program: string
+
+ options: Record<string, string>
+
+ startedAt: Date
+
+ server: unknown | null
+
+ client: unknown | null
+}
+
+/** Plain SDK Program state carried across the iframe boundary. */
+export function sdkProgram(program: Program) {
+
+ return {
+
+ reference: program.reference,
+
+ identity: program.identity,
+
+ installed: program.installed,
+
+ name: program.name,
+
+ version: program.version,
+
+ description: program.description,
+
+ server: program.server,
+
+ client: program.client
+ }
+}
+
+/** Plain Process state with its ownership chain embedded for synchronous navigation. */
+export function sdkProcess(process: SdkProcessSource, program: Program) {
+
+ return {
+
+ reference: process.reference,
+
+ identity: process.identity,
+
+ name: process.name,
+
+ program: sdkProgram(program),
+
+ options: process.options,
+
+ startedAt: process.startedAt,
+
+ server: process.server ? {} : null,
+
+ client: process.client ? {} : null
+ }
+}
diff --git a/source/client/view/desktop/desktop-display.tsx b/source/client/view/desktop/desktop-display.tsx
new file mode 100644
index 0000000..dda2a7e
--- /dev/null
+++ b/source/client/view/desktop/desktop-display.tsx
@@ -0,0 +1,54 @@
+import { type ReactNode, type Ref } from "react"
+import { desktopDisplayStyle } from "./geometry"
+
+/**
+ * The desktop's visible stacking structure. Each program layer owns a
+ * containing block; window geometry remains identical inside every layer.
+ */
+export default function DesktopDisplay({ wallpaper, underWindows, windows, overWindows, windowSurfaceRef, taskbar }: DesktopDisplayProps) {
+
+ return <main aria-label="Desktop display" className="grid min-h-0 grid-cols-1 grid-rows-[1fr_auto]" style={desktopDisplayStyle}>
+
+ <section aria-label="Desktop wallpaper" className="absolute inset-0 z-0 overflow-hidden">
+
+ {wallpaper}
+
+ </section>
+
+ <section aria-label="Under windows" className="pointer-events-none absolute inset-0 z-1 overflow-hidden">
+
+ {underWindows}
+
+ </section>
+
+ <section ref={windowSurfaceRef} aria-label="Windows" className="pointer-events-none relative z-2">
+
+ {windows}
+
+ </section>
+
+ <section aria-label="Over windows" className="pointer-events-none absolute inset-0 z-3 overflow-hidden">
+
+ {overWindows}
+
+ </section>
+
+ {taskbar}
+
+ </main>
+}
+
+interface DesktopDisplayProps {
+
+ wallpaper: ReactNode
+
+ underWindows: ReactNode
+
+ windows: ReactNode
+
+ overWindows: ReactNode
+
+ windowSurfaceRef: Ref<HTMLElement>
+
+ taskbar: ReactNode
+}
diff --git a/source/client/view/desktop/desktop-focus.ts b/source/client/view/desktop/desktop-focus.ts
new file mode 100644
index 0000000..7ae9119
--- /dev/null
+++ b/source/client/view/desktop/desktop-focus.ts
@@ -0,0 +1,86 @@
+import Process from "@client/core/link-manager/auth-manager/process-manager/process"
+import useWindows from "./window-manager/window-manager"
+import { type FocusEvent, type RefObject, useCallback, useRef } from "react"
+
+/** Focus transfer between the workspace, its windows and their taskbar items. */
+export default function useDesktopFocus(desktop: RefObject<HTMLDivElement | null>, windows: ReturnType<typeof useWindows>) {
+
+ const focusedWindow = useRef<string | null>(null)
+
+ const taskbarItems = useRef(new Map<string, HTMLButtonElement>())
+
+ const taskbarOrder = useRef(windows.panesByLayer.window.map(({ record }) => record))
+
+ taskbarOrder.current = windows.panesByLayer.window.map(({ record }) => record)
+
+ const taskbarItem = useCallback(function (record: Process, element: HTMLButtonElement | null) {
+
+ if (element) taskbarItems.current.set(record.identity, element)
+
+ else taskbarItems.current.delete(record.identity)
+
+ }, [])
+
+ const focusTaskbar = useCallback(function (record: Process) {
+
+ taskbarItems.current.get(record.identity)?.focus()
+
+ }, [])
+
+ const focusAfter = useCallback(function (record: Process) {
+
+ const records = taskbarOrder.current
+
+ const index = records.findIndex(entry => entry.identity === record.identity)
+
+ const candidates = index < 0 ? [] : [...records.slice(index + 1), ...records.slice(0, index).reverse()]
+
+ const target = candidates.map(entry => taskbarItems.current.get(entry.identity)).find(element => element)
+
+ if (target) target.focus()
+
+ else desktop.current?.focus()
+
+ }, [desktop])
+
+ const remember = useCallback(function (event: FocusEvent<HTMLDivElement>) {
+
+ const element = event.target instanceof Element ? event.target.closest<HTMLElement>("[data-process-window]") : null
+
+ focusedWindow.current = element?.dataset.processWindow ?? null
+
+ }, [])
+
+ // A process may minimize or end itself while its pane owns focus. The
+ // representation reports that it is leaving interaction before it hides
+ // or completes departure, so focus never remains in an inert subtree.
+ const unavailable = useCallback(function (record: Process, reason: "minimize" | "close") {
+
+ if (focusedWindow.current !== record.identity) return
+
+ focusedWindow.current = null
+
+ if (reason === "close") focusAfter(record)
+
+ else focusTaskbar(record)
+
+ }, [focusAfter, focusTaskbar])
+
+ const minimize = useCallback(function (record: Process, minimized: boolean) {
+
+ windows.minimize(record, minimized)
+
+ if (minimized) focusTaskbar(record)
+
+ }, [focusTaskbar, windows.minimize])
+
+ const close = useCallback(function (record: Process) {
+
+ focusAfter(record)
+
+ windows.close(record)
+
+ }, [focusAfter, windows.close])
+
+ return { taskbarItem, remember, unavailable, minimize, close }
+}
diff --git a/source/client/view/desktop/desktop.tsx b/source/client/view/desktop/desktop.tsx
new file mode 100644
index 0000000..44c8422
--- /dev/null
+++ b/source/client/view/desktop/desktop.tsx
@@ -0,0 +1,54 @@
+import ReactTunnel from "@libs/the-link/plugins/react-helper/react-tunnel"
+import useProperty from "@libs/the-link/plugins/react-helper/property-hook"
+import { TransmittedLinkManager } from "@server/core/link-manager/link-manager"
+import SocketLink from "@libs/the-link/plugins/client-link/socket-link"
+import LinkManager from "@client/core/link-manager/link-manager"
+import { ThemeProvider } from "@phreshos/react-ui"
+import Loading from "../components/loading"
+import { ApplicationContext, LinkManagerContext } from "../contexts"
+import usePromise from "@libs/react-promise"
+import Session from "./session/session"
+import { useCallback, useState } from "react"
+
+export default function () {
+
+ const application = ApplicationContext.useValue()
+
+ const [linkManager, setLinkManager] = useState<LinkManager | null>(null)
+
+ const internal = ReactTunnel.useFactory(application.clientLink.$internal)
+
+ internal.useSubscribe("subscribe", useCallback(function (socketLink: SocketLink<[TransmittedLinkManager, string]>) {
+
+ socketLink.$internal.subscribeOnce("unsubscribe", () => setLinkManager(null))
+
+ const [payload, connectionIdentity] = socketLink.payload
+
+ setLinkManager(new LinkManager(application, socketLink, payload, connectionIdentity))
+ }, [application]))
+
+ usePromise(async () => application.clientLink.subscribe(), [])
+
+ if (!linkManager) return <Loading />
+
+ return <ConnectedDesktop linkManager={linkManager} />
+}
+
+function ConnectedDesktop({ linkManager }: { linkManager: LinkManager }) {
+
+ const theme = useProperty(linkManager.theme)
+
+ return <LinkManagerContext.Provider value={linkManager}>
+
+ <ThemeProvider theme={theme}>
+
+ <div className="grid min-h-0" style={{ backgroundColor: theme.background }}>
+
+ <Session />
+
+ </div>
+
+ </ThemeProvider>
+
+ </LinkManagerContext.Provider>
+}
diff --git a/source/client/view/desktop/geometry.ts b/source/client/view/desktop/geometry.ts
new file mode 100644
index 0000000..c4f4204
--- /dev/null
+++ b/source/client/view/desktop/geometry.ts
@@ -0,0 +1,68 @@
+import { type CSSProperties } from "react"
+
+/**
+ * The gap between adjacent painted windows, in pixels. Each window uses
+ * half inside its own box; the ordinary workspace uses the other half
+ * at its boundary. Bare windows paint neither and receive this value
+ * through `host.surface.size()` so their own layout can align deliberately.
+ *
+ * The visible window edge, taskbar edge and Start Menu geometry derive from
+ * this value rather than restating its pixel or rem equivalent.
+ */
+export const desktopGutter = 12
+
+/** Paint inset for an ordinary window edge that touches no workspace boundary. */
+export const windowPaintInset = desktopGutter / 2
+
+/** The display core uses the same spacing between itself and its tracks. */
+export const desktopDisplayStyle = {
+
+ margin: desktopGutter,
+
+ gap: desktopGutter
+
+} satisfies CSSProperties
+
+/** The shared CSS anchor joining the taskbar and its Start Menu. */
+export const taskbarAnchorName = "--desktop-taskbar"
+
+/**
+ * The Start Menu stays in the browser's top layer while CSS anchor positioning
+ * keeps its geometry attached to the taskbar.
+ */
+export const startMenuStyle = {
+
+ positionAnchor: taskbarAnchorName,
+
+ top: "auto",
+
+ right: "auto",
+
+ bottom: `calc(anchor(top) + ${desktopGutter}px)`,
+
+ left: "anchor(left)",
+
+ maxHeight: `min(32rem, calc(100vh - var(--spacing-taskbar) - ${desktopGutter * 3}px))`,
+
+ width: `min(22rem, calc(100vw - ${desktopGutter * 2}px))`
+
+} satisfies CSSProperties
+
+/** System dialogs share the Start Menu's taskbar offset and center on it. */
+export const systemDialogStyle = {
+
+ positionAnchor: taskbarAnchorName,
+
+ top: "auto",
+
+ right: "auto",
+
+ bottom: `calc(anchor(top) + ${desktopGutter}px)`,
+
+ left: "anchor(center)",
+
+ translate: "-50% 0",
+
+ width: `min(28rem, calc(100vw - ${desktopGutter * 2}px))`
+
+} satisfies CSSProperties
diff --git a/source/client/view/desktop/program-access.tsx b/source/client/view/desktop/program-access.tsx
new file mode 100644
index 0000000..29ce905
--- /dev/null
+++ b/source/client/view/desktop/program-access.tsx
@@ -0,0 +1,117 @@
+import { type Dispatch, type SetStateAction, useLayoutEffect, useMemo, useRef } from "react"
+
+export type ProgramAccess = "checking" | "available" | "blocked"
+
+const programAccessRequest = "program-access-request"
+
+const programAccessMessage = "program-access"
+
+const timeout = 10_000
+
+/**
+ * Exercise the Program asset door from the same opaque origin as a real
+ * Program. A normal desktop fetch would be same-origin and would therefore
+ * prove nothing about the boundary that Program frames cross.
+ */
+export default function ({ door, setAccess }: ProgramAccessProbeProps) {
+
+ const frame = useRef<HTMLIFrameElement>(null)
+
+ const source = useMemo(function () {
+
+ const url = new URL(`${door}/ping`, window.location.href).href
+
+ return `<!doctype html><meta charset="utf-8"><script>
+let requested = false;
+let result;
+function report() {
+
+ if (requested && typeof result === "boolean") parent.postMessage([${JSON.stringify(programAccessMessage)}, result], "*");
+}
+addEventListener("message", event => {
+
+ if (event.data !== ${JSON.stringify(programAccessRequest)}) return;
+ requested = true;
+ report();
+});
+fetch(${JSON.stringify(url)}, { cache: "no-store" })
+ .then(response => { result = response.ok; report(); })
+ .catch(() => { result = false; report(); });
+</script>`
+
+ }, [door])
+
+ useLayoutEffect(function () {
+
+ const timer = window.setTimeout(() => setAccess("blocked"), timeout)
+
+ function receive(event: MessageEvent) {
+
+ if (event.source !== frame.current?.contentWindow) return
+
+ if (!Array.isArray(event.data) || event.data[0] !== programAccessMessage || typeof event.data[1] !== "boolean") return
+
+ window.clearTimeout(timer)
+
+ setAccess(event.data[1] ? "available" : "blocked")
+ }
+
+ window.addEventListener("message", receive)
+
+ return function () {
+
+ window.clearTimeout(timer)
+
+ window.removeEventListener("message", receive)
+ }
+
+ }, [setAccess])
+
+ return <iframe
+
+ ref={frame}
+
+ srcDoc={source}
+
+ title="Program asset compatibility check"
+
+ sandbox="allow-scripts"
+
+ onLoad={event => event.currentTarget.contentWindow?.postMessage(programAccessRequest, "*")}
+
+ hidden
+
+ />
+}
+
+interface ProgramAccessProbeProps {
+
+ door: string
+
+ setAccess: Dispatch<SetStateAction<ProgramAccess>>
+}
+
+export const blockedProgramDocument = `<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>Program unavailable</title>
+<style>
+ :root { color-scheme: light; font-family: system-ui, sans-serif; color: #233548; background: #eef8ff; }
+ * { box-sizing: border-box; }
+ body { min-height: 100vh; margin: 0; display: grid; place-items: center; padding: 2rem; background: radial-gradient(circle at top left, #ffffff 0, #eef8ff 48%, #dff4ff 100%); }
+ main { width: min(34rem, 100%); padding: 1.5rem; border: 1px solid rgba(89, 151, 191, .28); border-radius: 1.25rem; background: rgba(255, 255, 255, .82); box-shadow: 0 1.25rem 3rem rgba(47, 104, 145, .15); }
+ h1 { margin: 0 0 .75rem; font-size: 1.35rem; }
+ p { margin: 0; line-height: 1.6; }
+ p + p { margin-top: .8rem; color: #526b7f; font-size: .92rem; }
+</style>
+</head>
+<body>
+<main>
+ <h1>This Program cannot load</h1>
+ <p>The desktop is connected, but this hosting server blocks requests made by isolated Program frames.</p>
+ <p>Configure the server or reverse proxy to preserve the CORS headers on <code>/program/*</code>, including requests whose origin is <code>null</code>, then reload the desktop.</p>
+</main>
+</body>
+</html>`
diff --git a/source/client/view/desktop/program-frame.tsx b/source/client/view/desktop/program-frame.tsx
new file mode 100644
index 0000000..3cd24a4
--- /dev/null
+++ b/source/client/view/desktop/program-frame.tsx
@@ -0,0 +1,70 @@
+import Process from "@client/core/link-manager/auth-manager/process-manager/process"
+import ClientState from "@client/core/link-manager/auth-manager/process-manager/client-state"
+import { blockedProgramDocument, type ProgramAccess } from "./program-access"
+import { type ReactEventHandler, useCallback } from "react"
+
+export function programFrameSource(record: Process, client: ClientState, door: string) {
+
+ const window = client.window
+
+ return window.url
+
+ ? new URL(window.location.slice(1), window.url).href
+
+ : `${door}/${record.assetId}/assets/${window.location.slice(1)}`
+}
+
+/** The one sandboxed document representation shared by every Client role. */
+export default function ProgramFrame({ record, client, title, door, access, className = "size-full border-0", onFrame, onLoad }: ProgramFrameProps) {
+
+ const source = useCallback((element: HTMLIFrameElement | null) => onFrame(record.identity, element), [onFrame, record.identity])
+
+ if (access === "checking") return null
+
+ if (access === "blocked") return <iframe
+
+ srcDoc={blockedProgramDocument}
+
+ title={`${title}: Program unavailable`}
+
+ sandbox=""
+
+ className={className}
+
+ />
+
+ return <iframe
+
+ src={programFrameSource(record, client, door)}
+
+ title={title}
+
+ sandbox="allow-scripts"
+
+ className={className}
+
+ ref={source}
+
+ onLoad={onLoad}
+
+ />
+}
+
+interface ProgramFrameProps {
+
+ record: Process
+
+ client: ClientState
+
+ title: string
+
+ door: string
+
+ access: ProgramAccess
+
+ className?: string
+
+ onFrame: (identity: string, element: HTMLIFrameElement | null) => void
+
+ onLoad: ReactEventHandler<HTMLIFrameElement>
+}
diff --git a/source/client/view/desktop/programs/program-icon.ts b/source/client/view/desktop/programs/program-icon.ts
new file mode 100644
index 0000000..18f4650
--- /dev/null
+++ b/source/client/view/desktop/programs/program-icon.ts
@@ -0,0 +1,7 @@
+const icon = "icons/medium.png"
+
+/** The one browser location used for a program's desktop representation. */
+export default function programIcon(door: string, assetId: string) {
+
+ return `${door}/${assetId}/${icon}`
+}
diff --git a/source/client/view/desktop/programs/programs.ts b/source/client/view/desktop/programs/programs.ts
new file mode 100644
index 0000000..8518b86
--- /dev/null
+++ b/source/client/view/desktop/programs/programs.ts
@@ -0,0 +1,16 @@
+import ReactTunnel from "@libs/the-link/plugins/react-helper/react-tunnel"
+import { AuthManagerContext } from "../../contexts"
+
+/**
+ * The authorized view's programs: the list the peer re-emits on its
+ * tunnel, mirrored into React state — initial value derived from the
+ * born-whole Map, updates from the "/programs" event.
+ */
+export default function usePrograms() {
+
+ const authManager = AuthManagerContext.useValue()
+
+ const inbound = ReactTunnel.useFactory(authManager.programManager.$inbound)
+
+ return inbound.useFirstState("/programs", [...authManager.programManager.programs.values()]).filter(program => program.installed)
+}
diff --git a/source/client/view/desktop/session/credentials-form.tsx b/source/client/view/desktop/session/credentials-form.tsx
new file mode 100644
index 0000000..b7b357e
--- /dev/null
+++ b/source/client/view/desktop/session/credentials-form.tsx
@@ -0,0 +1,169 @@
+import { type AuthenticationState } from "@server/core/authentication/authentication"
+import { enterSurface, prepareSurfaceEntrance, restSurface } from "../../appearance/surface-presence"
+import { useReducedMotion } from "@libs/react-motion"
+import { GlassSurface, useTheme } from "@phreshos/react-ui"
+import { numericScale } from "@phreshos/core"
+import { obscuredBackground } from "../../components/loading"
+import Alert from "../../components/alert"
+import { type FormEvent, useLayoutEffect, useRef } from "react"
+
+/** The common username-and-password surface for registration and sign-in. */
+export default function CredentialsForm({ title, description, submitLabel, passwordAutocomplete, requirements, error, onSubmit }: CredentialsFormProps) {
+
+ const surface = useRef<HTMLFormElement>(null)
+
+ const reducedMotion = useReducedMotion()
+
+ const radius = numericScale(useTheme().radius)
+
+ const outerRadius = radius.large
+
+ const innerRadius = radius.medium
+
+ useLayoutEffect(function () {
+
+ prepareSurfaceEntrance(surface.current, reducedMotion)
+
+ const entrance = enterSurface(surface.current, reducedMotion)
+
+ return () => {
+
+ entrance?.kill()
+
+ restSurface(surface.current)
+ }
+
+ }, [reducedMotion])
+
+ function submit(event: FormEvent<HTMLFormElement>) {
+
+ event.preventDefault()
+
+ const data = new FormData(event.currentTarget)
+
+ onSubmit(String(data.get("username") ?? ""), String(data.get("password") ?? ""))
+ }
+
+ return <div className={`absolute inset-0 grid ${obscuredBackground}`}>
+
+ <form
+
+ ref={surface}
+
+ style={{ borderRadius: outerRadius }}
+
+ className="relative isolate m-auto grid w-[min(24rem,calc(100%-2rem))] grid-rows-[auto_minmax(0,1fr)] overflow-hidden border border-white/30 text-slate-800 shadow-window-active"
+
+ onSubmit={submit}
+
+ >
+
+ <GlassSurface aria-hidden="true" radius="inherit" className="pointer-events-none absolute inset-0" />
+
+ <header className="relative grid gap-1 px-5 py-4 text-shadow-chrome">
+
+ <h1 className="text-xl font-semibold">{title}</h1>
+
+ <p className="text-sm leading-5 text-slate-600/90">{description}</p>
+
+ </header>
+
+ <div style={{ borderRadius: innerRadius }} className="relative m-1.5 mt-0 grid gap-5 bg-white/25 p-5 shadow-window-content">
+
+ <div className="grid gap-4">
+
+ <label className="grid gap-1.5 text-sm font-medium">
+
+ Username
+
+ <input
+
+ name="username"
+
+ type="text"
+
+ autoComplete="username"
+
+ minLength={requirements?.username.minimumLength}
+
+ maxLength={requirements?.username.maximumLength}
+
+ required
+
+ autoFocus
+
+ className="h-10 rounded-lg border border-white/70 bg-white/70 px-3 font-normal shadow-window-content outline-none focus:border-sky-400 focus:ring-2 focus:ring-sky-200/80"
+
+ />
+
+ </label>
+
+ <label className="grid gap-1.5 text-sm font-medium">
+
+ Password
+
+ <input
+
+ name="password"
+
+ type="password"
+
+ autoComplete={passwordAutocomplete}
+
+ minLength={requirements?.password.minimumLength}
+
+ maxLength={requirements?.password.maximumLength}
+
+ required
+
+ className="h-10 rounded-lg border border-white/70 bg-white/70 px-3 font-normal shadow-window-content outline-none focus:border-sky-400 focus:ring-2 focus:ring-sky-200/80"
+
+ />
+
+ {requirements && <span className="font-normal text-slate-500">
+
+ Use at least {requirements.password.minimumLength} characters.
+
+ </span>}
+
+ </label>
+
+ </div>
+
+ {error && <Alert className="border-red-200/70 bg-red-50/70 text-sm text-red-700">{error}</Alert>}
+
+ <button
+
+ type="submit"
+
+ className="h-10 cursor-pointer rounded-lg border border-sky-700/35 from-sky-500 to-sky-600 px-4 font-medium text-white shadow-taskbar-control outline-none hover:from-sky-400 hover:to-sky-500 focus-visible:ring-2 focus-visible:ring-white/90"
+
+ >
+
+ {submitLabel}
+
+ </button>
+
+ </div>
+
+ </form>
+
+ </div>
+}
+
+interface CredentialsFormProps {
+
+ title: string
+
+ description: string
+
+ submitLabel: string
+
+ passwordAutocomplete: "current-password" | "new-password"
+
+ requirements?: AuthenticationState["requirements"]
+
+ error?: string | null
+
+ onSubmit: (username: string, password: string) => void
+}
diff --git a/source/client/view/desktop/session/register.tsx b/source/client/view/desktop/session/register.tsx
new file mode 100644
index 0000000..404ac72
--- /dev/null
+++ b/source/client/view/desktop/session/register.tsx
@@ -0,0 +1,69 @@
+import { type AuthenticationState, type RegistrationError } from "@server/core/authentication/authentication"
+import CredentialsForm from "./credentials-form"
+import { LinkManagerContext } from "../../contexts"
+import Loading from "../../components/loading"
+import usePromise from "@libs/react-promise"
+import useStorage from "@libs/storage-hook"
+
+export default function Register({ state, onClosed }: RegisterProps) {
+
+ const authorization = useStorage("authorization")
+
+ const linkManager = LinkManagerContext.useValue()
+
+ const registration = usePromise(async function (username: string, password: string) {
+
+ const response = await linkManager.register(username, password)
+
+ if ("authorization" in response) authorization.update(response.authorization)
+
+ else if (response.error === "registered") onClosed()
+
+ return "error" in response ? message(response.error, state) : null
+ })
+
+ if (registration.isPending) return <Loading />
+
+ return <CredentialsForm
+
+ title="Set up your system"
+
+ description="Create the credentials for this system's sole owner."
+
+ submitLabel="Register"
+
+ passwordAutocomplete="new-password"
+
+ requirements={state.requirements}
+
+ error={registration.exception ? String(registration.exception.current) : registration.solve?.current}
+
+ onSubmit={registration.safeExecute}
+
+ />
+}
+
+function message(error: RegistrationError, state: AuthenticationState) {
+
+ switch (error) {
+
+ case "registered": return "Registration is already complete."
+
+ case "username-required": return "Enter a username."
+
+ case "username-invalid": return `Use a username of at most ${state.requirements.username.maximumLength} characters without control characters.`
+
+ case "password-too-short": return `Use at least ${state.requirements.password.minimumLength} characters.`
+
+ case "password-too-long": return `Use at most ${state.requirements.password.maximumLength} characters.`
+
+ case "password-matches-username": return "The password must not be the username."
+ }
+}
+
+interface RegisterProps {
+
+ state: AuthenticationState
+
+ onClosed: () => void
+}
diff --git a/source/client/view/desktop/session/session.tsx b/source/client/view/desktop/session/session.tsx
new file mode 100644
index 0000000..e22e457
--- /dev/null
+++ b/source/client/view/desktop/session/session.tsx
@@ -0,0 +1,80 @@
+import AuthManager from "@client/core/link-manager/auth-manager/auth-manager"
+import { AuthManagerContext, LinkManagerContext } from "../../contexts"
+import Loading from "../../components/loading"
+import Alert from "../../components/alert"
+import usePromise from "@libs/react-promise"
+import useStorage from "@libs/storage-hook"
+import useCleanup from "@libs/cleanup-hook"
+import Workspace from "../workspace"
+import SignIn from "./sign-in"
+import Register from "./register"
+import { useState } from "react"
+import { type AuthenticationState } from "@server/core/authentication/authentication"
+import useProperty from "@libs/the-link/plugins/react-helper/property-hook"
+import { WallpaperStage } from "../../components/wallpaper"
+
+export default function () {
+
+ const authorization = useStorage("authorization")
+
+ const linkManager = LinkManagerContext.useValue()
+
+ const signInWallpaper = useProperty(linkManager.signInWallpaper)
+
+ const [revision, setRevision] = useState(0)
+
+ const sessionAuthenticate = usePromise<SessionResolution>(async function () {
+
+ const response = await linkManager.sessionAuthenticate(authorization.value)
+
+ if (!response) return { kind: "anonymous", authentication: await linkManager.authenticationState() }
+
+ const [authorizationToken, payload] = response
+
+ const authManager = new AuthManager(linkManager, authorizationToken, payload)
+
+ return { kind: "authenticated", authManager }
+
+ }, [authorization.value, revision])
+
+ useCleanup(() => {
+
+ if (sessionAuthenticate.solve?.kind === "authenticated") sessionAuthenticate.solve.authManager.disconnect()
+
+ }, [sessionAuthenticate.solve])
+
+ if (sessionAuthenticate.isPending) return <Loading />
+
+ if (sessionAuthenticate.exception) return <Alert className="m-auto w-fit">
+
+ {String(sessionAuthenticate.exception.current)}
+
+ </Alert>
+
+ if (!sessionAuthenticate.solve) return <Loading />
+
+ if (sessionAuthenticate.solve.kind === "anonymous") return sessionAuthenticate.solve.authentication.registered
+
+ ? <WallpaperStage file={signInWallpaper}><SignIn /></WallpaperStage>
+
+ : <WallpaperStage file={signInWallpaper}><Register state={sessionAuthenticate.solve.authentication} onClosed={() => setRevision(value => value + 1)} /></WallpaperStage>
+
+ return <AuthManagerContext.Provider value={sessionAuthenticate.solve.authManager}>
+
+ <Workspace />
+
+ </AuthManagerContext.Provider>
+}
+
+type SessionResolution = {
+
+ kind: "anonymous"
+
+ authentication: AuthenticationState
+
+} | {
+
+ kind: "authenticated"
+
+ authManager: AuthManager
+}
diff --git a/source/client/view/desktop/session/sign-in.tsx b/source/client/view/desktop/session/sign-in.tsx
new file mode 100644
index 0000000..a666cef
--- /dev/null
+++ b/source/client/view/desktop/session/sign-in.tsx
@@ -0,0 +1,39 @@
+import CredentialsForm from "./credentials-form"
+import { LinkManagerContext } from "../../contexts"
+import Loading from "../../components/loading"
+import usePromise from "@libs/react-promise"
+import useStorage from "@libs/storage-hook"
+
+export default function () {
+
+ const authorization = useStorage("authorization")
+
+ const linkManager = LinkManagerContext.useValue()
+
+ const signIn = usePromise(async function (username: string, password: string) {
+
+ const authorizationToken = await linkManager.signIn(username, password)
+
+ if (authorizationToken) authorization.update(authorizationToken)
+
+ return !!authorizationToken
+ })
+
+ if (signIn.isPending) return <Loading />
+
+ return <CredentialsForm
+
+ title="Sign in"
+
+ description="Enter the credentials for this system's owner."
+
+ submitLabel="Sign in"
+
+ passwordAutocomplete="current-password"
+
+ error={signIn.exception ? String(signIn.exception.current) : signIn.solve && !signIn.solve.current ? "The username or password is incorrect." : null}
+
+ onSubmit={signIn.safeExecute}
+
+ />
+}
diff --git a/source/client/view/desktop/start-menu/programs-section.tsx b/source/client/view/desktop/start-menu/programs-section.tsx
new file mode 100644
index 0000000..48f53c3
--- /dev/null
+++ b/source/client/view/desktop/start-menu/programs-section.tsx
@@ -0,0 +1,48 @@
+import LauncherItem from "../taskbar/launcher-item"
+import programIcon from "../programs/program-icon"
+import usePrograms from "../programs/programs"
+import { ApplicationContext } from "../../contexts"
+
+interface ProgramsSectionProps {
+
+ onChoose: () => void
+}
+
+/** The installed-program section of the Start Menu. */
+export default function ProgramsSection({ onChoose }: ProgramsSectionProps) {
+
+ const application = ApplicationContext.useValue()
+
+ const programs = usePrograms()
+
+ return <section aria-label="Programs" className="grid gap-1">
+
+ {programs.length
+
+ ? programs.map(record => <LauncherItem
+
+ key={record.identity}
+
+ label={record.name}
+
+ icon={programIcon(application.doors.program, record.assetId)}
+
+ description={record.description}
+
+ onClick={() => {
+
+ onChoose()
+
+ record.createProcess().catch(console.error)
+ }}
+
+ >
+
+ {record.name}
+
+ </LauncherItem>)
+
+ : <p className="px-3 py-8 text-center text-sm text-slate-600">No installed programs</p>}
+
+ </section>
+}
diff --git a/source/client/view/desktop/start-menu/start-menu.tsx b/source/client/view/desktop/start-menu/start-menu.tsx
new file mode 100644
index 0000000..28af84b
--- /dev/null
+++ b/source/client/view/desktop/start-menu/start-menu.tsx
@@ -0,0 +1,33 @@
+import logo from "@/assets/bundled/logo.png"
+import { memo } from "react"
+import { startMenuStyle } from "../geometry"
+import Launcher from "../taskbar/launcher"
+import ProgramsSection from "./programs-section"
+
+/** The taskbar entry point for current and future desktop actions. */
+export default memo(function StartMenu() {
+
+ return <Launcher
+
+ label="Start Menu"
+
+ trigger={<>
+
+ <img src={logo} alt="" className="size-5 shrink-0" />
+
+ <span className="hidden text-xs font-semibold sm:inline">Start Menu</span>
+
+ </>}
+
+ style={startMenuStyle}
+
+ >
+
+ {close => <div className="grid max-h-full overflow-y-auto p-2">
+
+ <ProgramsSection onChoose={close} />
+
+ </div>}
+
+ </Launcher>
+})
diff --git a/source/client/view/desktop/taskbar/launcher-item.tsx b/source/client/view/desktop/taskbar/launcher-item.tsx
new file mode 100644
index 0000000..ccc4bf5
--- /dev/null
+++ b/source/client/view/desktop/taskbar/launcher-item.tsx
@@ -0,0 +1,42 @@
+import { ComponentProps, ReactNode } from "react"
+
+/** One action in a launcher, without knowing what it launches. */
+export default function ({ icon, label, description, children, className, ...props }: LauncherItemProps) {
+
+ return <button
+
+ {...props}
+
+ type="button"
+
+ className={`group grid w-full grid-cols-[auto_minmax(0,1fr)] items-center gap-3 rounded-xl px-3 py-2 text-left outline-none hover:bg-white/45 focus-visible:bg-white/55 focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-white/85 active:bg-white/65 ${className ?? ""}`}
+
+ >
+
+ <span className="grid size-9 place-items-center overflow-hidden rounded-xl border border-white/55 bg-white/25 text-base font-semibold text-slate-700 shadow-launcher-icon">
+
+ <img src={icon} alt="" draggable={false} className="size-full object-contain p-1" />
+
+ </span>
+
+ <span className="min-w-0">
+
+ <span className="block truncate text-sm font-medium">{children}</span>
+
+ {description && <span className="block truncate text-xs text-slate-600/80">{description}</span>}
+
+ </span>
+
+ </button>
+}
+
+export interface LauncherItemProps extends ComponentProps<"button"> {
+
+ icon: string
+
+ label: string
+
+ description?: string | null
+
+ children: ReactNode
+}
diff --git a/source/client/view/desktop/taskbar/launcher.tsx b/source/client/view/desktop/taskbar/launcher.tsx
new file mode 100644
index 0000000..455a494
--- /dev/null
+++ b/source/client/view/desktop/taskbar/launcher.tsx
@@ -0,0 +1,137 @@
+import { ComponentProps, ReactNode, useCallback, useEffect, useId, useRef, useState } from "react"
+import { enterSurface, prepareSurfaceEntrance, restSurface } from "../../appearance/surface-presence"
+import { useReducedMotion } from "@libs/react-motion"
+import { useTheme } from "@phreshos/react-ui"
+import { numericScale } from "@phreshos/core"
+import TaskbarSurface, { taskbarSurfaceClassName } from "./taskbar-surface"
+import TaskbarButton from "./taskbar-button"
+
+/**
+ * A button and the dismissible surface it opens. Placement, contents and
+ * what selecting an item means belong to the caller.
+ */
+export default function ({ label, trigger, children, className, style, ...props }: LauncherProps) {
+
+ const id = useId()
+
+ const surface = useRef<HTMLElement>(null)
+
+ const reducedMotion = useReducedMotion()
+
+ const radius = numericScale(useTheme().radius).large
+
+ const [open, setOpen] = useState(false)
+
+ const close = useCallback(function () {
+
+ const element = surface.current
+
+ if (element?.matches(":popover-open")) element.hidePopover()
+
+ }, [])
+
+ useEffect(function () {
+
+ // A Program frame is a separate document, so its pointer events cannot
+ // participate in this document's native popover light dismissal. The
+ // browser does expose the focus crossing at the browsing-context wall:
+ // the iframe becomes this document's active element.
+ function closeForProgramFrame() {
+
+ if (document.activeElement instanceof HTMLIFrameElement) close()
+ }
+
+ window.addEventListener("blur", closeForProgramFrame)
+
+ return () => window.removeEventListener("blur", closeForProgramFrame)
+
+ }, [close])
+
+ return <>
+
+ <TaskbarButton
+
+ type="button"
+
+ aria-controls={id}
+
+ aria-expanded={open}
+
+ aria-haspopup="dialog"
+
+ aria-label={label}
+
+ title={label}
+
+ popoverTarget={id}
+
+ >
+
+ {trigger}
+
+ </TaskbarButton>
+
+ <section
+
+ {...props}
+
+ ref={surface}
+
+ id={id}
+
+ role="dialog"
+
+ popover="auto"
+
+ aria-labelledby={`${id}-label`}
+
+ tabIndex={-1}
+
+ style={{ ...style, borderRadius: radius }}
+
+ className={`${taskbarSurfaceClassName} hidden grid-rows-[auto_minmax(0,1fr)] open:grid ${className ?? ""}`}
+
+ onBeforeToggle={event => {
+
+ if (event.newState === "open") prepareSurfaceEntrance(event.currentTarget, reducedMotion)
+ }}
+
+ onToggle={event => {
+
+ const opening = event.newState === "open"
+
+ setOpen(opening)
+
+ if (opening) {
+
+ enterSurface(event.currentTarget, reducedMotion)
+
+ const focusTarget = event.currentTarget.querySelector<HTMLElement>("button:not(:disabled),a[href]") ?? event.currentTarget
+
+ focusTarget.focus()
+ }
+
+ else restSurface(event.currentTarget)
+ }}
+
+ >
+
+ <TaskbarSurface label={label} labelId={`${id}-label`}>
+
+ {children(close)}
+
+ </TaskbarSurface>
+
+ </section>
+
+ </>
+}
+
+export interface LauncherProps extends Omit<ComponentProps<"section">, "children" | "id" | "onBeforeToggle" | "onToggle" | "popover"> {
+
+ label: string
+
+ trigger: ReactNode
+
+ children: (close: () => void) => ReactNode
+}
diff --git a/source/client/view/desktop/taskbar/overflow-row.tsx b/source/client/view/desktop/taskbar/overflow-row.tsx
new file mode 100644
index 0000000..6eb5b6f
--- /dev/null
+++ b/source/client/view/desktop/taskbar/overflow-row.tsx
@@ -0,0 +1,144 @@
+import { ComponentProps, useId, useLayoutEffect, useRef, useState } from "react"
+import { useReducedMotion } from "@libs/react-motion"
+
+/** A horizontal row that reveals its own overflow without owning its items. */
+export default function OverflowRow({ children, backwardLabel = "Scroll backward", forwardLabel = "Scroll forward", className, ...props }: OverflowRowProps) {
+
+ const reducedMotion = useReducedMotion()
+
+ const container = useRef<HTMLDivElement>(null)
+
+ const viewport = useRef<HTMLDivElement>(null)
+
+ const content = useRef<HTMLDivElement>(null)
+
+ const viewportId = useId()
+
+ const [edges, setEdges] = useState({ overflowing: false, start: true, end: true })
+
+ useLayoutEffect(function () {
+
+ const box = container.current
+
+ const view = viewport.current
+
+ const row = content.current
+
+ if (!box || !view || !row) return
+
+ function measure() {
+
+ const end = Math.max(0, view!.scrollWidth - view!.clientWidth)
+
+ const next = {
+
+ // Compare natural content with the whole row, not the
+ // viewport after controls take their places. That avoids
+ // controls keeping themselves alive after content shrinks.
+ overflowing: row!.scrollWidth > box!.clientWidth + 1,
+
+ start: view!.scrollLeft <= 1,
+
+ end: view!.scrollLeft >= end - 1
+ }
+
+ setEdges(current => current.overflowing === next.overflowing && current.start === next.start && current.end === next.end ? current : next)
+ }
+
+ const observer = new ResizeObserver(measure)
+
+ observer.observe(box)
+
+ observer.observe(view)
+
+ observer.observe(row)
+
+ view.addEventListener("scroll", measure, { passive: true })
+
+ measure()
+
+ return () => {
+
+ observer.disconnect()
+
+ view.removeEventListener("scroll", measure)
+ }
+
+ }, [])
+
+ function scroll(direction: -1 | 1) {
+
+ const view = viewport.current
+
+ if (!view) return
+
+ view.scrollBy({ left: direction * view.clientWidth * 0.8, behavior: reducedMotion ? "auto" : "smooth" })
+ }
+
+ return <div ref={container} role="group" className={`flex min-w-0 items-center gap-1 ${className ?? ""}`} {...props}>
+
+ {edges.overflowing && <ScrollButton label={backwardLabel} controls={viewportId} direction="backward" disabled={edges.start} reducedMotion={reducedMotion} onClick={() => scroll(-1)} />}
+
+ <div id={viewportId} ref={viewport} className="-m-2 min-w-0 flex-1 overflow-x-auto p-2 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
+
+ <div ref={content} className="flex w-max min-w-full items-center gap-1.5">
+
+ {children}
+
+ </div>
+
+ </div>
+
+ {edges.overflowing && <ScrollButton label={forwardLabel} controls={viewportId} direction="forward" disabled={edges.end} reducedMotion={reducedMotion} onClick={() => scroll(1)} />}
+
+ </div>
+}
+
+function ScrollButton({ label, controls, direction, disabled, reducedMotion, onClick }: ScrollButtonProps) {
+
+ return <button
+
+ type="button"
+
+ aria-label={label}
+
+ aria-controls={controls}
+
+ disabled={disabled}
+
+ onClick={onClick}
+
+ className={`grid size-7 shrink-0 place-items-center rounded-lg border border-white/45 bg-white/55 text-slate-700 shadow-sm outline-none backdrop-blur-sm focus-visible:ring-2 focus-visible:ring-white disabled:opacity-35 ${reducedMotion ? "" : "transition-colors hover:bg-white/80 active:scale-95"}`}
+
+ >
+
+ <svg aria-hidden="true" viewBox="0 0 12 12" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" className="size-3">
+
+ <path d={direction === "backward" ? "m7.5 2.5-3.5 3.5 3.5 3.5" : "m4.5 2.5 3.5 3.5-3.5 3.5"} />
+
+ </svg>
+
+ </button>
+}
+
+interface OverflowRowProps extends ComponentProps<"div"> {
+
+ backwardLabel?: string
+
+ forwardLabel?: string
+}
+
+interface ScrollButtonProps {
+
+ label: string
+
+ controls: string
+
+ direction: "backward" | "forward"
+
+ disabled: boolean
+
+ reducedMotion: boolean
+
+ onClick: () => void
+}
diff --git a/source/client/view/desktop/taskbar/sign-out.tsx b/source/client/view/desktop/taskbar/sign-out.tsx
new file mode 100644
index 0000000..a30f19e
--- /dev/null
+++ b/source/client/view/desktop/taskbar/sign-out.tsx
@@ -0,0 +1,24 @@
+import useStorage from "@libs/storage-hook"
+import { ComponentProps, memo } from "react"
+import TaskbarButton from "./taskbar-button"
+
+export default memo(function (props: ComponentProps<typeof TaskbarButton>) {
+
+ const authorization = useStorage("authorization")
+
+ return <TaskbarButton
+
+ aria-label="Sign out"
+
+ title="Sign out"
+
+ onClick={authorization.remove}
+
+ {...props}
+
+ >
+
+ <span className="hidden text-taskbar-label font-medium sm:inline">Sign out</span>
+
+ </TaskbarButton>
+})
diff --git a/source/client/view/desktop/taskbar/system-dialogs.tsx b/source/client/view/desktop/taskbar/system-dialogs.tsx
new file mode 100644
index 0000000..ac6e850
--- /dev/null
+++ b/source/client/view/desktop/taskbar/system-dialogs.tsx
@@ -0,0 +1,207 @@
+import { type PermissionChoice, type PermissionDialog, type ServerCrashDialog } from "@server/core/dialog-manager"
+import ReactTunnel from "@libs/the-link/plugins/react-helper/react-tunnel"
+import { enterSurface, prepareSurfaceEntrance, restSurface } from "../../appearance/surface-presence"
+import { systemDialogStyle } from "../geometry"
+import { useReducedMotion } from "@libs/react-motion"
+import { useTheme } from "@phreshos/react-ui"
+import { numericScale } from "@phreshos/core"
+import { useEffect, useId, useRef } from "react"
+import { AuthManagerContext } from "../../contexts"
+import TaskbarSurface, { taskbarSurfaceClassName } from "./taskbar-surface"
+import TaskbarButton from "./taskbar-button"
+
+/** Taskbar-owned presentation of the system's authoritative dialog queue. */
+export default function SystemDialogs() {
+
+ const authManager = AuthManagerContext.useValue()
+
+ const dialogManager = authManager.dialogManager
+
+ const inbound = ReactTunnel.useFactory(dialogManager.$inbound)
+
+ const dialogs = inbound.useFirstState("/dialogs", dialogManager.list())
+
+ const dialog = dialogs[0]
+
+ const dialogIdentity = dialog?.identity
+
+ const surface = useRef<HTMLDialogElement>(null)
+
+ const title = useId()
+
+ const description = useId()
+
+ const reducedMotion = useReducedMotion()
+
+ const radius = numericScale(useTheme().radius).large
+
+ useEffect(function () {
+
+ const element = surface.current
+
+ if (!dialog || !element || element.open) return
+
+ prepareSurfaceEntrance(element, reducedMotion)
+
+ element.showModal()
+
+ enterSurface(element, reducedMotion)
+
+ return function () {
+
+ restSurface(element)
+
+ if (element.open) element.close()
+ }
+
+ }, [dialogIdentity, reducedMotion])
+
+ if (!dialog) return null
+
+ return <dialog
+
+ ref={surface}
+
+ role="alertdialog"
+
+ aria-modal="true"
+
+ aria-labelledby={title}
+
+ aria-describedby={description}
+
+ style={{ ...systemDialogStyle, borderRadius: radius }}
+
+ onCancel={event => event.preventDefault()}
+
+ className={`${taskbarSurfaceClassName} grid grid-rows-[auto_minmax(0,1fr)] backdrop:bg-transparent`}
+
+ >
+
+ <TaskbarSurface label={dialog.kind === "permission" ? "Permission request" : "System error"} labelId={title}>
+
+ {dialog.kind === "permission"
+
+ ? <PermissionRequest dialog={dialog} description={description} decide={choice => dialogManager.resolvePermission(dialog.identity, choice)} />
+
+ : <CrashReport dialog={dialog} description={description} acknowledge={() => dialogManager.acknowledge(dialog.identity)} />}
+
+ </TaskbarSurface>
+
+ </dialog>
+}
+
+function PermissionRequest({ dialog, description, decide }: PermissionRequestProps) {
+
+ return <div className="grid gap-5 p-4">
+
+ <div className="grid grid-cols-[auto_minmax(0,1fr)] items-start gap-3">
+
+ <span aria-hidden="true" className="grid size-8 place-items-center rounded-full border border-sky-600/25 bg-sky-500/15 text-sm font-medium text-sky-800">?</span>
+
+ <div className="grid gap-1">
+
+ <h3 className="text-base font-medium text-slate-900">{dialog.program.name} needs permission</h3>
+
+ <p id={description} className="text-sm leading-6 text-slate-600">{permissionDescription(dialog)}</p>
+
+ </div>
+
+ </div>
+
+ <div className="flex flex-wrap justify-end gap-2">
+
+ <TaskbarButton small onClick={() => decide(false).catch(() => undefined)}>Deny</TaskbarButton>
+
+ <TaskbarButton small autoFocus onClick={() => decide(null).catch(() => undefined)}>Later</TaskbarButton>
+
+ <TaskbarButton small onClick={() => decide("process").catch(() => undefined)}>Allow for this Process</TaskbarButton>
+
+ <TaskbarButton small onClick={() => decide("always").catch(() => undefined)}>Always allow</TaskbarButton>
+
+ </div>
+
+ </div>
+}
+
+function CrashReport({ dialog, description, acknowledge }: CrashReportProps) {
+
+ return <div className="grid gap-5 p-4">
+
+ <div className="grid grid-cols-[auto_minmax(0,1fr)] items-start gap-3">
+
+ <span aria-hidden="true" className="grid size-8 place-items-center rounded-full border border-rose-600/25 bg-rose-500/15 text-lg font-medium text-rose-700">!</span>
+
+ <div className="grid gap-1">
+
+ <h3 className="text-base font-medium text-slate-900">Server endpoint crashed</h3>
+
+ <p id={description} className="text-sm leading-6 text-slate-600">{crashDescription(dialog)}</p>
+
+ </div>
+
+ </div>
+
+ <div className="grid justify-end">
+
+ <TaskbarButton
+
+ small
+
+ autoFocus
+
+ onClick={() => acknowledge().catch(() => undefined)}
+
+ className="font-medium"
+
+ >
+
+ I understand
+
+ </TaskbarButton>
+
+ </div>
+
+ </div>
+}
+
+function permissionDescription(dialog: PermissionDialog) {
+
+ if (dialog.permission === "pointer") return "Allow this Program to read and listen to pointer movement across the desktop."
+
+ return unknownPermission(dialog.permission)
+}
+
+function unknownPermission(permission: never): never {
+
+ throw new Error(`The system has no description for permission "${permission}"`)
+}
+
+function crashDescription(dialog: ServerCrashDialog) {
+
+ const endpoint = dialog.process.name ? `the “${dialog.process.name}” Process’s server endpoint` : "its server endpoint"
+
+ if (dialog.signal) return `${dialog.program.name} stopped unexpectedly because ${endpoint} was terminated by ${dialog.signal}.`
+
+ if (dialog.code !== null) return `${dialog.program.name} stopped unexpectedly because ${endpoint} exited with code ${dialog.code}.`
+
+ return `${dialog.program.name} stopped because ${endpoint} ended unexpectedly.`
+}
+
+interface PermissionRequestProps {
+
+ dialog: PermissionDialog
+
+ description: string
+
+ decide(choice: PermissionChoice): Promise<void>
+}
+
+interface CrashReportProps {
+
+ dialog: ServerCrashDialog
+
+ description: string
+
+ acknowledge(): Promise<void>
+}
diff --git a/source/client/view/desktop/taskbar/taskbar-button.tsx b/source/client/view/desktop/taskbar/taskbar-button.tsx
new file mode 100644
index 0000000..1ead124
--- /dev/null
+++ b/source/client/view/desktop/taskbar/taskbar-button.tsx
@@ -0,0 +1,23 @@
+import { useReducedMotion } from "@libs/react-motion"
+import { ComponentProps } from "react"
+
+/** A compact taskbar control whose contents define its meaning. */
+export default function TaskbarButton({ small = false, className, ...props }: TaskbarButtonProps) {
+
+ const reducedMotion = useReducedMotion()
+
+ return <button
+
+ type="button"
+
+ className={`grid shrink-0 cursor-pointer select-none grid-flow-col auto-cols-max place-items-center rounded-lg border border-white/45 bg-white/30 text-slate-800 shadow-taskbar-control outline-none hover:bg-white/50 focus-visible:ring-2 focus-visible:ring-white/85 ${small ? "h-7 gap-1 px-2 text-xs" : "h-8 gap-1.5 px-2"} ${reducedMotion ? "" : "transition-colors duration-100 active:scale-95"} ${className ?? ""}`}
+
+ {...props}
+
+ />
+}
+
+interface TaskbarButtonProps extends ComponentProps<"button"> {
+
+ small?: boolean
+}
diff --git a/source/client/view/desktop/taskbar/taskbar-item.tsx b/source/client/view/desktop/taskbar/taskbar-item.tsx
new file mode 100644
index 0000000..462ed8c
--- /dev/null
+++ b/source/client/view/desktop/taskbar/taskbar-item.tsx
@@ -0,0 +1,42 @@
+import { ComponentProps } from "react"
+import { useReducedMotion } from "@libs/react-motion"
+
+/**
+ * A pressable item with a raised state. What "raised" means is the caller's.
+ */
+export default function ({ active = false, icon, children, className, ...props }: TaskbarItemProps) {
+
+ const reducedMotion = useReducedMotion()
+
+ const surface = active
+
+ ? "border-white/75 bg-gradient-to-b from-white/70 to-white/40 text-slate-900 shadow-taskbar-item-active"
+
+ : "border-white/35 bg-white/20 text-slate-800 shadow-taskbar-item hover:border-white/55 hover:bg-white/40"
+
+ return <button
+
+ aria-pressed={active}
+
+ className={`relative flex h-8 max-w-40 shrink-0 scroll-mx-8 cursor-pointer select-none items-center gap-1.5 overflow-hidden rounded-lg border px-2.5 text-xs font-medium text-shadow-chrome outline-none focus-visible:ring-2 focus-visible:ring-white/80 ${reducedMotion ? "" : "transition-colors duration-100 active:scale-95"} ${surface} ${className ?? ""}`}
+
+ {...props}
+
+ >
+
+ <img src={icon} alt="" draggable={false} className="size-4 shrink-0 rounded-sm object-contain" />
+
+ <span className="truncate">{children}</span>
+
+ {active && <span aria-hidden="true" className="absolute inset-x-3 bottom-0 h-0.5 rounded-full bg-sky-500 shadow-taskbar-indicator" />}
+
+ </button>
+}
+
+export interface TaskbarItemProps extends ComponentProps<"button"> {
+
+ active?: boolean
+
+ // Every system entry has either its Program icon or the system default.
+ icon: string
+}
diff --git a/source/client/view/desktop/taskbar/taskbar-separator.tsx b/source/client/view/desktop/taskbar/taskbar-separator.tsx
new file mode 100644
index 0000000..202ef0d
--- /dev/null
+++ b/source/client/view/desktop/taskbar/taskbar-separator.tsx
@@ -0,0 +1,5 @@
+/** A structural break between groups of taskbar controls. */
+export default function TaskbarSeparator() {
+
+ return <div aria-hidden="true" className="h-6 w-px bg-white/35 shadow-taskbar-separator" />
+}
diff --git a/source/client/view/desktop/taskbar/taskbar-surface.tsx b/source/client/view/desktop/taskbar/taskbar-surface.tsx
new file mode 100644
index 0000000..e4afdeb
--- /dev/null
+++ b/source/client/view/desktop/taskbar/taskbar-surface.tsx
@@ -0,0 +1,34 @@
+import { ReactNode } from "react"
+import { GlassSurface, useTheme } from "@phreshos/react-ui"
+import { numericScale } from "@phreshos/core"
+
+/** The window-material shell shared by surfaces opened from the taskbar. */
+export const taskbarSurfaceClassName = "m-0 isolate overflow-hidden border-0 bg-transparent p-0 text-slate-800 shadow-window-active outline-none"
+
+export default function TaskbarSurface({ label, labelId, children }: TaskbarSurfaceProps) {
+
+ const contentRadius = numericScale(useTheme().radius).medium
+
+ return <>
+
+ <GlassSurface aria-hidden="true" radius="inherit" className="pointer-events-none absolute inset-0" />
+
+ <h2 id={labelId} className="relative grid h-10 items-center px-3.5 text-window-title font-medium text-shadow-chrome select-none">{label}</h2>
+
+ <div style={{ borderRadius: contentRadius }} className="relative m-1.5 mt-0 min-h-0 overflow-hidden bg-white/25 shadow-window-content">
+
+ {children}
+
+ </div>
+
+ </>
+}
+
+interface TaskbarSurfaceProps {
+
+ label: string
+
+ labelId: string
+
+ children: ReactNode
+}
diff --git a/source/client/view/desktop/taskbar/taskbar.tsx b/source/client/view/desktop/taskbar/taskbar.tsx
new file mode 100644
index 0000000..1aa489f
--- /dev/null
+++ b/source/client/view/desktop/taskbar/taskbar.tsx
@@ -0,0 +1,53 @@
+import { ComponentProps, ReactNode } from "react"
+import { GlassSurface, useTheme } from "@phreshos/react-ui"
+import { numericScale } from "@phreshos/core"
+import { taskbarAnchorName } from "../geometry"
+import TaskbarSeparator from "./taskbar-separator"
+
+/**
+ * The desktop's persistent control surface. Leading, primary and trailing
+ * regions are structural; what each region means belongs to the caller.
+ */
+export default function Taskbar({ leading, trailing, dialogs, className, style, children, ...props }: TaskbarProps) {
+
+ const radius = numericScale(useTheme().radius).large
+
+ return <section
+
+ className={`relative isolate h-taskbar border border-white/30 shadow-taskbar ${className ?? ""}`}
+
+ style={{ anchorName: taskbarAnchorName, ...style, borderRadius: radius }}
+
+ {...props}
+
+ >
+
+ <GlassSurface aria-hidden="true" radius="inherit" className="pointer-events-none absolute inset-0" />
+
+ <div className="relative grid h-full min-w-0 grid-cols-[auto_auto_minmax(0,1fr)_auto_auto] items-center gap-1.5 p-2">
+
+ {leading}
+
+ <TaskbarSeparator />
+
+ {children}
+
+ <TaskbarSeparator />
+
+ {trailing}
+
+ </div>
+
+ {dialogs}
+
+ </section>
+}
+
+interface TaskbarProps extends ComponentProps<"section"> {
+
+ leading: ReactNode
+
+ trailing: ReactNode
+
+ dialogs?: ReactNode
+}
diff --git a/source/client/view/desktop/taskbar/window-taskbar-item.tsx b/source/client/view/desktop/taskbar/window-taskbar-item.tsx
new file mode 100644
index 0000000..a420ccb
--- /dev/null
+++ b/source/client/view/desktop/taskbar/window-taskbar-item.tsx
@@ -0,0 +1,40 @@
+import Process from "@client/core/link-manager/auth-manager/process-manager/process"
+import TaskbarItem from "./taskbar-item"
+import { memo, useCallback } from "react"
+
+/** A taskbar entry rerenders only when what that entry shows changes. */
+export default memo(function ({ record, title, icon, active, onElement, onMinimize, onShow }: WindowTaskbarItemProps) {
+
+ const press = useCallback(function () {
+
+ if (active) onMinimize(record, true)
+
+ else onShow(record)
+
+ }, [active, onMinimize, onShow, record])
+
+ const source = useCallback((element: HTMLButtonElement | null) => onElement(record, element), [onElement, record])
+
+ return <TaskbarItem ref={source} active={active} icon={icon} onClick={press}>
+
+ {title}
+
+ </TaskbarItem>
+})
+
+interface WindowTaskbarItemProps {
+
+ record: Process
+
+ title: string
+
+ icon: string
+
+ active: boolean
+
+ onElement: (record: Process, element: HTMLButtonElement | null) => void
+
+ onMinimize: (record: Process, minimized: boolean) => void
+
+ onShow: (record: Process) => void
+}
diff --git a/source/client/view/desktop/window-manager/process-window.tsx b/source/client/view/desktop/window-manager/process-window.tsx
new file mode 100644
index 0000000..7544617
--- /dev/null
+++ b/source/client/view/desktop/window-manager/process-window.tsx
@@ -0,0 +1,229 @@
+import Process from "@client/core/link-manager/auth-manager/process-manager/process"
+import ClientState from "@client/core/link-manager/auth-manager/process-manager/client-state"
+import { type WindowSurfaceSize } from "./window-geometry"
+import { type ProgramAccess } from "../program-access"
+import { type Position, type Size } from "@phreshos/core"
+import Loading from "../../components/loading"
+import Window from "./window"
+import ProgramFrame, { programFrameSource } from "../program-frame"
+import { memo, type SyntheticEvent, useCallback, useEffect, useState } from "react"
+
+const settleDelay = 80
+
+const loadingExitDuration = 200
+
+/**
+ * One process pane at the React boundary. Its primitive window values are
+ * props so memoization can see which process actually changed even though
+ * the peer deliberately keeps each Process instance alive and mutates it.
+ */
+export default memo(function ({ identity, record, client, title, icon, position, size, windowSurface, windowSurfaceRevision, paintSurfaceSize, depth, active, minimized, closing, stopping, entering, bare, door, programAccess, onFrame, onFrameLoad, onRaise, onMinimize, onFill, onClose, onClosed, onUnavailable, onMove, onResize, onSnap }: ProcessWindowProps) {
+
+ const activate = useCallback(() => onRaise(record), [onRaise, record])
+
+ const minimize = useCallback(() => onMinimize(record, true), [onMinimize, record])
+
+ const fill = useCallback(() => onFill(record), [onFill, record])
+
+ const close = useCallback(() => onClose(record), [onClose, record])
+
+ const closed = useCallback(() => onClosed(identity), [identity, onClosed])
+
+ const unavailable = useCallback((reason: "minimize" | "close") => onUnavailable(record, reason), [onUnavailable, record])
+
+ const move = useCallback((x: number, y: number) => onMove(record, x, y), [onMove, record])
+
+ const resize = useCallback((width: number, height: number, origin: { x: number, y: number } | null) => onResize(record, width, height, origin), [onResize, record])
+
+ const snap = useCallback((position: Position, size: Size) => onSnap(record, position, size), [onSnap, record])
+
+ const frameSource = programFrameSource(record, client, door)
+
+ const [loading, setLoading] = useState<LoadingState>({ source: null, phase: "loading" })
+
+ const loaded = useCallback(function (event: SyntheticEvent<HTMLIFrameElement>) {
+
+ setLoading({ source: frameSource, phase: "settling" })
+
+ onFrameLoad(record.identity, event.currentTarget)
+
+ }, [frameSource, onFrameLoad, record])
+
+ useEffect(function () {
+
+ if (loading.source !== frameSource || loading.phase === "loading" || loading.phase === "hidden") return
+
+ if (loading.phase === "leaving") {
+
+ const hidden = globalThis.setTimeout(() => setLoading({ source: frameSource, phase: "hidden" }), loadingExitDuration)
+
+ return () => globalThis.clearTimeout(hidden)
+ }
+
+ let secondFrame = 0
+
+ let settled: ReturnType<typeof setTimeout> | undefined
+
+ const firstFrame = requestAnimationFrame(() => {
+
+ secondFrame = requestAnimationFrame(() => {
+
+ settled = globalThis.setTimeout(() => setLoading({ source: frameSource, phase: "leaving" }), settleDelay)
+ })
+ })
+
+ return () => {
+
+ cancelAnimationFrame(firstFrame)
+
+ cancelAnimationFrame(secondFrame)
+
+ if (settled) globalThis.clearTimeout(settled)
+ }
+
+ }, [frameSource, loading])
+
+ const loadingVisible = closing || programAccess === "checking" || programAccess === "available" && (loading.source !== frameSource || loading.phase !== "hidden")
+
+ return <Window
+
+ title={title}
+
+ icon={icon}
+
+ position={position}
+
+ size={size}
+
+ windowSurface={windowSurface}
+
+ windowSurfaceRevision={windowSurfaceRevision}
+
+ paintSurfaceSize={paintSurfaceSize}
+
+ active={active}
+
+ bare={bare}
+
+ minimized={minimized}
+
+ closing={closing}
+
+ stopping={stopping}
+
+ animateEntrance={entering}
+
+ data-process-window={record.identity}
+
+ style={{ zIndex: depth }}
+
+ onActivate={activate}
+
+ onMinimize={minimize}
+
+ onMaximize={fill}
+
+ onClose={close}
+
+ onClosed={closed}
+
+ onUnavailable={unavailable}
+
+ onMove={move}
+
+ onResize={resize}
+
+ onSnap={snap}
+
+ >
+
+ {/* A launch names one of its client half's own pages; joining it
+ to the program asset route remains the view's responsibility.
+
+ Without allow-same-origin, the pane has an opaque origin and
+ cannot reach the desktop document or its authorization. Its
+ channel crosses through postMessage and resolves identity from
+ this frame, so isolation does not weaken communication. */}
+ {!closing && <ProgramFrame record={record} client={client} title={title} door={door} access={programAccess} onFrame={onFrame} onLoad={loaded} />}
+
+ {/* Bare layers are only the Program's content. Loading is system paint,
+ so it belongs exclusively to an ordinary window. */}
+ {!bare && loadingVisible && <Loading className={!closing && loading.source === frameSource && loading.phase === "leaving" ? "pointer-events-none opacity-0 transition-opacity duration-200 ease-out" : ""} />}
+
+ {/* First press focuses an inactive window before its program can
+ receive input. Bare layers have no system click-catcher. */}
+ {!bare && !active && <div className="absolute inset-0" />}
+
+ </Window>
+})
+
+interface ProcessWindowProps {
+
+ /** Identity of this Client incarnation, including one retained to animate out. */
+ identity: string
+
+ record: Process
+
+ client: ClientState
+
+ title: string
+
+ icon: string
+
+ position: Position
+
+ size: Size
+
+ windowSurface: ClientState["window"]["surface"]
+
+ windowSurfaceRevision: number
+
+ paintSurfaceSize?: WindowSurfaceSize
+
+ depth: number
+
+ active: boolean
+
+ minimized: boolean
+
+ closing: boolean
+
+ stopping: boolean
+
+ entering: boolean
+
+ bare: boolean
+
+ door: string
+
+ programAccess: ProgramAccess
+
+ onFrame: (identity: string, element: HTMLIFrameElement | null) => void
+
+ onFrameLoad: (identity: string, element: HTMLIFrameElement) => void
+
+ onRaise: (record: Process) => void
+
+ onMinimize: (record: Process, minimized: boolean) => void
+
+ onFill: (record: Process) => void
+
+ onClose: (record: Process) => void
+
+ onClosed: (identity: string) => void
+
+ onUnavailable: (record: Process, reason: "minimize" | "close") => void
+
+ onMove: (record: Process, x: number, y: number) => void
+
+ onResize: (record: Process, width: number, height: number, position: { x: number, y: number } | null) => void
+
+ onSnap: (record: Process, position: Position, size: Size) => void
+}
+
+interface LoadingState {
+
+ source: string | null
+
+ phase: "loading" | "settling" | "leaving" | "hidden"
+}
diff --git a/source/client/view/desktop/window-manager/window-geometry.ts b/source/client/view/desktop/window-manager/window-geometry.ts
new file mode 100644
index 0000000..c752a80
--- /dev/null
+++ b/source/client/view/desktop/window-manager/window-geometry.ts
@@ -0,0 +1,129 @@
+import { parseRelativeValue, type Position, type RelativeValue, type Size, type Value } from "@phreshos/core"
+import { windowPaintInset } from "../geometry"
+
+export interface WindowRegion {
+
+ x: number
+
+ y: number
+
+ width: number
+
+ height: number
+}
+
+export interface WindowSurfaceSize {
+
+ width: number
+
+ height: number
+}
+
+/**
+ * Every window type uses this same calculation inside the CSS containing
+ * block supplied by its layer. Every expression is one relative coefficient
+ * plus one pixel offset. No layer, boundary correction, gutter, or clamping
+ * participates here.
+ */
+export function resolveWindowValue(value: Value) {
+
+ const resolved = relative(value)
+
+ if (resolved.relative === 0) return `${resolved.pixels}px`
+
+ if (resolved.pixels === 0) return `calc(${resolved.relative * 100}%)`
+
+ const operator = resolved.pixels < 0 ? "-" : "+"
+
+ return `calc(${resolved.relative * 100}% ${operator} ${Math.abs(resolved.pixels)}px)`
+}
+
+/** Returns whether every geometry value is independent of its containing block. */
+export function absoluteWindowGeometry(position: Position, size: Size) {
+
+ return [position.x, position.y, size.width, size.height].every(value => relative(value).relative === 0)
+}
+
+/** Returns whether the geometry exactly fills its containing block. */
+export function wholeWindowGeometry(position: Position, size: Size) {
+
+ return equal(position.x, 0, 0) && equal(position.y, 0, 0) && equal(size.width, 1, 0) && equal(size.height, 1, 0)
+}
+
+/**
+ * The window's box is its geometry; an ordinary painted frame is inset only
+ * on edges that do not touch that box's containing surface. Snap previews use
+ * this same function, so preview and final paint cannot disagree.
+ */
+export function windowPaintInsets(position: Position, size: Size, surface: WindowSurfaceSize, current?: WindowRegion) {
+
+ const x = current?.x ?? pixels(position.x, surface.width)
+
+ const y = current?.y ?? pixels(position.y, surface.height)
+
+ const width = current?.width ?? pixels(size.width, surface.width)
+
+ const height = current?.height ?? pixels(size.height, surface.height)
+
+ return {
+
+ top: startsAtBoundary(position.y, y, surface.height) ? 0 : windowPaintInset,
+
+ right: endsAtBoundary(position.x, size.width, x, width, surface.width) ? 0 : windowPaintInset,
+
+ bottom: endsAtBoundary(position.y, size.height, y, height, surface.height) ? 0 : windowPaintInset,
+
+ left: startsAtBoundary(position.x, x, surface.width) ? 0 : windowPaintInset
+ }
+}
+
+function pixels(value: Value, span: number) {
+
+ const resolved = relative(value)
+
+ return resolved.relative * span + resolved.pixels
+}
+
+function startsAtBoundary(value: Value, resolved: number, span: number) {
+
+ if (span) return closeTo(resolved, 0)
+
+ return equal(value, 0, 0)
+}
+
+function endsAtBoundary(position: Value, size: Value, resolvedPosition: number, resolvedSize: number, span: number) {
+
+ if (span) return closeTo(resolvedPosition + resolvedSize, span)
+
+ const first = relative(position)
+
+ const second = relative(size)
+
+ return same(first.relative + second.relative, 1) && closeTo(first.pixels + second.pixels, 0)
+}
+
+function closeTo(value: number, boundary: number) {
+
+ return Math.abs(value - boundary) <= 0.5
+}
+
+function equal(value: Value, expectedRelative: number, expectedPixels: number) {
+
+ const resolved = relative(value)
+
+ return same(resolved.relative, expectedRelative) && same(resolved.pixels, expectedPixels)
+}
+
+function same(value: number, expected: number) {
+
+ return Math.abs(value - expected) <= 1e-9
+}
+
+function relative(value: Value): RelativeValue {
+
+ const parsed = parseRelativeValue(value)
+
+ if (!parsed) throw new Error("A Window received invalid geometry")
+
+ return parsed
+}
diff --git a/source/client/view/desktop/window-manager/window-header.tsx b/source/client/view/desktop/window-manager/window-header.tsx
new file mode 100644
index 0000000..3de3201
--- /dev/null
+++ b/source/client/view/desktop/window-manager/window-header.tsx
@@ -0,0 +1,151 @@
+import { ComponentProps, PointerEvent as ReactPointerEvent, ReactNode } from "react"
+
+/** The visible chrome above an ordinary window's content. */
+export default function WindowHeader({ title, icon, active, whole, reducedMotion, stopping, onGrab, onMinimize, onMaximize, onClose }: WindowHeaderProps) {
+
+ return <header
+
+ onPointerDown={onGrab}
+
+ onDoubleClick={onMaximize}
+
+ className="relative grid h-10 shrink-0 touch-none cursor-grab grid-cols-[minmax(0,1fr)_auto] items-center gap-3 px-3.5 select-none active:cursor-grabbing"
+
+ >
+
+ <div className="grid min-w-0 grid-cols-[auto_minmax(0,1fr)] items-center gap-3">
+
+ <img
+
+ src={icon}
+
+ alt=""
+
+ draggable={false}
+
+ className={`size-4 rounded-sm object-contain ${reducedMotion ? "" : "transition-opacity duration-200"} ${active ? "opacity-100" : "opacity-60"}`}
+
+ />
+
+ {/* Focus is said on the chrome and nowhere else. Content stays
+ equally legible when another window owns the keyboard. */}
+ <span className={`truncate text-window-title font-medium text-shadow-chrome ${reducedMotion ? "" : "transition-colors duration-200"} ${active ? "text-slate-800" : "text-slate-500"}`}>{title}</span>
+
+ </div>
+
+ <div className="grid shrink-0 grid-flow-col auto-cols-max gap-1" onPointerDown={event => event.stopPropagation()}>
+
+ {onMinimize && <Control label="Minimise" reducedMotion={reducedMotion} focusOnPointerDown={false} onClick={onMinimize}>
+
+ <path d="M1.5 7.5h7" />
+
+ </Control>}
+
+ {onMaximize && <Control label={whole ? "Restore" : "Fill"} reducedMotion={reducedMotion} onClick={onMaximize}>
+
+ {whole
+
+ ? <path d="M1 4h5v5H1zM4 1h5v5H6.5" strokeWidth="1.3" strokeLinejoin="round" />
+
+ : <path d="M1.5 1.5h7v7h-7z" strokeWidth="1.3" strokeLinejoin="round" />}
+
+ </Control>}
+
+ {onClose && <Control label="Close" reducedMotion={reducedMotion} focusOnPointerDown={false} onClick={onClose} disabled={stopping} danger>
+
+ <path d="M1.5 1.5 8.5 8.5M8.5 1.5 1.5 8.5" />
+
+ </Control>}
+
+ </div>
+
+ </header>
+}
+
+// A pointer control acts on the press: click waits for the release, and that
+// wait reads as lag on something meant to feel mechanical. Keyboard and
+// assistive technology still use the button's native click activation.
+function Control({ label, danger = false, focusOnPointerDown = true, reducedMotion, children, onClick, ...props }: ControlProps) {
+
+ const reaction = danger
+
+ ? "hover:border-rose-300/70 hover:bg-rose-500 hover:text-white active:bg-rose-600"
+
+ : "hover:border-white/70 hover:bg-white/65 hover:text-slate-900 active:bg-white/80"
+
+ return <button
+
+ aria-label={label}
+
+ onPointerDown={event => {
+
+ event.stopPropagation()
+
+ if (event.button !== 0) return
+
+ if (focusOnPointerDown) event.currentTarget.focus({ preventScroll: true })
+
+ // Minimise and close act without focusing their window. Preventing
+ // the pointer's default focus keeps that action from raising it.
+ else event.preventDefault()
+
+ onClick?.()
+ }}
+
+ onClick={event => {
+
+ event.stopPropagation()
+
+ if (event.detail === 0) onClick?.()
+ }}
+
+ className={`grid size-6 place-items-center rounded-md border border-transparent bg-white/15 text-slate-600 outline-none shadow-sm disabled:pointer-events-none disabled:opacity-40 focus-visible:relative focus-visible:z-10 focus-visible:ring-2 focus-visible:ring-sky-500 ${reducedMotion ? "" : "transition-colors duration-100 active:scale-95"} ${reaction}`}
+
+ {...props}
+
+ >
+
+ <svg viewBox="0 0 10 10" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" className="size-2.5">
+
+ {children}
+
+ </svg>
+
+ </button>
+}
+
+interface WindowHeaderProps {
+
+ title?: ReactNode
+
+ icon: string
+
+ active: boolean
+
+ whole: boolean
+
+ reducedMotion: boolean
+
+ stopping: boolean
+
+ onGrab: (event: ReactPointerEvent<HTMLElement>) => void
+
+ onMinimize?: () => void
+
+ onMaximize?: () => void
+
+ onClose?: () => void
+}
+
+interface ControlProps extends Omit<ComponentProps<"button">, "onClick"> {
+
+ label: string
+
+ danger?: boolean
+
+ focusOnPointerDown?: boolean
+
+ reducedMotion: boolean
+
+ onClick?: () => void
+}
diff --git a/source/client/view/desktop/window-manager/window-manager.ts b/source/client/view/desktop/window-manager/window-manager.ts
new file mode 100644
index 0000000..a98b89c
--- /dev/null
+++ b/source/client/view/desktop/window-manager/window-manager.ts
@@ -0,0 +1,407 @@
+import ClientState from "@client/core/link-manager/auth-manager/process-manager/client-state"
+import Process from "@client/core/link-manager/auth-manager/process-manager/process"
+import ReactTunnel from "@libs/the-link/plugins/react-helper/react-tunnel"
+import { Layer } from "@server/core/link-manager/auth-manager/program-manager/config"
+import { type Position, type Size, type Value } from "@phreshos/core"
+import { useCallback, useRef, useState } from "react"
+import { AuthManagerContext } from "../../contexts"
+import { wholeWindowGeometry } from "./window-geometry"
+
+/**
+ * The authorized view's windows: processes that have one. A window is a
+ * process whose program has a client half, so the process itself says
+ * whether it is shown — nothing else is consulted.
+ *
+ * Requests are answered before the server is: the object mutates here,
+ * the same tunnel event re-emits, and the echo lands on a peer already
+ * agreeing — while every other session sees the change as news.
+ *
+ * Departure is representation. The truth drops a stopped client and its
+ * Window at once; the exit still has to play, so the last desktop-owned
+ * representation is kept until its animation reports done. Its iframe is
+ * not part of that snapshot and leaves as soon as the stop is confirmed.
+ */
+export default function useWindows() {
+
+ const authManager = AuthManagerContext.useValue()
+
+ const peer = authManager.processManager
+
+ const inbound = ReactTunnel.useFactory(peer.$inbound)
+
+ const [processes, setProcesses] = useState(() => [...peer.processes.values()])
+
+ const incarnationIds = useRef(new WeakMap<ClientState, string>())
+
+ const nextIncarnation = useRef(0)
+
+ const incarnation = useCallback(function (record: Process, client: ClientState): WindowIncarnation {
+
+ let identity = incarnationIds.current.get(client)
+
+ if (!identity) {
+
+ identity = `${record.identity}:${nextIncarnation.current++}`
+
+ incarnationIds.current.set(client, identity)
+ }
+
+ return { identity, record, client }
+
+ }, [])
+
+ const initialIncarnations = useRef<Map<string, WindowIncarnation> | null>(null)
+
+ if (!initialIncarnations.current) initialIncarnations.current = new Map(processes.flatMap(record => record.client && record.client.window.layer !== "wallpaper" ? [[record.identity, incarnation(record, record.client)] as const] : []))
+
+ const initialClients = initialIncarnations.current
+
+ const previousClients = useRef(initialClients)
+
+ // Client states already present when this desktop mounts are restored,
+ // not launched, so their representations must not replay an entrance.
+ const inheritedClients = useRef(new WeakSet([...initialClients.values()].map(({ client }) => client)))
+
+ const [leaving, setLeaving] = useState<WindowIncarnation[]>([])
+
+ // A close press asks the core to terminate the Process. Keep that request
+ // visible until the Process actually leaves the authoritative collection.
+ const stopping = useRef(new Set<string>())
+
+ const [, redrawStopping] = useState(0)
+
+ // The order the desktop draws in: a window is added when it first
+ // appears and taken out when its departure has played, and nothing
+ // else moves it. Held rather than derived, because the two lists it
+ // orders are not one list, and their concatenation is not this.
+ const [order, setOrder] = useState<string[]>(() => [...initialClients.values()].map(({ identity }) => identity))
+
+ // Where a window was before it was made to fill the surface.
+ //
+ // The system stopped remembering this when `maximize` stopped being
+ // a state: filling the surface is a size like any other now, so
+ // nothing there can undo it. The button that offers the undo keeps
+ // what it needs to honour it — a ref rather than state, because
+ // nothing is drawn from it.
+ const filled = useRef(new Map<string, { position: Position, size: Size }>())
+
+ // Departures are derived at the moment the truth arrives — the same
+ // event updates both lists in one batch, so no render ever shows a
+ // window in neither.
+ const subscriber = useCallback((...results: unknown[]) => {
+
+ const [list] = results as [Process[]]
+
+ const present = new Set(list.map(process => process.identity))
+
+ const currentClients = new Map(list.flatMap(record => record.client && record.client.window.layer !== "wallpaper" ? [[record.identity, incarnation(record, record.client)] as const] : []))
+
+ let settled = false
+
+ for (const identity of stopping.current) {
+
+ if (present.has(identity)) continue
+
+ stopping.current.delete(identity)
+
+ settled = true
+ }
+
+ if (settled) redrawStopping(revision => revision + 1)
+
+ const gone = [...previousClients.current.values()].filter(previous => currentClients.get(previous.record.identity)?.client !== previous.client)
+
+ if (gone.length) setLeaving(function (current) {
+
+ const retained = new Set(current.map(({ identity }) => identity))
+
+ return [...current, ...gone.filter(({ identity }) => !retained.has(identity))]
+ })
+
+ setOrder(function (current) {
+
+ const retained = new Set(current)
+
+ const added = [...currentClients.values()].filter(({ identity }) => !retained.has(identity)).map(({ identity }) => identity)
+
+ return added.length ? [...current, ...added] : current
+ })
+
+ previousClients.current = currentClients
+
+ setProcesses(list)
+
+ }, [incarnation])
+
+ inbound.useSubscribe("/processes", subscriber)
+
+ const records = processes.filter(process => process.client && process.client.window.layer !== "wallpaper")
+
+ const wallpaper = processes.find(process => process.client?.window.layer === "wallpaper") ?? null
+
+ // Everything that is shown, in the layer it is shown in — and the
+ // taskbar's list, which is the `window` layer and nothing else. The
+ // taskbar shows windows, not processes: every entry in it is a thing
+ // you can focus, minimise and restore, and a row whose entries do
+ // not all answer the same press is one row teaching two rules.
+ const listed = records.filter(process => process.client!.window.layer === "window")
+
+ // The greatest depth *in one layer*. Bringing a window forward
+ // brings it forward among its own kind; a program in `over` opening
+ // does not push a window's number up.
+ const summit = useCallback((layer: Layer) => [...peer.processes.values()].reduce((highest, process) => process.client?.window.layer === layer ? Math.max(highest, process.client.window.depth) : highest, 0), [peer])
+
+ // The front window of each layer, resolved together. Three separate
+ // reductions walked every process three times on every window event.
+ const fronts: Record<Layer, Process | null> = { under: null, window: null, over: null }
+
+ for (const process of records) {
+
+ const window = process.client!.window
+
+ if (window.layer === "wallpaper" || window.minimized) continue
+
+ const best = fronts[window.layer]
+
+ if (!best || best.client!.window.depth <= window.depth) fronts[window.layer] = process
+ }
+
+ // A request answered locally first: the object changes, the tunnel
+ // re-emits, and the echo confirms what is already shown.
+ const commit = useCallback(function (request: Promise<void>) {
+
+ peer.$inbound.publish("/processes", [...peer.processes.values()]).catch(() => undefined)
+
+ request.catch(() => undefined)
+ }, [peer])
+
+ const close = useCallback(function (process: Process) {
+
+ if (stopping.current.has(process.identity)) return
+
+ stopping.current.add(process.identity)
+
+ redrawStopping(revision => revision + 1)
+
+ process.stop().catch(() => {
+
+ stopping.current.delete(process.identity)
+
+ redrawStopping(revision => revision + 1)
+ })
+
+ }, [])
+
+ const closed = useCallback(function (identity: string) {
+
+ setLeaving(current => current.filter(entry => entry.identity !== identity))
+
+ setOrder(current => current.filter(entry => entry !== identity))
+
+ }, [])
+
+ const raise = useCallback(function (process: Process) {
+
+ const window = process.client?.window
+
+ if (!window || window.layer === "wallpaper") return
+
+ const highest = summit(window.layer)
+
+ if (window.depth === highest) return
+
+ window.depth = highest + 1
+
+ commit(window.raise())
+
+ }, [commit, summit])
+
+ const minimize = useCallback(function (process: Process, minimized: boolean) {
+
+ const window = process.client?.window
+
+ if (!window) return
+
+ window.minimized = minimized
+
+ commit(window.minimize(minimized))
+
+ }, [commit])
+
+ const show = useCallback(function (process: Process) {
+
+ const window = process.client?.window
+
+ if (!window) return
+
+ if (window.minimized) minimize(process, false)
+
+ raise(process)
+
+ }, [minimize, raise])
+
+ const move = useCallback(function (process: Process, x: Value, y: Value) {
+
+ const window = process.client?.window
+
+ if (!window) return
+
+ window.localMove({ x, y })
+
+ commit(window.move({ x, y }))
+
+ }, [commit])
+
+ const resize = useCallback(function (process: Process, width: Value, height: Value, position: Position | null) {
+
+ const window = process.client?.window
+
+ if (!window) return
+
+ window.localResize({ width, height })
+
+ if (!position) {
+
+ commit(window.resize({ width, height }))
+
+ return
+ }
+
+ window.localMove(position)
+
+ commit(window.move(position).then(() => window.resize({ width, height })))
+
+ }, [commit])
+
+ const snap = useCallback(function (process: Process, position: Position, size: Size) {
+
+ const window = process.client?.window
+
+ if (!window) return
+
+ window.localMove(position)
+
+ window.localResize(size)
+
+ commit(window.move(position).then(() => window.resize(size)))
+
+ }, [commit])
+
+ const fill = useCallback(function (process: Process) {
+
+ const window = process.client?.window
+
+ if (!window) return
+
+ const was = filled.current.get(process.identity)
+
+ const whole = wholeWindowGeometry(window.position, window.size)
+
+ if (whole && was) {
+
+ filled.current.delete(process.identity)
+
+ move(process, was.position.x, was.position.y)
+
+ resize(process, was.size.width, was.size.height, null)
+
+ return
+ }
+
+ filled.current.set(process.identity, { position: window.position, size: window.size })
+
+ snap(process, { x: "0/1", y: "0/1" }, { width: "1/1", height: "1/1" })
+
+ }, [move, resize, snap])
+
+ // Every window on the desktop, in one list and one order.
+ //
+ // A closing client incarnation keeps the place it had. A restarted
+ // Client receives a new desktop-local representation identity even when
+ // the surrounding Process and its public Client-owned Window capability
+ // remain the same.
+ const rank = new Map(order.map((identity, index) => [identity, index]))
+
+ const panes = [
+
+ ...records.map(record => {
+
+ const live = incarnation(record, record.client!)
+
+ return { ...live, closing: false, stopping: stopping.current.has(record.identity), entering: !inheritedClients.current.has(live.client) }
+ }),
+
+ ...leaving.map(window => ({ ...window, closing: true, stopping: false, entering: !inheritedClients.current.has(window.client) }))
+ ]
+
+ .sort((one, other) => (rank.get(one.identity) ?? Number.MAX_SAFE_INTEGER) - (rank.get(other.identity) ?? Number.MAX_SAFE_INTEGER))
+
+ const panesByLayer: Record<Layer, typeof panes> = { under: [], window: [], over: [] }
+
+ for (const pane of panes) {
+
+ const layer = pane.client.window.layer
+
+ if (layer !== "wallpaper") panesByLayer[layer].push(pane)
+ }
+
+ return {
+
+ records,
+
+ wallpaper,
+
+ listed,
+
+ panesByLayer,
+
+ fronts,
+
+ close,
+
+ closed,
+
+ // ── The primitives, one act each ─────────────────────────────
+ //
+ // The window manager composes them below; nothing here does two
+ // things at once, because the system beneath does not either.
+ raise,
+
+ minimize,
+
+ // ── And the policy, which is the window manager's ────────────
+ //
+ // A person pressing a taskbar item means *show me this one*, so
+ // it is shown and brought to the front — two primitives, said
+ // here, where a person's expectation belongs. The system knows
+ // nothing about the pairing.
+ show,
+
+ // Filling the surface, and coming back from it. Not a state the
+ // system holds: there is no `maximized` any more, only a size —
+ // so the memory of where a window was before it filled the
+ // surface is kept here, in the interface that offers the button.
+ // Whoever offers an undo owns what it undoes.
+ fill,
+
+ move,
+
+ // A resize that moved no origin is only a resize: writing the
+ // pixels a share resolved to would silence the share, and the
+ // window would stop following the surface it was sized against.
+ resize,
+
+ // A snap names a share of the surface rather than pixels, so
+ // every client resolves it in its own space.
+ snap
+ }
+}
+
+interface WindowIncarnation {
+
+ identity: string
+
+ record: Process
+
+ client: ClientState
+}
diff --git a/source/client/view/desktop/window-manager/window-surface.tsx b/source/client/view/desktop/window-manager/window-surface.tsx
new file mode 100644
index 0000000..fb5ae97
--- /dev/null
+++ b/source/client/view/desktop/window-manager/window-surface.tsx
@@ -0,0 +1,132 @@
+import { useReducedMotion } from "@libs/react-motion"
+import { isScaleLevel, scale, type WindowSurfaceEasing, type WindowSurfaceSettings } from "@phreshos/core"
+import { GlassSurface, useTheme } from "@phreshos/react-ui"
+import { useLayoutEffect, useRef, useState } from "react"
+
+const systemDuration = 240
+
+const systemEasing = "ease-out"
+
+/** Projects one authoritative target and animates only live replacements. */
+export default function WindowSurface({ revision, settings }: WindowSurfaceProps) {
+
+ const element = useRef<HTMLDivElement>(null)
+
+ const previousRevision = useRef<number | null>(null)
+
+ const reducedMotion = useReducedMotion()
+
+ const themeRadius = useTheme().radius
+
+ // Rendering retains the last settled target while an incoming target is
+ // prepared imperatively. This leaves the element's current visual values
+ // available when a new transaction interrupts one already in flight.
+ const [rendered, setRendered] = useState(settings)
+
+ useLayoutEffect(function () {
+
+ const surface = element.current
+
+ if (!surface) return
+
+ const target = values(settings, themeRadius)
+
+ const current = getComputedStyle(surface)
+
+ const changed = previousRevision.current === null
+
+ ? revision > 0
+
+ : revision !== previousRevision.current
+
+ const from = previousRevision.current === null && changed
+
+ ? { opacity: 0, borderRadius: "0px" }
+
+ : { opacity: Number(current.opacity), borderRadius: current.borderRadius }
+
+ previousRevision.current = revision
+
+ setRendered(settings)
+
+ surface.style.opacity = String(target.opacity)
+
+ surface.style.borderRadius = target.borderRadius
+
+ const transaction = settings.transaction
+
+ const duration = transaction?.duration ?? systemDuration
+
+ if (!transaction || reducedMotion || duration === 0 || !changed) return
+
+ const animation = surface.animate([from, target], {
+
+ duration,
+
+ easing: easing(transaction.easing),
+
+ fill: "both"
+ })
+
+ animation.finished.then(function () {
+
+ animation.cancel()
+
+ }, () => undefined)
+
+ return function () {
+
+ const shown = getComputedStyle(surface)
+
+ surface.style.opacity = shown.opacity
+
+ surface.style.borderRadius = shown.borderRadius
+
+ animation.cancel()
+ }
+
+ }, [reducedMotion, revision, settings, themeRadius])
+
+ const target = values(rendered, themeRadius)
+
+ return <GlassSurface
+
+ ref={element}
+
+ data-window-surface
+
+ aria-hidden="true"
+
+ className="pointer-events-none absolute inset-0"
+
+ style={{ opacity: target.opacity, borderRadius: target.borderRadius }}
+
+ />
+}
+
+function values(settings: WindowSurfaceSettings, themeRadius: number) {
+
+ const radius = settings.radius
+
+ return {
+
+ opacity: settings.opacity ?? 1,
+
+ borderRadius: radius === "full" ? "50%" : `${isScaleLevel(radius) ? scale(themeRadius, radius) : radius ?? 0}px`
+ }
+}
+
+function easing(value: WindowSurfaceEasing | undefined) {
+
+ if (typeof value === "string") return value
+
+ return value ? `cubic-bezier(${value.join(", ")})` : systemEasing
+}
+
+interface WindowSurfaceProps {
+
+ settings: WindowSurfaceSettings
+
+ /** Zero is an initial snapshot; positive revisions are live changes. */
+ revision: number
+}
diff --git a/source/client/view/desktop/window-manager/window.tsx b/source/client/view/desktop/window-manager/window.tsx
new file mode 100644
index 0000000..ecd9a93
--- /dev/null
+++ b/source/client/view/desktop/window-manager/window.tsx
@@ -0,0 +1,709 @@
+import { ComponentProps, PointerEvent as ReactPointerEvent, ReactNode, useLayoutEffect, useRef, useState } from "react"
+import { useReducedMotion } from "@libs/react-motion"
+import { enterSurface, prepareSurfaceEntrance, restSurface } from "../../appearance/surface-presence"
+import { GlassSurface, useTheme } from "@phreshos/react-ui"
+import { absoluteWindowGeometry, resolveWindowValue, wholeWindowGeometry, windowPaintInsets, type WindowRegion, type WindowSurfaceSize } from "./window-geometry"
+import { numericScale, type Position, type Size, type WindowSurfaceSettings } from "@phreshos/core"
+import WindowHeader from "./window-header"
+import WindowSurface from "./window-surface"
+import gsap from "gsap"
+
+/**
+ * A window: a pure function of the record it is given. Every render
+ * declares the whole geometry from props — a float as left/top pixels,
+ * a tile as its relative form — and CSS transitions animate whatever
+ * changes between renders. There is no imperative geometry writer, no
+ * birth snapshot, no mode to reconcile: a refreshed page renders the
+ * truth it was born with because rendering the truth is all this
+ * component does.
+ *
+ * A gesture is state, not a side channel: while one runs, the render
+ * derives from the gesture's rectangle instead of the record — movement
+ * rides a transform above the grabbed origin, transitions pause — and
+ * release reports the outcome (onMove or onResize with resting pixels —
+ * a resize carrying an origin only when the edge dragged moved one —
+ * onSnap with the shares a zone names) and drops the gesture in the same
+ * batch the record updates, so nothing jumps.
+ *
+ * GSAP keeps exactly one duty: presence — the scale and drift of
+ * entering, minimising and closing, on the glass, never the frame.
+ *
+ * The chrome is the liquid material: refraction, frost, specular shell;
+ * content sits on an inset sheet. The close control requests — the
+ * window leaves only when the truth drops its process.
+ */
+const edges: { edge: WindowEdge, className: string }[] = [
+
+ { edge: "n", className: "inset-x-4 top-0 h-2 cursor-ns-resize" },
+ { edge: "s", className: "inset-x-4 bottom-0 h-2 cursor-ns-resize" },
+ { edge: "w", className: "inset-y-4 left-0 w-2 cursor-ew-resize" },
+ { edge: "e", className: "inset-y-4 right-0 w-2 cursor-ew-resize" },
+ { edge: "nw", className: "top-0 left-0 size-4 cursor-nwse-resize" },
+ { edge: "ne", className: "top-0 right-0 size-4 cursor-nesw-resize" },
+ { edge: "sw", className: "bottom-0 left-0 size-4 cursor-nesw-resize" },
+ { edge: "se", className: "bottom-0 right-0 size-4 cursor-nwse-resize" }
+]
+
+const settle = ["left", "top", "width", "height", "transform"].map(property => `${property} 0.3s cubic-bezier(0.65, 0, 0.35, 1)`).join(", ")
+
+const morphing = ["left", "top", "width", "height"].map(property => `${property} 0.22s cubic-bezier(0.33, 1, 0.68, 1)`).join(", ")
+
+export default function ({ title, icon, children, onClose, onClosed, onMinimize, onMaximize, onActivate, onUnavailable, onMove, onResize, onSnap, onFocusCapture, active = false, bare = false, closing = false, stopping = false, minimized = false, animateEntrance = true, position = { x: 0, y: 0 }, size = { width: 520, height: 340 }, windowSurface = null, windowSurfaceRevision = 0, paintSurfaceSize = { width: 0, height: 0 }, minWidth = 260, minHeight = 160, className, style, ...props }: WindowProps) {
+
+ const frame = useRef<HTMLDivElement>(null)
+
+ const glass = useRef<HTMLDivElement>(null)
+
+ const reducedMotion = useReducedMotion()
+
+ const radius = numericScale(useTheme().radius)
+
+ const outerRadius = radius.large
+
+ const innerRadius = radius.medium
+
+ const [gesture, setGesture] = useState<Gesture | null>(null)
+
+ const closureCompleted = useRef(false)
+
+ function completeClosure() {
+
+ if (closureCompleted.current) return
+
+ closureCompleted.current = true
+
+ onClosed?.()
+ }
+
+ // A window is absolute when none of its expressions depends on the surface.
+ const absolute = absoluteWindowGeometry(position, size)
+
+ // Whether it is filling the surface — read off the geometry, for
+ // this button's own label and nothing else. The system has no such
+ // state any more: filling the surface is a size like any other, and
+ // this is the interface recognising a size it offered to set.
+ const whole = wholeWindowGeometry(position, size)
+
+ // The render that lands a plain commit suppresses transitions for one
+ // frame: the record now equals what the gesture showed, and the
+ // decomposition swap (origin+transform to left alone) must not be
+ // interpolated — two properties animating opposite ways cancel only
+ // in exact math, and the browser's residue reads as drift.
+ const [landed, setLanded] = useState(false)
+
+ useLayoutEffect(function () {
+
+ if (!landed) return
+
+ const settle = requestAnimationFrame(() => setLanded(false))
+
+ return () => cancelAnimationFrame(settle)
+
+ }, [landed])
+
+ // Presence: a newly created window enters, while a window inherited
+ // when its desktop mounts is already here and renders at rest. A full
+ // page refresh remounts elements, not processes, and must not make all
+ // restored windows look newly opened.
+ //
+ // Bare, there is no entrance. Motion is a visual effect like the
+ // glass and the shadow, and `under` and `over` are the layers where
+ // the system paints nothing — so what would scale and drift here is
+ // the program's own content, which reads as the program stumbling
+ // rather than as a window opening. It showed on every refresh,
+ // because a refresh mounts every window and a mount is a birth.
+ useLayoutEffect(function () {
+
+ if (bare) return
+
+ if (minimized) {
+
+ gsap.set(glass.current, { scale: reducedMotion ? 1 : 0.86, y: reducedMotion ? 0 : 28, visibility: "hidden" })
+
+ return
+ }
+
+ if (!animateEntrance) {
+
+ restSurface(glass.current)
+
+ gsap.set(glass.current, { visibility: "visible" })
+
+ return
+ }
+
+ prepareSurfaceEntrance(glass.current, reducedMotion)
+
+ gsap.set(glass.current, { visibility: "visible" })
+
+ const animation = enterSurface(glass.current, reducedMotion)
+
+ return () => { animation?.kill() }
+
+ // Presence at birth reads the mount's own values once.
+ }, [])
+
+ // A preference change takes effect immediately. Any automatic travel
+ // already in progress is ended at its truthful final representation;
+ // closing still answers its completion handshake.
+ useLayoutEffect(function () {
+
+ if (!glass.current) return
+
+ // A hidden window can silently prepare the pose that a future
+ // restore will animate from if the preference has been relaxed.
+ if (!reducedMotion) {
+
+ if (minimized) gsap.set(glass.current, { scale: 0.86, y: 28, visibility: "hidden" })
+
+ return
+ }
+
+ gsap.killTweensOf(glass.current)
+
+ gsap.set(glass.current, { scale: 1, y: 0, visibility: minimized || closing ? "hidden" : "visible" })
+
+ if (closing) {
+
+ onUnavailable?.("close")
+
+ completeClosure()
+ }
+
+ else if (minimized) onUnavailable?.("minimize")
+
+ }, [reducedMotion])
+
+ // Minimising drifts toward the taskbar; restoring rises back.
+ const arrived = useRef(false)
+
+ useLayoutEffect(function () {
+
+ if (!arrived.current) {
+
+ arrived.current = true
+
+ return
+ }
+
+ if (!glass.current) return
+
+ if (minimized) onUnavailable?.("minimize")
+
+ // Bare, hiding is hiding: the visibility changes and nothing
+ // travels. There is no taskbar for it to drift toward — a
+ // program in `under` or `over` is not listed — so the drift
+ // would be motion toward nowhere.
+ if (bare || reducedMotion) {
+
+ gsap.set(glass.current, { scale: 1, y: 0, visibility: minimized ? "hidden" : "visible" })
+
+ return
+ }
+
+ // Presence is scale and drift, never opacity: an element with
+ // opacity below 1 is a backdrop root, and inside one there is
+ // nothing behind to sample — the glass would be dead for as long
+ // as the fade lasted, which is exactly as long as the eye is on
+ // it. Going away is a departure toward the taskbar; hiding at
+ // the end is visibility, which forms no such root.
+ if (!minimized) gsap.set(glass.current, { visibility: "visible" })
+
+ const animation = minimized
+
+ ? gsap.to(glass.current, { scale: 0.86, y: 28, duration: 0.11, ease: "power3.in", onComplete: () => gsap.set(glass.current, { visibility: "hidden" }) })
+
+ : gsap.to(glass.current, { scale: 1, y: 0, duration: 0.24, ease: "power3.out" })
+
+ return () => { animation.kill() }
+
+ }, [minimized])
+
+ // Closing is a handshake: the exit plays, onClosed reports the
+ // element may be unmounted.
+ useLayoutEffect(function () {
+
+ if (!closing || !glass.current) return
+
+ onUnavailable?.("close")
+
+ // Bare, there is no exit to play — but the handshake still has
+ // to be answered, or the desktop keeps the leaving record
+ // forever waiting for an animation that never runs.
+ if (bare || reducedMotion) {
+
+ completeClosure()
+
+ return
+ }
+
+ const animation = gsap.to(glass.current, { scale: 0.86, y: 12, duration: 0.16, ease: "power2.in", onComplete: completeClosure })
+
+ return () => { animation.kill() }
+
+ }, [closing])
+
+ function grab(event: ReactPointerEvent<HTMLElement>, edge: WindowEdge | null) {
+
+ // A cancelled pointerdown suppresses double-click synthesis, and
+ // a shared window restores by double-click; absolute ones keep
+ // it to block native drags.
+ if (absolute) event.preventDefault()
+
+ const handle = event.currentTarget
+
+ handle.setPointerCapture(event.pointerId)
+
+ const parent = frame.current?.offsetParent
+
+ const bounds = parent?.getBoundingClientRect()
+
+ if (!frame.current || !parent || !bounds) return
+
+ // The grabbed origin is measured, not assumed: grabbing a window
+ // mid-transition holds it exactly where the eye sees it.
+ const rect = frame.current.getBoundingClientRect()
+
+ let origin: WindowRegion = { x: rect.left - bounds.left, y: rect.top - bounds.top, width: rect.width, height: rect.height }
+
+ let current: WindowRegion = { ...origin }
+
+ // Pulling a shared window out of its placement belongs to the
+ // header alone. An edge is not a hand asking to float — it is a
+ // hand asking for a different size, and a window keeps whatever
+ // of its placement that edge does not touch.
+ let restoring = !absolute && edge === null
+
+ let moved = false
+
+ let morph = false
+
+ let zone: Snap | null = null
+
+ let shown: Snap | null = null
+
+ let renderFrame = 0
+
+ const start = { pointerX: event.clientX, pointerY: event.clientY }
+
+ // Pointer hardware can report faster than the display can paint. Keep
+ // gesture state authoritative while scheduling at most one React
+ // update for each visual frame.
+ function renderGesture() {
+
+ if (renderFrame) return
+
+ renderFrame = requestAnimationFrame(function () {
+
+ renderFrame = 0
+
+ setGesture({ origin, current, zone, shown, morph })
+ })
+ }
+
+ // Zones are where the pointer is — within 16px of an edge — and
+ // they name shares of the surface, which each client resolves in
+ // its own space.
+ function snapTerm(motion: globalThis.PointerEvent): Snap | null {
+
+ const pointerX = motion.clientX - bounds!.left
+
+ const pointerY = motion.clientY - bounds!.top
+
+ const west = pointerX <= 16
+
+ const east = pointerX >= bounds!.width - 16
+
+ const north = pointerY <= 16
+
+ const south = pointerY >= bounds!.height - 16
+
+ if (!west && !east && !north && !south) return null
+
+ return {
+
+ position: { x: east ? "1/2" : "0/1", y: south ? "1/2" : "0/1" },
+
+ size: { width: west || east ? "1/2" : "1/1", height: north || south ? "1/2" : "1/1" }
+ }
+ }
+
+ function move(motion: globalThis.PointerEvent) {
+
+ const dx = motion.clientX - start.pointerX
+
+ const dy = motion.clientY - start.pointerY
+
+ // A click is not a drag: without this, releasing a stationary
+ // press inside a snap zone would snap the window.
+ if (Math.hypot(dx, dy) >= 4) moved = true
+
+ if (restoring) {
+
+ if (Math.hypot(dx, dy) < 8) return
+
+ restoring = false
+
+ // The window returns to its floating size placed so the
+ // pointer keeps its proportional position across the
+ // header, and the same gesture carries on dragging.
+ const pointerX = motion.clientX - bounds!.left
+
+ const pointerY = motion.clientY - bounds!.top
+
+ const ratio = Math.min(Math.max((pointerX - origin.x) / origin.width, 0), 1)
+
+ origin = { x: pointerX - origin.width * ratio, y: pointerY - Math.min(Math.max(pointerY - origin.y, 0), 40), width: origin.width, height: origin.height }
+
+ current = { ...origin }
+
+ start.pointerX = motion.clientX
+
+ start.pointerY = motion.clientY
+
+ onMove?.(origin.x, origin.y)
+
+ // The shrink to floating size glides while the pointer
+ // stays live: a brief morph phase transitions the body,
+ // never the transform — and it must survive the moves
+ // that arrive while it plays.
+ morph = !reducedMotion
+
+ if (morph) setTimeout(() => {
+
+ morph = false
+
+ setGesture(active => active && { ...active, morph: false })
+
+ }, 220)
+
+ setGesture({ origin, current, zone, shown, morph })
+
+ return
+ }
+
+ if (edge === null) {
+
+ current = { ...origin, x: origin.x + dx, y: origin.y + dy }
+
+ zone = moved ? snapTerm(motion) : null
+
+ if (zone) shown = zone
+ }
+
+ else {
+
+ current = { ...current }
+
+ if (edge.includes("e")) current.width = Math.max(minWidth, origin.width + dx)
+
+ if (edge.includes("s")) current.height = Math.max(minHeight, origin.height + dy)
+
+ // West and north move the origin as well as the size; the
+ // clamped size keeps the far edge still at the minimum.
+ if (edge.includes("w")) {
+
+ current.width = Math.max(minWidth, origin.width - dx)
+
+ current.x = origin.x + origin.width - current.width
+ }
+
+ if (edge.includes("n")) {
+
+ current.height = Math.max(minHeight, origin.height - dy)
+
+ current.y = origin.y + origin.height - current.height
+ }
+ }
+
+ renderGesture()
+ }
+
+ function release(motion: globalThis.PointerEvent) {
+
+ if (renderFrame) cancelAnimationFrame(renderFrame)
+
+ handle.removeEventListener("pointermove", move)
+
+ handle.removeEventListener("pointerup", release)
+
+ handle.removeEventListener("pointercancel", release)
+
+ // A tiled press that never crossed the threshold changed
+ // nothing: the render returns to the tile it never left.
+ if (restoring) {
+
+ setGesture(null)
+
+ return
+ }
+
+ const term = moved && edge === null && motion.type === "pointerup" ? snapTerm(motion) : null
+
+ // The outcome and the gesture's end land in one batch: the
+ // record updates as the gesture stops overriding it, so the
+ // frame never shows a stale in-between.
+ if (term) onSnap?.(term.position, term.size)
+
+ else if (moved && motion.type === "pointerup") {
+
+ if (edge === null) onMove?.(current.x, current.y)
+
+ // Only the west and north edges move the origin. A drag
+ // on any other reports no position, because none was
+ // chosen — and a position nobody chose would replace a
+ // share with the pixels it happened to resolve to.
+ else onResize?.(current.width, current.height, current.x === origin.x && current.y === origin.y ? null : { x: current.x, y: current.y })
+
+ if (!reducedMotion) setLanded(true)
+ }
+
+ setGesture(null)
+ }
+
+ handle.addEventListener("pointermove", move)
+
+ handle.addEventListener("pointerup", release)
+
+ handle.addEventListener("pointercancel", release)
+
+ setGesture({ origin, current, zone, shown, morph: false })
+ }
+
+ // ------------------------------------------------------------ render
+
+ // The geometry, declared whole every render: the gesture's rectangle
+ // while one runs — movement as a transform above the grabbed origin,
+ // transitions paused — otherwise the record's own form.
+ const geometry = gesture
+
+ ? { left: gesture.origin.x, top: gesture.origin.y, width: gesture.current.width, height: gesture.current.height, transform: `translate(${gesture.current.x - gesture.origin.x}px, ${gesture.current.y - gesture.origin.y}px)`, transition: gesture.morph && !reducedMotion ? morphing : "none" }
+
+ : {
+
+ left: resolveWindowValue(position.x),
+
+ top: resolveWindowValue(position.y),
+
+ width: resolveWindowValue(size.width),
+
+ height: resolveWindowValue(size.height),
+
+ transform: "none",
+
+ // Bare, geometry does not travel. A window the system
+ // paints nothing on is one whose motion is not the
+ // system's either: asked to be somewhere, it is there,
+ // rather than gliding over half a second nobody asked for.
+ transition: bare || landed || reducedMotion ? "none" : settle
+ }
+
+ const surface = active
+
+ ? "shadow-window-active"
+
+ : "shadow-window-inactive"
+
+ const paintedInsets = windowPaintInsets(position, size, paintSurfaceSize, gesture?.current)
+
+ return <>
+
+ {/* The snap preview and its result resolve the same edge contacts. */}
+ {gesture?.shown && <div
+
+ className="pointer-events-none absolute"
+
+ style={{ left: resolveWindowValue(gesture.shown.position.x), top: resolveWindowValue(gesture.shown.position.y), width: resolveWindowValue(gesture.shown.size.width), height: resolveWindowValue(gesture.shown.size.height), opacity: gesture.zone ? 1 : 0, transition: reducedMotion ? "none" : "opacity 0.15s, left 0.18s, top 0.18s, width 0.18s, height 0.18s", zIndex: style?.zIndex }}
+
+ >
+
+ <div data-snap-preview-frame className="absolute border border-white/50 bg-white/25 shadow-snap-preview backdrop-blur-sm" style={bare ? { inset: 0 } : { ...windowPaintInsets(gesture.shown.position, gesture.shown.size, paintSurfaceSize), borderRadius: outerRadius }} />
+
+ </div>}
+
+ <div
+
+ ref={frame}
+
+ onPointerDown={onActivate}
+
+ // DOM focus and desktop focus are one fact. Tabbing into a
+ // background window therefore raises the same window a press
+ // would; the keyboard does not maintain a second selection.
+ onFocusCapture={event => {
+
+ if (!active && !minimized && !closing) onActivate?.()
+
+ onFocusCapture?.(event)
+ }}
+
+ className={`absolute ${minimized || closing ? "pointer-events-none" : "pointer-events-auto"} ${className ?? ""}`}
+
+ style={{ ...geometry, ...style }}
+
+ {...props}
+
+ // A hidden pane is absent from sequential focus as well as
+ // pointer hit-testing. Visibility currently provides the same
+ // effect visually; inert states the interaction rule directly.
+ inert={minimized || closing}
+
+ >
+
+ {/* The painted frame, inset inside the box. The box is where
+ the window *is*; this is what a person sees of it, and the
+ difference between them is the gap.
+
+ Bare, there is no difference: the frame fills the box, so
+ the window is exactly as large as it asked to be and its
+ boundaries are the ones its own content draws. */}
+ <div data-window-container ref={glass} style={bare ? { inset: 0 } : { ...paintedInsets, borderRadius: outerRadius }} className={`absolute isolate grid ${bare ? "grid-rows-1" : `overflow-hidden grid-rows-[auto_minmax(0,1fr)] ${reducedMotion ? "" : "transition-shadow duration-200"} ${surface}`}`}>
+
+ {/* A bare Client cannot refract the desktop through its iframe.
+ Its host surface is therefore a sibling behind the frame,
+ with its own radius and no clipping parent. */}
+ {bare && windowSurface && <WindowSurface settings={windowSurface} revision={windowSurfaceRevision} />}
+
+ {/* LAYER 1 — the shared Theme-driven glass material. */}
+ {!bare && <GlassSurface aria-hidden="true" radius="inherit" className="pointer-events-none absolute inset-0" />}
+
+ {!bare && <WindowHeader
+
+ title={title}
+
+ icon={icon}
+
+ active={active}
+
+ whole={whole}
+
+ reducedMotion={reducedMotion}
+
+ onGrab={event => grab(event, null)}
+
+ onMinimize={onMinimize}
+
+ onMaximize={onMaximize}
+
+ onClose={onClose}
+
+ stopping={stopping}
+
+ />}
+
+ {/* Where the program is. Bare, it is the whole of the
+ box and wears none of the system's own edges. */}
+ <div data-window-content style={bare ? undefined : { borderRadius: innerRadius }} className={bare ? "relative min-h-0" : "relative m-1.5 mt-0 min-h-0 overflow-hidden bg-white/25 shadow-window-content"}>
+
+ {children}
+
+ </div>
+
+ </div>
+
+ {edges.map(handle => <div
+
+ key={handle.edge}
+
+ onPointerDown={event => grab(event, handle.edge)}
+
+ className={`absolute touch-none ${handle.className}`}
+
+ />)}
+
+ </div>
+
+ </>
+}
+
+type WindowEdge = "n" | "s" | "e" | "w" | "ne" | "nw" | "se" | "sw"
+
+interface Snap {
+
+ position: Position
+
+ size: Size
+}
+
+interface WindowProps extends Omit<ComponentProps<"div">, "title"> {
+
+ title?: ReactNode
+
+ // Drawn beside the title. A URL rather than a node: what a window
+ // shows of its program is a picture the browser fetches, and the
+ // path it fetches from is the view's to build.
+ icon: string
+
+ onClose?: () => void
+
+ onClosed?: () => void
+
+ onMinimize?: () => void
+
+ onMaximize?: () => void
+
+ onActivate?: () => void
+
+ /** The window is leaving interaction; its composition chooses new focus. */
+ onUnavailable?: (reason: "minimize" | "close") => void
+
+ onMove?: (x: number, y: number) => void
+
+ onResize?: (width: number, height: number, position: { x: number, y: number } | null) => void
+
+ onSnap?: (position: Position, size: Size) => void
+
+ active?: boolean
+
+ // Nothing the system paints. The window's boundaries become the
+ // frame's exactly: no glass, no shadow, no rounding, no header, no
+ // controls, and no gutter — so what a program asked to be is what it
+ // gets, edge to edge, rather than half a gutter smaller.
+ //
+ // What stays is what is invisible and functional. The resize edges
+ // are hit areas rather than paint, so they stay; the geometry, the
+ // snapping and the layer are the system's and stay. What goes is
+ // only what was there to be seen.
+ bare?: boolean
+
+ closing?: boolean
+
+ /** The Process termination request has not settled yet. */
+ stopping?: boolean
+
+ minimized?: boolean
+
+ // Whether mounting this element represents a newly opened window.
+ animateEntrance?: boolean
+
+ position?: Position
+
+ size?: Size
+
+ /** Authoritative host Surface target behind a bare iframe. */
+ windowSurface?: WindowSurfaceSettings | null
+
+ /** Desktop delivery revision used to distinguish live changes from snapshots. */
+ windowSurfaceRevision?: number
+
+ /** Surface used only to decide which painted edges receive an inset. */
+ paintSurfaceSize?: WindowSurfaceSize
+
+ minWidth?: number
+
+ minHeight?: number
+
+}
+
+interface Gesture {
+
+ origin: WindowRegion
+
+ current: WindowRegion
+
+ zone: Snap | null
+
+ shown: Snap | null
+
+ morph: boolean
+}
diff --git a/source/client/view/desktop/workspace.tsx b/source/client/view/desktop/workspace.tsx
new file mode 100644
index 0000000..0dabc25
--- /dev/null
+++ b/source/client/view/desktop/workspace.tsx
@@ -0,0 +1,247 @@
+import { type Layer } from "@server/core/link-manager/auth-manager/program-manager/config"
+import { type SyntheticEvent, useCallback, useRef, useState } from "react"
+import { ApplicationContext, AuthManagerContext } from "../contexts"
+import useClientHost from "./client-host/client-host"
+import DesktopDisplay from "./desktop-display"
+import useDesktopFocus from "./desktop-focus"
+import programIcon from "./programs/program-icon"
+import ProgramAccessProbe, { type ProgramAccess } from "./program-access"
+import StartMenu from "./start-menu/start-menu"
+import OverflowRow from "./taskbar/overflow-row"
+import SignOut from "./taskbar/sign-out"
+import SystemDialogs from "./taskbar/system-dialogs"
+import Taskbar from "./taskbar/taskbar"
+import WindowTaskbarItem from "./taskbar/window-taskbar-item"
+import ProcessWindow from "./window-manager/process-window"
+import useWindows from "./window-manager/window-manager"
+import useProperty from "@libs/the-link/plugins/react-helper/property-hook"
+import { WallpaperBackground } from "../components/wallpaper"
+import ProgramFrame from "./program-frame"
+import Loading from "../components/loading"
+
+export default function Workspace() {
+
+ const application = ApplicationContext.useValue()
+
+ const authManager = AuthManagerContext.useValue()
+
+ const desktopWallpaper = useProperty(authManager.linkManager.desktopWallpaper)
+
+ const windows = useWindows()
+
+ const wallpaperIdentity = windows.wallpaper?.identity ?? null
+
+ const [readyWallpaper, setReadyWallpaper] = useState<string | null>(null)
+
+ const [fileWallpaperReady, setFileWallpaperReady] = useState(false)
+
+ const programWallpaperReady = wallpaperIdentity !== null && readyWallpaper === wallpaperIdentity
+
+ const wallpaperReady = windows.wallpaper ? programWallpaperReady : fileWallpaperReady
+
+ const desktop = useRef<HTMLDivElement>(null)
+
+ const [programAccess, setProgramAccess] = useState<ProgramAccess>("checking")
+
+ // Each frame, by process identity. This resolves a message's sender and
+ // lets the desktop announce the surface that actually contains it.
+ const sources = useRef(new Map<string, HTMLIFrameElement | null>())
+
+ const { windowSurfaceRef, windowSurfaceSize, frame, frameLoaded } = useClientHost(desktop, sources.current)
+
+ const wallpaperLoaded = useCallback((event: SyntheticEvent<HTMLIFrameElement>) => {
+
+ const wallpaper = windows.wallpaper
+
+ if (wallpaper) {
+
+ frameLoaded(wallpaper.identity, event.currentTarget)
+
+ setReadyWallpaper(wallpaper.identity)
+ }
+
+ }, [frameLoaded, windows.wallpaper])
+
+ const fileWallpaperLoaded = useCallback(() => setFileWallpaperReady(true), [])
+
+ const focus = useDesktopFocus(desktop, windows)
+
+ // Resolved once per desktop render. Asking inside every window and
+ // taskbar item would repeat the same linear scan for each process.
+ const fronts = windows.fronts
+
+ function icon(record: { assetId: string }) {
+
+ return programIcon(application.doors.program, record.assetId)
+ }
+
+ function renderWindows(layer: Layer) {
+
+ return windows.panesByLayer[layer].map(({ identity, record, client, closing, entering, stopping }) => <ProcessWindow
+
+ key={identity}
+
+ identity={identity}
+
+ record={record}
+
+ client={client}
+
+ title={client.window.title}
+
+ icon={icon(record)}
+
+ position={client.window.position}
+
+ size={client.window.size}
+
+ windowSurface={client.window.surface}
+
+ windowSurfaceRevision={client.window.surfaceRevision}
+
+ // Only system-painted windows need to know which paint edges
+ // touch their surface. Positioning is identical in every layer.
+ paintSurfaceSize={layer === "window" ? windowSurfaceSize : undefined}
+
+ depth={client.window.depth}
+
+ active={fronts[layer]?.identity === record.identity}
+
+ bare={layer !== "window"}
+
+ minimized={client.window.minimized}
+
+ closing={closing}
+
+ stopping={stopping}
+
+ entering={entering}
+
+ door={application.doors.program}
+
+ programAccess={programAccess}
+
+ onFrame={frame}
+
+ onFrameLoad={frameLoaded}
+
+ onRaise={windows.raise}
+
+ onMinimize={focus.minimize}
+
+ onFill={windows.fill}
+
+ onClose={focus.close}
+
+ onClosed={windows.closed}
+
+ onUnavailable={focus.unavailable}
+
+ onMove={windows.move}
+
+ onResize={windows.resize}
+
+ onSnap={windows.snap}
+
+ />)
+ }
+
+ const taskbar = <Taskbar
+
+ leading={<StartMenu />}
+
+ trailing={<SignOut />}
+
+ dialogs={<SystemDialogs />}
+
+ className="z-4 overflow-hidden"
+
+ >
+
+ {/* What a press means is composed here because it is a person's
+ expectation, not a system operation: the front window hides;
+ another window is shown and brought forward. */}
+ <OverflowRow aria-label="Open windows" backwardLabel="Earlier windows" forwardLabel="Later windows">
+
+ {windows.listed.map(record => <WindowTaskbarItem
+
+ key={record.identity}
+
+ record={record}
+
+ title={record.client!.window.title}
+
+ icon={icon(record)}
+
+ active={!record.client!.window.minimized && fronts.window?.identity === record.identity}
+
+ onElement={focus.taskbarItem}
+
+ onMinimize={focus.minimize}
+
+ onShow={windows.show}
+
+ />)}
+
+ </OverflowRow>
+
+ </Taskbar>
+
+ const wallpaper = <>
+
+ <WallpaperBackground
+
+ file={windows.wallpaper ? undefined : desktopWallpaper}
+
+ visible={!programWallpaperReady}
+
+ onReady={fileWallpaperLoaded}
+
+ />
+
+ {windows.wallpaper?.client && programAccess !== "checking" && <ProgramFrame
+
+ record={windows.wallpaper}
+
+ client={windows.wallpaper.client}
+
+ title={windows.wallpaper.client.window.title}
+
+ door={application.doors.program}
+
+ access={programAccess}
+
+ className={`absolute inset-0 size-full border-0 ${programWallpaperReady ? "" : "pointer-events-none opacity-0"}`}
+
+ onFrame={frame}
+
+ onLoad={wallpaperLoaded}
+
+ />}
+
+ </>
+
+ return <div ref={desktop} tabIndex={-1} aria-label="Desktop" onFocusCapture={focus.remember} className="relative isolate grid min-h-0 grid-cols-1 grid-rows-1 outline-none">
+
+ <ProgramAccessProbe door={application.doors.program} setAccess={setProgramAccess} />
+
+ <DesktopDisplay
+
+ wallpaper={wallpaper}
+
+ underWindows={renderWindows("under")}
+
+ windows={renderWindows("window")}
+
+ overWindows={renderWindows("over")}
+
+ windowSurfaceRef={windowSurfaceRef}
+
+ taskbar={taskbar}
+
+ />
+
+ {!wallpaperReady && <Loading />}
+
+ </div>
+}
diff --git a/source/client/view/view.tsx b/source/client/view/view.tsx
new file mode 100644
index 0000000..9603823
--- /dev/null
+++ b/source/client/view/view.tsx
@@ -0,0 +1,46 @@
+import Appearance from "./appearance/appearance"
+import Application, { type Doors } from "@client/core/application"
+import { ApplicationContext } from "./contexts"
+import Desktop from "./desktop/desktop"
+import client from "react-dom/client"
+import logo from "@/assets/bundled/logo.png"
+
+export default function (config: Config) {
+
+ config.document.title = `${config.displayName} v${config.version}`
+
+ const link = config.document.createElement("link")
+
+ link.rel = "icon"
+
+ link.href = logo
+
+ config.document.head.appendChild(link)
+
+ const application = new Application(config.name, config.displayName, config.version, config.doors)
+
+ const root = client.createRoot(config.document.body)
+
+ root.render(<ApplicationContext.Provider value={application}>
+
+ <Appearance>
+
+ <Desktop />
+
+ </Appearance>
+
+ </ApplicationContext.Provider>)
+}
+
+export interface Config {
+
+ doors: Doors
+
+ name: string
+
+ displayName: string
+
+ version: string
+
+ document: Document
+}
diff --git a/source/dev.ts b/source/dev.ts
new file mode 100644
index 0000000..9642617
--- /dev/null
+++ b/source/dev.ts
@@ -0,0 +1,38 @@
+import { displayName, name, version } from "@/package.json"
+import doors from "@server/view/doors"
+import view, { environmentHome, environmentPort } from "@server/view/view"
+import { createServer } from "vite"
+import { fileURLToPath } from "node:url"
+
+const storage = environmentHome(name, process.env) ?? fileURLToPath(new URL("../storage", import.meta.url))
+
+const host = await view({ name, displayName, version, mode: "development", hostname: "localhost", storage })
+
+const port = environmentPort(name, process.env)
+
+const client = await createServer({
+
+ configFile: "vite.client.ts",
+
+ server: {
+
+ allowedHosts: true,
+
+ port,
+
+ strictPort: port !== undefined,
+
+ proxy: Object.fromEntries(Object.values(doors).map(door => [door, {
+
+ changeOrigin: true,
+
+ target: host.origin,
+
+ ws: door === doors.link
+ }]))
+ }
+})
+
+await client.listen()
+
+client.printUrls()
diff --git a/source/libs/cleanup-hook.ts b/source/libs/cleanup-hook.ts
new file mode 100644
index 0000000..2c064df
--- /dev/null
+++ b/source/libs/cleanup-hook.ts
@@ -0,0 +1,17 @@
+import { DependencyList, useEffect } from "react"
+
+/**
+ * Registers a cleanup function that runs when the component unmounts
+ * or when any value in the dependency list changes.
+ *
+ * Wraps `useEffect` so that only the teardown callback needs to be provided,
+ * keeping call sites concise when no setup logic is required.
+ *
+ * @param cleanup - Teardown function executed on unmount or dependency change
+ * @param deps - Optional dependency list controlling when the cleanup is re-registered
+ */
+export default function useCleanup(cleanup: () => void, deps?: DependencyList) {
+
+ // Delegate to useEffect, returning the cleanup directly as the teardown phase
+ useEffect(() => cleanup, deps)
+}
\ No newline at end of file
diff --git a/source/libs/decorator-plugin.ts b/source/libs/decorator-plugin.ts
new file mode 100644
index 0000000..3815dfe
--- /dev/null
+++ b/source/libs/decorator-plugin.ts
@@ -0,0 +1,20 @@
+import babel from "@rolldown/plugin-babel"
+
+export default function decoratorPlugin() {
+
+ return babel({
+
+ presets: [{
+
+ preset: () => ({
+
+ plugins: [["@babel/plugin-proposal-decorators", { version: "2023-11" }]]
+ }),
+
+ rolldown: {
+
+ filter: { code: "@" }
+ }
+ }]
+ })
+}
\ No newline at end of file
diff --git a/source/libs/encryptor.ts b/source/libs/encryptor.ts
new file mode 100644
index 0000000..d8efd83
--- /dev/null
+++ b/source/libs/encryptor.ts
@@ -0,0 +1,145 @@
+/**
+ * # Encryptor: Secure Token Generation and Verification System
+ *
+ * Encryptor provides RSA-based cryptographic utilities for creating and verifying
+ * secure tokens. It extends NodeRSA to offer simplified token generation and validation
+ * for authentication and authorization workflows.
+ *
+ * The system uses asymmetric cryptography for:
+ * - Creating signed tokens containing arbitrary payloads
+ * - Verifying token authenticity through signature validation
+ * - Managing RSA key pairs with automatic key generation
+ *
+ * This implementation is ideal for stateless authentication systems, API authorization,
+ * secure data exchange between services, or any scenario requiring cryptographic
+ * verification of data integrity and origin.
+ */
+import { readFile, writeFile } from "fs/promises"
+import { existsSync } from "node:fs"
+import NodeRSA from "node-rsa"
+
+/**
+ * Cryptographic utility for token generation and verification using RSA.
+ * Extends NodeRSA to provide higher-level functions for working with signed tokens
+ * that can contain any serializable data payload.
+ */
+export default class Encryptor extends NodeRSA {
+
+ /**
+ * Creates and initializes an Encryptor instance with an existing private key or generates a new one.
+ * This factory method handles key generation, persistence, and instance creation in one operation.
+ *
+ * If a key exists at the specified path, it loads and uses that key.
+ * If no key exists, it generates a new 2048-bit RSA key and saves it to the provided path.
+ *
+ * @param privateKeyPath The filesystem path where the private key is stored or should be created
+ * @returns A configured Encryptor instance ready for token operations
+ *
+ * @example
+ *
+ * const encryptor = await Encryptor.initialize("/path/to/private-key.pem")
+ * // The encryptor is now ready to create and verify tokens
+ */
+ public static async initialize(privateKeyPath: string) {
+
+ let encryptor: Encryptor
+
+ // Check if the private key file already exists
+ if (existsSync(privateKeyPath)) {
+
+ // Load the existing key from the file
+ encryptor = new this(await readFile(privateKeyPath, "utf-8"))
+ }
+
+ else {
+
+ // No key exists, so generate a new 2048-bit RSA key
+ encryptor = new this({ b: 2048 })
+
+ // Save the newly generated key to the specified path
+ await writeFile(privateKeyPath, encryptor.exportKey("pkcs1-private-pem"))
+ }
+
+ // Return the configured encryptor instance
+ return encryptor
+ }
+
+ /**
+ * Creates a signed token containing the provided payload.
+ * The token format follows a simplified JWT-like structure of "{encoded_payload}.{signature}"
+ * where the payload is base64-encoded JSON and the signature is a base64-encoded RSA signature.
+ *
+ * This method:
+ * 1. Serializes and encodes the payload
+ * 2. Creates a cryptographic signature of the encoded payload
+ * 3. Combines them into a portable, verifiable token string
+ *
+ * @param payload Any serializable data to include in the token
+ * @returns A signed token string in the format "encoded_payload.signature"
+ *
+ * @example
+ *
+ * const token = encryptor.createToken({ userId: 123, role: "admin" })
+ * // Returns a string like "eyJwYXlsb2FkIjp7InVzZX...FyTxp4n2K0="
+ */
+ public createToken(payload: unknown): string {
+
+ // Serialize the payload to JSON and encode it to base64
+ const encode = btoa(JSON.stringify({ payload }))
+
+ // Generate a cryptographic signature for the encoded payload
+ const signature = this.sign(encode, "base64")
+
+ // Combine the encoded payload and signature with a dot separator
+ return `${encode}.${signature}`
+ }
+
+ /**
+ * Verifies a token's authenticity and extracts its payload.
+ * This method validates that the token was created by a system with the corresponding private key
+ * and has not been tampered with since creation.
+ *
+ * The verification process:
+ * 1. Splits the token into payload and signature components
+ * 2. Verifies the signature against the payload using RSA
+ * 3. Decodes and deserializes the full token structure if verification succeeds
+ *
+ * @param token A token string previously generated by createToken()
+ * @returns A Reference object containing the payload, or false if verification fails
+ *
+ * @example
+ *
+ * const result = encryptor.verifyToken<UserData>(token)
+ * if (result) {
+ * // result.payload contains the original data: { userId: 123, role: "admin" }
+ * } else {
+ * // Handle invalid token
+ * }
+ */
+ public verifyToken<Payload>(token: string): Reference<Payload> | false {
+
+ // Split the token into its two components: encoded payload and signature
+ const [encode, signature] = token.split(".")
+
+ // Convert the base64 signature to a Buffer for verification
+ const bufferSignature = Buffer.from(signature, "base64")
+
+ // Verify that the signature matches the encoded payload
+ // If verification fails, return false to indicate an invalid token
+ if (!this.verify(encode, bufferSignature)) return false
+
+ return JSON.parse(atob(encode))
+ }
+}
+
+/**
+ * Represents the structure of a verified token containing the original payload.
+ * This interface wraps the decoded token payload to maintain type safety
+ * and provide a consistent return format from the verifyToken method.
+ *
+ * @template Payload The type of the original data that was encoded in the token
+ */
+export interface Reference<Payload> {
+ /** The original payload data that was encoded in the token */
+ payload: Payload
+}
\ No newline at end of file
diff --git a/source/libs/environment.ts b/source/libs/environment.ts
new file mode 100644
index 0000000..54bec98
--- /dev/null
+++ b/source/libs/environment.ts
@@ -0,0 +1,22 @@
+/** Read one application-scoped environment variable without interpreting it. */
+export default function environment(application: string, variable: string, variables: Variables) {
+
+ const scope = normalize(application)
+
+ const name = normalize(variable)
+
+ if (!scope) throw new Error("An environment variable needs an application name")
+
+ if (!name) throw new Error("An environment variable needs a name")
+
+ const key = `${scope}_${name}`
+
+ return Object.freeze({ key, value: variables[key] })
+}
+
+function normalize(value: string) {
+
+ return value.replace(/[^a-zA-Z0-9]+/g, "_").replace(/^_+|_+$/g, "").toUpperCase()
+}
+
+type Variables = Readonly<Record<string, string | undefined>>
diff --git a/source/libs/file-area.ts b/source/libs/file-area.ts
new file mode 100644
index 0000000..7deafe5
--- /dev/null
+++ b/source/libs/file-area.ts
@@ -0,0 +1,153 @@
+import { createReadStream, createWriteStream, mkdirSync, readdirSync, renameSync, rmSync, statSync } from "node:fs"
+import { randomUUID } from "node:crypto"
+import { dirname, isAbsolute, join, relative, sep } from "node:path"
+import { rm } from "node:fs/promises"
+import { Readable } from "node:stream"
+import { pipeline } from "node:stream/promises"
+import { type ReadableStream as NodeReadableStream } from "node:stream/web"
+
+/** File operations structurally confined to one root directory. */
+export default class FileArea {
+
+ public readonly path: string
+
+ public readonly label: string
+
+ public constructor(path: string, label = "this area") {
+
+ this.path = path
+
+ this.label = label
+
+ mkdirSync(path, { recursive: true })
+ }
+
+ public resolve(joins: string[]) {
+
+ const path = join(this.path, ...joins)
+
+ const step = relative(this.path, path)
+
+ if (step === ".." || step.startsWith(`..${sep}`) || isAbsolute(step)) throw new Error("A storage path may not leave its area")
+
+ return path
+ }
+
+ public clear() {
+
+ rmSync(this.path, { recursive: true, force: true })
+
+ mkdirSync(this.path, { recursive: true })
+ }
+
+ public stat(joins: string[]): EntryStat | null {
+
+ let found
+
+ try {
+
+ found = statSync(this.resolve(joins))
+ }
+
+ catch (exception) {
+
+ if ((exception as NodeJS.ErrnoException).code === "ENOENT") return null
+
+ throw exception
+ }
+
+ const modifiedAt = Math.round(found.mtimeMs)
+
+ if (found.isFile()) return { kind: "file", size: found.size, modifiedAt }
+
+ if (found.isDirectory()) return { kind: "directory", modifiedAt }
+
+ return { kind: "other", modifiedAt }
+ }
+
+ public list(joins: string[]) {
+
+ return readdirSync(this.resolve(joins)).sort()
+ }
+
+ public delete(joins: string[]) {
+
+ if (joins.length === 0) throw new Error("Emptying a place is clear, not delete")
+
+ rmSync(this.resolve(joins), { recursive: true, force: true })
+ }
+
+ public stream(joins: string[]) {
+
+ const found = this.stat(joins)
+
+ if (!found) throw new MissingAreaEntryError(`There is no ${joins.join("/")} in ${this.label}`)
+
+ if (found.kind !== "file") throw new NotFileError(`${joins.join("/")} is not a file`)
+
+ return Readable.toWeb(createReadStream(this.resolve(joins))) as ReadableStream<Uint8Array>
+ }
+
+ public async write(joins: string[], content: ReadableStream<Uint8Array> | null, signal?: AbortSignal) {
+
+ if (joins.length === 0) throw new Error("Writing takes a file name and what to write")
+
+ if (!content) throw new Error("Writing takes a byte stream")
+
+ const path = this.resolve(joins)
+
+ mkdirSync(dirname(path), { recursive: true })
+
+ const temporary = join(dirname(path), `.${randomUUID()}.writing`)
+
+ try {
+
+ await pipeline(
+
+ Readable.fromWeb(content as unknown as NodeReadableStream<Uint8Array>),
+
+ createWriteStream(temporary, { flags: "wx" }),
+
+ { signal }
+ )
+
+ renameSync(temporary, path)
+ }
+
+ catch (exception) {
+
+ await rm(temporary, { force: true }).catch(() => undefined)
+
+ throw exception
+ }
+ }
+}
+
+export type EntryStat = FileStat | DirectoryStat | OtherStat
+
+export interface FileStat {
+
+ kind: "file"
+
+ size: number
+
+ modifiedAt: number
+}
+
+export interface DirectoryStat {
+
+ kind: "directory"
+
+ modifiedAt: number
+}
+
+export interface OtherStat {
+
+ kind: "other"
+
+ modifiedAt: number
+}
+
+export class MissingAreaEntryError extends Error { }
+
+export class NotFileError extends Error { }
diff --git a/source/libs/file-manager.ts b/source/libs/file-manager.ts
new file mode 100644
index 0000000..6bba702
--- /dev/null
+++ b/source/libs/file-manager.ts
@@ -0,0 +1,233 @@
+/**
+ * # FileManager: Application Directory Management System
+ *
+ * Cross-platform file system abstraction providing standardized directory
+ * management for application data storage and configuration persistence.
+ *
+ * ## Core Capabilities
+ * - Automatic directory creation with recursive path resolution
+ * - Platform-agnostic application data directory management
+ * - Path composition utilities for nested file organization
+ * - Home directory integration following OS conventions
+ *
+ * ## Use Cases
+ * - Application configuration and settings persistence
+ * - User data storage and cache management
+ * - Plugin and extension data organization
+ * - Cross-platform data directory standardization
+ *
+ * @example
+ * ```typescript
+ * // Application-specific directory management
+ * const appManager = FileManager.forApp("myapp");
+ * // Creates: @/.myapp/ (Unix) or %USERPROFILE%\.myapp\ (Windows)
+ *
+ * // Custom directory hierarchy
+ * const dataManager = new FileManager("/var", "data", "application");
+ *
+ * // Nested file path composition
+ * const configPath = appManager.join("config", "settings.json");
+ * ```
+ */
+import { existsSync, mkdirSync, rmSync } from "node:fs"
+import { homedir } from "node:os"
+import { join } from "node:path"
+
+/**
+ * Application directory management system providing automatic directory creation
+ * and standardized path composition for cross-platform file operations.
+ *
+ * Implements "create-on-instantiation" pattern where directories are automatically
+ * created if they don't exist, eliminating manual existence validation.
+ */
+export default class FileManager {
+
+ /**
+ * Absolute file system path to the managed directory.
+ * Guaranteed to exist in the file system after instantiation.
+ */
+ public readonly path: string
+
+ /**
+ * Initializes FileManager instance with automatic directory creation.
+ *
+ * Combines path segments using OS-appropriate separators and creates
+ * missing directories recursively, including intermediate paths.
+ *
+ * @param paths - Variable number of path segments to combine into target directory
+ *
+ * @example
+ * ```typescript
+ * // Single directory creation
+ * const tempManager = new FileManager("/tmp", "workspace");
+ *
+ * // Multi-level hierarchy creation
+ * const dataManager = new FileManager("data", "cache", "images");
+ * ```
+ */
+ public constructor(...paths: string[]) {
+
+ /**
+ * Combine all path segments into normalized absolute path.
+ */
+ this.path = join(...paths)
+
+ /**
+ * Ensure target directory exists with recursive creation.
+ */
+ if (!existsSync(this.path)) mkdirSync(this.path, { recursive: true })
+ }
+
+ /**
+ * Factory method for application-specific directory management.
+ *
+ * Creates a FileManager instance targeting the user's home directory
+ * with a hidden application folder following OS conventions.
+ *
+ * @param appName - Application identifier used for directory naming
+ * @returns FileManager instance managing application-specific directory
+ *
+ * @example
+ * ```typescript
+ * // Standard application data directory
+ * const configManager = FileManager.forApp("texteditor");
+ * // Creates: @/.texteditor/
+ *
+ * // Nested configuration structure
+ * const settingsPath = configManager.join("settings.json");
+ * ```
+ */
+ public static forApp(appName: string) {
+
+ /**
+ * Create FileManager instance targeting hidden application directory.
+ */
+ return new FileManager(homedir(), `.${appName}`)
+ }
+
+ /**
+ * Composes file paths within the managed directory structure.
+ *
+ * Provides safe path composition by combining the managed directory path
+ * with additional segments, ensuring cross-platform compatibility and
+ * preventing directory traversal issues.
+ *
+ * @param paths - Variable number of path segments to append to managed directory
+ * @returns Absolute path combining managed directory with specified segments
+ *
+ * @example
+ * ```typescript
+ * const appManager = FileManager.forApp("myapp");
+ *
+ * // Configuration file paths
+ * const configFile = appManager.join("config.json");
+ * const userSettings = appManager.join("settings", "user.json");
+ *
+ * // Cache directory structure
+ * const imageCache = appManager.join("cache", "images", "thumbnails");
+ * ```
+ */
+ public join(...paths: string[]) {
+
+ /**
+ * Combine managed directory path with additional segments.
+ */
+ return join(this.path, ...paths)
+ }
+
+ /**
+ * Permanently removes the managed directory and all its contents.
+ *
+ * Deletes the entire directory structure without recreation, effectively
+ * destroying the FileManager's target. Use this when the directory is no
+ * longer needed, as opposed to clear() which maintains the directory.
+ *
+ * @example
+ * ```typescript
+ * const tempManager = FileManager.forApp("myapp").navigateTo("temp");
+ * tempManager.destroy(); // Completely removes the temp directory
+ * ```
+ */
+ public destroy() {
+
+ // Remove directory and all contents without recreation
+ if (existsSync(this.path)) rmSync(this.path, { recursive: true, force: true })
+ }
+
+ /**
+ * Clears all files and directories within the managed directory.
+ *
+ * Removes all contents recursively while preserving the root directory.
+ * Safe operation that only affects contents within the managed path.
+ *
+ * @example
+ * ```typescript
+ * const cacheManager = FileManager.forApp("myapp").navigateTo("cache");
+ * cacheManager.clear(); // Removes all cache files and subdirectories
+ * ```
+ */
+ public clear() {
+
+ // Remove directory and all contents
+ this.destroy()
+
+ // Recreate empty directory
+ mkdirSync(this.path, { recursive: true })
+ }
+
+ /**
+ * Checks whether a path within the managed directory exists.
+ *
+ * Combines the managed directory path with the specified segments and
+ * checks for the existence of the resulting file or directory. Calling
+ * it without arguments checks the managed directory itself.
+ *
+ * @param paths - Variable number of path segments to append to managed directory
+ * @returns True when the combined path exists in the file system
+ *
+ * @example
+ * ```typescript
+ * const appManager = FileManager.forApp("myapp");
+ *
+ * // Check for a configuration file
+ * if (appManager.isExists("config.json")) loadConfiguration();
+ *
+ * // Check for a nested directory
+ * const hasCache = appManager.isExists("cache", "images");
+ * ```
+ */
+ public isExists(...paths: string[]): boolean {
+
+ return existsSync(this.join(...paths))
+ }
+
+ /**
+ * Creates a new FileManager instance for a subdirectory within the current managed directory.
+ *
+ * Navigates to a subdirectory by creating a new FileManager instance that manages
+ * the specified path relative to the current directory. The subdirectory is
+ * automatically created if it doesn't exist.
+ *
+ * @param paths - Variable number of path segments to navigate to from current directory
+ * @returns New FileManager instance managing the target subdirectory
+ *
+ * @example
+ * ```typescript
+ * const appManager = FileManager.forApp("myapp");
+ *
+ * // Navigate to subdirectories
+ * const configManager = appManager.navigateTo("config");
+ * const cacheManager = appManager.navigateTo("cache", "images");
+ *
+ * // Chain navigation operations
+ * const logsManager = appManager.navigateTo("logs").navigateTo("daily");
+ * ```
+ */
+ public navigateTo(...paths: string[]) {
+
+ /**
+ * Create new FileManager instance for subdirectory path.
+ */
+ return new FileManager(this.path, ...paths)
+ }
+}
\ No newline at end of file
diff --git a/source/libs/framing.ts b/source/libs/framing.ts
new file mode 100644
index 0000000..9adc4fd
--- /dev/null
+++ b/source/libs/framing.ts
@@ -0,0 +1,162 @@
+const metadataLimit = 1024 * 1024
+
+const encoder = new TextEncoder()
+
+const decoder = new TextDecoder()
+
+/** Prefix metadata to an optional byte stream without buffering that stream. */
+export function frame<Metadata>(metadata: Metadata, body: ReadableStream<Uint8Array> | null = null) {
+
+ const prefix = metadataPrefix(metadata)
+
+ const reader = body?.getReader()
+
+ let first: Uint8Array | null = prefix
+
+ return new ReadableStream<Uint8Array>({
+
+ async pull(controller) {
+
+ if (first) {
+
+ controller.enqueue(first)
+
+ first = null
+
+ return
+ }
+
+ if (!reader) return controller.close()
+
+ try {
+
+ const next = await reader.read()
+
+ if (next.done) controller.close()
+
+ else controller.enqueue(next.value)
+ }
+
+ catch (exception) {
+
+ controller.error(exception)
+ }
+ },
+
+ async cancel(reason) {
+
+ await reader?.cancel(reason)
+ }
+ })
+}
+
+/** Prefix metadata to a finite body while preserving its known byte length. */
+export function frameBlob<Metadata>(metadata: Metadata, body: Blob | null = null) {
+
+ return new Blob(body ? [metadataPrefix(metadata), body] : [metadataPrefix(metadata)])
+}
+
+function metadataPrefix<Metadata>(metadata: Metadata) {
+
+ const encoded = encoder.encode(JSON.stringify(metadata))
+
+ if (encoded.byteLength > metadataLimit) throw new Error("Framed metadata exceeds 1 MB")
+
+ const prefix = new Uint8Array(4 + encoded.byteLength)
+
+ new DataView(prefix.buffer).setUint32(0, encoded.byteLength)
+
+ prefix.set(encoded, 4)
+
+ return prefix
+}
+
+/** Read one metadata prefix and leave the remaining bytes as a live stream. */
+export async function unframe<Metadata>(stream: ReadableStream<Uint8Array> | null) {
+
+ if (!stream) throw new Error("A framed request body is required")
+
+ const reader = stream.getReader()
+
+ let buffered = new Uint8Array()
+
+ async function take(length: number) {
+
+ while (buffered.byteLength < length) {
+
+ const next = await reader.read()
+
+ if (next.done) throw new Error("The framed message ended before its metadata")
+
+ const joined = new Uint8Array(buffered.byteLength + next.value.byteLength)
+
+ joined.set(buffered)
+
+ joined.set(next.value, buffered.byteLength)
+
+ buffered = joined
+ }
+
+ const value = buffered.slice(0, length)
+
+ buffered = buffered.slice(length)
+
+ return value
+ }
+
+ try {
+
+ const sizeBytes = await take(4)
+
+ const size = new DataView(sizeBytes.buffer, sizeBytes.byteOffset, sizeBytes.byteLength).getUint32(0)
+
+ if (size > metadataLimit) throw new Error("Framed metadata exceeds 1 MB")
+
+ const metadata = JSON.parse(decoder.decode(await take(size))) as Metadata
+
+ const body = new ReadableStream<Uint8Array>({
+
+ async pull(controller) {
+
+ if (buffered.byteLength) {
+
+ const value = buffered
+
+ buffered = new Uint8Array()
+
+ controller.enqueue(value)
+
+ return
+ }
+
+ try {
+
+ const next = await reader.read()
+
+ if (next.done) controller.close()
+
+ else controller.enqueue(next.value)
+ }
+
+ catch (exception) {
+
+ controller.error(exception)
+ }
+ },
+
+ async cancel(reason) {
+
+ await reader.cancel(reason)
+ }
+ })
+
+ return { body, metadata }
+ }
+
+ catch (exception) {
+
+ await reader.cancel(exception).catch(() => undefined)
+
+ throw exception
+ }
+}
diff --git a/source/libs/process-tree.ts b/source/libs/process-tree.ts
new file mode 100644
index 0000000..e9b7f39
--- /dev/null
+++ b/source/libs/process-tree.ts
@@ -0,0 +1,106 @@
+import { ChildProcess } from "node:child_process"
+
+const terminationGrace = 1_000
+
+/** The complete operating-system process tree beneath one child command. */
+export default class ProcessTree {
+
+ private readonly child: ChildProcess
+
+ private readonly ended: Ending
+
+ private forcing: ReturnType<typeof setTimeout> | null = null
+
+ public constructor(child: ChildProcess, ended: Ending) {
+
+ this.child = child
+
+ this.ended = ended
+
+ child.on("exit", (code, signal) => { this.finish(code, signal).catch(() => undefined) })
+ }
+
+ public stop() {
+
+ signalProcessTree(this.child, "SIGTERM")
+
+ if (this.forcing) return
+
+ this.forcing = setTimeout(() => signalProcessTree(this.child, "SIGKILL"), terminationGrace)
+
+ this.forcing.unref()
+ }
+
+ private async finish(code: number | null, signal: NodeJS.Signals | null) {
+
+ if (this.forcing) {
+
+ clearTimeout(this.forcing)
+
+ this.forcing = null
+ }
+
+ await finishProcessTree(this.child)
+
+ await this.ended(code, signal)
+ }
+}
+
+/** Signal the complete process group represented by one child handle. */
+export function signalProcessTree(child: ChildProcess, signal: NodeJS.Signals) {
+
+ if (!child.pid) return
+
+ try { process.kill(-child.pid, signal) }
+
+ catch (error) {
+
+ if ((error as NodeJS.ErrnoException).code === "ESRCH") return
+
+ if (child.exitCode === null && child.signalCode === null) child.kill(signal)
+ }
+}
+
+/** End descendants left behind when the command at the tree's root exits. */
+async function finishProcessTree(child: ChildProcess) {
+
+ const pid = child.pid
+
+ if (!pid || !processTreeExists(pid)) return
+
+ signalProcessTree(child, "SIGTERM")
+
+ if (await waitForProcessTree(pid, terminationGrace)) return
+
+ signalProcessTree(child, "SIGKILL")
+
+ await waitForProcessTree(pid, terminationGrace)
+}
+
+async function waitForProcessTree(pid: number, timeout: number) {
+
+ const began = Date.now()
+
+ while (processTreeExists(pid)) {
+
+ if (Date.now() - began >= timeout) return false
+
+ await new Promise(resolve => setTimeout(resolve, 20))
+ }
+
+ return true
+}
+
+function processTreeExists(pid: number) {
+
+ try {
+
+ process.kill(-pid, 0)
+
+ return true
+ }
+
+ catch (error) { return (error as NodeJS.ErrnoException).code !== "ESRCH" }
+}
+
+type Ending = (code: number | null, signal: NodeJS.Signals | null) => Promise<void> | void
diff --git a/source/libs/react-context.tsx b/source/libs/react-context.tsx
new file mode 100644
index 0000000..985cef9
--- /dev/null
+++ b/source/libs/react-context.tsx
@@ -0,0 +1,20 @@
+import { createContext, useContext, type Provider } from "react"
+
+/**
+ * A typed React context that refuses use outside its provider.
+ */
+export default class ReactContext<Target> {
+
+ public readonly context = createContext<Target | undefined>(undefined)
+
+ public readonly Provider = this.context.Provider as Provider<Target>
+
+ public useValue() {
+
+ const value = useContext(this.context)
+
+ if (value === undefined) throw new Error("Context was not provided")
+
+ return value
+ }
+}
diff --git a/source/libs/react-motion.tsx b/source/libs/react-motion.tsx
new file mode 100644
index 0000000..cc9d897
--- /dev/null
+++ b/source/libs/react-motion.tsx
@@ -0,0 +1,51 @@
+import { ReactNode, createContext, useContext, useSyncExternalStore } from "react"
+
+const ReducedMotionContext = createContext(false)
+
+const media = "(prefers-reduced-motion: reduce)"
+
+let preference: MediaQueryList | null = null
+
+/** Provides the operating-system motion preference with an optional override. */
+export default function ReducedMotion({ children, reduced }: ReducedMotionProps) {
+
+ const preferred = useSyncExternalStore(subscribe, snapshot, () => false)
+
+ return <ReducedMotionContext.Provider value={reduced ?? preferred}>{children}</ReducedMotionContext.Provider>
+}
+
+export function useReducedMotion() {
+
+ return useContext(ReducedMotionContext)
+}
+
+function subscribe(change: () => void) {
+
+ const query = motionPreference()
+
+ query?.addEventListener("change", change)
+
+ return () => query?.removeEventListener("change", change)
+}
+
+function snapshot() {
+
+ return motionPreference()?.matches ?? false
+}
+
+function motionPreference() {
+
+ if (typeof window === "undefined" || !window.matchMedia) return null
+
+ preference ??= window.matchMedia(media)
+
+ return preference
+}
+
+interface ReducedMotionProps {
+
+ children: ReactNode
+
+ /** A deterministic environment may override the operating-system preference. */
+ reduced?: boolean
+}
diff --git a/source/libs/react-promise.ts b/source/libs/react-promise.ts
new file mode 100644
index 0000000..2a91955
--- /dev/null
+++ b/source/libs/react-promise.ts
@@ -0,0 +1,229 @@
+import { type DependencyList, useCallback, useEffect, useRef, useState } from "react"
+
+export default function usePromise<Solve>(executor: ExecuteWithDependencies<Solve>, dependencies: DependencyList): PromiseWithDependencies<Solve>
+
+export default function usePromise<Solve, Data extends unknown[]>(executor: ExecuteWithoutDependencies<Solve, Data>): PromiseWithoutDependencies<Solve, Data>
+
+export default function usePromise<Solve, Data extends unknown[]>(executor: ExecuteWithDependencies<Solve> | ExecuteWithoutDependencies<Solve, Data>, dependencies?: DependencyList) {
+
+ const automatic = dependencies !== undefined
+
+ const execution = useRef(0)
+
+ const mounted = useRef(true)
+
+ // Commands stay referentially stable while always calling the
+ // executor from the latest render. Without this indirection, an
+ // inline executor recreated `execute` and `safeExecute` on every
+ // render, which in turn retriggered effects that depended on them.
+ const executorReference = useRef(executor)
+
+ executorReference.current = executor
+
+ const initialState: PromiseState<Solve> = automatic ? { status: "pending" } : { status: "idle" }
+
+ const stateReference = useRef<PromiseState<Solve>>(initialState)
+
+ const [state, setState] = useState<PromiseState<Solve>>(initialState)
+
+ useEffect(function () {
+
+ mounted.current = true
+
+ return () => {
+
+ mounted.current = false
+
+ execution.current++
+ }
+
+ }, [])
+
+ const changeState = useCallback(function (state: PromiseState<Solve>) {
+
+ if (!mounted.current) return
+
+ stateReference.current = state
+
+ setState(state)
+
+ }, [])
+
+ const reset = useCallback(function () {
+
+ execution.current++
+
+ changeState({ status: "idle" })
+
+ }, [changeState])
+
+ const execute = useCallback(async function (...data: Data) {
+
+ const currentExecution = ++execution.current
+
+ changeState({ status: "pending" })
+
+ try {
+
+ const solve = await (executorReference.current as ExecuteWithoutDependencies<Solve, Data>)(...data)
+
+ if (currentExecution === execution.current) changeState({ status: "solve", solve })
+
+ return solve
+
+ } catch (exception) {
+
+ if (currentExecution === execution.current) changeState({ status: "exception", exception })
+
+ throw exception
+ }
+
+ }, [changeState])
+
+ const safeExecute = useCallback(async function (...data: Data) {
+
+ try {
+
+ return await execute(...data)
+
+ } catch {
+
+ return undefined
+ }
+
+ }, [execute])
+
+ useEffect(function () {
+
+ if (!automatic) return
+
+ void (safeExecute as () => Promise<Solve | undefined>)()
+
+ }, dependencies ?? [])
+
+ const dispatch = useCallback(function (value: UpdateValue<Solve>) {
+
+ const state = stateReference.current
+
+ if (state.status !== "solve") throw new Error("You can't update a promise before it has resolved")
+
+ changeState({ status: "solve", solve: update(value, state.solve) })
+
+ }, [changeState])
+
+ const forceRender = useCallback(function () {
+
+ dispatch(solve => solve)
+
+ }, [dispatch])
+
+ const methods = { execute, safeExecute, dispatch, forceRender }
+
+ if (automatic) {
+
+ if (state.status === "solve") return { ...methods, solve: state.solve, exception: undefined, isPending: false }
+
+ if (state.status === "exception") return { ...methods, solve: undefined, exception: { current: state.exception }, isPending: false }
+
+ return { ...methods, solve: undefined, exception: undefined, isPending: true }
+ }
+
+ return {
+
+ ...methods,
+
+ solve: state.status === "solve" ? { current: state.solve } : undefined,
+
+ exception: state.status === "exception" ? { current: state.exception } : undefined,
+
+ isPending: state.status === "pending",
+
+ reset
+ }
+}
+
+export function update<Target>(value: UpdateValue<Target>, old: Target): Target {
+
+ return value instanceof Function ? value(old) : value
+}
+
+export type UpdateValue<Target> = Target | ((value: Target) => Target)
+
+export type Update<Target> = (value: UpdateValue<Target>) => void
+
+export type ExecuteWithDependencies<Solve> = () => Promise<Solve>
+
+export type ExecuteWithoutDependencies<Solve, Data extends unknown[]> = (...data: Data) => Promise<Solve>
+
+export type PromiseWithDependencies<Solve> = (SolveStatus<Solve> | ExceptionStatus | PendingStatus) & PromiseMethods<Solve, []>
+
+export type PromiseWithoutDependencies<Solve, Data extends unknown[] = []> = {
+
+ solve: Reference<Solve> | undefined
+
+ exception: Reference<unknown> | undefined
+
+ isPending: boolean
+
+ reset: () => void
+} & PromiseMethods<Solve, Data>
+
+export interface SolveStatus<Solve> {
+
+ solve: Solve
+
+ exception: undefined
+
+ isPending: false
+}
+
+export interface ExceptionStatus {
+
+ solve: undefined
+
+ exception: Reference<unknown>
+
+ isPending: false
+}
+
+export interface PendingStatus {
+
+ solve: undefined
+
+ exception: undefined
+
+ isPending: true
+}
+
+export interface Reference<Target> {
+
+ current: Target
+}
+
+interface PromiseMethods<Solve, Data extends unknown[]> {
+
+ safeExecute: (...data: Data) => Promise<Solve | undefined>
+
+ execute: (...data: Data) => Promise<Solve>
+
+ dispatch: Update<Solve>
+
+ forceRender: () => void
+}
+
+type PromiseState<Solve> = {
+
+ status: "idle" | "pending"
+
+} | {
+
+ status: "solve"
+
+ solve: Solve
+
+} | {
+
+ status: "exception"
+
+ exception: unknown
+}
diff --git a/source/libs/react-screen.tsx b/source/libs/react-screen.tsx
new file mode 100644
index 0000000..1c60780
--- /dev/null
+++ b/source/libs/react-screen.tsx
@@ -0,0 +1,219 @@
+import React, { useState, useEffect } from "react"
+
+/**
+ * The useScreen hook provides responsive design capabilities by tracking
+ * if the current window width falls within specified minimum and maximum bounds.
+ *
+ * This hook enables components to adapt their behavior based on screen size,
+ * making it easier to implement responsive designs without relying on CSS media queries.
+ *
+ * @param min Optional minimum width in pixels for the range to be active
+ * @param max Optional maximum width in pixels for the range to be active
+ * @returns A boolean indicating whether the current screen width is within the specified range
+ *
+ * @example
+ *
+ * const isTablet = useScreen(768, 1024)
+ *
+ * if (isTablet) {
+ * // Render tablet-specific content
+ * }
+ */
+export const useScreen = function (min?: number, max?: number): boolean {
+
+ /**
+ * State tracking whether the current screen width is within the specified range.
+ * Initial value is determined by comparing the window width against min/max values.
+ */
+ const [inRange, setInRange] = useState((!min && !max) ? false : (min ? window.innerWidth >= min : true) && (max ? window.innerWidth <= max : true))
+
+ /**
+ * Sets up an event listener to track window resize events and update
+ * the inRange state when the screen dimensions change.
+ *
+ * The effect cleans up by removing the event listener when the component unmounts
+ * or when min/max dependencies change.
+ */
+ useEffect(() => {
+
+ /**
+ * Handler function that recalculates whether the screen width
+ * is within the specified range and updates the state accordingly.
+ */
+ const resize = () => setInRange((!min && !max) ? false : (min ? window.innerWidth >= min : true) && (max ? window.innerWidth <= max : true))
+
+ // Add resize listener
+ window.addEventListener("resize", resize)
+
+ /**
+ * On end remove resize listener
+ */
+ return () => window.removeEventListener("resize", resize)
+
+ }, [min, max])
+
+ return inRange
+}
+
+/**
+ * Screen is a responsive component that conditionally renders content
+ * based on whether the current screen width falls within specified bounds.
+ *
+ * It leverages the useScreen hook internally to determine which content to display,
+ * providing a declarative way to implement responsive UIs.
+ *
+ * @param min Optional minimum width in pixels for the content to be shown
+ * @param max Optional maximum width in pixels for the content to be shown
+ * @param available Content to display when the screen width is within range
+ * @param unavailable Content to display when the screen width is out of range
+ * @returns Either the 'available' or 'unavailable' content based on current screen size
+ *
+ * @example
+ *
+ * <Screen
+ * min={768}
+ * available={<DesktopNavigation />}
+ * unavailable={<MobileNavigation />}
+ * />
+ */
+const Screen = ({ min, max, available, unavailable }: ScreenProps) => {
+
+ /**
+ * Determines if the current screen width is within the specified range.
+ * The result controls which content variant is rendered.
+ */
+ const screen = useScreen(min, max)
+
+ return <React.Fragment>{screen ? available : unavailable}</React.Fragment>
+}
+
+/**
+ * The useOrientation hook tracks the current device orientation.
+ *
+ * It detects whether the device is in landscape, portrait, or square orientation
+ * based on comparing window width and height dimensions.
+ *
+ * @returns The current orientation as "landscape", "portrait", or "square"
+ *
+ * @example
+ *
+ * const orientation = useOrientation()
+ *
+ * if (orientation === "landscape") {
+ * // Apply landscape-specific logic
+ * }
+ */
+export const useOrientation = (): OrientationType => {
+
+ /**
+ * Determines the initial orientation based on comparing
+ * window width and height dimensions.
+ */
+ const initialOrientation: OrientationType = window.innerWidth > window.innerHeight ? "landscape" :
+ window.innerWidth < window.innerHeight ? "portrait" : "square"
+
+ /**
+ * State tracking the current device orientation.
+ */
+ const [orientation, setOrientation] = useState<OrientationType>(initialOrientation)
+
+ /**
+ * Sets up an event listener to track window resize events and
+ * recalculate the orientation when dimensions change.
+ *
+ * The effect cleans up by removing the event listener when the component unmounts.
+ */
+ useEffect(() => {
+
+ /**
+ * Handler function that recalculates the current orientation
+ * based on window dimensions and updates the state accordingly.
+ */
+ const resize = function () {
+
+ // Landscape orientation
+ if (window.innerWidth > window.innerHeight) setOrientation("landscape")
+
+ // Portrait orientation
+ else if (window.innerWidth < window.innerHeight) setOrientation("portrait")
+
+ // Square orientation
+ else setOrientation("square")
+
+ }
+
+ // Add resize listener
+ window.addEventListener("resize", resize)
+
+ /**
+ * On end remove resize listener
+ */
+ return () => window.removeEventListener("resize", resize)
+
+ }, [])
+
+ return orientation
+}
+
+/**
+ * Orientation is a component that conditionally renders content
+ * based on the current device orientation.
+ *
+ * It leverages the useOrientation hook internally to determine which
+ * content to display, providing a declarative way to adapt UI based on
+ * device orientation changes.
+ *
+ * @param cases An object containing content to display for different orientations
+ * @returns The content associated with the current orientation
+ *
+ * @example
+ *
+ * <Orientation
+ * landscape={<LandscapeLayout />}
+ * portrait={<PortraitLayout />}
+ * square={<SquareLayout />}
+ * />
+ */
+export const Orientation = (cases: Partial<Record<OrientationType, React.ReactNode>>) => {
+
+ /**
+ * Tracks the current device orientation to determine
+ * which content variant should be rendered.
+ */
+ const orientation = useOrientation()
+
+ return <React.Fragment>{cases[orientation]}</React.Fragment>
+}
+
+/**
+ * Common breakpoint for small screen devices.
+ * This constant can be used with the useScreen hook or Screen component
+ * to implement consistent responsive behavior across the application.
+ */
+export const SMALL_SCREEN: number = 768
+
+/**
+ * Detection for mobile devices based on user agent.
+ * This boolean can be used to apply mobile-specific logic or optimizations.
+ */
+export const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
+
+/**
+ * Defines the possible device orientation types.
+ * Used by the useOrientation hook and Orientation component.
+ */
+export type OrientationType = "landscape" | "portrait" | "square"
+
+/**
+ * Props interface for the Screen component.
+ * Defines the configuration options and content variants
+ * for responsive rendering.
+ */
+interface ScreenProps {
+ min?: number
+ max?: number
+ available?: React.ReactNode
+ unavailable?: React.ReactNode
+}
+
+export default Screen
\ No newline at end of file
diff --git a/source/libs/sqlite-database.ts b/source/libs/sqlite-database.ts
new file mode 100644
index 0000000..5fe6f89
--- /dev/null
+++ b/source/libs/sqlite-database.ts
@@ -0,0 +1,50 @@
+import { DatabaseSync } from "node:sqlite"
+import { mkdirSync } from "node:fs"
+import { dirname } from "node:path"
+
+/** A lazily opened SQLite database exposing one-statement queries. */
+export default class SqliteDatabase {
+
+ private readonly path: string
+
+ private database: DatabaseSync | null = null
+
+ public constructor(path: string) {
+
+ this.path = path
+ }
+
+ private open() {
+
+ if (this.database) return this.database
+
+ mkdirSync(dirname(this.path), { recursive: true })
+
+ const database = new DatabaseSync(this.path)
+
+ database.exec("pragma journal_mode = wal")
+
+ this.database = database
+
+ return database
+ }
+
+ /** Execute exactly one statement and return its rows. */
+ public query(sql: string, values: unknown[] = []) {
+
+ const statement = this.open().prepare(sql)
+
+ const rest = sql.slice(statement.sourceSQL.length).trim()
+
+ if (rest) throw new Error(`A query is one statement, and this is more than one — the rest was not run: ${rest.slice(0, 60)}`)
+
+ return statement.all(...values as never[]).map(row => ({ ...row }))
+ }
+
+ public close() {
+
+ this.database?.close()
+
+ this.database = null
+ }
+}
diff --git a/source/libs/sqlite-store.ts b/source/libs/sqlite-store.ts
new file mode 100644
index 0000000..294b405
--- /dev/null
+++ b/source/libs/sqlite-store.ts
@@ -0,0 +1,69 @@
+import { EventEmitter } from "node:events"
+import { DatabaseSync } from "node:sqlite"
+import { type KeyvStoreAdapter, type StoredData } from "keyv"
+
+/** A Keyv store backed directly by Node's built-in SQLite driver. */
+export default class SqliteStore extends EventEmitter implements KeyvStoreAdapter {
+
+ public readonly opts = { dialect: "sqlite" }
+
+ public namespace?: string
+
+ private readonly database: DatabaseSync
+
+ public constructor(path: string) {
+
+ super()
+
+ this.database = new DatabaseSync(path)
+
+ this.database.exec("pragma journal_mode = wal; pragma busy_timeout = 5000")
+
+ // This is the schema used by @keyv/sqlite. Keeping it unchanged makes
+ // the driver replacement transparent to every existing store file.
+ this.database.exec("create table if not exists keyv (key varchar(255) primary key, value text)")
+ }
+
+ public async get<Value>(key: string) {
+
+ const row = this.database.prepare("select value from keyv where key = ?").get(key) as { value: string } | undefined
+
+ return row?.value as StoredData<Value> | undefined
+ }
+
+ public async set(key: string, value: unknown) {
+
+ this.database.prepare("insert into keyv (key, value) values (?, ?) on conflict(key) do update set value = excluded.value").run(key, value as string)
+ }
+
+ public async delete(key: string) {
+
+ const result = this.database.prepare("delete from keyv where key = ?").run(key)
+
+ return Number(result.changes) > 0
+ }
+
+ public async clear() {
+
+ if (!this.namespace) {
+
+ this.database.exec("delete from keyv")
+
+ return
+ }
+
+ const prefix = `${this.namespace}:`
+
+ this.database.prepare("delete from keyv where substr(key, 1, ?) = ?").run(prefix.length, prefix)
+ }
+
+ public async has(key: string) {
+
+ return this.database.prepare("select 1 from keyv where key = ?").get(key) !== undefined
+ }
+
+ public async disconnect() {
+
+ this.database.close()
+ }
+}
diff --git a/source/libs/storage-hook.ts b/source/libs/storage-hook.ts
new file mode 100644
index 0000000..464cee2
--- /dev/null
+++ b/source/libs/storage-hook.ts
@@ -0,0 +1,124 @@
+import { useCallback, useEffect, useState } from "react"
+
+/**
+ * Reactive localStorage hook with cross-component and cross-tab synchronization.
+ *
+ * Wraps a single localStorage key with React state, providing memoized
+ * update/remove operations that broadcast changes via StorageEvent,
+ * and a nested subscription hook for external change listeners.
+ *
+ * @param key - The localStorage key to manage
+ * @returns Object containing the current value, update/remove operations, and a subscription hook
+ *
+ * @example
+ * ```typescript
+ * const { value, update, remove, useSubscribe } = useStorage("session-id");
+ *
+ * // Update value and broadcast change
+ * update("abc-123");
+ *
+ * // Subscribe to external changes
+ * useSubscribe((newValue) => {
+ * if (!newValue) redirectToLogin();
+ * });
+ * ```
+ */
+export default function useStorage(key: string) {
+
+ // Initialize state from current localStorage value (lazy initializer avoids read on every render)
+ const [value, setValue] = useState(() => localStorage.getItem(key))
+
+ /**
+ * Persists a new value to localStorage and broadcasts the change via StorageEvent.
+ * Short-circuits if the new value matches the current value to avoid redundant writes.
+ */
+ const update = useCallback(function (newValue: string) {
+
+ // Skip redundant writes when value hasn't changed
+ if (value === newValue) return
+
+ // Persist the new value to localStorage
+ localStorage.setItem(key, newValue)
+
+ // Dispatch StorageEvent to notify same-tab listeners (native events only fire cross-tab)
+ window.dispatchEvent(new StorageEvent("storage", { key, newValue }))
+
+ }, [key, value])
+
+ /**
+ * Removes the key from localStorage and broadcasts a null-value StorageEvent.
+ * Short-circuits if the value is already null to avoid redundant operations.
+ */
+ const remove = useCallback(function () {
+
+ // Skip if key is already absent from localStorage
+ if (value === null) return
+
+ // Remove the key from localStorage
+ localStorage.removeItem(key)
+
+ // Broadcast removal as a null-value StorageEvent
+ window.dispatchEvent(new StorageEvent("storage", { key, newValue: null }))
+
+ }, [key, value])
+
+ /**
+ * Internal handler that updates React state when a matching StorageEvent is received.
+ * Filters events by key to avoid reacting to unrelated storage changes.
+ */
+ const updateHandler = useCallback(function (event: StorageEvent) {
+
+ // Only update state when the event targets this hook's key
+ if (event.key === key) setValue(event.newValue)
+
+ }, [])
+
+ /**
+ * Nested hook that subscribes an external callback to storage changes for this key.
+ * Manages its own event listener lifecycle, cleaning up on unmount or dependency change.
+ *
+ * @param subscriber - Callback invoked with the new value (or null on removal) when the key changes
+ */
+ const useSubscribe = useCallback(function (subscriber: Subscriber) {
+
+ // Create a filtered event handler bound to the subscriber and current key
+ const subscribeHandler = useCallback(function (event: StorageEvent) {
+
+ // Forward the new value to the subscriber only for matching key events
+ if (event.key === key) subscriber(event.newValue)
+
+ }, [key, subscriber])
+
+ // Attach and detach the storage event listener tied to the subscriber's lifecycle
+ useEffect(function () {
+
+ window.addEventListener("storage", subscribeHandler)
+
+ return () => window.removeEventListener("storage", subscribeHandler)
+
+ }, [subscribeHandler])
+
+ }, [key])
+
+ // Re-sync React state from localStorage whenever the key changes
+ useEffect(() => setValue(localStorage.getItem(key)), [key])
+
+ // Subscribe to StorageEvent for cross-component and cross-tab reactivity
+ useEffect(function () {
+
+ window.addEventListener("storage", updateHandler)
+
+ return () => window.removeEventListener("storage", updateHandler)
+
+ }, [updateHandler])
+
+ return { value, update, remove, useSubscribe }
+}
+
+/**
+ * Callback type for storage change subscriptions.
+ * Receives the new value when the subscribed key is updated, or null when it is removed.
+ *
+ * @param value - The updated localStorage value, or null if the key was removed
+ */
+export type Subscriber = (value: string | null) => void
\ No newline at end of file
diff --git a/source/libs/superjson.ts b/source/libs/superjson.ts
new file mode 100644
index 0000000..f708bce
--- /dev/null
+++ b/source/libs/superjson.ts
@@ -0,0 +1,90 @@
+import superjson from "superjson"
+
+/**
+ * Convert any JavaScript value to a JSON string with type preservation.
+ *
+ * @param value The value to stringify
+ * @returns JSON string with embedded type metadata
+ */
+export const stringify = (value: unknown) => superjson.stringify(resolve(value))
+
+/**
+ * Resolve toJSON declarations before SuperJSON walks the value. SuperJSON
+ * preserves special types only where its own traversal sees them — and its
+ * traversal does not descend into toJSON results, so a Map inside one
+ * degrades to a plain object. Resolving first makes the runtime honor what
+ * the Transmitted type already promises (case 5). Types SuperJSON carries
+ * natively are left untouched — Date and URL have toJSON of their own,
+ * and calling it would degrade them to strings.
+ */
+const resolve = (value: unknown): unknown => {
+
+ if (value === null || typeof value !== "object") return value
+
+ if (value instanceof Date || value instanceof RegExp || value instanceof URL || value instanceof Error) return value
+
+ if (value instanceof Map) return new Map([...value].map(([key, entry]) => [resolve(key), resolve(entry)]))
+
+ if (value instanceof Set) return new Set([...value].map(entry => resolve(entry)))
+
+ if (Array.isArray(value)) return value.map(entry => resolve(entry))
+
+ if ("toJSON" in value && typeof value.toJSON === "function") return resolve(value.toJSON())
+
+ return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, resolve(entry)]))
+}
+
+/**
+ * Parse a SuperJSON string back to its original JavaScript value.
+ *
+ * @param value The SuperJSON string to parse
+ * @returns The reconstructed value with preserved types
+ */
+export const parse = <Value>(value: string) => superjson.parse<Transmitted<Value>>(value)
+
+/**
+ * Type representing a value after SuperJSON serialization.
+ *
+ * Functions are converted to null, special types (Date, Map, Set, etc.) are preserved,
+ * and object function properties are removed while maintaining all other properties.
+ *
+ * @template T The original type before serialization
+ */
+export type Transmitted<T> =
+ // Case 1: Functions are converted to null
+ T extends Function
+ ? null
+ // Case 2: Maps are preserved, with key and value types recursively serialized
+ : T extends Map<infer K, infer V>
+ ? Map<Transmitted<K>, Transmitted<V>> // Recurse into key and value types
+ // Case 3: Sets are preserved, with value types recursively serialized
+ : T extends Set<infer U>
+ ? Set<Transmitted<U>> // Recurse into value type
+ // Case 4: Special types (Date, RegExp, URL, Error) are preserved as-is
+ : T extends Date | RegExp | URL | Error
+ ? T
+ // Case 5: Objects with toJSON methods use the return type of toJSON, recursively serialized
+ : T extends { toJSON(): infer R }
+ ? Transmitted<R>
+ // Case 6: Non-empty tuples are preserved, with each element recursively serialized
+ : T extends readonly [infer U, ...infer V]
+ ? [Transmitted<U>, ...Transmitted<V>]
+ // Case 7: Empty tuples remain empty
+ : T extends readonly []
+ ? []
+ // Case 8: Arrays are preserved, with element types recursively serialized
+ : T extends Array<infer U>
+ ? Array<Transmitted<U>>
+ // Case 9: Plain objects have function properties removed, and other properties are recursively serialized
+ : T extends object
+ ? {
+ // Filter out keys where the property is a function
+ [K in keyof T as Extract<T[K], Function> extends never ? K : never]: Transmitted<T[K]>
+ }
+ // Case 10: Primitive values (string, number, boolean, etc.) are unchanged
+ : T
+
+/**
+ * Default export containing all SuperJSON utilities.
+ */
+export default { stringify, parse }
\ No newline at end of file
diff --git a/source/libs/the-link/decorators/escript.ts b/source/libs/the-link/decorators/escript.ts
new file mode 100644
index 0000000..c629358
--- /dev/null
+++ b/source/libs/the-link/decorators/escript.ts
@@ -0,0 +1,158 @@
+import { Finalizer, Forwarder, Interceptor, Subscriber } from "../tunnel"
+import TheLink, { Publisher, TunnelName } from "../the-link"
+
+/**
+ * Register a method as an interceptor on one of the link tunnels.
+ *
+ * Uses the standard ECMAScript decorator context to register the interceptor
+ * when each instance is initialized.
+ *
+ * @param tunnelName Target tunnel for interceptor registration
+ * @param prefix Event prefix to intercept, or an empty string for all events
+ * @returns ECMAScript method decorator
+ */
+export function Intercept(tunnelName: TunnelName, prefix: string = "") {
+
+ return function <TargetLink extends TheLink>(interceptor: Interceptor, context: ClassMethodDecoratorContext<TargetLink, Interceptor>) {
+
+ if (context.static) throw new Error(`@${String(context.name)} cannot be used on static methods`)
+
+ context.addInitializer(function () {
+
+ // Select the tunnel from the concrete instance.
+ const tunnel = tunnelName === "outbound" ? this.$outbound : this.$inbound
+
+ // Bind the method so interceptors preserve instance context.
+ tunnel.addInterceptor(interceptor.bind(this), prefix)
+ })
+ }
+}
+
+/**
+ * Register a method as a subscriber for a tunnel event.
+ *
+ * @param event Event identifier to subscribe to
+ * @param tunnelName Target tunnel for subscription
+ * @returns ECMAScript method decorator
+ */
+export function Subscribe(event: string, tunnelName: TunnelName = "inbound") {
+
+ return function <TargetLink extends TheLink>(subscriber: Subscriber, context: ClassMethodDecoratorContext<TargetLink, Subscriber>) {
+
+ if (context.static) throw new Error(`@${String(context.name)} cannot be used on static methods`)
+
+ context.addInitializer(function () {
+
+ // Select the tunnel from the concrete instance.
+ const tunnel = tunnelName === "outbound" ? this.$outbound : this.$inbound
+
+ // Bind the method so subscribers run with the instance as `this`.
+ tunnel.subscribe(event, subscriber.bind(this))
+ })
+ }
+}
+
+/**
+ * Register a method as a forwarder on one of the link tunnels.
+ *
+ * @param tunnelName Target tunnel for forwarder registration
+ * @param fromPrefix Source event prefix to match
+ * @param toPrefix Destination event prefix to apply
+ * @returns ECMAScript method decorator
+ */
+export function Forward(tunnelName: TunnelName, fromPrefix: string = "", toPrefix: string = "") {
+
+ return function <TargetLink extends TheLink>(forwarder: Forwarder, context: ClassMethodDecoratorContext<TargetLink, Forwarder>) {
+
+ if (context.static) throw new Error(`@${String(context.name)} cannot be used on static methods`)
+
+ context.addInitializer(function () {
+
+ // Select the tunnel from the concrete instance.
+ const tunnel = tunnelName === "outbound" ? this.$outbound : this.$inbound
+
+ // Bind the method before registering it as a tunnel forwarder.
+ tunnel.forwardTo(forwarder.bind(this), fromPrefix, toPrefix)
+ })
+ }
+}
+
+/**
+ * Register a method as a finalizer on one of the link tunnels.
+ *
+ * @param tunnelName Target tunnel for finalizer registration
+ * @param prefix Event prefix to finalize, or an empty string for all events
+ * @returns ECMAScript method decorator
+ */
+export function Finalize(tunnelName: TunnelName, prefix: string = "") {
+
+ return function <TargetLink extends TheLink>(finalizer: Finalizer, context: ClassMethodDecoratorContext<TargetLink, Finalizer>) {
+
+ if (context.static) throw new Error(`@${String(context.name)} cannot be used on static methods`)
+
+ context.addInitializer(function () {
+
+ // Select the tunnel from the concrete instance.
+ const tunnel = tunnelName === "outbound" ? this.$outbound : this.$inbound
+
+ // Bind the method so finalizers preserve instance context.
+ tunnel.addFinalizer(finalizer.bind(this), prefix)
+ })
+ }
+}
+
+/**
+ * Wrap a method so its return value is published as a tunnel event.
+ *
+ * The original method still returns its own result. After it resolves, that
+ * result is published on the configured tunnel.
+ *
+ * @param event Event identifier to publish after method execution
+ * @param tunnelName Target tunnel for publication
+ * @returns ECMAScript method decorator
+ */
+export function Publish(event: string, tunnelName: TunnelName = "outbound") {
+
+ return function <TargetLink extends TheLink>(publisher: Publisher, context: ClassMethodDecoratorContext<TargetLink, Publisher>) {
+
+ if (context.static) throw new Error(`@${String(context.name)} cannot be used on static methods`)
+
+ // Replace the decorated method with a publishing wrapper.
+ return async function (this: TargetLink, ...values: unknown[]) {
+
+ const tunnel = tunnelName === "outbound" ? this.$outbound : this.$inbound
+
+ const result = await publisher.apply(this, values)
+
+ await tunnel.publish(event, result)
+
+ return result
+ }
+ }
+}
+
+/**
+ * Combine inbound subscription with outbound publication for one method.
+ *
+ * Creates a publishing wrapper, registers that wrapper as the inbound subscriber,
+ * and returns the wrapper as the decorated method implementation.
+ *
+ * @param subscribeEvent Inbound event identifier to subscribe to
+ * @param publishEvent Optional outbound event identifier, defaults to subscribeEvent
+ * @returns ECMAScript method decorator
+ */
+export function Connect(subscribeEvent: string, publishEvent?: string) {
+
+ return function <TargetLink extends TheLink>(method: Subscriber & Publisher, context: ClassMethodDecoratorContext<TargetLink, Subscriber & Publisher>) {
+
+ if (context.static) throw new Error(`@${String(context.name)} cannot be used on static methods`)
+
+ // Create one publisher wrapper for both inbound and direct invocation.
+ const publisher = Publish(publishEvent || subscribeEvent, "outbound")(method, context)
+
+ // Register the publisher wrapper as the inbound subscriber.
+ Subscribe(subscribeEvent, "inbound")(publisher, context)
+
+ return publisher
+ }
+}
\ No newline at end of file
diff --git a/source/libs/the-link/decorators/legacy.ts b/source/libs/the-link/decorators/legacy.ts
new file mode 100644
index 0000000..972f633
--- /dev/null
+++ b/source/libs/the-link/decorators/legacy.ts
@@ -0,0 +1,166 @@
+import { Finalizer, Forwarder, Interceptor, Subscriber } from "../tunnel"
+import TheLink, { Publisher, TunnelName } from "../the-link"
+
+/**
+ * Register a method as an interceptor on one of the link tunnels.
+ *
+ * The decorated method is bound to each instance during TheLink initialization
+ * and registered with prefix matching on the selected tunnel.
+ *
+ * @param tunnelName Target tunnel for interceptor registration
+ * @param prefix Event prefix to intercept, or an empty string for all events
+ * @returns Legacy method decorator
+ */
+export function Intercept(tunnelName: TunnelName, prefix: string = "") {
+
+ return function <TargetLink extends TheLink>(targetLink: TargetLink, interceptorName: string, _descriptor: TypedPropertyDescriptor<Interceptor>) {
+
+ targetLink.addInitializer(function (instanceLink) {
+
+ // Select the tunnel when the concrete instance is available.
+ const tunnel = tunnelName === "outbound" ? instanceLink.$outbound : instanceLink.$inbound
+
+ const interceptor = instanceLink[interceptorName as keyof TargetLink] as Interceptor
+
+ // Bind the method so decorators preserve instance context.
+ tunnel.addInterceptor(interceptor.bind(instanceLink), prefix)
+ })
+ }
+}
+
+/**
+ * Register a method as a subscriber for a tunnel event.
+ *
+ * The decorated method is bound during instance initialization and subscribed to
+ * the configured event on the selected tunnel.
+ *
+ * @param event Event identifier to subscribe to
+ * @param tunnelName Target tunnel for subscription
+ * @returns Legacy method decorator
+ */
+export function Subscribe(event: string, tunnelName: TunnelName = "inbound") {
+
+ return function <TargetLink extends TheLink>(targetLink: TargetLink, subscriberName: string, _descriptor: TypedPropertyDescriptor<Subscriber>) {
+
+ targetLink.addInitializer(function (instanceLink) {
+
+ // Select the tunnel when the concrete instance is available.
+ const tunnel = tunnelName === "outbound" ? instanceLink.$outbound : instanceLink.$inbound
+
+ const subscriber = instanceLink[subscriberName as keyof TargetLink] as Subscriber
+
+ // Bind the method so subscribers run with the instance as `this`.
+ tunnel.subscribe(event, subscriber.bind(instanceLink))
+ })
+ }
+}
+
+/**
+ * Register a method as a forwarder on one of the link tunnels.
+ *
+ * Forwarders receive matching events from the selected tunnel and can route them
+ * to another destination with optional prefix translation.
+ *
+ * @param tunnelName Target tunnel for forwarder registration
+ * @param fromPrefix Source event prefix to match
+ * @param toPrefix Destination event prefix to apply
+ * @returns Legacy method decorator
+ */
+export function Forward(tunnelName: TunnelName, fromPrefix: string = "", toPrefix: string = "") {
+
+ return function <TargetLink extends TheLink>(targetLink: TargetLink, forwarderName: string, _descriptor: TypedPropertyDescriptor<Forwarder>) {
+
+ targetLink.addInitializer(function (instanceLink) {
+
+ // Select the tunnel when the concrete instance is available.
+ const tunnel = tunnelName === "outbound" ? instanceLink.$outbound : instanceLink.$inbound
+
+ const forwarder = instanceLink[forwarderName as keyof TargetLink] as Forwarder
+
+ // Bind the method before registering it as a tunnel forwarder.
+ tunnel.forwardTo(forwarder.bind(instanceLink), fromPrefix, toPrefix)
+ })
+ }
+}
+
+/**
+ * Register a method as a finalizer on one of the link tunnels.
+ *
+ * Finalizers run after subscribers and forwarders, allowing result arrays to be
+ * transformed before publish returns.
+ *
+ * @param tunnelName Target tunnel for finalizer registration
+ * @param prefix Event prefix to finalize, or an empty string for all events
+ * @returns Legacy method decorator
+ */
+export function Finalize(tunnelName: TunnelName, prefix: string = "") {
+
+ return function <TargetLink extends TheLink>(targetLink: TargetLink, finalizerName: string, _descriptor: TypedPropertyDescriptor<Finalizer>) {
+
+ targetLink.addInitializer(function (instanceLink) {
+
+ // Select the tunnel when the concrete instance is available.
+ const tunnel = tunnelName === "outbound" ? instanceLink.$outbound : instanceLink.$inbound
+
+ const finalizer = instanceLink[finalizerName as keyof TargetLink] as Finalizer
+
+ // Bind the method so finalizers preserve instance context.
+ tunnel.addFinalizer(finalizer.bind(instanceLink), prefix)
+ })
+ }
+}
+
+/**
+ * Wrap a method so its return value is published as a tunnel event.
+ *
+ * The original method still returns its own result. After it resolves, that
+ * result is published on the configured tunnel.
+ *
+ * @param event Event identifier to publish after method execution
+ * @param tunnelName Target tunnel for publication
+ * @returns Legacy method decorator
+ */
+export function Publish(event: string, tunnelName: TunnelName = "outbound") {
+
+ return function <TargetLink extends TheLink>(targetLink: TargetLink, publisherName: string, _descriptor: TypedPropertyDescriptor<Publisher>) {
+
+ targetLink.addInitializer(function (instanceLink) {
+
+ // Select the tunnel when the concrete instance is available.
+ const tunnel = tunnelName === "outbound" ? instanceLink.$outbound : instanceLink.$inbound
+
+ const publisher = instanceLink[publisherName as keyof TargetLink] as Publisher
+
+ // Replace the method with a wrapper that publishes its resolved result.
+ (instanceLink[publisherName as keyof TargetLink] as Publisher) = async function (...values: unknown[]) {
+
+ const result = await publisher.apply(instanceLink, values)
+
+ await tunnel.publish(event, result)
+
+ return result
+ }
+ })
+ }
+}
+
+/**
+ * Combine inbound subscription with outbound publication for one method.
+ *
+ * Equivalent to applying `Publish(publishEvent || subscribeEvent, "outbound")`
+ * and `Subscribe(subscribeEvent, "inbound")` to the same method.
+ *
+ * @param subscribeEvent Inbound event identifier to subscribe to
+ * @param publishEvent Optional outbound event identifier, defaults to subscribeEvent
+ * @returns Legacy method decorator
+ */
+export function Connect(subscribeEvent: string, publishEvent?: string) {
+
+ return function <TargetLink extends TheLink>(targetLink: TargetLink, methodName: string, descriptor: TypedPropertyDescriptor<Subscriber & Publisher>) {
+
+ // Register publish first so Subscribe captures the wrapped method.
+ Publish(publishEvent || subscribeEvent, "outbound")(targetLink, methodName, descriptor)
+
+ Subscribe(subscribeEvent, "inbound")(targetLink, methodName, descriptor)
+ }
+}
\ No newline at end of file
diff --git a/source/libs/the-link/plugins/client-link/client-link.ts b/source/libs/the-link/plugins/client-link/client-link.ts
new file mode 100644
index 0000000..a4f411c
--- /dev/null
+++ b/source/libs/the-link/plugins/client-link/client-link.ts
@@ -0,0 +1,281 @@
+import Tunnel, { Subscriber } from "../../tunnel"
+import SocketLink from "./socket-link"
+import TheLink from "../../the-link"
+import { v4 as uuidv4 } from "uuid"
+
+/**
+ * Client adapter for TheLink over HTTP publishing and WebSocket subscriptions.
+ *
+ * For outbound events, ClientLink forwards the outbound tunnel to the server's
+ * POST `/publish` endpoint. For subscriptions, it opens a WebSocket connection
+ * to `/subscribe`, waits for the server's subscribe envelope, then exposes the
+ * connection as a client-side SocketLink. Recoverable WebSocket closures trigger
+ * a delayed resubscribe with the original connection payload.
+ *
+ * The adapter uses JSON serialization by default, with hooks for custom
+ * serialization layers that must match the corresponding ServerLink.
+ *
+ * @example
+ * ```typescript
+ * const client = new ClientLink("https://api.example.com/events")
+ *
+ * const socket = await client.subscribeAsync<{ userId: string }>({ token })
+ *
+ * socket.$inbound.subscribe("server:event", handleServerEvent)
+ * await client.$outbound.publish("client:event", payload)
+ * ```
+ */
+export default class ClientLink extends TheLink {
+
+ /**
+ * Internal tunnel for client-side connection lifecycle events.
+ *
+ * Publishes `subscribe` when a WebSocket is accepted and `unsubscribe` when
+ * a tracked socket closes. UUID-scoped `subscribe:<uuid>` and
+ * `unsubscribe:<uuid>` events are also published so individual async
+ * subscription calls can resolve or reject their own connection.
+ */
+ public readonly $internal: Tunnel = new Tunnel()
+
+ /**
+ * Server base URL used to construct `/publish` and `/subscribe` endpoints.
+ */
+ private readonly url: string
+
+ /**
+ * Converts outbound values into wire-format strings.
+ */
+ private serialize = <Input>(input: Input): string => JSON.stringify(input)
+
+ /**
+ * Converts wire-format strings back into typed values.
+ */
+ private deserialize = <Output>(input: string): Output => JSON.parse(input)
+
+ /**
+ * Active WebSocket-backed SocketLink instances keyed by connection UUID.
+ */
+ public readonly sockets: Map<string, SocketLink> = new Map()
+
+ /**
+ * Initialize a ClientLink for a ServerLink base URL.
+ *
+ * @param url Server base URL that exposes `/publish` and `/subscribe`
+ */
+ public constructor(url: string) {
+
+ super()
+
+ // Store the server base URL for endpoint construction.
+ this.url = url
+
+ // Forward outbound tunnel events to the server via HTTP POST.
+ this.$outbound.forwardTo(this.publishHandler.bind(this))
+ }
+
+ /**
+ * Configure the serialization function used for HTTP and WebSocket payloads.
+ *
+ * @param serialize Custom function that converts values to strings
+ */
+ public setSerialize(serialize: typeof this.serialize<unknown>) {
+
+ this.serialize = serialize as typeof this.serialize
+ }
+
+ /**
+ * Configure the deserialization function used for HTTP and WebSocket payloads.
+ *
+ * @param deserialize Custom function that parses values from strings
+ */
+ public setDeserialize(deserialize: typeof this.deserialize<unknown>) {
+
+ this.deserialize = deserialize as typeof this.deserialize
+ }
+
+ /**
+ * Register a handler for successful WebSocket subscriptions.
+ *
+ * @param subscriber Handler invoked with each accepted SocketLink
+ * @returns Function that removes this subscriber
+ */
+ public onSubscribe<Payload>(subscriber: Subscriber<[SocketLink<Payload>]>) {
+
+ return this.$internal.subscribe("subscribe", subscriber)
+ }
+
+ /**
+ * Open a WebSocket subscription to the server.
+ *
+ * The connection payload is serialized into the `payload` query parameter.
+ * When the server responds with a `subscribe` envelope, this client creates a
+ * SocketLink and publishes it on the internal `subscribe` event plus the
+ * UUID-scoped `subscribe:<uuid>` event.
+ *
+ * @param payload Optional connection payload sent to the server
+ * @returns Connection UUID used for socket tracking and scoped lifecycle events
+ */
+ public subscribe(payload: unknown = undefined) {
+
+ const searchParams = new URLSearchParams()
+
+ // Include caller-provided connection context in the subscribe request.
+ searchParams.set("payload", this.serialize({ current: payload }))
+
+ const socket = new WebSocket(`${this.url}/subscribe?${searchParams.toString()}`)
+
+ const uuid = uuidv4()
+
+ // Route the server subscribe envelope through the WebSocket message handler.
+ socket.addEventListener("message", (event) => this.webSocketMessageHandler(event, socket, uuid))
+
+ // Ensure SocketLink cleanup and reconnect handling when the WebSocket closes.
+ socket.addEventListener("close", (event) => this.webSocketCloseHandler(event, payload, uuid))
+
+ return uuid
+ }
+
+ /**
+ * Open a WebSocket subscription and resolve with its SocketLink.
+ *
+ * Resolves when this subscription's UUID-scoped `subscribe:<uuid>` event is
+ * published. Rejects if `unsubscribe:<uuid>` is published before the
+ * subscription succeeds.
+ *
+ * @param payload Optional connection payload sent to the server
+ * @returns SocketLink created from the server subscription response
+ * @throws Error when the socket closes before subscription completes
+ */
+ public async subscribeAsync<Response>(payload: unknown = undefined) {
+
+ return await new Promise<SocketLink<Response>>((resolve, reject) => {
+
+ const socketUuid = this.subscribe(payload)
+
+ const removeSubscribeSubscriber = this.$internal.subscribeOnce(`subscribe:${socketUuid}`, function (socketLink: SocketLink<Response>) {
+
+ removeUnsubscribeSubscriber()
+
+ resolve(socketLink)
+ })
+
+ const removeUnsubscribeSubscriber = this.$internal.subscribeOnce(`unsubscribe:${socketUuid}`, function (event: CloseEvent) {
+
+ removeSubscribeSubscriber()
+
+ reject(new Error(event.reason))
+ })
+ })
+ }
+
+ /**
+ * Publish an outbound event to the server through HTTP POST.
+ *
+ * Automatically invoked by outbound tunnel forwarding configured in the
+ * constructor.
+ *
+ * @param event Event identifier routed on the server
+ * @param values Event payload values sent to the server
+ * @returns Deserialized server handler results
+ * @throws Error when the server returns a non-successful response
+ */
+ private async publishHandler(event: string, ...values: unknown[]) {
+
+ // Send the event envelope to ServerLink's POST /publish endpoint.
+ const response = await fetch(`${this.url}/publish`, {
+
+ body: this.serialize([event, ...values]),
+
+ method: "POST"
+ })
+
+ if (!response.ok) throw new Error(await response.text())
+
+ return this.deserialize(await response.text())
+ }
+
+ /**
+ * Handle the server's WebSocket subscribe envelope.
+ *
+ * A `subscribe` message creates the client-side SocketLink for this
+ * connection, configures matching serialization, and publishes the internal
+ * `subscribe` event for application code. It also publishes
+ * `subscribe:<uuid>` for the specific subscribeAsync() call that opened this
+ * socket.
+ *
+ * @param event WebSocket message containing the serialized subscribe envelope
+ * @param socket Browser WebSocket instance for this connection
+ * @param uuid Connection identifier used for socket tracking
+ */
+ private async webSocketMessageHandler(event: MessageEvent, socket: WebSocket, uuid: string) {
+
+ const result = this.deserialize<{ type: string, data: unknown }>(event.data)
+
+ if (result.type === "subscribe") {
+
+ try {
+
+ // Wrap the browser WebSocket in a TheLink-compatible socket adapter.
+ const socketLink = new SocketLink(socket, result.data)
+
+ socketLink.setSerialize(value => this.serialize(value))
+
+ socketLink.setDeserialize(value => this.deserialize(value))
+
+ this.sockets.set(uuid, socketLink)
+
+ // Notify application code that this subscription is ready.
+ await this.$internal.publish("subscribe", socketLink)
+
+ await this.$internal.publish(`subscribe:${uuid}`, socketLink)
+ }
+
+ catch (exception) {
+
+ console.error(exception instanceof Error ? exception.message : "An unknown exception occurred")
+
+ socket.close(1000, exception instanceof Error ? exception.message : "An unknown exception occurred")
+ }
+ }
+ }
+
+ /**
+ * Clean up a closed WebSocket subscription and reconnect when recoverable.
+ *
+ * Publishes the socket-level unsubscribe event before removing the SocketLink
+ * from the active map, then publishes `unsubscribe:<uuid>` for callers
+ * waiting on that specific subscription. Recoverable close codes open a new
+ * subscription with the original payload after a short delay.
+ *
+ * @param event Browser WebSocket close event
+ * @param payload Original connection payload used for reconnect attempts
+ * @param uuid Connection identifier used to find the SocketLink
+ */
+ private async webSocketCloseHandler(event: CloseEvent, payload: unknown, uuid: string) {
+
+ try {
+
+ const socketLink = this.sockets.get(uuid)
+
+ // Notify socket consumers before dropping the tracked connection.
+ if (socketLink) await socketLink.$internal.publish("unsubscribe", event)
+
+ await this.$internal.publish(`unsubscribe:${uuid}`, event)
+ }
+
+ finally {
+
+ this.sockets.delete(uuid)
+
+ // Retry transient server or network closures with the original payload.
+ const reconnectCodes = new Set([1001, 1006, 1011, 1012, 1013, 1014])
+
+ if (reconnectCodes.has(event.code)) {
+
+ await new Promise(resolve => setTimeout(resolve, 1000))
+
+ this.subscribe(payload)
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/source/libs/the-link/plugins/client-link/socket-link.ts b/source/libs/the-link/plugins/client-link/socket-link.ts
new file mode 100644
index 0000000..e5c9202
--- /dev/null
+++ b/source/libs/the-link/plugins/client-link/socket-link.ts
@@ -0,0 +1,179 @@
+import TheLink from "../../the-link"
+import Tunnel from "../../tunnel"
+
+/**
+ * Client-side WebSocket adapter for a subscribed ServerLink connection.
+ *
+ * Wraps one browser WebSocket with TheLink-compatible inbound and outbound
+ * tunnels. Server messages are routed into the inbound tunnel, while outbound
+ * tunnel events are serialized and sent back through the WebSocket.
+ *
+ * Event messages use a simple `[event, ...values]` envelope.
+ *
+ * @example
+ * ```typescript
+ * const socket = await client.subscribeAsync()
+ *
+ * socket.$inbound.subscribe("server:event", handleServerEvent)
+ * await socket.$outbound.publish("client:event", payload)
+ * ```
+ */
+export default class SocketLink<Payload = unknown> extends TheLink {
+
+ /**
+ * Internal tunnel for this socket's lifecycle events.
+ *
+ * Publishes `unsubscribe` when the underlying WebSocket closes.
+ */
+ public readonly $internal: Tunnel = new Tunnel()
+
+ /**
+ * Browser WebSocket used for bidirectional transport.
+ */
+ private readonly socket: WebSocket
+
+ /**
+ * Server response payload supplied during subscription establishment.
+ */
+ public readonly payload: Payload
+
+ /**
+ * Converts outbound values into wire-format strings.
+ */
+ private serialize = <Input>(input: Input): string => JSON.stringify(input)
+
+ /**
+ * Converts wire-format strings back into typed values.
+ */
+ private deserialize = <Output>(input: string): Output => JSON.parse(input)
+
+ /**
+ * Initialize a SocketLink for one browser WebSocket subscription.
+ *
+ * @param socket Browser WebSocket connected to the server subscription route
+ * @param payload Server-provided subscription response payload
+ */
+ public constructor(socket: WebSocket, payload: Payload) {
+
+ super()
+
+ // Store the raw WebSocket connection for later message delivery.
+ this.socket = socket
+
+ // Preserve server-provided connection context for application handlers.
+ this.payload = payload
+
+ // Route server messages and close events through local handlers.
+ this.socket.addEventListener("message", this.subscribeHandler.bind(this))
+
+ this.socket.addEventListener("close", this.closeHandler.bind(this))
+
+ // Send outbound tunnel events to the server automatically.
+ this.$outbound.forwardTo(this.publishHandler.bind(this))
+ }
+
+ /**
+ * Configure the serialization function used for WebSocket payloads.
+ *
+ * @param serialize Custom function that converts values to strings
+ */
+ public setSerialize(serialize: typeof this.serialize<unknown>) {
+
+ this.serialize = serialize as typeof this.serialize
+ }
+
+ /**
+ * Configure the deserialization function used for WebSocket payloads.
+ *
+ * @param deserialize Custom function that parses values from strings
+ */
+ public setDeserialize(deserialize: typeof this.deserialize<unknown>) {
+
+ this.deserialize = deserialize as typeof this.deserialize
+ }
+
+ /**
+ * Connect another TheLink instance to this socket until it unsubscribes.
+ *
+ * @param theLink Source link whose events should be forwarded
+ * @param fromPrefix Source event prefix to match
+ * @param toPrefix Destination event prefix to apply
+ * @returns Function that manually disconnects forwarding and cleanup
+ */
+ public autoJoin(theLink: TheLink, fromPrefix: string = "", toPrefix: string = "") {
+
+ // Forward matching events from the source link to this socket.
+ const disconnect = theLink.connectTo(this, fromPrefix, toPrefix)
+
+ // Stop forwarding automatically when the socket closes.
+ const removeUnsubscribeSubscriber = this.$internal.subscribeOnce("unsubscribe", disconnect)
+
+ return function () {
+
+ // Allow callers to tear down forwarding before socket closure.
+ disconnect()
+
+ removeUnsubscribeSubscriber()
+ }
+ }
+
+ /**
+ * Close the WebSocket subscription from the client side.
+ *
+ * @param code WebSocket close code
+ * @param reason Close reason sent to the server
+ */
+ public unsubscribe(code: number = 1000, reason: string = "Unsubscribed by client") {
+
+ this.socket.close(code, reason)
+ }
+
+ /**
+ * Process a server message envelope and route it into the inbound tunnel.
+ *
+ * @param event Browser WebSocket message event
+ */
+ private async subscribeHandler(event: MessageEvent) {
+
+ const result = this.deserialize<{ type: string, data: [string, ...unknown[]] }>(event.data)
+
+ if (result.type === "message") {
+
+ // Decode the event payload from the server.
+ const [eventName, ...values] = result.data
+
+ try {
+
+ // Publish server event through this socket's inbound tunnel.
+ await this.$inbound.publish(eventName, ...values)
+ }
+
+ catch (exception) {
+
+ console.error(exception instanceof Error ? exception.message : "An unknown exception occurred")
+ }
+ }
+ }
+
+ /**
+ * Send an outbound tunnel event to the server.
+ *
+ * @param event Event identifier sent to the server
+ * @param values Event payload values sent to the server
+ */
+ private publishHandler(event: string, ...values: unknown[]) {
+
+ // Send the event envelope using the same simple event tuple protocol.
+ this.socket.send(this.serialize([event, ...values]))
+ }
+
+ /**
+ * Publish the socket-level unsubscribe event after WebSocket closure.
+ *
+ * @param event Browser WebSocket close event
+ */
+ private async closeHandler(event: CloseEvent) {
+
+ await this.$internal.publish("unsubscribe", event.code, event.reason)
+ }
+}
\ No newline at end of file
diff --git a/source/libs/the-link/plugins/process-link/process-link.ts b/source/libs/the-link/plugins/process-link/process-link.ts
new file mode 100644
index 0000000..37f1102
--- /dev/null
+++ b/source/libs/the-link/plugins/process-link/process-link.ts
@@ -0,0 +1,87 @@
+import { ChildProcess } from "child_process"
+import TheLink from "../../the-link"
+
+/**
+ * Process communication adapter using Node.js IPC.
+ *
+ * Provides bidirectional event routing between Node.js processes through an
+ * active IPC channel. Incoming IPC messages are published through the inbound
+ * tunnel, and outbound tunnel events are sent to the target process.
+ *
+ * Messages use TheLink's array envelope format:
+ * `[event, ...values]`.
+ *
+ * @example
+ * ```typescript
+ * // Child process
+ * const childLink = new ProcessLink()
+ * childLink.$inbound.subscribe("job:start", startJob)
+ *
+ * // Parent process
+ * const parentLink = new ProcessLink(worker)
+ * await parentLink.$outbound.publish("job:start", { id: 1 })
+ * ```
+ */
+export default class ProcessLink extends TheLink {
+
+ /**
+ * Target process used for IPC communication.
+ *
+ * Can be a ChildProcess instance in a parent process or the global process
+ * object in a child process. The target must expose `send`.
+ */
+ private readonly target: NodeJS.Process | ChildProcess
+
+ /**
+ * Initialize a ProcessLink with a target IPC process.
+ *
+ * @param target Process to communicate with, defaults to the current process
+ * @throws Error when the target does not have an active IPC channel
+ */
+ public constructor(target: NodeJS.Process | ChildProcess = process) {
+
+ super()
+
+ // Store the IPC target for message delivery.
+ this.target = target
+
+ if (typeof this.target.send !== "function") throw new Error("IPC channel not available. Ensure the process was spawned with IPC support.")
+
+ // Route IPC messages from the target into the local inbound tunnel.
+ this.target.on("message", this.messageHandler.bind(this))
+
+ // Send outbound tunnel events to the target process automatically.
+ this.$outbound.forwardTo(this.publishHandler.bind(this))
+ }
+
+ /**
+ * Process an incoming IPC message from the target process.
+ *
+ * Ignores messages that do not match TheLink's `[event, ...values]`
+ * protocol shape.
+ *
+ * @param message Raw IPC message received from the process
+ */
+ private async messageHandler(message: unknown) {
+
+ if (Array.isArray(message) && typeof message[0] === "string") {
+
+ // Decode the event envelope after validating its protocol shape.
+ const [event, ...values] = message as [string, ...unknown[]]
+
+ await this.$inbound.publish(event, ...values)
+ }
+ }
+
+ /**
+ * Publish an outbound tunnel event through the IPC channel.
+ *
+ * @param event Event identifier for the remote process
+ * @param values Event payload values sent over IPC
+ */
+ private publishHandler(event: string, ...values: unknown[]) {
+
+ // The non-null assertion is guarded by the constructor IPC check.
+ this.target.send!([event, ...values])
+ }
+}
\ No newline at end of file
diff --git a/source/libs/the-link/plugins/react-helper/property-hook.ts b/source/libs/the-link/plugins/react-helper/property-hook.ts
new file mode 100644
index 0000000..4e24aa3
--- /dev/null
+++ b/source/libs/the-link/plugins/react-helper/property-hook.ts
@@ -0,0 +1,30 @@
+import Property from "../../property"
+import { useCallback, useSyncExternalStore } from "react"
+
+/**
+ * React hook for reading a Property value reactively.
+ *
+ * The Property remains the source of truth. React reads its current snapshot
+ * and subscribes only for invalidation, so there is no mirrored state that can
+ * fall out of step between rendering and effect setup.
+ *
+ * @param property Property instance to synchronize with React state
+ * @returns Current property value, updated when the property publishes `change`
+ *
+ * @example
+ * ```typescript
+ * function ThemeLabel({ theme }: { theme: Property<string> }) {
+ * const value = useProperty(theme)
+ *
+ * return <span>{value}</span>
+ * }
+ * ```
+ */
+export default function useProperty<Value>(property: Property<Value>) {
+
+ const subscribe = useCallback((changed: () => void) => property.tunnel.subscribe("change", changed), [property])
+
+ const snapshot = useCallback(() => property.value, [property])
+
+ return useSyncExternalStore(subscribe, snapshot, snapshot)
+}
diff --git a/source/libs/the-link/plugins/react-helper/react-tunnel.ts b/source/libs/the-link/plugins/react-helper/react-tunnel.ts
new file mode 100644
index 0000000..4ab6cb9
--- /dev/null
+++ b/source/libs/the-link/plugins/react-helper/react-tunnel.ts
@@ -0,0 +1,99 @@
+import { useCallback, useEffect, useMemo, useState } from "react"
+import Tunnel, { Subscriber } from "../../tunnel"
+
+/**
+ * React hook helper for a Tunnel instance.
+ *
+ * Provides React-friendly subscription and state helpers around Tunnel events.
+ * Subscriptions are registered in effects and cleaned up automatically, while
+ * event payloads can be mirrored into React state for rendering.
+ *
+ * @example
+ * ```typescript
+ * function StatusView({ tunnel }: { tunnel: Tunnel }) {
+ * const reactTunnel = ReactTunnel.useFactory(tunnel)
+ * const status = reactTunnel.useFirstState("status:update", "idle")
+ *
+ * return <span>{status}</span>
+ * }
+ * ```
+ */
+export default class ReactTunnel {
+
+ /**
+ * Tunnel instance used by the React hook helpers.
+ */
+ public readonly tunnel: Tunnel
+
+ /**
+ * Initialize a ReactTunnel wrapper around a Tunnel.
+ *
+ * @param tunnel Tunnel instance to integrate with React components
+ */
+ public constructor(tunnel: Tunnel) {
+
+ // Store the tunnel used by all helper hooks.
+ this.tunnel = tunnel
+ }
+
+ /**
+ * Create a memoized ReactTunnel instance for a Tunnel.
+ *
+ * @param tunnel Tunnel instance to wrap
+ * @returns Stable ReactTunnel wrapper while the Tunnel reference is unchanged
+ */
+ public static useFactory(tunnel: Tunnel) {
+
+ return useMemo(() => new ReactTunnel(tunnel), [tunnel])
+ }
+
+ /**
+ * Subscribe to a Tunnel event with React lifecycle cleanup.
+ *
+ * @param event Event identifier to subscribe to
+ * @param subscriber Handler invoked when the event is published
+ */
+ public useSubscribe(event: string, subscriber: Subscriber) {
+
+ useEffect(() => {
+
+ // Register on mount or when the event/subscriber pair changes.
+ this.tunnel.subscribe(event, subscriber)
+
+ // Remove the exact subscriber when React cleans up the effect.
+ return () => this.tunnel.unsubscribe(event, subscriber)
+
+ }, [event, subscriber])
+ }
+
+ /**
+ * Mirror a Tunnel event's payload values into React state.
+ *
+ * @param event Event identifier used for state updates
+ * @param defaultResults Initial state values before the event is published
+ * @returns Latest event payload values
+ */
+ public useState<Results extends unknown[]>(event: string, defaultResults: Results): Results {
+
+ const [results, setResults] = useState<Results>(defaultResults)
+
+ // Store each event publication payload as the next React state value.
+ const subscriber = useCallback((...results: Results) => setResults(results), [])
+
+ this.useSubscribe(event, subscriber)
+
+ return results
+ }
+
+ /**
+ * Mirror the first value of a Tunnel event payload into React state.
+ *
+ * @param event Event identifier used for state updates
+ * @param defaultResult Initial value before the event is published
+ * @returns Latest first event payload value
+ */
+ public useFirstState<Result>(event: string, defaultResult: Result): Result {
+
+ return this.useState(event, [defaultResult])[0]
+ }
+}
\ No newline at end of file
diff --git a/source/libs/the-link/plugins/server-link/server-link.ts b/source/libs/the-link/plugins/server-link/server-link.ts
new file mode 100644
index 0000000..c8be82f
--- /dev/null
+++ b/source/libs/the-link/plugins/server-link/server-link.ts
@@ -0,0 +1,305 @@
+import { UpgradeWebSocket, WSContext, WSEvents } from "hono/ws"
+import Tunnel, { Subscriber } from "../../tunnel"
+import { HonoOptions } from "hono/hono-base"
+import SocketLink from "./socket-link"
+import { BlankEnv } from "hono/types"
+import TheLink from "../../the-link"
+import { Hono, Context } from "hono"
+import { v4 as uuidv4 } from "uuid"
+
+/**
+ * Hono server adapter for TheLink over HTTP and WebSocket endpoints.
+ *
+ * Provides a POST `/publish` endpoint for client-to-server events and an
+ * optional WebSocket `/subscribe` endpoint for long-lived server-to-client
+ * communication. Each accepted WebSocket connection gets a dedicated
+ * SocketLink instance, allowing application code to route events per client.
+ *
+ * The adapter uses JSON serialization by default, with hooks for custom
+ * serialization layers such as compression, encryption, or type-preserving
+ * codecs.
+ *
+ * Connection lifecycle events:
+ * - `subscribe`: Published on the internal tunnel when a socket connects
+ * - `unsubscribe`: Published through the SocketLink when a socket closes
+ *
+ * @example
+ * ```typescript
+ * const server = new ServerLink()
+ *
+ * server.prepareConnection(upgradeWebSocket)
+ *
+ * server.onSubscribe((socket) => {
+ * socket.autoJoin(server)
+ * })
+ * ```
+ */
+export default class ServerLink extends TheLink {
+
+ /**
+ * Internal tunnel for server-only lifecycle events.
+ *
+ * Keeps connection coordination separate from application inbound and
+ * outbound event traffic.
+ */
+ public readonly $internal: Tunnel = new Tunnel()
+
+ /**
+ * Hono application that owns the HTTP and WebSocket routes.
+ */
+ public readonly app: Hono
+
+ /**
+ * Controls whether handler errors are exposed to clients.
+ *
+ * Keep disabled in production to avoid leaking internal details.
+ */
+ private debugging: boolean = false
+
+ /**
+ * Converts outbound values into wire-format strings.
+ */
+ private serialize = <Input>(input: Input): string => JSON.stringify(input)
+
+ /**
+ * Converts wire-format strings back into typed values.
+ */
+ private deserialize = <Output>(input: string): Output => JSON.parse(input)
+
+ /**
+ * Active WebSocket-backed SocketLink instances keyed by connection UUID.
+ */
+ public readonly sockets: Map<string, SocketLink> = new Map()
+
+ /**
+ * Initialize a ServerLink with an optional Hono configuration object.
+ *
+ * @param options Hono application options passed to the underlying app
+ */
+ public constructor(options?: HonoOptions<BlankEnv>) {
+
+ super()
+
+ this.app = new Hono(options)
+ }
+
+ /**
+ * Register server communication routes on the Hono application.
+ *
+ * Always registers the POST `/publish` endpoint. When an Hono WebSocket
+ * upgrader is provided, also registers GET `/subscribe` for WebSocket
+ * subscriptions.
+ *
+ * @param upgradeWebSocket Optional Hono WebSocket upgrade helper
+ */
+ public prepareConnection(upgradeWebSocket?: UpgradeWebSocket) {
+
+ // Configure client-to-server event publication.
+ this.app.post("/publish", this.publishHandler.bind(this))
+
+ if (upgradeWebSocket) {
+
+ // Configure long-lived client subscriptions when WebSocket support is available.
+ this.app.get("/subscribe", upgradeWebSocket(this.webSocketHandler.bind(this)))
+ }
+ }
+
+ /**
+ * Enable detailed client-facing error messages.
+ */
+ public enableDebugging() {
+
+ this.debugging = true
+ }
+
+ /**
+ * Disable detailed client-facing error messages.
+ */
+ public disableDebugging() {
+
+ this.debugging = false
+ }
+
+ /**
+ * Configure the serialization function used for HTTP and WebSocket payloads.
+ *
+ * @param serialize Custom function that converts values to strings
+ */
+ public setSerialize(serialize: typeof this.serialize<unknown>) {
+
+ this.serialize = serialize as typeof this.serialize
+ }
+
+ /**
+ * Configure the deserialization function used for HTTP and WebSocket payloads.
+ *
+ * @param deserialize Custom function that parses values from strings
+ */
+ public setDeserialize(deserialize: typeof this.deserialize<unknown>) {
+
+ this.deserialize = deserialize as typeof this.deserialize
+ }
+
+ /**
+ * Register a handler for accepted WebSocket subscriptions.
+ *
+ * The subscriber receives the SocketLink created for the connection and can
+ * attach handlers, join tunnels, or return connection initialization data.
+ *
+ * @param subscriber Handler invoked with each new SocketLink
+ * @returns Function that removes this subscriber
+ */
+ public onSubscribe<Payload>(subscriber: Subscriber<[SocketLink<Payload>]>) {
+
+ return this.$internal.subscribe("subscribe", subscriber)
+ }
+
+ /**
+ * Process a client POST request and publish it through the inbound tunnel.
+ *
+ * @param context Hono request context containing serialized event data
+ * @returns Serialized event handler results, or a 500 error response
+ */
+ private async publishHandler(context: Context) {
+
+ try {
+
+ // Decode the event envelope from the request body.
+ const [event, ...values] = this.deserialize<[string, ...unknown[]]>(await context.req.text())
+
+ // Route the client event into the server-side inbound tunnel.
+ const results = await this.$inbound.publish(event, ...values)
+
+ return context.text(this.serialize(results))
+ }
+
+ catch (exception) {
+
+ console.error(exception instanceof Error ? exception.message : "An unknown exception occurred")
+
+ if (this.debugging) return context.text(exception instanceof Error ? exception.message : "An unknown exception occurred", 500)
+
+ else return context.text("An unknown exception occurred", 500)
+ }
+ }
+
+ /**
+ * Create the Hono WebSocket event handlers for a new subscription request.
+ *
+ * @param context Hono request context containing subscription query data
+ * @returns WebSocket lifecycle callbacks for this connection
+ */
+ private webSocketHandler(context: Context): WSEvents {
+
+ const uuid = uuidv4()
+
+ return {
+
+ onOpen: (_event, socket) => this.webSocketOpenHandler(context, socket, uuid),
+
+ onMessage: (event) => this.webSocketMessageHandler(event, uuid),
+
+ onClose: (event) => this.webSocketCloseHandler(event, uuid)
+ }
+ }
+
+ /**
+ * Accept a WebSocket connection and create its SocketLink facade.
+ *
+ * Reads the serialized `payload` query parameter, initializes a SocketLink,
+ * publishes the internal subscribe event, and sends the subscription response
+ * back to the client.
+ *
+ * @param context Hono request context containing subscription payload data
+ * @param socket Accepted WebSocket context
+ * @param uuid Connection identifier used for socket tracking
+ */
+ private async webSocketOpenHandler(context: Context, socket: WSContext, uuid: string) {
+
+ try {
+
+ // Extract client-provided connection context.
+ const payload = context.req.query("payload")
+
+ if (payload === undefined) throw new Error("payload is required")
+
+ const parsedPayload = this.deserialize<{ current: unknown }>(payload)
+
+ // Wrap the raw WebSocket in TheLink-compatible socket routing.
+ const socketLink = new SocketLink(socket, parsedPayload.current)
+
+ socketLink.setSerialize(value => this.serialize(value))
+
+ socketLink.setDeserialize(value => this.deserialize(value))
+
+ // Let application code initialize the connection before notifying the client.
+ const response = await this.$internal.publishFirst("subscribe", socketLink)
+
+ this.sockets.set(uuid, socketLink)
+
+ socket.send(this.serialize({ type: "subscribe", data: response }))
+ }
+
+ catch (exception) {
+
+ console.error(exception instanceof Error ? exception.message : "An unknown exception occurred")
+
+ if (this.debugging) return socket.close(1011, exception instanceof Error ? exception.message : "An unknown exception occurred")
+
+ else return socket.close(1011, "An unknown exception occurred")
+ }
+ }
+
+ /**
+ * Route a WebSocket message through the matching SocketLink inbound tunnel.
+ *
+ * @param event WebSocket message containing a serialized event envelope
+ * @param uuid Connection identifier used to find the SocketLink
+ */
+ private async webSocketMessageHandler(event: MessageEvent, uuid: string) {
+
+ const socketLink = this.sockets.get(uuid)
+
+ if (socketLink) {
+
+ // Decode the event payload from the message.
+ const [eventName, ...values] = this.deserialize<[string, ...unknown[]]>(event.data)
+
+ try {
+
+ // Publish client event through this socket's inbound tunnel.
+ await socketLink.$inbound.publish(eventName, ...values)
+ }
+
+ catch (exception) {
+
+ console.error(exception instanceof Error ? exception.message : "An unknown exception occurred")
+ }
+ }
+ }
+
+ /**
+ * Clean up a closed WebSocket connection.
+ *
+ * Publishes the socket-level unsubscribe event before removing the connection
+ * from the active socket map.
+ *
+ * @param event WebSocket close event
+ * @param uuid Connection identifier used to find the SocketLink
+ */
+ private async webSocketCloseHandler(event: CloseEvent, uuid: string) {
+
+ try {
+
+ const socketLink = this.sockets.get(uuid)
+
+ // Notify socket consumers before dropping the active connection.
+ if (socketLink) await socketLink.$internal.publish("unsubscribe", event)
+ }
+
+ finally {
+
+ this.sockets.delete(uuid)
+ }
+ }
+}
\ No newline at end of file
diff --git a/source/libs/the-link/plugins/server-link/socket-link.ts b/source/libs/the-link/plugins/server-link/socket-link.ts
new file mode 100644
index 0000000..b499133
--- /dev/null
+++ b/source/libs/the-link/plugins/server-link/socket-link.ts
@@ -0,0 +1,145 @@
+import TheLink from "../../the-link"
+import { WSContext } from "hono/ws"
+import Tunnel from "../../tunnel"
+
+/**
+ * Per-connection WebSocket adapter for TheLink server subscriptions.
+ *
+ * Wraps a single accepted WebSocket connection with TheLink-compatible inbound
+ * and outbound tunnels. Server code can use each SocketLink to publish events to
+ * one client and receive events from that client.
+ *
+ * Outbound events are serialized into `{ type: "message", data: [...] }`
+ * envelopes using a simple `[event, ...values]` event tuple.
+ *
+ * @example
+ * ```typescript
+ * server.onSubscribe((socket) => {
+ * socket.autoJoin(server)
+ * socket.$inbound.subscribe("client:event", handleClientEvent)
+ * })
+ * ```
+ */
+export default class SocketLink<Payload = unknown> extends TheLink {
+
+ /**
+ * Internal tunnel for this socket's lifecycle events.
+ *
+ * Currently used to coordinate cleanup when the socket unsubscribes.
+ */
+ public readonly $internal: Tunnel = new Tunnel()
+
+ /**
+ * Accepted WebSocket connection used for bidirectional transport.
+ */
+ private readonly socket: WSContext
+
+ /**
+ * Client payload supplied during subscription establishment.
+ */
+ public readonly payload: Payload
+
+ /**
+ * Converts outbound values into wire-format strings.
+ */
+ private serialize = <Input>(input: Input): string => JSON.stringify(input)
+
+ /**
+ * Converts wire-format strings back into typed values.
+ */
+ private deserialize = <Output>(input: string): Output => JSON.parse(input)
+
+ /**
+ * Initialize a SocketLink for one accepted WebSocket connection.
+ *
+ * The constructor stores the connection payload and forwards all outbound
+ * tunnel events to the WebSocket publish handler.
+ *
+ * @param socket Accepted WebSocket context
+ * @param payload Client payload supplied during subscription
+ */
+ public constructor(socket: WSContext, payload: Payload) {
+
+ super()
+
+ // Store the raw WebSocket connection for later message delivery.
+ this.socket = socket
+
+ // Preserve caller-provided connection context for application handlers.
+ this.payload = payload
+
+ // Send outbound tunnel events to this client automatically.
+ this.$outbound.forwardTo(this.publishHandler.bind(this))
+ }
+
+ /**
+ * Configure the serialization function used for WebSocket payloads.
+ *
+ * @param serialize Custom function that converts values to strings
+ */
+ public setSerialize(serialize: typeof this.serialize<unknown>) {
+
+ this.serialize = serialize as typeof this.serialize
+ }
+
+ /**
+ * Configure the deserialization function used for WebSocket payloads.
+ *
+ * @param deserialize Custom function that parses values from strings
+ */
+ public setDeserialize(deserialize: typeof this.deserialize<unknown>) {
+
+ this.deserialize = deserialize as typeof this.deserialize
+ }
+
+ /**
+ * Connect another TheLink instance to this socket until it unsubscribes.
+ *
+ * Creates a forwarding relationship from the source link to this socket, then
+ * registers cleanup on this socket's internal `unsubscribe` event.
+ *
+ * @param theLink Source link whose events should be forwarded
+ * @param fromPrefix Source event prefix to match
+ * @param toPrefix Destination event prefix to apply
+ * @returns Function that manually disconnects forwarding and cleanup
+ */
+ public autoJoin(theLink: TheLink, fromPrefix: string = "", toPrefix: string = "") {
+
+ // Forward matching events from the source link to this socket.
+ const disconnect = theLink.connectTo(this, fromPrefix, toPrefix)
+
+ // Stop forwarding automatically when the socket closes.
+ const removeUnsubscribeSubscriber = this.$internal.subscribeOnce("unsubscribe", disconnect)
+
+ return function () {
+
+ // Allow callers to tear down forwarding before socket closure.
+ disconnect()
+
+ removeUnsubscribeSubscriber()
+ }
+ }
+
+ /**
+ * Close the WebSocket subscription from the server side.
+ *
+ * @param code WebSocket close code
+ * @param reason Close reason sent to the client
+ */
+ public unsubscribe(code: number = 1000, reason: string = "Unsubscribed by server") {
+
+ this.socket.close(code, reason)
+ }
+
+ /**
+ * Send an outbound tunnel event to the client.
+ *
+ * @param event Event identifier sent to the client
+ * @param values Event payload values sent to the client
+ */
+ private publishHandler(event: string, ...values: unknown[]) {
+
+ // Send the event envelope using the same simple event tuple protocol.
+ this.socket.send(this.serialize({ type: "message", data: [event, ...values] }))
+ }
+}
\ No newline at end of file
diff --git a/source/libs/the-link/plugins/tab-link/tab-link.ts b/source/libs/the-link/plugins/tab-link/tab-link.ts
new file mode 100644
index 0000000..78fb67d
--- /dev/null
+++ b/source/libs/the-link/plugins/tab-link/tab-link.ts
@@ -0,0 +1,69 @@
+import TheLink from "../../the-link"
+
+/**
+ * Cross-tab communication adapter using the BroadcastChannel API.
+ *
+ * Provides lightweight bidirectional event routing between browser tabs and
+ * windows on the same origin. A shared namespace creates an isolated
+ * BroadcastChannel, preventing unrelated application contexts from receiving
+ * each other's events.
+ *
+ * Outbound tunnel events are posted to the channel with structured cloning, and
+ * incoming channel messages are published through the inbound tunnel.
+ *
+ * @example
+ * ```typescript
+ * const firstTab = new TabLink("workspace-sync")
+ * firstTab.$inbound.subscribe("document:update", handleUpdate)
+ *
+ * const secondTab = new TabLink("workspace-sync")
+ * await secondTab.$outbound.publish("document:update", documentData)
+ * ```
+ */
+export default class TabLink extends TheLink {
+
+ /**
+ * Namespace-isolated BroadcastChannel used for cross-tab transport.
+ */
+ private readonly channel: BroadcastChannel
+
+ /**
+ * Initialize a TabLink for one BroadcastChannel namespace.
+ *
+ * @param namespace Unique channel name shared by tabs that should communicate
+ */
+ public constructor(namespace: string) {
+
+ super()
+
+ // Create the same-origin channel used to exchange events between tabs.
+ this.channel = new BroadcastChannel(namespace)
+
+ // Route messages from other tabs into the local inbound tunnel.
+ this.channel.addEventListener("message", this.messageHandler.bind(this))
+
+ // Broadcast local outbound events to other tabs.
+ this.$outbound.forwardTo(this.publishHandler.bind(this))
+ }
+
+ /**
+ * Process an incoming BroadcastChannel message.
+ *
+ * @param message BroadcastChannel message containing an event envelope
+ */
+ private async messageHandler(message: MessageEvent<[string, ...unknown[]]>) {
+
+ await this.$inbound.publish(...message.data)
+ }
+
+ /**
+ * Publish an outbound tunnel event to the BroadcastChannel.
+ *
+ * @param event Event identifier for remote tabs
+ * @param values Event payload values sent through structured cloning
+ */
+ private publishHandler(event: string, ...values: unknown[]) {
+
+ this.channel.postMessage([event, ...values])
+ }
+}
\ No newline at end of file
diff --git a/source/libs/the-link/property.ts b/source/libs/the-link/property.ts
new file mode 100644
index 0000000..854c60c
--- /dev/null
+++ b/source/libs/the-link/property.ts
@@ -0,0 +1,219 @@
+import { v4 as uuidv4 } from "uuid"
+import TheLink from "./the-link"
+import Tunnel from "./tunnel"
+
+/**
+ * Reactive property synchronized through a TheLink instance.
+ *
+ * A provider owns the property key and source value. Consumers bind to that key
+ * and receive `property-update:<key>` events through their link. Every Property
+ * also exposes a local tunnel that publishes `change` whenever its stored value
+ * changes.
+ */
+export default class Property<Value> {
+
+ /**
+ * Local notification tunnel for this property's value changes.
+ */
+ public readonly tunnel: Tunnel = new Tunnel()
+
+ /**
+ * Provider or consumer role controlling update propagation.
+ */
+ private readonly type: PropertyType
+
+ /**
+ * Link used to publish and receive cross-instance property updates.
+ */
+ private readonly theLink: TheLink
+
+ /**
+ * Unique property identifier used in the update event namespace.
+ */
+ public readonly key: string
+
+ /**
+ * Current locally stored value.
+ */
+ private _value: Value
+
+ /**
+ * Optional inbound value mapper or validator.
+ */
+ private interceptor: PropertyInterceptor<any, Value> | null = null
+
+ /**
+ * Initialize a property instance and subscribe it to its update namespace.
+ *
+ * @param type Provider or consumer role
+ * @param theLink Link used for cross-instance synchronization
+ * @param key Property update namespace key
+ * @param value Initial local value
+ */
+ private constructor(type: PropertyType, theLink: TheLink, key: string, value: Value) {
+
+ this.type = type
+
+ this.theLink = theLink
+
+ this.key = key
+
+ this._value = value
+
+ // Receive updates published by connected providers or consumers.
+ this.theLink.$inbound.subscribe(`property-update:${this.key}`, this.updateHandler.bind(this))
+ }
+
+ /**
+ * Create a public provider property with a generated key.
+ *
+ * Public providers accept inbound update requests and relay accepted values
+ * back outbound to synchronize all consumers.
+ *
+ * @param theLink Link used for synchronization
+ * @param value Initial provider value
+ * @param interceptor Optional inbound value mapper or validator
+ * @returns Provider property with a generated key
+ */
+ public static public<Value>(theLink: TheLink, value: Value, interceptor?: PropertyInterceptor<any, Value>) {
+
+ const property = new this("provider", theLink, uuidv4(), value)
+
+ if (interceptor) property.setInterceptor(interceptor)
+
+ return property
+ }
+
+ /**
+ * Create a private provider property with a generated key.
+ *
+ * Private providers reject inbound update requests by installing an
+ * interceptor that always throws.
+ *
+ * @param theLink Link used for synchronization
+ * @param value Initial provider value
+ * @returns Provider property that rejects consumer update requests
+ */
+ public static private<Value>(theLink: TheLink, value: Value) {
+
+ return this.public(theLink, value, function () {
+
+ throw new Error("You cannot request update a private property.")
+ })
+ }
+
+ /**
+ * Create a consumer property bound to an existing provider key.
+ *
+ * @param theLink Link used for synchronization
+ * @param key Provider property key to consume
+ * @param value Initial local value before the first provider update
+ * @param interceptor Optional inbound value mapper or validator
+ * @returns Consumer property bound to the provider key
+ */
+ public static consumer<Value>(theLink: TheLink, key: string, value: Value, interceptor?: PropertyInterceptor<any, Value>) {
+
+ const property = new Property("consumer", theLink, key, value)
+
+ if (interceptor) property.setInterceptor(interceptor)
+
+ return property
+ }
+
+ /**
+ * Set or clear the inbound value interceptor.
+ *
+ * @param interceptor Mapper or validator for inbound values, or null to clear
+ */
+ public setInterceptor(interceptor: PropertyInterceptor<any, Value> | null) {
+
+ this.interceptor = interceptor
+ }
+
+ /**
+ * Current local property value.
+ */
+ public get value() {
+
+ return this._value
+ }
+
+ /**
+ * Store a new local value and notify local subscribers.
+ *
+ * @param value New local value
+ */
+ private async setValue(value: Value) {
+
+ this._value = value
+
+ await this.tunnel.publish("change", value)
+ }
+
+ /**
+ * Publish a property update through the link's outbound tunnel.
+ *
+ * @param value Value to publish to connected links
+ */
+ private async publish(value: Value) {
+
+ await this.theLink.$outbound.publish(`property-update:${this.key}`, value)
+ }
+
+ /**
+ * Update this property and propagate the value.
+ *
+ * Providers update their local value immediately before publishing. Consumers
+ * publish the request and rely on the provider's relayed update to settle the
+ * synchronized value.
+ *
+ * @param value New value or requested value
+ */
+ public async update(value: Value) {
+
+ if (this.type === "provider") await this.setValue(value)
+
+ await this.publish(value)
+ }
+
+ /**
+ * Handle an inbound property update event.
+ *
+ * @param value Incoming value from the link inbound tunnel
+ */
+ private async updateHandler(value: Value) {
+
+ // Interceptors can transform or reject inbound values.
+ if (this.interceptor) value = this.interceptor(value)
+
+ await this.setValue(value)
+
+ // Providers relay accepted inbound updates to every connected consumer.
+ if (this.type === "provider") await this.publish(value)
+ }
+
+ /**
+ * Serialize the property as its public key/value shape.
+ *
+ * @returns Plain object representation used by JSON.stringify
+ */
+ public toJSON() {
+
+ return {
+
+ key: this.key,
+
+ value: this.value
+ }
+ }
+}
+
+/**
+ * Property role in the provider/consumer relationship.
+ */
+export type PropertyType = "provider" | "consumer"
+
+/**
+ * Function applied to inbound property values before local storage.
+ */
+export type PropertyInterceptor<IncomingValue, ProcessedValue> = (incomingValue: IncomingValue) => ProcessedValue
diff --git a/source/libs/the-link/the-link.ts b/source/libs/the-link/the-link.ts
new file mode 100644
index 0000000..b5acaa1
--- /dev/null
+++ b/source/libs/the-link/the-link.ts
@@ -0,0 +1,157 @@
+import Tunnel from "./tunnel"
+
+/**
+ * Base link abstraction built from inbound and outbound event tunnels.
+ *
+ * TheLink provides a two-tunnel model for bidirectional event flow. Subclasses
+ * can publish through `$outbound`, receive through `$inbound`, and connect to
+ * other links through prefix-aware forwarding relationships.
+ *
+ * Decorator implementations use `addInitializer()` to register instance setup
+ * work on the class prototype. The constructor executes those initializers for
+ * each new instance.
+ */
+export default class TheLink {
+
+ /**
+ * Events received by this link from other links or adapters.
+ */
+ public readonly $inbound: Tunnel = new Tunnel()
+
+ /**
+ * Events published by this link toward other links or adapters.
+ */
+ public readonly $outbound: Tunnel = new Tunnel()
+
+ /**
+ * Initialize a link and run prototype-registered decorator initializers.
+ */
+ public constructor() {
+
+ const initializers: Initializer<typeof this>[] = this.constructor.prototype.$initializers ??= []
+
+ // Decorators register these initializers on the prototype before construction.
+ for (const initializer of initializers) initializer(this)
+ }
+
+ /**
+ * Register a constructor-time initializer on the class prototype.
+ *
+ * Intended for decorator implementations only.
+ *
+ * @param initializer Function executed for each constructed instance
+ * @throws Error when called on an already constructed instance
+ */
+ public addInitializer(initializer: Initializer<typeof this>) {
+
+ if (this !== this.constructor.prototype) throw new Error("addInitializer() can only be called on the class prototype during decoration, not on constructed instances")
+
+ const initializers: Initializer<typeof this>[] = this.constructor.prototype.$initializers ??= []
+
+ initializers.push(initializer)
+ }
+
+ /**
+ * Forward another link's inbound events into this link's inbound tunnel.
+ *
+ * @param theLink Source link to subscribe to
+ * @param fromPrefix Source event prefix to match and strip
+ * @param toPrefix Destination event prefix to prepend
+ * @returns Cleanup function that removes this forwarding relationship
+ */
+ public subscribeTo(theLink: TheLink, fromPrefix: string = "", toPrefix: string = "") {
+
+ theLink.$inbound.forwardTo(this.$inbound, fromPrefix, toPrefix)
+
+ return () => this.unsubscribeFrom(theLink, fromPrefix, toPrefix)
+ }
+
+ /**
+ * Stop forwarding another link's inbound events into this link.
+ *
+ * @param theLink Source link used during subscription
+ * @param fromPrefix Source prefix used during subscription
+ * @param toPrefix Destination prefix used during subscription
+ */
+ public unsubscribeFrom(theLink: TheLink, fromPrefix: string = "", toPrefix: string = "") {
+
+ theLink.$inbound.stopForwardingTo(this.$inbound, fromPrefix, toPrefix)
+ }
+
+ /**
+ * Forward this link's outbound events into another link's outbound tunnel.
+ *
+ * @param theLink Target link to publish to
+ * @param fromPrefix Source event prefix to match and strip
+ * @param toPrefix Destination event prefix to prepend
+ * @returns Cleanup function that removes this forwarding relationship
+ */
+ public publishTo(theLink: TheLink, fromPrefix: string = "", toPrefix: string = "") {
+
+ this.$outbound.forwardTo(theLink.$outbound, fromPrefix, toPrefix)
+
+ return () => this.stopPublishingTo(theLink, fromPrefix, toPrefix)
+ }
+
+ /**
+ * Stop forwarding this link's outbound events into another link.
+ *
+ * @param theLink Target link used during publication forwarding
+ * @param fromPrefix Source prefix used during forwarding
+ * @param toPrefix Destination prefix used during forwarding
+ */
+ public stopPublishingTo(theLink: TheLink, fromPrefix: string = "", toPrefix: string = "") {
+
+ this.$outbound.stopForwardingTo(theLink.$outbound, fromPrefix, toPrefix)
+ }
+
+ /**
+ * Connect this link to another link in both directions.
+ *
+ * `fromPrefix` applies to events received from the target link. `toPrefix`
+ * applies to events sent to the target link, with prefixes swapped for the
+ * outbound side so the relationship is symmetric.
+ *
+ * @param theLink Link to connect with
+ * @param fromPrefix Prefix for events received from the target link
+ * @param toPrefix Prefix for events sent to the target link
+ * @returns Cleanup function that disconnects both directions
+ */
+ public connectTo(theLink: TheLink, fromPrefix: string = "", toPrefix: string = "") {
+
+ this.subscribeTo(theLink, fromPrefix, toPrefix)
+
+ this.publishTo(theLink, toPrefix, fromPrefix)
+
+ return () => this.disconnectFrom(theLink, fromPrefix, toPrefix)
+ }
+
+ /**
+ * Disconnect a bidirectional relationship created by connectTo().
+ *
+ * @param theLink Link to disconnect from
+ * @param fromPrefix Prefix used for received events
+ * @param toPrefix Prefix used for sent events
+ */
+ public disconnectFrom(theLink: TheLink, fromPrefix: string = "", toPrefix: string = "") {
+
+ this.unsubscribeFrom(theLink, fromPrefix, toPrefix)
+
+ this.stopPublishingTo(theLink, toPrefix, fromPrefix)
+ }
+}
+
+/**
+ * Constructor-time setup function registered by decorators.
+ */
+export type Initializer<TargetLink extends TheLink> = (instanceLink: TargetLink) => void
+
+/**
+ * Method shape used by publish-oriented decorators.
+ */
+export type Publisher = (...values: any[]) => Promise<any>
+
+/**
+ * TheLink tunnel selector used by decorators.
+ */
+export type TunnelName = "outbound" | "inbound"
\ No newline at end of file
diff --git a/source/libs/the-link/tunnel.ts b/source/libs/the-link/tunnel.ts
new file mode 100644
index 0000000..976e49b
--- /dev/null
+++ b/source/libs/the-link/tunnel.ts
@@ -0,0 +1,369 @@
+
+/**
+ * Event tunnel with interceptors, subscribers, forwarders, and finalizers.
+ *
+ * A publish call runs through four phases:
+ * intercept matching prefixes, exact-event subscribers, prefix-based forwarders,
+ * then result finalizers. Subscribers and forwarders contribute results, while
+ * interceptors transform payload values and finalizers transform result values.
+ */
+export default class Tunnel {
+
+ /**
+ * Prefix-matched functions that can transform values before publication.
+ */
+ private readonly interceptors: Map<string, Set<Interceptor>> = new Map()
+
+ /**
+ * Exact event subscribers keyed by event name.
+ */
+ private readonly subscribers: Map<string, Set<Subscriber>> = new Map()
+
+ /**
+ * Forwarding rules keyed by source prefix, then destination prefix.
+ */
+ private readonly forwarders: Map<string, Map<string, Set<Forwarder | Tunnel>>> = new Map()
+
+ /**
+ * Prefix-matched functions that can transform aggregated publish results.
+ */
+ private readonly finalizers: Map<string, Set<Finalizer>> = new Map()
+
+ /**
+ * Register a payload interceptor for events matching a prefix.
+ *
+ * @param interceptor Function that can transform publication values
+ * @param prefix Event prefix to match, or an empty string for all events
+ * @returns Cleanup function that removes this interceptor
+ */
+ public addInterceptor(interceptor: Interceptor, prefix: string = "") {
+
+ if (!this.interceptors.has(prefix)) this.interceptors.set(prefix, new Set())
+
+ this.interceptors.get(prefix)!.add(interceptor)
+
+ return () => this.removeInterceptor(interceptor, prefix)
+ }
+
+ /**
+ * Remove a previously registered interceptor.
+ *
+ * @param interceptor Interceptor function to remove
+ * @param prefix Prefix used during registration
+ */
+ public removeInterceptor(interceptor: Interceptor, prefix: string = "") {
+
+ const interceptorSet = this.interceptors.get(prefix)
+
+ if (interceptorSet) {
+
+ interceptorSet.delete(interceptor)
+
+ if (interceptorSet.size === 0) this.interceptors.delete(prefix)
+ }
+ }
+
+ /**
+ * Subscribe to an exact event name.
+ *
+ * @param event Event identifier to listen for
+ * @param subscriber Handler invoked when the event is published
+ * @returns Cleanup function that removes this subscriber
+ */
+ public subscribe(event: string, subscriber: Subscriber) {
+
+ if (!this.subscribers.has(event)) this.subscribers.set(event, new Set())
+
+ this.subscribers.get(event)!.add(subscriber)
+
+ return () => this.unsubscribe(event, subscriber)
+ }
+
+ /**
+ * Remove a previously registered subscriber.
+ *
+ * @param event Event identifier used during registration
+ * @param subscriber Subscriber function to remove
+ */
+ public unsubscribe(event: string, subscriber: Subscriber) {
+
+ const subscriberSet = this.subscribers.get(event)
+
+ if (subscriberSet) {
+
+ subscriberSet.delete(subscriber)
+
+ if (subscriberSet.size === 0) this.subscribers.delete(event)
+ }
+ }
+
+ /**
+ * Subscribe to an event once, then remove the subscriber before it runs.
+ *
+ * @param event Event identifier to listen for
+ * @param subscriber Handler invoked for the first matching publication
+ * @returns Cleanup function that cancels the pending one-time subscription
+ */
+ public subscribeOnce(event: string, subscriber: Subscriber) {
+
+ const removeSubscription = this.subscribe(event, async function (...values) {
+
+ // Remove before invocation so re-entrant publishes do not call it twice.
+ removeSubscription()
+
+ await subscriber(...values)
+ })
+
+ return removeSubscription
+ }
+
+ /**
+ * Wait for the next publication of an event.
+ *
+ * @param event Event identifier to wait for
+ * @param timeout Maximum wait time in milliseconds
+ * @returns Event payload values from the next matching publication
+ * @throws Error when the timeout expires before the event is published
+ */
+ public async waitFor<Results extends unknown[]>(event: string, timeout: number = 30_000) {
+
+ return await new Promise<Results>((resolve, reject) => {
+
+ const removeSubscription = this.subscribeOnce(event, function (...values: Results) {
+
+ resolve(values)
+
+ // Cancel timeout work after the awaited event arrives.
+ if (timer) clearTimeout(timer)
+ })
+
+ const timer = setTimeout(function () {
+
+ // Remove the one-time subscriber before rejecting on timeout.
+ removeSubscription()
+
+ reject(new Error(`Event promise timeout ${timeout}ms`))
+
+ }, timeout)
+ })
+ }
+
+ /**
+ * Wait for an event and return only its first payload value.
+ *
+ * @param event Event identifier to wait for
+ * @param timeout Maximum wait time in milliseconds
+ * @returns First value from the next matching publication
+ */
+ public async waitFirst<Result>(event: string, timeout: number = 30_000) {
+
+ const [result] = await this.waitFor<[Result]>(event, timeout)
+
+ return result
+ }
+
+ /**
+ * Forward matching events to another Tunnel or a custom forwarder.
+ *
+ * Matching removes `fromPrefix` from the source event name, then prepends
+ * `toPrefix` before forwarding.
+ *
+ * @param forwarder Target Tunnel or forwarding function
+ * @param fromPrefix Source event prefix to match and strip
+ * @param toPrefix Destination event prefix to prepend
+ * @returns Cleanup function that removes this forwarding rule
+ */
+ public forwardTo(forwarder: Forwarder | Tunnel, fromPrefix: string = "", toPrefix: string = "") {
+
+ if (!this.forwarders.has(fromPrefix)) this.forwarders.set(fromPrefix, new Map())
+
+ const forwardersFrom = this.forwarders.get(fromPrefix)!
+
+ if (!forwardersFrom.has(toPrefix)) forwardersFrom.set(toPrefix, new Set())
+
+ const forwardersTo = forwardersFrom.get(toPrefix)!
+
+ forwardersTo.add(forwarder)
+
+ return () => this.stopForwardingTo(forwarder, fromPrefix, toPrefix)
+ }
+
+ /**
+ * Remove a previously registered forwarding rule.
+ *
+ * @param forwarder Target Tunnel or forwarding function to remove
+ * @param fromPrefix Source prefix used during registration
+ * @param toPrefix Destination prefix used during registration
+ */
+ public stopForwardingTo(forwarder: Forwarder | Tunnel, fromPrefix: string = "", toPrefix: string = "") {
+
+ const forwardersFrom = this.forwarders.get(fromPrefix)
+
+ if (!forwardersFrom) return
+
+ const forwardersTo = forwardersFrom.get(toPrefix)
+
+ if (!forwardersTo) return
+
+ forwardersTo.delete(forwarder)
+
+ // Remove now-empty nested maps so stale prefix entries do not accumulate.
+ if (forwardersTo.size === 0) forwardersFrom.delete(toPrefix)
+
+ if (forwardersFrom.size === 0) this.forwarders.delete(fromPrefix)
+ }
+
+ /**
+ * Register a result finalizer for events matching a prefix.
+ *
+ * @param finalizer Function that can transform aggregated publish results
+ * @param prefix Event prefix to match, or an empty string for all events
+ * @returns Cleanup function that removes this finalizer
+ */
+ public addFinalizer(finalizer: Finalizer, prefix: string = "") {
+
+ if (!this.finalizers.has(prefix)) this.finalizers.set(prefix, new Set())
+
+ this.finalizers.get(prefix)!.add(finalizer)
+
+ return () => this.removeFinalizer(finalizer, prefix)
+ }
+
+ /**
+ * Remove a previously registered finalizer.
+ *
+ * @param finalizer Finalizer function to remove
+ * @param prefix Prefix used during registration
+ */
+ public removeFinalizer(finalizer: Finalizer, prefix: string = "") {
+
+ const finalizerSet = this.finalizers.get(prefix)
+
+ if (finalizerSet) {
+
+ finalizerSet.delete(finalizer)
+
+ if (finalizerSet.size === 0) this.finalizers.delete(prefix)
+ }
+ }
+
+ /**
+ * Publish an event through interceptors, subscribers, forwarders, and finalizers.
+ *
+ * @param event Event identifier to publish
+ * @param values Event payload values
+ * @returns Aggregated and finalized handler results
+ */
+ public async publish<Results extends unknown[]>(event: string, ...values: unknown[]): Promise<Results> {
+
+ let results = []
+
+ // Phase 1: matching interceptors can replace the payload values.
+ const interceptorGroups = this.interceptors.entries().filter(([prefix]) => event.startsWith(prefix))
+
+ for (const [_prefix, interceptorSet] of interceptorGroups) {
+
+ for (const interceptor of interceptorSet) {
+
+ const transformedValues = await interceptor(...values)
+
+ if (Array.isArray(transformedValues)) values = transformedValues
+
+ // A single non-undefined value becomes the next payload tuple.
+ else if (transformedValues !== undefined) values = [transformedValues]
+ }
+ }
+
+ // Phase 2: exact-event subscribers run with the final payload values.
+ const subscribers = this.subscribers.get(event) || []
+
+ for (const subscriber of subscribers) {
+
+ const result = await subscriber(...values)
+
+ if (result !== undefined) results.push(result)
+ }
+
+ // Phase 3: prefix-matched forwarders receive rewritten event names.
+ const forwardersFrom = this.forwarders.entries().filter(([prefix]) => event.startsWith(prefix))
+
+ for (const [fromPrefix, forwardersTo] of forwardersFrom) {
+
+ for (const [toPrefix, forwarders] of forwardersTo) {
+
+ for (const forwarder of forwarders) {
+
+ if (forwarder instanceof Tunnel) {
+
+ // Tunnel forwarders return arrays that are flattened into this result set.
+ const result = await forwarder.publish(toPrefix + event.slice(fromPrefix.length), ...values)
+
+ results.push(...result)
+ }
+
+ else {
+
+ const result = await forwarder(toPrefix + event.slice(fromPrefix.length), ...values)
+
+ if (Array.isArray(result)) results.push(...result)
+
+ // Custom forwarders can return one value or an array of values.
+ else if (result !== undefined) results.push(result)
+ }
+ }
+ }
+ }
+
+ // Phase 4: matching finalizers can replace the aggregated result values.
+ const finalizerGroups = this.finalizers.entries().filter(([prefix]) => event.startsWith(prefix))
+
+ for (const [_prefix, finalizerSet] of finalizerGroups) {
+
+ for (const finalizer of finalizerSet) {
+
+ const transformedResults = await finalizer(...results)
+
+ if (Array.isArray(transformedResults)) results = transformedResults
+
+ // A single non-undefined value becomes the next result tuple.
+ else if (transformedResults !== undefined) results = [transformedResults]
+ }
+ }
+
+ return results as Results
+ }
+
+ /**
+ * Publish an event and return only the first result.
+ *
+ * @param event Event identifier to publish
+ * @param values Event payload values
+ * @returns First value from the aggregated publish results
+ */
+ public async publishFirst<Result>(event: string, ...values: unknown[]): Promise<Result> {
+
+ const [result] = await this.publish<[Result]>(event, ...values)
+
+ return result
+ }
+}
+
+/**
+ * Interceptor function signature for transforming event payload values.
+ */
+export type Interceptor<Values extends unknown[] = any[]> = (...values: Values) => any
+
+/**
+ * Subscriber function signature for exact event handling.
+ */
+export type Subscriber<Values extends unknown[] = any[]> = (...values: Values) => any
+
+/**
+ * Forwarder function signature for custom prefix-based routing.
+ */
+export type Forwarder<Values extends unknown[] = any[]> = (forwardedEvent: string, ...values: Values) => any
+
+/**
+ * Finalizer function signature for transforming aggregated publish results.
+ */
+export type Finalizer<Results extends unknown[] = any[]> = (...results: Results) => any
\ No newline at end of file
diff --git a/source/pack.ts b/source/pack.ts
new file mode 100644
index 0000000..0ffabfe
--- /dev/null
+++ b/source/pack.ts
@@ -0,0 +1,32 @@
+import { name, version } from "@/package.json"
+import { createHash } from "node:crypto"
+import { readFileSync, readdirSync, writeFileSync } from "node:fs"
+import { resolve } from "node:path"
+import AdmZip from "adm-zip"
+
+const archive = `${name}@${version}.zip`
+
+const zip = new AdmZip()
+
+zip.addLocalFolder(resolve("dist"))
+
+// Bundled assets already live in each consumer's build output. Everything
+// else retains its filesystem identity and therefore accompanies the build.
+for (const asset of readdirSync(resolve("assets"), { withFileTypes: true })) {
+
+ if (asset.name === "bundled" || asset.name.startsWith(".")) continue
+
+ const source = resolve("assets", asset.name)
+
+ if (asset.isDirectory()) zip.addLocalFolder(source, `assets/${asset.name}`)
+
+ else if (asset.isFile()) zip.addLocalFile(source, "assets")
+}
+
+zip.writeZip(resolve(archive))
+
+const checksum = createHash("sha256").update(readFileSync(resolve(archive))).digest("hex")
+
+writeFileSync(resolve(`${archive}.sha256`), `${checksum} ${archive}\n`)
+
+console.log(`\nPacked ${archive}`)
diff --git a/source/server/core/application.ts b/source/server/core/application.ts
new file mode 100644
index 0000000..451689e
--- /dev/null
+++ b/source/server/core/application.ts
@@ -0,0 +1,120 @@
+import LinkManager from "./link-manager/link-manager"
+import Authentication from "./authentication/authentication"
+import FileManager from "@libs/file-manager"
+import Encryptor from "@libs/encryptor"
+import ServedFileManager from "./served-file-manager"
+import DialogManager from "./dialog-manager"
+import ThemeManager from "./theme-manager"
+import WallpaperManager from "./wallpaper-manager"
+import openStore from "./open-store"
+import Keyv from "keyv"
+
+export default class Application {
+
+ public readonly name: string
+
+ public readonly displayName: string
+
+ public readonly version: string
+
+ /** Filesystem-owned fallback used by the authoritative Program icon service. */
+ public readonly defaultProgramIcon: string
+
+ public readonly storage: FileManager
+
+ /** Internal application persistence, reached publicly through named methods. */
+ public readonly store: Keyv
+
+ public readonly encryptor: Encryptor
+
+ public readonly authentication: Authentication
+
+ public readonly servedFiles: ServedFileManager
+
+ public readonly dialogManager: DialogManager
+
+ public readonly themeManager: ThemeManager
+
+ public readonly wallpaperManager: WallpaperManager
+
+ public readonly linkManager: LinkManager
+
+ private constructor(payload: ApplicationPayload) {
+
+ this.name = payload.name
+
+ this.displayName = payload.displayName
+
+ this.version = payload.version
+
+ this.defaultProgramIcon = payload.defaultProgramIcon
+
+ this.storage = payload.storage
+
+ this.encryptor = payload.encryptor
+
+ this.store = payload.store
+
+ this.authentication = payload.authentication
+
+ this.themeManager = payload.themeManager
+
+ this.wallpaperManager = payload.wallpaperManager
+
+ this.servedFiles = payload.servedFiles
+
+ this.dialogManager = new DialogManager()
+
+ this.linkManager = new LinkManager(this)
+ }
+
+ public static async initialize(name: string, displayName: string, version: string, storagePath: string | undefined, defaultProgramIcon: string) {
+
+ const storage = storagePath ? new FileManager(storagePath) : FileManager.forApp(name)
+
+ const store = openStore(storage.path)
+
+ const encryptor = await Encryptor.initialize(storage.join("private.pem"))
+
+ const authentication = await Authentication.open(storage.join("credentials.json"), store)
+
+ const themeManager = await ThemeManager.open(store)
+
+ const servedFiles = new ServedFileManager(storage.navigateTo("uploads"))
+
+ const wallpaperManager = await WallpaperManager.open(store, servedFiles)
+
+ const application = new Application({ name, displayName, version, defaultProgramIcon, storage, store, encryptor, authentication, themeManager, wallpaperManager, servedFiles })
+
+ await application.linkManager.authManager.programManager.initialize()
+
+ await application.wallpaperManager.initialize(application.linkManager.authManager.programManager)
+
+ return application
+ }
+}
+
+interface ApplicationPayload {
+
+ name: string
+
+ displayName: string
+
+ version: string
+
+ defaultProgramIcon: string
+
+ storage: FileManager
+
+ store: Keyv
+
+ encryptor: Encryptor
+
+ authentication: Authentication
+
+ themeManager: ThemeManager
+
+ wallpaperManager: WallpaperManager
+
+ servedFiles: ServedFileManager
+}
diff --git a/source/server/core/authentication/authentication.ts b/source/server/core/authentication/authentication.ts
new file mode 100644
index 0000000..e50b38a
--- /dev/null
+++ b/source/server/core/authentication/authentication.ts
@@ -0,0 +1,346 @@
+import { readFile, writeFile } from "node:fs/promises"
+import { randomBytes, scrypt as derive, timingSafeEqual } from "node:crypto"
+import Sessions from "./sessions"
+import Keyv from "keyv"
+
+const parameters = {
+
+ cost: 16_384,
+
+ blockSize: 8,
+
+ parallelization: 1,
+
+ keyLength: 64
+} as const
+
+const requirements = {
+
+ username: {
+
+ minimumLength: 1,
+
+ maximumLength: 64
+ },
+
+ password: {
+
+ minimumLength: 8,
+
+ maximumLength: 1_024
+ }
+} as const
+
+/** Persistent credentials for the sole owner of one installation. */
+export default class Authentication {
+
+ private owner: Owner | null
+
+ private readonly path: string
+
+ private readonly sessions: Sessions
+
+ private constructor(path: string, owner: Owner | null, sessions: Sessions) {
+
+ this.path = path
+
+ this.owner = owner
+
+ this.sessions = sessions
+ }
+
+ public static async open(path: string, store: Keyv) {
+
+ const sessions = await Sessions.open(store)
+
+ try {
+
+ return new Authentication(path, parse(await readFile(path, "utf8")), sessions)
+ }
+
+ catch (exception) {
+
+ if (isMissing(exception)) return new Authentication(path, null, sessions)
+
+ throw exception
+ }
+ }
+
+ public state(): AuthenticationState {
+
+ return {
+
+ registered: this.owner !== null,
+
+ requirements
+ }
+ }
+
+ public async register(username: string, password: string): Promise<RegistrationResult> {
+
+ if (this.owner) return { error: "registered" }
+
+ const normalizedUsername = normalizeUsername(username)
+
+ const invalid = validate(normalizedUsername, password)
+
+ if (invalid) return { error: invalid }
+
+ const salt = randomBytes(16)
+
+ const hash = await hashPassword(password, salt, parameters)
+
+ const owner: Owner = {
+
+ version: 1,
+
+ username: normalizedUsername,
+
+ password: {
+
+ algorithm: "scrypt",
+
+ salt: salt.toString("base64"),
+
+ hash: hash.toString("base64"),
+
+ ...parameters
+ }
+ }
+
+ try {
+
+ await writeFile(this.path, JSON.stringify(owner), { flag: "wx", mode: 0o600 })
+
+ this.owner = owner
+
+ return { registered: true }
+ }
+
+ catch (exception) {
+
+ if (!isExisting(exception)) throw exception
+
+ // Another registration won the exclusive write. Load that owner
+ // before reporting the closed state so this instance cannot reopen it.
+ this.owner = parse(await readFile(this.path, "utf8"))
+
+ return { error: "registered" }
+ }
+ }
+
+ public async verify(username: string, password: string) {
+
+ if (!this.owner) return false
+
+ if ([...password].length > requirements.password.maximumLength) return false
+
+ const candidate = await hashPassword(password, Buffer.from(this.owner.password.salt, "base64"), this.owner.password)
+
+ const expected = Buffer.from(this.owner.password.hash, "base64")
+
+ return normalizeUsername(username) === this.owner.username
+
+ && candidate.length === expected.length
+
+ && timingSafeEqual(candidate, expected)
+ }
+
+ /** Creates a durable session after the owner has authenticated. */
+ public createSession() {
+
+ return this.sessions.create()
+ }
+
+ /** Whether a session is still within its connection-bound lifetime. */
+ public sessionValid(identity: string) {
+
+ return this.sessions.valid(identity)
+ }
+
+ /** Attaches a live connection and renews the session without a timer. */
+ public connectSession(identity: string) {
+
+ return this.sessions.connect(identity)
+ }
+
+ /** Records when the final live connection to a session disappears. */
+ public disconnectSession(identity: string) {
+
+ return this.sessions.disconnect(identity)
+ }
+
+ /** Revokes a session explicitly when its owner signs out. */
+ public removeSession(identity: string) {
+
+ return this.sessions.remove(identity)
+ }
+}
+
+function normalizeUsername(username: string) {
+
+ return username.trim().normalize("NFKC")
+}
+
+function validate(username: string, password: string): RegistrationError | null {
+
+ const usernameLength = [...username].length
+
+ if (usernameLength < requirements.username.minimumLength) return "username-required"
+
+ if (usernameLength > requirements.username.maximumLength || /\p{Cc}/u.test(username)) return "username-invalid"
+
+ const passwordLength = [...password].length
+
+ if (passwordLength < requirements.password.minimumLength) return "password-too-short"
+
+ if (passwordLength > requirements.password.maximumLength) return "password-too-long"
+
+ if (password.normalize("NFKC").toLowerCase() === username.toLowerCase()) return "password-matches-username"
+
+ return null
+}
+
+function hashPassword(password: string, salt: Buffer, parameters: ScryptParameters) {
+
+ return new Promise<Buffer>(function (resolve, reject) {
+
+ derive(password, salt, parameters.keyLength, {
+
+ cost: parameters.cost,
+
+ blockSize: parameters.blockSize,
+
+ parallelization: parameters.parallelization,
+
+ maxmem: 64 * 1_024 * 1_024
+
+ }, function (exception, key) {
+
+ if (exception) reject(exception)
+
+ else resolve(key)
+ })
+ })
+}
+
+function parse(contents: string): Owner {
+
+ const value: unknown = JSON.parse(contents)
+
+ if (!isOwner(value)) throw new Error("The owner credentials are invalid")
+
+ return value
+}
+
+function isOwner(value: unknown): value is Owner {
+
+ if (!value || typeof value !== "object") return false
+
+ const candidate = value as Partial<Owner>
+
+ if (candidate.version !== 1
+
+ || typeof candidate.username !== "string"
+
+ || candidate.password?.algorithm !== "scrypt"
+
+ || typeof candidate.password.salt !== "string"
+
+ || typeof candidate.password.hash !== "string"
+
+ || candidate.password.cost !== parameters.cost
+
+ || candidate.password.blockSize !== parameters.blockSize
+
+ || candidate.password.parallelization !== parameters.parallelization
+
+ || candidate.password.keyLength !== parameters.keyLength) return false
+
+ return Buffer.from(candidate.password.salt, "base64").length === 16
+
+ && Buffer.from(candidate.password.hash, "base64").length === parameters.keyLength
+}
+
+function isMissing(exception: unknown) {
+
+ return isFileError(exception, "ENOENT")
+}
+
+function isExisting(exception: unknown) {
+
+ return isFileError(exception, "EEXIST")
+}
+
+function isFileError(exception: unknown, code: string) {
+
+ return exception instanceof Error && "code" in exception && exception.code === code
+}
+
+export interface AuthenticationState {
+
+ registered: boolean
+
+ requirements: {
+
+ username: {
+
+ minimumLength: number
+
+ maximumLength: number
+ }
+
+ password: {
+
+ minimumLength: number
+
+ maximumLength: number
+ }
+ }
+}
+
+export type RegistrationResult = {
+
+ registered: true
+
+} | {
+
+ error: RegistrationError
+}
+
+export type RegistrationError = "registered" | "username-required" | "username-invalid" | "password-too-short" | "password-too-long" | "password-matches-username"
+
+interface Owner {
+
+ version: 1
+
+ username: string
+
+ password: {
+
+ algorithm: "scrypt"
+
+ salt: string
+
+ hash: string
+
+ cost: number
+
+ blockSize: number
+
+ parallelization: number
+
+ keyLength: number
+ }
+}
+
+interface ScryptParameters {
+
+ cost: number
+
+ blockSize: number
+
+ parallelization: number
+
+ keyLength: number
+}
diff --git a/source/server/core/authentication/sessions.ts b/source/server/core/authentication/sessions.ts
new file mode 100644
index 0000000..b8af142
--- /dev/null
+++ b/source/server/core/authentication/sessions.ts
@@ -0,0 +1,175 @@
+import Keyv from "keyv"
+import { randomUUID } from "node:crypto"
+
+const storageKey = "authentication:sessions"
+
+/** How long an authentication session survives without a live connection. */
+export const disconnectedSessionLifetime = 24 * 60 * 60 * 1_000
+
+/**
+ * Durable authentication sessions, independent of transient desktop links.
+ *
+ * A session remains valid while at least one connection holds it. The link
+ * manager records the final connection loss here; reconnecting clears that
+ * timestamp, while a full disconnected day makes the session unreachable.
+ */
+export default class Sessions {
+
+ private readonly store: Keyv
+
+ private readonly sessions: Map<string, StoredSession>
+
+ private writing: Promise<unknown> = Promise.resolve()
+
+ private constructor(store: Keyv, sessions: Map<string, StoredSession>) {
+
+ this.store = store
+
+ this.sessions = sessions
+ }
+
+ public static async open(store: Keyv) {
+
+ const stored = parse(await store.get(storageKey))
+
+ const now = Date.now()
+
+ const sessions = new Map<string, StoredSession>()
+
+ let changed = false
+
+ for (const record of stored) {
+
+ // No connections survive a host restart. A record that was live
+ // when the host stopped becomes disconnected when this host opens.
+ const disconnectedAt = record.disconnectedAt ?? now
+
+ if (disconnectedAt !== record.disconnectedAt) changed = true
+
+ if (now - disconnectedAt > disconnectedSessionLifetime) {
+
+ changed = true
+
+ continue
+ }
+
+ sessions.set(record.identity, { identity: record.identity, disconnectedAt })
+ }
+
+ const opened = new Sessions(store, sessions)
+
+ if (changed) await opened.persist()
+
+ return opened
+ }
+
+ /** Creates a resumable session which has not yet acquired a connection. */
+ public async create() {
+
+ this.prune(Date.now())
+
+ const identity = randomUUID()
+
+ this.sessions.set(identity, { identity, disconnectedAt: Date.now() })
+
+ await this.persist()
+
+ return identity
+ }
+
+ /** Whether the session exists and has not exhausted its disconnected day. */
+ public valid(identity: string) {
+
+ const session = this.sessions.get(identity)
+
+ if (!session) return false
+
+ if (session.disconnectedAt === null || Date.now() - session.disconnectedAt <= disconnectedSessionLifetime) return true
+
+ this.sessions.delete(identity)
+
+ this.persist().catch(() => undefined)
+
+ return false
+ }
+
+ /** Resumes a valid session and removes its disconnected deadline. */
+ public async connect(identity: string) {
+
+ if (!this.valid(identity)) return false
+
+ const session = this.sessions.get(identity)!
+
+ if (session.disconnectedAt === null) return true
+
+ session.disconnectedAt = null
+
+ await this.persist()
+
+ return true
+ }
+
+ /** Starts the grace period after the session's final connection is lost. */
+ public async disconnect(identity: string) {
+
+ const session = this.sessions.get(identity)
+
+ if (!session) return
+
+ session.disconnectedAt = Date.now()
+
+ await this.persist()
+ }
+
+ /** Revokes a session immediately, independently of its connections. */
+ public async remove(identity: string) {
+
+ if (!this.sessions.delete(identity)) return
+
+ await this.persist()
+ }
+
+ private persist() {
+
+ const snapshot = [...this.sessions.values()].map(session => ({ ...session }))
+
+ const writing = this.writing.catch(() => undefined).then(() => this.store.set(storageKey, snapshot))
+
+ this.writing = writing
+
+ return writing
+ }
+
+ private prune(now: number) {
+
+ for (const [identity, session] of this.sessions) {
+
+ if (session.disconnectedAt !== null && now - session.disconnectedAt > disconnectedSessionLifetime) this.sessions.delete(identity)
+ }
+ }
+}
+
+function parse(value: unknown): StoredSession[] {
+
+ if (value === undefined) return []
+
+ if (!Array.isArray(value) || !value.every(isStoredSession)) throw new Error("The authentication sessions are invalid")
+
+ return value
+}
+
+function isStoredSession(value: unknown): value is StoredSession {
+
+ if (!value || typeof value !== "object") return false
+
+ const record = value as Partial<StoredSession>
+
+ return typeof record.identity === "string" && (record.disconnectedAt === null || typeof record.disconnectedAt === "number" && Number.isFinite(record.disconnectedAt))
+}
+
+interface StoredSession {
+
+ identity: string
+
+ disconnectedAt: number | null
+}
diff --git a/source/server/core/dialog-manager.ts b/source/server/core/dialog-manager.ts
new file mode 100644
index 0000000..44a49db
--- /dev/null
+++ b/source/server/core/dialog-manager.ts
@@ -0,0 +1,234 @@
+import { Subscribe } from "@libs/the-link/decorators/escript"
+import { Transmitted } from "@libs/superjson"
+import TheLink from "@libs/the-link/the-link"
+import { randomUUID } from "node:crypto"
+import { type default as Process } from "./link-manager/auth-manager/process-manager/process"
+import { type PermissionName } from "@phreshos/core"
+
+/** Authoritative runtime queue of system messages awaiting acknowledgment. */
+export default class DialogManager extends TheLink {
+
+ public readonly dialogs = new Map<string, SystemDialog>()
+
+ private readonly permissionRequests = new Map<string, PendingPermission>()
+
+ private readonly permissionProcesses = new Map<string, string>()
+
+ public list() {
+
+ return [...this.dialogs.values()]
+ }
+
+ /** Records one unexpected Server ending independently of its dead handle. */
+ public async serverCrashed(process: Process, code: number | null, signal: NodeJS.Signals | null) {
+
+ const dialog: ServerCrashDialog = {
+
+ identity: randomUUID(),
+
+ kind: "serverCrash",
+
+ createdAt: new Date(),
+
+ program: {
+
+ identity: process.program.identity,
+
+ name: process.program.name
+ },
+
+ process: {
+
+ identity: process.identity,
+
+ name: process.name
+ },
+
+ code,
+
+ signal
+ }
+
+ this.dialogs.set(dialog.identity, dialog)
+
+ // Authority already retains the record. A lost desktop is born with
+ // the queue when it returns; notification failure must not interrupt
+ // the Process teardown that produced this dialog.
+ await this.$outbound.publish("/created", dialog).catch(() => undefined)
+ }
+
+ /** Waits for one authoritative user decision for a Client Process. */
+ public async requestPermission(process: Process, request: string, permission: PermissionName): Promise<PermissionChoice> {
+
+ if (this.permissionProcesses.has(process.reference)) throw new Error("This Client Process already has a pending permission request")
+
+ const dialog: PermissionDialog = {
+
+ identity: randomUUID(),
+
+ kind: "permission",
+
+ createdAt: new Date(),
+
+ permission,
+
+ program: {
+
+ identity: process.program.identity,
+
+ name: process.program.name
+ },
+
+ process: {
+
+ identity: process.identity,
+
+ name: process.name
+ }
+ }
+
+ let settle: (choice: PermissionChoice) => void = () => undefined
+
+ const answer = new Promise<PermissionChoice>(resolve => { settle = resolve })
+
+ const stopExit = process.onExit(() => { this.cancelPermission(request, process.reference).catch(() => undefined) })
+
+ this.permissionRequests.set(request, { request, dialog, process: process.reference, settle, stopExit })
+
+ this.permissionProcesses.set(process.reference, request)
+
+ this.dialogs.set(dialog.identity, dialog)
+
+ await this.$outbound.publish("/created", dialog).catch(() => undefined)
+
+ return await answer
+ }
+
+ /** Resolves one permission prompt from any synchronized desktop. */
+ @Subscribe("/resolve-permission")
+ protected async resolvePermission(identity: unknown, choice: unknown) {
+
+ if (!isPermissionChoice(choice)) return
+
+ const pending = [...this.permissionRequests.values()].find(entry => entry.dialog.identity === identity)
+
+ if (!pending) return
+
+ await this.finishPermission(pending, choice)
+ }
+
+ /** Cancels one boundary-owned prompt without creating a decision. */
+ public async cancelPermission(request: string, process: string) {
+
+ const pending = this.permissionRequests.get(request)
+
+ if (!pending || pending.process !== process) return
+
+ await this.finishPermission(pending, null)
+ }
+
+ private async finishPermission(pending: PendingPermission, choice: PermissionChoice) {
+
+ if (!this.permissionRequests.delete(pending.request)) return
+
+ this.permissionProcesses.delete(pending.process)
+
+ this.dialogs.delete(pending.dialog.identity)
+
+ pending.stopExit()
+
+ pending.settle(choice)
+
+ await this.$outbound.publish("/removed", pending.dialog.identity).catch(() => undefined)
+ }
+
+ /** Removes an acknowledged dialog once, including simultaneous acknowledgments. */
+ @Subscribe("/acknowledge")
+ protected async acknowledge(identity: unknown) {
+
+ if (typeof identity !== "string" || this.dialogs.get(identity)?.kind !== "serverCrash" || !this.dialogs.delete(identity)) return
+
+ await this.$outbound.publish("/removed", identity)
+ }
+
+ public toJSON() {
+
+ return { dialogs: this.dialogs }
+ }
+}
+
+export interface ServerCrashDialog {
+
+ readonly identity: string
+
+ readonly kind: "serverCrash"
+
+ readonly createdAt: Date
+
+ readonly program: Readonly<{
+
+ identity: string
+
+ name: string
+ }>
+
+ readonly process: Readonly<{
+
+ identity: string
+
+ name: string | null
+ }>
+
+ readonly code: number | null
+
+ readonly signal: string | null
+}
+
+export interface PermissionDialog {
+
+ readonly identity: string
+
+ readonly kind: "permission"
+
+ readonly createdAt: Date
+
+ readonly permission: PermissionName
+
+ readonly program: Readonly<{
+
+ identity: string
+
+ name: string
+ }>
+
+ readonly process: Readonly<{
+
+ identity: string
+
+ name: string | null
+ }>
+}
+
+export type PermissionChoice = "process" | "always" | false | null
+
+export type SystemDialog = ServerCrashDialog | PermissionDialog
+
+interface PendingPermission {
+
+ readonly request: string
+
+ readonly dialog: PermissionDialog
+
+ readonly process: string
+
+ readonly settle: (choice: PermissionChoice) => void
+
+ readonly stopExit: () => void
+}
+
+function isPermissionChoice(value: unknown): value is PermissionChoice {
+
+ return value === "process" || value === "always" || value === false || value === null
+}
+
+export type TransmittedDialogManager = Transmitted<DialogManager>
diff --git a/source/server/core/link-manager/auth-manager/auth-manager.ts b/source/server/core/link-manager/auth-manager/auth-manager.ts
new file mode 100644
index 0000000..dbe6935
--- /dev/null
+++ b/source/server/core/link-manager/auth-manager/auth-manager.ts
@@ -0,0 +1,172 @@
+import { Connect, Forward, Intercept, Subscribe } from "@libs/the-link/decorators/escript"
+import ServedFileManager from "@server/core/served-file-manager"
+import DialogManager from "@server/core/dialog-manager"
+import ProcessManager from "./process-manager/process-manager"
+import ProgramManager from "./program-manager/program-manager"
+import { Transmitted } from "@libs/superjson"
+import TheLink from "@libs/the-link/the-link"
+import LinkManager from "../link-manager"
+import { isPermissionName } from "@phreshos/core"
+
+export default class AuthManager extends TheLink {
+
+ public readonly linkManager: LinkManager
+
+ public readonly programManager: ProgramManager
+
+ public readonly processManager: ProcessManager
+
+ public readonly dialogManager: DialogManager
+
+ public constructor(linkManager: LinkManager) {
+
+ super()
+
+ this.linkManager = linkManager
+
+ this.programManager = new ProgramManager(this)
+
+ this.processManager = new ProcessManager(this)
+
+ this.dialogManager = this.linkManager.application.dialogManager
+
+ this.dialogManager.connectTo(this, "/dialog")
+
+ this.subscribeTo(this.linkManager, "/auth")
+ }
+
+ private get servedFiles(): ServedFileManager {
+
+ return this.linkManager.application.servedFiles
+ }
+
+ // What being authorized means, decided once. Every road in asks
+ // here: the link before it carries a message, and the uploads door
+ // before it accepts bytes.
+ public verify(authorization: unknown) {
+
+ const session = typeof authorization === "string" ? this.linkManager.resolveAuthorization(authorization) : null
+
+ if (!session) throw new Error("Unauthorized")
+ }
+
+ @Intercept("inbound")
+ protected authenticate(authorization: string, ...values: unknown[]) {
+
+ this.verify(authorization)
+
+ return values
+ }
+
+ // Making a value public is authorized here; the uploads door is only the
+ // client transport that brings its bytes to this operation.
+ public async serve(authorization: unknown, content: ReadableStream<Uint8Array> | null, type: string | null, extension: string, signal?: AbortSignal) {
+
+ this.verify(authorization)
+
+ const file = await this.servedFiles.write(extension, content, signal)
+
+ return { ...this.servedFiles.describe(file), type }
+ }
+
+ /** Perform a server-side request after the desktop door proves authorization. */
+ public fetch(authorization: unknown, input: string | URL | Request, init?: RequestInit) {
+
+ this.verify(authorization)
+
+ return fetch(input, init)
+ }
+
+ public streamArea(authorization: unknown, identity: string, area: "data" | "cache", path: string[]) {
+
+ this.verify(authorization)
+
+ return this.programManager.streamArea(identity, area, path)
+ }
+
+ /** Replace the system Theme through the authenticated boundary. */
+ @Subscribe("/theme")
+ public async updateTheme(value: unknown) {
+
+ return await this.linkManager.updateTheme(value)
+ }
+
+ @Connect("/permission/granted")
+ protected async permissionGranted(process: unknown, permission: unknown) {
+
+ if (typeof process !== "string" || !isPermissionName(permission)) throw new Error("A permission request is invalid")
+
+ return this.processManager.permissionGranted(process, permission)
+ }
+
+ @Connect("/permission/request")
+ protected async requestPermission(request: unknown, process: unknown, permission: unknown) {
+
+ if (typeof request !== "string" || typeof process !== "string" || !isPermissionName(permission)) throw new Error("A permission request is invalid")
+
+ return await this.processManager.requestPermission(process, request, permission)
+ }
+
+ @Subscribe("/permission/cancel")
+ protected async cancelPermission(request: unknown, process: unknown) {
+
+ if (typeof request !== "string" || typeof process !== "string") return
+
+ await this.processManager.cancelPermission(process, request)
+ }
+
+ public async writeArea(authorization: unknown, identity: string, area: "data" | "cache", path: string[], content: ReadableStream<Uint8Array> | null, signal?: AbortSignal) {
+
+ this.verify(authorization)
+
+ await this.programManager.writeArea(identity, area, path, content, signal)
+ }
+
+ // A targeted client observation belongs to one authorized desktop
+ // connection. Send its copy only there; the ordinary outbound road is a
+ // broadcast and would widen one frame's interest to every session.
+ public async publishToConnection(connectionIdentity: string, event: string, ...values: unknown[]) {
+
+ const connection = this.linkManager.connections.get(connectionIdentity)
+
+ if (!connection?.session) return
+
+ await connection.link.$outbound.publish(`/auth${event}`, ...values)
+ }
+
+ @Forward("outbound", undefined, "/auth")
+ protected async broadcastToConnections(event: string, ...values: unknown[]) {
+
+ for (const connection of this.linkManager.connections.values()) {
+
+ if (!connection.session) continue
+
+ await connection.link.$outbound.publish(event, ...values)
+ }
+ }
+
+ public toJSON() {
+
+ return {
+
+ programManager: this.programManager,
+
+ processManager: this.processManager,
+
+ dialogManager: this.dialogManager
+ }
+ }
+}
+
+export type TransmittedAuthManager = Transmitted<AuthManager>
+
+export interface ServedFile {
+
+ file: string
+
+ type: string | null
+
+ size: number
+
+ time: number
+}
diff --git a/source/server/core/link-manager/auth-manager/process-manager/client-process-forwarder.ts b/source/server/core/link-manager/auth-manager/process-manager/client-process-forwarder.ts
new file mode 100644
index 0000000..07e86b9
--- /dev/null
+++ b/source/server/core/link-manager/auth-manager/process-manager/client-process-forwarder.ts
@@ -0,0 +1,175 @@
+import AuthManager from "../auth-manager"
+import ProcessTraffic, { type Half, type TrafficKind } from "./process-traffic"
+import EndpointEvents from "./endpoint-events"
+
+/**
+ * Server-host counterpart of one client Process boundary lease.
+ *
+ * The desktop boundary owns the subscription semantically. This small relay
+ * retains only the transport forwarding needed to reach that exact connection,
+ * pane and document, and releases every interest with that lease.
+ */
+export default class ClientProcessForwarder {
+
+ public readonly connection: string
+
+ public readonly pane: string
+
+ public readonly owner: string
+
+ private readonly authManager: AuthManager
+
+ private readonly traffic: ProcessTraffic
+
+ private readonly endpointEvents: EndpointEvents
+
+ private readonly observations = new Map<string, () => void>()
+
+ private readonly endpointSubscriptions = new Map<string, () => void>()
+
+ private readonly requests = new Map<string, () => void>()
+
+ private readonly subscriptions = new Map<string, string | null>()
+
+ private readonly shapeObservedValues: (values: unknown[]) => unknown[]
+
+ public constructor(connection: string, pane: string, owner: string, authManager: AuthManager, traffic: ProcessTraffic, endpointEvents: EndpointEvents, shapeObservedValues: (values: unknown[]) => unknown[]) {
+
+ this.connection = connection
+
+ this.pane = pane
+
+ this.owner = owner
+
+ this.authManager = authManager
+
+ this.traffic = traffic
+
+ this.endpointEvents = endpointEvents
+
+ this.shapeObservedValues = shapeObservedValues
+ }
+
+ public observe(subscription: string, target: string, half: Half, kind: TrafficKind, event: string | null, reportImpossible: boolean) {
+
+ this.unobserve(subscription)
+
+ const stop = this.traffic.observe(target, half, kind, event, (word, ...payload) => {
+
+ const values = this.shapeObservedValues(event === null ? [word, ...payload] : payload)
+
+ this.authManager.publishToConnection(this.connection, "/process/observed", this.pane, this.owner, subscription, JSON.stringify(values)).catch(() => undefined)
+ }, reportImpossible ? reason => this.impossible(subscription, reason) : undefined)
+
+ this.observations.set(subscription, stop)
+ }
+
+ public impossible(subscription: string, reason: string) {
+
+ this.unobserve(subscription)
+
+ this.authManager.publishToConnection(this.connection, "/process/impossible", this.pane, this.owner, subscription, reason).catch(() => undefined)
+ }
+
+ public unobserve(subscription: string) {
+
+ this.observations.get(subscription)?.()
+
+ this.observations.delete(subscription)
+ }
+
+ /** Retain one live inbound Channel publication interest for this exact client lease. */
+ public subscribe(subscription: string, event: string | null) {
+
+ this.subscriptions.set(subscription, event)
+ }
+
+ public unsubscribe(subscription: string) {
+
+ this.subscriptions.delete(subscription)
+ }
+
+ /** Forward ordinary publications only when this lease asked for them. */
+ public async forward(values: unknown[]) {
+
+ const event = values[0]
+
+ if (typeof event !== "string" || ![...this.subscriptions.values()].some(registered => registered === null || registered === event)) return
+
+ await this.send(values)
+ }
+
+ /** Complete only a question retained by this exact client lease. */
+ public answer(question: string, values: unknown[]) {
+
+ if (!this.requests.has(question)) return false
+
+ this.requests.delete(question)
+
+ this.send(values).catch(() => undefined)
+
+ return true
+ }
+
+ public follow(subscription: string, target: string, half: Half, event: string | null, reportImpossible: boolean) {
+
+ this.unfollow(subscription)
+
+ const stop = this.endpointEvents.follow(target, half, event, (word, payload) => {
+
+ const values = event === null ? [word, payload] : [payload]
+
+ this.authManager.publishToConnection(this.connection, "/process/emitted", this.pane, this.owner, subscription, JSON.stringify(values)).catch(() => undefined)
+ }, reportImpossible ? reason => this.impossibleFollow(subscription, reason) : undefined)
+
+ this.endpointSubscriptions.set(subscription, stop)
+ }
+
+ private impossibleFollow(subscription: string, reason: string) {
+
+ this.authManager.publishToConnection(this.connection, "/process/impossible", this.pane, this.owner, subscription, reason).catch(() => undefined)
+ }
+
+ public unfollow(subscription: string) {
+
+ this.endpointSubscriptions.get(subscription)?.()
+
+ this.endpointSubscriptions.delete(subscription)
+ }
+
+ public retain(question: string, stop: () => void) {
+
+ this.requests.get(question)?.()
+
+ this.requests.set(question, stop)
+ }
+
+ public cancel(question: string) {
+
+ this.requests.get(question)?.()
+
+ this.requests.delete(question)
+ }
+
+ public release() {
+
+ for (const stop of this.observations.values()) stop()
+
+ for (const stop of this.endpointSubscriptions.values()) stop()
+
+ for (const stop of this.requests.values()) stop()
+
+ this.observations.clear()
+
+ this.endpointSubscriptions.clear()
+
+ this.requests.clear()
+
+ this.subscriptions.clear()
+ }
+
+ private async send(values: unknown[]) {
+
+ await this.authManager.publishToConnection(this.connection, "/process/end-end", this.pane, JSON.stringify(values))
+ }
+}
diff --git a/source/server/core/link-manager/auth-manager/process-manager/client-state.ts b/source/server/core/link-manager/auth-manager/process-manager/client-state.ts
new file mode 100644
index 0000000..e433b12
--- /dev/null
+++ b/source/server/core/link-manager/auth-manager/process-manager/client-state.ts
@@ -0,0 +1,18 @@
+import Window from "./window"
+
+/**
+ * The one authoritative client state of a Process.
+ *
+ * Browser tabs may each represent this state with an iframe and a nearby
+ * boundary, but none of those representations owns it. The Window is part of
+ * this state and therefore begins and ends with the client, not with a tab.
+ */
+export default class ClientState {
+
+ public readonly window: Window
+
+ public constructor(window: Window) {
+
+ this.window = window
+ }
+}
diff --git a/source/server/core/link-manager/auth-manager/process-manager/endpoint-events.ts b/source/server/core/link-manager/auth-manager/process-manager/endpoint-events.ts
new file mode 100644
index 0000000..e59ee5e
--- /dev/null
+++ b/source/server/core/link-manager/auth-manager/process-manager/endpoint-events.ts
@@ -0,0 +1,63 @@
+import TheLink from "@libs/the-link/the-link"
+import { type Half } from "./process-traffic"
+
+/**
+ * Destinationless application events emitted by Process endpoints.
+ *
+ * Unlike ProcessTraffic, these routes have no destination metadata: the
+ * Endpoint is the source being followed, and only explicit followers join its
+ * route. Endpoint incarnation changes do not end a route; Process exit does.
+ */
+export default class EndpointEvents extends TheLink {
+
+ public emit(process: string, half: Half, event: string, payload: unknown) {
+
+ return this.$inbound.publish(this.event(process, half, event), event, payload)
+ }
+
+ /** End every fallible subscription to this Process's Endpoint events. */
+ public end(process: string, reason: string) {
+
+ return this.$inbound.publish(this.terminal(process), reason)
+ }
+
+ public follow(process: string, half: Half, event: string | null, subscriber: Subscriber, impossible?: (reason: string) => void) {
+
+ const prefix = this.prefix(process, half)
+
+ const stopEvent = event !== null
+ ? this.$inbound.subscribe(prefix + encodeURIComponent(event), (_word, payload) => subscriber(event, payload))
+ : this.$inbound.forwardTo((_route, word, payload) => {
+
+ if (typeof word === "string") subscriber(word, payload)
+ }, prefix)
+
+ const stopTerminal = impossible
+ ? this.$inbound.subscribe(this.terminal(process), (reason: unknown) => impossible(String(reason)))
+ : () => undefined
+
+ return () => {
+
+ stopEvent()
+
+ stopTerminal()
+ }
+ }
+
+ private terminal(process: string) {
+
+ return `terminal/${encodeURIComponent(process)}`
+ }
+
+ private prefix(process: string, half: Half) {
+
+ return `${encodeURIComponent(process)}/${half}/`
+ }
+
+ private event(process: string, half: Half, event: string) {
+
+ return this.prefix(process, half) + encodeURIComponent(event)
+ }
+}
+
+type Subscriber = (event: string, payload: unknown) => unknown
diff --git a/source/server/core/link-manager/auth-manager/process-manager/endpoint-reference.ts b/source/server/core/link-manager/auth-manager/process-manager/endpoint-reference.ts
new file mode 100644
index 0000000..959984e
--- /dev/null
+++ b/source/server/core/link-manager/auth-manager/process-manager/endpoint-reference.ts
@@ -0,0 +1,31 @@
+import { type Half } from "./process-traffic"
+import Process, { type ProcessRecord } from "./process"
+
+export type ProcessReference = Omit<ProcessRecord, "program"> & Readonly<{
+
+ program: ReturnType<Process["program"]["record"]>
+}>
+
+/**
+ * An endpoint identity carried only between trusted boundaries and SDKs.
+ *
+ * The host derives both fields from its authoritative Process registry.
+ * Program code can therefore receive a real Endpoint handle without being
+ * able to forge the sender or destination attached to application traffic.
+ */
+export interface EndpointReference {
+
+ readonly kind: Half
+
+ readonly process: ProcessReference
+}
+
+export function processReference(process: Process): ProcessReference {
+
+ return { ...process.record(), program: process.program.record() }
+}
+
+export function endpointReference(process: Process, kind: Half): EndpointReference {
+
+ return { kind, process: processReference(process) }
+}
diff --git a/source/server/core/link-manager/auth-manager/process-manager/host-traffic.ts b/source/server/core/link-manager/auth-manager/process-manager/host-traffic.ts
new file mode 100644
index 0000000..5e91fc8
--- /dev/null
+++ b/source/server/core/link-manager/auth-manager/process-manager/host-traffic.ts
@@ -0,0 +1,44 @@
+import TheLink from "@libs/the-link/the-link"
+
+/** Host announcements routed only into Process boundaries that requested them. */
+export default class HostTraffic extends TheLink {
+
+ public async emit(event: string, publicSubject: string, scopedSubject: string, ...values: unknown[]) {
+
+ const delivery = {}
+
+ const deliveries = [
+ this.$inbound.publish(this.event(null, event), delivery, publicSubject, ...values),
+ this.$inbound.publish(this.event(scopedSubject, event), delivery, scopedSubject, ...values)
+ ]
+
+ await Promise.all(deliveries)
+ }
+
+ /** Emits a Process-scoped fact without also exposing it as a host event. */
+ public emitSubject(event: string, subject: string, ...values: unknown[]) {
+
+ return this.$inbound.publish(this.event(subject, event), {}, subject, ...values)
+ }
+
+ public observe(event: string | null, subject: string | null, subscriber: Subscriber) {
+
+ const prefix = this.prefix(subject)
+
+ if (event !== null) return this.$inbound.subscribe(prefix + encodeURIComponent(event), (delivery, ...values) => subscriber(delivery as object, event, ...values))
+
+ return this.$inbound.forwardTo((word, delivery, ...values) => subscriber(delivery as object, decodeURIComponent(word), ...values), prefix)
+ }
+
+ private prefix(subject: string | null) {
+
+ return subject === null ? "all/" : `subject/${encodeURIComponent(subject)}/`
+ }
+
+ private event(subject: string | null, event: string) {
+
+ return this.prefix(subject) + encodeURIComponent(event)
+ }
+}
+
+type Subscriber = (delivery: object, event: string, ...values: unknown[]) => unknown
diff --git a/source/server/core/link-manager/auth-manager/process-manager/process-manager.ts b/source/server/core/link-manager/auth-manager/process-manager/process-manager.ts
new file mode 100644
index 0000000..94912c3
--- /dev/null
+++ b/source/server/core/link-manager/auth-manager/process-manager/process-manager.ts
@@ -0,0 +1,2161 @@
+import { Connect, Subscribe } from "@libs/the-link/decorators/escript"
+import { serveLimit } from "@server/core/served-file-manager"
+import { ChildProcess } from "node:child_process"
+import { type Launch, type LaunchClient, type Options } from "../program-manager/program-manager"
+import Program from "../program-manager/program"
+import { Layer } from "../program-manager/config"
+import Window, { Position, Size } from "./window"
+import TheLink from "@libs/the-link/the-link"
+import { Transmitted } from "@libs/superjson"
+import AuthManager from "../auth-manager"
+import { signalProcessTree } from "@libs/process-tree"
+import Process, { type HostedProcess } from "./process"
+import ServerProcessBoundary from "./server-process-boundary"
+import ProcessTraffic, { type Half, type TrafficKind } from "./process-traffic"
+import ClientProcessForwarder from "./client-process-forwarder"
+import HostTraffic from "./host-traffic"
+import { failed, succeeded, type Outcome } from "@server/core/outcome"
+import { endpointReference, processReference } from "./endpoint-reference"
+import EndpointEvents from "./endpoint-events"
+import { isPermissionName, type PermissionName, type WindowLayer } from "@phreshos/core"
+
+/**
+ * The core's processes: the wire and the collection. Each process owns
+ * itself — its endpoint incarnations and serialisation — and this manager
+ * routes: it holds them by identity, carries operations in from connections,
+ * and broadcasts what changed.
+ *
+ * The channel speaks three envelopes named by route. end-end is relayed
+ * to the program's other end untouched; end-host terminates in the
+ * vocabulary below, the finite set of words a program may address to its
+ * environment; host-end is what this side says of its own accord.
+ */
+
+export default class ProcessManager extends TheLink {
+
+ public readonly authManager: AuthManager
+
+ public readonly processes = new Map<string, Process>()
+
+ // Application traffic is an event route, not manager state. Each Process
+ // boundary subscribes directly and owns the resulting cleanup.
+ private readonly traffic = new ProcessTraffic()
+
+ // Destinationless events remain separate from directed traffic. A source
+ // Endpoint speaks once; only boundaries following that Endpoint join.
+ private readonly endpointEvents = new EndpointEvents()
+
+ // Host facts use their own the-link routes. A server boundary joins only
+ // the event and subject routes its endpoint explicitly requested.
+ private readonly hostTraffic = new HostTraffic()
+
+ // The remote half of each desktop boundary lease. It owns only that
+ // document's forwarding interests and disappears with the lease.
+ private readonly clientForwarders = new Map<string, ClientProcessForwarder>()
+
+ // Endpoint transitions for one Process are serialized. State is changed in
+ // one place, so two simultaneous stop requests cannot both believe the
+ // other endpoint will preserve the Process lifetime.
+ private readonly transitions = new Map<string, Promise<void>>()
+
+ private readonly stoppingServers = new Set<ServerProcessBoundary>()
+
+ private highest = 0
+
+ // Questions name their waiting endpoint in their correlation address.
+ // The host reads that address only to route the answer. The source Process
+ // boundary retains the cancellation forwarding for its lifetime, but no
+ // host owns the Promise, timer, callback, or result.
+ public constructor(authManager: AuthManager) {
+
+ super()
+
+ this.authManager = authManager
+
+ this.connectTo(this.authManager, "/process")
+
+ }
+
+ private find(identity: string) {
+
+ const process = this.processes.get(identity)
+
+ if (!process) throw new Error("The host does not know this process")
+
+ return process
+ }
+
+ /** Resolve an SDK handle without ever letting an old handle retarget a replacement. */
+ private heldProcess(value: unknown, fallback?: Process) {
+
+ if (value === undefined || value === null) {
+
+ if (fallback) return fallback
+
+ throw new Error("A Process handle is required")
+ }
+
+ if (!isHandleAddress(value)) throw new Error("The boundary returned an invalid Process handle")
+
+ const process = this.processes.get(value.identity)
+
+ if (!process || process.reference !== value.reference) throw new Error("The Process represented by this handle does not exist")
+
+ return process
+ }
+
+ /** Resolve the exact runtime Program entity addressed by an SDK handle. */
+ private heldProgram(value: unknown, fallback?: Program) {
+
+ if (value === undefined || value === null) {
+
+ if (fallback) return fallback
+
+ throw new Error("A Program handle is required")
+ }
+
+ if (!isHandleAddress(value)) throw new Error("The boundary returned an invalid Program handle")
+
+ const program = this.authManager.programManager.reach(value.identity)
+
+ if (!program || program.reference !== value.reference) throw new Error("The Program represented by this handle does not exist")
+
+ return program
+ }
+
+ private heldWindow(value: unknown, fallback: Process) {
+
+ const process = this.heldProcess(value, fallback)
+
+ const window = process.client?.window
+
+ if (!window) throw new Error("This process has no live client endpoint")
+
+ return { process, window }
+ }
+
+ private windowOf(identity: string) {
+
+ const window = this.find(identity).client?.window
+
+ if (!window) throw new Error("This process has no live client endpoint")
+
+ return window
+ }
+
+ private mutableWindowOf(identity: string) {
+
+ const window = this.windowOf(identity)
+
+ if (window.layer === "wallpaper") throw new Error("A wallpaper Window is managed by the system")
+
+ return window
+ }
+
+ private surfaceWindowOf(identity: string) {
+
+ const window = this.windowOf(identity)
+
+ if (window.layer === "window") throw new Error("A window-layer Window cannot own a Surface")
+
+ if (window.layer === "wallpaper") throw new Error("A wallpaper-layer Window cannot own a Surface")
+
+ return window
+ }
+
+ // A server runtime is a ProcessLink. Speaking through its outbound
+ // tunnel keeps IPC as a transport detail and leaves a stopped child as
+ // fire-and-forget: there is no receiver to promise once it has gone.
+ private say(server: ServerProcessBoundary | null | undefined, event: string, ...values: unknown[]) {
+
+ return server?.deliver(event, ...values).catch(() => undefined) ?? Promise.resolve()
+ }
+
+ private clientOwnerKey(connection: string, pane: string) {
+
+ return `${connection}:${pane}`
+ }
+
+ private observation(target: Process, half: string): { half: Half } | { error: string } {
+
+ if (half === "server") return target.program.server ? { half: "server" } : { error: "This program declared no server half" }
+
+ if (half === "client") return target.program.client ? { half: "client" } : { error: "This program declared no client half" }
+
+ return { error: `A process has no "${half}" end` }
+ }
+
+ private observeServer(owner: Process, subscription: string, target: Process, half: string, kind: TrafficKind, event: string | null, reportImpossible: boolean) {
+
+ if (!owner.server) return
+
+ const observation = this.observation(target, half)
+
+ if ("error" in observation) {
+
+ if (reportImpossible) owner.server.impossible(subscription, observation.error)
+
+ return
+ }
+
+ owner.server.observe(this.traffic, subscription, target.reference, observation.half, kind, event, reportImpossible)
+ }
+
+ private unobserveServer(owner: Process, subscription: string) {
+
+ owner.server?.unobserve(subscription)
+ }
+
+ private followServer(owner: Process, subscription: string, target: Process, half: string, event: string | null, reportImpossible: boolean) {
+
+ if (!owner.server) return
+
+ const observation = this.observation(target, half)
+
+ if ("error" in observation) {
+
+ if (reportImpossible) owner.server.impossible(subscription, observation.error)
+
+ return
+ }
+
+ owner.server.follow(this.endpointEvents, subscription, target.reference, observation.half, event, reportImpossible)
+ }
+
+ private unfollowServer(owner: Process, subscription: string) {
+
+ owner.server?.unfollow(subscription)
+ }
+
+ private ownClient(connection: string, pane: string, owner: string) {
+
+ if (!this.authManager.linkManager.connections.has(connection) || !this.processes.get(pane)?.client) return
+
+ const key = this.clientOwnerKey(connection, pane)
+
+ const current = this.clientForwarders.get(key)
+
+ if (current?.owner === owner) return
+
+ current?.release()
+
+ this.clientForwarders.set(key, new ClientProcessForwarder(connection, pane, owner, this.authManager, this.traffic, this.endpointEvents, values => this.clientVisibleTraffic(pane, values)))
+ }
+
+ private releaseClient(connection: string, pane: string, owner: string) {
+
+ const key = this.clientOwnerKey(connection, pane)
+
+ const current = this.clientForwarders.get(key)
+
+ if (current?.owner !== owner) return
+
+ current.release()
+
+ this.clientForwarders.delete(key)
+ }
+
+ private registerClientObservation(connection: string, pane: string, owner: string, subscription: string, target: unknown, half: string, kind: TrafficKind, event: string | null, reportImpossible: boolean) {
+
+ const boundary = this.clientForwarders.get(this.clientOwnerKey(connection, pane))
+
+ if (boundary?.owner !== owner) return
+
+ let observed: Process
+
+ try {
+
+ observed = this.heldProcess(target)
+
+ if (observed.program !== this.find(pane).program) throw new Error("The desktop does not know this process")
+ }
+
+ catch (error) {
+
+ if (reportImpossible) boundary.impossible(subscription, error instanceof Error ? error.message : "The desktop does not know this process")
+
+ return
+ }
+
+ const observation = this.observation(observed, half)
+
+ if ("error" in observation) {
+
+ if (reportImpossible) boundary.impossible(subscription, observation.error)
+
+ return
+ }
+
+ boundary.observe(subscription, observed.reference, observation.half, kind, event, reportImpossible)
+ }
+
+ /** Remove foreign Endpoint identities before observed traffic reaches a Client boundary. */
+ private clientVisibleTraffic(pane: string, values: unknown[]) {
+
+ const viewer = this.processes.get(pane)
+
+ const index = values.length - 1
+
+ const message = values[index]
+
+ if (!viewer || index < 0 || typeof message !== "object" || message === null || !("to" in message)) return values
+
+ const to = message.to
+
+ if (typeof to !== "object" || to === null || !("process" in to)) return values
+
+ const reference = to as ReturnType<typeof endpointReference>
+
+ if (reference.process.program.identity === viewer.program.identity) return values
+
+ const masked = [...values]
+
+ masked[index] = { ...message, to: null }
+
+ return masked
+ }
+
+ private removeClientObservation(connection: string, pane: string, owner: string, subscription: string) {
+
+ const boundary = this.clientForwarders.get(this.clientOwnerKey(connection, pane))
+
+ if (boundary?.owner === owner) boundary.unobserve(subscription)
+ }
+
+ private registerClientFollow(connection: string, pane: string, owner: string, subscription: string, target: unknown, half: string, event: string | null, reportImpossible: boolean) {
+
+ const boundary = this.clientForwarders.get(this.clientOwnerKey(connection, pane))
+
+ if (boundary?.owner !== owner) return
+
+ let observed: Process
+
+ try {
+
+ observed = this.heldProcess(target)
+
+ if (observed.program !== this.find(pane).program) throw new Error("The desktop does not know this process")
+ }
+
+ catch (error) {
+
+ if (reportImpossible) boundary.impossible(subscription, error instanceof Error ? error.message : "The desktop does not know this process")
+
+ return
+ }
+
+ const observation = this.observation(observed, half)
+
+ if ("error" in observation) {
+
+ if (reportImpossible) boundary.impossible(subscription, observation.error)
+
+ return
+ }
+
+ boundary.follow(subscription, observed.reference, observation.half, event, reportImpossible)
+ }
+
+ private removeClientFollow(connection: string, pane: string, owner: string, subscription: string) {
+
+ const boundary = this.clientForwarders.get(this.clientOwnerKey(connection, pane))
+
+ if (boundary?.owner === owner) boundary.unfollow(subscription)
+ }
+
+ private registerClientSubscription(connection: string, pane: string, owner: string, subscription: string, event: string | null) {
+
+ const boundary = this.clientForwarders.get(this.clientOwnerKey(connection, pane))
+
+ if (boundary?.owner === owner) boundary.subscribe(subscription, event)
+ }
+
+ private removeClientSubscription(connection: string, pane: string, owner: string, subscription: string) {
+
+ const boundary = this.clientForwarders.get(this.clientOwnerKey(connection, pane))
+
+ if (boundary?.owner === owner) boundary.unsubscribe(subscription)
+ }
+
+ private retainClientQuestion(connection: string, source: string, question: string, target: string) {
+
+ const address = addressed(question)
+
+ if (address?.half !== "client" || address.identity !== source) throw new Error("A client question must return to its own Process boundary")
+
+ const boundary = this.clientForwarders.get(this.clientOwnerKey(connection, source))
+
+ if (!boundary) throw new Error("The desktop does not own this client Process boundary")
+
+ const server = this.processes.get(target)?.server
+
+ if (!server) return false
+
+ boundary.retain(question, () => server.forget(question))
+
+ return true
+ }
+
+ private answerClientQuestion(source: string, question: string, values: unknown[]) {
+
+ for (const boundary of this.clientForwarders.values()) {
+
+ if (boundary.pane === source && boundary.answer(question, values)) return
+ }
+ }
+
+ private rejectClientQuestion(connection: string, pane: string, values: unknown[], reason: string) {
+
+ if (values[0] !== "wait" || typeof values[1] !== "string" || typeof values[2] !== "string" || typeof values[3] !== "string") return
+
+ const answer = ["answer", values[1], values[2], values[3], failed(new Error(reason))]
+
+ this.authManager.publishToConnection(connection, "/process/end-end", pane, JSON.stringify(answer)).catch(() => undefined)
+ }
+
+ public releaseConnection(connection: string) {
+
+ for (const [key, boundary] of this.clientForwarders) {
+
+ if (!key.startsWith(`${connection}:`)) continue
+
+ boundary.release()
+
+ this.clientForwarders.delete(key)
+ }
+ }
+
+ // Raw boundary delivery. Application publications and questions are
+ // shaped before they reach this point so the receiving SDK sees the
+ // source Endpoint supplied by the host rather than by Program code.
+ private deliver(identity: string, half: "server" | "client", values: unknown[]) {
+
+ const process = this.processes.get(identity)
+
+ if (!process) return Promise.resolve()
+
+ if (half === "server") {
+
+ if (!process.server) return Promise.resolve()
+
+ return this.say(process.server, "end-end", ...values)
+ }
+
+ if (!process.client) return Promise.resolve()
+
+ return Promise.all([...this.clientForwarders.values()]
+ .filter(boundary => boundary.pane === identity)
+ .map(boundary => boundary.forward(values))).then(() => undefined)
+ }
+
+ private publish(source: string, sourceHalf: "server" | "client", target: string, targetHalf: "server" | "client", values: unknown[]) {
+
+ const event = values[0]
+
+ if (typeof event !== "string") return Promise.resolve()
+
+ const sourceProcess = this.processes.get(source)
+
+ const targetProcess = this.processes.get(target)
+
+ if (!sourceProcess || !targetProcess) return Promise.resolve()
+
+ const payload = values[1]
+
+ const received = {
+
+ from: targetHalf === "client" && sourceProcess.program !== targetProcess.program
+ ? null
+ : endpointReference(sourceProcess, sourceHalf),
+
+ payload
+ }
+
+ const observed = this.traffic.emit(sourceProcess.reference, sourceHalf, "publish", event, {
+
+ to: endpointReference(targetProcess, targetHalf),
+
+ payload
+ })
+
+ return Promise.all([observed, this.deliver(target, targetHalf, [event, received])]).then(() => undefined)
+ }
+
+ // Answers travel to the address written by the waiting endpoint. The host
+ // reads that private address only to choose the return boundary; observers
+ // receive the separate public id and can correlate it themselves.
+ private returnAnswer(answerer: Process | null, values: unknown[]) {
+
+ if (values[0] !== "answer" || typeof values[1] !== "string" || typeof values[2] !== "string" || typeof values[3] !== "string") return false
+
+ const back = addressed(values[1])
+
+ if (!back) return false
+
+ const process = this.processes.get(back.identity)
+
+ const outcome = values[4] as Outcome
+
+ if (answerer && process) {
+
+ this.traffic.emit(answerer.reference, "server", "answer", values[3], values[2], {
+
+ to: endpointReference(process, back.half),
+
+ outcome
+ }).catch(() => undefined)
+ }
+
+ if (back.half === "server") {
+
+ if (!process?.server) return true
+
+ this.say(process.server, "end-end", ...values)
+
+ return true
+ }
+
+ this.answerClientQuestion(back.identity, values[1], values)
+
+ return true
+ }
+
+ private rejectQuestion(values: unknown[], reason: string) {
+
+ if (values[0] !== "wait" || typeof values[1] !== "string" || typeof values[2] !== "string" || typeof values[3] !== "string") return
+
+ this.returnAnswer(null, ["answer", values[1], values[2], values[3], failed(new Error(reason))])
+ }
+
+ private transition(process: Process, change: () => Promise<void> | void) {
+
+ const before = this.transitions.get(process.identity) ?? Promise.resolve()
+
+ const next = before.catch(() => undefined).then(async () => {
+
+ if (this.processes.get(process.identity) !== process) throw new Error("The process no longer exists")
+
+ await change()
+ })
+
+ this.transitions.set(process.identity, next)
+
+ next.finally(() => {
+
+ if (this.transitions.get(process.identity) === next) this.transitions.delete(process.identity)
+ }).catch(() => undefined)
+
+ return next
+ }
+
+ private bindServer(process: Process, server: ServerProcessBoundary) {
+
+ server.$inbound.forwardTo((event, ...values) => {
+
+ if (process.server !== server || event === "boundary") return
+
+ if (event === "end-end") {
+
+ if (values[0] === "answer" && typeof values[1] === "string") server.answered(values[1])
+
+ if (this.returnAnswer(process, values)) return
+
+ this.publish(process.identity, "server", process.identity, "client", values).catch(() => undefined)
+
+ return
+ }
+
+ if (event === "end-host") {
+
+ if (values[0] === "wait" && typeof values[1] === "string") {
+
+ this.endHostWait(process, values[1], values.slice(2)).catch(() => undefined)
+
+ return
+ }
+
+ this.endHost(process, values).catch(() => undefined)
+ }
+ })
+
+ server.$inbound.subscribe("boundary-ready", (ready: unknown) => {
+
+ if (ready !== true || process.server !== server) return
+
+ process.serverBecameReady(server)
+
+ this.$outbound.publish("/server-ready", process.identity).catch(() => undefined)
+ })
+ }
+
+ private async endpointEvent(event: EndpointEvent, process: Process, endpoint: "server" | "client") {
+
+ const record = processReference(process)
+
+ await Promise.all([
+
+ this.announce(event, process.program.identity, process.program.reference, record, endpoint),
+
+ this.hostTraffic.emitSubject(event, process.reference, record, endpoint)
+ ])
+ }
+
+ private async serverStarted(process: Process) {
+
+ await this.$outbound.publish("/server-start", process.identity, process.hosted())
+
+ // Readiness can arrive while the start announcement is crossing to
+ // the desktop. Repeating the current fact after that awaited crossing
+ // guarantees the desktop never applies ready before it knows the new
+ // incarnation exists.
+ if (process.server?.ready) await this.$outbound.publish("/server-ready", process.identity)
+
+ await this.endpointEvent("endpointStart", process, "server")
+ }
+
+ private async serverEnded(process: Process, boundary: ServerProcessBoundary, code: number | null, signal: NodeJS.Signals | null) {
+
+ const explicitlyStopped = this.stoppingServers.delete(boundary)
+
+ const finish = async () => {
+
+ if (!process.serverStopped(boundary, code, signal)) return
+
+ boundary.release()
+
+ await this.$outbound.publish("/server-stop", process.identity, process.hosted(), code, signal)
+
+ await this.endpointEvent("endpointStop", process, "server")
+
+ // A server crash invalidates the complete execution. Only the
+ // explicit server.stop() road may intentionally leave the client
+ // state alive without its server counterpart.
+ if (!explicitlyStopped) {
+
+ await this.authManager.linkManager.application.dialogManager.serverCrashed(process, code, signal)
+
+ if (process.client) await this.deactivateClient(process)
+ }
+
+ if (!process.live) await this.remove(process.identity, code, signal)
+ }
+
+ if (explicitlyStopped) await finish()
+
+ else await this.transition(process, finish).catch(() => undefined)
+ }
+
+ private activateServer(process: Process, child: ChildProcess) {
+
+ const server = process.startServer(child,
+
+ (boundary, code, signal) => this.serverEnded(process, boundary, code, signal),
+
+ (values, reason) => this.rejectQuestion(values, reason),
+
+ this.authManager.linkManager.theme.tunnel
+ )
+
+ this.bindServer(process, server)
+
+ return server
+ }
+
+ private window(program: Program, shape: Shape) {
+
+ const shown = { title: program.title, url: program.clientRoot, layer: shape.layer, location: shape.location }
+
+ return new Window(shown, shape.position, shape.size, ++this.highest, shape.minimize)
+ }
+
+ public async register(identity: string, name: string | null, program: Program, options: Options, child: ChildProcess | null, client: boolean, shape: Shape | null, parent: Process | null, configure?: (process: Process) => void) {
+
+ if (this.processes.has(identity)) {
+
+ if (child) signalProcessTree(child, "SIGKILL")
+
+ throw new Error("The host already knows this process identity")
+ }
+
+ if (name !== null && [...this.processes.values()].some(process => process.program === program && process.name === name)) {
+
+ if (child) signalProcessTree(child, "SIGKILL")
+
+ throw new Error("This program already has a process with that name")
+ }
+
+ // Who had focus before this one opened, in the layer it is
+ // opening into. A window is born on top of its own layer and
+ // takes focus from whoever held it there; the other two layers
+ // do not hear about it.
+ const front = shape && this.front(shape.layer)
+
+ const window = shape ? this.window(program, shape) : null
+
+ const process = new Process(identity, name, program, options, parent, this.hostTraffic)
+
+ this.processes.set(identity, process)
+
+ process.ownExit(() => this.exitProcess(identity))
+
+ process.onExit((code, signal) => { this.remove(identity, code, signal).catch(() => undefined) })
+
+ configure?.(process)
+
+ // Initial activation is one endpoint transition too. A server that
+ // exits immediately is queued behind it, preserving the only coherent
+ // order: Process creation, endpoint start, endpoint stop, Process exit.
+ await this.transition(process, async () => {
+
+ if (client && window) process.startClient(window)
+
+ if (child) this.activateServer(process, child)
+
+ // The subject first, which is what scopes a listener without
+ // anything being checked: a kit's `Events` refuses a value whose
+ // first item is not the subject it was built for, so a program's
+ // listener hears only its own program's news by the shape of the
+ // message rather than by a rule somewhere reading it.
+ //
+ // An unscoped listener — `host` — is built for no subject and so
+ // receives the subject as its first value.
+ await this.announce("processCreate", program.identity, program.reference, processReference(process))
+
+ await this.$outbound.publish("/created", process.hosted())
+
+ if (window) this.settleFront(window.layer, front)
+
+ if (process.server) await this.serverStarted(process)
+
+ if (process.client) {
+
+ await this.$outbound.publish("/client-start", process.identity, process.hosted())
+
+ await this.endpointEvent("endpointStart", process, "client")
+ }
+ })
+
+ return process
+ }
+
+ public async remove(identity: string, code: number | null = 0, signal: NodeJS.Signals | null = null) {
+
+ const process = this.processes.get(identity)
+
+ if (!process) return
+
+ // Who had focus while this one was still here, in its own layer.
+ // A window closing hands it to whatever is left showing
+ // underneath *it* — a layer emptying hands nothing across.
+ const layer = process.client?.window.layer ?? null
+
+ const front = layer && this.front(layer)
+
+ if (!this.processes.delete(identity)) return
+
+ process.server?.release("The process ended before answering")
+
+ for (const [key, boundary] of this.clientForwarders) {
+
+ if (boundary.pane !== identity) continue
+
+ boundary.release()
+
+ this.clientForwarders.delete(key)
+ }
+
+ // Dropping the record is an ending, and for a program with no
+ // server half it is the only one there will ever be.
+ process.ended(code, signal)
+
+ // The subject leads so that narrowing is the shape of the
+ // message, and what follows is the thing the event is about —
+ // the process, whole, not an identity a listener would have to look
+ // up. It is already gone, which is what `exited()` answers and
+ // why holding it is legitimate.
+ await this.announce("processExit", process.program.identity, process.program.reference, processReference(process), code, signal)
+
+ // The same ending, said to whoever holds this one process rather
+ // than to whoever watches the program. A launcher wants the
+ // second; a program managing its instances wants the first.
+ await this.hostTraffic.emitSubject("exit", process.reference, code, signal)
+
+ // The window that had it is gone, so nobody is told they lost
+ // it — only whoever inherits it is told they have it.
+ if (layer) this.settleFront(layer, front)
+
+ // Whose it was, said rather than looked up. A session holds the
+ // record too and drops it on this same event, so anything that
+ // needed to know the program would be racing the handler that
+ // removes it — and which of them ran first would decide whether
+ // the answer existed.
+ // And when it started, because the record is gone by the time a
+ // session reads this and that is the one thing an ending cannot
+ // recover — a listener handed a process must be handed the whole
+ // of one, or the shape a handle promises is not the shape it has.
+ await this.$outbound.publish("/exited", process.hosted(), code, signal)
+
+ await this.traffic.end(process.reference, "The process ended — no further events are possible")
+
+ await this.endpointEvents.end(process.reference, "The process ended — no further events are possible")
+
+ this.transitions.delete(identity)
+ }
+
+ public async startServer(identity: string) {
+
+ const process = this.find(identity)
+
+ await this.transition(process, async () => {
+
+ if (!process.program.server) throw new Error("This program declared no server half")
+
+ if (process.server) throw new Error("The server endpoint is already running")
+
+ await process.program.validate()
+
+ const child = this.authManager.programManager.spawnServer(process.program)
+
+ try { this.activateServer(process, child) }
+
+ catch (error) {
+
+ signalProcessTree(child, "SIGKILL")
+
+ throw error
+ }
+
+ await this.serverStarted(process)
+ })
+
+ return identity
+ }
+
+ public async stopServer(identity: string) {
+
+ const process = this.find(identity)
+
+ await this.transition(process, async () => {
+
+ if (!process.server) throw new Error("The server endpoint is already stopped")
+
+ if (!process.client) throw new Error("The final live endpoint cannot be stopped; exit the Process instead")
+
+ const stopping = process.server
+
+ this.stoppingServers.add(stopping)
+
+ stopping.stop()
+
+ await stopping.finished
+ })
+
+ return identity
+ }
+
+ public async startClient(identity: string, overrides?: LaunchClient) {
+
+ const process = this.find(identity)
+
+ await this.transition(process, async () => {
+
+ if (!process.program.client) throw new Error("This program declared no client half")
+
+ if (process.client) throw new Error("The client endpoint is already running")
+
+ await process.program.validate()
+
+ const shape = this.authManager.programManager.clientShape(process.program, overrides)
+
+ const window = this.window(process.program, shape)
+
+ const before = this.front(window.layer)
+
+ process.startClient(window)
+
+ await this.$outbound.publish("/client-start", process.identity, process.hosted())
+
+ this.settleFront(window.layer, before)
+
+ await this.endpointEvent("endpointStart", process, "client")
+ })
+
+ return identity
+ }
+
+ public async stopClient(identity: string) {
+
+ const process = this.find(identity)
+
+ await this.transition(process, async () => {
+
+ if (!process.client) throw new Error("The client endpoint is already stopped")
+
+ if (process.client.window.layer === "wallpaper") throw new Error("A wallpaper Client cannot be stopped; exit the Process instead")
+
+ if (!process.server) throw new Error("The final live endpoint cannot be stopped; exit the Process instead")
+
+ await this.deactivateClient(process)
+ })
+
+ return identity
+ }
+
+ private async deactivateClient(process: Process) {
+
+ const layer = process.client?.window.layer ?? null
+
+ const before = layer ? this.front(layer) : null
+
+ process.stopClient()
+
+ for (const [key, boundary] of this.clientForwarders) {
+
+ if (boundary.pane !== process.identity) continue
+
+ boundary.release()
+
+ this.clientForwarders.delete(key)
+ }
+
+ await this.$outbound.publish("/client-stop", process.identity, process.hosted())
+
+ if (layer) this.settleFront(layer, before)
+
+ await this.endpointEvent("endpointStop", process, "client")
+ }
+
+ private async exitProcess(identity: string) {
+
+ const process = this.find(identity)
+
+ await this.transition(process, async () => {
+
+ const server = process.server
+
+ // Classify and stop the child before awaiting any other teardown.
+ // Otherwise a natural child exit during an awaited client
+ // announcement could queue behind this transition while this
+ // transition waits for that same child's completion.
+ if (server) {
+
+ this.stoppingServers.add(server)
+
+ server.stop()
+
+ await server.finished
+ }
+
+ if (process.client) await this.deactivateClient(process)
+
+ if (this.processes.get(identity) === process) await this.remove(identity)
+ })
+
+ return identity
+ }
+
+ // Every instance of one program, ended. The asker goes last when it
+ // is one of them: killed first, it would never issue the rest.
+ //
+ // One implementation for both roads — a process asks over its
+ // channel, a pane over the link — because two that agreed today
+ // would be two that could stop agreeing.
+ @Connect("/exit-all")
+ public async exitAll(program: string, asker: string | null = null) {
+
+ const owner = this.authManager.programManager.reachOrRefuse(program)
+
+ const ended = [...this.processes.values()].filter(entry => entry.program === owner).map(entry => entry.identity)
+
+ for (const identity of [...ended.filter(identity => identity !== asker), ...ended.filter(identity => identity === asker)]) await this.stop(identity)
+
+ return ended
+ }
+
+ // A desktop supplies the publishing pane separately from the destination.
+ // The pane comes from its structural frame gate rather than application
+ // data, so a client cannot attribute its publication to another Process.
+ @Connect("/send")
+ public async publishClient(source: string, identity: string, which: string, values: unknown[]) {
+
+ if (which !== "server" && which !== "client") throw new Error(`A process has no "${which}" end`)
+
+ if (!this.find(source).client) throw new Error("The publishing process has no live client endpoint")
+
+ await this.publish(source, "client", identity, which, values)
+ }
+
+ /** A Client emits from the structurally identified pane, never a claimed source. */
+ @Connect("/emit")
+ public async emitClient(source: string, event: string, payload: unknown) {
+
+ if (!this.find(source).client) return
+
+ await this.endpointEvents.emit(this.find(source).reference, "client", event, payload)
+ }
+
+ @Subscribe("/frame/own")
+ protected ownClientFrame(connection: string, pane: string, owner: string) {
+
+ this.ownClient(connection, pane, owner)
+ }
+
+ @Subscribe("/frame/release")
+ protected releaseClientFrame(connection: string, pane: string, owner: string) {
+
+ this.releaseClient(connection, pane, owner)
+ }
+
+ @Subscribe("/frame/subscribe")
+ protected subscribeClientFrame(connection: string, pane: string, owner: string, subscription: string, kind: unknown, event: unknown) {
+
+ if (kind !== "publish" || event !== null && typeof event !== "string") return
+
+ this.registerClientSubscription(connection, pane, owner, subscription, event)
+ }
+
+ @Subscribe("/frame/unsubscribe")
+ protected unsubscribeClientFrame(connection: string, pane: string, owner: string, subscription: string) {
+
+ this.removeClientSubscription(connection, pane, owner, subscription)
+ }
+
+ @Subscribe("/frame/observe")
+ protected observeClientFrame(connection: string, pane: string, owner: string, subscription: string, target: unknown, half: string, kind: unknown, event: unknown, reportImpossible: unknown) {
+
+ if (!isTrafficKind(kind)) return
+
+ if (event !== null && typeof event !== "string") return
+
+ this.registerClientObservation(connection, pane, owner, subscription, target, half, kind, event, reportImpossible === true)
+ }
+
+ @Subscribe("/frame/unobserve")
+ protected unobserveClientFrame(connection: string, pane: string, owner: string, subscription: string) {
+
+ this.removeClientObservation(connection, pane, owner, subscription)
+ }
+
+ @Subscribe("/frame/follow")
+ protected followClientFrame(connection: string, pane: string, owner: string, subscription: string, target: unknown, half: string, event: unknown, reportImpossible: unknown) {
+
+ if (event !== null && typeof event !== "string") return
+
+ this.registerClientFollow(connection, pane, owner, subscription, target, half, event, reportImpossible === true)
+ }
+
+ @Subscribe("/frame/unfollow")
+ protected unfollowClientFrame(connection: string, pane: string, owner: string, subscription: string) {
+
+ this.removeClientFollow(connection, pane, owner, subscription)
+ }
+
+ @Subscribe("/frame/log")
+ protected logClientFrame(_connection: string, pane: string, kind: unknown, content: unknown) {
+
+ if (typeof kind !== "string" || typeof content !== "string") return
+
+ const process = this.processes.get(pane)
+
+ if (!process?.client) return
+
+ this.authManager.programManager.record(process.program, process.identity, "client", kind, content)
+ }
+
+ // Host facts enter only the Process boundaries whose endpoint subscriptions
+ // established a matching the-link route.
+ public async announce(event: string, publicSubject: string, scopedSubject: string, ...values: unknown[]) {
+
+ await this.hostTraffic.emit(event, publicSubject, scopedSubject, ...values)
+ }
+
+ /** Reads the effective permission decision for one live Client Process. */
+ public permissionGranted(identity: string, permission: PermissionName): boolean | null {
+
+ const process = this.find(identity)
+
+ if (!process.client) throw new Error("This process has no live client endpoint")
+
+ if (process.permissions.has(permission)) return true
+
+ return this.authManager.programManager.permission(process.program, permission) ?? null
+ }
+
+ /** Creates at most one user-facing permission request for a Client Process. */
+ public async requestPermission(identity: string, request: string, permission: PermissionName) {
+
+ const process = this.find(identity)
+
+ if (!process.client) throw new Error("This process has no live client endpoint")
+
+ const known = this.permissionGranted(identity, permission)
+
+ if (known !== null) return known
+
+ const choice = await this.authManager.dialogManager.requestPermission(process, request, permission)
+
+ if (choice === "process") {
+
+ if (this.processes.get(identity) !== process || !process.client) return null
+
+ process.permissions.add(permission)
+
+ await this.permissionChanged(process.program, permission)
+
+ return true
+ }
+
+ if (choice === "always") {
+
+ if (this.processes.get(identity) !== process || !process.client) return null
+
+ this.authManager.programManager.setPermission(process.program, permission, true)
+
+ return true
+ }
+
+ return choice
+ }
+
+ public async cancelPermission(identity: string, request: string) {
+
+ const process = this.processes.get(identity)
+
+ if (!process) return
+
+ await this.authManager.dialogManager.cancelPermission(request, process.reference)
+ }
+
+ /** Publishes one effective-decision change to every desktop counterpart. */
+ public async permissionChanged(program: Program, permission: PermissionName) {
+
+ for (const process of this.processes.values()) {
+
+ if (process.program !== program || !process.client) continue
+
+ await this.$outbound.publish("/permission", process.identity, permission, this.permissionGranted(process.identity, permission))
+ }
+ }
+
+ // A window's news, said once and heard by both kinds of half.
+ //
+ // A server half hears it over its own channel. A client half is a
+ // frame in a session, so the same words go out to the sessions and
+ // the desktop posts them into the frame — relayed verbatim rather
+ // than worked out again there. Coming to the front is a transition,
+ // and a second place deciding when they happened is a second place
+ // that can decide differently.
+ private said(identity: string, event: string, value: unknown) {
+
+ const process = this.processes.get(identity)
+
+ if (process?.client) this.hostTraffic.emitSubject(event, process.reference, value).catch(() => undefined)
+
+ this.$outbound.publish("/said", identity, event, value).catch(() => undefined)
+ }
+
+ // The host's vocabulary — the words a program may address to its
+ // environment. Predefined and finite: the kits' named operations
+ // compile to exactly these. Unknown words are refused, so a
+ // misspelling fails loudly instead of vanishing.
+ protected async endHost(process: Process, args: unknown[]): Promise<unknown[]> {
+
+ const [word, ...rest] = args
+
+ const programManager = this.authManager.programManager
+
+ if (word === "programs") return [[...programManager.programs.values()].filter(entry => rest[0] !== true || entry.installed)]
+
+ if (word === "program") {
+
+ const identity = typeof rest[0] === "string" ? rest[0] : process.program.identity
+
+ return [programManager.find(identity)]
+ }
+
+ if (word === "api-docs") {
+
+ return [this.heldProgram(rest[0], process.program).apiDocs()]
+ }
+
+ if (word === "icon") {
+
+ return [await programManager.icon(this.heldProgram(rest[0], process.program).identity, rest[1])]
+ }
+
+ if (word === "startup") {
+
+ const program = this.heldProgram(rest[0], process.program)
+
+ return [await programManager.startup(program, String(rest[1]), rest[2])]
+ }
+
+ if (word === "permissions") {
+
+ const program = this.heldProgram(rest[0], process.program)
+ const operation = rest[1]
+ const name = rest[2]
+
+ if (operation === "getAll") return [programManager.permissions(program)]
+
+ if (!isPermissionName(name)) throw new Error(`The system does not know the permission "${String(name)}"`)
+
+ if (operation === "get") return [programManager.permission(program, name)]
+
+ if (operation === "set") {
+
+ if (typeof rest[3] !== "boolean") throw new Error("A permission decision must be boolean")
+
+ programManager.setPermission(program, name, rest[3])
+
+ return []
+ }
+
+ if (operation === "delete") {
+
+ programManager.deletePermission(program, name)
+
+ return []
+ }
+
+ throw new Error(`The host does not know the permission operation "${String(operation)}"`)
+ }
+
+ // Which live process made this one through `program.createProcess()`.
+ // The child retains a handle, but the registry remains authoritative:
+ // once the parent disappears that retained handle no longer resolves.
+ if (word === "parent") {
+
+ const target = this.heldProcess(rest[0], process)
+
+ if (!target.parent) return [null]
+
+ if (this.processes.get(target.parent.identity) !== target.parent) throw new Error("The parent Process no longer exists")
+
+ return [processReference(target.parent)]
+ }
+
+ // A program brought into being by a program enters the same
+ // registry and returns the same record shape as every other
+ // program. Its installed flag begins false.
+ if (word === "create-program") {
+
+ const source = rest[0]
+
+ if (typeof source !== "string" && (typeof source !== "object" || source === null)) throw new Error("A program is created from a config or a path")
+
+ const created = await programManager.create(source as Parameters<typeof programManager.create>[0])
+
+ return [programManager.find(created.identity)]
+ }
+
+ if (word === "theme") return [this.authManager.linkManager.theme.value]
+
+ if (word === "update-theme") return [await this.authManager.updateTheme(rest[0])]
+
+ if (word === "wallpaper") {
+
+ const surface = rest[0]
+
+ const operation = rest[1]
+
+ const link = this.authManager.linkManager
+
+ if (surface === "sign-in") {
+
+ if (operation === "set") return [await link.setSignInWallpaper(rest[2])]
+
+ if (operation === "remove") return [await link.removeSignInWallpaper()]
+
+ throw new Error(`The host does not know the sign-in wallpaper operation "${String(operation)}"`)
+ }
+
+ if (surface === "desktop") {
+
+ if (operation === "set") return [await link.setDesktopWallpaper(rest[2])]
+
+ if (operation === "remove") return [await link.removeDesktopWallpaper()]
+
+ if (operation === "set-program") {
+
+ const program = this.heldProgram(rest[2])
+
+ return [await link.setDesktopWallpaperProgram(program, rest[3] as import("@phreshos/core").WallpaperLaunch)]
+ }
+
+ throw new Error(`The host does not know the desktop wallpaper operation "${String(operation)}"`)
+ }
+
+ throw new Error(`The host does not know the wallpaper surface "${String(surface)}"`)
+ }
+
+ // Laid out here, or removed from here. Both operations mutate the
+ // installed flag on the exact Program the caller addressed.
+ if (word === "install") {
+
+ const program = this.heldProgram(rest[0])
+
+ return [await programManager.install(program, process.identity)]
+ }
+
+ if (word === "fork") {
+
+ const program = this.heldProgram(rest[0])
+
+ const forked = await programManager.fork(program, String(rest[1]))
+
+ return [programManager.find(forked.identity)]
+ }
+
+ if (word === "installed") {
+
+ return [programManager.installed(this.heldProgram(rest[0]))]
+ }
+
+ if (word === "uninstall") {
+
+ const program = this.heldProgram(rest[0])
+
+ return [await programManager.uninstall(program, rest[1] === true, process.identity)]
+ }
+
+ if (word === "forget") {
+
+ const program = this.heldProgram(rest[0])
+
+ return [await programManager.forget(program, process.identity)]
+ }
+
+ if (word === "create-process") {
+
+ const program = this.heldProgram(rest[0])
+
+ // The whole record, not the identity alone: the kit builds a
+ // Process from this answer, and a record invented at the
+ // other end — identity and program, nothing else — was how every
+ // process held by its launcher had no startedAt while every
+ // other road's did.
+ return [processReference(this.find(await programManager.createProcess(program.identity, rest[1] as Launch, process)))]
+ }
+
+ // Named, only that program's instances; unnamed, every one.
+ if (word === "processes") {
+
+ const living = [...this.processes.values()]
+
+ if (rest[0] === undefined) return [living.map(processReference)]
+
+ // Resolved before it is filtered. Filtering alone answered
+ // an empty list for a program the system does not know,
+ // which reads as *running nothing* and is a different claim
+ // from *there is no such program* — every other act on one
+ // refuses, and a word that answers falsely where its
+ // neighbours refuse is worse than either.
+ const program = this.heldProgram(rest[0])
+
+ return [living.filter(entry => entry.program === program).map(processReference)]
+ }
+
+ if (word === "program-process") {
+
+ const program = this.heldProgram(rest[0])
+
+ const wanted = String(rest[1])
+
+ const identified = this.processes.get(wanted)
+
+ if (identified?.program === program) return [processReference(identified)]
+
+ const found = [...this.processes.values()].find(entry => entry.program === program && entry.name === wanted)
+
+ return [found ? processReference(found) : null]
+ }
+
+ if (word === "process") {
+
+ const target = typeof rest[0] === "string" ? this.find(rest[0]) : this.heldProcess(rest[0], process)
+
+ return [processReference(target)]
+ }
+
+ if (word === "exists") {
+
+ const target = this.heldProcess(rest[1], process)
+
+ if (rest[0] === "server") return [target.server !== null]
+
+ if (rest[0] === "client") return [target.client !== null]
+
+ throw new Error("A Process endpoint is server or client")
+ }
+
+ if (word === "start-endpoint") {
+
+ const target = this.heldProcess(rest[0], process)
+
+ if (rest[1] === "server") return [await this.startServer(target.identity)]
+
+ if (rest[1] === "client") return [await this.startClient(target.identity, rest[2] as LaunchClient | undefined)]
+
+ throw new Error("A Process endpoint is server or client")
+ }
+
+ if (word === "stop-endpoint") {
+
+ const target = this.heldProcess(rest[0], process)
+
+ if (rest[1] === "server") return [await this.stopServer(target.identity)]
+
+ if (rest[1] === "client") return [await this.stopClient(target.identity)]
+
+ throw new Error("A Process endpoint is server or client")
+ }
+
+ if (word === "stop-current") return [await this.stopServer(process.identity)]
+
+ // The one word here that answers about a process the host does
+ // not know, because that absence is its whole subject. Every
+ // other refuses it: for those there is nothing to answer about,
+ // and whether an identity ever named anything is not something the
+ // host tells. A *handle* is different — it could only have been
+ // obtained for a process the host knew, so through one, absence
+ // means ended and can mean nothing else.
+ if (word === "exited") {
+
+ if (!isHandleAddress(rest[0])) throw new Error("The boundary returned an invalid Process handle")
+
+ return [this.processes.get(rest[0].identity)?.reference !== rest[0].reference]
+ }
+
+ // What a program may know about how it is shown. Not the whole
+ // record: `depth` is how the host works out which window is at
+ // the front of its layer — a mechanism, and a value a program
+ // can read but never act on is a mechanism leaking through the
+ // contract. What it is told instead is `front`, which is what
+ // depth was being used to ask.
+ if (word === "window") {
+
+ const { process: target, window } = this.heldWindow(rest[0], process)
+
+ return [{
+
+ title: window.title,
+
+ position: window.position,
+
+ size: window.size,
+
+ minimized: window.minimized,
+
+ // At the front of its own layer — which is ordering, and
+ // is not the keyboard. There is no word here for the
+ // keyboard at all.
+ front: this.front(window.layer) === target.identity,
+
+ // Which layer it lives in, and which of its own pages it
+ // was opened at. A launch may say either, so a program
+ // cannot read them off its own description — and `front`
+ // is a weaker claim than it reads as unless you know
+ // which layer it is the front of.
+ layer: window.layer,
+
+ location: window.location,
+
+ surface: window.surface
+ }]
+ }
+
+ if (word === "move") {
+
+ const target = this.heldWindow(rest[0], process).process.identity
+
+ await this.move(target, rest[1] as Position)
+
+ return [target]
+ }
+
+ if (word === "resize") {
+
+ const target = this.heldWindow(rest[0], process).process.identity
+
+ await this.resize(target, rest[1] as Size)
+
+ return [target]
+ }
+
+ if (word === "surfaceSet") {
+
+ const target = this.heldWindow(rest[0], process).process.identity
+
+ await this.surface(target, rest[1] === undefined ? {} : rest[1])
+
+ return [target]
+ }
+
+ if (word === "surfaceRemove") {
+
+ const target = this.heldWindow(rest[0], process).process.identity
+
+ await this.surface(target, null)
+
+ return [target]
+ }
+
+ if (word === "changeTitle") {
+
+ const target = this.heldWindow(rest[0], process).process.identity
+
+ await this.changeTitle(target, String(rest[1] ?? ""))
+
+ return [target]
+ }
+
+ if (word === "raise") {
+
+ const target = this.heldWindow(rest[0], process).process.identity
+
+ await this.raise(target)
+
+ return [target]
+ }
+
+ if (word === "minimize") {
+
+ const target = this.heldWindow(rest[0], process).process.identity
+
+ await this.minimize(target, rest[1] !== false)
+
+ return [target]
+ }
+
+ if (word === "exit") {
+
+ const target = this.heldProcess(rest[0], process)
+
+ await this.stop(target.identity)
+
+ return [target.identity]
+ }
+
+ if (word === "exit-all") return [await this.exitAll(this.heldProgram(rest[0]).identity, process.identity)]
+
+ if (word === "observe") {
+
+ const kind = rest[3]
+
+ const event = rest[4]
+
+ const reportImpossible = rest[5] === true
+
+ if (!isTrafficKind(kind)) return []
+
+ if (event !== null && typeof event !== "string") return []
+
+ const target = this.heldProcess(rest[1], process)
+
+ this.observeServer(process, String(rest[0]), target, String(rest[2]), kind, event, reportImpossible)
+
+ return []
+ }
+
+ if (word === "unobserve") {
+
+ this.unobserveServer(process, String(rest[0]))
+
+ return []
+ }
+
+ if (word === "follow") {
+
+ const event = rest[3]
+
+ if (event !== null && typeof event !== "string") return []
+
+ const target = this.heldProcess(rest[1], process)
+
+ this.followServer(process, String(rest[0]), target, String(rest[2]), event, rest[4] === true)
+
+ return []
+ }
+
+ if (word === "unfollow") {
+
+ this.unfollowServer(process, String(rest[0]))
+
+ return []
+ }
+
+ if (word === "emit") {
+
+ if (typeof rest[0] !== "string") return []
+
+ await this.endpointEvents.emit(process.reference, "server", rest[0], rest[1])
+
+ return []
+ }
+
+ // Speaking into one end of another process's channel.
+ //
+ // Which end is said rather than implied. `publish` reached the
+ // server end and only the server end, so a program with no
+ // server half could not be spoken to at all — which was a
+ // consequence of one hidden destination rather than a rule
+ // anyone chose.
+ //
+ // The boundary derives the sender. Program code supplies only the
+ // payload, so it cannot impersonate another Endpoint.
+ if (word === "send") {
+
+ const half = rest[1]
+
+ if (half !== "server" && half !== "client") throw new Error(`A process has no "${String(half)}" end`)
+
+ const target = this.heldProcess(rest[0])
+
+ await this.publish(process.identity, "server", target.identity, half, rest.slice(2))
+
+ return []
+ }
+
+ // Only into a server end, and refused here rather than merely
+ // absent from a kit: a client side is not one thing, so there is
+ // no answerer to name, and whoever was quickest is not an
+ // answer.
+ //
+ // Forwarded, and that is all. The asker wrote its own address
+ // into the question and holds its own deadline, so there is
+ // nothing here to wait for and nothing to answer with. A caller
+ // that stopped waiting will ignore what comes back, which is its
+ // business and not this one's.
+ if (word === "ask") {
+
+ if (rest[1] !== "server") throw new Error("Only a server end can be asked — a client end has no one answerer")
+
+ const question = String(rest[2])
+
+ if (typeof rest[3] !== "string" || typeof rest[4] !== "string") throw new Error("A question needs a public id and an event name")
+
+ const targetProcess = this.heldProcess(rest[0])
+
+ const target = targetProcess.server
+
+ if (!target) {
+
+ this.rejectQuestion(["wait", question, rest[3], rest[4], ...rest.slice(5)], "This process has no live server endpoint")
+
+ return []
+ }
+
+ process.server?.retain(question, () => target.forget(question))
+
+ this.asked(process.identity, "server", targetProcess.identity, rest.slice(2))
+
+ return []
+ }
+
+ // What a launch said, carried by the process it launched.
+ if (word === "option") {
+
+ const asked = this.heldProcess(rest[0], process)
+
+ return [asked.options[String(rest[1])]]
+ }
+
+ // A server SDK asks the host only where a Program's area begins;
+ // every filesystem operation belongs to the SDK after that. The
+ // area is shared by every Process, so the Program is named rather
+ // than the Process. With no name, it is the asker's own Program.
+ if (word === "data" || word === "cache") {
+
+ // The one registry is the authority for every program,
+ // installed or not. Naming the current program explicitly
+ // must therefore be equivalent to leaving the subject empty.
+ const program = this.heldProgram(rest[0], process.program)
+
+ if (rest[1] !== "path") throw new Error("A server half asks the host only for an area path")
+
+ return [programManager.operate(program, word, "path", [])]
+ }
+
+ // What a program has said, asked for and never told. The
+ // connection behind this is read-only, so a query that tries to
+ // change what it reads is refused by the database rather than by
+ // anything here deciding what a query means.
+ if (word === "logs") {
+
+ const program = this.heldProgram(rest[0], process.program)
+
+ return [programManager.logsOf(program).query(String(rest[1]), Array.isArray(rest[2]) ? rest[2] : [])]
+ }
+
+ // A program's own database. Written as well as read, unlike the
+ // log above: that is the system's account of a program and this
+ // is the program's own, which is why they are two files.
+ if (word === "database") {
+
+ const program = this.heldProgram(rest[0], process.program)
+
+ return [programManager.databaseOf(program).query(String(rest[1]), Array.isArray(rest[2]) ? rest[2] : [])]
+ }
+
+ // A server half writes served values locally, as it does its program
+ // areas. The SDK asks for the one managed root and canonical limit;
+ // neither becomes a separate public capability.
+ if (word === "serve") {
+
+ const { servedFiles } = this.authManager.linkManager.application
+
+ return [servedFiles.fileManager.path, serveLimit]
+ }
+
+ // A program's own persistent key-value store. A Program handle names
+ // whose; an omitted subject means the asking process's program. The
+ // application store has no generic host road — application methods
+ // expose only the values the application actually owns.
+ if (word === "store") {
+
+ const [operation, key, value, ttl] = rest.slice(1) as [string, string, unknown, number | undefined]
+
+ const whose = this.heldProgram(rest[0], process.program).identity
+
+ return [await programManager.store(whose, operation, key, value, ttl)]
+ }
+
+ throw new Error(`The host does not know the word "${String(word)}"`)
+ }
+
+ private async endHostWait(process: Process, question: string, args: unknown[]) {
+
+ try {
+
+ if (args[0] === "wait-ready") {
+
+ const target = this.heldProcess(args[1], process)
+
+ const requireCurrentIncarnation = args[2] === true
+
+ if (!target.program.server) throw new Error("This program declared no server half")
+
+ if (requireCurrentIncarnation && !target.server) throw new Error("This process has no live server endpoint")
+
+ if (target.server?.ready) {
+
+ this.say(process.server, "host-end", "answer", question, succeeded([]))
+
+ return
+ }
+
+ let active = true
+
+ const incarnation = requireCurrentIncarnation ? target.server : null
+
+ const ready = target.waitReady(() => {
+
+ if (!active) return
+
+ active = false
+
+ this.say(process.server, "host-end", "answer", question, succeeded([]))
+ })
+
+ target.onExit(() => {
+
+ if (!active) return
+
+ active = false
+
+ ready()
+
+ this.say(process.server, "host-end", "answer", question, failed(new Error("The process ended before its server became ready")))
+ })
+
+ incarnation?.finished.then(() => {
+
+ if (!active) return
+
+ active = false
+
+ ready()
+
+ this.say(process.server, "host-end", "answer", question, failed(new Error("The server endpoint stopped before becoming ready")))
+ }).catch(() => undefined)
+
+ process.server?.retain(question, () => {
+
+ active = false
+
+ ready()
+ })
+
+ return
+ }
+
+ // The host's words answer with a list — one item each — and a
+ // wire carries one value, so the list is that value. A
+ // program's own endpoint answers a value directly; these are
+ // the two shapes and they meet here.
+ const result = await this.endHost(process, args)
+
+ this.say(process.server, "host-end", "answer", question, succeeded(result))
+ }
+
+ catch (exception) {
+
+ this.say(process.server, "host-end", "answer", question, failed(exception))
+ }
+ }
+
+ // A client question retains its cancellation at the server-host
+ // counterpart of that exact desktop boundary. Replacing the document or
+ // losing the session therefore removes the target's queued request even
+ // when the desktop can no longer send an explicit cancellation.
+ @Subscribe("/frame/ask")
+ protected askClientFrame(connection: string, source: string, identity: string, values: unknown[]) {
+
+ const question = String(values[0])
+
+ if (!this.retainClientQuestion(connection, source, question, identity)) {
+
+ this.rejectClientQuestion(connection, source, ["wait", ...values], "This process has no live server endpoint")
+
+ return
+ }
+
+ this.asked(source, "client", identity, values)
+ }
+
+ @Subscribe("/frame/cancel")
+ protected cancelClientFrame(connection: string, source: string, question: string) {
+
+ this.clientForwarders.get(this.clientOwnerKey(connection, source))?.cancel(question)
+ }
+
+ // Where both roads meet: a question named by whoever is waiting for
+ // it, put into the server half's hands.
+ private asked(source: string, sourceHalf: Half, identity: string, values: unknown[]) {
+
+ if (typeof values[0] !== "string" || typeof values[1] !== "string" || typeof values[2] !== "string") return
+
+ const sourceProcess = this.processes.get(source)
+
+ const targetProcess = this.processes.get(identity)
+
+ if (!sourceProcess || !targetProcess?.server) {
+
+ this.rejectQuestion(["wait", ...values], "This process has no live server endpoint")
+
+ return
+ }
+
+ const payload = values[3]
+
+ const received = { from: endpointReference(sourceProcess, sourceHalf), payload }
+
+ this.traffic.emit(sourceProcess.reference, sourceHalf, "ask", values[2], values[1], {
+
+ to: endpointReference(targetProcess, "server"),
+
+ payload
+ }).catch(() => undefined)
+
+ this.deliver(identity, "server", ["wait", values[0], values[1], values[2], received]).catch(() => undefined)
+ }
+
+ @Subscribe("/frame/end-end")
+ protected async endEndClientFrame(connection: string, identity: string, json: string) {
+
+ // The payload crossed The Link as standard JSON in a plain
+ // string — parsed here, delivered in its envelope: an end knows
+ // who speaks by the route name it hears.
+ const values = JSON.parse(json) as unknown[]
+
+ if (values[0] === "wait" && typeof values[1] === "string" && !this.retainClientQuestion(connection, identity, values[1], identity)) {
+
+ this.rejectClientQuestion(connection, identity, values, "This process has no live server endpoint")
+
+ return
+ }
+
+ if (values[0] === "wait") {
+
+ this.asked(identity, "client", identity, values.slice(1))
+
+ return
+ }
+
+ await this.publish(identity, "client", identity, "server", values)
+ }
+
+ @Connect("/stop")
+ public async stop(identity: string) {
+
+ return await this.exitProcess(identity)
+ }
+
+ @Connect("/endpoint/start")
+ protected async startEndpoint(identity: string, which: string, overrides?: LaunchClient) {
+
+ if (which === "server") return await this.startServer(identity)
+
+ if (which === "client") return await this.startClient(identity, overrides)
+
+ throw new Error("A Process endpoint is server or client")
+ }
+
+ @Connect("/endpoint/stop")
+ protected async stopEndpoint(identity: string, which: string) {
+
+ if (which === "server") return await this.stopServer(identity)
+
+ if (which === "client") return await this.stopClient(identity)
+
+ throw new Error("A Process endpoint is server or client")
+ }
+
+ // Geometry, said as it changes — and only geometry.
+ //
+ // It also announced a `maximize` when a move happened to land on the
+ // whole surface. Filling the surface is not a state any more: it is
+ // a size like any other, and the button that asks for it lives in
+ // the window manager with a memory of its own. So a move is a move.
+ //
+ // Minimized is untouched by both. Where a window is and whether it
+ // is shown are two questions, so a hidden window can be moved and
+ // resized and will appear where it now is.
+ @Connect("/move")
+ public async move(identity: string, position: Position) {
+
+ const window = this.mutableWindowOf(identity)
+
+ window.move(position)
+
+ this.said(identity, "move", window.position)
+
+ return { identity, window }
+ }
+
+ @Connect("/resize")
+ public async resize(identity: string, size: Size) {
+
+ const window = this.mutableWindowOf(identity)
+
+ window.resize(size)
+
+ this.said(identity, "resize", window.size)
+
+ return { identity, window }
+ }
+
+ @Connect("/change-title")
+ public async changeTitle(identity: string, title: string) {
+
+ const window = this.mutableWindowOf(identity)
+
+ window.changeTitle(title)
+
+ this.said(identity, "changeTitle", window.title)
+
+ return { identity, window }
+ }
+
+ @Connect("/surface")
+ public async surface(identity: string, settings: unknown) {
+
+ const window = this.surfaceWindowOf(identity)
+
+ const changed = settings === null ? window.removeSurface() : window.setSurface(settings)
+
+ if (!changed) return null
+
+ this.said(identity, "surface", window.surface)
+
+ return { identity, window }
+ }
+
+ // To the front of its own layer, and that is the whole of it.
+ //
+ // It was called `focus` and it did three things: it showed a hidden
+ // window, it reordered, and its name claimed the keyboard. Now it
+ // reorders. A hidden window raised stays hidden and appears at its
+ // new place in the order when it is shown; a taskbar click that
+ // wants both says both, which is the window manager composing
+ // primitives rather than one primitive doing two jobs.
+ //
+ // And the name matters beyond tidiness. **No word here may take real
+ // input focus**, or a program could pull typing away from the
+ // program a person believes they are typing into. Keyboard focus is
+ // the browser's, reached by a person clicking and no other way, so
+ // the system's word for ordering must not be called focus.
+ @Connect("/raise")
+ public async raise(identity: string) {
+
+ const window = this.mutableWindowOf(identity)
+
+ const front = this.front(window.layer)
+
+ window.depth = ++this.highest
+
+ this.settleFront(window.layer, front)
+
+ return { identity, window }
+ }
+
+ // Shown, or not shown. Nothing else: the order is untouched, so a
+ // window hidden and shown again comes back exactly where it was in
+ // its layer rather than on top of it.
+ @Connect("/minimize")
+ public async minimize(identity: string, minimized: boolean) {
+
+ const window = this.mutableWindowOf(identity)
+
+ const front = this.front(window.layer)
+
+ window.minimized = minimized
+
+ this.said(identity, "minimize", window.minimized)
+
+ this.settleFront(window.layer, front)
+
+ return { identity, window }
+ }
+
+ // ── The front window of a layer ──────────────────────────────────
+ //
+ // Which window is at the front is a fact about one *layer* at a
+ // time: the shown one in that layer with the greatest depth.
+ // Nothing stores it, so nothing can hold a stale copy — and
+ // everything that could move it (raising, hiding, showing, a window
+ // opening, a process ending) reads it before and settles it after,
+ // rather than each announcing what it guessed.
+ //
+ // Three layers, so up to three front windows, and what happens in
+ // one is not news in another: a window opening in `over` does not
+ // reorder anything a person is typing in.
+ //
+ // **Not the keyboard.** A browser focuses one element and the keys
+ // go where a person typed. This is ordering, and calling it focus
+ // was a claim the system cannot back — and must not, since a
+ // program able to take real focus could read typing meant for
+ // another.
+ //
+ // The order includes hidden windows; this reads only the shown ones.
+ // A minimized window has a place in the order and is not at the
+ // front of anything, which is why raising one changes where it will
+ // appear rather than whether it appears.
+ public front(layer: WindowLayer) {
+
+ let best: string | null = null
+
+ let depth = -Infinity
+
+ for (const [identity, process] of this.processes) {
+
+ const window = process.client?.window
+
+ if (!process.client || !window || window.layer === "wallpaper" || window.minimized || window.layer !== layer) continue
+
+ if (window.depth <= depth) continue
+
+ best = identity
+
+ depth = window.depth
+ }
+
+ return best
+ }
+
+ // Said only where it changed: two windows at most, and neither hears
+ // news about the other — the one that lost it and the one that took
+ // it, each told about itself.
+ //
+ // Settled within one layer, because that is the only layer the
+ // change could have reached.
+ public settleFront(layer: WindowLayer, was: string | null) {
+
+ const now = this.front(layer)
+
+ if (now === was) return
+
+ if (was) this.said(was, "front", false)
+
+ if (now) this.said(now, "front", true)
+ }
+
+ public toJSON() {
+
+ return {
+
+ processes: [...this.processes].map(([identity, process]) => [identity, process.hosted()] as [string, HostedProcess])
+ }
+ }
+}
+
+// Where an answer goes, read out of the question itself.
+//
+// A question is named by its asker before it leaves — which half of
+// which process is holding the promise — so routing an answer needs no
+// memory at all. The address is in the message, which is the one place
+// it cannot go stale, and the only place that does not require the
+// middle to be trusted.
+function addressed(question: string): { half: Half, identity: string } | null {
+
+ const [half, identity] = question.split(":")
+
+ if (half !== "server" && half !== "client") return null
+
+ return { half, identity }
+}
+
+function isTrafficKind(value: unknown): value is TrafficKind {
+
+ return value === "publish" || value === "ask" || value === "answer"
+}
+
+interface HandleAddress {
+
+ identity: string
+
+ reference: string
+}
+
+function isHandleAddress(value: unknown): value is HandleAddress {
+
+ return typeof value === "object" && value !== null && "identity" in value && "reference" in value
+ && typeof value.identity === "string" && typeof value.reference === "string"
+}
+
+// What a launch resolved to, before a window exists to hold it.
+//
+// Handed to `register` rather than worked out there: the declaration and
+// what the launch overrode are reconciled in one place, by whoever is
+// starting the process, so there are not two places deciding what a
+// window opens as.
+interface ShapeBase {
+
+ position: Position
+
+ size: Size
+
+ location: string
+
+ minimize: boolean
+}
+
+export interface StandardShape extends ShapeBase {
+
+ layer: Layer
+}
+
+export interface WallpaperShape extends ShapeBase {
+
+ layer: "wallpaper"
+}
+
+export type Shape = StandardShape | WallpaperShape
+
+type EndpointEvent = "endpointStart" | "endpointStop"
+
+export type TransmittedProcessManager = Transmitted<ProcessManager>
+
+// Inside, or not at all. A program joining its own paths from the root
+// gives that up knowingly; a join asked of the host does not.
diff --git a/source/server/core/link-manager/auth-manager/process-manager/process-traffic.ts b/source/server/core/link-manager/auth-manager/process-manager/process-traffic.ts
new file mode 100644
index 0000000..971891e
--- /dev/null
+++ b/source/server/core/link-manager/auth-manager/process-manager/process-traffic.ts
@@ -0,0 +1,69 @@
+import TheLink from "@libs/the-link/the-link"
+
+/**
+ * Application traffic spoken by one Process endpoint.
+ *
+ * Publications, questions and answers have independent routes. A boundary
+ * joins only the kind it explicitly requested, so the separation exists at
+ * the routing boundary rather than as filtering inside a Program endpoint.
+ */
+export default class ProcessTraffic extends TheLink {
+
+ public emit(process: string, half: Half, kind: TrafficKind, event: string, ...message: unknown[]) {
+
+ return this.$inbound.publish(this.event(process, half, kind, event), event, ...message)
+ }
+
+ /** End every fallible observation of this Process's application traffic. */
+ public end(process: string, reason: string) {
+
+ return this.$inbound.publish(this.terminal(process), reason)
+ }
+
+ public observe(process: string, half: Half, kind: TrafficKind, event: string | null, subscriber: Subscriber, impossible?: (reason: string) => void) {
+
+ const prefix = this.prefix(process, half, kind)
+
+ const stopEvent = event !== null
+ ? this.$inbound.subscribe(prefix + encodeURIComponent(event), (word, ...payload) => {
+
+ if (typeof word === "string") subscriber(word, ...payload)
+ })
+ : this.$inbound.forwardTo((_route, word, ...payload) => {
+
+ if (typeof word === "string") subscriber(word, ...payload)
+ }, prefix)
+
+ const stopTerminal = impossible
+ ? this.$inbound.subscribe(this.terminal(process), (reason: unknown) => impossible(String(reason)))
+ : () => undefined
+
+ return () => {
+
+ stopEvent()
+
+ stopTerminal()
+ }
+ }
+
+ private terminal(process: string) {
+
+ return `terminal/${encodeURIComponent(process)}`
+ }
+
+ private prefix(process: string, half: Half, kind: TrafficKind) {
+
+ return `${encodeURIComponent(process)}/${half}/${kind}/`
+ }
+
+ private event(process: string, half: Half, kind: TrafficKind, event: string) {
+
+ return this.prefix(process, half, kind) + encodeURIComponent(event)
+ }
+}
+
+export type Half = "server" | "client"
+
+export type TrafficKind = "publish" | "ask" | "answer"
+
+type Subscriber = (event: string, ...payload: unknown[]) => unknown
diff --git a/source/server/core/link-manager/auth-manager/process-manager/process.ts b/source/server/core/link-manager/auth-manager/process-manager/process.ts
new file mode 100644
index 0000000..5b58fb8
--- /dev/null
+++ b/source/server/core/link-manager/auth-manager/process-manager/process.ts
@@ -0,0 +1,324 @@
+import { Options } from "../program-manager/program-manager"
+import Program from "../program-manager/program"
+import Window, { Position, Size } from "./window"
+import { ChildProcess } from "node:child_process"
+import { Transmitted } from "@libs/superjson"
+import ServerProcessBoundary from "./server-process-boundary"
+import HostTraffic from "./host-traffic"
+import ClientState from "./client-state"
+import { randomUUID } from "node:crypto"
+import { type PermissionName } from "@phreshos/core"
+import Tunnel from "@libs/the-link/tunnel"
+
+/**
+ * One live execution of a Program.
+ *
+ * Its immutable options are the launch state carried by this particular
+ * life. They are available to either half without becoming part of the
+ * Program declaration that later launches inherit.
+ *
+ * Endpoint presence is mutable live state. Each start creates a fresh
+ * boundary incarnation; each stop removes that boundary and everything it
+ * owns. The Process remains the stable aggregate around those incarnations
+ * and must always have at least one live endpoint.
+ *
+ * The child handle lives here beside the transmitted values and is left
+ * out of toJSON: what crosses is declared, so a host-only handle needs no
+ * second structure to hide in.
+ */
+export default class Process {
+
+ /** Opaque identity of this one Process entity, never a public address. */
+ public readonly reference = randomUUID()
+
+ public readonly identity: string
+
+ // A meaningful address within this program. Null means this process
+ // has no role beyond its random identity.
+ public readonly name: string | null
+
+ // The program it is an instance of, held rather than named: a
+ // process is derived from a program, and a name is only what that
+ // program calls itself.
+ public readonly program: Program
+
+ // What its launch said. Attached the moment it started and carried
+ // wherever it goes — a process is exactly one launch, so this is
+ // the process's own state rather than a message it was sent.
+ public readonly options: Options
+
+ /** Permission grants that live exactly as long as this Process. */
+ public readonly permissions = new Set<PermissionName>()
+
+ // When this instance began. A process's birth is its construction,
+ // so nothing hands this over — there is no earlier moment to mean.
+ //
+ // A `Date`, and the link keeps it one: superjson carries dates, and
+ // `libs/superjson` leaves them alone rather than letting `toJSON`
+ // degrade them to strings. The other two roads out of here speak
+ // plain JSON — a program's channel and this machine's door — so on
+ // those it arrives as the ISO string a date serialises to. That is
+ // harmless while nothing reads it there, and would stop being
+ // harmless the moment a kit declared it a `Date`.
+ public readonly startedAt = new Date()
+
+ // The current server incarnation. Null is current live state, not a
+ // declaration or a permanent launch-shape decision.
+ public server: ServerProcessBoundary | null = null
+
+ // The current client incarnation and the Window it owns. Its nearby iframe
+ // boundary belongs to the desktop session, but both existence and Window
+ // lifetime originate here. Stopping the client destroys this value whole.
+ public client: ClientState | null = null
+
+ // The process whose call to `program.createProcess()` created this
+ // one. Lineage only: keeping this handle neither owns nor prolongs
+ // either life.
+ public readonly parent: Process | null
+
+ private readonly hostTraffic: HostTraffic
+
+ private readonly serverStarts: ((server: ServerProcessBoundary) => void)[] = []
+
+ private readonly serverStops: ((code: number | null, signal: NodeJS.Signals | null) => void)[] = []
+
+ private readonly clientStops: (() => void)[] = []
+
+ private readonly readyWaiters = new Set<() => void>()
+
+ private readonly endings: Ending[] = []
+
+ private ending: { code: number | null, signal: NodeJS.Signals | null } | null = null
+
+ private exitProcess: (() => Promise<unknown>) | null = null
+
+ public constructor(identity: string, name: string | null, program: Program, options: Options, parent: Process | null, hostTraffic: HostTraffic) {
+
+ this.identity = identity
+
+ this.name = name
+
+ this.program = program
+
+ this.options = options
+
+ this.parent = parent
+
+ this.hostTraffic = hostTraffic
+ }
+
+ public startServer(child: ChildProcess, ended: (boundary: ServerProcessBoundary, code: number | null, signal: NodeJS.Signals | null) => Promise<void> | void, unanswered: (values: unknown[], reason: string) => void, theme: Tunnel) {
+
+ if (this.server) return this.server
+
+ let boundary!: ServerProcessBoundary
+
+ boundary = new ServerProcessBoundary(child, this.program.client !== null, (code, signal) => ended(boundary, code, signal), unanswered, this.hostTraffic, theme)
+
+ this.server = boundary
+
+ for (const listener of this.serverStarts) listener(boundary)
+
+ return boundary
+ }
+
+ public serverStopped(boundary: ServerProcessBoundary, code: number | null, signal: NodeJS.Signals | null) {
+
+ if (this.server !== boundary) return false
+
+ this.server = null
+
+ for (const listener of this.serverStops) listener(code, signal)
+
+ return true
+ }
+
+ public serverBecameReady(boundary: ServerProcessBoundary) {
+
+ if (this.server !== boundary || !boundary.ready) return
+
+ const waiters = [...this.readyWaiters]
+
+ this.readyWaiters.clear()
+
+ for (const waiter of waiters) waiter()
+ }
+
+ public waitReady(notify: () => void) {
+
+ if (this.server?.ready) {
+
+ notify()
+
+ return () => undefined
+ }
+
+ this.readyWaiters.add(notify)
+
+ return () => { this.readyWaiters.delete(notify) }
+ }
+
+ public startClient(window: Window) {
+
+ if (this.client) return false
+
+ this.client = new ClientState(window)
+
+ return true
+ }
+
+ public stopClient() {
+
+ if (!this.client) return false
+
+ this.client = null
+
+ for (const listener of this.clientStops) listener()
+
+ return true
+ }
+
+ public get live() {
+
+ return this.server !== null || this.client !== null
+ }
+
+ public onServerStart(listener: (server: ServerProcessBoundary) => void) {
+
+ this.serverStarts.push(listener)
+
+ if (this.server) listener(this.server)
+ }
+
+ /** Internal aggregate exit used by lifecycle owners and focused probes. */
+ public async stop() {
+
+ if (!this.exitProcess) throw new Error("This Process has no lifecycle owner")
+
+ await this.exitProcess()
+ }
+
+ public ownExit(exit: () => Promise<unknown>) {
+
+ this.exitProcess = exit
+ }
+
+ public onServerStop(listener: (code: number | null, signal: NodeJS.Signals | null) => void) {
+
+ this.serverStops.push(listener)
+ }
+
+ public onClientStop(listener: () => void) {
+
+ this.clientStops.push(listener)
+ }
+
+ // Every aggregate ending, one word. Endpoint stops are separate lifecycle
+ // transitions and reach this only when the complete Process is gone.
+ //
+ // The code and signal come with it, because whoever launched a
+ // process may have to exit with its status. A listener that took
+ // nothing dropped both.
+ public onExit(listener: Ending) {
+
+ if (this.ending) {
+
+ listener(this.ending.code, this.ending.signal)
+
+ return () => undefined
+ }
+
+ this.endings.push(listener)
+
+ return () => {
+
+ const index = this.endings.indexOf(listener)
+
+ if (index !== -1) this.endings.splice(index, 1)
+ }
+ }
+
+ // Said once, however many ways it could be said: a child's exit
+ // removes the record, and removing the record is itself an ending.
+ // The result remains terminal state rather than becoming lost history:
+ // process creation announces externally before every internal owner has
+ // finished attaching, and a fast child can exit during that announcement.
+ public ended(code: number | null, signal: NodeJS.Signals | null) {
+
+ if (this.ending) return
+
+ this.ending = { code, signal }
+
+ this.readyWaiters.clear()
+
+ const endings = this.endings.splice(0)
+
+ for (const listener of endings) listener(code, signal)
+ }
+
+ // The process value every road carries. Parentage is deliberately
+ // absent: it is asked through `current.parent()`, so a client gate
+ // can hide a cross-program parent without first exposing it here.
+ public record() {
+
+ return {
+
+ reference: this.reference,
+
+ identity: this.identity,
+
+ name: this.name,
+
+ program: this.program.identity,
+
+ options: this.options,
+
+ startedAt: this.startedAt,
+
+ // These are live endpoint snapshots. Program declarations answer
+ // which endpoint kinds can be started.
+ server: this.server ? {} : null,
+
+ client: this.client ? {} : null
+ }
+ }
+
+ public hosted() {
+
+ return {
+
+ ...this.record(),
+
+ // The trusted desktop counterpart keeps this essential fact
+ // current. Framed program records are shaped separately.
+ server: this.server ? { ready: this.server.ready } : null,
+
+ // The trusted desktop needs the relationship in order to
+ // answer a pane locally after the parent has exited. The
+ // pane never receives this record whole.
+ parent: this.parent?.record() ?? null,
+
+ assetId: this.program.assetId,
+
+ client: this.client
+ }
+ }
+
+ public toJSON() {
+
+ return this.record()
+ }
+}
+
+export type HostedProcess = ReturnType<Process["hosted"]>
+
+/** Public Process data from which an endpoint SDK reconstructs a handle. */
+export type ProcessRecord = ReturnType<Process["record"]>
+
+export type TransmittedProcess = Transmitted<HostedProcess>
+
+export type Ending = (code: number | null, signal: NodeJS.Signals | null) => void
+
+export type { Position, Size }
+
+export type { Stream } from "./server-process-boundary"
diff --git a/source/server/core/link-manager/auth-manager/process-manager/server-process-boundary.ts b/source/server/core/link-manager/auth-manager/process-manager/server-process-boundary.ts
new file mode 100644
index 0000000..b38ee8e
--- /dev/null
+++ b/source/server/core/link-manager/auth-manager/process-manager/server-process-boundary.ts
@@ -0,0 +1,459 @@
+import ProcessLink from "@libs/the-link/plugins/process-link/process-link"
+import ProcessTree from "@libs/process-tree"
+import { type ChildProcess } from "node:child_process"
+import ProcessTraffic, { type Half, type TrafficKind } from "./process-traffic"
+import HostTraffic from "./host-traffic"
+import EndpointEvents from "./endpoint-events"
+import Tunnel from "@libs/the-link/tunnel"
+
+/**
+ * The boundary around one server execution endpoint.
+ *
+ * The child speaks only here. Application events cross only when its SDK has
+ * registered an interest. Readiness travels out of the endpoint; the boundary
+ * never injects startup state into it.
+ */
+export default class ServerProcessBoundary extends ProcessLink {
+
+ public ready = false
+
+ private readonly clientDeclared: boolean
+
+ private readonly subscriptions = new Map<string, EndpointSubscription>()
+
+ private readonly expected = new Set<string>()
+
+ private readonly waiting = new Map<string, WaitingQuestion[]>()
+
+ // Every question addressed to this incarnation, including those already
+ // delivered into its SDK. Teardown completes each one with an error so a
+ // caller never waits for an endpoint that no longer exists.
+ private readonly incoming = new Map<string, unknown[]>()
+
+ private readonly requests = new Map<string, () => void>()
+
+ private readonly observations = new Map<string, () => void>()
+
+ private readonly endpointSubscriptions = new Map<string, () => void>()
+
+ private readonly hostSubscriptions = new Map<string, () => void>()
+
+ private readonly themeSubscriptions = new Set<string>()
+
+ private stopTheme: (() => void) | null = null
+
+ private readonly child: ChildProcess
+
+ private readonly tree: ProcessTree
+
+ private readonly hostTraffic: HostTraffic
+
+ private readonly theme: Tunnel
+
+ private readonly unanswered: (values: unknown[], reason: string) => void
+
+ public readonly finished: Promise<{ code: number | null, signal: NodeJS.Signals | null }>
+
+ public constructor(child: ChildProcess, clientDeclared: boolean, ended: Ending, unanswered: (values: unknown[], reason: string) => void, hostTraffic: HostTraffic, theme: Tunnel) {
+
+ super(child)
+
+ this.clientDeclared = clientDeclared
+
+ this.child = child
+
+ let finish!: (ending: { code: number | null, signal: NodeJS.Signals | null }) => void
+
+ this.finished = new Promise(resolve => { finish = resolve })
+
+ this.tree = new ProcessTree(child, async (code, signal) => {
+
+ try { await ended(code, signal) }
+
+ finally { finish({ code, signal }) }
+ })
+
+ this.hostTraffic = hostTraffic
+
+ this.theme = theme
+
+ this.unanswered = unanswered
+
+ child.on("error", () => undefined)
+
+ this.$inbound.subscribe("boundary", (...values) => this.control(values))
+ }
+
+ /** Deliver one routed envelope only when this endpoint requested it. */
+ public async deliver(route: string, ...values: unknown[]) {
+
+ if (values[0] === "answer" && typeof values[1] === "string") {
+
+ if (!this.expected.has(values[1])) return
+
+ this.requests.delete(values[1])
+
+ await this.$outbound.publish(route, ...values)
+
+ return
+ }
+
+ const question = values[0] === "wait" && typeof values[1] === "string" ? values[1] : null
+
+ if (question && route === "end-end") this.incoming.set(question, values)
+
+ const eventIndex = question && route === "end-end" ? 3 : 2
+
+ const event = String(question ? values[eventIndex] : values[0])
+
+ const payload = question ? values.slice(eventIndex + 1) : values.slice(1)
+
+ const kind: TrafficKind = question ? "ask" : "publish"
+
+ if (this.accepts(kind, route, event, payload)) {
+
+ await this.$outbound.publish(route, ...values)
+
+ return
+ }
+
+ if (!question) return
+
+ const key = `${route}:${event}`
+
+ const waiting = this.waiting.get(key) ?? []
+
+ waiting.push({ route, values, question })
+
+ this.waiting.set(key, waiting)
+ }
+
+ public retain(question: string, stop: () => void) {
+
+ this.requests.get(question)?.()
+
+ this.requests.set(question, stop)
+ }
+
+ /** Observe another Process through a subscription owned by this boundary. */
+ public observe(traffic: ProcessTraffic, subscription: string, target: string, half: Half, kind: TrafficKind, event: string | null, reportImpossible: boolean) {
+
+ this.unobserve(subscription)
+
+ const stop = traffic.observe(target, half, kind, event, (word, ...payload) => {
+
+ const values = event === null ? [word, ...payload] : payload
+
+ this.deliver("observed", subscription, ...values).catch(() => undefined)
+ }, reportImpossible ? reason => this.impossible(subscription, reason) : undefined)
+
+ this.observations.set(subscription, stop)
+ }
+
+ /** Terminate one asynchronous observation without affecting silent ones. */
+ public impossible(subscription: string, reason: string) {
+
+ this.unobserve(subscription)
+
+ this.$outbound.publish("boundary", "impossible", subscription, reason).catch(() => undefined)
+ }
+
+ public unobserve(subscription: string) {
+
+ this.observations.get(subscription)?.()
+
+ this.observations.delete(subscription)
+ }
+
+ /** Follow destinationless events emitted by another Endpoint. */
+ public follow(events: EndpointEvents, subscription: string, target: string, half: Half, event: string | null, reportImpossible: boolean) {
+
+ this.unfollow(subscription)
+
+ const stop = events.follow(target, half, event, (word, payload) => {
+
+ const values = event === null ? [word, payload] : [payload]
+
+ this.deliver("emitted", subscription, ...values).catch(() => undefined)
+ }, reportImpossible ? reason => this.impossibleFollow(subscription, reason) : undefined)
+
+ this.endpointSubscriptions.set(subscription, stop)
+ }
+
+ private impossibleFollow(subscription: string, reason: string) {
+
+ this.$outbound.publish("boundary", "impossible", subscription, reason).catch(() => undefined)
+ }
+
+ public unfollow(subscription: string) {
+
+ this.endpointSubscriptions.get(subscription)?.()
+
+ this.endpointSubscriptions.delete(subscription)
+ }
+
+ /** Remove a question whether it is waiting here or inside the SDK. */
+ public forget(question: string) {
+
+ this.forgetWaiting(question)
+
+ this.incoming.delete(question)
+
+ this.$outbound.publish("boundary", "forget", question).catch(() => undefined)
+ }
+
+ public answered(question: string) {
+
+ this.incoming.delete(question)
+ }
+
+ /** End every forwarding interest owned by this Process endpoint. */
+ public release(reason = "The server endpoint stopped before answering") {
+
+ for (const stop of this.requests.values()) stop()
+
+ for (const stop of this.observations.values()) stop()
+
+ for (const stop of this.endpointSubscriptions.values()) stop()
+
+ for (const stop of this.hostSubscriptions.values()) stop()
+
+ this.requests.clear()
+
+ this.observations.clear()
+
+ this.endpointSubscriptions.clear()
+
+ this.hostSubscriptions.clear()
+
+ this.themeSubscriptions.clear()
+
+ this.stopTheme?.()
+
+ this.stopTheme = null
+
+ this.subscriptions.clear()
+
+ this.expected.clear()
+
+ this.waiting.clear()
+
+ const incoming = [...this.incoming.values()]
+
+ this.incoming.clear()
+
+ for (const values of incoming) this.unanswered(values, reason)
+ }
+
+ public stop() {
+
+ this.tree.stop()
+ }
+
+ public onOutput(listener: (stream: Stream, text: string) => void) {
+
+ this.child.stdout?.on("data", chunk => listener("out", String(chunk)))
+
+ this.child.stderr?.on("data", chunk => listener("err", String(chunk)))
+ }
+
+ private control(values: unknown[]) {
+
+ const [operation, ...args] = values
+
+ if (operation === "ready") {
+
+ if (this.ready) return
+
+ this.ready = true
+
+ this.$inbound.publish("boundary-ready", true).catch(() => undefined)
+
+ return
+ }
+
+ if (operation === "subscribe") {
+
+ const [subscription, kind, route, event, subject, reportImpossible] = args
+
+ if (typeof subscription !== "string" || !isTrafficKind(kind) || typeof route !== "string") return
+
+ if (event !== null && typeof event !== "string") return
+
+ if (subject !== null && typeof subject !== "string") return
+
+ if (reportImpossible === true && route === "end-end" && !this.clientDeclared) {
+
+ this.impossible(subscription, "This program declared no client half")
+
+ return
+ }
+
+ this.removeSubscription(subscription)
+
+ const description = { kind, route, event, subject }
+
+ this.subscriptions.set(subscription, description)
+
+ if (themeSubscription(description)) {
+
+ this.themeSubscriptions.add(subscription)
+
+ if (!this.stopTheme) this.stopTheme = this.theme.subscribe("change", theme => {
+
+ this.deliver("host-theme", "change", theme).catch(() => undefined)
+ })
+
+ }
+
+ if (route === "host-events" || route === "host-end" || route === "process-host") {
+
+ this.hostSubscriptions.get(subscription)?.()
+
+ this.hostSubscriptions.set(subscription, this.hostTraffic.observe(event, subject, (_delivery, word, ...values) => {
+
+ this.deliver(route, word, ...values).catch(() => undefined)
+ }))
+ }
+
+ if (kind === "ask") this.releaseWaiting(route, event)
+
+ return
+ }
+
+ if (operation === "unsubscribe") {
+
+ if (typeof args[0] === "string") {
+
+ this.removeSubscription(args[0])
+ }
+
+ return
+ }
+
+ if (operation === "expect") {
+
+ if (typeof args[0] === "string") this.expected.add(args[0])
+
+ return
+ }
+
+ if (operation === "forget") {
+
+ if (typeof args[0] !== "string") return
+
+ this.expected.delete(args[0])
+
+ this.requests.get(args[0])?.()
+
+ this.requests.delete(args[0])
+
+ this.forgetWaiting(args[0])
+ }
+ }
+
+ private accepts(kind: TrafficKind, route: string, event: string, payload: unknown[]) {
+
+ for (const subscription of this.subscriptions.values()) {
+
+ if (subscription.kind !== kind || subscription.route !== route) continue
+
+ if (subscription.event !== null && subscription.event !== event) continue
+
+ if (subscription.subject !== null && payload[0] !== subscription.subject) continue
+
+ return true
+ }
+
+ return false
+ }
+
+ private removeSubscription(subscription: string) {
+
+ this.subscriptions.delete(subscription)
+
+ this.hostSubscriptions.get(subscription)?.()
+
+ this.hostSubscriptions.delete(subscription)
+
+ if (this.themeSubscriptions.delete(subscription) && this.themeSubscriptions.size === 0) {
+
+ this.stopTheme?.()
+
+ this.stopTheme = null
+ }
+ }
+
+ private releaseWaiting(route: string, event: string | null) {
+
+ for (const [key, waiting] of this.waiting) {
+
+ if (!key.startsWith(`${route}:`)) continue
+
+ const remaining: WaitingQuestion[] = []
+
+ for (const held of waiting) {
+
+ const eventIndex = held.route === "end-end" ? 3 : 2
+
+ const word = String(held.values[eventIndex])
+
+ const payload = held.values.slice(eventIndex + 1)
+
+ if ((event === null || event === word) && this.accepts("ask", route, word, payload)) this.$outbound.publish(held.route, ...held.values).catch(() => undefined)
+
+ else remaining.push(held)
+ }
+
+ if (remaining.length) this.waiting.set(key, remaining)
+
+ else this.waiting.delete(key)
+ }
+ }
+
+ private forgetWaiting(question: string) {
+
+ for (const [key, waiting] of this.waiting) {
+
+ const remaining = waiting.filter(held => held.question !== question)
+
+ if (remaining.length) this.waiting.set(key, remaining)
+
+ else this.waiting.delete(key)
+ }
+ }
+}
+
+interface EndpointSubscription {
+
+ kind: TrafficKind
+
+ route: string
+
+ event: string | null
+
+ subject: string | null
+}
+
+function themeSubscription(subscription: EndpointSubscription) {
+
+ return subscription.kind === "publish" && subscription.route === "host-theme" && (subscription.event === null || subscription.event === "change")
+}
+
+function isTrafficKind(value: unknown): value is TrafficKind {
+
+ return value === "publish" || value === "ask" || value === "answer"
+}
+
+interface WaitingQuestion {
+
+ route: string
+
+ values: unknown[]
+
+ question: string
+}
+
+export type Stream = "out" | "err"
+
+export type Ending = (code: number | null, signal: NodeJS.Signals | null) => void
diff --git a/source/server/core/link-manager/auth-manager/process-manager/window.ts b/source/server/core/link-manager/auth-manager/process-manager/window.ts
new file mode 100644
index 0000000..0b7ee70
--- /dev/null
+++ b/source/server/core/link-manager/auth-manager/process-manager/window.ts
@@ -0,0 +1,306 @@
+import { isRelativeValue, isScaleLevel, type Position, type ScaleLevel, type Size, type Value, type WindowLayer, type WindowSurfaceEasing, type WindowSurfaceSettings, type WindowSurfaceTransaction } from "@phreshos/core"
+import { Transmitted } from "@libs/superjson"
+
+/**
+ * How a process is shown. Every value is either a number of pixels or a
+ * linear expression of workspace-relative and pixel terms — so a window can
+ * be absolute in one axis and relative in the other, and arrangements no
+ * vocabulary anticipated (a third-width sidebar, a full-width dock sixty
+ * pixels tall) are simply values.
+ *
+ * A share is resolved by each client in its own layer workspace. Margins
+ * and gutters are presentation outside this value, so pixels and shares
+ * use one coordinate space and neither carries desktop arithmetic.
+ *
+ * **Geometry, visibility and order are three questions**, and no word
+ * here answers two of them. A hidden window can be moved, resized and
+ * reordered, and none of that shows it; showing it shows it wherever it
+ * now is and wherever the order now puts it. There is nothing to
+ * remember and nothing to restore, which is why the two `previous`
+ * fields are gone: they existed to undo `maximize`, and filling the
+ * surface is a size like any other now.
+ *
+ * **What is shown lives here, not on the process.** A title and
+ * where the frame is filled from are all "how this is shown", the same
+ * kind of fact as a size — and `client.size` already becomes
+ * `window.size`, so `title` becomes `window.title` by the same road. A
+ * process with no window needs none of them, and had to carry them all
+ * while they sat on the process.
+ *
+ * The title is the window's own from the moment it opens: born from what
+ * the client half declared, or the program's name when it declared
+ * nothing, and changeable afterwards. A window showing one file of many
+ * is the ordinary case, and a program that cannot say so has to put the
+ * whole story in its own frame.
+ *
+ * **Front is not kept here.** Which window is at the front is a fact about
+ * all of them at once — the un-minimized one with the greatest depth —
+ * so it is answered where every window is in view, and a flag stored
+ * per window could disagree with what is drawn. `depth` is how that is
+ * worked out and stays the host's: a number a program could read but
+ * never interpret is a mechanism leaking through the contract.
+ */
+// What a Window says about the Program behind it. Resolved when the Process
+// first gains Window state and again only when a stopped client is restarted
+// with explicit overrides; ordinary live Window operations remain narrower.
+export interface Shown {
+
+ title: string
+
+ url: string | null
+
+ // Which runtime layer this Window occupies. Ordinary clients are confined
+ // to the three authorable layers; the system assigns its wallpaper Window
+ // the dedicated fourth value.
+ layer: WindowLayer
+
+ // Which page of the client half to open, beneath its declared root.
+ // `/` is the root itself, so absence never has a second meaning.
+ location: string
+}
+
+export default class Window {
+
+ public position: Position
+
+ public size: Size
+
+ public depth: number
+
+ // Whether it is shown. A window may be born hidden, which is a
+ // state at birth rather than an act afterwards: hidden from the
+ // first frame is not the same as shown once and then hidden.
+ public minimized: boolean
+
+ // Optional host material is Window state like geometry: born absent,
+ // changed only here, and echoed whole to every desktop counterpart.
+ public surface: WindowSurfaceSettings | null = null
+
+ // What a person reads on it. Born from the program, the window's
+ // own afterwards.
+ public title: string
+
+ // Where the frame is filled from, when it is not the program asset route: a
+ // client half may name a URL instead of a directory, which is what
+ // lets a program under development be shown from its own dev server.
+ public readonly url: string | null
+
+ // The Window's authoritative runtime layer. `wallpaper` can only be
+ // assigned by the system's dedicated wallpaper launch path.
+ public readonly layer: WindowLayer
+
+ // Which of the half's own pages the frame opens on.
+ public readonly location: string
+
+ public constructor(shown: Shown, position: Position, size: Size, depth: number, minimized: boolean) {
+
+ this.title = shown.title
+
+ this.url = shown.url
+
+ this.layer = shown.layer
+
+ this.location = shown.location
+
+ this.position = position
+
+ this.size = size
+
+ validate(position.x, "x")
+
+ validate(position.y, "y")
+
+ validate(size.width, "width")
+
+ validate(size.height, "height")
+
+ this.depth = depth
+
+ this.minimized = minimized
+ }
+
+ // ── The primitives, and each does only its own work ──────────────
+ //
+ // Geometry, visibility and order are three questions, and no word
+ // here answers two of them. A window that is moved while hidden is
+ // moved; showing it again shows it where it now is, because nothing
+ // was remembered to put it back to. Raising a hidden window changes
+ // where it will appear, not whether it appears.
+ //
+ // Filling the surface used to be an act with a name, and a name
+ // needed a memory: `previousPosition` and `previousSize` existed to
+ // undo `maximize` and were read by nothing else. Both are gone. A
+ // window that wants the whole surface asks for the whole surface —
+ // and the button that does it in the interface keeps its own memory
+ // of where the window was, which is the window manager's business
+ // and not the system's.
+ public move(position: Position) {
+
+ validate(position.x, "x")
+
+ validate(position.y, "y")
+
+ this.position = position
+ }
+
+ public resize(size: Size) {
+
+ validate(size.width, "width")
+
+ validate(size.height, "height")
+
+ this.size = size
+ }
+
+ public changeTitle(title: string) {
+
+ const said = String(title ?? "").trim()
+
+ if (!said) throw new Error("A window's title is something a person can read")
+
+ this.title = said
+ }
+
+ public setSurface(value: unknown) {
+
+ const surface = validateSurface(value)
+
+ if (sameSurface(this.surface, surface)) return false
+
+ this.surface = surface
+
+ return true
+ }
+
+ public removeSurface() {
+
+ if (this.surface === null) return false
+
+ this.surface = null
+
+ return true
+ }
+
+ public toJSON() {
+
+ return {
+
+ title: this.title,
+
+ url: this.url,
+
+ layer: this.layer,
+
+ location: this.location,
+
+ position: this.position,
+
+ size: this.size,
+
+ depth: this.depth,
+
+ minimized: this.minimized,
+
+ surface: this.surface
+ }
+ }
+}
+
+function validateSurface(value: unknown): WindowSurfaceSettings {
+
+ if (value === undefined) return Object.freeze({})
+
+ const record = plain(value, "Surface settings")
+
+ fields(record, ["opacity", "radius", "transaction"], "Surface settings")
+
+ const surface: { opacity?: number, radius?: ScaleLevel | number | "full", transaction?: WindowSurfaceTransaction } = {}
+
+ if ("opacity" in record) {
+
+ if (!finite(record.opacity) || record.opacity < 0 || record.opacity > 1) throw new Error("Surface opacity must be a finite number from 0 to 1")
+
+ surface.opacity = record.opacity
+ }
+
+ if ("radius" in record) {
+
+ if (record.radius !== "full" && !isScaleLevel(record.radius) && (!finite(record.radius) || record.radius < 0)) throw new Error('Surface radius must be a ScaleLevel, a finite nonnegative pixel number, or "full"')
+
+ surface.radius = record.radius
+ }
+
+ if ("transaction" in record) surface.transaction = validateTransaction(record.transaction)
+
+ return Object.freeze(surface)
+}
+
+function validateTransaction(value: unknown): WindowSurfaceTransaction {
+
+ const record = plain(value, "Surface transaction")
+
+ fields(record, ["duration", "easing"], "Surface transaction")
+
+ const transaction: { duration?: number, easing?: WindowSurfaceEasing } = {}
+
+ if ("duration" in record) {
+
+ if (!finite(record.duration) || record.duration < 0 || record.duration > 60_000) throw new Error("Surface transaction duration must be finite milliseconds from 0 to 60000")
+
+ transaction.duration = record.duration
+ }
+
+ if ("easing" in record) transaction.easing = validateEasing(record.easing)
+
+ return Object.freeze(transaction)
+}
+
+function validateEasing(value: unknown): WindowSurfaceEasing {
+
+ if (value === "linear" || value === "ease" || value === "ease-in" || value === "ease-out" || value === "ease-in-out") return value
+
+ if (!Array.isArray(value) || value.length !== 4 || !value.every(finite) || value[0] < 0 || value[0] > 1 || value[2] < 0 || value[2] > 1) throw new Error("Surface transaction easing must be a standard easing name or four cubic Bézier numbers with x values from 0 to 1")
+
+ return Object.freeze([...value]) as [number, number, number, number]
+}
+
+function plain(value: unknown, name: string): Record<string, unknown> {
+
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error(`${name} must be an object`)
+
+ const prototype = Object.getPrototypeOf(value)
+
+ if (prototype !== Object.prototype && prototype !== null) throw new Error(`${name} must be an object`)
+
+ return value as Record<string, unknown>
+}
+
+function fields(record: Record<string, unknown>, allowed: string[], name: string) {
+
+ const unknown = Object.keys(record).find(field => !allowed.includes(field))
+
+ if (unknown) throw new Error(`${name} has no "${unknown}" field`)
+}
+
+function finite(value: unknown): value is number {
+
+ return typeof value === "number" && Number.isFinite(value)
+}
+
+function sameSurface(left: WindowSurfaceSettings | null, right: WindowSurfaceSettings) {
+
+ return JSON.stringify(left) === JSON.stringify(right)
+}
+
+// A value is pixels or one linear relative expression; anything else is
+// refused where it is written, not where it is rendered.
+function validate(value: Value, name: string) {
+
+ if (isRelativeValue(value)) return
+
+ throw new Error(`${name} must be a finite pixel number or a relative expression such as "50% + 10"`)
+}
+
+export type TransmittedWindow = Transmitted<Window>
+
+export type { Position, Size, Value } from "@phreshos/core"
diff --git a/source/server/core/link-manager/auth-manager/program-manager/config.ts b/source/server/core/link-manager/auth-manager/program-manager/config.ts
new file mode 100644
index 0000000..7409c0b
--- /dev/null
+++ b/source/server/core/link-manager/auth-manager/program-manager/config.ts
@@ -0,0 +1,117 @@
+import { type Layer, type Position, type Size } from "@phreshos/core"
+
+/**
+ * What a program says it is.
+ *
+ * A description, and nothing that acts. It arrives either as a
+ * `program.json` beside the things it names, or as an object built in
+ * code — a program the system owns has no file to be read from.
+ *
+ * The union is the contract's one hard rule wearing a type: a program
+ * has a server half, a client half, or both, and a description with
+ * neither cannot be written down.
+ */
+export type ProgramConfig = (Described & { server: ServerConfig, client?: ClientConfig }) | (Described & { server?: ServerConfig, client: ClientConfig })
+
+interface Described {
+
+ // What addresses it. Kebab-case, because it is also the name of the
+ // directory the system lays the program out in — so it is a path
+ // component, and every path component from outside is checked.
+ //
+ // Never shown. What a person reads is `name`, and keeping the two
+ // apart is what every operating system does — an identifier that is
+ // also a label ends up being one or the other badly.
+ identity: string
+
+ // What a person reads. Free-form, addresses nothing, and absent
+ // means the identity serves for both.
+ name?: string
+
+ version?: string
+
+ description?: string
+
+ // The official Markdown entry point to this Program's API. It is a path
+ // here, but paths never cross into an SDK; Program.apiDocs() returns only
+ // its contents. Installed descriptions name the canonical api-docs.md.
+ apiDocs?: string
+
+ // One PNG source from which hosting derives every standard size. How a
+ // Program is shown belongs to the Program rather than its client half — a
+ // headless Program is shown too.
+ icon?: string
+
+ // Where it keeps what it keeps. Absent means the system decides.
+ storage?: string
+}
+
+export interface ServerConfig {
+
+ // Where this half is. Empty names the program's own root.
+ location: string
+
+ // Whether a Process starts this endpoint by default. True when omitted.
+ start?: boolean
+
+ // Run once before the program is first started, in that directory.
+ installCommand?: string
+
+ // Run to start a process, in that directory.
+ startCommand: string
+}
+
+export interface ClientConfig {
+
+ // Where this half is: a directory holding index.html, or a URL.
+ // Empty names the program's own root. For a URL, its last slash
+ // ends the launch root and the remainder is the default location.
+ // Not `path`, because a path cannot be a URL and this is one field
+ // with both readings — which is what lets a program under
+ // development be framed from a live dev server.
+ location: string
+
+ // Whether a Process starts this endpoint by default. True when omitted.
+ start?: boolean
+
+ // What its window is called when it opens. The window owns its title
+ // from then on and may change it; this is what it is born with, so
+ // there is no moment of showing the wrong thing while the half
+ // starts. Absent means the program's own name.
+ title?: string
+
+ // How its window opens. Absent means the system decides.
+ size?: Size
+
+ position?: Position
+
+ // Which of the desktop's three layers its window lives in, and so
+ // whether it is a window at all.
+ //
+ // `window` is one: in the taskbar, wearing the system's chrome,
+ // focused by a click before the click reaches the program. The other
+ // two are not — no taskbar entry, no paint of any kind, no controls,
+ // and no click-catcher — so a program's own content is the whole of
+ // what is on the screen. `under` sits below every window and can
+ // never rise above one; `over` sits above every window and none can
+ // rise above it. The taskbar is above all three.
+ //
+ // Absent means `window`, said as an absence rather than written down
+ // twice: what a description leaves unsaid, the system decides.
+ layer?: Layer
+
+ // Whether its window opens hidden. Absent means shown.
+ //
+ // A state at birth rather than an act to perform afterwards: a
+ // program that opens hidden and shows itself when it is ready has
+ // nothing to undo, where one that opens shown and hides itself has
+ // already been seen.
+ minimize?: boolean
+}
+
+export { layers, type Layer, type Position, type Size, type Value } from "@phreshos/core"
+
+// An identity is a directory's name before it is anything else.
+export const kebab = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
+
+export { isRelativeValue as isValue } from "@phreshos/core"
diff --git a/source/server/core/link-manager/auth-manager/program-manager/entry.ts b/source/server/core/link-manager/auth-manager/program-manager/entry.ts
new file mode 100644
index 0000000..a5e0d91
--- /dev/null
+++ b/source/server/core/link-manager/auth-manager/program-manager/entry.ts
@@ -0,0 +1,57 @@
+import { Transmitted } from "@libs/superjson"
+import Program from "./program"
+
+/**
+ * One program in the runtime registry. Installation is a state of this
+ * same record, never membership in a second collection.
+ */
+export default class Entry {
+
+ public readonly program: Program
+
+ public installed: boolean
+
+ public constructor(program: Program, installed = true) {
+
+ this.program = program
+
+ this.installed = installed
+ }
+
+ public get identity() {
+
+ return this.program.identity
+ }
+
+ // What crosses: what a program says it is, and what a session needs
+ // to draw it. Never a path — a browser has no disk, and where this
+ // machine put things is not a program's own word about itself.
+ public record() {
+
+ return {
+
+ ...this.program.record(),
+
+ installed: this.installed
+ }
+ }
+
+ // Only the trusted desktop needs the private route that hosts this
+ // program's files. It is deliberately absent from `toJSON`, which is
+ // also what crosses into program SDKs.
+ public hosted() {
+
+ return { ...this.record(), assetId: this.program.assetId }
+ }
+
+ public toJSON() {
+
+ return this.record()
+ }
+}
+
+export type ProgramRecord = ReturnType<Entry["record"]>
+
+export type HostedEntry = ReturnType<Entry["hosted"]>
+
+export type TransmittedEntry = Transmitted<ProgramRecord>
diff --git a/source/server/core/link-manager/auth-manager/program-manager/icon.ts b/source/server/core/link-manager/auth-manager/program-manager/icon.ts
new file mode 100644
index 0000000..913d550
--- /dev/null
+++ b/source/server/core/link-manager/auth-manager/program-manager/icon.ts
@@ -0,0 +1,141 @@
+import { stat } from "node:fs/promises"
+import { type ProgramIconSize } from "@phreshos/core"
+import type Program from "./program"
+import sharp from "sharp"
+
+export const iconSizes = {
+
+ small: 32,
+
+ medium: 64,
+
+ large: 128
+
+} as const
+
+export type IconSize = ProgramIconSize
+
+export function isIconSize(value: unknown): value is IconSize {
+
+ return typeof value === "string" && value in iconSizes
+}
+
+export const iconSource = {
+
+ minimum: 128,
+
+ maximum: 2_048,
+
+ maximumBytes: 5 * 1_024 * 1_024
+
+} as const
+
+/** Verify the one source image before a Program is accepted. */
+export async function validateIcon(path: string) {
+
+ const information = await stat(path).catch(() => null)
+
+ if (!information?.isFile()) throw new Error(`The icon file is not there: ${path}`)
+
+ if (information.size > iconSource.maximumBytes) throw new Error(`A Program icon cannot exceed ${iconSource.maximumBytes / 1_024 / 1_024} MiB`)
+
+ let metadata: Awaited<ReturnType<ReturnType<typeof sharp>["metadata"]>>
+
+ try {
+
+ metadata = await sharp(path, { failOn: "error", limitInputPixels: iconSource.maximum ** 2 }).metadata()
+ }
+
+ catch { throw new Error(`The Program icon is not a valid PNG: ${path}`) }
+
+ if (metadata.format !== "png") throw new Error(`The Program icon must be a PNG: ${path}`)
+
+ const width = metadata.width ?? 0
+
+ const height = metadata.height ?? 0
+
+ if (width < iconSource.minimum || height < iconSource.minimum) throw new Error(`A Program icon must be at least ${iconSource.minimum} pixels in both dimensions`)
+
+ if (width > iconSource.maximum || height > iconSource.maximum) throw new Error(`A Program icon cannot exceed ${iconSource.maximum} pixels in either dimension`)
+}
+
+/** Lazily render each standard representation no more than once. */
+export class IconRenderer {
+
+ private validation: Promise<void> | null = null
+
+ private readonly rendered = new Map<IconSize, Promise<Buffer>>()
+
+ public constructor(private readonly path: string) {}
+
+ public render(size: IconSize) {
+
+ const existing = this.rendered.get(size)
+
+ if (existing) return existing
+
+ const rendering = this.create(size)
+
+ this.rendered.set(size, rendering)
+
+ return rendering
+ }
+
+ private async create(size: IconSize) {
+
+ this.validation ??= validateIcon(this.path)
+
+ await this.validation
+
+ const length = iconSizes[size]
+
+ return await sharp(this.path, { failOn: "error", limitInputPixels: iconSource.maximum ** 2 })
+
+ .resize(length, length, { fit: "contain", background: { r: 0, g: 0, b: 0, alpha: 0 } })
+
+ .png()
+
+ .toBuffer()
+ }
+}
+
+interface CachedRenderer {
+
+ revision: number
+
+ renderer: IconRenderer
+}
+
+/**
+ * The authoritative, bounded icon renderer shared by every delivery road.
+ * Runtime Programs own at most three buffers; every omitted icon shares the
+ * same default renderer, and forgotten Programs leave this WeakMap naturally.
+ */
+export class ProgramIcons {
+
+ private readonly fallback: IconRenderer
+
+ private readonly programs = new WeakMap<Program, CachedRenderer>()
+
+ public constructor(defaultIcon: string) {
+
+ this.fallback = new IconRenderer(defaultIcon)
+ }
+
+ public async render(program: Program, size: IconSize) {
+
+ const path = program.iconPath
+
+ if (!path) return await this.fallback.render(size)
+
+ const cached = this.programs.get(program)
+
+ const renderer = cached?.revision === program.revision ? cached.renderer : new IconRenderer(path)
+
+ if (renderer !== cached?.renderer) this.programs.set(program, { revision: program.revision, renderer })
+
+ // A source can disappear after Program validation. The icon contract
+ // remains total, so this external filesystem race uses the default.
+ return await renderer.render(size).catch(() => this.fallback.render(size))
+ }
+}
diff --git a/source/server/core/link-manager/auth-manager/program-manager/logs.ts b/source/server/core/link-manager/auth-manager/program-manager/logs.ts
new file mode 100644
index 0000000..db8c7d3
--- /dev/null
+++ b/source/server/core/link-manager/auth-manager/program-manager/logs.ts
@@ -0,0 +1,281 @@
+import { DatabaseSync } from "node:sqlite"
+import { existsSync, mkdirSync } from "node:fs"
+import { dirname } from "node:path"
+
+/**
+ * What a program's halves have said, kept.
+ *
+ * A program says something and it is kept. Server pipes arrive as raw
+ * stdout and stderr; a client endpoint mirrors the console through its
+ * private boundary. Neither is a request: recording is best-effort and
+ * can never delay or disturb the program that produced it.
+ *
+ * Which is also why reading opens its own connection **read-only**. Not
+ * a rule that a query must begin with `select`, which would mean parsing
+ * SQL and being right about it forever — a property of the handle, which
+ * the database enforces whatever arrives.
+ *
+ * It lives at `storage/logs.sqlite`, beside the `store.sqlite` this
+ * copies: a thing the system manages, that the program has no word for,
+ * that survives an update because everything under `storage` does, and
+ * that goes with `uninstall(true)`. Nothing new had to be said anywhere
+ * for any of that.
+ *
+ * **The system is the only writer.** Every process of every program
+ * writes through the core, so nothing here contends and a line's rowid
+ * is the order the system drained it — which is the only order it can
+ * honestly claim, two pipes having no order between them.
+ */
+export default class Logs {
+
+ private readonly path: string
+
+ private writer: DatabaseSync | null = null
+
+ private ready = false
+
+ // What a process has said without a newline to end it. A pipe hands
+ // over chunks that do not align to lines, so a line is complete when
+ // the program says it is; the rest waits here for the next chunk or
+ // for the end of the process, and neither of those is a clock.
+ private readonly partial = new Map<string, string>()
+
+ private readonly queued: LogRow[] = []
+
+ private scheduled = false
+
+ // How many rows a program keeps. Old ones go rather than a program
+ // growing without end — bounded because this is a record of the
+ // recent past, and a machine that fills its disk with what a chatty
+ // program said is a machine that stops.
+ private static readonly keeps = 20_000
+
+ // Not every write: dropping the oldest is itself writes, so it is
+ // paid every so often rather than per line, and the count is what
+ // says when — a number of rows, not a length of time.
+ private static readonly sweepEvery = 500
+
+ private since = 0
+
+ public constructor(path: string) {
+
+ this.path = path
+ }
+
+ // Opened when there is something to say. A program that never runs
+ // never gets a file, which is what makes an empty storage directory
+ // stay empty.
+ private open() {
+
+ if (this.writer) return this.writer
+
+ mkdirSync(dirname(this.path), { recursive: true })
+
+ const database = new DatabaseSync(this.path)
+
+ try {
+
+ // Writes and reads do not block each other, and a reader sees a
+ // consistent database while a program is mid-sentence.
+ database.exec("pragma journal_mode = wal")
+
+ this.prepare(database)
+ }
+
+ catch (exception) {
+
+ database.close()
+
+ throw exception
+ }
+
+ this.writer = database
+
+ this.ready = true
+
+ return database
+ }
+
+ private prepare(database: DatabaseSync) {
+
+ const columns = database.prepare("pragma table_info(logs)").all() as { name: string }[]
+
+ if (!columns.length) {
+
+ database.exec("create table logs (createdAt integer not null, process text not null, source text not null, kind text not null, content text not null)")
+
+ database.exec("create index logs_process on logs (process)")
+
+ return
+ }
+
+ const expected = ["createdAt", "process", "source", "kind", "content"]
+
+ if (columns.map(column => column.name).join("\0") !== expected.join("\0")) throw new Error("The logs database has an unsupported schema")
+
+ database.exec("create index if not exists logs_process on logs (process)")
+ }
+
+ // What arrived on a pipe, as lines. `\r\n` loses its carriage return
+ // with its newline: both are the delimiter, and neither is what the
+ // program printed.
+ public printed(process: string, source: "stdout" | "stderr", chunk: string) {
+
+ const held = `${this.partial.get(`${process}:${source}`) ?? ""}${chunk}`
+
+ const lines = held.split("\n")
+
+ this.partial.set(`${process}:${source}`, lines.pop() ?? "")
+
+ this.enqueue(lines.map(line => [process, "server", source, line.endsWith("\r") ? line.slice(0, -1) : line] as const))
+ }
+
+ /** Keep one already-complete record without ever making logging a request. */
+ public record(process: string, source: LogSource, kind: string, content: string) {
+
+ this.enqueue([[process, source, kind, content]])
+ }
+
+ // The end of one endpoint incarnation, and the last thing said by it.
+ //
+ // Always last for that incarnation, which is a fact worth having even
+ // though a later launch may append new rows for the same Process. What a
+ // server was holding unfinished is put down first — an endpoint that
+ // printed without a newline and then died said that, and it is often the
+ // sentence that matters.
+ public endpointExited(process: string, source: LogSource, code: number | null, signal: string | null) {
+
+ const rest: LogRow[] = []
+
+ for (const stream of source === "server" ? ["stdout", "stderr"] as const : [] as const) {
+
+ const held = this.partial.get(`${process}:${stream}`)
+
+ if (held) rest.push([process, "server", stream, held])
+
+ this.partial.delete(`${process}:${stream}`)
+ }
+
+ this.enqueue([...rest, [process, source, "exit", JSON.stringify({ code, signal })]])
+ }
+
+ private enqueue(rows: LogRow[]) {
+
+ if (!rows.length) return
+
+ this.queued.push(...rows)
+
+ if (this.scheduled) return
+
+ this.scheduled = true
+
+ queueMicrotask(() => {
+
+ this.scheduled = false
+
+ this.write(this.queued.splice(0))
+ })
+ }
+
+ private write(rows: LogRow[]) {
+
+ if (!rows.length) return
+
+ try {
+
+ const database = this.open()
+
+ const at = Date.now()
+
+ const insert = database.prepare("insert into logs (createdAt, process, source, kind, content) values (?, ?, ?, ?, ?)")
+
+ for (const [process, source, kind, content] of rows) insert.run(at, process, source, kind, content)
+
+ this.since += rows.length
+
+ if (this.since >= Logs.sweepEvery) this.sweep(database)
+ }
+
+ // A log is never work the producer is waiting on. A full disk, a
+ // closed database or a malformed file drops this emission and
+ // changes nothing about the Process that produced it.
+ catch { /* best-effort by contract */ }
+ }
+
+ private sweep(database: DatabaseSync) {
+
+ this.since = 0
+
+ // Everything older than the newest `keeps` rows. One statement,
+ // so the whole drop is one transaction and a reader never sees
+ // half of it.
+ database.prepare("delete from logs where rowid <= (select rowid from logs order by rowid desc limit 1 offset ?)").run(Logs.keeps)
+ }
+
+ /**
+ * Asked, and never told.
+ *
+ * The connection is read-only, so `insert`, `delete` and `create`
+ * are refused by the database rather than by anything here reading
+ * the SQL and deciding. A program may say whatever it likes; it
+ * cannot change what it said.
+ *
+ * A fresh connection each time rather than one held open: a query is
+ * a moment, and a reader that outlives its answer is a handle
+ * somebody has to remember to close. Opening is cheap and the file
+ * is local.
+ */
+ public query(sql: string, values: unknown[] = []) {
+
+ // A program that has never printed has no file, and a read-only
+ // connection will not make one. Answered with nothing, which is
+ // what it said.
+ if (!existsSync(this.path)) return []
+
+ if (!this.ready) {
+
+ const writable = new DatabaseSync(this.path)
+
+ try {
+
+ this.prepare(writable)
+
+ this.ready = true
+ }
+
+ finally { writable.close() }
+ }
+
+ const database = new DatabaseSync(this.path, { readOnly: true })
+
+ try { return database.prepare(sql).all(...values as never[]).map(row => ({ ...row })) }
+
+ finally { database.close() }
+ }
+
+ // Closed because the file is about to go, or has. An open handle to
+ // a deleted file is a handle to something nobody can reach, and the
+ // next install would open a second one beside it.
+ public close() {
+
+ const writer = this.writer
+
+ this.writer = null
+
+ this.ready = false
+
+ try { writer?.close() }
+
+ catch { /* logging cleanup cannot obstruct Program cleanup */ }
+
+ this.partial.clear()
+
+ this.queued.length = 0
+
+ this.scheduled = false
+ }
+}
+
+export type LogSource = "client" | "server"
+
+type LogRow = readonly [process: string, source: LogSource, kind: string, content: string]
diff --git a/source/server/core/link-manager/auth-manager/program-manager/permissions.ts b/source/server/core/link-manager/auth-manager/program-manager/permissions.ts
new file mode 100644
index 0000000..6368bad
--- /dev/null
+++ b/source/server/core/link-manager/auth-manager/program-manager/permissions.ts
@@ -0,0 +1,46 @@
+import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"
+import { randomUUID } from "node:crypto"
+import { join } from "node:path"
+import type Program from "./program"
+import { isPermissionName, type PermissionDecisions } from "@phreshos/core"
+
+const file = "permissions.json"
+
+/** Reads one Program's system-managed persistent permission decisions. */
+export function readPermissions(program: Program): PermissionDecisions {
+ const path = join(program.storagePath, file)
+
+ if (!existsSync(path)) return {}
+
+ const parsed = JSON.parse(readFileSync(path, "utf8")) as unknown
+
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("The Program permissions file is invalid")
+
+ const entries = Object.entries(parsed)
+
+ const permissions: PermissionDecisions = {}
+
+ for (const [name, value] of entries) {
+
+ if (!isPermissionName(name) || typeof value !== "boolean") throw new Error("The Program permissions file is invalid")
+
+ permissions[name] = value
+ }
+
+ return permissions
+}
+
+/** Atomically replaces one Program's persistent permission decisions. */
+export function writePermissions(program: Program, permissions: PermissionDecisions) {
+
+ mkdirSync(program.storagePath, { recursive: true })
+
+ const path = join(program.storagePath, file)
+ const temporary = join(program.storagePath, `.${file}.${randomUUID()}`)
+
+ try {
+ writeFileSync(temporary, `${JSON.stringify(permissions, null, 2)}\n`)
+ renameSync(temporary, path)
+ }
+ finally { rmSync(temporary, { force: true }) }
+}
diff --git a/source/server/core/link-manager/auth-manager/program-manager/program-manager.ts b/source/server/core/link-manager/auth-manager/program-manager/program-manager.ts
new file mode 100644
index 0000000..d89800f
--- /dev/null
+++ b/source/server/core/link-manager/auth-manager/program-manager/program-manager.ts
@@ -0,0 +1,1305 @@
+import { copyFileSync, cpSync, existsSync, mkdirSync, mkdtempSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs"
+import { Connect } from "@libs/the-link/decorators/escript"
+import { spawn } from "node:child_process"
+import { randomUUID } from "node:crypto"
+import TheLink from "@libs/the-link/the-link"
+import SqliteDatabase from "@libs/sqlite-database"
+import { Transmitted } from "@libs/superjson"
+import FileManager from "@libs/file-manager"
+import FileArea from "@libs/file-area"
+import openStore from "@server/core/open-store"
+import AuthManager from "../auth-manager"
+import { dirname, isAbsolute, join } from "node:path"
+import Logs, { type LogSource } from "./logs"
+import { isValue, layers, type Layer, type Position, type ProgramConfig, type Size } from "./config"
+import { type PermissionName, type WallpaperLaunch } from "@phreshos/core"
+import { type default as Process, type Stream } from "../process-manager/process"
+import { type StandardShape, type WallpaperShape } from "../process-manager/process-manager"
+import Program from "./program"
+import Entry, { type HostedEntry } from "./entry"
+import Keyv from "keyv"
+import { isIconSize, ProgramIcons } from "./icon"
+import { readStartup, removeStartup, writeStartup } from "./startup"
+import { readPermissions, writePermissions } from "./permissions"
+
+const maximumProcessesPerProgram = 20
+
+/**
+ * Every program this runtime knows, in one map keyed by its public
+ * identity. Installation is a flag on the record; it changes persistence,
+ * never which collection contains the program.
+ */
+export default class ProgramManager extends TheLink {
+
+ public readonly authManager: AuthManager
+
+ public readonly fileManager: FileManager
+
+ public readonly programs = new Map<string, Entry>()
+
+ // One lifecycle transition per public identity. Besides preventing
+ // two installs from replacing the same files at once, this keeps an
+ // identity reserved until its final forget announcement has crossed
+ // the trusted link. A new occupant can therefore never be erased by
+ // the previous occupant's late echo.
+ private readonly changing = new Map<string, Promise<void>>()
+
+ // What each program remembers about itself, opened on first use and
+ // kept by the identity of the program that asked.
+ private readonly opened = new Map<string, Keyv>()
+
+ // What each program's halves have said. Opened like the store above
+ // and dropped in the same place, because it is the same kind of
+ // thing: kept under `storage`, managed by the system, with no word
+ // in the program's own vocabulary for writing it.
+ private readonly said = new Map<string, Logs>()
+
+ // And each program's own database — the third file under `storage`,
+ // and the only one of the three the program writes itself.
+ private readonly kept = new Map<string, SqliteDatabase>()
+
+ private readonly icons: ProgramIcons
+
+ public constructor(authManager: AuthManager) {
+
+ super()
+
+ this.fileManager = authManager.linkManager.application.storage.navigateTo("programs")
+
+ this.authManager = authManager
+
+ this.icons = new ProgramIcons(authManager.linkManager.application.defaultProgramIcon)
+
+ this.connectTo(this.authManager, "/program")
+ }
+
+ /** Reconstruct every valid installed Program before the host is exposed. */
+ public async initialize() {
+
+ // What the system laid out, it can find again — by name, which is
+ // what the directory is. A directory that no longer holds a
+ // program is left where it is rather than guessed at.
+ for (const found of readdirSync(this.fileManager.path, { withFileTypes: true })) {
+
+ if (!found.isDirectory()) continue
+
+ const declaration = this.fileManager.join(found.name, "program.json")
+
+ if (!existsSync(declaration)) continue
+
+ try {
+
+ await this.register(new Program(declaration), true, true)
+ }
+
+ catch (exception) { console.log(`programs: ${found.name} was not read — ${exception instanceof Error ? exception.message : "unreadable"}`) }
+ }
+
+ // Registration establishes the complete Program registry first. Read
+ // every startup declaration before executing any of them as well, so
+ // one early Server cannot rewrite what a later Program was going to do
+ // during this same boot.
+ const starting: [Program, Launch][] = []
+
+ for (const entry of this.programs.values()) {
+
+ try {
+
+ const launch = await this.startup(entry.program, "get")
+
+ if (launch) starting.push([entry.program, launch])
+ }
+
+ catch (exception) { console.log(`programs: ${entry.identity} did not start — ${exception instanceof Error ? exception.message : "unreadable startup settings"}`) }
+ }
+
+ // One invalid or impossible launch cannot prevent its neighbours or
+ // the system itself from starting.
+ for (const [program, launch] of starting) {
+
+ try { await this.start(program, launch) }
+
+ catch (exception) { console.log(`programs: ${program.identity} did not start — ${exception instanceof Error ? exception.message : "invalid startup settings"}`) }
+ }
+
+ }
+
+ public find(identity: string) {
+
+ const entry = this.programs.get(identity)
+
+ if (!entry) throw new Error("The system does not know this program")
+
+ return entry
+ }
+
+ /** Reads one persistent permission decision without creating storage. */
+ public permission(program: Program, name: PermissionName) {
+
+ return readPermissions(program)[name]
+ }
+
+ /** Returns an independent snapshot of one Program's persistent decisions. */
+ public permissions(program: Program) {
+
+ return readPermissions(program)
+ }
+
+ /** Stores one persistent permission decision. */
+ public setPermission(program: Program, name: PermissionName, value: boolean) {
+
+ const permissions = readPermissions(program)
+
+ Object.defineProperty(permissions, name, { configurable: true, enumerable: true, value, writable: true })
+
+ writePermissions(program, permissions)
+
+ this.authManager.processManager.permissionChanged(program, name).catch(() => undefined)
+ }
+
+ /** Removes one persistent permission decision. */
+ public deletePermission(program: Program, name: PermissionName) {
+
+ const permissions = readPermissions(program)
+
+ if (!Object.hasOwn(permissions, name)) return
+
+ delete permissions[name]
+
+ writePermissions(program, permissions)
+
+ this.authManager.processManager.permissionChanged(program, name).catch(() => undefined)
+ }
+
+ public reach(identity: string) {
+
+ return this.programs.get(identity)?.program ?? null
+ }
+
+ // Resolve the browser-only hosting address. This is intentionally a
+ // separate lookup from public identity: stable program identities
+ // must never become stable asset routes.
+ public fromAsset(assetId: string) {
+
+ return [...this.programs.values()].find(entry => entry.program.assetId === assetId)?.program ?? null
+ }
+
+ // A program created in memory. From the moment it exists it is an
+ // ordinary record in the same runtime registry as every installed
+ // program. Only its installed flag differs, so it survives no
+ // restart unless it is installed.
+ //
+ // Everything it names must be absolute. An object's relative paths
+ // resolve against the system's own working directory, which is
+ // decided by whoever started the system and means nothing to the
+ // program that called this — a launched program once wrote storage
+ // into a repository through exactly that resolution. A path form
+ // resolves against the program.json it names, so it only has to be
+ // absolute itself.
+ public async create(source: ProgramConfig | string) {
+
+ if (typeof source === "string") {
+
+ if (!isAbsolute(source)) throw new Error("A program is created from an absolute path — the system's working directory is not the caller's")
+
+ const path = statSync(source, { throwIfNoEntry: false })?.isDirectory() ? join(source, "program.json") : source
+
+ const entry = await this.register(new Program(path), false)
+
+ await this.created(entry)
+
+ return entry.program
+ }
+
+ // Storage is where what it keeps outlives its processes, and
+ // "absent means the system decides" is an installed program's
+ // deal — the system has no directory to decide for a program it
+ // is not holding on disk.
+ if (typeof source.storage !== "string") throw new Error("A created program names its storage")
+
+ for (const [what, place] of [["storage", source.storage], ["apiDocs", source.apiDocs], ["icon", source.icon], ["server", source.server?.location]] as const) {
+
+ if (place === undefined) continue
+
+ if (!isAbsolute(place)) throw new Error(`A created program's ${what} must be an absolute filesystem path`)
+ }
+
+ const client = source.client?.location
+
+ if (client !== undefined && !/^https?:\/\//i.test(client) && !isAbsolute(client)) throw new Error("A created program's client must be an absolute filesystem path or an HTTP(S) URL")
+
+ const entry = await this.register(new Program(source), false)
+
+ await this.created(entry)
+
+ return entry.program
+ }
+
+ public async fork(program: Program, identity: string) {
+
+ const entry = await this.register(program.fork(identity), false)
+
+ await this.created(entry)
+
+ return entry.program
+ }
+
+ private async register(program: Program, installed: boolean, transitionOwnsIdentity = false) {
+
+ await program.validate()
+
+ // The runtime map is the live registry, while an installed
+ // declaration is the durable reservation reconstructed on boot.
+ // Forgetting an installed Program removes the former but cannot
+ // make its identity available to an ordinary create or fork while the
+ // latter still exists. Attached replacement is the one transition
+ // that deliberately owns this identity across both representations.
+ if (this.programs.has(program.identity) || (!transitionOwnsIdentity && (this.changing.has(program.identity) || existsSync(this.fileManager.join(program.identity, "program.json"))))) throw new Error("The system already knows this program identity")
+
+ const entry = new Entry(program, installed)
+
+ this.programs.set(entry.identity, entry)
+
+ return entry
+ }
+
+ // Creation is one fact about a Program, emitted after it enters the
+ // map and before any of its processes can be created. Installed
+ // programs reconstructed in the constructor are initial state, not
+ // replayed event history, so only runtime registrations use this.
+ private async created(entry: Entry) {
+
+ await this.authManager.processManager.announce("programCreate", entry.identity, entry.program.reference, entry)
+
+ await this.$outbound.publish("/create", entry.hosted())
+ }
+
+ private async change<T>(identity: string, operation: () => Promise<T>) {
+
+ if (this.changing.has(identity)) throw new Error("This program is already changing")
+
+ let finish: () => void = () => undefined
+
+ // What observers await is the whole transition, including releasing
+ // the identity lock. Awaiting the operation alone allowed an attached
+ // exit to resume in the narrow interval before `finally` removed it.
+ const changing = new Promise<void>(settle => { finish = settle })
+
+ this.changing.set(identity, changing)
+
+ try { return await operation() }
+
+ finally {
+
+ if (this.changing.get(identity) === changing) this.changing.delete(identity)
+
+ finish()
+ }
+ }
+
+ // A place is made when it is first wanted, which is also when a
+ // program has something to put in it. Metadata and content meet in
+ // this object even though their transports differ.
+ private areaOf(program: Program, area: Area) {
+
+ return new FileArea(join(program.storagePath, area), `this program's ${area}`)
+ }
+
+ // A program's own store, kept beside what it keeps.
+ private storeOf(program: Program) {
+
+ const already = this.opened.get(program.identity)
+
+ if (already) return already
+
+ const store = openStore(program.storagePath)
+
+ this.opened.set(program.identity, store)
+
+ return store
+ }
+
+ // What this program has said. Its own file under `storage`, so it
+ // survives an update and goes with everything.
+ public logsOf(program: Program) {
+
+ const already = this.said.get(program.identity)
+
+ if (already) return already
+
+ const logs = new Logs(join(program.storagePath, "logs.sqlite"))
+
+ this.said.set(program.identity, logs)
+
+ return logs
+ }
+
+ // A log emission is not an operation the producer waits for. The Program's
+ // own storage is authoritative whether that Program is installed or is an
+ // attached authoring run.
+ public record(program: Program, process: string, source: LogSource, kind: string, content: string) {
+
+ this.logsOf(program).record(process, source, kind, content)
+ }
+
+ // Read, and only ever read. The same word a process says over its
+ // channel and a pane says over the link, because the two roads must
+ // mean the same thing.
+ @Connect("/logs")
+ public async logs(identity: string, sql: string, values: unknown[]) {
+
+ return this.logsOf(this.reachOrRefuse(identity)).query(sql, values)
+ }
+
+ // A program's own database, opened on first use like the managed files
+ // beside it. Its schema belongs entirely to the program: the system
+ // supplies SQLite without creating tables or inventing another query
+ // language. A separate file keeps that authority structurally apart from
+ // the store and logs the system manages for the same program.
+ public databaseOf(program: Program) {
+
+ const already = this.kept.get(program.identity)
+
+ if (already) return already
+
+ const database = new SqliteDatabase(join(program.storagePath, "database.sqlite"))
+
+ this.kept.set(program.identity, database)
+
+ return database
+ }
+
+ // Read and written both: this file is the program's own, which is
+ // the whole of why it is a file of its own.
+ @Connect("/database")
+ public async database(identity: string, sql: string, values: unknown[]) {
+
+ return this.databaseOf(this.reachOrRefuse(identity)).query(sql, values)
+ }
+
+ // The official API entry point is requested, never synchronized. This is
+ // the one authoritative read used by both SDK roads; the desktop derives
+ // the identity from its frame before asking through this connection.
+ @Connect("/api-docs")
+ public async apiDocs(identity: string) {
+
+ return this.reachOrRefuse(identity).apiDocs()
+ }
+
+ /** One authoritative icon operation shared by SDKs and HTTP hosting. */
+ @Connect("/icon")
+ public async icon(identity: string, size: unknown) {
+
+ if (!isIconSize(size)) throw new Error("A Program icon size is small, medium, or large")
+
+ return [...await this.icons.render(this.reachOrRefuse(identity), size)]
+ }
+
+ /** Read or change the system-managed startup launch for one Program. */
+ public async startup(program: Program, operation: string, value?: unknown): Promise<Launch | null | void> {
+
+ if (operation === "get") {
+
+ const launch = readStartup(program)
+
+ if (launch === null) return null
+
+ this.resolveLaunch(program, launch)
+
+ return launch
+ }
+
+ if (operation === "enable") {
+
+ if (!this.installed(program)) throw new Error("Only an installed program can start with the system")
+
+ await program.validate()
+
+ this.resolveLaunch(program, value)
+
+ writeStartup(program, value)
+
+ return
+ }
+
+ if (operation === "disable") {
+
+ removeStartup(program)
+
+ return
+ }
+
+ throw new Error(`The host does not know the startup operation "${operation}"`)
+ }
+
+ // A store's five controls, in one place. Reached from a process
+ // over its own channel and from a session over the link, and both
+ // must mean the same thing. The identity always names a Program;
+ // application persistence has no generic route through this manager.
+ @Connect("/store")
+ public async store(identity: string, operation: string, key: string, value?: unknown, ttl?: number) {
+
+ const store = this.storeOf(this.reachOrRefuse(identity))
+
+ if (operation === "get") return await store.get(key) as unknown
+
+ if (operation === "set") return await store.set(key, value, ttl)
+
+ if (operation === "delete") return await store.delete(key as string | string[])
+
+ if (operation === "has") return await store.has(key)
+
+ if (operation === "clear") return await store.clear()
+
+ throw new Error(`The host does not know the store operation "${String(operation)}"`)
+ }
+
+ // Area metadata reached from a session over the link. Content stays
+ // a byte stream at the storage door; locations remain server-only.
+ @Connect("/area")
+ public async area(identity: string, area: string, operation: string, args: unknown[]) {
+
+ if (area !== "data" && area !== "cache") throw new Error(`The host does not know the place "${String(area)}"`)
+
+ return this.operate(this.reachOrRefuse(identity), area, operation, args)
+ }
+
+ public reachOrRefuse(identity: string) {
+
+ const program = this.reach(identity)
+
+ if (!program) throw new Error("The system does not know this program")
+
+ return program
+ }
+
+ // Client metadata stays in the link as ordinary values and client
+ // content stays a byte stream. A server asks only for `path`, then
+ // performs every operation in its SDK against that root.
+ public operate(program: Program, area: Area, operation: string, args: unknown[]): unknown {
+
+ const place = this.areaOf(program, area)
+
+ const joins = args.map(String)
+
+ if (operation === "path") return place.path
+
+ if (operation === "clear") {
+
+ place.clear()
+
+ return undefined
+ }
+
+ if (operation === "stat") return place.stat(joins)
+
+ // Sorted, so two runs of the same program see the same order and
+ // a program showing a list does not have to sort it again.
+ if (operation === "list") return place.list(joins)
+
+ // Removing a place is `clear`, and one act with two names is how
+ // a program empties everything meaning to remove one thing.
+ if (operation === "delete") {
+
+ place.delete(joins)
+
+ return undefined
+ }
+
+ throw new Error(`The host does not know the storage operation "${operation}"`)
+ }
+
+ public streamArea(identity: string, area: Area, joins: string[]) {
+
+ return this.areaOf(this.reachOrRefuse(identity), area).stream(joins)
+ }
+
+ public async writeArea(identity: string, area: Area, joins: string[], content: ReadableStream<Uint8Array> | null, signal?: AbortSignal) {
+
+ await this.areaOf(this.reachOrRefuse(identity), area).write(joins, content, signal)
+ }
+
+ // ── Installing and uninstalling ──────────────────────────────────
+ //
+ // Installation is the flag on the sole registry record. The files
+ // laid out under its identity are the durable representation of that
+ // state, reconstructed into the same model on boot.
+
+ public installed(program: Program) {
+
+ return this.programs.get(program.identity)?.installed === true
+ }
+
+ // Installation changes every path a process may have remembered, so
+ // validation happens first and every process ends before the live
+ // Program is pointed at its canonical files.
+ @Connect("/install-program")
+ public async installNamed(identity: string, asker: string | null = null) {
+
+ const program = this.reach(identity)
+
+ if (!program) throw new Error("The system does not know this program")
+
+ return await this.install(program, asker)
+ }
+
+ @Connect("/uninstall-program")
+ public async uninstallNamed(identity: string, everything = false, asker: string | null = null) {
+
+ const program = this.reach(identity)
+
+ if (!program) throw new Error("The system does not know this program")
+
+ return await this.uninstall(program, everything, asker)
+ }
+
+ // A local project addresses the durable installation, not a handle it
+ // already holds. Attached use may have replaced or forgotten the runtime
+ // entry while the installed declaration still exists, so this resolves
+ // from the installed area first and reconstructs the runtime counterpart
+ // only when the operation needs one.
+ public async uninstallInstalled(identity: string, everything = false, asker: string | null = null) {
+
+ return await this.change(identity, async () => {
+
+ const declaration = this.fileManager.join(identity, "program.json")
+
+ if (!existsSync(declaration)) throw new Error("This program is not installed — there is nothing here to remove")
+
+ let entry = this.programs.get(identity)
+
+ if (!entry) {
+
+ entry = await this.register(new Program(declaration), true, true)
+
+ await this.created(entry)
+ }
+
+ return await this.uninstallEntry(entry, everything, asker)
+ })
+ }
+
+ @Connect("/forget-program")
+ public async forgetNamed(identity: string, asker: string | null = null) {
+
+ const program = this.reach(identity)
+
+ if (!program) throw new Error("The system does not know this program")
+
+ return await this.forget(program, asker)
+ }
+
+ public async installSource(source: ProgramConfig) {
+
+ const program = new Program(source)
+
+ await program.validate()
+
+ // A runtime Program may have been forgotten while its installed
+ // declaration remains. Replacement is therefore a fact about the
+ // durable files, not the current registry entry's installed flag.
+ const replaced = existsSync(this.fileManager.join(program.identity, "program.json"))
+
+ return { entry: await this.install(program), replaced }
+ }
+
+ public async install(source: Program, asker: string | null = null) {
+
+ return await this.change(source.identity, async () => {
+
+ const home = this.fileManager.join(source.identity)
+
+ const already = existsSync(home)
+
+ // Copied outside the installed files rather than into their place,
+ // so a description that turns out not to be a program has not
+ // taken a working one down on its way to being refused. Kept on
+ // the installed programs area's own filesystem: the final rename is then
+ // local even when the operating-system temp directory is a
+ // separate mount, as it is in Codespaces.
+ const staged = mkdtempSync(join(dirname(this.fileManager.path), `.install-${source.identity}-`))
+
+ const backup = mkdtempSync(join(dirname(this.fileManager.path), `.backup-${source.identity}-`))
+
+ let swapping = false
+
+ let committed = false
+
+ let createdHere = false
+
+ try {
+
+ copy(source, staged)
+
+ // Whether what was copied is a program: asked here, while the
+ // old one is still standing, so a description that turns out
+ // to be lying takes nothing down with it. `laidOut` used to
+ // guard this and no longer can — a copied program's
+ // description says nothing about where its parts are,
+ // because they are wherever the system puts them.
+ await new Program(join(staged, "program.json")).validate()
+
+ // A process may have retained an absolute server,
+ // client, or storage path. Its ending is part of the
+ // install operation, not advice for the caller.
+ if (this.programs.has(source.identity)) await this.authManager.processManager.exitAll(source.identity, asker)
+
+ await this.release(source.identity)
+
+ swapping = true
+
+ mkdirSync(home, { recursive: true })
+
+ for (const what of installedParts) {
+
+ if (existsSync(join(home, what))) renameSync(join(home, what), join(backup, what))
+ }
+
+ for (const what of readdirSync(staged)) renameSync(join(staged, what), join(home, what))
+
+ const installed = new Program(join(home, "program.json"))
+
+ // Preparation runs against the laid-out files but before
+ // the registry claims the install succeeded.
+ await installed.installServer()
+
+ let entry = this.programs.get(source.identity)
+
+ if (entry) {
+
+ entry.program.replace(installed)
+
+ entry.installed = true
+ }
+
+ else {
+
+ entry = await this.register(installed, true, true)
+
+ createdHere = true
+ }
+
+ committed = true
+
+ if (createdHere) await this.created(entry)
+
+ await this.authManager.processManager.announce("programInstall", entry.identity, entry.program.reference, entry)
+
+ // Said to the sessions, though none of them may ask for it.
+ // `@Connect` used to be both the road in and the echo out,
+ // and removing the road took the echo with it — a desktop
+ // that never learns a program arrived is a desktop showing
+ // yesterday's list.
+ await this.$outbound.publish("/install", entry.hosted())
+
+ return entry
+ }
+
+ catch (exception) {
+
+ // Restore the prior program files after any failure in
+ // the swap or install command. Storage never entered the
+ // transaction and is therefore neither copied nor moved.
+ if (swapping && !committed) {
+
+ for (const what of installedParts) rmSync(join(home, what), { recursive: true, force: true })
+
+ for (const what of readdirSync(backup)) renameSync(join(backup, what), join(home, what))
+
+ if (!already && !readdirSync(home).length) rmSync(home, { recursive: true, force: true })
+ }
+
+ throw exception
+ }
+
+ finally {
+
+ rmSync(staged, { recursive: true, force: true })
+
+ rmSync(backup, { recursive: true, force: true })
+ }
+ })
+ }
+
+ // Without `everything`, only the installed description and program
+ // files leave. Processes and open storage handles remain alive. With
+ // it, everything the system owns for this program leaves: processes,
+ // files, storage, and finally the runtime registry entry.
+ public async uninstall(program: Program, everything = false, asker: string | null = null) {
+
+ return await this.change(program.identity, async () => {
+
+ if (!this.installed(program)) throw new Error("This program is not installed — there is nothing here to remove")
+
+ const entry = this.find(program.identity)
+
+ return await this.uninstallEntry(entry, everything, asker)
+ })
+ }
+
+ private async uninstallEntry(entry: Entry, everything: boolean, asker: string | null) {
+
+ if (everything) {
+
+ await this.authManager.processManager.exitAll(entry.identity, asker)
+
+ await this.release(entry.identity)
+ }
+
+ const home = this.fileManager.join(entry.identity)
+
+ if (everything) rmSync(home, { recursive: true, force: true })
+
+ else {
+
+ for (const what of installedParts) rmSync(join(home, what), { recursive: true, force: true })
+
+ if (!readdirSync(home).length) rmSync(home, { recursive: true, force: true })
+ }
+
+ entry.installed = false
+
+ await this.authManager.processManager.announce("programUninstall", entry.identity, entry.program.reference, entry, everything)
+
+ await this.authManager.processManager.announce("uninstall", entry.identity, entry.program.reference, everything)
+
+ await this.$outbound.publish("/uninstall", entry.hosted(), everything)
+
+ if (everything) await this.forgetEntry(entry)
+
+ return entry.identity
+ }
+
+ public async forget(program: Program, asker: string | null = null) {
+
+ return await this.change(program.identity, async () => {
+
+ const entry = this.find(program.identity)
+
+ await this.authManager.processManager.exitAll(program.identity, asker)
+
+ return await this.forgetEntry(entry)
+ })
+ }
+
+ private async forgetEntry(entry: Entry) {
+
+ if (this.programs.get(entry.identity) !== entry) throw new Error("The system no longer knows this program")
+
+ await this.release(entry.identity)
+
+ this.programs.delete(entry.identity)
+
+ await this.authManager.processManager.announce("programForget", entry.identity, entry.program.reference, entry)
+
+ await this.authManager.processManager.announce("forget", entry.identity, entry.program.reference)
+
+ await this.$outbound.publish("/forget", entry.identity)
+
+ return entry.identity
+ }
+
+ private async release(identity: string) {
+
+ const store = this.opened.get(identity)
+
+ this.opened.delete(identity)
+
+ await store?.disconnect()
+
+ this.said.get(identity)?.close()
+
+ this.said.delete(identity)
+
+ this.kept.get(identity)?.close()
+
+ this.kept.delete(identity)
+ }
+
+ @Connect("/create-process")
+ public async createProcess(identity: string, launch: Launch = {}, parent: Process | string | null = null) {
+
+ // Every runtime program, installed or not, is reached through the
+ // same registry. A created process therefore starts from the exact
+ // Program its caller addressed, never from an installed-only view.
+ const program = this.reach(identity)
+
+ if (!program) throw new Error("The system does not know this program")
+
+ const creator = typeof parent === "string" ? this.authManager.processManager.processes.get(parent) : parent
+
+ if (typeof parent === "string" && !creator) throw new Error("The system does not know the parent process")
+
+ return await this.start(program, launch, undefined, creator ?? null)
+ }
+
+ // An attached launch is the local project's authoritative runtime use of
+ // its declared identity. Replacement is one transition: every old process
+ // exits, the old Program is forgotten with its ordinary announcements,
+ // and only then does the new uninstalled Program become reachable. The
+ // installed files, if any, are deliberately untouched and may be installed
+ // over later or reconstructed on the next system start.
+ public async launchAttached(source: ProgramConfig, options: Options, watching: Watching) {
+
+ // Unlike an installed Program, an attached one has no canonical
+ // system-owned directory from which an omitted storage path can be
+ // derived. The authoring tool supplies the project storage explicitly.
+ if (typeof source.storage !== "string") throw new Error("An attached program names its storage")
+
+ if (!isAbsolute(source.storage)) throw new Error("An attached program's storage must be an absolute filesystem path")
+
+ const program = new Program(source)
+
+ // Refuse a bad incoming declaration before taking a coherent existing
+ // Program down. `start` asks again immediately before spawning because
+ // files can move between these two moments.
+ await program.validate()
+
+ return await this.change(program.identity, async () => {
+
+ const existing = this.programs.get(program.identity)
+
+ if (existing) {
+
+ await this.authManager.processManager.exitAll(existing.identity)
+
+ await this.forgetEntry(existing)
+ }
+
+ // This transition owns the identity. In particular, an installed
+ // declaration may still reserve it on disk after its runtime
+ // Program was forgotten; attached use is explicitly allowed to
+ // stand there without deleting or changing that installation.
+ const entry = await this.register(program, false, true)
+
+ try {
+
+ await this.created(entry)
+
+ return await this.start(program, { options }, {
+
+ output: watching.output,
+
+ exited: (code, signal) => {
+
+ // The launcher hears the ending only after the attached
+ // Program has left the registry. Otherwise a command
+ // started immediately afterwards can collide with a life
+ // whose process has already ended.
+ this.finishAttached(program).then(
+
+ () => watching.exited(code, signal),
+
+ () => watching.exited(code, signal)
+ )
+ }
+ }, null, true)
+ }
+
+ catch (exception) {
+
+ if (this.programs.get(program.identity) === entry) {
+
+ await this.authManager.processManager.exitAll(program.identity)
+
+ await this.forgetEntry(entry)
+ }
+
+ throw exception
+ }
+ })
+ }
+
+ private async finishAttached(program: Program) {
+
+ const changing = this.changing.get(program.identity)
+
+ if (changing) await changing
+
+ if (this.programs.get(program.identity)?.program === program) await this.forget(program)
+ }
+
+ // One interpretation of a Process launch, used both when it is created now
+ // and when a future startup launch is persisted. Runtime-only facts such as
+ // name occupancy and capacity remain in `start`.
+ private resolveLaunch(program: Program, value: unknown) {
+
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error("A launch must be a named shape")
+
+ const launch = value as Launch
+
+ if (launch.name !== undefined && (typeof launch.name !== "string" || !launch.name)) throw new Error("A process name must be non-empty text")
+
+ const options = launch.options ?? {}
+
+ if (typeof options !== "object" || options === null || Array.isArray(options) || Object.values(options).some(value => typeof value !== "string")) throw new Error("A launch's options must be text values")
+
+ if (launch.server !== undefined && typeof launch.server !== "boolean") throw new Error("A launch's server must be true or false")
+
+ if (launch.client !== undefined && typeof launch.client !== "boolean" && (typeof launch.client !== "object" || launch.client === null || Array.isArray(launch.client))) throw new Error("A launch's client must be true, false, or a client shape")
+
+ const asked = typeof launch.client === "object" ? launch.client : {}
+
+ if (launch.server === true && !program.server) throw new Error("This program declared no server half — a launch cannot add one")
+
+ if ((launch.client === true || typeof launch.client === "object") && !program.client) throw new Error("This program declared no client half — a launch cannot add one")
+
+ const server = program.server && (launch.server ?? program.server.start) ? program.server : null
+
+ const clientSelected = typeof launch.client === "object" || (launch.client ?? program.client?.start ?? false)
+
+ const client = program.client && clientSelected ? program.client : null
+
+ if (!server && !client) throw new Error("A process must have a server half, a client half, or both")
+
+ // Resolving the Window here validates the same launch grammar even when
+ // the launch is being stored for a later boot. Only the original launch
+ // is persisted; system defaults are derived again when it actually runs.
+ const shape = client ? this.clientShape(program, asked) : null
+
+ return { options, server, client, shape }
+ }
+
+ private async start(program: Program, launch: Launch = {}, watching?: Watching, parent: Process | null = null, transitionOwnsIdentity = false, wallpaper = false) {
+
+ if (!transitionOwnsIdentity && this.changing.has(program.identity)) throw new Error("This program is changing and cannot create a process")
+
+ // A retained Program survives uninstall(false), but its declared
+ // files do not. Refuse before a process identity or window is
+ // allocated, so a failed launch never briefly exists.
+ await program.validate()
+
+ const resolved = this.resolveLaunch(program, launch)
+
+ const { options, server, client } = resolved
+
+ const shape = client ? wallpaper ? this.wallpaperShape(resolved.shape!) : resolved.shape : null
+
+ // Recheck the program-local name immediately before registration,
+ // then create and register without yielding so concurrent launches
+ // cannot both claim it.
+ if (launch.name !== undefined && [...this.authManager.processManager.processes.values()].some(process => process.program === program && process.name === launch.name)) throw new Error("This program already has a process with that name")
+
+ // Capacity belongs to the Program being executed, not to whichever
+ // Process requested the launch. This is the final gate before identity
+ // allocation, endpoint spawning, and synchronous registration; no
+ // concurrent launch can pass it without the preceding one entering the
+ // authoritative Process map first.
+ let active = 0
+
+ for (const process of this.authManager.processManager.processes.values()) {
+
+ if (process.program !== program) continue
+
+ active++
+
+ if (active >= maximumProcessesPerProgram) throw new Error(`This program has reached its limit of ${maximumProcessesPerProgram} active processes`)
+ }
+
+ let identity = randomUUID()
+
+ while (this.authManager.processManager.processes.has(identity)) identity = randomUUID()
+
+ // Kept in this Program's declared storage, whoever is or is not
+ // watching and whether the Program is installed or attached. Each
+ // server incarnation attaches to the same Process-level listeners.
+ const logs = this.logsOf(program)
+
+ const child = server ? this.spawnServer(program) : null
+
+ // Lifecycle consumers are attached before either initial endpoint is
+ // activated, so even a server command that exits immediately has a
+ // complete output and exit record.
+ await this.authManager.processManager.register(identity, launch.name ?? null, program, options, child, client !== null, shape, parent, record => {
+
+ record.onServerStart(server => server.onOutput((stream, text) => logs.printed(identity, stream === "err" ? "stderr" : "stdout", text)))
+
+ record.onServerStop((code, signal) => logs.endpointExited(identity, "server", code, signal))
+
+ record.onClientStop(() => logs.endpointExited(identity, "client", null, null))
+
+ if (watching) {
+
+ record.onServerStart(server => server.onOutput(watching.output))
+
+ record.onExit(watching.exited)
+ }
+ })
+
+ return identity
+ }
+
+ /** Creates the one protected Process representation used as desktop wallpaper. */
+ public async startWallpaper(program: Program, launch: WallpaperLaunch = {}) {
+
+ if (!program.client) throw new Error("A desktop wallpaper Program must declare a Client")
+
+ return await this.start(program, { ...launch, client: launch.client ?? true }, undefined, null, false, true)
+ }
+
+ /** Starts one fresh server endpoint incarnation for a Process. */
+ public spawnServer(program: Program) {
+
+ const server = program.server
+
+ if (!server) throw new Error("This program declared no server half")
+
+ return spawn(server.startCommand, {
+
+ shell: true,
+
+ // One Process owns everything its server command starts.
+ // A separate operating-system group makes that ownership real:
+ // closing the Process can end the whole tree instead of only the
+ // shell at its root.
+ detached: true,
+
+ cwd: program.serverPath!,
+
+ // Always piped, because the system is always the audience.
+ //
+ // This was piped only when somebody was listening: a pipe
+ // nobody reads fills at about 64 KB and the program stops
+ // mid-write, and `stdio` is decided here and once, so an
+ // audience arriving later heard nothing. Both halves of that
+ // stopped being true when the core began keeping what a
+ // program says — it reads, so the pipe drains, and a
+ // listener no longer has to have been there at the start.
+ //
+ // Which also ends the difference between the two ways of
+ // running one: an attached program's output is no longer a
+ // road of its own, it is the same drain with somebody else
+ // also watching.
+ stdio: ["ignore", "pipe", "pipe", "ipc"],
+
+ // Only what the operating system needs to run a command.
+ // No program data travels this way: options and places are
+ // asked for over the channel, which is the one road a
+ // client half can walk too.
+ env: {
+
+ ...process.env,
+
+ PATH: `${join(process.cwd(), "node_modules", ".bin")}:${process.env.PATH}`
+ }
+ })
+ }
+
+ /** Resolves and validates one client endpoint incarnation. */
+ public clientShape(program: Program, asked: LaunchClient = {}): StandardShape {
+
+ const client = program.client
+
+ if (!client) throw new Error("This program declared no client half")
+
+ if (typeof asked !== "object" || asked === null || Array.isArray(asked)) throw new Error("A client launch must be a named shape")
+
+ for (const [what, value] of [["size", asked.size], ["position", asked.position]] as const) {
+
+ if (value === undefined) continue
+
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error(`A launch client's ${what} must name both of its values`)
+
+ const pair = what === "size" ? [value.width, value.height] : [value.x, value.y]
+
+ if (!pair.every(isValue)) throw new Error(`A launch client's ${what} is a finite pixel number or a relative expression such as "50% + 10"`)
+ }
+
+ if (asked.layer !== undefined && !layers.includes(asked.layer)) throw new Error(`A launch client's layer is one of ${layers.join(", ")}`)
+
+ if (asked.location !== undefined && typeof asked.location !== "string") throw new Error("A launch client's location must be text")
+
+ if (asked.minimize !== undefined && typeof asked.minimize !== "boolean") throw new Error("A launch client's minimize state must be true or false")
+
+ const shift = this.authManager.processManager.processes.size % 8 * 32
+
+ return {
+
+ position: asked.position ?? client.position ?? { x: 120 + shift, y: 80 + shift },
+
+ size: asked.size ?? client.size ?? { width: 520, height: 340 },
+
+ layer: asked.layer ?? client.layer ?? "window",
+
+ location: page(asked.location, program.clientLocation),
+
+ minimize: asked.minimize ?? client.minimize ?? false
+ }
+ }
+
+ private wallpaperShape(shape: StandardShape): WallpaperShape {
+
+ return {
+
+ ...shape,
+
+ position: { x: "0/1", y: "0/1" },
+
+ size: { width: "1/1", height: "1/1" },
+
+ layer: "wallpaper",
+
+ minimize: false
+ }
+ }
+
+ public toJSON() {
+
+ return {
+
+ programs: [...this.programs].map(([identity, entry]) => [identity, entry.hosted()] as [string, HostedEntry])
+ }
+ }
+}
+
+export type TransmittedProgramManager = Transmitted<ProgramManager>
+
+// Which of a half's own pages a launch asked for.
+//
+// A launch location is rooted in the client half's declared place,
+// whether that place is the program's assets or a URL directory. The
+// artificial prefix lets the URL parser normalise every spelling of a
+// path before the boundary is checked; what comes back is the client's
+// own location, always beginning at `/` and never naming its root.
+function page(said: string | undefined, fallback: string) {
+
+ if (said === undefined) return fallback
+
+ const root = "http://client.invalid/client/"
+
+ const asked = new URL(said.replace(/^\/+/, ""), root)
+
+ if (!asked.href.startsWith(root)) throw new Error("A client half's location cannot leave its declared root")
+
+ return `/${asked.pathname.slice("/client/".length)}${asked.search}${asked.hash}`
+}
+
+// What a launcher may say at the start. Named rather than ordered,
+// because an order is invisible where it is written — and text, because
+// an option must mean one thing however the process was started, and
+// the command line can only hand over text.
+export type Options = Record<string, string>
+
+// What a launch says in named parts: which declared halves this process
+// has, what it is told, and how this one instance is shown. Ordered
+// arguments would have been invisible at the place they are written,
+// and two anonymous bags in a row is the shape that grows a third.
+export interface Launch {
+
+ // Optional and unique among this program's living processes. It is
+ // a meaningful address; the process identity remains random.
+ name?: string
+
+ // Omitted uses the declaration's default. True starts the declared server
+ // endpoint; false leaves it stopped. Neither can declare a new endpoint.
+ server?: boolean
+
+ // An object starts the declared client endpoint and resolves its Window.
+ client?: boolean | LaunchClient
+
+ options?: Options
+}
+
+// The declaration's own words, all optional, overriding one Process's initial
+// or restarted client endpoint. Not `location` as a place to serve from — the declared
+// client root stays fixed — but as which page beneath it the frame
+// opens on. And not `icon`, which is the program's identity rather
+// than a fact about a launch.
+export interface LaunchClient {
+
+ size?: Size
+
+ position?: Position
+
+ layer?: Layer
+
+ location?: string
+
+ minimize?: boolean
+}
+
+// The two places a program keeps things. One survives an update and one
+// may be emptied at any moment; both are the program's, shared by every
+// process of it.
+export type Area = "data" | "cache"
+
+// Someone listening to a process from outside it. Given at launch
+// because that is when the child's pipes are decided, and they cannot be
+// decided twice.
+export interface Watching {
+
+ output: (stream: Stream, text: string) => void
+
+ exited: (code: number | null, signal: NodeJS.Signals | null) => void
+}
+
+// What a program is, copied to where it is going: the halves it
+// declares, its icon, and the description itself — rewritten so the
+// copy names its parts where they now are rather than where they were.
+//
+// Never `storage`: what a program kept belongs to the place it is kept
+// in, and a copy that carried it would be two programs sharing one
+// memory.
+function copy(program: Program, into: string) {
+
+ const config: Record<string, unknown> = { ...program.config }
+
+ for (const [what, from] of [["server", program.serverPath], ["client", program.clientPath]] as const) {
+
+ // A client half that is a URL has no directory to copy and is
+ // not carried: an installed program's client is its own files.
+ if (what === "client" && program.clientUrl) throw new Error("A program installed here keeps its client at ./client, and a URL is somewhere else entirely")
+
+ if (!from || !existsSync(from)) continue
+
+ cpSync(from, join(into, what), { recursive: true })
+
+ config[what] = { ...config[what] as object, location: what }
+ }
+
+ if (program.iconPath) {
+
+ copyFileSync(program.iconPath, join(into, "icon.png"))
+
+ config.icon = "icon.png"
+ }
+
+ else delete config.icon
+
+ // Unlike a half or icon source this is one file. Installed Programs
+ // nevertheless give it the same canonical shape regardless of where the
+ // author kept it, and the persisted description names that canonical file.
+ if (program.apiDocsPath) {
+
+ cpSync(program.apiDocsPath, join(into, "api-docs.md"))
+
+ config.apiDocs = "api-docs.md"
+ }
+
+ else delete config.apiDocs
+
+ // The description names the places the system chose. Presence is
+ // part of a half's declaration, so its location is never omitted.
+ delete config.storage
+
+ writeFileSync(join(into, "program.json"), JSON.stringify(strip(config), null, 4))
+}
+
+const installedParts = ["server", "client", "icon.png", "api-docs.md", "program.json"] as const
+
+// JSON has no `undefined`, and a key whose value is one would be written
+// as nothing at all — so they are removed rather than left to vanish.
+function strip(value: unknown): unknown {
+
+ if (Array.isArray(value)) return value.map(strip)
+
+ if (typeof value !== "object" || value === null) return value
+
+ return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined).map(([key, entry]) => [key, strip(entry)]))
+}
+
+// An installed program is one the system laid out, so its places are the
+// ones the system lays out. Saying them is allowed — a program.json
+// written by hand may well spell out what it could have left unsaid —
+// but saying anything else is not, because then the system could no
+// longer find any installed program without reading its config first.
diff --git a/source/server/core/link-manager/auth-manager/program-manager/program.ts b/source/server/core/link-manager/auth-manager/program-manager/program.ts
new file mode 100644
index 0000000..d245279
--- /dev/null
+++ b/source/server/core/link-manager/auth-manager/program-manager/program.ts
@@ -0,0 +1,378 @@
+import { ClientConfig, isValue, kebab, layers, Position, ProgramConfig, ServerConfig, Size } from "./config"
+import { accessSync, constants, existsSync, readFileSync, statSync } from "node:fs"
+import { dirname, isAbsolute, resolve } from "node:path"
+import { spawn } from "node:child_process"
+import { randomUUID } from "node:crypto"
+import { validateIcon } from "./icon"
+
+/**
+ * A program: a description, and the things it names.
+ *
+ * It is built either from a `program.json` — in which case every
+ * relative path it declares is relative to that file, because the file
+ * stands in the program's own place — or from an object, in which case
+ * they are relative to the running process, as any tool's paths are. A
+ * program the system builds for itself should therefore name absolute
+ * paths, since the system's own working directory is decided by whoever
+ * started it.
+ *
+ * Being built is a check in itself: a description that contradicts
+ * itself is refused here, so a Program that exists is coherent. Whether
+ * it is *true* — whether the things it names are there — is a different
+ * question, asked when the system is told to rely on it, and asked
+ * again by whatever uses it, because the world moves in between.
+ *
+ * Identity is the program's one public address, whether or not it is
+ * installed. Client files use a separate random address whose only job
+ * is hosting: a stable identity never becomes a stable asset URL.
+ */
+export default class Program {
+
+ public readonly identity: string
+
+ /** Opaque identity of this runtime Program entity. */
+ public readonly reference = randomUUID()
+
+ public readonly assetId = randomUUID()
+
+ /** Changes whenever this runtime Program is replaced in place. */
+ public revision = 0
+
+ // What every relative path is relative to.
+ public root: string
+
+ public config: ProgramConfig
+
+ public constructor(source: string | ProgramConfig, root?: string) {
+
+ const [config, where] = typeof source === "string" ? read(source) : [source, process.cwd()]
+
+ this.config = coherent(config)
+
+ this.identity = this.config.identity
+
+ // Given only when a program is made from another: the same
+ // description standing in the same place, which an object alone
+ // cannot say because an object's relative paths resolve against
+ // whatever directory the system was started in.
+ this.root = root ?? where
+ }
+
+ // The same description and place under an explicitly different
+ // identity. A fork is another program, never an alias for this one.
+ public fork(identity: string) {
+
+ return new Program({ ...this.config, identity }, this.root)
+ }
+
+ // Installation lays the same logical program out in the system's
+ // canonical place. Its public identity and private asset address do
+ // not change; only the description and root it runs from do.
+ public replace(source: Program) {
+
+ if (source.identity !== this.identity) throw new Error("A program cannot change its identity")
+
+ this.config = source.config
+
+ this.root = source.root
+
+ this.revision++
+ }
+
+ // What a person reads. A program that said nothing is read by its
+ // identity, which is why nothing has to declare both.
+ public get name() {
+
+ return this.config.name ?? this.config.identity
+ }
+
+ // What its window is called when one opens. The window owns its
+ // title afterwards; this is only what it is born with.
+ public get title() {
+
+ return this.config.client?.title ?? this.name
+ }
+
+ public get server(): Resolved<ServerConfig> | null {
+
+ return this.config.server ? { ...this.config.server, start: this.config.server.start ?? true } : null
+ }
+
+ public get client(): Resolved<ClientConfig> | null {
+
+ return this.config.client ? { ...this.config.client, start: this.config.client.start ?? true } : null
+ }
+
+ // A client half may name a URL instead of a directory, which is how
+ // a program under development is framed from a live dev server. An
+ // installed program cannot: its paths are not its own to choose.
+ public get clientUrl() {
+
+ const location = this.config.client?.location
+
+ return location && /^https?:\/\//i.test(location) ? location : null
+ }
+
+ // A URL declaration says two things in one ordinary URL: its last
+ // slash ends the place this client may be launched beneath, and the
+ // remainder is the page it opens on when a launch says nothing.
+ public get clientRoot() {
+
+ const location = this.clientUrl
+
+ if (!location) return null
+
+ const url = new URL(location)
+
+ url.pathname = url.pathname.slice(0, url.pathname.lastIndexOf("/") + 1)
+
+ url.search = ""
+
+ url.hash = ""
+
+ return url.href
+ }
+
+ public get clientLocation() {
+
+ const location = this.clientUrl
+
+ if (!location) return "/"
+
+ const url = new URL(location)
+
+ return `/${url.pathname.slice(url.pathname.lastIndexOf("/") + 1)}${url.search}${url.hash}`
+ }
+
+ // The three places, resolved. A client that is a URL has no
+ // directory, and a half that was not declared has no place.
+ public get serverPath() {
+
+ return this.config.server ? this.place(this.config.server.location) : null
+ }
+
+ public get clientPath() {
+
+ return this.config.client && !this.clientUrl ? this.place(this.config.client.location) : null
+ }
+
+ public get storagePath() {
+
+ return this.place(this.config.storage, "./storage")
+ }
+
+ public get apiDocsPath() {
+
+ return this.config.apiDocs ? this.place(this.config.apiDocs) : null
+ }
+
+ // Contents, never the path. Reading on demand keeps an attached
+ // development Program's documentation current while installed Programs
+ // naturally read their immutable canonical copy.
+ public apiDocs() {
+
+ const path = this.apiDocsPath
+
+ return path ? readFileSync(path, "utf-8") : null
+ }
+
+ // One authored source, or none. Hosting owns every derived size and the
+ // system-owned default, so neither becomes part of the Program contract.
+ public get iconPath() {
+
+ return this.config.icon ? this.place(this.config.icon) : null
+ }
+
+ /** SDK Program record; internal references are consumed by the SDK boundary. */
+ public record() {
+
+ const { version, description } = this.config
+
+ return {
+
+ // Opaque runtime identity for SDK handle canonicalization. Public
+ // Program identity may be reused after this Program is forgotten.
+ reference: this.reference,
+
+ identity: this.identity,
+
+ name: this.name,
+
+ version: version ?? null,
+
+ description: description ?? null,
+
+ server: this.server && { start: this.server.start },
+
+ client: this.client && {
+
+ start: this.client.start,
+
+ title: this.client.title ?? null,
+
+ size: this.client.size ?? null,
+
+ position: this.client.position ?? null,
+
+ layer: this.client.layer ?? null,
+
+ minimize: this.client.minimize ?? null
+ }
+ }
+ }
+
+ private place(declared: string | undefined, fallback = "") {
+
+ const path = declared ?? fallback
+
+ return isAbsolute(path) ? path : resolve(this.root, path)
+ }
+
+ // Whether the description is telling the truth. Asked when the
+ // system is told to rely on this program — once, while someone is
+ // there to be told what they mistyped.
+ //
+ // Storage is not among it: a program that has kept nothing yet has
+ // nowhere for it, and that is not a lie.
+ public async validate() {
+
+ const server = this.serverPath
+
+ if (server && !directory(server)) throw new Error(`The server directory is not there: ${server}`)
+
+ const client = this.clientPath
+
+ if (client && !directory(client)) throw new Error(`The client directory is not there: ${client}`)
+
+ if (client && !existsSync(resolve(client, "index.html"))) throw new Error(`The client directory has no index.html: ${client}`)
+
+ if (this.iconPath) await validateIcon(this.iconPath)
+
+ const apiDocs = this.apiDocsPath
+
+ if (apiDocs && !file(apiDocs)) throw new Error(`The API documentation file is not there: ${apiDocs}`)
+ }
+
+ // Preparing a server half, when it says it needs preparing. Run
+ // once, where the half lives, before anything starts it.
+ public async installServer() {
+
+ const command = this.config.server?.installCommand
+
+ if (!command) return
+
+ await execute(command, this.serverPath!)
+ }
+}
+
+function read(path: string): [ProgramConfig, string] {
+
+ const file = isAbsolute(path) ? path : resolve(process.cwd(), path)
+
+ if (!existsSync(file)) throw new Error(`There is no program at ${file}`)
+
+ try { return [JSON.parse(readFileSync(file, "utf-8")) as ProgramConfig, dirname(file)] }
+
+ catch (exception) { throw new Error(`${file} is not valid JSON: ${exception instanceof Error ? exception.message : "unreadable"}`) }
+}
+
+// What a description must be for a program to exist at all. Nothing
+// here touches a disk: it asks whether the words agree with each other,
+// not whether they are true.
+function coherent(config: ProgramConfig) {
+
+ // A name is also the name of a directory, so it is checked as a path
+ // component before it is anything else — a program calling itself
+ // "../../etc" would otherwise be laid out in the system's own files.
+ if (typeof config?.identity !== "string" || !kebab.test(config.identity)) throw new Error("A program's identity is kebab-case, because it is also the name of its directory")
+
+ if (!config.server && !config.client) throw new Error("A program must have a server half, a client half, or both")
+
+ for (const field of ["name", "version", "description", "icon", "storage"] as const) {
+
+ if (config[field] !== undefined && typeof config[field] !== "string") throw new Error(`A program's ${field} must be text`)
+ }
+
+ if (config.apiDocs !== undefined && (typeof config.apiDocs !== "string" || config.apiDocs.trim().length === 0)) throw new Error("A program's apiDocs must be a non-empty path")
+
+ for (const half of ["server", "client"] as const) {
+
+ const declared = config[half]
+
+ if (declared === undefined) continue
+
+ if (typeof declared !== "object" || declared === null || Array.isArray(declared)) throw new Error(`A program's ${half} half must be a declaration`)
+
+ if (typeof declared.location !== "string") throw new Error(`A declared ${half} half must have a location`)
+
+ if (declared.start !== undefined && typeof declared.start !== "boolean") throw new Error(`A declared ${half} endpoint's start default must be true or false`)
+ }
+
+ if (config.client && /^https?:\/\//i.test(config.client.location)) {
+
+ try { new URL(config.client.location) }
+
+ catch { throw new Error("A client half's URL must be a valid HTTP or HTTPS URL") }
+ }
+
+ if (!(config.server && (config.server.start ?? true)) && !(config.client && (config.client.start ?? true))) throw new Error("A Program's default Process must start a server endpoint, a client endpoint, or both")
+
+ if (config.server && (typeof config.server.startCommand !== "string" || config.server.startCommand.length === 0)) throw new Error("A server half must declare a start command")
+
+ if (config.server?.installCommand !== undefined && typeof config.server.installCommand !== "string") throw new Error("A server half's install command must be text")
+
+ if (config.client?.title !== undefined && typeof config.client.title !== "string") throw new Error("A client half's title must be text")
+
+ if (config.client?.minimize !== undefined && typeof config.client.minimize !== "boolean") throw new Error("A client half's minimize default must be true or false")
+
+ for (const [what, value] of [["size", config.client?.size], ["position", config.client?.position]] as const) {
+
+ if (value === undefined) continue
+
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error(`A window's ${what} must name both of its values`)
+
+ const pair = what === "size" ? [(value as Size).width, (value as Size).height] : [(value as Position).x, (value as Position).y]
+
+ if (!pair.every(isValue)) throw new Error(`A window's ${what} is a finite pixel number or a relative expression such as "50% + 10"`)
+ }
+
+ // A layer nobody named is `window`; a layer named wrong is a mistake
+ // caught here, rather than at the moment a window has to be put
+ // somewhere and there is nowhere to put it.
+ if (config.client?.layer !== undefined && !layers.includes(config.client.layer)) throw new Error(`A client half's layer is one of ${layers.join(", ")}`)
+
+ return config
+}
+
+type Resolved<Half extends { start?: boolean }> = Omit<Half, "start"> & { start: boolean }
+
+function directory(path: string) {
+
+ return existsSync(path) && statSync(path).isDirectory()
+}
+
+function file(path: string) {
+
+ try {
+
+ if (!statSync(path).isFile()) return false
+
+ accessSync(path, constants.R_OK)
+
+ return true
+ }
+
+ catch { return false }
+}
+
+function execute(command: string, cwd: string) {
+
+ return new Promise<void>(function (settle, refuse) {
+
+ const child = spawn(command, { shell: true, cwd, stdio: "ignore" })
+
+ child.on("error", refuse)
+
+ child.on("exit", code => code === 0 ? settle() : refuse(new Error(`"${command}" exited with ${code}`)))
+ })
+}
diff --git a/source/server/core/link-manager/auth-manager/program-manager/startup.ts b/source/server/core/link-manager/auth-manager/program-manager/startup.ts
new file mode 100644
index 0000000..7c18da9
--- /dev/null
+++ b/source/server/core/link-manager/auth-manager/program-manager/startup.ts
@@ -0,0 +1,41 @@
+import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"
+import { randomUUID } from "node:crypto"
+import { join } from "node:path"
+import type Program from "./program"
+
+const file = "startup.json"
+
+/** Read the system-managed startup declaration without interpreting it. */
+export function readStartup(program: Program): unknown | null {
+
+ const path = join(program.storagePath, file)
+
+ if (!existsSync(path)) return null
+
+ return JSON.parse(readFileSync(path, "utf8")) as unknown
+}
+
+/** Atomically replace one Program's system-managed startup declaration. */
+export function writeStartup(program: Program, launch: unknown) {
+
+ mkdirSync(program.storagePath, { recursive: true })
+
+ const path = join(program.storagePath, file)
+
+ const temporary = join(program.storagePath, `.${file}.${randomUUID()}`)
+
+ try {
+
+ writeFileSync(temporary, `${JSON.stringify(launch, null, 2)}\n`)
+
+ renameSync(temporary, path)
+ }
+
+ finally { rmSync(temporary, { force: true }) }
+}
+
+/** Disable startup without touching any other Program storage. */
+export function removeStartup(program: Program) {
+
+ rmSync(join(program.storagePath, file), { force: true })
+}
diff --git a/source/server/core/link-manager/link-manager.ts b/source/server/core/link-manager/link-manager.ts
new file mode 100644
index 0000000..1f8e837
--- /dev/null
+++ b/source/server/core/link-manager/link-manager.ts
@@ -0,0 +1,272 @@
+import { Forward, Subscribe } from "@libs/the-link/decorators/escript"
+import AuthManager from "./auth-manager/auth-manager"
+import TheLink from "@libs/the-link/the-link"
+import Property from "@libs/the-link/property"
+import { Transmitted } from "@libs/superjson"
+import Application from "../application"
+import { type ThemeProperties, type WallpaperLaunch } from "@phreshos/core"
+import { type default as Program } from "./auth-manager/program-manager/program"
+import { type AuthenticationState, type RegistrationError } from "../authentication/authentication"
+
+export default class LinkManager extends TheLink {
+
+ public readonly application: Application
+
+ /** Live desktop connections. Authentication sessions outlive these links. */
+ public readonly connections = new Map<string, Connection>()
+
+ public readonly authManager: AuthManager
+
+ /** Public, read-only representation of the authoritative system Theme. */
+ public readonly theme: Property<ThemeProperties>
+
+ /** Public sign-in wallpaper filename, or `null` for the bundled asset. */
+ public readonly signInWallpaper: Property<string | null>
+
+ /** Public desktop file wallpaper, or `null` when bundled or Program-backed. */
+ public readonly desktopWallpaper: Property<string | null>
+
+ private updatingTheme: Promise<void> = Promise.resolve()
+
+ public constructor(application: Application) {
+
+ super()
+
+ this.application = application
+
+ this.theme = Property.private(this, this.application.themeManager.value)
+
+ this.signInWallpaper = Property.private(this, this.application.wallpaperManager.signIn)
+
+ this.desktopWallpaper = Property.private(this, this.application.wallpaperManager.desktopFile)
+
+ this.authManager = new AuthManager(this)
+ }
+
+ public addConnection(link: TheLink) {
+
+ const identity = crypto.randomUUID()
+
+ this.connections.set(identity, { link, session: null })
+
+ return identity
+ }
+
+ public async removeConnection(identity: string) {
+
+ const connection = this.connections.get(identity)
+
+ this.authManager.processManager.releaseConnection(identity)
+
+ this.connections.delete(identity)
+
+ if (connection?.session && !this.connected(connection.session)) await this.application.authentication.disconnectSession(connection.session)
+ }
+
+ @Subscribe("/owner/state")
+ protected authenticationState(): AuthenticationState {
+
+ return this.application.authentication.state()
+ }
+
+ @Subscribe("/owner/register")
+ protected async register(username: string, password: string): Promise<RegistrationResponse> {
+
+ const result = await this.application.authentication.register(username, password)
+
+ if ("error" in result) return result
+
+ return { authorization: await this.createAuthorization() }
+ }
+
+ @Subscribe("/owner/sign-in")
+ protected async signIn(username: string, password: string) {
+
+ if (!await this.application.authentication.verify(username, password)) return false
+
+ return await this.createAuthorization()
+ }
+
+ private async createAuthorization() {
+
+ const session = await this.application.authentication.createSession()
+
+ return this.application.encryptor.createToken({ version: 1, session })
+ }
+
+ public resolveAuthorization(authorization: string) {
+
+ // Anything that is not a token at all makes the verifier throw
+ // about buffers. What that means is "not authorized", and that
+ // is what a caller should be told.
+ try {
+
+ const result = this.application.encryptor.verifyToken<unknown>(authorization)
+
+ if (!result || !isAuthorization(result.payload)) return false
+
+ return this.application.authentication.sessionValid(result.payload.session) ? result.payload.session : false
+ }
+
+ catch {
+
+ return false
+ }
+ }
+
+ @Subscribe("/session-authenticate")
+ protected async sessionAuthenticate(connectionIdentity: string, authorization: string | null) {
+
+ const connection = this.connections.get(connectionIdentity)
+
+ if (!connection) throw new Error("Connection not found")
+
+ if (!authorization) {
+
+ await this.releaseAuthorization(connection, true)
+
+ return false
+ }
+
+ const session = this.resolveAuthorization(authorization)
+
+ if (!session) {
+
+ await this.releaseAuthorization(connection)
+
+ return false
+ }
+
+ if (connection.session !== session) await this.releaseAuthorization(connection)
+
+ if (!await this.application.authentication.connectSession(session)) return false
+
+ connection.session = session
+
+ return [authorization, this.authManager]
+ }
+
+ @Forward("outbound")
+ protected async broadcastToConnections(event: string, ...values: unknown[]) {
+
+ for (const { link } of this.connections.values()) {
+
+ await link.$outbound.publish(event, ...values)
+ }
+ }
+
+ private connected(session: string) {
+
+ return [...this.connections.values()].some(connection => connection.session === session)
+ }
+
+ private async releaseAuthorization(connection: Connection, remove = false) {
+
+ const session = connection.session
+
+ connection.session = null
+
+ if (!session) return
+
+ if (remove) {
+
+ for (const current of this.connections.values()) {
+
+ if (current.session === session) current.session = null
+ }
+
+ await this.application.authentication.removeSession(session)
+
+ return
+ }
+
+ if (!this.connected(session)) await this.application.authentication.disconnectSession(session)
+ }
+
+ /** Persist and publish one authorized Theme replacement in call order. */
+ public updateTheme(value: unknown) {
+
+ const update = this.updatingTheme.then(async () => {
+
+ const theme = await this.application.themeManager.update(value)
+
+ await this.theme.update(theme)
+
+ return theme
+ })
+
+ this.updatingTheme = update.then(() => undefined, () => undefined)
+
+ return update
+ }
+
+ public async setSignInWallpaper(file: unknown) {
+
+ const selected = await this.application.wallpaperManager.setSignIn(file)
+
+ await this.signInWallpaper.update(selected)
+ }
+
+ public async removeSignInWallpaper() {
+
+ await this.application.wallpaperManager.removeSignIn()
+
+ await this.signInWallpaper.update(null)
+ }
+
+ public async setDesktopWallpaper(file: unknown) {
+
+ const selected = await this.application.wallpaperManager.setDesktopFile(file, this.authManager.programManager)
+
+ await this.desktopWallpaper.update(selected)
+ }
+
+ public async setDesktopWallpaperProgram(program: Program, launch: WallpaperLaunch) {
+
+ await this.application.wallpaperManager.setDesktopProgram(program, launch, this.authManager.programManager)
+
+ await this.desktopWallpaper.update(null)
+ }
+
+ public async removeDesktopWallpaper() {
+
+ await this.application.wallpaperManager.removeDesktop(this.authManager.programManager)
+
+ await this.desktopWallpaper.update(null)
+ }
+
+ // Nothing about the link itself crosses. The declaration stays, so
+ // what a session is born with is stated rather than inferred from
+ // whatever the object happens to hold.
+ public toJSON() {
+
+ return {
+
+ theme: this.theme,
+
+ signInWallpaper: this.signInWallpaper,
+
+ desktopWallpaper: this.desktopWallpaper
+ }
+ }
+}
+
+export type TransmittedLinkManager = Transmitted<LinkManager>
+
+export type RegistrationResponse = { authorization: string } | { error: RegistrationError }
+
+interface Connection {
+
+ link: TheLink
+
+ session: string | null
+}
+
+function isAuthorization(value: unknown): value is { version: 1, session: string } {
+
+ if (!value || typeof value !== "object") return false
+
+ const authorization = value as { version?: unknown, session?: unknown }
+
+ return authorization.version === 1 && typeof authorization.session === "string"
+}
diff --git a/source/server/core/open-store.ts b/source/server/core/open-store.ts
new file mode 100644
index 0000000..ac7e3b8
--- /dev/null
+++ b/source/server/core/open-store.ts
@@ -0,0 +1,12 @@
+import { mkdirSync } from "node:fs"
+import { join } from "node:path"
+import Keyv from "keyv"
+import SqliteStore from "@libs/sqlite-store"
+
+/** Open the persistent key-value store in an owned directory. */
+export default function openStore(directory: string) {
+
+ mkdirSync(directory, { recursive: true })
+
+ return new Keyv(new SqliteStore(join(directory, "store.sqlite")))
+}
diff --git a/source/server/core/outcome.ts b/source/server/core/outcome.ts
new file mode 100644
index 0000000..25316f4
--- /dev/null
+++ b/source/server/core/outcome.ts
@@ -0,0 +1,39 @@
+import { type Outcome } from "@phreshos/core"
+
+export type { Outcome } from "@phreshos/core"
+
+/** Wrap a successful boundary result, including `undefined`, without ambiguity. */
+export function succeeded<Result>(result: Result): Outcome<Result> {
+
+ return { success: true, result }
+}
+
+/**
+ * Normalize a thrown value at the boundary where it occurred.
+ *
+ * Arbitrary thrown values never become transport data. An Error may disclose
+ * its message only where the caller is permitted to receive details.
+ */
+export function failed(exception: unknown, disclose = true): Outcome<never> {
+
+ return {
+
+ success: false,
+
+ error: disclose && exception instanceof Error ? exception.message : "An unknown exception occurred"
+ }
+}
+
+/** Resolve a successful boundary outcome or reconstruct its failure locally. */
+export function unwrap<Result>(outcome: Outcome<Result>): Result {
+
+ if (!outcome || typeof outcome !== "object" || !("success" in outcome)) throw new Error("The boundary returned an invalid outcome")
+
+ // JSON omits an `undefined` property. Success is the known envelope fact;
+ // reading its absent result reconstructs that valid `undefined` value.
+ if (outcome.success === true) return outcome.result
+
+ if (outcome.success !== false || !("error" in outcome) || typeof outcome.error !== "string") throw new Error("The boundary returned an invalid outcome")
+
+ throw new Error(outcome.error)
+}
diff --git a/source/server/core/protocol/proxy.ts b/source/server/core/protocol/proxy.ts
new file mode 100644
index 0000000..54e2434
--- /dev/null
+++ b/source/server/core/protocol/proxy.ts
@@ -0,0 +1,49 @@
+export const proxyMediaType = "application/x-proxy-stream"
+
+/** A normalized request whose body follows its metadata in the proxy stream. */
+export interface ProxyRequest {
+
+ body: boolean
+
+ cache: RequestCache
+
+ credentials: RequestCredentials
+
+ headers: [string, string][]
+
+ integrity: string
+
+ keepalive: boolean
+
+ method: string
+
+ mode: RequestMode
+
+ redirect: RequestRedirect
+
+ referrer: string
+
+ referrerPolicy: ReferrerPolicy
+
+ url: string
+}
+
+/** The parts of a server-side Response that can be reconstructed in a pane. */
+export interface ProxyResponse {
+
+ body: boolean
+
+ headers: [string, string][]
+
+ redirected: boolean
+
+ status: number
+
+ statusText: string
+
+ type: ResponseType
+
+ url: string
+}
+
+export type ProxyOutcome = { response: ProxyResponse } | { error: { message: string, name: string } }
diff --git a/source/server/core/protocol/storage.ts b/source/server/core/protocol/storage.ts
new file mode 100644
index 0000000..570f900
--- /dev/null
+++ b/source/server/core/protocol/storage.ts
@@ -0,0 +1,12 @@
+export const storageMediaType = "application/x-storage-stream"
+
+export interface StorageRequest {
+
+ program: string
+
+ area: "data" | "cache"
+
+ operation: "stream" | "write"
+
+ path: string[]
+}
diff --git a/source/server/core/served-file-manager.ts b/source/server/core/served-file-manager.ts
new file mode 100644
index 0000000..6993910
--- /dev/null
+++ b/source/server/core/served-file-manager.ts
@@ -0,0 +1,112 @@
+import { createWriteStream, mkdirSync, statSync } from "node:fs"
+import FileManager from "@libs/file-manager"
+import { rename, rm } from "node:fs/promises"
+import { randomUUID } from "node:crypto"
+import { Readable } from "node:stream"
+import { pipeline } from "node:stream/promises"
+import { type ReadableStream as NodeReadableStream } from "node:stream/web"
+
+export const serveLimit = 1024 * 1024 * 1024
+
+export class MissingServedValueError extends Error {
+
+ public constructor() {
+
+ super("A value is required")
+ }
+}
+
+export class ServedValueTooLargeError extends Error {
+
+ public constructor() {
+
+ super(`The served value exceeds ${serveLimit / 1024 / 1024 / 1024} GB`)
+ }
+}
+
+/**
+ * Completed public files. Their generated filename is their whole record:
+ * there is no table to synchronize and no visibility state to remember.
+ *
+ * Incoming bytes are written beside their destination under a hidden name.
+ * Only a complete value at or below the limit is renamed into public reach;
+ * interruption and refusal remove the temporary file.
+ */
+const shape = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.[a-z0-9]+$/
+
+export default class ServedFileManager {
+
+ public readonly fileManager: FileManager
+
+ public constructor(fileManager: FileManager) {
+
+ this.fileManager = fileManager
+
+ mkdirSync(fileManager.path, { recursive: true })
+ }
+
+ public path(file: string) {
+
+ if (!shape.test(file)) throw new Error("That is not a served file")
+
+ return this.fileManager.join(file)
+ }
+
+ public async write(extension: string, content: ReadableStream<Uint8Array> | null, signal?: AbortSignal) {
+
+ if (!/^[a-z0-9]+$/.test(extension)) throw new Error("A served file needs a valid extension")
+
+ if (!content) throw new MissingServedValueError()
+
+ const uuid = randomUUID()
+
+ const file = `${uuid}.${extension}`
+
+ const temporary = this.fileManager.join(`.${uuid}.serving`)
+
+ let size = 0
+
+ try {
+
+ await pipeline(
+
+ Readable.fromWeb(content as unknown as NodeReadableStream<Uint8Array>),
+
+ async function* (source: AsyncIterable<Uint8Array>) {
+
+ for await (const chunk of source) {
+
+ size += chunk.byteLength
+
+ if (size > serveLimit) throw new ServedValueTooLargeError()
+
+ yield chunk
+ }
+ },
+
+ createWriteStream(temporary, { flags: "wx" }),
+
+ { signal }
+ )
+
+ await rename(temporary, this.path(file))
+ }
+
+ catch (exception) {
+
+ await rm(temporary, { force: true }).catch(() => undefined)
+
+ throw exception
+ }
+
+ return file
+ }
+
+ public describe(file: string) {
+
+ const stat = statSync(this.path(file))
+
+ return { file, size: stat.size, time: Math.round(stat.mtimeMs) }
+ }
+
+}
diff --git a/source/server/core/theme-manager.ts b/source/server/core/theme-manager.ts
new file mode 100644
index 0000000..9aa8a6f
--- /dev/null
+++ b/source/server/core/theme-manager.ts
@@ -0,0 +1,67 @@
+import Keyv from "keyv"
+import { z } from "zod"
+import { createThemeSnapshot, standardTheme, themeLimits, type ThemeProperties, type ThemeRange } from "@phreshos/core"
+
+const storageKey = "appearance:theme"
+
+/** The authoritative schema for the system Theme. */
+export const themeSchema: z.ZodType<ThemeProperties> = z.strictObject({
+ background: z.string().min(1).default(standardTheme.background),
+ foreground: z.string().min(1).default(standardTheme.foreground),
+ accent: z.string().min(1).default(standardTheme.accent),
+ spacing: bounded(themeLimits.spacing).default(standardTheme.spacing),
+ radius: bounded(themeLimits.radius).default(standardTheme.radius),
+ glass: z.strictObject({
+ distortion: bounded(themeLimits.glass.distortion).default(standardTheme.glass.distortion),
+ blur: bounded(themeLimits.glass.blur).default(standardTheme.glass.blur),
+ saturation: bounded(themeLimits.glass.saturation).default(standardTheme.glass.saturation),
+ brightness: bounded(themeLimits.glass.brightness).default(standardTheme.glass.brightness),
+ opacity: bounded(themeLimits.glass.opacity).default(standardTheme.glass.opacity)
+ }).default(standardTheme.glass)
+})
+
+/** Durable, authoritative Theme state owned by the server core. */
+export default class ThemeManager {
+
+ private current: ThemeProperties
+
+ private constructor(private readonly store: Keyv, theme: ThemeProperties) {
+
+ this.current = theme
+ }
+
+ /** Opens and validates the persisted Theme, or starts from the default. */
+ public static async open(store: Keyv) {
+
+ const stored = await store.get(storageKey)
+
+ const theme = createThemeSnapshot(themeSchema.parse(stored ?? standardTheme))
+
+ if (stored === undefined) await store.set(storageKey, theme)
+
+ return new ThemeManager(store, theme)
+ }
+
+ /** The complete immutable Theme snapshot. */
+ public get value() {
+
+ return this.current
+ }
+
+ /** Validates and durably replaces the authoritative Theme. */
+ public async update(value: unknown) {
+
+ const theme = createThemeSnapshot(themeSchema.parse(value))
+
+ await this.store.set(storageKey, theme)
+
+ this.current = theme
+
+ return theme
+ }
+}
+
+function bounded(range: ThemeRange) {
+
+ return z.number().min(range.minimum).max(range.maximum)
+}
diff --git a/source/server/core/wallpaper-manager.ts b/source/server/core/wallpaper-manager.ts
new file mode 100644
index 0000000..272c64f
--- /dev/null
+++ b/source/server/core/wallpaper-manager.ts
@@ -0,0 +1,198 @@
+import { extname } from "node:path"
+import Keyv from "keyv"
+import { z } from "zod"
+import { type WallpaperLaunch } from "@phreshos/core"
+import ServedFileManager from "./served-file-manager"
+import { type default as Program } from "./link-manager/auth-manager/program-manager/program"
+import { type default as ProgramManager } from "./link-manager/auth-manager/program-manager/program-manager"
+
+const signInKey = "appearance:signInWallpaper"
+const desktopKey = "appearance:desktopWallpaper"
+
+const servedFileSchema = z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.[a-z0-9]+$/)
+
+const launchSchema: z.ZodType<WallpaperLaunch> = z.strictObject({
+ name: z.string().min(1).optional(),
+ server: z.boolean().optional(),
+ client: z.strictObject({ location: z.string().optional() }).optional(),
+ options: z.record(z.string(), z.string()).optional()
+})
+
+const desktopSchema = z.discriminatedUnion("type", [
+
+ z.strictObject({ type: z.literal("file"), file: servedFileSchema }),
+
+ z.strictObject({
+ type: z.literal("program"),
+ program: z.string().min(1),
+ launch: launchSchema
+ })
+]).nullable()
+
+const signInSchema = servedFileSchema.nullable()
+
+const wallpaperExtensions = new Set(["avif", "bmp", "gif", "htm", "html", "jpeg", "jpg", "png", "svg", "webp"])
+
+export type DesktopWallpaperState = z.infer<typeof desktopSchema>
+
+/** Durable appearance choices and the lifecycle of the optional wallpaper Program. */
+export default class WallpaperManager {
+
+ private changing: Promise<void> = Promise.resolve()
+
+ private constructor(
+ private readonly store: Keyv,
+ private readonly servedFiles: ServedFileManager,
+ private signInValue: string | null,
+ private desktopValue: DesktopWallpaperState
+ ) { }
+
+ /** Opens and validates only the current appearance keys. */
+ public static async open(store: Keyv, servedFiles: ServedFileManager) {
+
+ const storedSignIn = await store.get(signInKey)
+
+ const storedDesktop = await store.get(desktopKey)
+
+ const signIn = signInSchema.parse(storedSignIn ?? null)
+
+ const desktop = desktopSchema.parse(storedDesktop ?? null)
+
+ if (storedSignIn === undefined) await store.set(signInKey, signIn)
+
+ if (storedDesktop === undefined) await store.set(desktopKey, desktop)
+
+ return new WallpaperManager(store, servedFiles, signIn, desktop)
+ }
+
+ /** File selected for sign-in, or `null` for the bundled wallpaper. */
+ public get signIn() { return this.signInValue }
+
+ /** File selected for the desktop, or `null` when bundled or Program-backed. */
+ public get desktopFile() { return this.desktopValue?.type === "file" ? this.desktopValue.file : null }
+
+ /** Restores the persisted Program wallpaper after the Program registry exists. */
+ public async initialize(programs: ProgramManager) {
+
+ const selected = this.desktopValue
+
+ if (selected?.type !== "program") return
+
+ const program = programs.reach(selected.program)
+
+ if (!program) return
+
+ try { await programs.startWallpaper(program, selected.launch) }
+
+ catch (exception) {
+
+ console.log(`wallpaper: ${selected.program} did not start — ${exception instanceof Error ? exception.message : "unavailable"}`)
+ }
+ }
+
+ public setSignIn(file: unknown) {
+
+ return this.change(async () => {
+
+ const selected = this.file(file)
+
+ await this.store.set(signInKey, selected)
+
+ this.signInValue = selected
+
+ return selected
+ })
+ }
+
+ public removeSignIn() {
+
+ return this.change(async () => {
+
+ await this.store.set(signInKey, null)
+
+ this.signInValue = null
+
+ return null
+ })
+ }
+
+ public setDesktopFile(file: unknown, programs: ProgramManager) {
+
+ return this.change(async () => {
+
+ const selected = this.file(file)
+
+ await this.exitProgram(programs)
+
+ this.desktopValue = { type: "file", file: selected }
+
+ await this.store.set(desktopKey, this.desktopValue)
+
+ return selected
+ })
+ }
+
+ public removeDesktop(programs: ProgramManager) {
+
+ return this.change(async () => {
+
+ await this.exitProgram(programs)
+
+ this.desktopValue = null
+
+ await this.store.set(desktopKey, null)
+
+ return null
+ })
+ }
+
+ public setDesktopProgram(program: Program, value: unknown, programs: ProgramManager) {
+
+ return this.change(async () => {
+
+ if (!program.client) throw new Error("A desktop wallpaper Program must declare a Client")
+
+ const launch = launchSchema.parse(value ?? {})
+
+ await this.exitProgram(programs)
+
+ this.desktopValue = { type: "program", program: program.identity, launch }
+
+ await this.store.set(desktopKey, this.desktopValue)
+
+ await programs.startWallpaper(program, launch)
+
+ return program.identity
+ })
+ }
+
+ private file(value: unknown) {
+
+ const file = servedFileSchema.parse(value)
+
+ if (!wallpaperExtensions.has(extname(file).slice(1))) throw new Error("A wallpaper must be an image or HTML file")
+
+ this.servedFiles.describe(file)
+
+ return file
+ }
+
+ private async exitProgram(programs: ProgramManager) {
+
+ for (const process of [...programs.authManager.processManager.processes.values()]) {
+
+ if (process.client?.window.layer !== "wallpaper") continue
+
+ await process.stop()
+ }
+ }
+
+ private change<Result>(operation: () => Promise<Result>) {
+
+ const changing = this.changing.then(operation)
+
+ this.changing = changing.then(() => undefined, () => undefined)
+
+ return changing
+ }
+}
diff --git a/source/server/dec.d.ts b/source/server/dec.d.ts
new file mode 100644
index 0000000..b388dad
--- /dev/null
+++ b/source/server/dec.d.ts
@@ -0,0 +1 @@
+/// <reference types="@types/node" />
\ No newline at end of file
diff --git a/source/server/main.ts b/source/server/main.ts
new file mode 100644
index 0000000..c35da71
--- /dev/null
+++ b/source/server/main.ts
@@ -0,0 +1,18 @@
+import { displayName, name, version } from "@/package.json"
+import view, { environmentPort } from "./view/view"
+import { fileURLToPath } from "node:url"
+
+await view({
+
+ name,
+
+ displayName,
+
+ version,
+
+ mode: "production",
+
+ port: environmentPort(name, process.env) ?? 4300,
+
+ assets: fileURLToPath(new URL("../client", import.meta.url))
+})
diff --git a/source/server/view/doors.ts b/source/server/view/doors.ts
new file mode 100644
index 0000000..65d54b2
--- /dev/null
+++ b/source/server/view/doors.ts
@@ -0,0 +1,20 @@
+/**
+ * The paths exposed by the server view. These are the actual route names used
+ * by Hono in production and forwarded by Vite in development.
+ */
+const doors = {
+
+ link: "/link",
+
+ proxy: "/proxy",
+
+ storage: "/storage",
+
+ uploads: "/uploads",
+
+ program: "/program"
+}
+
+export type Doors = typeof doors
+
+export default doors
diff --git a/source/server/view/intake.ts b/source/server/view/intake.ts
new file mode 100644
index 0000000..be5cb1d
--- /dev/null
+++ b/source/server/view/intake.ts
@@ -0,0 +1,294 @@
+import { chmodSync, mkdirSync, rmSync } from "node:fs"
+import Application from "@server/core/application"
+import { connect, createServer, type Socket } from "node:net"
+import { dirname } from "node:path"
+
+/**
+ * The local program intake: programs entering from this machine.
+ *
+ * One narrow local interface beside the web view a person lives in. The
+ * two views are the two audiences, and this one accepts exactly one subject:
+ * the Program a local project declares: attached, installed, or uninstalled.
+ *
+ * It was called *control* while it had two words and no stated limit,
+ * and the name invited every next word: anything about the machine could
+ * be called controlling it, so the surface had no edge. The role is
+ * named instead. The boundary is the lifecycle of one locally identified
+ * Program project: laid out, run attached, or removed from its installed
+ * place. Words about arbitrary Processes, Windows, stores, or application
+ * state remain outside it because this is not the machine's control panel.
+ *
+ * The link is how a person somewhere else reaches the system, and it has
+ * to prove who it is because it arrived over a network. This is how a
+ * local project standing on the same machine reaches it, and it is already
+ * proven by being able to open the socket.
+ *
+ * **That is the whole authorization model, and it is the operating
+ * system's rather than ours.** The socket is a filesystem entry at mode
+ * 0600, so only the account that owns this machine may speak here — and
+ * that account is exactly who may run programs on it. Nothing is checked
+ * in this file because there is nothing left to check.
+ *
+ * A port would have had the opposite property. Every process on the
+ * machine can reach a port, a browser page can `fetch` one, and stopping
+ * that means inventing a token — a mechanism the transport made
+ * necessary rather than one anything needed.
+ *
+ * **POSIX only, deliberately.** Node maps a listening path onto a named
+ * pipe on Windows, so the *address* would port with two lines. The
+ * authorization would not: a named pipe made through Node has no
+ * permission story reachable from here, and its default admits any local
+ * process. Windows support is therefore not a transport change but a
+ * security-model change, and it is not owed one until something needs
+ * it. The rest of the system is already POSIX-only for smaller reasons.
+ *
+ * **One system per storage root.** The socket lives in the root, so it
+ * follows wherever the root is — which is how the lab runs a throwaway
+ * system beside a real one, by moving `HOME`. Two systems sharing a root
+ * were already colliding over its persistent state and its programs before this
+ * existed; the socket is where that finally gets said out loud.
+ *
+ * **Three words, and the list is closed.** `install` lays a Program out,
+ * `uninstall` removes that same project's installed form, and `run` starts it
+ * attached. None was ever a session's business —
+ * install had a button on the desktop until it was noticed that a person
+ * at a browser somewhere else installing software onto this machine is
+ * exactly what the remote and local split says should not happen.
+ *
+ * What is refused is inheriting a vocabulary wholesale: running The Link
+ * over this would hand intake the whole remote surface, and the two views
+ * do not have the same trust to spend. Nor does a word earn a
+ * place here by being about the machine — that test admits everything.
+ * It earns one by being a way the local project enters the system, and
+ * nothing else is.
+ *
+ * **The connection is the lifetime.** A program launched here is attached
+ * to the connection that asked for it: when that connection goes, the
+ * process is stopped. Not a pid, not a heartbeat, not a timeout — the
+ * operating system closes an ended process's descriptors whatever killed
+ * it, so a terminal closed, an ssh session dropped and a `kill -9` all
+ * arrive here as the same event, and none of them can be missed.
+ *
+ * That makes a launched program's life its launcher's, which is the line
+ * between the two ways in: **attached means not installed, installed
+ * means persistent.** Something meant to outlive a terminal is installed.
+ */
+export default function intake(application: Application, path: string) {
+
+ // A message is a line. The first version had no framing at all — a
+ // question was whatever arrived before the asker closed its own side
+ // — which is elegant and needs half-close to work, and bun's `net`
+ // does not half-close: `end(data)` there closes the socket, so the
+ // answer was written into nothing. A line costs one delimiter and
+ // depends on no runtime agreeing about anything.
+ const server = createServer(function (socket) {
+
+ let said = ""
+
+ // What this connection launched, ended when it goes.
+ const attached = new Set<string>()
+
+ socket.on("data", function (chunk) {
+
+ said += String(chunk)
+
+ const lines = said.split("\n")
+
+ said = lines.pop() ?? ""
+
+ for (const line of lines) if (line.trim()) reply(application, socket, attached, line)
+ })
+
+ // Both directions of the tether meet here. The asker going is
+ // what ends the process; the process ending is what ends the
+ // socket, and either arriving first makes the other a no-op.
+ socket.on("close", function () {
+
+ for (const identity of attached) {
+
+ application.linkManager.authManager.processManager.stop(identity).catch(() => undefined)
+ }
+
+ attached.clear()
+ })
+
+ socket.on("error", () => undefined)
+ })
+
+ mkdirSync(dirname(path), { recursive: true })
+
+ return new Promise<string>(function (settle, refuse) {
+
+ server.once("error", function (error: NodeJS.ErrnoException) {
+
+ if (error.code !== "EADDRINUSE") return refuse(error)
+
+ // Two meanings, and only one of them is safe to act on. A
+ // socket file outlives the process that made it, so this is
+ // either a system that is running or the litter of one that
+ // is not — and the only way to tell is to knock.
+ //
+ // The first version unlinked before listening, which never
+ // asked. A second system took the path, the first kept
+ // running and was reachable by nobody, and every launch
+ // afterwards spoke to the newcomer. Proved by running two.
+ alive(path).then(function (running) {
+
+ if (running) return refuse(new Error(`A system is already running here — ${dirname(path)} holds one system, and two would share its programs and persistent state`))
+
+ rmSync(path, { force: true })
+
+ server.listen(path, () => settle(secured(path)))
+ }, refuse)
+ })
+
+ server.listen(path, () => settle(secured(path)))
+ })
+}
+
+// The mode is the authorization, so it is set before anything is
+// answered rather than left to whatever umask was in force.
+function secured(path: string) {
+
+ chmodSync(path, 0o600)
+
+ return path
+}
+
+// Whether anything is listening there. Connecting is the only honest
+// test: the file's existence says only that a socket was made once.
+function alive(path: string) {
+
+ return new Promise<boolean>(function (settle) {
+
+ const knock = connect(path)
+
+ knock.on("connect", () => { knock.destroy(); settle(true) })
+
+ knock.on("error", () => settle(false))
+ })
+}
+
+// One question in, many events out. A launch is not a thing with an
+// answer — it is a thing with a beginning, a middle of whatever the
+// program says, and an end.
+function reply(application: Application, socket: Socket, attached: Set<string>, line: string) {
+
+ const say = (event: Record<string, unknown>) => { if (socket.writable) socket.write(JSON.stringify(event) + "\n") }
+
+ const done = () => socket.end()
+
+ const alive = () => !socket.destroyed
+
+ answer(application, attached, say, done, alive, line).catch((error: Error) => {
+
+ say({ event: "error", message: error.message })
+
+ done()
+ })
+}
+
+async function answer(application: Application, attached: Set<string>, say: (event: Record<string, unknown>) => void, done: () => void, alive: () => boolean, said: string) {
+
+ let asked: Asked
+
+ try { asked = JSON.parse(said) as Asked }
+
+ catch { throw new Error("What arrived is not JSON") }
+
+ // Direct launch and installation both enter the same runtime registry
+ // under the Program's declared identity. Installation sets its installed
+ // flag; launch atomically forgets the prior runtime occupant, if any, and
+ // tethers the resulting uninstalled Program to its root process.
+ const programManager = application.linkManager.authManager.programManager
+
+ if (asked.word === "uninstall") {
+
+ if (typeof asked.identity !== "string" || !asked.identity) throw new Error("Uninstalling needs a Program identity")
+
+ if (asked.everything !== undefined && typeof asked.everything !== "boolean") throw new Error("Uninstalling everything must be true or false")
+
+ await programManager.uninstallInstalled(asked.identity, asked.everything === true)
+
+ say({ event: "uninstalled", identity: asked.identity, everything: asked.everything === true })
+
+ return done()
+ }
+
+ // Laid out: a description, and only ever a description.
+ //
+ // The system does not know what an archive is, and this is where it
+ // stopped needing to. A package is a way of *carrying* a program to
+ // another machine, so opening one belongs with whatever brought it —
+ // and installing programs at all is work for a program, not for the
+ // core. The core is a foundation; what a person installs from, and
+ // how, is the business of something built on it.
+ if (asked.word === "install") {
+
+ if (!asked.program) throw new Error("Installing needs a program description")
+
+ const { entry, replaced } = await programManager.installSource(asked.program)
+
+ // Whether it replaced one. Installation has already ended every
+ // process that could have retained one of the previous paths.
+ say({ event: "installed", replaced, program: { identity: entry.identity, name: entry.program.name, version: entry.program.config.version ?? null } })
+
+ return done()
+ }
+
+ if (asked.word !== "run") throw new Error(`This machine's intake does not know the word "${String(asked.word)}"`)
+
+ if (!asked.program) throw new Error("Running needs a program description")
+
+ let identity: string | null = null
+
+ let ended = false
+
+ identity = await programManager.launchAttached(asked.program, asked.options ?? {}, {
+
+ output: (stream, text) => say({ event: "output", stream, text }),
+
+ exited: function (code, signal) {
+
+ ended = true
+
+ if (identity) attached.delete(identity)
+
+ say({ event: "exited", code, signal })
+
+ // Nothing more will be said on this connection: one question
+ // per connection, and its subject has ended.
+ done()
+ }
+ })
+
+ // A child may end before launch finishes announcing its creation, and
+ // the launcher may itself disappear during that same interval. Neither
+ // event may leave a process attached to a connection that is already
+ // finished.
+ if (ended) return
+
+ if (!alive()) {
+
+ if (application.linkManager.authManager.processManager.processes.has(identity)) await application.linkManager.authManager.processManager.stop(identity)
+
+ return
+ }
+
+ attached.add(identity)
+
+ say({ event: "started", process: identity })
+}
+
+interface Asked {
+
+ word?: string
+
+ identity?: string
+
+ everything?: boolean
+
+ program?: Parameters<Application["linkManager"]["authManager"]["programManager"]["launchAttached"]>[0]
+
+ options?: Record<string, string>
+}
diff --git a/source/server/view/link.ts b/source/server/view/link.ts
new file mode 100644
index 0000000..7154c08
--- /dev/null
+++ b/source/server/view/link.ts
@@ -0,0 +1,66 @@
+import ServerLink from "@libs/the-link/plugins/server-link/server-link"
+import { upgradeWebSocket } from "@hono/node-server"
+import Application from "@server/core/application"
+import superjson from "@libs/superjson"
+import LZString from "lz-string"
+import { failed, succeeded } from "@server/core/outcome"
+
+export default function (application: Application, debugging: boolean) {
+
+ const serverLink = new ServerLink()
+
+ if (debugging) serverLink.enableDebugging()
+
+ serverLink.setSerialize(data => LZString.compressToBase64(superjson.stringify(data)))
+
+ serverLink.setDeserialize(data => superjson.parse(LZString.decompressFromBase64(data)))
+
+ serverLink.onSubscribe(function (socketLink) {
+
+ const connectionIdentity = application.linkManager.addConnection(socketLink)
+
+ const stopForwarding = socketLink.$inbound.forwardTo(async function (event, responseUuid: string | null, ...values: unknown[]) {
+
+ // A null response address is an intentional one-way transport
+ // envelope. Route it once and do not manufacture an acknowledgement.
+ if (responseUuid === null) {
+
+ const routed = event.startsWith("/auth/process/frame/") ? [values[0], connectionIdentity, ...values.slice(1)] : values
+
+ application.linkManager.$inbound.publish(event, ...routed).catch(() => undefined)
+
+ return
+ }
+
+ try {
+
+ // Every client Process-boundary operation is owned by this
+ // socket. Insert the connection here, where it comes from the
+ // connection itself and cannot be supplied by an iframe.
+ const routed = event.startsWith("/auth/process/frame/") ? [values[0], connectionIdentity, ...values.slice(1)] : values
+
+ const results = await application.linkManager.$inbound.publish(event, ...routed)
+
+ await socketLink.$outbound.publish(responseUuid, succeeded(results))
+ }
+
+ catch (exception) {
+
+ await socketLink.$outbound.publish(responseUuid, failed(exception, debugging))
+ }
+ })
+
+ socketLink.$internal.subscribeOnce("unsubscribe", async function () {
+
+ await application.linkManager.removeConnection(connectionIdentity)
+
+ stopForwarding()
+ })
+
+ return [application.linkManager, connectionIdentity]
+ })
+
+ serverLink.prepareConnection(upgradeWebSocket)
+
+ return serverLink.app
+}
diff --git a/source/server/view/program.ts b/source/server/view/program.ts
new file mode 100644
index 0000000..2726393
--- /dev/null
+++ b/source/server/view/program.ts
@@ -0,0 +1,89 @@
+import { serveStatic } from "@hono/node-server/serve-static"
+import Application from "@server/core/application"
+import { isIconSize } from "@server/core/link-manager/auth-manager/program-manager/icon"
+import { existsSync } from "node:fs"
+import doors from "./doors"
+import { Hono } from "hono"
+
+/**
+ * What a program shows: its client half at `/program/<assetId>/assets`,
+ * and how it is drawn at `/program/<assetId>/icons`.
+ *
+ * The asset id is a private runtime address, separate from public
+ * program identity. Both are reachable only while the runtime registry
+ * retains the program.
+ *
+ * No authorization: these are files a browser reads, with no link and
+ * no operations. Nothing here can be found from a program's stable
+ * identity.
+ */
+export default function (application: Application) {
+
+ const { programManager } = application.linkManager.authManager
+
+ const program = new Hono()
+
+ // The desktop asks from a sandbox identical to a Program frame. Keeping
+ // this beneath the same door and giving it the same public CORS response
+ // makes it a real test of the asset boundary rather than a health check
+ // performed from the desktop's own origin.
+ program.get("/ping", context => {
+
+ context.header("Access-Control-Allow-Origin", "*")
+
+ context.header("Cache-Control", "no-store")
+
+ return context.text("Program assets are available")
+ })
+
+ // A client is entered at its directory: the trailing slash makes
+ // the page's relative assets resolve beneath it.
+ program.get("/:assetId{[0-9a-f-]{36}}/assets", context => context.redirect(`${new URL(context.req.url).pathname}/`))
+
+ program.use("/:assetId{[0-9a-f-]{36}}/assets/:path{.*}", async (context, next) => {
+
+ const assetId = context.req.param("assetId") ?? ""
+
+ const found = programManager.fromAsset(assetId)
+
+ if (!found) return context.text("Unknown program", 404)
+
+ const root = found.clientPath
+
+ // A retained Program may outlive files removed by uninstall(false).
+ if (!root || !existsSync(root)) return context.text("The program has no assets", 404)
+
+ context.header("Access-Control-Allow-Origin", "*")
+
+ return await serveStatic({
+
+ root,
+
+ rewriteRequestPath: path => path.slice(`${doors.program}/${assetId}/assets`.length)
+
+ })(context, next)
+ })
+
+ program.get("/:assetId{[0-9a-f-]{36}}/icons/:file", async context => {
+
+ const found = programManager.fromAsset(context.req.param("assetId") ?? "")
+
+ if (!found) return context.text("Unknown program", 404)
+
+ const file = context.req.param("file") ?? ""
+
+ const size = file.endsWith(".png") ? file.slice(0, -4) : ""
+
+ if (!isIconSize(size)) return context.text("Unknown icon size", 404)
+
+ context.header("Access-Control-Allow-Origin", "*")
+
+ context.header("Cache-Control", "no-cache")
+
+ context.header("Content-Type", "image/png")
+
+ return context.body(Uint8Array.from(await programManager.icon(found.identity, size)))
+ })
+
+ return program
+}
diff --git a/source/server/view/proxy.ts b/source/server/view/proxy.ts
new file mode 100644
index 0000000..5e2cb12
--- /dev/null
+++ b/source/server/view/proxy.ts
@@ -0,0 +1,135 @@
+import { type ProxyOutcome, type ProxyRequest, type ProxyResponse, proxyMediaType } from "@server/core/protocol/proxy"
+import { frame, unframe } from "@libs/framing"
+import Application from "@server/core/application"
+import { Hono } from "hono"
+
+/** The authorized HTTP door for unrestricted server-side fetch. */
+export default function (application: Application) {
+
+ const { authManager } = application.linkManager
+
+ const proxy = new Hono()
+
+ proxy.post("/", async function (context) {
+
+ const authorization = context.req.header("authorization")
+
+ try {
+
+ authManager.verify(authorization)
+ }
+
+ catch (exception) {
+
+ return context.text(exception instanceof Error ? exception.message : "Unauthorized", 401)
+ }
+
+ let request: Awaited<ReturnType<typeof unframe<ProxyRequest>>>
+
+ try {
+
+ request = await unframe<ProxyRequest>(context.req.raw.body)
+ }
+
+ catch (exception) {
+
+ return context.text(exception instanceof Error ? exception.message : "The proxy request is invalid", 400)
+ }
+
+ let outcome: ProxyOutcome
+
+ let responseBody: ReadableStream<Uint8Array> | null = null
+
+ try {
+
+ const metadata = request.metadata
+
+ const response = await authManager.fetch(authorization, metadata.url, {
+
+ body: metadata.body ? request.body : undefined,
+
+ cache: metadata.cache,
+
+ credentials: metadata.credentials,
+
+ headers: metadata.headers,
+
+ integrity: metadata.integrity,
+
+ keepalive: metadata.keepalive,
+
+ method: metadata.method,
+
+ mode: metadata.mode,
+
+ redirect: metadata.redirect,
+
+ referrer: metadata.referrer,
+
+ referrerPolicy: metadata.referrerPolicy,
+
+ signal: context.req.raw.signal,
+
+ ...metadata.body ? { duplex: "half" } : {}
+
+ } as RequestInit & { duplex?: "half" })
+
+ const responseMetadata: ProxyResponse = {
+
+ body: response.body !== null,
+
+ headers: responseHeaders(response.headers),
+
+ redirected: response.redirected,
+
+ status: response.status,
+
+ statusText: response.statusText,
+
+ type: response.type,
+
+ url: response.url
+ }
+
+ outcome = { response: responseMetadata }
+
+ responseBody = response.body
+ }
+
+ catch (exception) {
+
+ outcome = {
+
+ error: {
+
+ message: exception instanceof Error ? exception.message : "The request failed",
+
+ name: exception instanceof Error ? exception.name : "TypeError"
+ }
+ }
+ }
+
+ return new Response(frame(outcome, responseBody), {
+
+ headers: {
+
+ "cache-control": "no-store",
+
+ "content-type": proxyMediaType
+ }
+ })
+ })
+
+ return proxy
+}
+
+function responseHeaders(headers: Headers): [string, string][] {
+
+ const values = [...headers.entries()].filter(([name]) => name !== "set-cookie") as [string, string][]
+
+ const getSetCookie = (headers as Headers & { getSetCookie?: () => string[] }).getSetCookie
+
+ if (getSetCookie) for (const value of getSetCookie.call(headers)) values.push(["set-cookie", value])
+
+ return values
+}
diff --git a/source/server/view/storage.ts b/source/server/view/storage.ts
new file mode 100644
index 0000000..075b1b8
--- /dev/null
+++ b/source/server/view/storage.ts
@@ -0,0 +1,99 @@
+import { MissingAreaEntryError, NotFileError } from "@libs/file-area"
+import { type StorageRequest } from "@server/core/protocol/storage"
+import { unframe } from "@libs/framing"
+import Application from "@server/core/application"
+import { Hono } from "hono"
+
+/** The desktop-authorized byte stream into or out of a Program area. */
+export default function (application: Application) {
+
+ const { authManager } = application.linkManager
+
+ const storage = new Hono()
+
+ storage.post("/", async function (context) {
+
+ const authorization = context.req.header("authorization")
+
+ try {
+
+ authManager.verify(authorization)
+ }
+
+ catch (exception) {
+
+ return context.text(exception instanceof Error ? exception.message : "Unauthorized", 401)
+ }
+
+ let request: Awaited<ReturnType<typeof unframe<StorageRequest>>>
+
+ try {
+
+ request = await unframe<StorageRequest>(context.req.raw.body)
+
+ validate(request.metadata)
+ }
+
+ catch (exception) {
+
+ return context.text(exception instanceof Error ? exception.message : "The storage request is invalid", 400)
+ }
+
+ try {
+
+ const { area, operation, path, program } = request.metadata
+
+ if (operation === "stream") {
+
+ await request.body.cancel()
+
+ return new Response(authManager.streamArea(authorization, program, area, path), {
+
+ headers: {
+
+ "cache-control": "no-store",
+
+ "content-type": "application/octet-stream"
+ }
+ })
+ }
+
+ await authManager.writeArea(authorization, program, area, path, request.body, context.req.raw.signal)
+
+ return new Response(null, { status: 204 })
+ }
+
+ catch (exception) {
+
+ if (exception instanceof MissingAreaEntryError) return context.text(exception.message, 404)
+
+ if (exception instanceof NotFileError) return context.text(exception.message, 400)
+
+ if (exception instanceof Error && exception.message === "Unauthorized") return context.text(exception.message, 401)
+
+ if (exception instanceof Error && (exception.message.includes("may not leave its area") || exception.message.includes("Writing takes"))) {
+
+ return context.text(exception.message, 400)
+ }
+
+ console.error(exception)
+
+ return context.text("The storage operation failed", 500)
+ }
+ })
+
+ return storage
+}
+
+function validate(request: StorageRequest) {
+
+ if (!request || typeof request !== "object") throw new Error("A storage request is required")
+
+ if (typeof request.program !== "string") throw new Error("A storage request needs a Program")
+
+ if (request.area !== "data" && request.area !== "cache") throw new Error("A storage area is data or cache")
+
+ if (request.operation !== "stream" && request.operation !== "write") throw new Error("A storage operation is stream or write")
+
+ if (!Array.isArray(request.path) || request.path.some(part => typeof part !== "string")) throw new Error("A storage path is a list of names")
+}
diff --git a/source/server/view/uploads.ts b/source/server/view/uploads.ts
new file mode 100644
index 0000000..dc3c2f8
--- /dev/null
+++ b/source/server/view/uploads.ts
@@ -0,0 +1,115 @@
+import { serveStatic } from "@hono/node-server/serve-static"
+import { MissingServedValueError, ServedValueTooLargeError, serveLimit } from "@server/core/served-file-manager"
+import Application from "@server/core/application"
+import doors from "./doors"
+import { Hono } from "hono"
+
+/**
+ * The door bytes come through, and the one they go back out of.
+ *
+ * Transport only: making a value public is an authorized operation on the
+ * auth manager. Reading the completed file needs no authorization.
+ *
+ * The request body remains a stream all the way into ServedFileManager. Declared
+ * oversize bodies are refused before reading; undeclared ones are counted as
+ * they arrive, with incomplete temporary files removed on every failure.
+ */
+export default function (application: Application) {
+
+ const { authManager } = application.linkManager
+
+ const uploads = new Hono()
+
+ uploads.post("/", async function (context) {
+
+ const authorization = context.req.header("authorization")
+
+ try {
+
+ authManager.verify(authorization)
+ }
+
+ catch (exception) {
+
+ return context.text(exception instanceof Error ? exception.message : "Unauthorized", 401)
+ }
+
+ if (Number(context.req.header("content-length")) > serveLimit) return context.text(new ServedValueTooLargeError().message, 413)
+
+ try {
+
+ const type = context.req.header("content-type") ?? null
+
+ const served = await authManager.serve(
+
+ authorization,
+
+ context.req.raw.body,
+
+ type,
+
+ extension(filename(context.req.header("content-disposition"))) ?? typeExtension(type),
+
+ context.req.raw.signal
+ )
+
+ return context.json(served)
+ }
+
+ catch (exception) {
+
+ if (exception instanceof MissingServedValueError) return context.text(exception.message, 400)
+
+ if (exception instanceof ServedValueTooLargeError) return context.text(exception.message, 413)
+
+ if (exception instanceof Error && exception.message === "Unauthorized") return context.text(exception.message, 401)
+
+ console.error(exception)
+
+ return context.text("The value could not be served", 500)
+ }
+ })
+
+ uploads.use("/:file", async function (context, next) {
+
+ await next()
+
+ context.header("Access-Control-Allow-Origin", "*")
+ })
+
+ uploads.use("/:file", serveStatic({
+
+ root: application.servedFiles.fileManager.path,
+
+ rewriteRequestPath: path => path.slice(doors.uploads.length + 1)
+ }))
+
+ return uploads
+}
+
+// The standard place a filename travels when a body is raw bytes.
+function filename(disposition: string | undefined) {
+
+ const found = disposition?.match(/filename\*?=(?:UTF-8'')?"?([^";]+)"?/i)
+
+ return found ? decodeURIComponent(found[1]) : null
+}
+
+// What a file is, as far as its name says. The name itself is not kept:
+// it came from a browser, and the extension is the only part of it that
+// identifies anything.
+function extension(name: string | null) {
+
+ const found = name?.match(/\.([A-Za-z0-9]+)$/)
+
+ return found?.[1]?.toLowerCase() ?? null
+}
+
+function typeExtension(type: string | null) {
+
+ if (type?.split(";", 1)[0]?.toLowerCase() === "text/plain") return "txt"
+
+ if (type?.split(";", 1)[0]?.toLowerCase() === "application/json") return "json"
+
+ return "bin"
+}
diff --git a/source/server/view/view.ts b/source/server/view/view.ts
new file mode 100644
index 0000000..7b395fa
--- /dev/null
+++ b/source/server/view/view.ts
@@ -0,0 +1,136 @@
+import Application from "@server/core/application"
+import { serveStatic } from "@hono/node-server/serve-static"
+import { serve } from "@hono/node-server"
+import { WebSocketServer } from "ws"
+import doors from "./doors"
+import intake from "./intake"
+import program from "./program"
+import proxy from "./proxy"
+import storage from "./storage"
+import uploads from "./uploads"
+import link from "./link"
+import getPort from "get-port"
+import cfonts from "cfonts"
+import { Hono } from "hono"
+import { isAbsolute, resolve } from "node:path"
+import { styleText } from "node:util"
+import environment from "@libs/environment"
+
+export default async function (config: Config) {
+
+ const debugging = config.mode === "development"
+
+ cfonts.say(`${config.displayName} v${config.version}`, {
+
+ colors: ["blue", "white"],
+
+ font: "simple"
+ })
+
+ const application = await Application.initialize(config.name, config.displayName, config.version, config.storage, resolve("assets/default-icon.png"))
+
+ // One server, five doors, each at its own name. A program's client
+ // is still not the API — it is files a browser reads, with no link,
+ // no authorization and no operations — but a separate port was a
+ // second address for one machine. The names keep them apart.
+ const server = new Hono()
+
+ server.route(doors.link, link(application, debugging))
+
+ server.route(doors.proxy, proxy(application))
+
+ server.route(doors.storage, storage(application))
+
+ server.route(doors.uploads, uploads(application))
+
+ server.route(doors.program, program(application))
+
+ if (config.assets) server.use("*", serveStatic({ root: config.assets }))
+
+ const port = config.port ?? await getPort()
+
+ const hostname = config.hostname ?? "localhost"
+
+ await new Promise(function (resolve) {
+
+ serve({
+
+ port,
+
+ hostname,
+
+ fetch: server.fetch,
+
+ websocket: {
+
+ server: new WebSocketServer({ noServer: true })
+ }
+
+ }, resolve)
+ })
+
+ // Local program intake beside the way the network reaches the system.
+ // Not HTTP: it is a filesystem socket reachable only from this machine,
+ // for installing or running the one program a local project declares.
+ const socket = await intake(application, application.storage.join("intake.sock"))
+
+ const origin = `http://localhost:${port}`
+
+ if (config.assets) console.log(` ➜ ${styleText("bold", "Desktop:")} ${origin}`)
+
+ console.log(` ➜ ${styleText("bold", "Intake:")} ${socket}`)
+
+ return { origin }
+}
+
+export interface Config {
+
+ name: string
+
+ displayName: string
+
+ version: string
+
+ mode: "development" | "production"
+
+ /** Explicit instance storage. Omission selects the real user installation. */
+ storage?: string
+
+ assets?: string
+
+ hostname?: string
+
+ port?: number
+}
+
+/** Read the optional public port override named from the application identity. */
+export function environmentPort(name: string, variables: NodeJS.ProcessEnv) {
+
+ const selected = environment(name, "PORT", variables)
+
+ const value = selected.value
+
+ if (value === undefined) return undefined
+
+ if (!/^[0-9]+$/.test(value)) throw new Error(`${selected.key} must be an integer from 1 to 65535`)
+
+ const port = Number(value)
+
+ if (port < 1 || port > 65_535) throw new Error(`${selected.key} must be an integer from 1 to 65535`)
+
+ return port
+}
+
+/** Read an optional absolute home for an isolated development instance. */
+export function environmentHome(name: string, variables: NodeJS.ProcessEnv) {
+
+ const selected = environment(name, "HOME", variables)
+
+ const value = selected.value
+
+ if (value === undefined) return undefined
+
+ if (!isAbsolute(value)) throw new Error(`${selected.key} must be an absolute filesystem path`)
+
+ return value
+}
diff --git a/tsconfig.json b/tsconfig.json
new file mode 100644
index 0000000..654e12b
--- /dev/null
+++ b/tsconfig.json
@@ -0,0 +1,27 @@
+{
+ "compilerOptions": {
+ "moduleResolution": "bundler",
+ "noUnusedParameters": true,
+ "noUnusedLocals": true,
+ "skipLibCheck": true,
+ "module": "ESNext",
+ "target": "ESNext",
+ "jsx": "react-jsx",
+ "strict": true,
+ "noEmit": true,
+ "paths": {
+ "@/*": [
+ "./*"
+ ],
+ "@libs/*": [
+ "./source/libs/*"
+ ],
+ "@server/*": [
+ "./source/server/*"
+ ],
+ "@client/*": [
+ "./source/client/*"
+ ]
+ }
+ }
+}
diff --git a/vite.client.ts b/vite.client.ts
new file mode 100644
index 0000000..a38afca
--- /dev/null
+++ b/vite.client.ts
@@ -0,0 +1,23 @@
+import react, { reactCompilerPreset } from "@vitejs/plugin-react"
+import decoratorPlugin from "./source/libs/decorator-plugin.js"
+import tailwindcss from "@tailwindcss/vite"
+import babel from "@rolldown/plugin-babel"
+import { defineConfig } from "vite"
+import { resolve } from "node:path"
+
+export default defineConfig({
+ root: "source/client",
+ plugins: [
+ react(),
+ tailwindcss(),
+ decoratorPlugin(),
+ babel({ presets: [reactCompilerPreset()] })
+ ],
+ resolve: {
+ tsconfigPaths: true
+ },
+ build: {
+ emptyOutDir: true,
+ outDir: resolve(import.meta.dirname, "dist/client")
+ }
+})
diff --git a/vite.server.ts b/vite.server.ts
new file mode 100644
index 0000000..b81bc1f
--- /dev/null
+++ b/vite.server.ts
@@ -0,0 +1,29 @@
+import packageConfig from "./package.json" with { type: "json" }
+import decoratorPlugin from "./source/libs/decorator-plugin.js"
+import { defineConfig } from "vite"
+import { resolve } from "node:path"
+
+export const externalDependencies: (keyof typeof packageConfig.dependencies)[] = [
+ "cfonts",
+ "sharp"
+]
+
+export default defineConfig({
+ root: "source/server",
+ plugins: [decoratorPlugin()],
+ resolve: {
+ tsconfigPaths: true
+ },
+ ssr: {
+ noExternal: true,
+ external: externalDependencies
+ },
+ build: {
+ ssr: true,
+ emptyOutDir: true,
+ outDir: resolve(import.meta.dirname, "dist/server"),
+ rolldownOptions: {
+ input: "main.ts"
+ }
+ }
+})