Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
feat: register flow with token lifecycle and real-time WS updates
Generc14bf06d477c
diff --git a/package.json b/package.jsonindex 9de92980d..bec9dc65a 100644--- a/package.json+++ b/package.json@@ -11,7 +11,7 @@"reinstall": "pnpm run clean && pnpm install","typecheck": "turbo run typecheck","dev:web": "pnpm --filter @alook/web dev",- "dev:cli": "pnpm --filter @alook/cli dev",+ "dev:cli": "ALOOK_SERVER_URL=http://localhost:3000 pnpm --filter @alook/cli dev","dev:email": "pnpm --filter @alook/email-worker dev","dev:send": "node -e \"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)}fetch('http://localhost:8788/simulate',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({from:f,to:t,subject:s,body:b})}).then(r=>r.json()).then(console.log).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.yamlindex 0c7f4285b..3d99662a0 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -32,6 +32,9 @@ importers:citty:specifier: ^0.2.2version: 0.2.2+ commander:+ specifier: ^14.0.3+ version: 14.0.3devDependencies:'@types/bun':specifier: latest@@ -6715,7 +6718,7 @@ snapshots:optionalDependencies:'@types/react': 19.2.14- '@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@cloudflare/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])':+ '@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@cloudflare/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])':dependencies:'@better-auth/utils': 0.4.0'@better-fetch/fetch': 1.1.21@@ -6730,36 +6733,36 @@ snapshots:optionalDependencies:'@cloudflare/workers-types': 4.20260410.1- '@better-auth/[email protected](@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@cloudflare/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])':+ '@better-auth/[email protected](@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@cloudflare/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])':dependencies:- '@better-auth/core': 1.6.2(@better-auth/[email protected])(@better-fetch/[email protected])(@cloudflare/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])+ '@better-auth/core': 1.6.2(@better-auth/[email protected])(@better-fetch/[email protected])(@cloudflare/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])'@better-auth/utils': 0.4.0- '@better-auth/[email protected](@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@cloudflare/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])([email protected])':+ '@better-auth/[email protected](@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@cloudflare/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])([email protected])':dependencies:- '@better-auth/core': 1.6.2(@better-auth/[email protected])(@better-fetch/[email protected])(@cloudflare/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])+ '@better-auth/core': 1.6.2(@better-auth/[email protected])(@better-fetch/[email protected])(@cloudflare/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])'@better-auth/utils': 0.4.0optionalDependencies:kysely: 0.28.15- '@better-auth/[email protected](@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@cloudflare/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])':+ '@better-auth/[email protected](@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@cloudflare/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])':dependencies:- '@better-auth/core': 1.6.2(@better-auth/[email protected])(@better-fetch/[email protected])(@cloudflare/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])+ '@better-auth/core': 1.6.2(@better-auth/[email protected])(@better-fetch/[email protected])(@cloudflare/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])'@better-auth/utils': 0.4.0- '@better-auth/[email protected](@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@cloudflare/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])':+ '@better-auth/[email protected](@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@cloudflare/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])':dependencies:- '@better-auth/core': 1.6.2(@better-auth/[email protected])(@better-fetch/[email protected])(@cloudflare/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])+ '@better-auth/core': 1.6.2(@better-auth/[email protected])(@better-fetch/[email protected])(@cloudflare/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])'@better-auth/utils': 0.4.0- '@better-auth/[email protected](@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@cloudflare/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])':+ '@better-auth/[email protected](@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@cloudflare/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])':dependencies:- '@better-auth/core': 1.6.2(@better-auth/[email protected])(@better-fetch/[email protected])(@cloudflare/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])+ '@better-auth/core': 1.6.2(@better-auth/[email protected])(@better-fetch/[email protected])(@cloudflare/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])'@better-auth/utils': 0.4.0- '@better-auth/[email protected](@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@cloudflare/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])(@better-fetch/[email protected])':+ '@better-auth/[email protected](@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@cloudflare/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])(@better-fetch/[email protected])':dependencies:- '@better-auth/core': 1.6.2(@better-auth/[email protected])(@better-fetch/[email protected])(@cloudflare/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])+ '@better-auth/core': 1.6.2(@better-auth/[email protected])(@better-fetch/[email protected])(@cloudflare/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])'@better-auth/utils': 0.4.0'@better-fetch/fetch': 1.1.21@@ -8583,13 +8586,13 @@ snapshots:[email protected](@cloudflare/[email protected])(@opentelemetry/[email protected])([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])([email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))):dependencies:- '@better-auth/core': 1.6.2(@better-auth/[email protected])(@better-fetch/[email protected])(@cloudflare/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])- '@better-auth/drizzle-adapter': 1.6.2(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@cloudflare/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])- '@better-auth/kysely-adapter': 1.6.2(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@cloudflare/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])([email protected])- '@better-auth/memory-adapter': 1.6.2(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@cloudflare/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])- '@better-auth/mongo-adapter': 1.6.2(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@cloudflare/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])- '@better-auth/prisma-adapter': 1.6.2(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@cloudflare/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])- '@better-auth/telemetry': 1.6.2(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@cloudflare/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])(@better-fetch/[email protected])+ '@better-auth/core': 1.6.2(@better-auth/[email protected])(@better-fetch/[email protected])(@cloudflare/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])+ '@better-auth/drizzle-adapter': 1.6.2(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@cloudflare/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])+ '@better-auth/kysely-adapter': 1.6.2(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@cloudflare/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])([email protected])+ '@better-auth/memory-adapter': 1.6.2(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@cloudflare/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])+ '@better-auth/mongo-adapter': 1.6.2(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@cloudflare/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])+ '@better-auth/prisma-adapter': 1.6.2(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@cloudflare/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])+ '@better-auth/telemetry': 1.6.2(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@cloudflare/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])(@better-fetch/[email protected])'@better-auth/utils': 0.4.0'@better-fetch/fetch': 1.1.21'@noble/ciphers': 2.1.1diff --git a/src/cli/commands/agent.ts b/src/cli/commands/agent.tsindex a7f7f286c..cb79203dd 100644--- a/src/cli/commands/agent.ts+++ b/src/cli/commands/agent.ts@@ -2,6 +2,7 @@ import { Command } from "commander";import { APIClient } from "../lib/client.js";import { loadCLIConfigForProfile } from "../lib/config.js";import { printTable, printJSON } from "../lib/output.js";+import { cmdPrefix } from "../lib/env.js";interface Agent {id: string;@@ -20,7 +21,7 @@ function resolveClientOpts(command: Command) {if (!token) {console.error(- "Error: not registered. Run 'alook register --token <token>' first.",+ `Error: not registered. Run '${cmdPrefix()} register --token <token>' first.`,);process.exit(1);}diff --git a/src/cli/commands/daemon.ts b/src/cli/commands/daemon.tsindex cbfa70cae..9b1e303b0 100644--- a/src/cli/commands/daemon.ts+++ b/src/cli/commands/daemon.ts@@ -1,5 +1,6 @@import { Command } from "commander";import { startDaemon } from "../daemon/daemon.js";+import { cmdPrefix } from "../lib/env.js";export function daemonCommand(): Command {const cmd = new Command("daemon").description("Manage the Alook daemon");@@ -17,7 +18,7 @@ export function daemonCommand(): Command {if (!opts.foreground) {console.log(- "Hint: run 'alook daemon start --foreground' to start the daemon in the foreground.",+ `Hint: run '${cmdPrefix()} daemon start --foreground' to start the daemon in the foreground.`,);return;}diff --git a/src/cli/commands/register.ts b/src/cli/commands/register.tsindex 5c0c22e13..27b8cd74e 100644--- a/src/cli/commands/register.ts+++ b/src/cli/commands/register.ts@@ -1,6 +1,9 @@import { Command } from "commander";+import { execSync } from "child_process";+import { hostname } from "os";import { APIClient } from "../lib/client.js";import { saveCLIConfigForProfile } from "../lib/config.js";+import { cmdPrefix } from "../lib/env.js";interface MeResponse {id: string;@@ -12,6 +15,36 @@ interface Workspace {name: string;}+interface ActivateResponse {+ daemon_id: string;+ runtimes: { id: string; provider: string }[];+}++function isCommandAvailable(cmd: string): boolean {+ try {+ execSync(`which ${cmd}`, { stdio: "ignore" });+ return true;+ } catch {+ return false;+ }+}++function detectRuntimes(): { type: string; version: string }[] {+ const found: { type: string; version: string }[] = [];+ for (const type of ["claude", "codex", "opencode"]) {+ if (isCommandAvailable(type)) {+ let version = "";+ try {+ version = execSync(`${type} --version`, { encoding: "utf-8" }).trim();+ } catch {+ // version detection optional+ }+ found.push({ type, version });+ }+ }+ return found;+}+export function registerCommand(): Command {const cmd = new Command("register").description("Register CLI with your Alook account")@@ -25,11 +58,12 @@ export function registerCommand(): Command {const serverUrl: string =opts.server ||command.parent?.opts().server ||- "http://localhost:3000";+ process.env.ALOOK_SERVER_URL ||+ "https://alook.ai";if (!token) {console.error(- "Error: --token is required\nUsage: alook register --token <token>",+ `Error: --token is required\nUsage: ${cmdPrefix()} register --token <token>`,);process.exit(1);}@@ -43,6 +77,7 @@ export function registerCommand(): Command {const client = new APIClient(serverUrl, token);+ // Verify tokenlet me: MeResponse;try {me = await client.getJSON<MeResponse>("/api/me");@@ -70,17 +105,54 @@ export function registerCommand(): Command {const ws = workspaces[0];+ // Detect local runtimes+ console.log("Scanning for AI runtimes...");+ const runtimes = detectRuntimes();+ if (runtimes.length === 0) {+ console.error(+ "Error: no runtimes found. Install claude, codex, or opencode first.",+ );+ process.exit(1);+ }+ console.log(+ `Found: ${runtimes.map((r) => r.type).join(", ")}`,+ );++ // Activate token — no auth header needed, token in body+ const host = hostname();+ console.log("Registering runtime...");+ let activateResp: ActivateResponse;+ try {+ const res = await fetch(`${serverUrl}/api/machine-tokens/activate`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ token, hostname: host, runtimes }),+ });+ if (!res.ok) {+ const text = await res.text();+ console.error(`Error: registration failed (${res.status}): ${text}`);+ process.exit(1);+ }+ activateResp = await res.json() as ActivateResponse;+ } catch (err) {+ console.error(+ `Error: failed to activate: ${err instanceof Error ? err.message : err}`,+ );+ process.exit(1);+ }+saveCLIConfigForProfile(profile, {token,server_url: serverUrl,watched_workspaces: [{ id: ws.id, name: ws.name }],});- console.log(`Registered as ${me.email}`);+ console.log(`\nRegistered as ${me.email}`);console.log(`Workspace: ${ws.name} (${ws.id})`);+ console.log(`Runtimes: ${activateResp.runtimes.map((r) => r.provider).join(", ")}`);console.log();console.log(- "Run 'alook daemon start --foreground' to start the daemon.",+ `Run '${cmdPrefix()} daemon start --foreground' to start the daemon.`,);});diff --git a/src/cli/commands/status.ts b/src/cli/commands/status.tsindex aa79aa531..91b7444e1 100644--- a/src/cli/commands/status.ts+++ b/src/cli/commands/status.ts@@ -1,5 +1,6 @@import { Command } from "commander";import { loadCLIConfigForProfile } from "../lib/config.js";+import { cmdPrefix } from "../lib/env.js";export function statusCommand(): Command {const cmd = new Command("status")@@ -11,7 +12,7 @@ export function statusCommand(): Command {if (!cfg.token) {console.log("Not registered");console.log(- "Run 'alook register --token <token>' to register.",+ `Run '${cmdPrefix()} register --token <token>' to register.`,);return;}diff --git a/src/cli/daemon/config.test.ts b/src/cli/daemon/config.test.tsindex ea33c76ca..042498f0f 100644--- a/src/cli/daemon/config.test.ts+++ b/src/cli/daemon/config.test.ts@@ -33,7 +33,7 @@ describe("loadDaemonConfig defaults", () => {it("returns correct defaults when no env vars set", () => {const cfg = loadDaemonConfig();- expect(cfg.serverURL).toBe("http://localhost:8080");+ expect(cfg.serverURL).toBe("https://alook.ai");expect(cfg.pollInterval).toBe(3000);expect(cfg.heartbeatInterval).toBe(15000);expect(cfg.agentTimeout).toBe(7200000);diff --git a/src/cli/daemon/config.ts b/src/cli/daemon/config.tsindex f20974fb4..7782013bc 100644--- a/src/cli/daemon/config.ts+++ b/src/cli/daemon/config.ts@@ -70,7 +70,7 @@ export function loadDaemonConfig(profile?: string): DaemonConfig {return {serverURL: normalizeServerBaseURL(- process.env.ALOOK_SERVER_URL || "http://localhost:8080",+ process.env.ALOOK_SERVER_URL || "https://alook.ai",),claudePath: process.env.ALOOK_CLAUDE_PATH || "claude",codexPath: process.env.ALOOK_CODEX_PATH || "codex",diff --git a/src/cli/daemon/daemon.ts b/src/cli/daemon/daemon.tsindex 76404c0ad..dcea9229f 100644--- a/src/cli/daemon/daemon.ts+++ b/src/cli/daemon/daemon.ts@@ -6,6 +6,7 @@ import { createBackend, detectVersion } from "./agent/index.js";import { type Task, type TaskResult, fromApiTask } from "./types.js";import { loadCLIConfigForProfile } from "../lib/config.js";import { log } from "../lib/logger.js";+import { cmdPrefix } from "../lib/env.js";import { mkdirSync } from "fs";import { join } from "path";import { execSync } from "child_process";@@ -39,7 +40,7 @@ export async function startDaemon(const cliConfig = loadCLIConfigForProfile(profile);if (!cliConfig.token) {- log.error("Not registered. Run 'alook register' first.");+ log.error(`Not registered. Run '${cmdPrefix()} register' first.`);process.exit(1);}if (cliConfig.server_url) config.serverURL = cliConfig.server_url;diff --git a/src/cli/lib/env.test.ts b/src/cli/lib/env.test.tsnew file mode 100644index 000000000..9bf6615ca--- /dev/null+++ b/src/cli/lib/env.test.ts@@ -0,0 +1,28 @@+import { describe, it, expect, afterEach } from "vitest";+import { isDev, cmdPrefix } from "./env.js";++afterEach(() => {+ delete process.env.ALOOK_SERVER_URL;+});++describe("isDev", () => {+ it("returns false when ALOOK_SERVER_URL is not set", () => {+ expect(isDev()).toBe(false);+ });++ it("returns true when ALOOK_SERVER_URL is set", () => {+ process.env.ALOOK_SERVER_URL = "http://localhost:3000";+ expect(isDev()).toBe(true);+ });+});++describe("cmdPrefix", () => {+ it("returns 'alook' in production", () => {+ expect(cmdPrefix()).toBe("alook");+ });++ it("returns 'pnpm dev:cli' in dev", () => {+ process.env.ALOOK_SERVER_URL = "http://localhost:3000";+ expect(cmdPrefix()).toBe("pnpm dev:cli");+ });+});diff --git a/src/cli/lib/env.ts b/src/cli/lib/env.tsnew file mode 100644index 000000000..b8d045073--- /dev/null+++ b/src/cli/lib/env.ts@@ -0,0 +1,7 @@+export function isDev(): boolean {+ return !!process.env.ALOOK_SERVER_URL;+}++export function cmdPrefix(): string {+ return isDev() ? "pnpm dev:cli" : "alook";+}diff --git a/src/cli/package.json b/src/cli/package.jsonindex 607865e5c..094a67284 100644--- a/src/cli/package.json+++ b/src/cli/package.json@@ -13,7 +13,8 @@"@alook/shared": "workspace:*","@anthropic-ai/claude-agent-sdk": "latest","@openai/codex-sdk": "latest",- "citty": "^0.2.2"+ "citty": "^0.2.2",+ "commander": "^14.0.3"},"devDependencies": {"@types/bun": "latest",diff --git a/src/cli/src/index.ts b/src/cli/src/index.tsindex b2dda2a5f..77f314501 100644--- a/src/cli/src/index.ts+++ b/src/cli/src/index.ts@@ -1 +1,25 @@-console.log("alook cli")+#!/usr/bin/env node+import { Command } from "commander";+import { registerCommand } from "../commands/register.js";+import { statusCommand } from "../commands/status.js";+import { agentCommand } from "../commands/agent.js";+import { daemonCommand } from "../commands/daemon.js";+import { configCommand } from "../commands/config.js";+import { versionCommand } from "../commands/version.js";++const program = new Command();++program+ .name("alook")+ .description("Alook CLI")+ .option("--server <url>", "Server URL")+ .option("--profile <name>", "Profile name");++program.addCommand(registerCommand());+program.addCommand(statusCommand());+program.addCommand(agentCommand());+program.addCommand(daemonCommand());+program.addCommand(configCommand());+program.addCommand(versionCommand());++program.parse();diff --git a/src/cli/tsconfig.json b/src/cli/tsconfig.jsonindex 0ffc968ca..74166aeac 100644--- a/src/cli/tsconfig.json+++ b/src/cli/tsconfig.json@@ -7,6 +7,6 @@"skipLibCheck": true,"types": ["bun"]},- "include": ["src"],- "exclude": ["src/__tests__"]+ "include": ["src", "commands", "daemon", "lib"],+ "exclude": ["**/__tests__", "**/*.test.ts"]}diff --git a/src/shared/index.ts b/src/shared/index.tsindex 8ad88be81..35377ea73 100644--- a/src/shared/index.ts+++ b/src/shared/index.ts@@ -61,6 +61,8 @@ export {ClaimTaskResponseSchema,RegisterResponseSchema,DaemonRuntimeItemSchema,+ ActivateTokenRuntimeSchema,+ ActivateTokenRequestSchema,RegisterDaemonRequestSchema,DeregisterRequestSchema,HeartbeatRequestSchema,@@ -78,6 +80,8 @@ export type {ClaimTaskResponse,RegisterResponse,DaemonRuntimeItem,+ ActivateTokenRuntime,+ ActivateTokenRequest,RegisterDaemonRequest,DeregisterRequest,HeartbeatRequest,diff --git a/src/shared/src/db/index.ts b/src/shared/src/db/index.tsindex e2e739283..49a7534ca 100644--- a/src/shared/src/db/index.ts+++ b/src/shared/src/db/index.ts@@ -1,7 +1,7 @@-import { drizzle } from "drizzle-orm/d1";+import { drizzle, type AnyD1Database } from "drizzle-orm/d1";import * as schema from "./schema";-export function createDb(d1: D1Database) {+export function createDb(d1: AnyD1Database) {return drizzle(d1, { schema });}diff --git a/src/shared/src/db/queries/machine-token.ts b/src/shared/src/db/queries/machine-token.tsindex 55c830afc..49eca7f99 100644--- a/src/shared/src/db/queries/machine-token.ts+++ b/src/shared/src/db/queries/machine-token.ts@@ -7,8 +7,9 @@ export async function createMachineToken(data: {userId: string;workspaceId: string;- tokenHash: string;+ token: string;name: string;+ status?: string;}) {const rows = await db@@ -16,31 +17,59 @@ export async function createMachineToken(.values({userId: data.userId,workspaceId: data.workspaceId,- tokenHash: data.tokenHash,+ token: data.token,name: data.name,+ status: data.status ?? "active",}).returning();return rows[0]!;}-export async function getMachineTokenByHash(db: Database, tokenHash: string) {+export async function getMachineTokenByToken(db: Database, token: string) {const rows = await db.select({id: machineToken.id,userId: machineToken.userId,workspaceId: machineToken.workspaceId,- tokenHash: machineToken.tokenHash,+ token: machineToken.token,name: machineToken.name,+ status: machineToken.status,lastUsedAt: machineToken.lastUsedAt,createdAt: machineToken.createdAt,userEmail: user.email,}).from(machineToken).innerJoin(user, eq(user.id, machineToken.userId))- .where(eq(machineToken.tokenHash, tokenHash));+ .where(eq(machineToken.token, token));return rows[0] ?? null;}+export async function getPendingMachineToken(+ db: Database,+ userId: string,+ workspaceId: string+) {+ const rows = await db+ .select()+ .from(machineToken)+ .where(+ and(+ eq(machineToken.userId, userId),+ eq(machineToken.workspaceId, workspaceId),+ eq(machineToken.status, "pending")+ )+ )+ .limit(1);+ return rows[0] ?? null;+}++export async function activateMachineToken(db: Database, id: string) {+ await db+ .update(machineToken)+ .set({ status: "active" })+ .where(eq(machineToken.id, id));+}+export async function listMachineTokens(db: Database,userId: string,diff --git a/src/shared/src/db/schema.ts b/src/shared/src/db/schema.tsindex 5695f3c08..1b830f0e8 100644--- a/src/shared/src/db/schema.ts+++ b/src/shared/src/db/schema.ts@@ -262,10 +262,11 @@ export const machineToken = sqliteTable(workspaceId: text("workspace_id").notNull().references(() => workspace.id, { onDelete: "cascade" }),- tokenHash: text("token_hash").unique().notNull(),+ token: text("token").unique().notNull(),name: text("name").notNull().default(""),+ status: text("status").notNull().default("active"),lastUsedAt: text("last_used_at"),createdAt: text("created_at").notNull().$defaultFn(() => new Date().toISOString()),},- (t) => [index("idx_machine_token_hash").on(t.tokenHash)]+ (t) => [index("idx_machine_token").on(t.token)]);diff --git a/src/shared/src/index.ts b/src/shared/src/index.tsindex 743d398f0..00ad7aa6c 100644--- a/src/shared/src/index.ts+++ b/src/shared/src/index.ts@@ -70,6 +70,8 @@ export {ClaimTaskResponseSchema,RegisterResponseSchema,DaemonRuntimeItemSchema,+ ActivateTokenRuntimeSchema,+ ActivateTokenRequestSchema,RegisterDaemonRequestSchema,DeregisterRequestSchema,HeartbeatRequestSchema,@@ -87,6 +89,8 @@ export type {ClaimTaskResponse,RegisterResponse,DaemonRuntimeItem,+ ActivateTokenRuntime,+ ActivateTokenRequest,RegisterDaemonRequest,DeregisterRequest,HeartbeatRequest,diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.tsindex e048f4dee..b1276d184 100644--- a/src/shared/src/schemas.ts+++ b/src/shared/src/schemas.ts@@ -115,6 +115,19 @@ export const DaemonRuntimeItemSchema = z.object({});export type DaemonRuntimeItem = z.infer<typeof DaemonRuntimeItemSchema>;+export const ActivateTokenRuntimeSchema = z.object({+ type: z.string().min(1),+ version: z.string().optional().default(""),+});+export type ActivateTokenRuntime = z.infer<typeof ActivateTokenRuntimeSchema>;++export const ActivateTokenRequestSchema = z.object({+ token: z.string().min(1),+ hostname: z.string().min(1),+ runtimes: z.array(ActivateTokenRuntimeSchema).min(1),+});+export type ActivateTokenRequest = z.infer<typeof ActivateTokenRequestSchema>;+export const RegisterDaemonRequestSchema = z.object({workspace_id: z.string().min(1),daemon_id: z.string().min(1),diff --git a/src/web/migrations/0001_schema.sql b/src/web/migrations/0001_schema.sqlindex 406ae7c3e..3bfd4e283 100644--- a/src/web/migrations/0001_schema.sql+++ b/src/web/migrations/0001_schema.sql@@ -195,13 +195,14 @@ CREATE TABLE IF NOT EXISTS machine_token (id TEXT PRIMARY KEY,user_id TEXT NOT NULL REFERENCES "user"(id) ON DELETE CASCADE,workspace_id TEXT NOT NULL REFERENCES workspace(id) ON DELETE CASCADE,- token_hash TEXT NOT NULL UNIQUE,+ token TEXT NOT NULL UNIQUE,name TEXT NOT NULL DEFAULT '',+ status TEXT NOT NULL DEFAULT 'active',last_used_at TEXT,created_at TEXT NOT NULL DEFAULT (datetime('now')));-CREATE INDEX IF NOT EXISTS idx_machine_token_hash ON machine_token(token_hash);+CREATE INDEX IF NOT EXISTS idx_machine_token ON machine_token(token);-- Better Auth indexesCREATE INDEX IF NOT EXISTS idx_session_user_id ON "session"(userId);diff --git a/src/web/src/app/(app)/w/[slug]/home/page.tsx b/src/web/src/app/(app)/w/[slug]/home/page.tsxindex c795d85ae..73d3a7a82 100644--- a/src/web/src/app/(app)/w/[slug]/home/page.tsx+++ b/src/web/src/app/(app)/w/[slug]/home/page.tsx@@ -64,7 +64,7 @@ export default function HomePage() {<Buttonsize="sm"className="mt-4"- onClick={() => router.push(`/w/${slug}/runtimes`)}+ onClick={() => router.push(`/w/${slug}/runtimes?connect`)}>Connect Machine</Button>diff --git a/src/web/src/app/(app)/w/[slug]/runtimes/page.tsx b/src/web/src/app/(app)/w/[slug]/runtimes/page.tsxindex 7275268f9..0209bb925 100644--- a/src/web/src/app/(app)/w/[slug]/runtimes/page.tsx+++ b/src/web/src/app/(app)/w/[slug]/runtimes/page.tsx@@ -1,6 +1,7 @@"use client";import { useState, useRef, useEffect, useCallback } from "react";+import { useSearchParams, useRouter, usePathname } from "next/navigation";import { useAgentContext } from "@/contexts/agent-context";import { Button } from "@/components/ui/button";import { Badge } from "@/components/ui/badge";@@ -23,6 +24,7 @@ import { ConfirmDialog } from "@/components/ui/confirm-dialog";import { toast } from "sonner";import { Loader2, Monitor, Plus } from "lucide-react";import type { Runtime } from "@/lib/api";+import { CLI_CMD } from "@/lib/utils";function ConnectMachineSteps({generatedToken,@@ -71,12 +73,12 @@ function ConnectMachineSteps({className="rounded-md bg-muted p-2.5 font-mono text-xs text-muted-foreground cursor-pointer hover:bg-muted/80 transition-colors"onClick={() =>copyToClipboard(- `npx @alook/cli register --token ${generatedToken}`+ `${CLI_CMD} register --token ${generatedToken}`)}title="Click to copy">- npx @alook/cli register --token{" "}+ {CLI_CMD} register --token{" "}<span className="text-foreground/70">{generatedToken.slice(0, 12)}...</span>@@ -85,7 +87,7 @@ function ConnectMachineSteps({size="sm"onClick={() => {navigator.clipboard.writeText(- `npx @alook/cli register --token ${generatedToken}`+ `${CLI_CMD} register --token ${generatedToken}`);toast("Copied to clipboard");}}@@ -113,11 +115,11 @@ function ConnectMachineSteps({<divclassName="ml-7 rounded-md bg-muted p-2.5 font-mono text-xs text-muted-foreground cursor-pointer hover:bg-muted/80 transition-colors"onClick={() =>- copyToClipboard("npx @alook/cli daemon start --foreground")+ copyToClipboard(`${CLI_CMD} daemon start --foreground`)}title="Click to copy">- npx @alook/cli daemon start --foreground+ {CLI_CMD} daemon start --foreground</div></div>@@ -128,6 +130,9 @@ function ConnectMachineSteps({export default function RuntimesPage() {const { runtimes, loading, handleGenerateToken, handleDeleteMachine, reload } =useAgentContext();+ const searchParams = useSearchParams();+ const router = useRouter();+ const pathname = usePathname();const [sheetOpen, setSheetOpen] = useState(false);const [generatedToken, setGeneratedToken] = useState("");@@ -143,6 +148,14 @@ export default function RuntimesPage() {reload();}, [reload]);+ // Auto-open "New machine" sheet when navigated with ?connect+ useEffect(() => {+ if (searchParams.has("connect")) {+ setSheetOpen(true);+ router.replace(pathname, { scroll: false });+ }+ }, [searchParams, router, pathname]);+const openConfirm = (title: string,description: string,diff --git a/src/web/src/app/(app)/workspaces/page.tsx b/src/web/src/app/(app)/workspaces/page.tsxindex 245db4962..de7edda95 100644--- a/src/web/src/app/(app)/workspaces/page.tsx+++ b/src/web/src/app/(app)/workspaces/page.tsx@@ -1,4 +1,5 @@import { redirect } from "next/navigation"+import { isRedirectError } from "next/dist/client/components/redirect-error"import { getCloudflareContext } from "@opennextjs/cloudflare"import { createDb, queries } from "@alook/shared"import { requireSession } from "@/lib/session"@@ -46,7 +47,8 @@ export default async function WorkspacesPage({role: "owner",})redirect(`/w/${ws.slug}/home`)- } catch {+ } catch (err) {+ if (isRedirectError(err)) throw err// Slug conflict — append random suffix and retryslug = `${baseSlug}-${randomSuffix()}`}diff --git a/src/web/src/app/api/daemon/deregister/route.ts b/src/web/src/app/api/daemon/deregister/route.tsindex 3e9678601..4a5c5c9f9 100644--- a/src/web/src/app/api/daemon/deregister/route.ts+++ b/src/web/src/app/api/daemon/deregister/route.ts@@ -5,6 +5,7 @@ import { withAuth } from "@/lib/middleware/auth";import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers";import { DeregisterRequestSchema } from "@alook/shared";import { log } from "@/lib/logger";+import { broadcastToUser } from "@/lib/broadcast";export const POST = withAuth(async (req: NextRequest, ctx) => {const { env } = getCloudflareContext()@@ -32,5 +33,11 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {}}+ broadcastToUser(ctx.userId, {+ type: "runtime.status",+ runtimeIds: body.runtime_ids,+ status: "offline",+ }).catch(() => {});+return writeJSON({ status: "ok" });});diff --git a/src/web/src/app/api/daemon/heartbeat/route.ts b/src/web/src/app/api/daemon/heartbeat/route.tsindex 9c20c2f4a..614e1ee52 100644--- a/src/web/src/app/api/daemon/heartbeat/route.ts+++ b/src/web/src/app/api/daemon/heartbeat/route.ts@@ -5,6 +5,7 @@ import { withAuth } from "@/lib/middleware/auth";import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers";import { HeartbeatRequestSchema } from "@alook/shared";import { TaskService } from "@/lib/services/task";+import { broadcastToUser } from "@/lib/broadcast";export const POST = withAuth(async (req: NextRequest, ctx) => {const { env } = getCloudflareContext()@@ -28,6 +29,13 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {await queries.runtime.updateAgentRuntimeHeartbeat(db, body.runtime_id);+ // Notify web UI of status change+ broadcastToUser(ctx.userId, {+ type: "runtime.status",+ runtimeId: body.runtime_id,+ status: "online",+ }).catch(() => {});+// Mark runtimes that haven't sent a heartbeat in >45s as offlineawait queries.runtime.markStaleRuntimesOffline(db, ctx.workspaceId);diff --git a/src/web/src/app/api/machine-tokens/activate/route.ts b/src/web/src/app/api/machine-tokens/activate/route.tsnew file mode 100644index 000000000..4079f3d5f--- /dev/null+++ b/src/web/src/app/api/machine-tokens/activate/route.ts@@ -0,0 +1,67 @@+import { NextRequest } from "next/server";+import { getCloudflareContext } from "@opennextjs/cloudflare";+import { createDb, queries, ActivateTokenRequestSchema } from "@alook/shared";+import { writeJSON } from "@/lib/middleware/helpers";+import { runtimeToResponse } from "@/lib/api/responses";+import { broadcastToUser } from "@/lib/broadcast";++export async function POST(req: NextRequest) {+ let raw: unknown;+ try {+ raw = await req.json();+ } catch {+ return writeJSON({ error: "invalid request body" }, 400);+ }++ const parsed = ActivateTokenRequestSchema.safeParse(raw);+ if (!parsed.success) {+ return writeJSON({ error: "invalid payload", details: parsed.error.flatten() }, 400);+ }++ const { token, hostname, runtimes } = parsed.data;++ const { env } = await getCloudflareContext({ async: true });+ const db = createDb((env as Env).DB);++ const mt = await queries.machineToken.getMachineTokenByToken(db, token);+ if (!mt) {+ return writeJSON({ error: "token not found" }, 404);+ }+ if (mt.status !== "pending") {+ return writeJSON({ error: "token already used" }, 409);+ }++ // Use hostname as daemonId — must match what the daemon uses (os.hostname())+ // so that daemon start's upsert hits the same records instead of creating duplicates+ const daemonId = hostname;+ const results = [];++ for (const rt of runtimes) {+ const name = `${rt.type} (${hostname})`;+ const result = await queries.runtime.upsertAgentRuntime(db, {+ workspaceId: mt.workspaceId,+ daemonId,+ name,+ runtimeMode: "local",+ provider: rt.type,+ status: "offline",+ deviceInfo: hostname,+ metadata: { version: rt.version },+ });+ results.push(result);+ }++ await queries.machineToken.activateMachineToken(db, mt.id);++ // Notify the web UI+ broadcastToUser(mt.userId, {+ type: "runtime.registered",+ daemonId,+ hostname,+ }).catch(() => {});++ return writeJSON({+ daemon_id: daemonId,+ runtimes: results.map(runtimeToResponse),+ });+}diff --git a/src/web/src/app/api/machine-tokens/route.test.ts b/src/web/src/app/api/machine-tokens/route.test.tsindex 17cfa92f5..2b31d12e5 100644--- a/src/web/src/app/api/machine-tokens/route.test.ts+++ b/src/web/src/app/api/machine-tokens/route.test.ts@@ -3,6 +3,7 @@ import { NextRequest } from "next/server";const mockListMachineTokens = vi.fn();const mockCreateMachineToken = vi.fn();+const mockGetPendingMachineToken = vi.fn();const mockMachineTokenToResponse = vi.fn((mt: any) => ({id: mt.id,name: mt.name,@@ -10,7 +11,6 @@ const mockMachineTokenToResponse = vi.fn((mt: any) => ({created_at: "2025-01-01T00:00:00Z",}));const mockGenerateMachineToken = vi.fn(() => "al_abc123");-const mockHashToken = vi.fn(() => "hashed_abc123");vi.mock("@/lib/middleware/helpers", () => ({writeJSON: (data: any, status = 200) =>@@ -33,6 +33,7 @@ vi.mock("@alook/shared", () => ({machineToken: {listMachineTokens: (...args: any[]) => mockListMachineTokens(...args),createMachineToken: (...args: any[]) => mockCreateMachineToken(...args),+ getPendingMachineToken: (...args: any[]) => mockGetPendingMachineToken(...args),},},}));@@ -50,7 +51,6 @@ vi.mock("@/lib/api/responses", () => ({}));vi.mock("@/lib/token", () => ({generateMachineToken: (...args: any[]) => mockGenerateMachineToken(...args),- hashToken: (...args: any[]) => mockHashToken(...args),}));import { GET, POST } from "./route";@@ -80,7 +80,27 @@ describe("GET /api/machine-tokens", () => {describe("POST /api/machine-tokens", () => {beforeEach(() => vi.clearAllMocks());- it("creates token and returns 201", async () => {+ it("returns existing pending token if one exists", async () => {+ const pending = { id: "mt0", token: "al_existing", name: "default", lastUsedAt: null, createdAt: "2025-01-01T00:00:00Z" };+ mockGetPendingMachineToken.mockResolvedValue(pending);++ const res = await POST(+ new NextRequest("http://localhost/api/machine-tokens", {+ method: "POST",+ body: JSON.stringify({}),+ headers: { "Content-Type": "application/json" },+ })+ );+ const body = await res.json();++ expect(res.status).toBe(200);+ expect(body.token).toBe("al_existing");+ expect(mockCreateMachineToken).not.toHaveBeenCalled();+ expect(mockGenerateMachineToken).not.toHaveBeenCalled();+ });++ it("creates pending token when none exists and returns 201", async () => {+ mockGetPendingMachineToken.mockResolvedValue(null);const mt = { id: "mt1", name: "my-token", lastUsedAt: null, createdAt: "2025-01-01T00:00:00Z" };mockCreateMachineToken.mockResolvedValue(mt);@@ -104,12 +124,14 @@ describe("POST /api/machine-tokens", () => {expect(mockCreateMachineToken).toHaveBeenCalledWith({}, {userId: "u1",workspaceId: "w1",- tokenHash: "hashed_abc123",+ token: "al_abc123",name: "my-token",+ status: "pending",});});- it("returns the unhashed token in the response", async () => {+ it("returns the raw token in the response", async () => {+ mockGetPendingMachineToken.mockResolvedValue(null);const mt = { id: "mt2", name: "default", lastUsedAt: null, createdAt: "2025-01-01T00:00:00Z" };mockCreateMachineToken.mockResolvedValue(mt);@@ -123,7 +145,5 @@ describe("POST /api/machine-tokens", () => {const body = await res.json();expect(body.token).toBe("al_abc123");- expect(body.token).not.toBe("hashed_abc123");- expect(mockHashToken).toHaveBeenCalledWith("al_abc123");});});diff --git a/src/web/src/app/api/machine-tokens/route.ts b/src/web/src/app/api/machine-tokens/route.tsindex 8b594951f..a1ff15e30 100644--- a/src/web/src/app/api/machine-tokens/route.ts+++ b/src/web/src/app/api/machine-tokens/route.ts@@ -1,7 +1,7 @@import { NextRequest } from "next/server";import { getCloudflareContext } from "@opennextjs/cloudflare"import { createDb, queries } from "@alook/shared"-import { generateMachineToken, hashToken } from "@/lib/token";+import { generateMachineToken } from "@/lib/token";import { withAuth } from "@/lib/middleware/auth";import { withWorkspaceMember } from "@/lib/middleware/workspace";import { writeJSON } from "@/lib/middleware/helpers";@@ -25,6 +25,12 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {const { env } = getCloudflareContext()const db = createDb((env as Env).DB)+ // Reuse existing pending token for this workspace+ const pending = await queries.machineToken.getPendingMachineToken(db, ctx.userId, ws.workspaceId);+ if (pending) {+ return writeJSON({ token: pending.token, ...machineTokenToResponse(pending) });+ }+let name = "default";try {const body = (await req.json()) as { name?: string };@@ -36,13 +42,13 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {}const raw = generateMachineToken();- const tokenHash = hashToken(raw);const mt = await queries.machineToken.createMachineToken(db, {userId: ctx.userId,workspaceId: ws.workspaceId,- tokenHash,+ token: raw,name,+ status: "pending",});return writeJSON({ token: raw, ...machineTokenToResponse(mt) }, 201);diff --git a/src/web/src/app/api/runtimes/machine/route.ts b/src/web/src/app/api/runtimes/machine/route.tsindex 3f35a75b0..78d9607bb 100644--- a/src/web/src/app/api/runtimes/machine/route.ts+++ b/src/web/src/app/api/runtimes/machine/route.ts@@ -5,6 +5,7 @@ import { withAuth } from "@/lib/middleware/auth";import { withWorkspaceMember } from "@/lib/middleware/workspace";import { writeJSON } from "@/lib/middleware/helpers";import { log } from "@/lib/logger";+import { broadcastToUser } from "@/lib/broadcast";export const DELETE = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx);@@ -25,5 +26,10 @@ export const DELETE = withAuth(async (req: NextRequest, ctx) => {return writeJSON({ error: "Failed to remove machine" }, 500);}+ broadcastToUser(ctx.userId, {+ type: "runtime.deleted",+ daemonId,+ }).catch(() => {});+return new Response(null, { status: 204 });});diff --git a/src/web/src/components/dashboard-navbar.tsx b/src/web/src/components/dashboard-navbar.tsxindex c9f70fff8..eb91ed8f9 100644--- a/src/web/src/components/dashboard-navbar.tsx+++ b/src/web/src/components/dashboard-navbar.tsx@@ -23,6 +23,7 @@ import { Logo } from "@/components/logo";import { toast } from "sonner";import type { Runtime } from "@/lib/api";import { signOut } from "@/lib/auth-client";+import { CLI_CMD } from "@/lib/utils";function OnboardingSteps({generatedToken,@@ -81,12 +82,12 @@ function OnboardingSteps({className="rounded-md bg-muted p-2.5 font-mono text-xs text-muted-foreground cursor-pointer hover:bg-muted/80 transition-colors"onClick={() =>copyToClipboard(- `npx @alook/cli register --token ${generatedToken}`+ `${CLI_CMD} register --token ${generatedToken}`)}title="Click to copy">- npx @alook/cli register --token{" "}+ {CLI_CMD} register --token{" "}<span className="text-foreground/70">{generatedToken.slice(0, 12)}...</span>@@ -95,7 +96,7 @@ function OnboardingSteps({size="sm"onClick={() => {navigator.clipboard.writeText(- `npx @alook/cli register --token ${generatedToken}`+ `${CLI_CMD} register --token ${generatedToken}`);toast("Copied to clipboard");}}@@ -123,11 +124,11 @@ function OnboardingSteps({<divclassName="ml-7 rounded-md bg-muted p-2.5 font-mono text-xs text-muted-foreground cursor-pointer hover:bg-muted/80 transition-colors"onClick={() =>- copyToClipboard("npx @alook/cli daemon start --foreground")+ copyToClipboard(`${CLI_CMD} daemon start --foreground`)}title="Click to copy">- npx @alook/cli daemon start --foreground+ {CLI_CMD} daemon start --foreground</div></div></div>diff --git a/src/web/src/contexts/agent-context.tsx b/src/web/src/contexts/agent-context.tsxindex 1e27ed35f..87a9cd902 100644--- a/src/web/src/contexts/agent-context.tsx+++ b/src/web/src/contexts/agent-context.tsx@@ -25,7 +25,9 @@ import type {Agent,CreateAgentRequest,UpdateAgentRequest,+ WsMessage,} from "@alook/shared";+import { useUserWs } from "@/lib/use-user-ws";interface AgentContextValue {agents: Agent[];@@ -81,6 +83,21 @@ export function AgentProvider({reload();}, [reload]);+ // Listen for real-time WS events+ const handleWsMessage = useCallback(+ (msg: WsMessage) => {+ switch (msg.type) {+ case "runtime.registered":+ case "runtime.status":+ case "runtime.deleted":+ reload();+ break;+ }+ },+ [reload]+ );+ useUserWs(handleWsMessage);+const handleCreateAgent = useCallback(async (req: CreateAgentRequest): Promise<Agent | null> => {try {diff --git a/src/web/src/lib/api-auth.ts b/src/web/src/lib/api-auth.tsindex 164da7c7d..f99cf5c23 100644--- a/src/web/src/lib/api-auth.ts+++ b/src/web/src/lib/api-auth.ts@@ -1,24 +1,18 @@import { getCloudflareContext } from "@opennextjs/cloudflare"import { createDb, queries } from "@alook/shared"-import { createHash } from "crypto"--function hashToken(raw: string): string {- return createHash("sha256").update(raw).digest("hex")-}export async function withToken(request: Request) {const authHeader = request.headers.get("Authorization")if (!authHeader?.startsWith("Bearer ")) {return { error: new Response("Unauthorized", { status: 401 }), machineToken: null }}- const token = authHeader.slice(7)- if (!token.startsWith("al_")) {+ const raw = authHeader.slice(7)+ if (!raw.startsWith("al_")) {return { error: new Response("Invalid token format", { status: 401 }), machineToken: null }}const { env } = await getCloudflareContext({ async: true })const db = createDb((env as Env).DB)- const hashedToken = hashToken(token)- const mt = await queries.machineToken.getMachineTokenByHash(db, hashedToken)+ const mt = await queries.machineToken.getMachineTokenByToken(db, raw)if (!mt) {return { error: new Response("Token not found", { status: 401 }), machineToken: null }}diff --git a/src/web/src/lib/dual-auth.ts b/src/web/src/lib/dual-auth.tsindex 35e456724..4fbf3bb22 100644--- a/src/web/src/lib/dual-auth.ts+++ b/src/web/src/lib/dual-auth.ts@@ -1,11 +1,6 @@import { getCloudflareContext } from "@opennextjs/cloudflare"import { createDb, queries } from "@alook/shared"import { createAuth } from "@/lib/auth"-import { createHash } from "crypto"--function hashToken(raw: string): string {- return createHash("sha256").update(raw).digest("hex")-}export async function requireAuth(request: Request) {const { env } = await getCloudflareContext({ async: true })@@ -13,11 +8,10 @@ export async function requireAuth(request: Request) {const authHeader = request.headers.get("Authorization")if (authHeader?.startsWith("Bearer ")) {- const token = authHeader.slice(7)- if (token.startsWith("al_")) {+ const raw = authHeader.slice(7)+ if (raw.startsWith("al_")) {const db = createDb(cloudflareEnv.DB)- const hashedToken = hashToken(token)- const mt = await queries.machineToken.getMachineTokenByHash(db, hashedToken)+ const mt = await queries.machineToken.getMachineTokenByToken(db, raw)if (mt) {queries.machineToken.updateMachineTokenLastUsed(db, mt.id).catch(() => {})return { userId: mt.userId, email: mt.userEmail, workspaceId: mt.workspaceId ?? undefined, error: null }diff --git a/src/web/src/lib/middleware/auth.test.ts b/src/web/src/lib/middleware/auth.test.tsindex cd0694319..295ce5fa8 100644--- a/src/web/src/lib/middleware/auth.test.ts+++ b/src/web/src/lib/middleware/auth.test.ts@@ -9,7 +9,7 @@ vi.mock("@alook/shared", () => ({createDb: vi.fn(() => ({})),queries: {machineToken: {- getMachineTokenByHash: vi.fn(),+ getMachineTokenByToken: vi.fn(),updateMachineTokenLastUsed: vi.fn(),},},@@ -26,7 +26,7 @@ import { withAuth } from "./auth";import { queries } from "@alook/shared";const mockGetMachineTokenByHash = queries.machineToken- .getMachineTokenByHash as ReturnType<typeof vi.fn>;+ .getMachineTokenByToken as ReturnType<typeof vi.fn>;const mockUpdateMachineTokenLastUsed = queries.machineToken.updateMachineTokenLastUsed as ReturnType<typeof vi.fn>;@@ -127,7 +127,7 @@ describe("withAuth middleware", () => {expect(mockGetMachineTokenByHash).toHaveBeenCalledOnce();});- it("returns 401 for unknown machine token (getMachineTokenByHash returns null)", async () => {+ it("returns 401 for unknown machine token (getMachineTokenByToken returns null)", async () => {mockGetMachineTokenByHash.mockResolvedValue(null);const req = new NextRequest("http://localhost/api/test", {diff --git a/src/web/src/lib/middleware/auth.ts b/src/web/src/lib/middleware/auth.tsindex 2be589818..384ace39a 100644--- a/src/web/src/lib/middleware/auth.ts+++ b/src/web/src/lib/middleware/auth.ts@@ -2,7 +2,6 @@ import { NextRequest, NextResponse } from "next/server"import { getCloudflareContext } from "@opennextjs/cloudflare"import { createDb, queries } from "@alook/shared"import { createAuth } from "@/lib/auth"-import { createHash } from "crypto"export interface AuthContext {userId: string@@ -15,10 +14,6 @@ export type AuthenticatedHandler = (ctx: AuthContext & { params?: Record<string, string> }) => Promise<NextResponse | Response>-function hashToken(raw: string): string {- return createHash("sha256").update(raw).digest("hex")-}-export function withAuth(handler: AuthenticatedHandler) {return async (req: NextRequest,@@ -35,12 +30,11 @@ export function withAuth(handler: AuthenticatedHandler) {const authHeader = req.headers.get("Authorization")if (authHeader?.startsWith("Bearer ")) {- const token = authHeader.slice(7)- if (token.startsWith("al_")) {+ const raw = authHeader.slice(7)+ if (raw.startsWith("al_")) {try {const db = createDb(cloudflareEnv.DB)- const hashed = hashToken(token)- const mt = await queries.machineToken.getMachineTokenByHash(db, hashed)+ const mt = await queries.machineToken.getMachineTokenByToken(db, raw)if (!mt) {return NextResponse.json({ error: "invalid token" }, { status: 401 })}diff --git a/src/web/src/lib/token.ts b/src/web/src/lib/token.tsindex 066a537a4..24049409c 100644--- a/src/web/src/lib/token.ts+++ b/src/web/src/lib/token.ts@@ -1,10 +1,6 @@-import { randomBytes, createHash } from "crypto";+import { randomBytes } from "crypto";export function generateMachineToken(): string {const bytes = randomBytes(24);return "al_" + bytes.toString("hex");}--export function hashToken(raw: string): string {- return createHash("sha256").update(raw).digest("hex");-}diff --git a/src/web/src/lib/utils.ts b/src/web/src/lib/utils.tsindex bd0c391dd..7664553da 100644--- a/src/web/src/lib/utils.ts+++ b/src/web/src/lib/utils.ts@@ -4,3 +4,6 @@ import { twMerge } from "tailwind-merge"export function cn(...inputs: ClassValue[]) {return twMerge(clsx(inputs))}++export const CLI_CMD =+ process.env.NODE_ENV === "development" ? "pnpm dev:cli" : "npx @alook/cli";diff --git a/src/web/src/test/helpers/seed.ts b/src/web/src/test/helpers/seed.tsindex 8d9d0c42f..22ad48867 100644--- a/src/web/src/test/helpers/seed.ts+++ b/src/web/src/test/helpers/seed.ts@@ -1,4 +1,4 @@-import { createHash, randomUUID } from "crypto"+import { randomUUID } from "crypto"import { sql } from "./db"export interface TestSeed {@@ -16,10 +16,6 @@ function nanoid() {return randomUUID().replace(/-/g, "").slice(0, 21)}-function hashToken(raw: string): string {- return createHash("sha256").update(raw).digest("hex")-}-/*** Seed a full test environment: user, workspace, member, runtime, agent, machine token.* All IDs are unique per call.@@ -32,7 +28,6 @@ export function seedTestData(): TestSeed {const agentId = `ag_${nanoid()}`const machineTokenId = `mt_${nanoid()}`const rawToken = `al_${randomUUID().replace(/-/g, "")}`- const tokenHash = hashToken(rawToken)const now = new Date().toISOString()const slug = `test-${nanoid()}`@@ -42,7 +37,7 @@ export function seedTestData(): TestSeed {sql(`INSERT INTO member (id, workspace_id, user_id, role, created_at) VALUES ('${memberId}', '${workspaceId}', '${userId}', 'owner', '${now}')`)sql(`INSERT INTO agent_runtime (id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, created_at, updated_at) VALUES ('${runtimeId}', '${workspaceId}', 'daemon_${nanoid()}', 'Test Runtime', 'local', 'claude', 'online', 'test-device', '${now}', '${now}')`)sql(`INSERT INTO agent (id, workspace_id, name, runtime_id, created_at, updated_at) VALUES ('${agentId}', '${workspaceId}', 'Test Agent', '${runtimeId}', '${now}', '${now}')`)- sql(`INSERT INTO machine_token (id, user_id, workspace_id, token_hash, name, created_at) VALUES ('${machineTokenId}', '${userId}', '${workspaceId}', '${tokenHash}', 'test-token', '${now}')`)+ sql(`INSERT INTO machine_token (id, user_id, workspace_id, token, name, status, created_at) VALUES ('${machineTokenId}', '${userId}', '${workspaceId}', '${rawToken}', 'test-token', 'active', '${now}')`)return { userId, workspaceId, memberId, runtimeId, agentId, machineToken: rawToken, machineTokenId }}