Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat: add @alook/app — run Alook locally with one command (#73)

Genera9a351bb1797
diff --git a/.github/workflows/publish-app.yml b/.github/workflows/publish-app.yml
new file mode 100644
index 000000000..629b9af5c
--- /dev/null
+++ b/.github/workflows/publish-app.yml
@@ -0,0 +1,105 @@
+name: Publish App
+
+on:
+ push:
+ branches: [main]
+ paths: [src/app/package.json]
+
+concurrency:
+ group: publish-app
+ cancel-in-progress: false
+
+jobs:
+ publish:
+ name: Publish @alook/app to npm
+ runs-on: ubuntu-latest
+ timeout-minutes: 30
+ permissions:
+ id-token: write
+ contents: write
+ steps:
+ - uses: actions/checkout@v6
+
+ - name: Detect version
+ id: version
+ run: |
+ VERSION=$(node -p "require('./src/app/package.json').version")
+ echo "version=$VERSION" >> "$GITHUB_OUTPUT"
+ echo "tag=app/v$VERSION" >> "$GITHUB_OUTPUT"
+
+ - name: Check if version already published
+ id: check
+ run: |
+ if npm view "@alook/app@${{ steps.version.outputs.version }}" version >/dev/null 2>&1; then
+ echo "skip=true" >> "$GITHUB_OUTPUT"
+ echo "::notice::@alook/app@${{ steps.version.outputs.version }} already on npm — skipping"
+ else
+ echo "skip=false" >> "$GITHUB_OUTPUT"
+ fi
+
+ - uses: pnpm/action-setup@v6
+ if: steps.check.outputs.skip == 'false'
+
+ - uses: oven-sh/setup-bun@v2
+ if: steps.check.outputs.skip == 'false'
+
+ - uses: actions/setup-node@v6
+ if: steps.check.outputs.skip == 'false'
+ with:
+ node-version: 22
+ registry-url: https://registry.npmjs.org
+ cache: pnpm
+
+ - name: Upgrade npm for Trusted Publishers
+ if: steps.check.outputs.skip == 'false'
+ run: |
+ npm install -g --prefix="$RUNNER_TEMP/npm-new" npm@latest
+ echo "$RUNNER_TEMP/npm-new/bin" >> "$GITHUB_PATH"
+
+ - run: pnpm install --frozen-lockfile
+ if: steps.check.outputs.skip == 'false'
+
+ - name: Build all packages
+ if: steps.check.outputs.skip == 'false'
+ run: pnpm build
+
+ - name: Bundle app (pre-build workers)
+ if: steps.check.outputs.skip == 'false'
+ run: pnpm -C src/app run bundle
+
+ - name: Build app CLI
+ if: steps.check.outputs.skip == 'false'
+ run: pnpm -C src/app run build
+
+ - name: Publish to npm (OIDC)
+ if: steps.check.outputs.skip == 'false'
+ working-directory: src/app
+ run: npm publish --access public
+
+ - name: Create GitHub release
+ if: steps.check.outputs.skip == 'false'
+ env:
+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ run: gh release create "${{ steps.version.outputs.tag }}" --generate-notes --title "App v${{ steps.version.outputs.version }}"
+
+ - name: Notify Discord
+ if: steps.check.outputs.skip == 'false'
+ env:
+ DISCORD_WEBHOOK: ${{ secrets.DISCORD_WEBHOOK_URL }}
+ VERSION: ${{ steps.version.outputs.version }}
+ run: |
+ BODY=$(python3 -c "
+ import json, os
+ version = os.environ['VERSION']
+ payload = {
+ 'embeds': [{
+ 'title': f'📦 @alook/app v{version} published to npm',
+ 'description': 'Run Alook locally with one command:\n\n\`\`\`\nnpx @alook/app onboard\n\`\`\`',
+ 'color': 5025616,
+ 'url': f'https://www.npmjs.com/package/@alook/app/v/{version}',
+ 'footer': {'text': 'npm registry'},
+ }]
+ }
+ print(json.dumps(payload))
+ ")
+ curl -sf -H "Content-Type: application/json" -d "$BODY" "$DISCORD_WEBHOOK"
diff --git a/.gitignore b/.gitignore
index da077916a..8a73eb3c1 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,5 +1,6 @@
node_modules/
dist/
+bundled/
.turbo/
.wrangler/
.env
diff --git a/package.json b/package.json
index 8277fc3e2..e5d83a17f 100644
--- a/package.json
+++ b/package.json
@@ -6,7 +6,7 @@
"build": "turbo run build",
"test": "turbo run test",
"predev": "[ -f src/web/.dev.vars ] || (cp src/web/.dev.vars.example src/web/.dev.vars && sed -i '' \"s|^BETTER_AUTH_SECRET=$|BETTER_AUTH_SECRET=$(openssl rand -base64 32)|\" src/web/.dev.vars && sed -i '' \"s|^ENCRYPTION_KEY=$|ENCRYPTION_KEY=$(openssl rand -base64 32)|\" src/web/.dev.vars && echo '✓ Generated src/web/.dev.vars (fill in OAuth keys if needed)'); [ -f src/email-worker/.dev.vars ] || (cp src/email-worker/.dev.vars.example src/email-worker/.dev.vars && KEY=$(grep '^ENCRYPTION_KEY=' src/web/.dev.vars | cut -d= -f2-) && sed -i '' \"s|^ENCRYPTION_KEY=$|ENCRYPTION_KEY=$KEY|\" src/email-worker/.dev.vars && echo '✓ Generated src/email-worker/.dev.vars (synced ENCRYPTION_KEY from web)')",
- "dev": "turbo run dev --filter='!@alook/cli'",
+ "dev": "turbo run dev --filter='!@alook/cli' --filter='!@alook/app'",
"clean": "rm -rf node_modules src/*/node_modules src/*/dist src/*/.turbo .turbo src/web/.next src/web/.open-next src/*/.wrangler .alook",
"clean:builds": "rm -rf src/*/dist src/web/.next src/web/.open-next .turbo src/*/.turbo",
"reinstall": "pnpm run clean && pnpm install",
@@ -16,6 +16,7 @@
"dev:cli": "ALOOK_SERVER_URL=http://localhost:3000 ALOOK_PROJECT_ROOT=$PWD ALOOK_HEALTH_PORT=19515 pnpm --filter @alook/cli dev",
"dev:email": "pnpm --filter @alook/email-worker dev",
"dev:ws": "pnpm --filter @alook/ws-do dev",
+ "dev:app": "node scripts/dev-app.mjs",
"dev:meeting": "node scripts/dev-meeting.mjs",
"dev:send": "node -e \"const c=require('crypto');const a=process.argv.slice(1);const[f,t,s='Test',b='Hello from dev']=a;if(!f||!t){console.error('Usage: pnpm dev:send <from> <to> [subject] [body]');process.exit(1)}const raw=['From: '+f,'To: '+t,'Subject: '+s,'Message-ID: <'+c.randomUUID()+'@dev.local>','Date: '+new Date().toUTCString(),'MIME-Version: 1.0','Content-Type: text/plain; charset=utf-8','',b].join('\\r\\n');fetch('http://localhost:8787/cdn-cgi/handler/email?from='+encodeURIComponent(f)+'&to='+encodeURIComponent(t),{method:'POST',headers:{'Content-Type':'application/json'},body:raw}).then(r=>{if(r.ok)console.log('Email delivered to worker');else return r.text().then(t=>{throw new Error(t)})}).catch(e=>console.error('Email worker not running?',e.message))\"",
"test:shared": "pnpm --filter @alook/shared test",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 884261b52..ea6b5d076 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -24,6 +24,25 @@ importers:
specifier: ^4.90.0
version: 4.90.0(@cloudflare/[email protected])
+ src/app:
+ dependencies:
+ commander:
+ specifier: ^14.0.3
+ version: 14.0.3
+ wrangler:
+ specifier: ^4.90.0
+ version: 4.90.0(@cloudflare/[email protected])
+ devDependencies:
+ '@alook/shared':
+ specifier: workspace:*
+ version: link:../shared
+ '@types/bun':
+ specifier: ^1.3.13
+ version: 1.3.13
+ typescript:
+ specifier: ^6.0.3
+ version: 6.0.3
+
src/cli:
dependencies:
citty:
@@ -11154,8 +11173,8 @@ snapshots:
'@next/eslint-plugin-next': 16.2.6
eslint: 9.39.4([email protected])
eslint-import-resolver-node: 0.3.10
- eslint-import-resolver-typescript: 3.10.1([email protected])([email protected]([email protected]))
eslint-plugin-jsx-a11y: 6.10.2([email protected]([email protected]))
eslint-plugin-react: 7.37.5([email protected]([email protected]))
eslint-plugin-react-hooks: 7.1.1([email protected]([email protected]))
@@ -11177,7 +11196,7 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
'@nolyfill/is-core-module': 1.0.39
debug: 4.4.3
@@ -11188,22 +11207,22 @@ snapshots:
tinyglobby: 0.2.16
unrs-resolver: 1.11.1
optionalDependencies:
transitivePeerDependencies:
- supports-color
dependencies:
debug: 3.2.7
optionalDependencies:
'@typescript-eslint/parser': 8.59.2([email protected]([email protected]))([email protected])
eslint: 9.39.4([email protected])
eslint-import-resolver-node: 0.3.10
- eslint-import-resolver-typescript: 3.10.1([email protected])([email protected]([email protected]))
transitivePeerDependencies:
- supports-color
dependencies:
'@rtsao/scc': 1.1.0
array-includes: 3.1.9
@@ -11214,7 +11233,7 @@ snapshots:
doctrine: 2.1.0
eslint: 9.39.4([email protected])
eslint-import-resolver-node: 0.3.10
hasown: 2.0.3
is-core-module: 2.16.2
is-glob: 4.0.3
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index fa1850d25..1b6c74f1c 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -4,3 +4,4 @@ packages:
- "src/web"
- "src/email-worker"
- "src/ws-do"
+ - "src/app"
diff --git a/scripts/bump-version.mjs b/scripts/bump-version.mjs
index 9a6ba6613..868ff6e8c 100644
--- a/scripts/bump-version.mjs
+++ b/scripts/bump-version.mjs
@@ -4,7 +4,7 @@ import { join } from "node:path";
import { execSync } from "node:child_process";
const ROOT = new URL("..", import.meta.url).pathname.replace(/\/$/, "");
-const WORKSPACE_DIRS = ["src/shared", "src/cli", "src/web", "src/email-worker", "src/ws-do"];
+const WORKSPACE_DIRS = ["src/shared", "src/cli", "src/app", "src/web", "src/email-worker", "src/ws-do"];
function readPkg(dir) {
const p = join(ROOT, dir, "package.json");
diff --git a/scripts/dev-app.mjs b/scripts/dev-app.mjs
new file mode 100644
index 000000000..504ab0593
--- /dev/null
+++ b/scripts/dev-app.mjs
@@ -0,0 +1,26 @@
+#!/usr/bin/env node
+/**
+ * Dev wrapper for @alook/app — run from monorepo root:
+ * pnpm dev:app onboard
+ * pnpm dev:app start
+ * pnpm dev:app stop
+ *
+ * Dev mode runs all services directly from monorepo source — no bundle needed.
+ */
+import { spawn } from "child_process";
+import { join, dirname } from "path";
+import { fileURLToPath } from "url";
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const root = join(__dirname, "..");
+const appDir = join(root, "src", "app");
+
+const args = process.argv.slice(2);
+
+const child = spawn("bun", ["run", "src/index.ts", ...args], {
+ cwd: appDir,
+ stdio: "inherit",
+ env: { ...process.env, NODE_ENV: "development", ALOOK_PROJECT_ROOT: root },
+});
+
+child.on("exit", (code) => process.exit(code ?? 0));
diff --git a/src/app/README.md b/src/app/README.md
new file mode 100644
index 000000000..d2787d725
--- /dev/null
+++ b/src/app/README.md
@@ -0,0 +1,49 @@
+# @alook/app
+
+Run Alook locally — one command, no clone needed.
+
+## Quick Start
+
+```bash
+npx @alook/app onboard
+```
+
+This will:
+1. Install Alook to `~/.alook/self-hosted/`
+2. Initialize the database
+3. Start all services (web, email worker, WebSocket)
+4. Guide you through account creation
+5. Register your AI runtime (Claude, Codex, or OpenCode)
+6. Open the dashboard in your browser
+
+## Commands
+
+| Command | Description |
+| --- | --- |
+| `npx @alook/app onboard` | Full setup and start |
+| `npx @alook/app start` | Start existing installation |
+| `npx @alook/app stop` | Stop all services |
+| `npx @alook/app update` | Update to latest version |
+
+## Options
+
+```
+--port-web <port> Web server port (default: 3000)
+--port-email <port> Email worker port (default: 8787)
+--port-ws <port> WebSocket worker port (default: 8789)
+--skip-register Skip account creation
+```
+
+## Requirements
+
+- Node.js >= 20
+- One of: `claude`, `codex`, or `opencode` CLI installed
+
+## Limitations
+
+- Email send/receive is not available in local mode
+- OAuth login (GitHub, Google) is disabled; use email/password
+
+## License
+
+Apache-2.0
diff --git a/src/app/package.json b/src/app/package.json
new file mode 100644
index 000000000..976826b91
--- /dev/null
+++ b/src/app/package.json
@@ -0,0 +1,47 @@
+{
+ "name": "@alook/app",
+ "version": "0.0.1",
+ "description": "Run Alook locally — one command, no clone needed",
+ "license": "Apache-2.0",
+ "homepage": "https://github.com/alookai/alook#readme",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/alookai/alook.git",
+ "directory": "src/app"
+ },
+ "bugs": {
+ "url": "https://github.com/alookai/alook/issues"
+ },
+ "type": "module",
+ "bin": {
+ "alook-app": "dist/index.js"
+ },
+ "main": "./dist/index.js",
+ "files": [
+ "dist",
+ "bundled",
+ "README.md",
+ "LICENSE"
+ ],
+ "engines": {
+ "node": ">=20"
+ },
+ "publishConfig": {
+ "access": "public"
+ },
+ "scripts": {
+ "build": "bun build src/index.ts --outdir dist --target node --format esm --external commander --external wrangler",
+ "prepack": "pnpm run build",
+ "bundle": "bun run scripts/bundle.ts",
+ "test": "vitest run"
+ },
+ "dependencies": {
+ "commander": "^14.0.3",
+ "wrangler": "^4.90.0"
+ },
+ "devDependencies": {
+ "@alook/shared": "workspace:*",
+ "@types/bun": "^1.3.13",
+ "typescript": "^6.0.3"
+ }
+}
diff --git a/src/app/scripts/bundle.ts b/src/app/scripts/bundle.ts
new file mode 100644
index 000000000..1d54132d7
--- /dev/null
+++ b/src/app/scripts/bundle.ts
@@ -0,0 +1,69 @@
+#!/usr/bin/env bun
+/**
+ * Bundle script — run in CI before `npm publish` of @alook/app.
+ * Builds web (opennextjs-cloudflare), email-worker, and ws-do into
+ * pre-compiled bundles that can run with `wrangler dev --local` without
+ * needing source code or node_modules.
+ */
+import { execSync } from "child_process";
+import { cpSync, rmSync, mkdirSync, existsSync, readdirSync, readFileSync, writeFileSync } from "fs";
+import { join, dirname } from "path";
+import { fileURLToPath } from "url";
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const appRoot = join(__dirname, "..");
+const monoRoot = join(appRoot, "..", "..");
+const bundledDir = join(appRoot, "bundled");
+
+function run(cmd: string, cwd: string) {
+ console.log(`[bundle] ${cmd}`);
+ execSync(cmd, { cwd, stdio: "inherit" });
+}
+
+// Clean
+if (existsSync(bundledDir)) rmSync(bundledDir, { recursive: true });
+
+// --- Build Web ---
+console.log("\n=== Building Web (opennextjs-cloudflare) ===\n");
+const webSrc = join(monoRoot, "src", "web");
+run("npx opennextjs-cloudflare build", webSrc);
+
+const webDest = join(bundledDir, "web");
+mkdirSync(webDest, { recursive: true });
+cpSync(join(webSrc, ".open-next"), join(webDest, ".open-next"), { recursive: true });
+cpSync(join(webSrc, "wrangler.toml"), join(webDest, "wrangler.toml"));
+cpSync(join(webSrc, "custom-worker.ts"), join(webDest, "custom-worker.ts"));
+cpSync(join(webSrc, "migrations"), join(webDest, "migrations"), { recursive: true });
+
+// --- Build Email Worker ---
+console.log("\n=== Building Email Worker ===\n");
+const emailSrc = join(monoRoot, "src", "email-worker");
+const emailDest = join(bundledDir, "email-worker");
+mkdirSync(emailDest, { recursive: true });
+
+run("npx wrangler deploy --dry-run --outdir dist", emailSrc);
+cpSync(join(emailSrc, "dist", "index.js"), join(emailDest, "index.js"));
+
+const emailToml = readFileSync(join(emailSrc, "wrangler.toml"), "utf-8");
+writeFileSync(
+ join(emailDest, "wrangler.toml"),
+ emailToml.replace('main = "src/index.ts"', 'main = "index.js"'),
+);
+
+// --- Build WS-DO ---
+console.log("\n=== Building WS-DO ===\n");
+const wsSrc = join(monoRoot, "src", "ws-do");
+const wsDest = join(bundledDir, "ws-do");
+mkdirSync(wsDest, { recursive: true });
+
+run("npx wrangler deploy --dry-run --outdir dist", wsSrc);
+cpSync(join(wsSrc, "dist", "index.js"), join(wsDest, "index.js"));
+
+const wsToml = readFileSync(join(wsSrc, "wrangler.toml"), "utf-8");
+writeFileSync(
+ join(wsDest, "wrangler.toml"),
+ wsToml.replace('main = "src/index.ts"', 'main = "index.js"'),
+);
+
+console.log("\n✓ Bundle complete at:", bundledDir);
+console.log(" Contents:", readdirSync(bundledDir).join(", "));
diff --git a/src/app/src/commands/onboard.ts b/src/app/src/commands/onboard.ts
new file mode 100644
index 000000000..ccf144d4d
--- /dev/null
+++ b/src/app/src/commands/onboard.ts
@@ -0,0 +1,151 @@
+import { Command } from "commander";
+import { execSync, spawnSync, spawn as spawnAsync } from "child_process";
+import { checkNodeVersion, checkAIRuntime, checkPorts } from "../lib/checks.js";
+import { isInstalled, installBundled } from "../lib/install.js";
+import { ensureSecrets } from "../lib/secrets.js";
+import { runMigrations } from "../lib/migrate.js";
+import { startServices, isRunning } from "../lib/services.js";
+import {
+ collectEmail,
+ registerUser,
+ createWorkspace,
+ createMachineToken,
+ activateToken,
+ waitForServer,
+} from "../lib/register.js";
+import { DEFAULT_PORTS, WEB_URL, SELF_HOSTED_DIR } from "../lib/constants.js";
+import { patchWranglerConfigs } from "../lib/wrangler-config.js";
+
+export function onboardCommand(): Command {
+ return new Command("onboard")
+ .description("Set up and start Alook locally")
+ .option("--port-web <port>", "Web server port", String(DEFAULT_PORTS.web))
+ .option("--port-email <port>", "Email worker port", String(DEFAULT_PORTS.emailWorker))
+ .option("--port-ws <port>", "WebSocket worker port", String(DEFAULT_PORTS.wsDo))
+ .option("--skip-register", "Skip account creation (just start services)")
+ .action(async (opts) => {
+ const ports = {
+ web: parseInt(opts.portWeb, 10),
+ emailWorker: parseInt(opts.portEmail, 10),
+ wsDo: parseInt(opts.portWs, 10),
+ };
+
+ console.log("\n🚀 Alook Local Setup\n");
+
+ // 1. Environment checks
+ checkNodeVersion();
+
+ // 2. Check ports
+ await checkPorts(ports);
+
+ // 3. Check AI runtimes
+ console.log("Scanning for AI runtimes...");
+ const runtimes = checkAIRuntime();
+ if (runtimes.length === 0) {
+ console.error("Error: no AI runtimes found.");
+ console.error("Install one of: claude, codex, or opencode");
+ process.exit(1);
+ }
+ console.log(` Found: ${runtimes.map((r) => r.type).join(", ")}\n`);
+
+ const devMode = !!process.env.ALOOK_PROJECT_ROOT;
+
+ if (devMode) {
+ // Dev mode: run predev + migrations from monorepo
+ const root = process.env.ALOOK_PROJECT_ROOT!;
+ console.log("Preparing dev environment...");
+ try {
+ execSync("pnpm predev", { cwd: root, stdio: "inherit" });
+ } catch {}
+ execSync("pnpm db:migrate", { cwd: root, stdio: "inherit" });
+ } else {
+ // Production: install bundled assets
+ if (!isInstalled()) {
+ console.log("Installing Alook...");
+ installBundled();
+ } else {
+ console.log(`Installation found at ${SELF_HOSTED_DIR}`);
+ }
+
+ ensureSecrets(ports.web);
+ patchWranglerConfigs(ports);
+ runMigrations();
+ }
+
+ // 7. Collect user input before starting services
+ let email: string | undefined;
+ if (!opts.skipRegister) {
+ email = await collectEmail();
+ }
+
+ // 8. Start services
+ if (isRunning()) {
+ console.log("\nServices already running.");
+ } else {
+ startServices(ports, { foreground: devMode });
+ }
+
+ // 9. Wait for web server
+ const baseURL = WEB_URL(ports.web);
+ console.log("\nWaiting for server to be ready...");
+ await waitForServer(baseURL);
+ console.log(" ✓ Server ready\n");
+
+ // 10. Register with collected email
+ if (email) {
+ const { sessionCookie } = await registerUser(baseURL, email);
+ const workspace = await createWorkspace(baseURL, sessionCookie);
+ const { token } = await createMachineToken(baseURL, sessionCookie, workspace.id);
+ const { runtimeIds } = await activateToken(baseURL, token, runtimes);
+
+ console.log(` ✓ Daemon registered with ${runtimes.map((r) => r.type).join(", ")} runtime`);
+ console.log(` ✓ Machine token activated\n`);
+
+ // Start the daemon pointing to local server
+ // Pass ALOOK_PROJECT_ROOT so CLI stores config in the same .alook/ dir
+ const cliEnv: Record<string, string> = {
+ ...process.env as Record<string, string>,
+ ALOOK_SERVER_URL: baseURL,
+ };
+ if (process.env.ALOOK_PROJECT_ROOT) {
+ cliEnv.ALOOK_PROJECT_ROOT = process.env.ALOOK_PROJECT_ROOT;
+ }
+ console.log("Starting daemon...");
+ try {
+ spawnSync("npx", ["@alook/cli", "register", "--token", token], {
+ stdio: "inherit",
+ env: cliEnv,
+ });
+ spawnSync("npx", ["@alook/cli", "daemon", "start"], {
+ stdio: "inherit",
+ env: cliEnv,
+ });
+ } catch {
+ console.warn(" Warning: daemon auto-start failed. Start manually:");
+ console.warn(` ALOOK_SERVER_URL=${baseURL} npx @alook/cli register --token ${token}`);
+ console.warn(` ALOOK_SERVER_URL=${baseURL} npx @alook/cli daemon start`);
+ }
+ }
+
+ // 11. Print summary
+ console.log("\n" + "─".repeat(50));
+ console.log("\n⚠️ Local mode: email send/receive is not available.");
+ console.log(" To enable email, connect to alook.ai cloud.\n");
+ console.log("─".repeat(50));
+ console.log(`\n🎉 Alook is running!`);
+ console.log(` Dashboard: ${baseURL}`);
+ console.log(`\n Stop: npx @alook/app stop`);
+ console.log(` Start: npx @alook/app start`);
+ console.log(` Update: npx @alook/app update\n`);
+
+ // 12. Open browser
+ const openCmd = process.platform === "darwin" ? "open" :
+ process.platform === "win32" ? "cmd" : "xdg-open";
+ try {
+ const openArgs = process.platform === "win32"
+ ? ["/c", "start", "", baseURL]
+ : [baseURL];
+ spawnAsync(openCmd, openArgs, { stdio: "ignore", detached: true }).unref();
+ } catch {}
+ });
+}
diff --git a/src/app/src/commands/start.ts b/src/app/src/commands/start.ts
new file mode 100644
index 000000000..6282ffcab
--- /dev/null
+++ b/src/app/src/commands/start.ts
@@ -0,0 +1,35 @@
+import { Command } from "commander";
+import { checkPorts } from "../lib/checks.js";
+import { isInstalled } from "../lib/install.js";
+import { startServices, isRunning } from "../lib/services.js";
+import { DEFAULT_PORTS, WEB_URL } from "../lib/constants.js";
+
+export function startCommand(): Command {
+ return new Command("start")
+ .description("Start Alook services")
+ .option("--port-web <port>", "Web server port", String(DEFAULT_PORTS.web))
+ .option("--port-email <port>", "Email worker port", String(DEFAULT_PORTS.emailWorker))
+ .option("--port-ws <port>", "WebSocket worker port", String(DEFAULT_PORTS.wsDo))
+ .action(async (opts) => {
+ if (!isInstalled()) {
+ console.error("Error: Alook not installed. Run 'npx @alook/app onboard' first.");
+ process.exit(1);
+ }
+
+ if (isRunning()) {
+ console.log("Services already running.");
+ return;
+ }
+
+ const ports = {
+ web: parseInt(opts.portWeb, 10),
+ emailWorker: parseInt(opts.portEmail, 10),
+ wsDo: parseInt(opts.portWs, 10),
+ };
+
+ await checkPorts(ports);
+ startServices(ports, { foreground: !!process.env.ALOOK_PROJECT_ROOT });
+
+ console.log(`\nDashboard: ${WEB_URL(ports.web)}`);
+ });
+}
diff --git a/src/app/src/commands/stop.ts b/src/app/src/commands/stop.ts
new file mode 100644
index 000000000..44d58dd0a
--- /dev/null
+++ b/src/app/src/commands/stop.ts
@@ -0,0 +1,12 @@
+import { Command } from "commander";
+import { stopServices } from "../lib/services.js";
+
+export function stopCommand(): Command {
+ return new Command("stop")
+ .description("Stop all Alook services")
+ .action(() => {
+ console.log("Stopping Alook services...");
+ stopServices();
+ console.log("\nAll services stopped.");
+ });
+}
diff --git a/src/app/src/commands/update.ts b/src/app/src/commands/update.ts
new file mode 100644
index 000000000..0ce5f4270
--- /dev/null
+++ b/src/app/src/commands/update.ts
@@ -0,0 +1,32 @@
+import { Command } from "commander";
+import { stopServices, isRunning } from "../lib/services.js";
+import { installBundled } from "../lib/install.js";
+import { ensureSecrets } from "../lib/secrets.js";
+import { patchWranglerConfigs } from "../lib/wrangler-config.js";
+import { runMigrations } from "../lib/migrate.js";
+import { DEFAULT_PORTS } from "../lib/constants.js";
+
+export function updateCommand(): Command {
+ return new Command("update")
+ .description("Update Alook to the latest version")
+ .action(() => {
+ console.log("Updating Alook...\n");
+
+ if (isRunning()) {
+ console.log("Stopping running services...");
+ stopServices();
+ }
+
+ console.log("Installing latest version...");
+ installBundled();
+
+ ensureSecrets(DEFAULT_PORTS.web);
+ patchWranglerConfigs(DEFAULT_PORTS);
+
+ console.log("Running migrations...");
+ runMigrations();
+
+ console.log("\n✓ Update complete.");
+ console.log("Run 'npx @alook/app start' to restart.");
+ });
+}
diff --git a/src/app/src/index.ts b/src/app/src/index.ts
new file mode 100644
index 000000000..b445a4987
--- /dev/null
+++ b/src/app/src/index.ts
@@ -0,0 +1,34 @@
+#!/usr/bin/env node
+import { Command } from "commander";
+import { readFileSync } from "fs";
+import { join, dirname } from "path";
+import { fileURLToPath } from "url";
+import { onboardCommand } from "./commands/onboard.js";
+import { startCommand } from "./commands/start.js";
+import { stopCommand } from "./commands/stop.js";
+import { updateCommand } from "./commands/update.js";
+
+function getVersion(): string {
+ const __dirname = dirname(fileURLToPath(import.meta.url));
+ for (const candidate of [join(__dirname, "..", "package.json"), join(__dirname, "..", "..", "package.json")]) {
+ try {
+ const pkg = JSON.parse(readFileSync(candidate, "utf-8"));
+ if (pkg.version) return pkg.version;
+ } catch {}
+ }
+ return "0.0.0";
+}
+
+const program = new Command();
+
+program
+ .name("alook-app")
+ .description("Run Alook locally — one command, no clone needed")
+ .version(getVersion());
+
+program.addCommand(onboardCommand());
+program.addCommand(startCommand());
+program.addCommand(stopCommand());
+program.addCommand(updateCommand());
+
+program.parse();
diff --git a/src/app/src/lib/checks.ts b/src/app/src/lib/checks.ts
new file mode 100644
index 000000000..8efe0fe6f
--- /dev/null
+++ b/src/app/src/lib/checks.ts
@@ -0,0 +1,51 @@
+import { execSync } from "child_process";
+import { createConnection } from "net";
+
+export function checkNodeVersion(): void {
+ const major = parseInt(process.versions.node.split(".")[0], 10);
+ if (major < 20) {
+ console.error(`Error: Node.js >= 20 required (found ${process.versions.node})`);
+ process.exit(1);
+ }
+}
+
+export function checkAIRuntime(): { type: string; version: string }[] {
+ const found: { type: string; version: string }[] = [];
+ for (const type of ["claude", "codex", "opencode"]) {
+ try {
+ const check = process.platform === "win32" ? `where ${type}` : `which ${type}`;
+ execSync(check, { stdio: "ignore" });
+ let version = "";
+ try {
+ version = execSync(`${type} --version`, { encoding: "utf-8" }).trim();
+ } catch {}
+ found.push({ type, version });
+ } catch {}
+ }
+ return found;
+}
+
+export async function checkPort(port: number): Promise<boolean> {
+ return new Promise((resolve) => {
+ const conn = createConnection({ port, host: "127.0.0.1" });
+ conn.on("connect", () => { conn.destroy(); resolve(false); });
+ conn.on("error", () => { resolve(true); });
+ });
+}
+
+export async function checkPorts(ports: { web: number; emailWorker: number; wsDo: number }): Promise<void> {
+ const checks = [
+ { name: "web", port: ports.web },
+ { name: "email-worker", port: ports.emailWorker },
+ { name: "ws-do", port: ports.wsDo },
+ ];
+
+ for (const { name, port } of checks) {
+ const available = await checkPort(port);
+ if (!available) {
+ console.error(`Error: port ${port} (${name}) is already in use.`);
+ console.error(`Use --port-web, --port-email, --port-ws to specify alternative ports.`);
+ process.exit(1);
+ }
+ }
+}
diff --git a/src/app/src/lib/constants.ts b/src/app/src/lib/constants.ts
new file mode 100644
index 000000000..91b2013d0
--- /dev/null
+++ b/src/app/src/lib/constants.ts
@@ -0,0 +1,20 @@
+import { homedir } from "os";
+import { join } from "path";
+
+function resolveBaseDir(): string {
+ if (process.env.ALOOK_PROJECT_ROOT) {
+ return join(process.env.ALOOK_PROJECT_ROOT, ".alook", "self-hosted");
+ }
+ return join(homedir(), ".alook", "self-hosted");
+}
+
+export const SELF_HOSTED_DIR = resolveBaseDir();
+export const PID_FILE = join(SELF_HOSTED_DIR, ".pids.json");
+
+export const DEFAULT_PORTS = {
+ web: 3000,
+ emailWorker: 8787,
+ wsDo: 8789,
+} as const;
+
+export const WEB_URL = (port: number) => `http://localhost:${port}`;
diff --git a/src/app/src/lib/install.ts b/src/app/src/lib/install.ts
new file mode 100644
index 000000000..eb2b0289a
--- /dev/null
+++ b/src/app/src/lib/install.ts
@@ -0,0 +1,25 @@
+import { cpSync, existsSync, mkdirSync } from "fs";
+import { join, dirname } from "path";
+import { fileURLToPath } from "url";
+import { SELF_HOSTED_DIR } from "./constants.js";
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+
+function bundledDir(): string {
+ const candidate = join(__dirname, "..", "..", "bundled");
+ if (existsSync(candidate)) return candidate;
+ const npmCandidate = join(__dirname, "..", "bundled");
+ if (existsSync(npmCandidate)) return npmCandidate;
+ throw new Error("Cannot find bundled directory. Package may be corrupted.");
+}
+
+export function isInstalled(): boolean {
+ return existsSync(join(SELF_HOSTED_DIR, "web", "wrangler.toml"));
+}
+
+export function installBundled(): void {
+ const src = bundledDir();
+ mkdirSync(SELF_HOSTED_DIR, { recursive: true });
+ cpSync(src, SELF_HOSTED_DIR, { recursive: true });
+ console.log(`Installed to ${SELF_HOSTED_DIR}`);
+}
diff --git a/src/app/src/lib/migrate.ts b/src/app/src/lib/migrate.ts
new file mode 100644
index 000000000..9f4e6cd57
--- /dev/null
+++ b/src/app/src/lib/migrate.ts
@@ -0,0 +1,18 @@
+import { execSync } from "child_process";
+import { join } from "path";
+import { SELF_HOSTED_DIR } from "./constants.js";
+
+export function runMigrations(): void {
+ const webDir = join(SELF_HOSTED_DIR, "web");
+ console.log("Running database migrations...");
+ try {
+ execSync("npx wrangler d1 migrations apply alook-app --local", {
+ cwd: webDir,
+ stdio: "inherit",
+ });
+ console.log("Migrations complete");
+ } catch (err) {
+ console.error("Error: failed to run migrations");
+ process.exit(1);
+ }
+}
diff --git a/src/app/src/lib/pid.ts b/src/app/src/lib/pid.ts
new file mode 100644
index 000000000..5bb191fed
--- /dev/null
+++ b/src/app/src/lib/pid.ts
@@ -0,0 +1,36 @@
+import { readFileSync, writeFileSync, existsSync, unlinkSync, mkdirSync } from "fs";
+import { dirname } from "path";
+import { PID_FILE } from "./constants.js";
+
+interface PidRecord {
+ web?: number;
+ emailWorker?: number;
+ wsDo?: number;
+}
+
+export function readPids(): PidRecord {
+ if (!existsSync(PID_FILE)) return {};
+ try {
+ return JSON.parse(readFileSync(PID_FILE, "utf-8"));
+ } catch {
+ return {};
+ }
+}
+
+export function writePids(pids: PidRecord): void {
+ mkdirSync(dirname(PID_FILE), { recursive: true });
+ writeFileSync(PID_FILE, JSON.stringify(pids, null, 2), { mode: 0o600 });
+}
+
+export function clearPids(): void {
+ if (existsSync(PID_FILE)) unlinkSync(PID_FILE);
+}
+
+export function isAlive(pid: number): boolean {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch {
+ return false;
+ }
+}
diff --git a/src/app/src/lib/register.ts b/src/app/src/lib/register.ts
new file mode 100644
index 000000000..dfed90f73
--- /dev/null
+++ b/src/app/src/lib/register.ts
@@ -0,0 +1,201 @@
+import { createInterface } from "readline";
+import { DEV_PASSWORD } from "@alook/shared";
+import { SELF_HOSTED_DIR } from "./constants.js";
+import { join } from "path";
+
+interface SignupResult {
+ sessionCookie: string;
+ userId: string;
+}
+
+interface WorkspaceResult {
+ id: string;
+ name: string;
+ slug: string;
+}
+
+interface TokenResult {
+ token: string;
+ id: string;
+}
+
+interface RuntimeInfo {
+ type: string;
+ version: string;
+}
+
+function prompt(question: string): Promise<string> {
+ return new Promise((resolve) => {
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
+ rl.question(question, (answer) => { rl.close(); resolve(answer); });
+ });
+}
+
+function extractSession(res: Response): { sessionCookie: string; userId: string } | null {
+ const cookies = res.headers.getSetCookie?.() || [];
+ const sessionCookie = cookies.find((c) => c.includes("better-auth.session_token")) || "";
+ if (!sessionCookie) return null;
+ return { sessionCookie, userId: "" };
+}
+
+export async function collectEmail(): Promise<string> {
+ const { userInfo } = await import("os");
+ const defaultEmail = `${userInfo().username || "user"}@local.alook`;
+ console.log("\n📝 Create your account:\n");
+ const input = await prompt(` Email (${defaultEmail}): `);
+ return input.trim() || defaultEmail;
+}
+
+export async function registerUser(baseURL: string, email: string): Promise<SignupResult> {
+ const { userInfo } = await import("os");
+ const name = userInfo().username || "User";
+ const password = DEV_PASSWORD;
+
+ let res = await fetch(`${baseURL}/api/auth/sign-up/email`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ email, password, name }),
+ redirect: "manual",
+ });
+
+ if (!res.ok) {
+ const text = await res.text();
+ if (text.includes("already exists") || text.includes("already registered") || text.includes("User already")) {
+ res = await fetch(`${baseURL}/api/auth/sign-in/email`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ email, password }),
+ redirect: "manual",
+ });
+
+ if (!res.ok) {
+ console.error(`\nError: account exists but could not sign in.`);
+ console.error(`Open ${baseURL} in browser and sign in manually.`);
+ process.exit(1);
+ }
+
+ const session = extractSession(res);
+ if (!session) {
+ console.error(`\nError: account exists but could not get session.`);
+ console.error(`Open ${baseURL} in browser and sign in manually.`);
+ process.exit(1);
+ }
+ console.log(` ✓ Signed in (${email})`);
+ return session;
+ }
+ console.error(`\nError: signup failed (${res.status}): ${text}`);
+ process.exit(1);
+ }
+
+ const session = extractSession(res);
+ if (!session) {
+ console.error("\nError: no session cookie received after signup");
+ process.exit(1);
+ }
+
+ console.log(` ✓ Account created (${email})`);
+ return session;
+}
+
+export async function createWorkspace(baseURL: string, cookie: string): Promise<WorkspaceResult> {
+ const res = await fetch(`${baseURL}/api/workspaces`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Cookie: cookie,
+ },
+ body: JSON.stringify({ name: "Personal", slug: "personal" }),
+ });
+
+ if (!res.ok) {
+ const listRes = await fetch(`${baseURL}/api/workspaces`, {
+ headers: { Cookie: cookie },
+ });
+ if (listRes.ok) {
+ const workspaces = (await listRes.json()) as WorkspaceResult[];
+ if (workspaces.length > 0) return workspaces[0];
+ }
+ console.error("Error: failed to create workspace");
+ process.exit(1);
+ }
+
+ const ws = (await res.json()) as WorkspaceResult;
+ console.log(` ✓ Workspace "${ws.name}" ready`);
+ return ws;
+}
+
+export async function createMachineToken(
+ baseURL: string,
+ cookie: string,
+ workspaceId: string,
+): Promise<TokenResult> {
+ const res = await fetch(`${baseURL}/api/machine-tokens?workspace_id=${workspaceId}`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Cookie: cookie,
+ },
+ body: JSON.stringify({ name: "local-onboard" }),
+ });
+
+ if (!res.ok) {
+ const text = await res.text();
+ console.error(`Error: failed to create machine token (${res.status}): ${text}`);
+ process.exit(1);
+ }
+
+ return (await res.json()) as TokenResult;
+}
+
+export async function activateToken(
+ baseURL: string,
+ token: string,
+ runtimes: RuntimeInfo[],
+): Promise<{ workspaceId: string; runtimeIds: string[] }> {
+ const { hostname } = await import("os");
+
+ const res = await fetch(`${baseURL}/api/machine-tokens/activate`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ token,
+ hostname: hostname(),
+ runtimes,
+ }),
+ });
+
+ if (!res.ok) {
+ const text = await res.text();
+ console.error(`Error: failed to activate token (${res.status}): ${text}`);
+ process.exit(1);
+ }
+
+ const data = (await res.json()) as {
+ workspace_id: string;
+ runtimes: { id: string; provider: string }[];
+ };
+
+ return {
+ workspaceId: data.workspace_id,
+ runtimeIds: data.runtimes.map((r) => r.id),
+ };
+}
+
+export async function waitForServer(baseURL: string, timeoutMs = 90000): Promise<void> {
+ const deadline = Date.now() + timeoutMs;
+ let dots = 0;
+ while (Date.now() < deadline) {
+ try {
+ const res = await fetch(`${baseURL}/api/auth/session`, { method: "GET" });
+ if (res.status < 500) return;
+ } catch {}
+ dots++;
+ if (dots % 10 === 0) {
+ process.stdout.write(" still starting...\n");
+ }
+ await new Promise((r) => setTimeout(r, 1000));
+ }
+ console.error("Error: server did not start within 90 seconds");
+ console.error(`Check logs at ${join(SELF_HOSTED_DIR, "logs", "web.log")}`);
+ process.exit(1);
+}
diff --git a/src/app/src/lib/secrets.ts b/src/app/src/lib/secrets.ts
new file mode 100644
index 000000000..5b2abc1d4
--- /dev/null
+++ b/src/app/src/lib/secrets.ts
@@ -0,0 +1,48 @@
+import { existsSync, writeFileSync, readFileSync } from "fs";
+import { randomBytes } from "crypto";
+import { join } from "path";
+import { SELF_HOSTED_DIR } from "./constants.js";
+
+function generateSecret(): string {
+ return randomBytes(32).toString("base64");
+}
+
+function extractKey(filePath: string, key: string): string | null {
+ try {
+ const content = readFileSync(filePath, "utf-8");
+ const match = content.match(new RegExp(`^${key}=(.+)$`, "m"));
+ return match?.[1] ?? null;
+ } catch {
+ return null;
+ }
+}
+
+export function ensureSecrets(webPort: number): void {
+ const webVars = join(SELF_HOSTED_DIR, "web", ".dev.vars");
+ const emailVars = join(SELF_HOSTED_DIR, "email-worker", ".dev.vars");
+
+ if (!existsSync(webVars)) {
+ const authSecret = generateSecret();
+ const encryptionKey = generateSecret();
+ const content = [
+ `BETTER_AUTH_SECRET=${authSecret}`,
+ `BETTER_AUTH_URL=http://localhost:${webPort}`,
+ `ENCRYPTION_KEY=${encryptionKey}`,
+ `GITHUB_CLIENT_ID=`,
+ `GITHUB_CLIENT_SECRET=`,
+ `GOOGLE_CLIENT_ID=`,
+ `GOOGLE_CLIENT_SECRET=`,
+ ].join("\n");
+ writeFileSync(webVars, content, { mode: 0o600 });
+ console.log("Generated web secrets");
+
+ writeFileSync(emailVars, `ENCRYPTION_KEY=${encryptionKey}\n`, { mode: 0o600 });
+ console.log("Generated email-worker secrets");
+ } else if (!existsSync(emailVars)) {
+ const encryptionKey = extractKey(webVars, "ENCRYPTION_KEY") || generateSecret();
+ writeFileSync(emailVars, `ENCRYPTION_KEY=${encryptionKey}\n`, { mode: 0o600 });
+ console.log("Synced email-worker secrets from web");
+ } else {
+ console.log("Secrets already exist, skipping");
+ }
+}
diff --git a/src/app/src/lib/services.ts b/src/app/src/lib/services.ts
new file mode 100644
index 000000000..7d2c032c5
--- /dev/null
+++ b/src/app/src/lib/services.ts
@@ -0,0 +1,169 @@
+import { spawn, execSync, type ChildProcess } from "child_process";
+import { join } from "path";
+import { openSync, mkdirSync, closeSync } from "fs";
+import { SELF_HOSTED_DIR } from "./constants.js";
+import { writePids, readPids, isAlive, clearPids } from "./pid.js";
+
+interface ServicePorts {
+ web: number;
+ emailWorker: number;
+ wsDo: number;
+}
+
+interface StartOptions {
+ foreground?: boolean;
+}
+
+function isDevMode(): boolean {
+ return !!process.env.ALOOK_PROJECT_ROOT;
+}
+
+function logDir(): string {
+ const dir = join(SELF_HOSTED_DIR, "logs");
+ mkdirSync(dir, { recursive: true });
+ return dir;
+}
+
+function spawnService(name: string, cmd: string, args: string[], cwd: string, foreground: boolean): ChildProcess {
+ if (foreground) {
+ const child = spawn(cmd, args, {
+ cwd,
+ stdio: ["ignore", "pipe", "pipe"],
+ env: { ...process.env, NODE_ENV: "development" },
+ });
+ child.stdout?.on("data", (data: Buffer) => {
+ const lines = data.toString().trimEnd();
+ if (lines) console.log(`[${name}] ${lines}`);
+ });
+ child.stderr?.on("data", (data: Buffer) => {
+ const lines = data.toString().trimEnd();
+ if (lines) console.log(`[${name}] ${lines}`);
+ });
+ return child;
+ }
+ const logPath = join(logDir(), `${name}.log`);
+ const logFd = openSync(logPath, "a", 0o600);
+ const child = spawn(cmd, args, {
+ cwd,
+ detached: true,
+ stdio: ["ignore", logFd, logFd],
+ env: { ...process.env, NODE_ENV: "development" },
+ });
+ child.unref();
+ closeSync(logFd);
+ return child;
+}
+
+function killProcess(pid: number): boolean {
+ try {
+ if (process.platform === "win32") {
+ execSync(`taskkill /F /T /PID ${pid}`, { stdio: "ignore" });
+ } else {
+ try {
+ process.kill(-pid, "SIGTERM");
+ } catch {
+ process.kill(pid, "SIGTERM");
+ }
+ }
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+export function startServices(ports: ServicePorts, opts: StartOptions = {}): void {
+ const existing = readPids();
+ const anyAlive = [existing.web, existing.emailWorker, existing.wsDo].some(
+ (pid) => pid && isAlive(pid),
+ );
+ if (anyAlive) {
+ console.log("Services already running. Use 'alook-app stop' first.");
+ return;
+ }
+
+ const foreground = opts.foreground ?? false;
+ console.log(`Starting services${foreground ? " (foreground)" : ""}...`);
+
+ let webChild: ChildProcess;
+ let emailChild: ChildProcess;
+ let wsChild: ChildProcess;
+
+ if (isDevMode()) {
+ const root = process.env.ALOOK_PROJECT_ROOT!;
+ const webDir = join(root, "src", "web");
+ const emailDir = join(root, "src", "email-worker");
+ const wsDir = join(root, "src", "ws-do");
+ const persistTo = ["--persist-to", join(webDir, ".wrangler", "state")];
+
+ webChild = spawnService("web", "npx", ["next", "dev", "--port", String(ports.web)], webDir, foreground);
+ emailChild = spawnService("email-worker", "npx", ["wrangler", "dev", "--local", "--port", String(ports.emailWorker), ...persistTo], emailDir, foreground);
+ wsChild = spawnService("ws-do", "npx", ["wrangler", "dev", "--local", "--port", String(ports.wsDo), ...persistTo], wsDir, foreground);
+ } else {
+ webChild = spawnService("web", "npx", ["wrangler", "dev", "--local", "--port", String(ports.web)], join(SELF_HOSTED_DIR, "web"), foreground);
+ emailChild = spawnService("email-worker", "npx", ["wrangler", "dev", "--local", "--port", String(ports.emailWorker)], join(SELF_HOSTED_DIR, "email-worker"), foreground);
+ wsChild = spawnService("ws-do", "npx", ["wrangler", "dev", "--local", "--port", String(ports.wsDo)], join(SELF_HOSTED_DIR, "ws-do"), foreground);
+ }
+
+ if (!webChild.pid || !emailChild.pid || !wsChild.pid) {
+ console.error("Error: failed to start one or more services.");
+ for (const child of [webChild, emailChild, wsChild]) {
+ if (child.pid) killProcess(child.pid);
+ }
+ process.exit(1);
+ }
+
+ writePids({
+ web: webChild.pid,
+ emailWorker: emailChild.pid,
+ wsDo: wsChild.pid,
+ });
+
+ console.log(` Web: http://localhost:${ports.web} (pid=${webChild.pid})`);
+ console.log(` Email Worker: port ${ports.emailWorker} (pid=${emailChild.pid})`);
+ console.log(` WS-DO: port ${ports.wsDo} (pid=${wsChild.pid})`);
+
+ if (foreground) {
+ let exiting = false;
+ const cleanup = () => {
+ if (exiting) return;
+ exiting = true;
+ console.log("\nStopping services...");
+ for (const child of [webChild, emailChild, wsChild]) {
+ if (child.pid) killProcess(child.pid);
+ }
+ clearPids();
+ process.exit(0);
+ };
+ process.on("SIGINT", cleanup);
+ process.on("SIGTERM", cleanup);
+ }
+}
+
+export function stopServices(): void {
+ const pids = readPids();
+ let stopped = 0;
+
+ for (const [name, pid] of Object.entries(pids)) {
+ if (pid && isAlive(pid)) {
+ if (killProcess(pid)) {
+ stopped++;
+ console.log(` Stopped ${name} (pid=${pid})`);
+ } else {
+ console.warn(` Could not stop ${name} (pid=${pid})`);
+ }
+ }
+ }
+
+ if (stopped === 0) {
+ console.log("No running services found.");
+ }
+
+ clearPids();
+}
+
+export function isRunning(): boolean {
+ const pids = readPids();
+ return [pids.web, pids.emailWorker, pids.wsDo].some(
+ (pid) => pid && isAlive(pid),
+ );
+}
diff --git a/src/app/src/lib/wrangler-config.ts b/src/app/src/lib/wrangler-config.ts
new file mode 100644
index 000000000..011843013
--- /dev/null
+++ b/src/app/src/lib/wrangler-config.ts
@@ -0,0 +1,42 @@
+import { readFileSync, writeFileSync } from "fs";
+import { join } from "path";
+import { SELF_HOSTED_DIR } from "./constants.js";
+
+function setDevPort(tomlPath: string, port: number): void {
+ let content = readFileSync(tomlPath, "utf-8");
+ if (content.includes("[dev]")) {
+ content = content.replace(/(\[dev\][^\[]*?)port\s*=\s*\d+/, `$1port = ${port}`);
+ } else {
+ content += `\n[dev]\nport = ${port}\n`;
+ }
+ writeFileSync(tomlPath, content);
+}
+
+function setVar(content: string, key: string, value: string): string {
+ const pattern = new RegExp(`${key}\\s*=\\s*"[^"]*"`);
+ if (pattern.test(content)) {
+ return content.replace(pattern, `${key} = "${value}"`);
+ }
+ if (content.includes("[vars]")) {
+ return content.replace(/\[vars\]/, `[vars]\n${key} = "${value}"`);
+ }
+ return content + `\n[vars]\n${key} = "${value}"\n`;
+}
+
+export function patchWranglerConfigs(ports: { web: number; emailWorker: number; wsDo: number }): void {
+ const webToml = join(SELF_HOSTED_DIR, "web", "wrangler.toml");
+ let webContent = readFileSync(webToml, "utf-8");
+
+ if (!webContent.includes("[dev]")) {
+ webContent += `\n[dev]\nport = ${ports.web}\n`;
+ } else {
+ webContent = webContent.replace(/(\[dev\][^\[]*?)port\s*=\s*\d+/, `$1port = ${ports.web}`);
+ }
+
+ webContent = setVar(webContent, "DEV_WS_DO_URL", `http://localhost:${ports.wsDo}`);
+ webContent = setVar(webContent, "DEV_EMAIL_WORKER_URL", `http://localhost:${ports.emailWorker}`);
+ writeFileSync(webToml, webContent);
+
+ setDevPort(join(SELF_HOSTED_DIR, "email-worker", "wrangler.toml"), ports.emailWorker);
+ setDevPort(join(SELF_HOSTED_DIR, "ws-do", "wrangler.toml"), ports.wsDo);
+}
diff --git a/src/app/test/checks.test.ts b/src/app/test/checks.test.ts
new file mode 100644
index 000000000..aea1da201
--- /dev/null
+++ b/src/app/test/checks.test.ts
@@ -0,0 +1,27 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+
+describe("checks", () => {
+ describe("checkNodeVersion", () => {
+ it("does not exit for Node >= 20", async () => {
+ const exitSpy = vi.spyOn(process, "exit").mockImplementation((() => {
+ throw new Error("exit");
+ }) as never);
+
+ const { checkNodeVersion } = await import("../src/lib/checks.js");
+ const major = parseInt(process.versions.node.split(".")[0], 10);
+ if (major >= 20) {
+ expect(() => checkNodeVersion()).not.toThrow();
+ }
+ exitSpy.mockRestore();
+ });
+ });
+
+ describe("checkPort", () => {
+ it("returns true for an unused port", async () => {
+ const { checkPort } = await import("../src/lib/checks.js");
+ // Port 0 or a random high port should be unused
+ const result = await checkPort(49999);
+ expect(result).toBe(true);
+ });
+ });
+});
diff --git a/src/app/test/pid.test.ts b/src/app/test/pid.test.ts
new file mode 100644
index 000000000..4e85cccfb
--- /dev/null
+++ b/src/app/test/pid.test.ts
@@ -0,0 +1,75 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
+import { readFileSync, existsSync, unlinkSync, mkdirSync } from "fs";
+import { join } from "path";
+import { tmpdir } from "os";
+
+vi.mock("../src/lib/constants.js", () => {
+ const dir = join(tmpdir(), `alook-test-pid-${process.pid}`);
+ return {
+ SELF_HOSTED_DIR: dir,
+ PID_FILE: join(dir, ".pids.json"),
+ };
+});
+
+const { readPids, writePids, clearPids, isAlive } = await import("../src/lib/pid.js");
+const { PID_FILE, SELF_HOSTED_DIR } = await import("../src/lib/constants.js");
+
+describe("pid", () => {
+ beforeEach(() => {
+ mkdirSync(SELF_HOSTED_DIR, { recursive: true });
+ if (existsSync(PID_FILE)) unlinkSync(PID_FILE);
+ });
+
+ afterEach(() => {
+ if (existsSync(PID_FILE)) unlinkSync(PID_FILE);
+ });
+
+ describe("readPids", () => {
+ it("returns empty record when no file exists", () => {
+ expect(readPids()).toEqual({});
+ });
+
+ it("returns parsed pids when file exists", () => {
+ const pids = { web: 1234, emailWorker: 5678, wsDo: 9012 };
+ writePids(pids);
+ expect(readPids()).toEqual(pids);
+ });
+
+ it("returns empty record for corrupted file", () => {
+ const { writeFileSync } = require("fs");
+ writeFileSync(PID_FILE, "not json");
+ expect(readPids()).toEqual({});
+ });
+ });
+
+ describe("writePids", () => {
+ it("writes pids with restricted permissions", () => {
+ writePids({ web: 100, emailWorker: 200, wsDo: 300 });
+ const content = JSON.parse(readFileSync(PID_FILE, "utf-8"));
+ expect(content).toEqual({ web: 100, emailWorker: 200, wsDo: 300 });
+ });
+ });
+
+ describe("clearPids", () => {
+ it("removes pid file", () => {
+ writePids({ web: 1 });
+ expect(existsSync(PID_FILE)).toBe(true);
+ clearPids();
+ expect(existsSync(PID_FILE)).toBe(false);
+ });
+
+ it("does not throw when file does not exist", () => {
+ expect(() => clearPids()).not.toThrow();
+ });
+ });
+
+ describe("isAlive", () => {
+ it("returns true for current process", () => {
+ expect(isAlive(process.pid)).toBe(true);
+ });
+
+ it("returns false for non-existent pid", () => {
+ expect(isAlive(999999)).toBe(false);
+ });
+ });
+});
diff --git a/src/app/test/secrets.test.ts b/src/app/test/secrets.test.ts
new file mode 100644
index 000000000..d71d05b9b
--- /dev/null
+++ b/src/app/test/secrets.test.ts
@@ -0,0 +1,72 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
+import { writeFileSync, mkdirSync, existsSync, rmSync } from "fs";
+import { join } from "path";
+import { tmpdir } from "os";
+
+const testDir = join(tmpdir(), `alook-test-secrets-${process.pid}`);
+
+vi.mock("../src/lib/constants.js", () => ({
+ SELF_HOSTED_DIR: testDir,
+ PID_FILE: join(testDir, ".pids.json"),
+ DEFAULT_PORTS: { web: 3000, emailWorker: 8787, wsDo: 8789 },
+ WEB_URL: (port: number) => `http://localhost:${port}`,
+}));
+
+describe("secrets", () => {
+ beforeEach(() => {
+ mkdirSync(join(testDir, "web"), { recursive: true });
+ mkdirSync(join(testDir, "email-worker"), { recursive: true });
+ });
+
+ afterEach(() => {
+ if (existsSync(testDir)) {
+ rmSync(testDir, { recursive: true, force: true });
+ }
+ vi.resetModules();
+ });
+
+ it("generates new secrets when none exist", async () => {
+ const { ensureSecrets } = await import("../src/lib/secrets.js");
+ ensureSecrets(3000);
+
+ const webVars = join(testDir, "web", ".dev.vars");
+ const emailVars = join(testDir, "email-worker", ".dev.vars");
+
+ expect(existsSync(webVars)).toBe(true);
+ expect(existsSync(emailVars)).toBe(true);
+
+ const { readFileSync } = require("fs");
+ const webContent = readFileSync(webVars, "utf-8");
+ expect(webContent).toContain("BETTER_AUTH_SECRET=");
+ expect(webContent).toContain("ENCRYPTION_KEY=");
+ expect(webContent).toContain("BETTER_AUTH_URL=http://localhost:3000");
+ });
+
+ it("syncs encryption key from web to email-worker when email vars missing", async () => {
+ // Pre-create web vars with a known key
+ writeFileSync(
+ join(testDir, "web", ".dev.vars"),
+ "BETTER_AUTH_SECRET=abc\nENCRYPTION_KEY=test-key-123\n",
+ { mode: 0o600 },
+ );
+
+ const { ensureSecrets } = await import("../src/lib/secrets.js");
+ ensureSecrets(3000);
+
+ const { readFileSync } = require("fs");
+ const emailContent = readFileSync(join(testDir, "email-worker", ".dev.vars"), "utf-8");
+ expect(emailContent).toContain("ENCRYPTION_KEY=test-key-123");
+ });
+
+ it("skips when both secret files already exist", async () => {
+ writeFileSync(join(testDir, "web", ".dev.vars"), "existing", { mode: 0o600 });
+ writeFileSync(join(testDir, "email-worker", ".dev.vars"), "existing", { mode: 0o600 });
+
+ const consoleSpy = vi.spyOn(console, "log");
+ const { ensureSecrets } = await import("../src/lib/secrets.js");
+ ensureSecrets(3000);
+
+ expect(consoleSpy).toHaveBeenCalledWith("Secrets already exist, skipping");
+ consoleSpy.mockRestore();
+ });
+});
diff --git a/src/app/test/services.test.ts b/src/app/test/services.test.ts
new file mode 100644
index 000000000..c4faff754
--- /dev/null
+++ b/src/app/test/services.test.ts
@@ -0,0 +1,69 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
+import { mkdirSync, existsSync, rmSync, writeFileSync } from "fs";
+import { join } from "path";
+import { tmpdir } from "os";
+
+const testDir = join(tmpdir(), `alook-test-services-${process.pid}`);
+
+vi.mock("../src/lib/constants.js", () => ({
+ SELF_HOSTED_DIR: testDir,
+ PID_FILE: join(testDir, ".pids.json"),
+ DEFAULT_PORTS: { web: 3000, emailWorker: 8787, wsDo: 8789 },
+ WEB_URL: (port: number) => `http://localhost:${port}`,
+}));
+
+describe("services", () => {
+ beforeEach(() => {
+ mkdirSync(testDir, { recursive: true });
+ });
+
+ afterEach(() => {
+ if (existsSync(testDir)) {
+ rmSync(testDir, { recursive: true, force: true });
+ }
+ vi.resetModules();
+ });
+
+ describe("isRunning", () => {
+ it("returns false when no pid file exists", async () => {
+ const { isRunning } = await import("../src/lib/services.js");
+ expect(isRunning()).toBe(false);
+ });
+
+ it("returns false when all pids are dead", async () => {
+ const { writePids } = await import("../src/lib/pid.js");
+ writePids({ web: 999999, emailWorker: 999998, wsDo: 999997 });
+ const { isRunning } = await import("../src/lib/services.js");
+ expect(isRunning()).toBe(false);
+ });
+
+ it("returns true when any service pid is alive", async () => {
+ const { writePids } = await import("../src/lib/pid.js");
+ // Use current process pid as a live process
+ writePids({ web: 999999, emailWorker: process.pid, wsDo: 999997 });
+ const { isRunning } = await import("../src/lib/services.js");
+ expect(isRunning()).toBe(true);
+ });
+
+ it("returns true when only web is alive (backward compat)", async () => {
+ const { writePids } = await import("../src/lib/pid.js");
+ writePids({ web: process.pid, emailWorker: 999998, wsDo: 999997 });
+ const { isRunning } = await import("../src/lib/services.js");
+ expect(isRunning()).toBe(true);
+ });
+ });
+
+ describe("stopServices", () => {
+ it("clears pid file even when no services are running", async () => {
+ const { writePids } = await import("../src/lib/pid.js");
+ const { stopServices } = await import("../src/lib/services.js");
+ const { PID_FILE } = await import("../src/lib/constants.js");
+
+ writePids({ web: 999999 });
+ expect(existsSync(PID_FILE)).toBe(true);
+
+ stopServices();
+ expect(existsSync(PID_FILE)).toBe(false);
+ });
+ });
+});
diff --git a/src/app/test/wrangler-config.test.ts b/src/app/test/wrangler-config.test.ts
new file mode 100644
index 000000000..649e75676
--- /dev/null
+++ b/src/app/test/wrangler-config.test.ts
@@ -0,0 +1,65 @@
+import { describe, it, expect } from "vitest";
+
+// Test the setVar logic directly (extracted for testability)
+function setVar(content: string, key: string, value: string): string {
+ const pattern = new RegExp(`${key}\\s*=\\s*"[^"]*"`);
+ if (pattern.test(content)) {
+ return content.replace(pattern, `${key} = "${value}"`);
+ }
+ if (content.includes("[vars]")) {
+ return content.replace(/\[vars\]/, `[vars]\n${key} = "${value}"`);
+ }
+ return content + `\n[vars]\n${key} = "${value}"\n`;
+}
+
+function setDevPort(content: string, port: number): string {
+ if (content.includes("[dev]")) {
+ return content.replace(/(\[dev\][^\[]*?)port\s*=\s*\d+/, `$1port = ${port}`);
+ }
+ return content + `\n[dev]\nport = ${port}\n`;
+}
+
+describe("wrangler-config", () => {
+ describe("setVar", () => {
+ it("replaces existing var value", () => {
+ const content = `[vars]\nDEV_WS_DO_URL = "http://localhost:8789"`;
+ const result = setVar(content, "DEV_WS_DO_URL", "http://localhost:9999");
+ expect(result).toContain(`DEV_WS_DO_URL = "http://localhost:9999"`);
+ });
+
+ it("adds var under existing [vars] section", () => {
+ const content = `name = "web"\n[vars]\nFOO = "bar"`;
+ const result = setVar(content, "NEW_KEY", "new_value");
+ expect(result).toContain(`[vars]\nNEW_KEY = "new_value"`);
+ expect(result).toContain(`FOO = "bar"`);
+ });
+
+ it("creates [vars] section when missing", () => {
+ const content = `name = "web"\n[dev]\nport = 3000`;
+ const result = setVar(content, "DEV_WS_DO_URL", "http://localhost:8789");
+ expect(result).toContain(`[vars]`);
+ expect(result).toContain(`DEV_WS_DO_URL = "http://localhost:8789"`);
+ });
+
+ it("handles empty content", () => {
+ const result = setVar("", "KEY", "value");
+ expect(result).toContain(`[vars]\nKEY = "value"`);
+ });
+ });
+
+ describe("setDevPort", () => {
+ it("replaces port in existing [dev] section", () => {
+ const content = `name = "web"\n[dev]\nport = 3000`;
+ const result = setDevPort(content, 4000);
+ expect(result).toContain("port = 4000");
+ expect(result).not.toContain("port = 3000");
+ });
+
+ it("appends [dev] section when missing", () => {
+ const content = `name = "web"`;
+ const result = setDevPort(content, 3000);
+ expect(result).toContain("[dev]");
+ expect(result).toContain("port = 3000");
+ });
+ });
+});
diff --git a/src/app/tsconfig.json b/src/app/tsconfig.json
new file mode 100644
index 000000000..487514e1c
--- /dev/null
+++ b/src/app/tsconfig.json
@@ -0,0 +1,15 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "strict": true,
+ "esModuleInterop": true,
+ "skipLibCheck": true,
+ "outDir": "dist",
+ "rootDir": "src",
+ "types": ["bun-types"]
+ },
+ "include": ["src"],
+ "exclude": ["node_modules", "dist", "bundled"]
+}
diff --git a/src/app/vitest.config.ts b/src/app/vitest.config.ts
new file mode 100644
index 000000000..1066d80b4
--- /dev/null
+++ b/src/app/vitest.config.ts
@@ -0,0 +1,8 @@
+import { defineConfig, mergeConfig } from "vitest/config"
+import shared from "../../vitest.shared"
+
+export default mergeConfig(shared, defineConfig({
+ test: {
+ include: ["test/**/*.test.ts"],
+ },
+}))
diff --git a/src/shared/src/constants.ts b/src/shared/src/constants.ts
index 41241b611..c652f6058 100644
--- a/src/shared/src/constants.ts
+++ b/src/shared/src/constants.ts
@@ -108,6 +108,9 @@ export const TERMINAL_MEETING_STATUSES: readonly MeetingStatusType[] = [
MeetingStatus.FAILED,
] as const;
+// Dev mode auth (shared between web frontend and @alook/app CLI)
+export const DEV_PASSWORD = "dev-password-000";
+
// Local dev URLs (used for service-binding fallbacks)
export const DEV_WEB_URL = process.env.ALOOK_SERVER_URL || "http://localhost:3000";
export const DEV_WS_DO_URL = process.env.DEV_WS_DO_URL || "http://localhost:8789";
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index 062eed0c2..2c1afaeb7 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -82,6 +82,7 @@ export {
EVENT_POLL_INTERVAL_MS,
AGENT_HANDLE_MIN_LENGTH,
MAX_TASKS_PER_TRACE,
+ DEV_PASSWORD,
DEV_WEB_URL,
DEV_WS_DO_URL,
DEV_EMAIL_WORKER_URL,
diff --git a/src/web/src/app/(auth)/sign-in/page.tsx b/src/web/src/app/(auth)/sign-in/page.tsx
index 24b21750c..1890dff85 100644
--- a/src/web/src/app/(auth)/sign-in/page.tsx
+++ b/src/web/src/app/(auth)/sign-in/page.tsx
@@ -25,7 +25,7 @@ import { TypewriterVisual, EMAILS_PLAYFUL } from "@/components/typewriter-visual
const isProd = process.env.NODE_ENV === "production"
-const DEV_PASSWORD = "dev-password-000"
+import { DEV_PASSWORD } from "@alook/shared"
const DEFAULT_POST_LOGIN = "/workspaces?auto"
function safeRedirectUrl(redirect: string | null): string {
diff --git a/vitest.config.ts b/vitest.config.ts
index 02898f513..9a7153d80 100644
--- a/vitest.config.ts
+++ b/vitest.config.ts
@@ -2,6 +2,6 @@ import { defineConfig } from "vitest/config"
export default defineConfig({
test: {
- projects: ["src/shared", "src/web", "src/email-worker"],
+ projects: ["src/shared", "src/web", "src/email-worker", "src/app"],
},
})