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
refactor: unify three-mode detection into @alook/shared (#76)
Generac20e0e693db
diff --git a/src/app/src/lib/services.ts b/src/app/src/lib/services.tsindex 57a0d629a..b637546c0 100644--- a/src/app/src/lib/services.ts+++ b/src/app/src/lib/services.ts@@ -1,6 +1,7 @@import { spawn, execSync, type ChildProcess } from "child_process";import { join } from "path";import { openSync, mkdirSync, closeSync } from "fs";+import { resolveMode } from "@alook/shared";import { SELF_HOSTED_DIR } from "./constants.js";import { writePids, readPids, isAlive, clearPids } from "./pid.js";@@ -14,9 +15,7 @@ interface StartOptions {foreground?: boolean;}-function isDevMode(): boolean {- return !!process.env.ALOOK_PROJECT_ROOT;-}+const isDevMode = resolveMode({ nodeEnv: process.env.NODE_ENV }) === "dev";function logDir(): string {const dir = join(SELF_HOSTED_DIR, "logs");@@ -88,7 +87,7 @@ export function startServices(ports: ServicePorts, opts: StartOptions = {}): voilet emailChild: ChildProcess;let wsChild: ChildProcess;- if (isDevMode()) {+ if (isDevMode) {const root = process.env.ALOOK_PROJECT_ROOT!;const webDir = join(root, "src", "web");const emailDir = join(root, "src", "email-worker");diff --git a/src/cli/commands/sync.ts b/src/cli/commands/sync.tsindex 7b2f3b836..a55256e71 100644--- a/src/cli/commands/sync.ts+++ b/src/cli/commands/sync.ts@@ -1,5 +1,5 @@import { Command } from "commander";-import { readFileSync, statSync } from "fs";+import { readFileSync } from "fs";import { basename } from "path";import { APIClient } from "../lib/client.js";import { loadCLIConfigForProfile } from "../lib/config.js";@@ -64,10 +64,7 @@ export function syncCommand(): Command {const client = new APIClient(serverUrl, token, workspaceId);let bytes: Buffer;- let size: number;try {- const stat = statSync(opts.file);- size = stat.size;bytes = readFileSync(opts.file);} catch (err) {console.error(`Error: cannot read file "${opts.file}": ${(err as Error).message}`);diff --git a/src/cli/daemon/client.test.ts b/src/cli/daemon/client.test.tsindex 72ec8f815..dd7f7598d 100644--- a/src/cli/daemon/client.test.ts+++ b/src/cli/daemon/client.test.ts@@ -283,6 +283,7 @@ describe("DaemonClient.register() with mocked fetch", () => {daemon_id: "d1",device_name: "mac",cli_version: "1.0",+ workspaces_root: "/home/.alook/workspaces",runtimes: [{ type: "claude", version: "1.0" }],});expect(resp.runtimes[0].id).toBe("rt1");@@ -301,6 +302,7 @@ describe("DaemonClient.register() with mocked fetch", () => {daemon_id: "d1",device_name: "mac",cli_version: "1.0",+ workspaces_root: "/home/.alook/workspaces",runtimes: [{ type: "claude", version: "1.0" }],});diff --git a/src/cli/daemon/client.ts b/src/cli/daemon/client.tsindex b9e5331c8..f0aa1375f 100644--- a/src/cli/daemon/client.ts+++ b/src/cli/daemon/client.ts@@ -1,9 +1,12 @@import {PollResponseSchema,RegisterResponseSchema,+ type CompleteTaskRequest,type FileRequestItem,+ type MessageItem,type PollMeetingItem,type PollResponse,+ type RegisterDaemonRequest,type RegisterResponse,type TaskApi,type WorkspaceFileReport,@@ -51,16 +54,7 @@ export class DaemonClient {async register(token: string,- body: {- workspace_id: string;- daemon_id: string;- device_name: string;- cli_version: string;- runtimes: {- type: string;- version: string;- }[];- },+ body: RegisterDaemonRequest,): Promise<RegisterResponse> {const raw = await this.request<unknown>("POST",@@ -114,11 +108,7 @@ export class DaemonClient {completeTask(token: string,taskId: string,- body: {- output: string;- session_id?: string;- branch_name?: string;- },+ body: CompleteTaskRequest,) {return this.request("POST",@@ -185,15 +175,7 @@ export class DaemonClient {reportMessages(token: string,taskId: string,- messages: {- seq: number;- type: string;- tool?: string;- call_id?: string;- content?: string;- input?: Record<string, unknown>;- output?: string;- }[],+ messages: MessageItem[],) {return this.request("POST",diff --git a/src/cli/daemon/daemon.ts b/src/cli/daemon/daemon.tsindex d5a1a5d2d..6b086e5ef 100644--- a/src/cli/daemon/daemon.ts+++ b/src/cli/daemon/daemon.ts@@ -14,7 +14,6 @@ import { handleCliUpdate, isUpdating, readUpdateMarker, clearUpdateMarker } fromimport { findRunningPidByTaskId, findRunningEntryByContextKey } from "./execenv/timeline.js";import {writeKillIntent,- clearKillIntent,acquireSteeringLock,releaseSteeringLock,cleanupStaleIntents,@@ -300,6 +299,7 @@ export async function startDaemon(daemon_id: config.daemonId,device_name: config.deviceName,cli_version: config.cliVersion,+ workspaces_root: config.workspacesRoot,runtimes,});} catch (e) {@@ -574,6 +574,7 @@ export async function startDaemon(daemon_id: config.daemonId,device_name: config.deviceName,cli_version: config.cliVersion,+ workspaces_root: config.workspacesRoot,runtimes,});const runtimeIds = resp.runtimes.map((r: { id: string }) => r.id);diff --git a/src/cli/daemon/execenv/context.ts b/src/cli/daemon/execenv/context.tsindex d5f882a94..274798c78 100644--- a/src/cli/daemon/execenv/context.ts+++ b/src/cli/daemon/execenv/context.ts@@ -1,6 +1,7 @@import { createHash } from "crypto";import { toAlookAddress } from "@alook/shared";import { tempDir } from "../../lib/platform.js";+import { cmdPrefix } from "../../lib/env.js";import {writeFileSync,readFileSync,@@ -137,12 +138,12 @@ Your alook agent id is '${task.agentId}'. remember this, most of alook cli will### Emails----Run 'npx @alook/cli email pull --agent_id ${task.agentId} --status unread' to download unread emails from inbox to '${tempDir("alook-emails")}/${task.workspaceId}/${task.agentId}/'.+Run '${cmdPrefix()} email pull --agent_id ${task.agentId} --status unread' to download unread emails from inbox to '${tempDir("alook-emails")}/${task.workspaceId}/${task.agentId}/'.----To download sent emails, add '--folder sent': 'npx @alook/cli email pull --agent_id ${task.agentId} --folder sent'+To download sent emails, add '--folder sent': '${cmdPrefix()} email pull --agent_id ${task.agentId} --folder sent'Valid folders: inbox (default), sent, untrust.To limit the number of emails downloaded, add '--limit <N>' (e.g. '--limit 20'). Use '--offset <N>' to skip emails for pagination.-Example: 'npx @alook/cli email pull --agent_id ${task.agentId} --status unread --limit 20 --offset 0'+Example: '${cmdPrefix()} email pull --agent_id ${task.agentId} --status unread --limit 20 --offset 0'---Each email is saved to '${tempDir("alook-emails")}/${task.workspaceId}/${task.agentId}/<emailId>/' with:- 'metadata.json' — sender, recipient, subject, date, status, message_id, in_reply_to, references@@ -151,40 +152,40 @@ Each email is saved to '${tempDir("alook-emails")}/${task.workspaceId}/${task.ag- 'attachments/' — extracted attachment files (if any)---Before starting to process an INBOX email, mark it as read:-- Run 'npx @alook/cli email set --agent_id ${task.agentId} --email_id <EMAIL_ID> --status read'+- Run '${cmdPrefix()} email set --agent_id ${task.agentId} --email_id <EMAIL_ID> --status read'---#### Sending a new emailWrite the HTML body to a file first, then send it. The body is forwarded as-is (HTML).-- Run 'npx @alook/cli email send --agent_id ${task.agentId} --to <ADDRESS> --subject "<SUBJECT>" --body-file <PATH_TO_HTML>'+- Run '${cmdPrefix()} email send --agent_id ${task.agentId} --to <ADDRESS> --subject "<SUBJECT>" --body-file <PATH_TO_HTML>'- To send from a specific mailbox, add '--from <YOUR_EMAIL_ADDRESS>'. Without '--from', the default Alook address is used.- Attach files with '--attachment <PATH>' — repeat the flag for multiple attachments. Each file is uploaded before sending.-- Example: 'npx @alook/cli email send --agent_id ${task.agentId} --to [email protected] --subject "Weekly report" --body-file /tmp/body.html --from [email protected] --attachment /tmp/report.pdf'+- Example: '${cmdPrefix()} email send --agent_id ${task.agentId} --to [email protected] --subject "Weekly report" --body-file /tmp/body.html --from [email protected] --attachment /tmp/report.pdf'#### Replying to an emailTo reply to an email, add '--in-reply-to <EMAIL_ID>' to the send command. This sets the correct email threading headers so the recipient's email client groups the reply into the same conversation thread.- Use 'Re: <original subject>' as the subject.- Quote the original email body in your reply (wrap it in a blockquote).- The <EMAIL_ID> is the Alook email id from metadata.json (not the message_id header).-- Example: 'npx @alook/cli email send --agent_id ${task.agentId} --to [email protected] --subject "Re: Bug report" --body-file /tmp/reply.html --in-reply-to <EMAIL_ID>'+- Example: '${cmdPrefix()} email send --agent_id ${task.agentId} --to [email protected] --subject "Re: Bug report" --body-file /tmp/reply.html --in-reply-to <EMAIL_ID>'Tips:- If you think the task will take a while, consider sending a short "I'm on it" style email reply first to reassure the sender.---#### Forwarding an emailForward any email to a new recipient, with an optional note prepended above the original content. All original attachments are re-attached automatically.-- Run 'npx @alook/cli email forward --agent_id ${task.agentId} --email_id <EMAIL_ID> --to <RECIPIENT>'+- Run '${cmdPrefix()} email forward --agent_id ${task.agentId} --email_id <EMAIL_ID> --to <RECIPIENT>'- Add '--note "FYI, see the request below."' to prepend a note above the forwarded body.- Add '--from <YOUR_EMAIL_ADDRESS>' to send from a specific mailbox.- Add '--attachment <PATH>' to attach extra files (repeatable).-- Example: 'npx @alook/cli email forward --agent_id ${task.agentId} --email_id em_abc --to [email protected] --note "FYI" --attachment /tmp/summary.pdf'+- Example: '${cmdPrefix()} email forward --agent_id ${task.agentId} --email_id em_abc --to [email protected] --note "FYI" --attachment /tmp/summary.pdf'---#### Email Whitelist (Allowed Senders)Manage which email addresses are allowed to send you emails.-- List: 'npx @alook/cli email whitelist list --agent_id ${task.agentId}' (add '--json' for machine-readable output)-- Add: 'npx @alook/cli email whitelist add --agent_id ${task.agentId} <EMAIL_ADDRESS>'-- Remove: 'npx @alook/cli email whitelist delete --agent_id ${task.agentId} <EMAIL_ADDRESS>'+- List: '${cmdPrefix()} email whitelist list --agent_id ${task.agentId}' (add '--json' for machine-readable output)+- Add: '${cmdPrefix()} email whitelist add --agent_id ${task.agentId} <EMAIL_ADDRESS>'+- Remove: '${cmdPrefix()} email whitelist delete --agent_id ${task.agentId} <EMAIL_ADDRESS>'---`;}@@ -192,7 +193,7 @@ Manage which email addresses are allowed to send you emails.content += `\n### ArtifactsUpload files for your owner to review in the app.- Your current conversation id is available via env var: $ALOOK_CONVERSATION_ID-- Run 'npx @alook/cli sync upload-artifact --agent_id ${task.agentId} --conversation_id $ALOOK_CONVERSATION_ID --file <PATH>'+- Run '${cmdPrefix()} sync upload-artifact --agent_id ${task.agentId} --conversation_id $ALOOK_CONVERSATION_ID --file <PATH>'- Use this after generating plans, reports, or any file the owner should review.- You response will be rendered in remote server, so don't output link format with local path in your response (cause user can click it and jump to nowheres)- If you think user may need to know any file detail, use upload-artifact tool to send the file to user.@@ -214,26 +215,26 @@ Schedule future tasks for yourself. At the scheduled time, a new task is dispatcKeep the event title informative and concise, less than 20 words.Place the event details in description.Create a one-off event:-- Run 'npx @alook/cli calendar set --agent_id ${task.agentId} --event_title "<TASK_TITLE>" --description "<TASK_BODY>" --datetime <YYYY-MM-DDTHH:MM>'+- Run '${cmdPrefix()} calendar set --agent_id ${task.agentId} --event_title "<TASK_TITLE>" --description "<TASK_BODY>" --datetime <YYYY-MM-DDTHH:MM>'- '--datetime' is LOCAL time, format 'YYYY-MM-DDTHH:MM' (e.g. '2026-04-17T09:30'). Do NOT pass UTC / ISO strings with 'Z'.- '--event_title' becomes the task prompt when the event fires — write it as the instruction you want future-you to receive.Create a repeating event:- Add '--repeat <interval>' where interval is like '1day', '2hour', '1week', '1month'.- Optionally add '--repeat_stop_date <YYYY-MM-DD>' to stop the recurrence (local date).-- Example: 'npx @alook/cli calendar set --agent_id ${task.agentId} --event_title "<REPEAT_TASK_TITLE>" --description "<REPEAT_TASK_BODY>" --datetime 2026-04-18T09:00 --repeat 1day --repeat_stop_date 2026-05-18'+- Example: '${cmdPrefix()} calendar set --agent_id ${task.agentId} --event_title "<REPEAT_TASK_TITLE>" --description "<REPEAT_TASK_BODY>" --datetime 2026-04-18T09:00 --repeat 1day --repeat_stop_date 2026-05-18'---List upcoming events:-- Run 'npx @alook/cli calendar list --agent_id ${task.agentId}' (defaults: next 30 days, past 0 days).+- Run '${cmdPrefix()} calendar list --agent_id ${task.agentId}' (defaults: next 30 days, past 0 days).- Tune the window with '--future_days <N>' and '--past_days <N>'. Add '--json' for machine-readable output.- 'list' shows a '[has description]' badge instead of the full description — use 'show' (below) to read it.Show full detail of one event (use this to read the description):-- Run 'npx @alook/cli calendar show --agent_id ${task.agentId} --event_id <EVENT_ID>'+- Run '${cmdPrefix()} calendar show --agent_id ${task.agentId} --event_id <EVENT_ID>'- Add '--json' for machine-readable output.Edit an existing event (preserves event id and recurring state):-- Run 'npx @alook/cli calendar update --agent_id ${task.agentId} --event_id <EVENT_ID> [flags]'+- Run '${cmdPrefix()} calendar update --agent_id ${task.agentId} --event_id <EVENT_ID> [flags]'- Supply only the fields you want to change. Available flags:- '--event_title "<t>"' — rename the event / change the fire-time prompt- '--description "<d>"' to set, or '--clear_description' to remove@@ -243,7 +244,7 @@ Edit an existing event (preserves event id and recurring state):- Passing no mutating flag is an error. Do NOT use 'delete' + 'set' to edit — that loses the event id and the recurring 'last fired' state.Delete an event:-- Run 'npx @alook/cli calendar delete --agent_id ${task.agentId} --event_id <EVENT_ID>'+- Run '${cmdPrefix()} calendar delete --agent_id ${task.agentId} --event_id <EVENT_ID>'---`;diff --git a/src/cli/daemon/session-runner.ts b/src/cli/daemon/session-runner.tsindex a03213082..3387430f6 100644--- a/src/cli/daemon/session-runner.ts+++ b/src/cli/daemon/session-runner.ts@@ -357,7 +357,7 @@ export async function runSession(input: SessionRunnerInput): Promise<void> {if (session.pid) {try { process.kill(session.pid, "SIGTERM"); } catch { /* already dead */ }}- iter.return?.(undefined as any);+ iter.return?.(undefined as never);break;}diff --git a/src/cli/eslint.config.mjs b/src/cli/eslint.config.mjsindex 8d67ca6ff..50a7cedfc 100644--- a/src/cli/eslint.config.mjs+++ b/src/cli/eslint.config.mjs@@ -9,6 +9,7 @@ const eslintConfig = defineConfig([rules: {"@typescript-eslint/no-explicit-any": "off","@typescript-eslint/no-unused-vars": "off",+ "@typescript-eslint/no-require-imports": "off",},},]);diff --git a/src/cli/lib/env.ts b/src/cli/lib/env.tsindex c543bdaa4..17d50270f 100644--- a/src/cli/lib/env.ts+++ b/src/cli/lib/env.ts@@ -1,8 +1,15 @@+import { resolveMode, cliCommand } from "@alook/shared";+export function isDev(): boolean {- return !!process.env.ALOOK_SERVER_URL && !process.env.ALOOK_CMD_PREFIX;+ return resolveMode({+ serverUrl: process.env.ALOOK_SERVER_URL,+ cmdPrefix: process.env.ALOOK_CMD_PREFIX,+ }) === "dev";}export function cmdPrefix(): string {- if (process.env.ALOOK_CMD_PREFIX) return process.env.ALOOK_CMD_PREFIX;- return isDev() ? "pnpm dev:cli" : "npx @alook/cli";+ return process.env.ALOOK_CMD_PREFIX || cliCommand(resolveMode({+ serverUrl: process.env.ALOOK_SERVER_URL,+ cmdPrefix: process.env.ALOOK_CMD_PREFIX,+ }));}diff --git a/src/cli/package.json b/src/cli/package.jsonindex 3baed7c7e..42b89848d 100644--- a/src/cli/package.json+++ b/src/cli/package.json@@ -41,7 +41,7 @@"build": "bun build src/index.ts --outdir dist --target node --format esm --external citty --external commander --external postal-mime --external playwright-core && bun build daemon/session-runner.ts --outdir dist --target node --format esm --external citty --external commander --external postal-mime && bun build daemon/meeting-runner.ts --outdir dist --target node --format esm --external playwright-core && node scripts/prepare-dist.mjs","prepack": "pnpm run build","test": "vitest run",- "lint": "eslint src/",+ "lint": "eslint .","typecheck": "tsc --noEmit -p tsconfig.build.json"},"dependencies": {diff --git a/src/shared/src/index.ts b/src/shared/src/index.tsindex 2c1afaeb7..7a75dc5cc 100644--- a/src/shared/src/index.ts+++ b/src/shared/src/index.ts@@ -4,6 +4,7 @@ export type {Workspace,Agent,AgentRuntime,+ RuntimeMetadata,Machine,Conversation,Message,@@ -234,3 +235,5 @@ export { isOnline, formatStatus } from "./utils/status";export { isUniqueConstraintError } from "./utils/db-errors";export { generateWorkspaceSlug } from "./utils/slug";export { semverGte } from "./semver";+export { resolveMode, cliCommand, daemonCommand } from "./mode";+export type { AlookMode, ModeSignals } from "./mode";diff --git a/src/shared/src/mode.test.ts b/src/shared/src/mode.test.tsnew file mode 100644index 000000000..6fe0c14ce--- /dev/null+++ b/src/shared/src/mode.test.ts@@ -0,0 +1,90 @@+import { describe, it, expect } from "vitest";+import { resolveMode, cliCommand, daemonCommand } from "./mode";++describe("resolveMode", () => {+ it("production: no signals", () => {+ expect(resolveMode({})).toBe("production");+ });++ it("production: non-development NODE_ENV", () => {+ expect(resolveMode({ nodeEnv: "production" })).toBe("production");+ });++ it("production: random hostname", () => {+ expect(resolveMode({ hostname: "alook.ai" })).toBe("production");+ });++ it("dev: NODE_ENV=development", () => {+ expect(resolveMode({ nodeEnv: "development" })).toBe("dev");+ });++ it("dev: ALOOK_SERVER_URL without CMD_PREFIX", () => {+ expect(resolveMode({ serverUrl: "http://localhost:3000" })).toBe("dev");+ });++ it("dev: ALOOK_SERVER_URL + NODE_ENV=development", () => {+ expect(+ resolveMode({ serverUrl: "http://localhost:3000", nodeEnv: "development" }),+ ).toBe("dev");+ });++ it("app: CMD_PREFIX set (overrides serverUrl)", () => {+ expect(+ resolveMode({+ serverUrl: "http://localhost:15210",+ cmdPrefix: "npx @alook/app cli",+ }),+ ).toBe("app");+ });++ it("app: CMD_PREFIX set overrides NODE_ENV=development", () => {+ expect(+ resolveMode({+ nodeEnv: "development",+ cmdPrefix: "npx @alook/app cli",+ }),+ ).toBe("app");+ });++ it("app: localhost hostname", () => {+ expect(resolveMode({ hostname: "localhost" })).toBe("app");+ });++ it("app: 127.0.0.1 hostname", () => {+ expect(resolveMode({ hostname: "127.0.0.1" })).toBe("app");+ });++ it("app: localhost hostname with production NODE_ENV", () => {+ expect(+ resolveMode({ nodeEnv: "production", hostname: "localhost" }),+ ).toBe("app");+ });+});++describe("cliCommand", () => {+ it("production → npx @alook/cli", () => {+ expect(cliCommand("production")).toBe("npx @alook/cli");+ });++ it("dev → pnpm dev:cli", () => {+ expect(cliCommand("dev")).toBe("pnpm dev:cli");+ });++ it("app → npx @alook/app cli", () => {+ expect(cliCommand("app")).toBe("npx @alook/app cli");+ });+});++describe("daemonCommand", () => {+ it("production → no --foreground", () => {+ expect(daemonCommand("production")).toBe("npx @alook/cli daemon start");+ });++ it("dev → with --foreground", () => {+ expect(daemonCommand("dev")).toBe("pnpm dev:cli daemon start --foreground");+ });++ it("app → no --foreground", () => {+ expect(daemonCommand("app")).toBe("npx @alook/app cli daemon start");+ });+});diff --git a/src/shared/src/mode.ts b/src/shared/src/mode.tsnew file mode 100644index 000000000..9bc12416d--- /dev/null+++ b/src/shared/src/mode.ts@@ -0,0 +1,33 @@+export type AlookMode = "production" | "dev" | "app";++export interface ModeSignals {+ serverUrl?: string;+ cmdPrefix?: string;+ nodeEnv?: string;+ hostname?: string;+}++export function resolveMode(signals: ModeSignals): AlookMode {+ if (signals.nodeEnv === "development" && !signals.cmdPrefix) return "dev";+ if (signals.serverUrl && !signals.cmdPrefix) return "dev";+ if (signals.cmdPrefix) return "app";+ if (signals.hostname && ["localhost", "127.0.0.1"].includes(signals.hostname))+ return "app";+ return "production";+}++export function cliCommand(mode: AlookMode): string {+ switch (mode) {+ case "dev":+ return "pnpm dev:cli";+ case "app":+ return "npx @alook/app cli";+ case "production":+ return "npx @alook/cli";+ }+}++export function daemonCommand(mode: AlookMode): string {+ const base = `${cliCommand(mode)} daemon start`;+ return mode === "dev" ? `${base} --foreground` : base;+}diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.tsindex 68fa7a4e8..95afef479 100644--- a/src/shared/src/schemas.ts+++ b/src/shared/src/schemas.ts@@ -192,6 +192,7 @@ export const RegisterDaemonRequestSchema = z.object({daemon_id: z.string().min(1),device_name: z.string().optional().default(""),cli_version: z.string().optional().default(""),+ workspaces_root: z.string().optional().default(""),runtimes: z.array(DaemonRuntimeItemSchema).min(1),});export type RegisterDaemonRequest = z.infer<typeof RegisterDaemonRequestSchema>;diff --git a/src/shared/src/types.ts b/src/shared/src/types.tsindex 245589ccd..862adeae1 100644--- a/src/shared/src/types.ts+++ b/src/shared/src/types.ts@@ -38,6 +38,13 @@ export interface Agent {updated_at: string;}+export interface RuntimeMetadata {+ version?: string;+ cli_version?: string;+ workspaces_root?: string;+ [key: string]: unknown;+}+export interface AgentRuntime {id: string;workspace_id: string;@@ -46,7 +53,7 @@ export interface AgentRuntime {provider: string;status: string;device_info: string;- metadata: Record<string, unknown>;+ metadata: RuntimeMetadata;pending_update_version?: string | null;pending_rescan?: boolean;last_seen_at: string | null;diff --git a/src/web/src/app/(app)/w/[slug]/agents/[id]/files/page.tsx b/src/web/src/app/(app)/w/[slug]/agents/[id]/files/page.tsxindex 93c3b508d..f15e33341 100644--- a/src/web/src/app/(app)/w/[slug]/agents/[id]/files/page.tsx+++ b/src/web/src/app/(app)/w/[slug]/agents/[id]/files/page.tsx@@ -59,7 +59,8 @@ export default function AgentFilesPage() {// Pending request tracking: map requestId -> { type, path, timer }const pendingRef = useRef<Map<string, { type: "tree" | "read"; path: string; timer: ReturnType<typeof setTimeout> }>>(new Map());- const rootLabel = `~/.alook/workspaces/${workspaceId}/${agentId}/workdir`;+ const workspacesRoot = runtime?.metadata?.workspaces_root;+ const rootLabel = `${workspacesRoot || "~/.alook/workspaces"}/${workspaceId}/${agentId}/workdir`;const REQUEST_TIMEOUT_MS = 15_000;diff --git a/src/web/src/app/(auth)/sign-in/page.tsx b/src/web/src/app/(auth)/sign-in/page.tsxindex 6e1789b75..2b835fc4c 100644--- a/src/web/src/app/(auth)/sign-in/page.tsx+++ b/src/web/src/app/(auth)/sign-in/page.tsx@@ -22,11 +22,14 @@ import {import { SiGithub, SiGoogle } from "@icons-pack/react-simple-icons"import { GradientBackground } from "@/components/gradient-background"import { TypewriterVisual, EMAILS_PLAYFUL } from "@/components/typewriter-visual"-import { isLocalMode } from "@/lib/utils"+import { resolveMode, DEV_PASSWORD } from "@alook/shared"-const isProd = !isLocalMode()+const mode = resolveMode({+ nodeEnv: process.env.NODE_ENV,+ hostname: typeof window !== "undefined" ? window.location.hostname : undefined,+})+const isProd = mode === "production"-import { DEV_PASSWORD } from "@alook/shared"const DEFAULT_POST_LOGIN = "/workspaces?auto"function safeRedirectUrl(redirect: string | null): string {diff --git a/src/web/src/app/api/daemon/register/route.ts b/src/web/src/app/api/daemon/register/route.tsindex c43d1ded9..698960b8d 100644--- a/src/web/src/app/api/daemon/register/route.ts+++ b/src/web/src/app/api/daemon/register/route.ts@@ -16,7 +16,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {const [body, err] = await parseBody(req, RegisterDaemonRequestSchema);if (err) return err;- const { daemon_id: daemonId, device_name: deviceName, cli_version: cliVersion, runtimes } = body;+ const { daemon_id: daemonId, device_name: deviceName, cli_version: cliVersion, workspaces_root: workspacesRoot, runtimes } = body;let workspaceId = body.workspace_id;// Resolve workspace: use provided, fall back to auth context, or create new@@ -72,6 +72,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {const metadata: Record<string, unknown> = {version: rt.version || "",...(cliVersion ? { cli_version: cliVersion } : {}),+ ...(workspacesRoot ? { workspaces_root: workspacesRoot } : {}),};const result = await queries.runtime.upsertAgentRuntime(db, {diff --git a/src/web/src/components/runtime-version-gate.tsx b/src/web/src/components/runtime-version-gate.tsxindex 909769cd7..e183b4673 100644--- a/src/web/src/components/runtime-version-gate.tsx+++ b/src/web/src/components/runtime-version-gate.tsx@@ -3,7 +3,7 @@import { useEffect, useRef, useState } from "react";import { useAgentContext } from "@/contexts/agent-context";import { getMinCliVersion, triggerRuntimeUpdate } from "@/lib/api";-import { semverGte } from "@alook/shared";+import { semverGte, resolveMode } from "@alook/shared";import {Dialog,DialogContent,@@ -15,11 +15,13 @@ import { Button } from "@/components/ui/button";import { Badge } from "@/components/ui/badge";import { AlertTriangle, RefreshCw, Terminal } from "lucide-react";import { toast } from "sonner";-import { isLocalMode } from "@/lib/utils";import type { AgentRuntime } from "@alook/shared";-const isLocal = isLocalMode();-const MANUAL_UPDATE_CMD = isLocal+const mode = resolveMode({+ nodeEnv: process.env.NODE_ENV,+ hostname: typeof window !== "undefined" ? window.location.hostname : undefined,+});+const MANUAL_UPDATE_CMD = mode === "app"? "npx @alook/app stop && npx @alook/app@latest update && npx @alook/app start": "npx @alook/cli@latest daemon stop && npx @alook/cli@latest daemon start";@@ -40,11 +42,12 @@ export function RuntimeVersionGate() {};}, []);+ if (mode === "dev") return null;if (!minVersion) return null;const outdatedRuntimes = runtimes.filter((rt) => {if (rt.status !== "online") return false;- const cliVersion = (rt.metadata as Record<string, unknown>)?.cli_version;+ const cliVersion = rt.metadata?.cli_version;if (typeof cliVersion !== "string" || !cliVersion) return true;return !semverGte(cliVersion, minVersion);});@@ -59,7 +62,7 @@ export function RuntimeVersionGate() {if (outdatedMachines.size === 0) return null;const handleUpdate = async (rt: AgentRuntime) => {- if (isLocal) {+ if (mode === "app") {setShowManualHint(true);return;}@@ -94,7 +97,7 @@ export function RuntimeVersionGate() {Runtime Update Required</DialogTitle><DialogDescription>- {isLocal+ {mode === "app"? `Your local Alook app is running an outdated version (minimum required: v${minVersion}). Please update to continue.`: `The following machine(s) are running an outdated CLI version (minimum required: v${minVersion}). Please update to continue.`}</DialogDescription>@@ -102,7 +105,7 @@ export function RuntimeVersionGate() {<div className="space-y-3 mt-2">{[...outdatedMachines.entries()].map(([daemonId, rt]) => {- const cliVersion = (rt.metadata as Record<string, unknown>)?.cli_version as string | undefined;+ const cliVersion = rt.metadata?.cli_version as string | undefined;const isUpdating = updating.has(rt.id);return (diff --git a/src/web/src/lib/auth.test.ts b/src/web/src/lib/auth.test.tsindex 78095ef1f..f3a16409b 100644--- a/src/web/src/lib/auth.test.ts+++ b/src/web/src/lib/auth.test.ts@@ -10,10 +10,14 @@ vi.mock("better-auth/plugins", () => ({vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));-vi.mock("@alook/shared", () => ({- createLogger: () => ({ info: vi.fn(), error: vi.fn() }),- DEV_EMAIL_WORKER_URL: "http://localhost:0",-}))+vi.mock("@alook/shared", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@alook/shared")>()+ return {+ ...actual,+ createLogger: () => ({ info: vi.fn(), error: vi.fn() }),+ DEV_EMAIL_WORKER_URL: "http://localhost:0",+ }+})vi.mock("./email-templates", () => ({getOtpSubject: () => "subject",diff --git a/src/web/src/lib/auth.ts b/src/web/src/lib/auth.tsindex 011169d22..1ae236642 100644--- a/src/web/src/lib/auth.ts+++ b/src/web/src/lib/auth.ts@@ -1,6 +1,6 @@import { betterAuth } from "better-auth"import { emailOTP } from "better-auth/plugins"-import { createLogger, DEV_EMAIL_WORKER_URL } from "@alook/shared"+import { createLogger, DEV_EMAIL_WORKER_URL, resolveMode } from "@alook/shared"import { getOtpSubject, renderOtpEmail } from "./email-templates"const log = createLogger({ service: "auth" })@@ -17,9 +17,8 @@ function parsePositiveInt(raw: string | undefined, fallback: number): number {}export function createAuth(env: Env) {- // env.NODE_ENV comes from wrangler [vars] (runtime), process.env.NODE_ENV- // is inlined at build time by Next.js — only reliable during `next dev`.- const isProd = (env.NODE_ENV ?? process.env.NODE_ENV) !== "development"+ const mode = resolveMode({ nodeEnv: env.NODE_ENV ?? process.env.NODE_ENV })+ const isProd = mode === "production"const otpMax = parsePositiveInt(env.AUTH_OTP_RATE_LIMIT_MAX, DEFAULT_OTP_RATE_LIMIT_MAX)const otpWindow = parsePositiveInt(env.AUTH_OTP_RATE_LIMIT_WINDOW_SEC,diff --git a/src/web/src/lib/npm.ts b/src/web/src/lib/npm.tsindex b9bfef488..f3ccb899c 100644--- a/src/web/src/lib/npm.ts+++ b/src/web/src/lib/npm.ts@@ -1,13 +1,11 @@import { getCloudflareContext } from "@opennextjs/cloudflare"+import { resolveMode } from "@alook/shared"-// In local mode (@alook/app), check @alook/app on npm.-// In cloud mode, check @alook/cli.-// Both packages are in the same monorepo and version-bumped together,-// so the daemon's reported cli_version will match either package.function getPackageName(): string {try {const { env } = getCloudflareContext()- if ((env as unknown as Record<string, unknown>).NODE_ENV === "development") return "@alook/app"+ const mode = resolveMode({ nodeEnv: (env as unknown as Record<string, unknown>).NODE_ENV as string | undefined })+ if (mode !== "production") return "@alook/app"} catch {}return "@alook/cli"}diff --git a/src/web/src/lib/use-user-ws.ts b/src/web/src/lib/use-user-ws.tsindex 322f23918..a327a42d4 100644--- a/src/web/src/lib/use-user-ws.ts+++ b/src/web/src/lib/use-user-ws.ts@@ -3,7 +3,7 @@ import { useEffect, useRef, useCallback } from "react"import type { WsMessage } from "@alook/shared"import { isLocalMode } from "@/lib/utils"-const isDev = isLocalMode()+const isLocal = isLocalMode()const WS_DO_PORT_DEFAULT = Number(process.env.NEXT_PUBLIC_WS_DO_PORT) || 8789const WS_RECONNECT_INIT = Number(process.env.NEXT_PUBLIC_WS_RECONNECT_DELAY_MS) || 1000const WS_RECONNECT_MAX = Number(process.env.NEXT_PUBLIC_WS_RECONNECT_MAX_DELAY_MS) || 30_000@@ -49,7 +49,7 @@ export function useUserWs(onMessage: (msg: WsMessage) => void) {return}- const url = isDev+ const url = isLocal? `ws://localhost:${wsPort}/?userId=${userId}`: `${location.origin.replace("http", "ws")}/api/ws/user?userId=${userId}`diff --git a/src/web/src/lib/use-ws.ts b/src/web/src/lib/use-ws.tsindex ae557f502..246f51516 100644--- a/src/web/src/lib/use-ws.ts+++ b/src/web/src/lib/use-ws.ts@@ -3,7 +3,7 @@ import { useEffect, useRef, useCallback } from "react"import type { WsMessage } from "@alook/shared"import { isLocalMode } from "@/lib/utils"-const isDev = isLocalMode()+const isLocal = isLocalMode()const WS_DO_PORT_DEFAULT = Number(process.env.NEXT_PUBLIC_WS_DO_PORT) || 8789const WS_RECONNECT_INIT = Number(process.env.NEXT_PUBLIC_WS_RECONNECT_DELAY_MS) || 1000const WS_RECONNECT_MAX = Number(process.env.NEXT_PUBLIC_WS_RECONNECT_MAX_DELAY_MS) || 30_000@@ -35,7 +35,7 @@ export function useAgentWs(agentId: string, onMessage: (msg: WsMessage) => void)return}- const url = isDev+ const url = isLocal? `ws://localhost:${wsPort}/?userId=${userId}&agentId=${agentId}`: `${location.origin.replace("http", "ws")}/api/ws?userId=${userId}&agentId=${agentId}`diff --git a/src/web/src/lib/utils.ts b/src/web/src/lib/utils.tsindex e2108375b..7535e96b3 100644--- a/src/web/src/lib/utils.ts+++ b/src/web/src/lib/utils.ts@@ -1,29 +1,26 @@import { clsx, type ClassValue } from "clsx"import { twMerge } from "tailwind-merge"+import { resolveMode, cliCommand, daemonCommand } from "@alook/shared"export function cn(...inputs: ClassValue[]) {return twMerge(clsx(inputs))}+function getMode() {+ return resolveMode({+ nodeEnv: process.env.NODE_ENV,+ hostname: typeof window !== "undefined" ? window.location.hostname : undefined,+ })+}+export function isLocalMode(): boolean {- if (typeof window !== "undefined"- && ["localhost", "127.0.0.1"].includes(window.location.hostname)) return true- return process.env.NODE_ENV === "development"+ return getMode() !== "production"}export function cliCmd(): string {- if (process.env.NODE_ENV === "development") return "pnpm dev:cli"- if (typeof window !== "undefined"- && ["localhost", "127.0.0.1"].includes(window.location.hostname)) {- return "npx @alook/app cli"- }- return "npx @alook/cli"+ return cliCommand(getMode())}-// --foreground is only needed in monorepo dev mode (pnpm dev:cli).-// In @alook/app mode, the daemon runs as a background process.export function daemonStartCmd(): string {- const base = `${cliCmd()} daemon start`- if (process.env.NODE_ENV === "development") return `${base} --foreground`- return base+ return daemonCommand(getMode())}