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(community): minimal agent:wake command + real local wake delivery
Gus9f7056a0bfab
diff --git a/package.json b/package.jsonindex 776632a69..01f16820f 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/web --filter=@alook/email-worker --filter=@alook/ws-do --filter=@alook/shared",+ "dev": "turbo run dev --filter=@alook/web --filter=@alook/email-worker --filter=@alook/ws-do --filter=@alook/wake-worker --filter=@alook/shared","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",@@ -19,6 +19,7 @@"build:desktop": "pnpm --filter @alook/desktop build","dev:email": "pnpm --filter @alook/email-worker dev","dev:ws": "pnpm --filter @alook/ws-do dev",+ "dev:wake-worker": "pnpm --filter @alook/wake-worker 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))\"",diff --git a/src/daemon/README.md b/src/daemon/README.mdindex 0e7c3e357..5c39121ec 100644--- a/src/daemon/README.md+++ b/src/daemon/README.md@@ -173,9 +173,14 @@ orchestration so it can run agents end-to-end:- **data plane** (`ServerApi`): what the `alook` CLI calls — `send` / `inboxPull` /`ack` / `read` / `listChannels`, addressed by path-style `ChannelRef`s.- **control plane** (`HostCommand` + `HostControlChannel`): server → host commands- (`agent:start` / `agent:deliver` / `agent:stop`); the server owns addressing.- `mockServer.ts` is a fully in-process `ServerApi`/`AdminApi`. The **control plane- runs over a real WebSocket** so local dev exercises the actual transport, not an+ (`agent:wake` / `agent:stop`; plus `bot:*` lifecycle frames). `agent:wake` carries a+ bodiless `UnreadNotice` (channel + latest seq, no message content) — the DAEMON+ (`AgentRouter`/`AgentProcessManager`), not the server, decides whether to spawn a+ process, notify an already-running one, or coalesce the notice for the next turn.+ `mockServer.ts` is a fully in-process `ServerApi`/`AdminApi` — data/admin/enrollment+ only, with **no** control-plane state (`runningAgents`, unacked deliveries, etc.) and+ no dispatch logic of its own; it never decides when to wake an agent. The **control+ plane runs over a real WebSocket** so local dev exercises the actual transport, not anin-process shortcut: `wsControlServer.ts` (server end) and `wsControlChannel.ts`(host end, injectable socket + exponential-backoff reconnect + heartbeat) carry the`HostCommand` frames over `ws://127.0.0.1`. `localControlChannel.ts` is kept only for@@ -183,12 +188,15 @@ orchestration so it can run agents end-to-end:real URL — nothing upstream changes.The e2e test `test/e2e/controlPlane.e2e.test.ts` wires `MockServer →(real ws)→-AgentRouter → AgentProcessManager` into a complete loop (provision a-server/agent/channel, post a message, the server dispatches `agent:start`/`agent:deliver`-over the socket, the agent replies back to the channel) — single process, no real-runtime, but the control frames cross an actual WebSocket. The `scripts/` dir runs-the same stack across SEPARATE processes — `mock-server` (the server) and `daemon`-(machine-key + URL only, no server ref) — with `smoke`/`test-server` as operators.+AgentRouter → AgentProcessManager` into a complete loop: provision a server/agent/+channel, post a message, then explicitly push an `agent:wake` `HostCommand` (standing+in for `src/web`'s wake producer + `src/wake-worker`'s consumer) over the socket — the+agent replies back to the channel. Single process, no real runtime, but the control+frames cross an actual WebSocket. The `scripts/` dir runs the same stack across+SEPARATE processes — `mock-server` (the server, which pushes `agent:wake` to a+channel's members right after `postMessage` so `smoke`/`test-server` still see replies)+and `daemon` (machine-key + URL only, no server ref) — with `smoke`/`test-server` as+operators.## Credentials (zero-trust isolation)diff --git a/src/daemon/eslint.config.ts b/src/daemon/eslint.config.tsindex 7386d4d02..f6e9d8cb6 100644--- a/src/daemon/eslint.config.ts+++ b/src/daemon/eslint.config.ts@@ -5,7 +5,7 @@ const eslintConfig = defineConfig([...tseslint.configs.recommended,globalIgnores(["dist/**", "coverage/**"]),{- files: ["src/drivers/**/*.ts", "src/cli/proxyServerApi.ts", "src/server/contract.ts"],+ files: ["src/drivers/**/*.ts", "src/cli/proxyServerApi.ts", "src/server/contract.ts", "src/server/wsControlServer.ts"],rules: {"@typescript-eslint/no-explicit-any": "off","@typescript-eslint/no-unused-vars": ["error", { argsIgnorePattern: "^_", varsIgnorePattern: "^_" }],diff --git a/src/daemon/scripts/mock-server.ts b/src/daemon/scripts/mock-server.tsindex 0dbda9709..c163f845e 100644--- a/src/daemon/scripts/mock-server.ts+++ b/src/daemon/scripts/mock-server.ts@@ -5,8 +5,11 @@* privileged surfaces; the daemon (separate process) can reach it ONLY over the* network, exactly as it would a real server:*- * - control plane (ws): server → daemon commands (agent:start/deliver/stop),+ * - control plane (ws): server → daemon commands (agent:wake/stop),* daemon → server reports (ready/session/ack).+ * This mock never decides WHEN to send agent:wake —+ * that's `src/web`/`src/wake-worker`'s job in+ * production. It only logs what the daemon reports.* Daemons must connect with `Authorization: Bearer* <machineKey>` — unauthenticated connections are* refused (`verifyMachineKey`).@@ -27,6 +30,8 @@import { WebSocketServer } from "ws";import type { IncomingMessage } from "http";import { MockServer, WsControlServer } from "../src/server/index";+import type { HostCommand } from "../src/server/contract";+import { makeRuntimeConfig } from "../src/runtimeConfig";import { startLocalBridge } from "./localBridge";const HTTP_PORT = Number(process.env.ALOOK_SERVER_PORT || 4517);@@ -35,21 +40,15 @@ const WS_PORT = Number(process.env.ALOOK_SERVER_WS_PORT || HTTP_PORT + 1);async function main() {const server = new MockServer();- // Wrap resetRunningAgents to log daemon ready reports- const originalReset = server.resetRunningAgents.bind(server);- server.resetRunningAgents = (agentIds: string[]) => {- console.log(`[mock-server] daemon ready — reported ${agentIds.length} running agent(s)${agentIds.length ? `: ${agentIds.join(", ")}` : ""}`);- originalReset(agentIds);- };-// Enroll THIS machine and surface its key for the daemon (script greps this line).const machineKey = server.enrollMachine();// Control plane: a ws server, authenticated by machine key. The factory adapts// `ws`'s (socket, request) connection event into our (socket, meta) shape,// pulling the upgrade request's Authorization header through for verification.+ // This mock never pushes `agent:wake` on its own — it's a pure transport ++ // data/admin/enroll fixture. Waking a daemon here is manual (see below).const wsServer = new WsControlServer({- server,port: WS_PORT,verifyMachineKey: (authHeader) => {const ok = server.verifyMachineKey(parseBearer(authHeader));@@ -60,9 +59,18 @@ async function main() {}return ok;},+ onReady: (ready) => {+ console.log(`[mock-server] daemon ready — reported ${ready.runningAgents.length} running agent(s)${ready.runningAgents.length ? `: ${ready.runningAgents.join(", ")}` : ""}`);+ },onAgentSession: (info) => {console.log(`[mock-server] agent session: ${info.agentId} → session=${info.sessionId}`);},+ onWakeAck: (info) => {+ console.log(`[mock-server] agent_wake_ack: ${info.agentId} launch=${info.launchId} status=${info.status}`);+ },+ onStoppedAck: (info) => {+ console.log(`[mock-server] agent_stopped_ack: ${info.agentId} status=${info.status}`);+ },webSocketServerFactory: (port) => {const wss = new WebSocketServer({ host: "127.0.0.1", port });wss.on("error", (err: NodeJS.ErrnoException) => {@@ -88,6 +96,28 @@ async function main() {});wsServer.start();+ // Stand-in for the real wake producer/consumer (src/web + src/wake-worker):+ // after a message is stored, explicitly push `agent:wake` to every member+ // of the channel so `pnpm run smoke` still sees replies. MockServer itself+ // makes no such decision — see its class doc comment.+ const originalPostMessage = server.postMessage.bind(server);+ server.postMessage = async (req) => {+ const result = await originalPostMessage(req);+ for (const agentId of server.membersOf(req.channel)) {+ const config = server.getAgentConfig(agentId) ?? makeRuntimeConfig({ runtime: "mock" });+ const cmd: HostCommand = {+ type: "agent:wake",+ agentId,+ config,+ launchId: `launch_${agentId}_${result.message.seq}`,+ unreadNotice: { kind: "unread_notice", channel: req.channel, latestSeq: Number(result.message.seq.replace("#", "")) },+ };+ const sent = wsServer.pushCommand(cmd);+ console.log(`[mock-server] postMessage → agent:wake ${agentId} (${sent ? "sent" : "no daemon connected"})`);+ }+ return result;+ };+// HTTP planes: data (/api), admin (/admin), enroll (/enroll). Same process as// the server state — this is the SERVER side; the daemon connects from outside.const bridge = await startLocalBridge({ admin: server, api: server, enrollment: server }, HTTP_PORT);diff --git a/src/daemon/src/daemon/createDaemon.ts b/src/daemon/src/daemon/createDaemon.tsindex 7389eec24..36fc39f4e 100644--- a/src/daemon/src/daemon/createDaemon.ts+++ b/src/daemon/src/daemon/createDaemon.ts@@ -6,7 +6,7 @@* whole capability surface is three network faces (all toward the server* it was pointed at):*- * 1. control plane (ws): receive agent:start/deliver/stop, report ready/+ * 1. control plane (ws): receive agent:wake/stop, report ready/* session/ack. Connects with `Authorization: Bearer <machineKey>`* (`cmk_`). This is the only path — no URL-token fallback exists.* 2. enroll plane (http): POST /api/community/daemon/enroll-agent@@ -30,7 +30,7 @@ import { createTimelineRecorder } from "../timeline/index.js";import { resolveAlookCliPathWithFallback } from "../discovery.js";import type { Driver, LaunchContext } from "../types.js";import type { RuntimeConfig } from "../runtimeConfig.js";-import type { Message, HostCommand } from "../server/contract.js";+import type { UnreadNotice, HostCommand } from "../server/contract.js";// Cold-start warmup backoff schedule (ms).const WARMUP_BACKOFF_MS = [250, 500, 1000, 2000, 4000] as const;@@ -58,7 +58,7 @@ export interface CreateDaemonOptions {}>;/*** Per-agent runtime driver. `runtimeConfig` (server-pushed on- * `agent:start`) is passed so callers can dispatch on the actual runtime+ * `agent:wake`) is passed so callers can dispatch on the actual runtime* the agent asked for; tests may omit it and hand back a stub driver.*/driverFor: (agentId: string, runtimeConfig?: RuntimeConfig) => Driver;@@ -159,8 +159,8 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDaattempt++;}}- // Ceiling exhausted — resolve empty. A subsequent `agent:start` /- // `agent:deliver` frame will trigger a deferred retry via enrollAgent.+ // Ceiling exhausted — resolve empty. A subsequent `agent:wake` frame+ // will trigger a deferred retry via enrollAgent.}const enrollAgent = async (agentId: string): Promise<string> => {@@ -314,8 +314,8 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa}await enrollAgent(agentId);},- transformWakeText: (message: Message) =>- `You have a new message in channel ${message.channel}.`,+ formatUnreadNoticeText: (notice: UnreadNotice) =>+ `You have unread messages in channel ${notice.channel}.`,});// Register the bot-cache pre-hook. `onCommand` supports multiple listenersdiff --git a/src/daemon/src/discovery.ts b/src/daemon/src/discovery.tsindex fac836d55..4c0e79e65 100644--- a/src/daemon/src/discovery.ts+++ b/src/daemon/src/discovery.ts@@ -96,7 +96,6 @@ export interface RuntimeInfo {/*** Probe all registered drivers and return which runtimes are available.- * Mirrors raft's `detectRuntimes()` — called ONCE at daemon startup to report* capabilities to the server. Runtime health after startup is mutated live* by `AgentRouter.markRuntimeUnhealthy` / `markRuntimeHealthy` — see* plans/community-machine-presence-fix.md.diff --git a/src/daemon/src/drivers/spawnEnv.test.ts b/src/daemon/src/drivers/spawnEnv.test.tsindex e9f9b6d01..b6fd76b38 100644--- a/src/daemon/src/drivers/spawnEnv.test.ts+++ b/src/daemon/src/drivers/spawnEnv.test.ts@@ -82,14 +82,14 @@ describe("platformEnv", () => {});it("swaps the prefix", () => {- const v = platformEnv("RAFT", {+ const v = platformEnv("MOCK_CLI", {stateHome: "/h",agentId: "a",- cliName: "raft",+ cliName: "mock-cli",capabilities: [],});- expect(v.RAFT_ID).toBe("a");- expect(v.RAFT_LAUNCH_ID).toBeUndefined(); // omitted optional → undefined (skipped on merge)+ expect(v.MOCK_CLI_ID).toBe("a");+ expect(v.MOCK_CLI_LAUNCH_ID).toBeUndefined(); // omitted optional → undefined (skipped on merge)});});diff --git a/src/daemon/src/drivers/systemPrompt.test.ts b/src/daemon/src/drivers/systemPrompt.test.tsindex 64ed0508a..c0dbccc67 100644--- a/src/daemon/src/drivers/systemPrompt.test.ts+++ b/src/daemon/src/drivers/systemPrompt.test.ts@@ -43,8 +43,8 @@ describe("buildCliSystemPrompt — host-neutral slim default", () => {});it("uses the configured cli name everywhere", () => {- const p = buildCliSystemPrompt(baseConfig, { cli: "raft", messageNotificationStyle: "direct" });- expect(p).toContain("`raft`");+ const p = buildCliSystemPrompt(baseConfig, { cli: "mock-cli", messageNotificationStyle: "direct" });+ expect(p).toContain("`mock-cli`");expect(p).not.toContain("`alook`");});});@@ -70,7 +70,7 @@ describe("buildCliSystemPrompt — runtime-driven notification section", () => {describe("buildCliSystemPrompt — host injection points", () => {it("appends the host communicationGuide verbatim", () => {- const guide = "## Communication\nUse `raft message send` with the [target=…] header.";+ const guide = "## Communication\nUse `mock-cli message send` with the [target=…] header.";const p = buildCliSystemPrompt(baseConfig, { communicationGuide: guide });expect(p).toContain(guide);});diff --git a/src/daemon/src/manager/agentProfile.test.ts b/src/daemon/src/manager/agentProfile.test.tsindex 00e583b31..a548dd935 100644--- a/src/daemon/src/manager/agentProfile.test.ts+++ b/src/daemon/src/manager/agentProfile.test.ts@@ -5,7 +5,7 @@ import { makeRuntimeConfig } from "../runtimeConfig";/*** The daemon does not invent an agent's identity: when the server downlinks a- * RuntimeConfig (via agent:start → manager.register), its `instruction` becomes+ * RuntimeConfig (via agent:wake → manager.register), its `instruction` becomes* the description on the LaunchConfig. The driver's `buildSystemPrompt(config)`* is called to assemble the full standing prompt — the daemon never passes raw* instruction text as the prompt.diff --git a/src/daemon/src/manager/agentRouter.test.ts b/src/daemon/src/manager/agentRouter.test.tsindex 89545bb33..25728c753 100644--- a/src/daemon/src/manager/agentRouter.test.ts+++ b/src/daemon/src/manager/agentRouter.test.ts@@ -1,30 +1,29 @@import { describe, it, expect } from "vitest";import { AgentRouter, UnknownRuntimeError } from "./agentRouter";import type { AgentProcessManager } from "./managerRuntime";-import type { HostControlChannel, HostCommand, Message, SessionErrorFrame } from "../server/contract";--function msg(seq: string, text: string): Message {- return { seq, channel: "/demo/general", sender: "@gustavo", content: { text }, time: "t" };-}+import type { HostControlChannel, HostCommand, SessionErrorFrame } from "../server/contract";/** Fake manager recording deliver/register; enough for router behavior tests. */function fakeManager() {- const delivers: Array<{ agentId: string; text: string }> = [];+ const delivers: Array<{ agentId: string; text: string; seq?: number }> = [];+ const registers: Array<{ agentId: string; sessionId?: string; launchId?: string }> = [];const mgr = {- register() {},- deliver(agentId: string, m: { seq: number; text: string }) {- delivers.push({ agentId, text: m.text });+ register(agentId: string, launch?: { sessionId?: string; launchId?: string }) {+ registers.push({ agentId, sessionId: launch?.sessionId, launchId: launch?.launchId });+ },+ deliver(agentId: string, m: { seq?: number; text: string }) {+ delivers.push({ agentId, text: m.text, seq: m.seq });},stop() {},liveSessionReports: () => [],} as unknown as AgentProcessManager;- return { mgr, delivers };+ return { mgr, delivers, registers };}/** Fake channel capturing acks + the command handler the router registers. */function fakeChannel() {let handler: ((c: HostCommand) => void | Promise<void>) | null = null;- const acks: string[] = [];+ const wakeAcks: Array<{ agentId: string; launchId: string; status: string }> = [];const readys: Array<Parameters<HostControlChannel["reportReady"]>[0]> = [];const sessionErrors: SessionErrorFrame[] = [];const ch: HostControlChannel = {@@ -35,50 +34,77 @@ function fakeChannel() {readys.push(ready);},async reportAgentSession() {},- async reportDeliverAck(info) {- acks.push(info.deliveryId);+ async reportWakeAck(info) {+ wakeAcks.push({ agentId: info.agentId, launchId: info.launchId, status: info.status });},async reportSessionError(frame) {sessionErrors.push(frame);},onResync() {},};- return { ch, acks, readys, sessionErrors, fire: (c: HostCommand) => handler?.(c) };+ return { ch, wakeAcks, readys, sessionErrors, fire: (c: HostCommand) => handler?.(c) };}-describe("AgentRouter — at-least-once dedup", () => {- it("acks every delivery, but only wakes the manager once per deliveryId", async () => {- const { mgr, delivers } = fakeManager();- const { ch, acks, fire } = fakeChannel();+describe("AgentRouter — agent:wake", () => {+ it("registers the runtime config, delivers the notice text, and acks the wake", async () => {+ const { mgr, delivers, registers } = fakeManager();+ const { ch, wakeAcks, fire } = fakeChannel();const router = new AgentRouter({ manager: mgr, channel: ch, runtimeReport: [{ id: "mock" }] });await router.start();- const deliver: HostCommand = { type: "agent:deliver", agentId: "a1", message: msg("#1", "hello"), deliveryId: "dlv_1" };- await fire(deliver);- await fire(deliver); // redelivery of the SAME id (e.g. after a reconnect)+ await fire({+ type: "agent:wake",+ agentId: "a1",+ config: { version: 1, runtime: "mock", model: { kind: "default" }, mode: { kind: "default" } },+ launchId: "l1",+ unreadNotice: { kind: "unread_notice", channel: "/demo/general", latestSeq: 7 },+ });- // Manager woken exactly once; both deliveries acked (so the server retires it).- expect(delivers.length).toBe(1);- expect(delivers[0]).toEqual({ agentId: "a1", text: "hello" });- expect(acks).toEqual(["dlv_1", "dlv_1"]);+ expect(registers).toEqual([{ agentId: "a1", sessionId: undefined, launchId: "l1" }]);+ expect(delivers).toEqual([{ agentId: "a1", text: "You have unread messages in channel /demo/general.", seq: 7 }]);+ expect(wakeAcks).toEqual([{ agentId: "a1", launchId: "l1", status: "ok" }]);});- it("agent:start wake delivers + acks its deliveryId", async () => {+ it("uses a custom formatUnreadNoticeText when provided", async () => {const { mgr, delivers } = fakeManager();- const { ch, acks, fire } = fakeChannel();- const router = new AgentRouter({ manager: mgr, channel: ch, runtimeReport: [{ id: "mock" }] });+ const { ch, fire } = fakeChannel();+ const router = new AgentRouter({+ manager: mgr,+ channel: ch,+ runtimeReport: [{ id: "mock" }],+ formatUnreadNoticeText: (notice) => `custom: ${notice.channel}#${notice.latestSeq}`,+ });await router.start();await fire({- type: "agent:start",+ type: "agent:wake",agentId: "a1",config: { version: 1, runtime: "mock", model: { kind: "default" }, mode: { kind: "default" } },- wakeMessage: msg("#1", "wake"),- deliveryId: "dlv_w",launchId: "l1",+ unreadNotice: { kind: "unread_notice", channel: "/demo/general", latestSeq: 7 },});- expect(delivers).toEqual([{ agentId: "a1", text: "wake" }]);- expect(acks).toEqual(["dlv_w"]);++ expect(delivers).toEqual([{ agentId: "a1", text: "custom: /demo/general#7", seq: 7 }]);+ });++ it("repeated agent:wake commands for the same agent each register + deliver again (no dedup — no deliveryId anymore)", async () => {+ const { mgr, delivers } = fakeManager();+ const { ch, wakeAcks, fire } = fakeChannel();+ const router = new AgentRouter({ manager: mgr, channel: ch, runtimeReport: [{ id: "mock" }] });+ await router.start();++ const wake: HostCommand = {+ type: "agent:wake",+ agentId: "a1",+ config: { version: 1, runtime: "mock", model: { kind: "default" }, mode: { kind: "default" } },+ launchId: "l1",+ unreadNotice: { kind: "unread_notice", channel: "/demo/general", latestSeq: 7 },+ };+ await fire(wake);+ await fire(wake);++ expect(delivers.length).toBe(2);+ expect(wakeAcks.length).toBe(2);});});@@ -100,10 +126,11 @@ describe("AgentRouter — unknown runtime → session.error", () => {await router.start();await fire({- type: "agent:start",+ type: "agent:wake",agentId: "a1",config: { version: 1, runtime: "gemini", model: { kind: "default" }, mode: { kind: "default" } },launchId: "l1",+ unreadNotice: { kind: "unread_notice", channel: "/demo/general", latestSeq: 1 },});expect(sessionErrors.length).toBe(1);@@ -276,7 +303,6 @@ describe("AgentRouter — runtime health map", () => {onCommand() {},async reportReady() {},async reportAgentSession() {},- async reportDeliverAck() {},};const router = new AgentRouter({manager: mgr,diff --git a/src/daemon/src/manager/agentRouter.ts b/src/daemon/src/manager/agentRouter.tsindex d70da40ad..956035041 100644--- a/src/daemon/src/manager/agentRouter.ts+++ b/src/daemon/src/manager/agentRouter.ts@@ -3,20 +3,22 @@** The server pushes `HostCommand`s down a `HostControlChannel`; the router turns* them into `AgentProcessManager` calls. It is deliberately thin and does NO- * addressing — every `agent:deliver` already names its recipient `agentId`- * (the server decided who receives). The host just executes.+ * addressing — every command already names its recipient `agentId` (the+ * server decided who receives). The host just executes.*- * agent:start → register + deliver wakeMessage (manager spawns single-flight)- * agent:deliver → manager.deliver(agentId, message)- * agent:stop → manager.stop(agentId)+ * agent:wake → register (server-pushed RuntimeConfig) + deliver the+ * bodiless unread-notice prompt. The MANAGER (not this+ * router, and not the server) decides whether that means+ * spawning a fresh process, notifying an already-running one,+ * or coalescing the notice for the next turn — see+ * `AgentProcessManager`/`managerPolicy`.+ * agent:stop → manager.stop(agentId)*- * It also reports readiness + session ids back up the channel, ACKs at-least-once- * deliveries (dedup by deliveryId so an agent never sees a duplicate wake), and- * supplies a resync snapshot so the server recovers this host's state after a- * dropped control connection.+ * It also reports readiness + session ids back up the channel, ACKs+ * `agent:wake`/`agent:stop` outcomes, and supplies a resync snapshot so the+ * server recovers this host's state after a dropped control connection.*/-import type { HostCommand, HostControlChannel, HostReady, HostReadyRuntime, Message, AgentSessionReport, SessionErrorFrame } from "../server/contract.js";-import { parseSeq } from "../server/contract.js";+import type { HostCommand, HostControlChannel, HostReady, HostReadyRuntime, UnreadNotice, AgentSessionReport, SessionErrorFrame } from "../server/contract.js";import type { AgentProcessManager } from "./managerRuntime.js";/**@@ -83,11 +85,13 @@ export interface AgentRouterOpts {*/onBeforeAgent?: (agentId: string) => Promise<void>;/**- * Transform the raw message text into the prompt the agent actually sees.- * The default passes text through unchanged. A real deployment replaces this- * with a notify-style wake ("you have N messages, pull inbox").+ * Format the bodiless `UnreadNotice` into the prompt text the agent+ * actually sees. The default is a fixed "you have unread messages in+ * channel X" line. Deliberately does NOT include the inbox-pull+ * instruction — that's `wakePromptFooter` on `ManagerRuntimeOpts`, appended+ * once after coalescing/dedup so a burst of notices doesn't repeat it.*/- transformWakeText?: (message: Message) => string;+ formatUnreadNoticeText?: (notice: UnreadNotice) => string;/*** Coalescer scheduler for on-demand ready-frame resends. Defaults to* `queueMicrotask` so a burst of health mutations in the same tick collapse@@ -96,10 +100,12 @@ export interface AgentRouterOpts {scheduleReadyResend?: (fn: () => void) => void;}+function defaultFormatUnreadNoticeText(notice: UnreadNotice): string {+ return `You have unread messages in channel ${notice.channel}.`;+}+export class AgentRouter {private readonly running = new Set<string>();- /** Delivery ids already accepted — dedups redelivery so no duplicate wake. */- private readonly seenDeliveries = new Set<string>();/*** Mutable per-runtime health map. Seeded from the startup snapshot passed* on construction; mutated live by `markRuntimeUnhealthy` / `markRuntimeHealthy`@@ -236,7 +242,7 @@ export class AgentRouter {private async onCommand(cmd: HostCommand): Promise<void> {switch (cmd.type) {- case "agent:start":+ case "agent:wake":try {await this.opts.onBeforeAgent?.(cmd.agentId);this.opts.manager.register(cmd.agentId, {@@ -245,8 +251,11 @@ export class AgentRouter {launchId: cmd.launchId,});this.running.add(cmd.agentId);- if (cmd.wakeMessage) this.deliver(cmd.agentId, cmd.wakeMessage, cmd.deliveryId);- await this.opts.channel.reportStartedAck?.({+ const text = (this.opts.formatUnreadNoticeText ?? defaultFormatUnreadNoticeText)(cmd.unreadNotice);+ // The manager (not this router) decides spawn vs. in-process notify+ // vs. coalesce — see managerPolicy's `onWake`.+ this.opts.manager.deliver(cmd.agentId, { seq: cmd.unreadNotice.latestSeq, text });+ await this.opts.channel.reportWakeAck?.({agentId: cmd.agentId,launchId: cmd.launchId,status: "ok",@@ -266,7 +275,7 @@ export class AgentRouter {},};await this.opts.channel.reportSessionError?.(frame);- await this.opts.channel.reportStartedAck?.({+ await this.opts.channel.reportWakeAck?.({agentId: cmd.agentId,launchId: cmd.launchId,status: "error",@@ -279,7 +288,7 @@ export class AgentRouter {}// Any other throw — including onBeforeAgent throws that used to be// swallowed silently — surfaces as a structured error ack.- await this.opts.channel.reportStartedAck?.({+ await this.opts.channel.reportWakeAck?.({agentId: cmd.agentId,launchId: cmd.launchId,status: "error",@@ -291,23 +300,6 @@ export class AgentRouter {return;}break;- case "agent:deliver":- try {- await this.opts.onBeforeAgent?.(cmd.agentId);- this.running.add(cmd.agentId);- this.deliver(cmd.agentId, cmd.message, cmd.deliveryId);- } catch (err) {- await this.opts.channel.reportDeliverAck({- agentId: cmd.agentId,- deliveryId: cmd.deliveryId,- status: "error",- error: {- code: classifyErrorCode(err),- message: err instanceof Error ? err.message : String(err),- },- });- }- break;case "agent:stop":try {this.running.delete(cmd.agentId);@@ -335,22 +327,4 @@ export class AgentRouter {break;}}-- /**- * Hand an addressed message to the manager. At-least-once: a redelivered id is- * deduped (not re-woken) but STILL acked, so the server can retire it.- */- private deliver(agentId: string, message: Message, deliveryId?: string): void {- if (deliveryId !== undefined && this.seenDeliveries.has(deliveryId)) {- void this.opts.channel.reportDeliverAck({ agentId, deliveryId });- return;- }- this.opts.manager.register(agentId);- const text = this.opts.transformWakeText ? this.opts.transformWakeText(message) : message.content.text;- this.opts.manager.deliver(agentId, { seq: parseSeq(message.seq), text });- if (deliveryId !== undefined) {- this.seenDeliveries.add(deliveryId);- void this.opts.channel.reportDeliverAck({ agentId, deliveryId });- }- }}diff --git a/src/daemon/src/manager/managerRuntime.ts b/src/daemon/src/manager/managerRuntime.tsindex f84d1e1f3..b1eee69ab 100644--- a/src/daemon/src/manager/managerRuntime.ts+++ b/src/daemon/src/manager/managerRuntime.ts@@ -130,11 +130,11 @@ export interface TimelineRecorder {export class AgentProcessManager {private state: ManagerState;private readonly sessions = new Map<string, ManagedSession>();- /** agentId → server-pushed RuntimeConfig (from agent:start). */+ /** agentId → server-pushed RuntimeConfig (from agent:wake). */private readonly runtimeConfigs = new Map<string, RuntimeConfig>();- /** agentId → resume sessionId pushed by the server (from agent:start). */+ /** agentId → resume sessionId pushed by the server (from agent:wake). */private readonly resumeSessions = new Map<string, string>();- /** agentId → launchId from the latest agent:start (for session correlation). */+ /** agentId → launchId from the latest agent:wake (for session correlation). */private readonly launchIds = new Map<string, string>();/** agentId → live runtime sessionId (learned from session_init), for resync. */private readonly liveSessions = new Map<string, string>();@@ -179,7 +179,7 @@ export class AgentProcessManager {/*** Register an agent (idempotent) so it can receive messages. `launch` carries* the server-pushed RuntimeConfig (and optional resume sessionId) from- * `agent:start`; it's remembered and merged into the LaunchContext at spawn.+ * `agent:wake`; it's remembered and merged into the LaunchContext at spawn.*/register(agentId: string, launch?: { runtimeConfig?: RuntimeConfig; sessionId?: string; launchId?: string }): void {if (launch?.runtimeConfig) this.runtimeConfigs.set(agentId, launch.runtimeConfig);@@ -275,7 +275,7 @@ export class AgentProcessManager {private doSpawn(agentId: string, prompt: string, resumeSessionId: string | null): void {const driver = this.opts.driverFor(agentId, this.runtimeConfigs.get(agentId));const base = this.opts.baseContextFor(agentId);- // The server-pushed RuntimeConfig (from agent:start) takes precedence over+ // The server-pushed RuntimeConfig (from agent:wake) takes precedence over// any baseContextFor default; the resume sessionId likewise prefers the// manager's runtime-tracked id, then the server-pushed one, then the base.const runtimeConfig = this.runtimeConfigs.get(agentId) ?? base.config?.runtimeConfig;diff --git a/src/daemon/src/runtimeConfig.ts b/src/daemon/src/runtimeConfig.tsindex 0de510dc1..f264aaef3 100644--- a/src/daemon/src/runtimeConfig.ts+++ b/src/daemon/src/runtimeConfig.ts@@ -2,11 +2,12 @@* RuntimeConfig — the structured, versioned agent runtime configuration.** The canonical `RuntimeConfig`/`makeRuntimeConfig` now live in- * `@alook/shared/runtime-config` (lifted there so the `src/web` wake producer,- * which cannot depend on this CLI/daemon package, can construct a `config` for- * `agent:start` — see `plans/community-agent-cli-bridge.md` §1). Re-exported- * here so existing daemon call sites keep importing from `./runtimeConfig.js`- * unchanged.+ * `@alook/shared/runtime-config` (lifted there so the `src/web` wake producer+ * and `src/wake-worker` consumer, neither of which can depend on this+ * CLI/daemon package, can construct the `config` field of an `agent:wake`+ * `HostCommand` — see `plans/community-agent-cli-bridge.md` §1 and+ * `plans/minimal-wake-queue-unread-notice.md`). Re-exported here so existing+ * daemon call sites keep importing from `./runtimeConfig.js` unchanged.** This file keeps `resolveLaunchFields`/`ResolvedLaunchFields` — daemon-only,* host-side resolution of a `RuntimeConfig` into flat launch fields (CLI args +diff --git a/src/daemon/src/server/contract.ts b/src/daemon/src/server/contract.tsindex 433ad860d..d5b45561a 100644--- a/src/daemon/src/server/contract.ts+++ b/src/daemon/src/server/contract.ts@@ -41,6 +41,7 @@ export type {ResolveRequest,ListChannelsRequest,ServerApi,+ UnreadNotice,HostCommand,HostReadyRuntime,HostReady,diff --git a/src/daemon/src/server/deliveryAck.test.ts b/src/daemon/src/server/deliveryAck.test.tsdeleted file mode 100644index 1443c83bc..000000000--- a/src/daemon/src/server/deliveryAck.test.ts+++ /dev/null@@ -1,65 +0,0 @@-import { describe, it, expect } from "vitest";-import { MockServer } from "./mockServer";-import type { HostCommand } from "./contract";--/**- * At-least-once control-plane delivery: the server tags each dispatch with a- * deliveryId, keeps it "unacked" until the host acks, and redelivers the SAME id- * on reconnect. These tests drive the real MockServer command sink directly.- */-async function setup() {- const s = new MockServer();- const { user } = await s.createUser({ name: "u" });- const { agent } = await s.createAgent({ userId: user.id, name: "cindy", runtime: "mock" });- const { server } = await s.createServer({ name: "demo" });- await s.addAgentToServer({ agentId: agent.id, server: server.id });- const { channel } = await s.createChannel({ server: server.id, name: "general" });- const ref = `/${server.id}/${channel.id}`;- return { s, agentId: agent.id, ref };-}--describe("control-plane at-least-once delivery", () => {- it("tags a dispatch with a deliveryId and retains it until acked", async () => {- const { s, ref } = await setup();- const cmds: HostCommand[] = [];- s.attachHost((c) => cmds.push(c));-- s.post({ channel: ref, sender: "@gustavo", text: "hi" });- expect(cmds.length).toBe(1);- const cmd = cmds[0];- // The recipient isn't running yet → it's an agent:start carrying the wake.- expect(cmd.type).toBe("agent:start");- const deliveryId = (cmd as Extract<HostCommand, { type: "agent:start" }>).deliveryId!;- expect(deliveryId).toMatch(/^dlv_/);-- // Before ack: a reconnect redelivers the same id.- const redelivered: HostCommand[] = [];- s.attachHost((c) => redelivered.push(c));- s.redeliverUnacked();- expect(redelivered.length).toBe(1);- expect((redelivered[0] as any).deliveryId).toBe(deliveryId);-- // After ack: nothing is redelivered.- s.ackDelivery(deliveryId);- const after: HostCommand[] = [];- s.attachHost((c) => after.push(c));- s.redeliverUnacked();- expect(after.length).toBe(0);- });-- it("resetRunningAgents replaces (not merges) the running set", async () => {- const { s, agentId, ref } = await setup();- const cmds: HostCommand[] = [];- s.attachHost((c) => cmds.push(c));-- // Host says a1 is running → a post delivers (not starts).- s.resetRunningAgents([agentId]);- s.post({ channel: ref, sender: "@gustavo", text: "one" });- expect(cmds.at(-1)!.type).toBe("agent:deliver");-- // Host reconnects reporting NO running agents → next post must start again.- s.resetRunningAgents([]);- s.post({ channel: ref, sender: "@gustavo", text: "two" });- expect(cmds.at(-1)!.type).toBe("agent:start");- });-});diff --git a/src/daemon/src/server/mockServer.ts b/src/daemon/src/server/mockServer.tsindex 6f77ce08c..05893710f 100644--- a/src/daemon/src/server/mockServer.ts+++ b/src/daemon/src/server/mockServer.ts@@ -9,6 +9,15 @@* Addressing is by `ChannelRef` path strings (`/server/channel`, `/.dm/peer`);* messages are located by channel + seq. The agent-facing `Message` is flat:* `{ seq:"#N", channel, sender:"@handle", content:{text}, time }`.+ *+ * Data/admin/enrollment-only (minimal-wake-queue-unread-notice plan §6) —+ * this class deliberately carries NO control-plane state or dispatch logic.+ * The server never decides whether/when a daemon should wake an agent; in+ * production that decision starts with `src/web`'s wake producer and is+ * finished by the DAEMON (`AgentRouter`/`AgentProcessManager`), not here.+ * Tests that need to exercise `agent:wake` push a `HostCommand` directly+ * through `WsControlServer.pushCommand` / a `LocalControlChannel`, they do+ * NOT get one synthesized by `postMessage`/`post`.*/import type {ServerApi,@@ -36,7 +45,6 @@ import type {User,ChannelKind,UserId,- HostCommand,EnrollmentApi,} from "./contract.js";import { DM_SERVER, parseRef, formatSeq } from "./contract.js";@@ -84,7 +92,12 @@ export class MockServer implements ServerApi, AdminApi, EnrollmentApi {private readonly membership = new Map<string, Set<string>>();/** agentId → handle ("@name") for sender stamping. */private readonly agentHandles = new Map<string, string>();- /** agentId → RuntimeConfig — what `agent:start` will carry. */+ /**+ * agentId → RuntimeConfig, as set by `createAgent`. Admin-surface storage+ * only — a test harness that wants to push an `agent:wake` HostCommand for+ * this agent reads it back via `getAgentConfig` so the wake's `config`+ * matches what "the server" told the admin API it created.+ */private readonly agentConfigs = new Map<string, RuntimeConfig>();/** channelRef → ordered messages. */private readonly log = new Map<ChannelRef, StoredMessage[]>();@@ -94,14 +107,6 @@ export class MockServer implements ServerApi, AdminApi, EnrollmentApi {private readonly readMarks = new Map<string, Map<ChannelRef, Seq>>();private seed?: MockServerSeed;- /** Control-plane sink: a connected host registers here to receive commands. */- private commandSink: ((cmd: HostCommand) => void | Promise<void>) | null = null;- /** Agents the host has reported as running (so we deliver vs. start). */- private readonly runningAgents = new Set<string>();- private launchCounter = 0;- private deliveryCounter = 0;- /** deliveryId → unacked delivery (for at-least-once redelivery on reconnect). */- private readonly unackedDeliveries = new Map<string, HostCommand>();/** Valid machine keys this server issued on enrollment (tier-1). */private readonly machineKeys = new Set<string>();/** runnerKey → agentId, so a swapped-in runner key is traceable (tier-2). */@@ -147,82 +152,33 @@ export class MockServer implements ServerApi, AdminApi, EnrollmentApi {return { runnerKey };}- /* ----- control plane (server → host) ----- */-- /** A host attaches its command handler; returns the current running set tracker. */- attachHost(sink: (cmd: HostCommand) => void | Promise<void>): void {- this.commandSink = sink;- }- /** Host reports an agent started (so subsequent messages `agent:deliver`). */- markRunning(agentId: string): void {- this.runningAgents.add(agentId);- }- markStopped(agentId: string): void {- this.runningAgents.delete(agentId);- }- /**- * Replace the running set wholesale with what a (re)connecting host reports.- * Idempotent refresh — a host that crashed and came back with fewer agents- * must not leave stale "running" entries that suppress agent:start.- */- resetRunningAgents(agentIds: string[]): void {- this.runningAgents.clear();- for (const id of agentIds) this.runningAgents.add(id);- }-- /** Compute recipients for a message and push control commands to the host. */- private dispatchToRecipients(stored: StoredMessage): void {- if (!this.commandSink) return;- const message = toAgentMessage(stored);- for (const agentId of this.recipientsFor(stored)) {- this.deliveryCounter += 1;- const deliveryId = `dlv_${this.deliveryCounter}`;- let cmd: HostCommand;- if (this.runningAgents.has(agentId)) {- cmd = { type: "agent:deliver", agentId, message, deliveryId };- } else {- // Not running → start it (with the triggering message), then it's running.- const config = this.agentConfigs.get(agentId) ?? makeRuntimeConfig({ runtime: "mock" });- this.launchCounter += 1;- cmd = { type: "agent:start", agentId, config, wakeMessage: message, deliveryId, launchId: `launch_${this.launchCounter}` };- this.runningAgents.add(agentId);- }- // Track for at-least-once until the host acks; then push to the host.- this.unackedDeliveries.set(deliveryId, cmd);- this.commandSink(cmd);- }- }-- /** Host acked a delivery — retire it so it isn't redelivered. */- ackDelivery(deliveryId: string): void {- this.unackedDeliveries.delete(deliveryId);- }-/**- * Re-push every still-unacked delivery to the (reconnected) host. The host- * dedups by deliveryId, so redelivering an already-processed message is safe.+ * The RuntimeConfig `createAgent` recorded for this agent, if any. Purely a+ * convenience for test harnesses assembling an `agent:wake` `HostCommand`+ * to push through a control-plane fixture — MockServer itself never reads+ * this to make a dispatch decision.*/- redeliverUnacked(): void {- if (!this.commandSink) return;- for (const cmd of this.unackedDeliveries.values()) this.commandSink(cmd);+ getAgentConfig(agentId: AgentId): RuntimeConfig | undefined {+ return this.agentConfigs.get(agentId);}/**- * SERVER-side addressing: who should receive this message? Agents that are- * members of the channel's server (for a real channel) or the DM peer (for a- * DM), excluding the sender. The host never does this — it's server policy.+ * Agents that can receive messages posted to `channel`: server members for+ * a `/server/channel` ref, or the resolved peer for a `/.dm/<handle>` ref.+ * Pure data query, same class as `listServers`/`listChannels` — NOT a+ * dispatch decision. A caller standing in for the real wake producer (e.g.+ * the `mock-server` script, or a test) uses this to decide who to push an+ * `agent:wake` `HostCommand` for after `postMessage`.*/- private recipientsFor(stored: StoredMessage): string[] {- const p = parseRef(stored.channel);+ membersOf(channelArg: ChannelRef): AgentId[] {+ const p = parseRef(this.canon(channelArg));if (p.server === DM_SERVER) {- // DM: deliver to the peer agent if it's a known agent (by handle).- const peerAgent = [...this.agentHandles].find(([, h]) => h === `@${p.channel}`)?.[0];- return peerAgent && `@${this.agentHandles.get(peerAgent)}` !== stored.senderHandle ? [peerAgent] : peerAgent ? [peerAgent] : [];+ const handle = p.channel.startsWith("@") ? p.channel : `@${p.channel}`;+ const peer = [...this.agentHandles].find(([, h]) => h === handle)?.[0];+ return peer ? [peer] : [];}- const serverId = this.resolveServerId(p.server);- if (!serverId) return [];- const members = this.membership.get(serverId) ?? new Set();- return [...members].filter((agentId) => this.agentHandles.get(agentId) !== stored.senderHandle);+ const serverId = this.resolveServerId(p.server) ?? p.server;+ return [...(this.membership.get(serverId) ?? [])];}private applySeed(seed: MockServerSeed): void {@@ -297,8 +253,6 @@ export class MockServer implements ServerApi, AdminApi, EnrollmentApi {const arr = this.log.get(channel) ?? [];arr.push(msg);this.log.set(channel, arr);- // Control plane: push delivery/start commands to the connected host (if any).- this.dispatchToRecipients(msg);return msg;}@@ -499,7 +453,7 @@ export class MockServer implements ServerApi, AdminApi, EnrollmentApi {const agent: Agent = { id: this.mkId("agent"), name: req.name, userId: req.userId };this.agentHandles.set(agent.id, `@${req.name}`);// The agent's identity (name + instruction) lives in its RuntimeConfig — the- // same config downlinked via agent:start — so the daemon gets it from the+ // same config downlinked via agent:wake — so the daemon gets it from the// server, not by inventing it.this.agentConfigs.set(agent.id,@@ -530,7 +484,9 @@ export class MockServer implements ServerApi, AdminApi, EnrollmentApi {}async postMessage(req: { channel: ChannelRef; sender: string; text: string }): Promise<{ message: Message }> {- // append() handles validation + control-plane dispatch to recipients.+ // append() only validates + stores; it never dispatches a wake — see the+ // class doc comment. Callers that want a wake push a HostCommand+ // themselves (real deployments: via the wake producer/consumer path).return { message: this.post({ channel: req.channel, sender: req.sender, text: req.text }) };}diff --git a/src/daemon/src/server/wsControlChannel.test.ts b/src/daemon/src/server/wsControlChannel.test.tsindex a44a802c3..ebbc83ac7 100644--- a/src/daemon/src/server/wsControlChannel.test.ts+++ b/src/daemon/src/server/wsControlChannel.test.ts@@ -161,25 +161,28 @@ describe("WsControlChannel — ready frame", () => {});});-describe("WsControlChannel — deliver acks", () => {- it("sends an ack when open", async () => {+describe("WsControlChannel — wake/stop acks", () => {+ it("sends agent_wake_ack when open", async () => {const { ch, sockets } = makeChannel();ch.onResync(() => ({ ready: { runtimeReport: [], runningAgents: [] }, sessions: [] }));ch.connect();sockets[0].emit("open");- await ch.reportDeliverAck({ agentId: "a1", deliveryId: "dlv_1" });- expect(sockets[0].frames().some((f) => f.type === "agent_deliver_ack" && f.deliveryId === "dlv_1")).toBe(true);+ await ch.reportWakeAck({ agentId: "a1", launchId: "l1", status: "ok" });+ expect(sockets[0].frames().some((f) => f.type === "agent_wake_ack" && f.launchId === "l1")).toBe(true);});- it("buffers an ack issued before open and flushes it on connect", async () => {+ it("drops (does not throw, does not send) an ack issued before the socket is open", async () => {+ // Unlike the retired agent_deliver_ack, wake/stop acks are point-in-time —+ // there is no queue-side unacked-delivery store retiring them, so there+ // is nothing to buffer for. A dropped ack while offline is fine: the+ // server never addressed this wake attempt on this connection anyway.const { ch, sockets } = makeChannel();ch.onResync(() => ({ ready: { runtimeReport: [], runningAgents: [] }, sessions: [] }));ch.connect();- // Ack before the socket opens — must be buffered, not lost.- await ch.reportDeliverAck({ agentId: "a1", deliveryId: "dlv_early" });- expect(sockets[0].frames().some((f) => f.type === "agent_deliver_ack")).toBe(false);+ await ch.reportWakeAck({ agentId: "a1", launchId: "l_early", status: "ok" });+ expect(sockets[0].frames().some((f) => f.type === "agent_wake_ack")).toBe(false);sockets[0].emit("open");- expect(sockets[0].frames().some((f) => f.type === "agent_deliver_ack" && f.deliveryId === "dlv_early")).toBe(true);+ expect(sockets[0].frames().some((f) => f.type === "agent_wake_ack" && f.launchId === "l_early")).toBe(false);});});diff --git a/src/daemon/src/server/wsControlChannel.ts b/src/daemon/src/server/wsControlChannel.tsindex bcafacce9..fe1f65cc8 100644--- a/src/daemon/src/server/wsControlChannel.ts+++ b/src/daemon/src/server/wsControlChannel.ts@@ -11,8 +11,10 @@* endpoint URL and auth headers are host-supplied — no platform is hardcoded.** Wire framing is intentionally minimal and host-defined:- * - inbound frames are JSON `HostCommand`-shaped (server → host);- * - outbound frames are JSON `{ type: "ready" | "agent_session", … }` (host → server).+ * - inbound frames are JSON `HostCommand`-shaped (server → host), now just+ * `agent:wake` / `agent:stop` / `bot:*` (minimal-wake-queue-unread-notice+ * plan §2 — `agent:start`/`agent:deliver` are gone);+ * - outbound frames are JSON `{ type: "ready" | "agent_session" | "agent_wake_ack" | "agent_stopped_ack", … }` (host → server).* A real server adapter maps these to its own protocol.** This is the control plane local dev actually uses: `mock-server`+`daemon` and the@@ -71,9 +73,12 @@ export interface WsControlChannelOpts {/*** Command reply protocol — daemon → server. New in v0.2.0.*- * `agent_started_ack` / `agent_stopped_ack` are new frames. `agent_deliver_ack`- * is additively extended with optional `status` + `error`; existing server-side- * consumers that read only `{ agentId, deliveryId }` still work.+ * `agent_wake_ack` means "daemon accepted/handled the `agent:wake` command,"+ * NOT "process started" — a wake may spawn, notify an already-running+ * process, or coalesce for later (see `HostControlChannel.reportWakeAck`).+ * `agent_deliver_ack` / `reportDeliverAck` are retired together with+ * `agent:deliver` — the server never decides start-vs-deliver, so there is+ * nothing left for the daemon to ack beyond the wake command itself.** Error codes:* - bot_unknown daemon received a command for a bot not in botsById@@ -89,14 +94,7 @@ type OutboundFrame =| ({ type: "ready" } & HostReady)| { type: "agent_session"; agentId: AgentId; sessionId: string; launchId: string }| {- type: "agent_deliver_ack";- agentId: AgentId;- deliveryId: string;- status?: AgentCommandAckStatus;- error?: AgentCommandAckError;- }- | {- type: "agent_started_ack";+ type: "agent_wake_ack";agentId: AgentId;launchId: string;status: AgentCommandAckStatus;@@ -112,13 +110,6 @@ type OutboundFrame =type ResyncProvider = () => { ready: HostReady; sessions: AgentSessionReport[] };-type PendingAck = {- agentId: AgentId;- deliveryId: string;- status?: AgentCommandAckStatus;- error?: AgentCommandAckError;-};-export class WsControlChannel implements HostControlChannel {private statusValue: ControlChannelStatus = "idle";// Multiple listeners so consumers can layer behavior (e.g. bot-cache pre-hook@@ -132,13 +123,6 @@ export class WsControlChannel implements HostControlChannel {private pingTimer: ReturnType<typeof setInterval> | null = null;private pongDeadline = 0;private resyncProvider: ResyncProvider | null = null;- /**- * Acks enqueued before the socket is open. Acks (not ready/session) are the- * only frames worth buffering across a brief gap — ready/session are instead- * regenerated fresh by the resync provider on (re)connect, so stale snapshots- * are never replayed.- */- private pendingAcks: PendingAck[] = [];constructor(private readonly opts: WsControlChannelOpts) {}@@ -213,28 +197,18 @@ export class WsControlChannel implements HostControlChannel {this.sendFrame({ type: "agent_session", ...info });}- async reportDeliverAck(info: {- agentId: AgentId;- deliveryId: string;- status?: AgentCommandAckStatus;- error?: AgentCommandAckError;- }): Promise<void> {- // Acks must not be lost across a brief disconnect — buffer if not open.- if (this.statusValue !== "open" || !this.ws) {- this.pendingAcks.push(info);- return;- }- this.ws.send(JSON.stringify({ type: "agent_deliver_ack", ...info }));- }-- /** Reply to an `agent:start` HostCommand with the launch outcome. */- async reportStartedAck(info: {+ /**+ * Reply to an `agent:wake` HostCommand with the wake outcome — "daemon+ * accepted/handled the wake command", NOT "process started" (see+ * `HostControlChannel.reportWakeAck`).+ */+ async reportWakeAck(info: {agentId: AgentId;launchId: string;status: AgentCommandAckStatus;error?: AgentCommandAckError;}): Promise<void> {- this.sendFrame({ type: "agent_started_ack", ...info });+ this.sendFrame({ type: "agent_wake_ack", ...info });}/** Reply to an `agent:stop` HostCommand with the stop outcome. */@@ -265,9 +239,8 @@ export class WsControlChannel implements HostControlChannel {/*** On every (re)connect, re-announce the host's CURRENT state: ready handshake- * + a fresh agent_session per live agent (from the resync provider), then flush- * any buffered acks. This is what lets the server recover this host after a- * dropped connection.+ * + a fresh agent_session per live agent (from the resync provider). This is+ * what lets the server recover this host after a dropped connection.*/private resyncOnConnect(): void {if (this.resyncProvider) {@@ -275,11 +248,6 @@ export class WsControlChannel implements HostControlChannel {this.sendFrame({ type: "ready", ...ready });for (const s of sessions) this.sendFrame({ type: "agent_session", ...s });}- if (this.pendingAcks.length && this.ws && this.statusValue === "open") {- const acks = this.pendingAcks;- this.pendingAcks = [];- for (const a of acks) this.ws.send(JSON.stringify({ type: "agent_deliver_ack", ...a }));- }for (const hook of this.resyncHooks) {try {hook();diff --git a/src/daemon/src/server/wsControlServer.test.ts b/src/daemon/src/server/wsControlServer.test.tsindex f5b3a7a73..6e0a14d81 100644--- a/src/daemon/src/server/wsControlServer.test.ts+++ b/src/daemon/src/server/wsControlServer.test.ts@@ -1,6 +1,6 @@-import { describe, it, expect } from "vitest";+import { describe, it, expect, vi } from "vitest";import { WsControlServer, type WebSocketServerLike, type WsConnectionMeta } from "./wsControlServer";-import type { WebSocketLike } from "./contract";+import type { WebSocketLike, HostCommand } from "./contract";/** A fake accepted socket recording send/close. */class FakeSocket implements WebSocketLike {@@ -33,28 +33,18 @@ function fakeWss(): { wss: WebSocketServerLike; connect: (s: FakeSocket, meta?:return { wss, connect: (s, meta) => cb?.(s, meta) };}-/** Minimal MockServer stand-in (only what WsControlServer touches). */-function fakeServer() {- let sink: ((cmd: unknown) => void) | null = null;- return {- attachHost: (s: (cmd: unknown) => void) => {- sink = s;- },- resetRunningAgents: () => {},- redeliverUnacked: () => {},- ackDelivery: () => {},- get sink() {- return sink;- },- };-}+const sampleWakeCommand: HostCommand = {+ type: "agent:wake",+ agentId: "agent1",+ config: { version: 1, runtime: "mock", model: { kind: "default" }, mode: { kind: "default" } },+ launchId: "launch1",+ unreadNotice: { kind: "unread_notice", channel: "/demo/general", latestSeq: 1 },+};describe("WsControlServer — machine-key auth on connect", () => {- it("closes a connection whose machine key fails verification (and never attaches it)", () => {- const server = fakeServer();+ it("closes a connection whose machine key fails verification (and never becomes the active socket)", () => {const { wss, connect } = fakeWss();const cs = new WsControlServer({- server: server as never,port: 0,webSocketServerFactory: () => wss,verifyMachineKey: (auth) => auth === "Bearer good",@@ -64,15 +54,14 @@ describe("WsControlServer — machine-key auth on connect", () => {const bad = new FakeSocket();connect(bad, { authHeader: "Bearer forged" });expect(bad.closed).toBe(true);- // It must NOT have been wired as the active host: a command dispatch reaches no socket.- expect(server.sink).toBeNull();+ // It must NOT have become the active socket: pushCommand reaches nobody.+ expect(cs.isConnected).toBe(false);+ expect(cs.pushCommand(sampleWakeCommand)).toBe(false);});- it("accepts a connection with a valid machine key", () => {- const server = fakeServer();+ it("accepts a connection with a valid machine key and lets pushCommand reach it", () => {const { wss, connect } = fakeWss();const cs = new WsControlServer({- server: server as never,port: 0,webSocketServerFactory: () => wss,verifyMachineKey: (auth) => auth === "Bearer good",@@ -82,16 +71,54 @@ describe("WsControlServer — machine-key auth on connect", () => {const ok = new FakeSocket();connect(ok, { authHeader: "Bearer good" });expect(ok.closed).toBe(false);- expect(server.sink).not.toBeNull(); // wired as the active host+ expect(cs.isConnected).toBe(true);++ expect(cs.pushCommand(sampleWakeCommand)).toBe(true);+ expect(ok.sent).toHaveLength(1);+ expect(JSON.parse(ok.sent[0]!)).toEqual(sampleWakeCommand);});it("with no verifyMachineKey configured, accepts (unit-test convenience)", () => {- const server = fakeServer();const { wss, connect } = fakeWss();- const cs = new WsControlServer({ server: server as never, port: 0, webSocketServerFactory: () => wss });+ const cs = new WsControlServer({ port: 0, webSocketServerFactory: () => wss });cs.start();const s = new FakeSocket();connect(s, { authHeader: undefined });expect(s.closed).toBe(false);});});++describe("WsControlServer — inbound frame observers", () => {+ it("forwards ready/agent_session/agent_wake_ack/agent_stopped_ack frames to their callbacks", () => {+ const { wss, connect } = fakeWss();+ const onReady = vi.fn();+ const onAgentSession = vi.fn();+ const onWakeAck = vi.fn();+ const onStoppedAck = vi.fn();+ const cs = new WsControlServer({+ port: 0,+ webSocketServerFactory: () => wss,+ onReady,+ onAgentSession,+ onWakeAck,+ onStoppedAck,+ });+ cs.start();++ const s = new FakeSocket();+ connect(s);++ const ready = { runtimeReport: [], runningAgents: [] };+ s.emit("message", JSON.stringify({ type: "ready", ...ready }));+ expect(onReady).toHaveBeenCalledWith(ready);++ s.emit("message", JSON.stringify({ type: "agent_session", agentId: "a1", sessionId: "s1", launchId: "l1" }));+ expect(onAgentSession).toHaveBeenCalledWith({ agentId: "a1", sessionId: "s1", launchId: "l1" });++ s.emit("message", JSON.stringify({ type: "agent_wake_ack", agentId: "a1", launchId: "l1", status: "ok" }));+ expect(onWakeAck).toHaveBeenCalledWith({ agentId: "a1", launchId: "l1", status: "ok", error: undefined });++ s.emit("message", JSON.stringify({ type: "agent_stopped_ack", agentId: "a1", status: "ok" }));+ expect(onStoppedAck).toHaveBeenCalledWith({ agentId: "a1", status: "ok", error: undefined });+ });+});diff --git a/src/daemon/src/server/wsControlServer.ts b/src/daemon/src/server/wsControlServer.tsindex c66c1b9c4..e32f86368 100644--- a/src/daemon/src/server/wsControlServer.ts+++ b/src/daemon/src/server/wsControlServer.ts@@ -1,27 +1,30 @@/*** WsControlServer — the SERVER end of the control plane, over a real WebSocket.*- * This is the network counterpart to wiring a host's `LocalControlChannel`- * directly into a `MockServer` in-process. Instead, the server listens on a ws- * port; a host connects with a `WsControlChannel`; and the two exchange the same- * control-plane frames the local path used — only now over a real socket, so- * local dev exercises the actual transport rather than an in-process shortcut.+ * This is a thin ws-transport shim: it authenticates a connecting daemon by+ * machine key, then lets the caller `pushCommand()` a `HostCommand` down the+ * active socket and observe inbound `ready` / `agent_session` / ack frames.+ * It does NOT decide when to wake an agent, does NOT track a server-side+ * "running agents" set, and does NOT retry/redeliver anything — that+ * server-side control-plane state was retired (minimal-wake-queue-unread-notice+ * plan §6): the real production path is `src/web`'s wake producer →+ * `src/wake-worker`'s queue consumer → `sendWakeToMachine`, and the DAEMON+ * (not this fixture) decides spawn-vs-notify-vs-coalesce for `agent:wake`.+ * This class exists purely so daemon-side control-plane/e2e tests can drive+ * `agent:wake`/`agent:stop` over a REAL WebSocket instead of an in-process+ * shortcut, exercising the same transport (`WsControlChannel`) production+ * code uses.** Frames (symmetric with `WsControlChannel`):- * - server → host: the JSON `HostCommand` (`agent:start` / `agent:deliver` / `agent:stop`)- * - host → server: `{ type:"ready", …HostReady }` | `{ type:"agent_session", … }`- *- * The server's command sink (`MockServer.attachHost`) is bridged to the connected- * socket: every command the server computes is serialized and sent down the wire.- * Inbound `ready` frames mark the host's running agents; `agent_session` frames- * are forwarded to an optional observer (a real server would persist them).+ * - server → host: the JSON `HostCommand` (`agent:wake` / `agent:stop` / `bot:*`)+ * - host → server: `{ type:"ready", …HostReady }` | `{ type:"agent_session", … }` |+ * `{ type:"agent_wake_ack" | "agent_stopped_ack", … }`** The ws server impl is injected (`WebSocketServerLike`) so this file carries no* hard `ws` dependency and stays unit-testable; `mock-server` passes a factory* built on the `ws` package.*/import type { HostCommand, HostReady, AgentId, WebSocketLike } from "./contract.js";-import type { MockServer } from "./mockServer.js";// Re-export so existing importers of WebSocketLike from this module keep working.export type { WebSocketLike } from "./contract.js";@@ -42,15 +45,17 @@ export interface WebSocketServerLike {close(cb?: () => void): void;}+type AckStatus = "ok" | "error";+type AckError = { code: string; message: string };+/** Inbound (host → server) control frames. `ready` fields are spread flat — see `WsControlChannel`. */type InboundFrame =| ({ type: "ready" } & HostReady)| { type: "agent_session"; agentId: AgentId; sessionId: string; launchId: string }- | { type: "agent_deliver_ack"; agentId: AgentId; deliveryId: string };+ | { type: "agent_wake_ack"; agentId: AgentId; launchId: string; status: AckStatus; error?: AckError }+ | { type: "agent_stopped_ack"; agentId: AgentId; status: AckStatus; error?: AckError };export interface WsControlServerOpts {- /** The server whose control plane is exposed over ws. */- server: MockServer;/*** Build the ws server bound to `port` on loopback. Injected so this module has* no hard `ws` dependency; `mock-server` passes a real factory.@@ -59,6 +64,12 @@ export interface WsControlServerOpts {port: number;/** Optional: observe agent-session reports (a real server persists for resume). */onAgentSession?: (info: { agentId: AgentId; sessionId: string; launchId: string }) => void;+ /** Optional: observe each inbound `ready` handshake/resync frame. */+ onReady?: (ready: HostReady) => void;+ /** Optional: observe `agent_wake_ack` frames (test assertions). */+ onWakeAck?: (info: { agentId: AgentId; launchId: string; status: AckStatus; error?: AckError }) => void;+ /** Optional: observe `agent_stopped_ack` frames (test assertions). */+ onStoppedAck?: (info: { agentId: AgentId; status: AckStatus; error?: AckError }) => void;/*** Authenticate a connecting daemon by its upgrade `Authorization` header* (`Bearer <machineKey>`). Returns true to accept. When provided, a connection@@ -69,8 +80,11 @@ export interface WsControlServerOpts {}/**- * Bridges a `MockServer`'s control plane onto a ws server. One connected host at- * a time (the dev case); a later host replaces the active sink.+ * Ws-transport shim for exactly one connected host at a time (the dev/test+ * case); a later host replaces the active socket. Commands are pushed+ * explicitly via `pushCommand` — there is no automatic dispatch, because+ * deciding WHEN to wake an agent is now `src/web`/`src/wake-worker`'s job in+ * production, not this fixture's.*/export class WsControlServer {private wss: WebSocketServerLike | null = null;@@ -93,6 +107,26 @@ export class WsControlServer {});}+ /** True iff a daemon is currently connected and authenticated. */+ get isConnected(): boolean {+ return this.active !== null;+ }++ /**+ * Send a `HostCommand` down to the currently connected daemon. Returns+ * false (no throw) when nothing is connected — callers (tests) decide+ * whether that's a failure.+ */+ pushCommand(cmd: HostCommand): boolean {+ if (!this.active) return false;+ try {+ this.active.send(JSON.stringify(cmd));+ return true;+ } catch {+ return false;+ }+ }+private onConnection(socket: WebSocketLike, meta?: WsConnectionMeta): void {// Authenticate the daemon by its machine key before wiring anything up. A// connection without a valid key never reaches the control plane — this is@@ -109,17 +143,6 @@ export class WsControlServer {this.active = socket;- // Bridge server→host commands onto this socket.- this.opts.server.attachHost((cmd: HostCommand) => {- if (this.active === socket) {- try {- socket.send(JSON.stringify(cmd));- } catch {- /* socket gone; the close handler clears it */- }- }- });-socket.on("message", (data: unknown) => this.onMessage(data));socket.on("close", () => {if (this.active === socket) this.active = null;@@ -138,19 +161,20 @@ export class WsControlServer {}if (!frame || typeof frame.type !== "string") return;if (frame.type === "ready") {- // (Re)connect handshake: REPLACE the running set with what the host reports- // (idempotent refresh, not additive — a reconnect after a crash may report- // fewer agents), then re-push any still-unacked deliveries to the host.- this.opts.server.resetRunningAgents(frame.runningAgents);- this.opts.server.redeliverUnacked();+ // Strip the wire-only `type` discriminant — `HostReady` itself has no+ // `type` field (see `WsControlChannel.reportReady`'s flat-spread frame).+ const { type: _type, ...ready } = frame;+ this.opts.onReady?.(ready);} else if (frame.type === "agent_session") {this.opts.onAgentSession?.({agentId: frame.agentId,sessionId: frame.sessionId,launchId: frame.launchId,});- } else if (frame.type === "agent_deliver_ack") {- this.opts.server.ackDelivery(frame.deliveryId);+ } else if (frame.type === "agent_wake_ack") {+ this.opts.onWakeAck?.({ agentId: frame.agentId, launchId: frame.launchId, status: frame.status, error: frame.error });+ } else if (frame.type === "agent_stopped_ack") {+ this.opts.onStoppedAck?.({ agentId: frame.agentId, status: frame.status, error: frame.error });}}}diff --git a/src/daemon/test/e2e/controlPlane.e2e.test.ts b/src/daemon/test/e2e/controlPlane.e2e.test.tsindex a54e69914..54543a32d 100644--- a/src/daemon/test/e2e/controlPlane.e2e.test.ts+++ b/src/daemon/test/e2e/controlPlane.e2e.test.ts@@ -1,8 +1,19 @@/**- * E2E: the full control plane over a REAL WebSocket.+ * E2E: the `agent:wake` control plane over a REAL WebSocket.*- * MockServer (data + control + admin) ─(real ws)─▶ AgentRouter ─▶ AgentProcessManager- * ─▶ mock agent session (pulls inbox via ServerApi, replies "hi!").+ * MockServer (data + admin only) + a manually-pushed `agent:wake` HostCommand+ * ─(real ws)─▶ AgentRouter ─▶ AgentProcessManager ─▶ mock agent session+ * (pulls inbox via ServerApi, replies "hi!").+ *+ * Per minimal-wake-queue-unread-notice plan §6, the SERVER (MockServer) no+ * longer decides when to wake an agent or tracks a running-agents set —+ * `postMessage` only writes the message. This test drives the control plane+ * the way production does: something OUTSIDE the daemon (here, the test+ * itself, standing in for `src/web`'s wake producer + `src/wake-worker`'s+ * consumer) decides a bot is behind and pushes an `agent:wake` HostCommand+ * with a bodiless `UnreadNotice`. The DAEMON (AgentRouter/AgentProcessManager)+ * is what decides spawn-vs-notify-vs-coalesce and turns the notice into an+ * `alook inbox pull` prompt — never the server.** Asserts the round-trip works end to end and that the control frames actually* cross a socket (not an in-process shortcut): we point WsControlChannel at the@@ -13,10 +24,12 @@ import { WebSocketServer, WebSocket } from "ws";import { MockServer, WsControlServer, WsControlChannel } from "../../src/server/index";import { AgentProcessManager, AgentRouter } from "../../src/manager/index";import type { ManagedSession } from "../../src/manager/managerRuntime";-import type { ServerApi } from "../../src/server/contract";+import type { ServerApi, HostCommand } from "../../src/server/contract";+import { makeRuntimeConfig } from "../../src/runtimeConfig";interface Harness {server: MockServer;+ wsServer: WsControlServer;teardown: () => Promise<void>;}@@ -32,7 +45,6 @@ async function setup(): Promise<Harness> {const wsPort = typeof addr === "object" && addr ? addr.port : 0;const wsServer = new WsControlServer({- server,port: wsPort,webSocketServerFactory: () => wss, // reuse the already-listening server});@@ -48,15 +60,18 @@ async function setup(): Promise<Harness> {sessionFactory: ({ agentId }) => makeMockAgentSession(agentId, api),tickIntervalMs: 500,onAgentSession: (info) => void channel.reportAgentSession(info),+ wakePromptFooter: "Use `alook inbox pull` to read your messages, then reply with `alook message send`.",});manager.start();const router = new AgentRouter({ manager, channel, runtimeReport: [{ id: "mock" }] });channel.connect();await router.start();await waitFor(() => channel.status === "open", 3000);+ await waitFor(() => wsServer.isConnected, 3000);return {server,+ wsServer,teardown: async () => {channel.close();await wsServer.close();@@ -65,6 +80,24 @@ async function setup(): Promise<Harness> {};}+/** Push an `agent:wake` HostCommand for `agentId`, notice pointed at `channel` @ `latestSeq`. */+function pushWake(+ wsServer: WsControlServer,+ server: MockServer,+ input: { agentId: string; channel: string; latestSeq: number },+): void {+ const config = server.getAgentConfig(input.agentId) ?? makeRuntimeConfig({ runtime: "mock" });+ const cmd: HostCommand = {+ type: "agent:wake",+ agentId: input.agentId,+ config,+ launchId: `launch_${input.agentId}_${input.latestSeq}`,+ unreadNotice: { kind: "unread_notice", channel: input.channel, latestSeq: input.latestSeq },+ };+ const sent = wsServer.pushCommand(cmd);+ if (!sent) throw new Error("pushWake: no daemon connected");+}+/** Mock agent: on wake, pull inbox, ack, reply "hi!" to each message. */function makeMockAgentSession(agentId: string, api: ServerApi): ManagedSession {const sessionId = `mock-${agentId}`;@@ -132,10 +165,10 @@ describe("control plane over real ws (e2e)", () => {teardown = undefined;});- it("a posted message drives agent:start over ws and the agent replies", async () => {+ it("a pushed agent:wake drives the daemon over ws and the agent replies", async () => {const h = await setup();teardown = h.teardown;- const { server } = h;+ const { server, wsServer } = h;const { user } = await server.createUser({ name: "me" });const { agent } = await server.createAgent({ userId: user.id, name: "cindy", runtime: "mock" });@@ -144,7 +177,9 @@ describe("control plane over real ws (e2e)", () => {const { channel: ch } = await server.createChannel({ server: srv.id, name: "general" });const ref = `/${srv.id}/${ch.id}`;- await server.postMessage({ channel: ref, sender: "@gustavo", text: "cindy, say hi" });+ const { message } = await server.postMessage({ channel: ref, sender: "@gustavo", text: "cindy, say hi" });++ pushWake(wsServer, server, { agentId: agent.id, channel: ref, latestSeq: Number(message.seq.replace("#", "")) });// Wait until the agent has replied (its message lands in the channel).await waitFor(async () => {@@ -157,10 +192,10 @@ describe("control plane over real ws (e2e)", () => {expect(replies.length).toBe(1);});- it("multiple agents each reply (3/3)", async () => {+ it("multiple agents each reply (3/3) to their own agent:wake push", async () => {const h = await setup();teardown = h.teardown;- const { server } = h;+ const { server, wsServer } = h;const { user } = await server.createUser({ name: "me" });const { server: srv } = await server.createServer({ name: "demo" });@@ -174,7 +209,11 @@ describe("control plane over real ws (e2e)", () => {ids.push(agent.id);}- await server.postMessage({ channel: ref, sender: "@gustavo", text: "hello team" });+ const { message } = await server.postMessage({ channel: ref, sender: "@gustavo", text: "hello team" });+ const latestSeq = Number(message.seq.replace("#", ""));+ for (const agentId of ids) {+ pushWake(wsServer, server, { agentId, channel: ref, latestSeq });+ }await waitFor(async () => {const page = await server.read({ agentId: ids[0], channel: ref, limit: 20 });diff --git a/src/shared/src/community-cli-contract.ts b/src/shared/src/community-cli-contract.tsindex a3d6345d5..ba8f6cd4a 100644--- a/src/shared/src/community-cli-contract.ts+++ b/src/shared/src/community-cli-contract.ts@@ -315,6 +315,24 @@ export interface ServerApi {resolve(req: ResolveRequest): Promise<{ message: Message }>;}+/* ------------------------------------------------------------------ */+/* Unread wake notice */+/* ------------------------------------------------------------------ */++/**+ * A bodiless "you have unread work" signal — deliberately carries no message+ * content. The daemon turns this into a fixed inbox-pull prompt; the agent+ * must call `inboxPull` to fetch the actual message content from the server,+ * which remains the only source of truth for message bodies.+ */+export interface UnreadNotice {+ kind: "unread_notice";+ /** Path ref of the scope with unread work (channel, thread, or DM). */+ channel: ChannelRef;+ /** The high-water seq that triggered this notice, for `AgentMsg.seq`. */+ latestSeq: Seq;+}+/* ------------------------------------------------------------------ *//* Control plane — server → host commands *//* ------------------------------------------------------------------ */@@ -322,12 +340,18 @@ export interface ServerApi {/*** Commands the SERVER pushes DOWN to a host (daemon). This is the control plane —* distinct from the agent-initiated data plane (`ServerApi`). The server owns- * ADDRESSING: every `agent:deliver` already names its recipient `agentId`; the- * host never fans out by channel membership.+ * ADDRESSING: every command already names its recipient `agentId`; the host+ * never fans out by channel membership.+ *+ * `agent:wake` is the ONE semantic unread-wake command — "ensure this agent+ * handles unread work." The server/wake-worker does not decide whether a+ * daemon process is already running; that is daemon-owned state. The daemon+ * decides whether to spawn a fresh process, notify an already-running one, or+ * coalesce the notice for the next turn (see `AgentProcessManager`).*/export type HostCommand =| {- type: "agent:start";+ type: "agent:wake";agentId: AgentId;/*** The full structured runtime configuration the server stores for this@@ -337,29 +361,12 @@ export type HostCommand =config: RuntimeConfig;/** Resume an existing runtime session, if any (separate from RuntimeConfig). */sessionId?: string;- /** Optional triggering message delivered with the start. */- wakeMessage?: Message;- /**- * Delivery id for `wakeMessage` (when present), so the host can ack it and- * the server can redeliver the same id on no-ack (at-least-once + dedup).- */- deliveryId?: string;- /** Unique id for this launch (correlates host↔server). */+ /** Unique id for this wake/launch attempt (correlates host↔server). */launchId: string;+ /** The bodiless unread signal — the daemon prompts "pull your inbox". */+ unreadNotice: UnreadNotice;}| { type: "agent:stop"; agentId: AgentId }- | {- type: "agent:deliver";- /** Pre-addressed by the server — host delivers to exactly this agent. */- agentId: AgentId;- message: Message;- /**- * At-least-once delivery id. The host acks it (`agent:deliver:ack`) once the- * message is accepted; the server redelivers the SAME id until acked, and the- * host dedups by id so the agent never sees a duplicate wake.- */- deliveryId: string;- }// ─── Bot lifecycle events (server → daemon) ────────────────────────────// Colon-namespaced to match the agent:* naming convention. Delivered to// the specific machine's daemon connection via the WS DO. On the daemon,@@ -447,22 +454,12 @@ export interface HostControlChannel {/** Report an agent's runtime session id (after it starts / resumes). */reportAgentSession(info: { agentId: AgentId; sessionId: string; launchId: string }): Promise<void>;/**- * Acknowledge an at-least-once delivery so the server stops redelivering it.- * `status`/`error` are additive — existing callers passing only- * `{ agentId, deliveryId }` still work; the server side reads them when- * present to report an error inline.- */- reportDeliverAck(info: {- agentId: AgentId;- deliveryId: string;- status?: "ok" | "error";- error?: { code: string; message: string };- }): Promise<void>;- /**- * Reply to an `agent:start` command with the launch outcome. New in v0.2.+ * Reply to an `agent:wake` command with the wake outcome — "daemon+ * accepted/handled the wake command", NOT "process started" (a wake may+ * spawn, notify an already-running process, or coalesce for later).* Optional so the local mock channel can omit it.*/- reportStartedAck?(info: {+ reportWakeAck?(info: {agentId: AgentId;launchId: string;status: "ok" | "error";@@ -478,7 +475,7 @@ export interface HostControlChannel {}): Promise<void>;/*** Report a `session.error` upward. Used by `AgentRouter` when a driver- * can't fulfil an `agent:start` (e.g. runtime not installed) — the server+ * can't fulfil an `agent:wake` (e.g. runtime not installed) — the server* routes the frame through the machine DO which stashes it as an overlay* on the machine summary so the web card renders it inline.*/@@ -529,9 +526,11 @@ export type WebSocketFactory = (url: string, headers: Record<string, string>) =>/*** Server-side provisioning, separate from the agent's daily `ServerApi`. Used by* the test-server command surface (and, in production, by privileged callers) to- * create servers/agents/channels and inject messages. `postMessage` is what- * drives the control plane: the server computes recipients and emits- * `agent:deliver` (preceded by `agent:start` for any agent not yet running).+ * create servers/agents/channels and inject messages. `postMessage` writes+ * the message; real deployments separately enqueue an `agent:wake` for any+ * bot behind on the new message (see `src/web`'s wake producer ++ * `src/wake-worker`'s consumer) — this admin surface does not itself compute+ * or dispatch control-plane commands.*/export interface AdminApi {/** Create a user (owner of agents). */diff --git a/src/shared/src/community-ws-events.ts b/src/shared/src/community-ws-events.tsindex 7aaff827e..a65e9f25b 100644--- a/src/shared/src/community-ws-events.ts+++ b/src/shared/src/community-ws-events.ts@@ -355,7 +355,7 @@ export type CommunityMachineSummary = {/*** Last runtime error reported by the daemon. Optional overlay; undefined* means "no known error." Optimistically cleared when the DO forwards a- * subsequent `agent:start` frame to the daemon.+ * subsequent `agent:wake` frame to the daemon.*/lastRuntimeError?: {requested: string@@ -392,8 +392,8 @@ export type CommunityMachineRemoved = {// ── Bot events ────────────────────────────────────────────────────────────────//// Server → daemon frames. Colon-namespaced to match the existing HostCommand-// convention (`agent:start` / `agent:stop` / `agent:deliver`). Delivered to-// the specific machine's daemon connection via the WS Durable Object.+// convention (`agent:wake` / `agent:stop`). Delivered to the specific+// machine's daemon connection via the WS Durable Object.export type BotAddedFrame = {type: "bot:added"diff --git a/src/shared/src/community/wake-dispatch.ts b/src/shared/src/community/wake-dispatch.tsindex f1807ecb7..6f67896ad 100644--- a/src/shared/src/community/wake-dispatch.ts+++ b/src/shared/src/community/wake-dispatch.ts@@ -1,4 +1,12 @@-import type { HostCommand } from "../community-cli-contract";+import { nanoid } from "nanoid";+import type { HostCommand, UnreadNotice } from "../community-cli-contract";+import { makeRuntimeConfig } from "../runtime-config";+import * as message from "../db/queries/community/message";+import * as bot from "../db/queries/community/bot";+import * as member from "../db/queries/community/member";+import * as readState from "../db/queries/community/read-state";+import * as agentInbox from "../db/queries/community/agent-inbox";+import type { Database } from "../db/index";/*** Deliberately NOT `@cloudflare/workers-types`' `Fetcher` — this module is@@ -12,26 +20,30 @@ interface FetcherLike {fetch(input: string, init?: RequestInit): Promise<Response>;}-/** One `WAKE_QUEUE` message — the producer (`src/web`'s `enqueueBotWakes`)- * builds the full `HostCommand` up front (it has D1 access); the consumer- * (`src/wake-worker`) is a dumb, stateless forwarder that never touches D1. */+/**+ * One `WAKE_QUEUE` message — deliberately minimal (plan+ * minimal-wake-queue-unread-notice §1): just enough to rebuild the wake+ * command from CURRENT D1 state at consume time. No `machineId`, `runtime`,+ * `launchId`, message text, sender, or preview — all of that is re-derived+ * by `buildUnreadWakeCommand` in `src/wake-worker` so a stale queue item+ * never wakes an old machine or carries stale content.+ */export interface WakePayload {+ messageId: string;botUserId: string;- machineId: string;- command: HostCommand;}/**- * Thin wake-dispatch seam (plan §8/#13). Lives in `src/shared` (not- * `src/web`) because BOTH the `src/web` wake producer AND the- * `src/wake-worker` queue consumer need it, and the consumer has no- * `@opennextjs/cloudflare` / Next.js context — this module does a plain- * `Fetcher.fetch`, nothing CF-Workers-Next.js-specific.+ * Thin wake-dispatch seam. Lives in `src/shared` (not `src/web`) because+ * BOTH the `src/web` wake producer AND the `src/wake-worker` queue consumer+ * need it, and the consumer has no `@opennextjs/cloudflare` / Next.js+ * context — this module does a plain `Fetcher.fetch`, nothing+ * CF-Workers-Next.js-specific.** `env.WS_DO_WORKER` is a service binding to the `alook-ws-do` worker's HTTP* surface (never a raw DO namespace — `src/web`/`src/wake-worker` cannot* fetch a DO stub directly). This function POSTs an already-fully-built- * `HostCommand` to that worker's `/community-machine/by-id/<machineId>/forward-agent-start`+ * `HostCommand` to that worker's `/community-machine/by-id/<machineId>/forward-agent-wake`* route and normalizes the response to a boolean — it never inspects,* validates, or constructs any part of `command`, and it never exposes the* DO-naming mechanics (no public `getMachineDoName` here or anywhere else).@@ -55,7 +67,7 @@ export async function sendWakeToMachine(machineId: string,command: HostCommand): Promise<{ sent: boolean }> {- const path = `/community-machine/by-id/${encodeURIComponent(machineId)}/forward-agent-start`;+ const path = `/community-machine/by-id/${encodeURIComponent(machineId)}/forward-agent-wake`;const res = await env.WS_DO_WORKER.fetch(`http://internal${path}`, {method: "POST",headers: { "content-type": "application/json" },@@ -69,3 +81,107 @@ export async function sendWakeToMachine(const data = (await res.json()) as { sent?: number };return { sent: (data.sent ?? 0) > 0 };}++/** Why `buildUnreadWakeCommand` decided NOT to wake — every reason is a permanent, current-state miss the consumer must `ack()`, never `retry()`. */+export type SkipReason =+ | "message_missing"+ | "invalid_message_scope"+ | "self_authored"+ | "bot_missing"+ | "bot_deleted"+ | "bot_unbound"+ | "bot_not_in_scope"+ | "notice_channel_unresolvable"+ | "already_read";++export type BuildUnreadWakeResult =+ | { state: "ready"; machineId: string; command: HostCommand }+ | { state: "skip"; reason: SkipReason };++/**+ * Rebuild an `agent:wake` `HostCommand` from CURRENT D1 state — the queue+ * consumer's core orchestration (plan minimal-wake-queue-unread-notice §3/§4).+ * Re-checks the message, the bot's binding, the bot's current access to the+ * message scope, and the bot's read-state before waking, so a stale queue+ * item (membership revoked, bot rebound to a new machine, already caught up+ * via an earlier `inboxPull`) never produces a bogus or wasted wake.+ *+ * Every `skip` reason here is a PERMANENT current-state miss — the caller+ * `ack()`s the queue message. D1 exceptions propagate (thrown, not+ * returned) so the caller can `retry()` instead.+ */+export async function buildUnreadWakeCommand(+ db: Database,+ input: { messageId: string; botUserId: string }+): Promise<BuildUnreadWakeResult> {+ const msg = await message.getWakeMessageScopeById(db, input.messageId);+ if (!msg) return { state: "skip", reason: "message_missing" };++ const scope = msg.channelId+ ? { channelId: msg.channelId }+ : msg.dmConversationId+ ? { dmConversationId: msg.dmConversationId }+ : null;+ if (!scope) return { state: "skip", reason: "invalid_message_scope" };++ // Producer filtering already excludes self-wakes; the consumer must still+ // be robust to malformed/internal queue items that point a bot at its own+ // message.+ if (msg.authorId === input.botUserId) return { state: "skip", reason: "self_authored" };++ const botCtx = await bot.getBotWakeContext(db, input.botUserId);+ if (botCtx.state !== "ready") return { state: "skip", reason: botCtx.state };++ const canRead = await member.canBotReadWakeScope(db, input.botUserId, scope);+ if (!canRead) return { state: "skip", reason: "bot_not_in_scope" };++ const lastReadSeq = await readState.getWakeReadSeq(db, input.botUserId, scope);+ if (lastReadSeq >= msg.seq) return { state: "skip", reason: "already_read" };++ const channel = await agentInbox.resolveUnreadNoticeChannel(db, scope, input.botUserId);+ if (!channel) return { state: "skip", reason: "notice_channel_unresolvable" };++ const unreadNotice: UnreadNotice = { kind: "unread_notice", channel, latestSeq: msg.seq };+ const config = makeRuntimeConfig({+ runtime: botCtx.runtime,+ agentName: botCtx.name,+ agentHandle: `@${botCtx.name}`,+ });+ const command: HostCommand = {+ type: "agent:wake",+ agentId: botCtx.botUserId,+ config,+ launchId: nanoid(),+ unreadNotice,+ };+ return { state: "ready", machineId: botCtx.machineId, command };+}++/** Outcome of resolving ONE wake candidate — what every caller (the real queue consumer, and the dev-only inline stand-in) needs to decide what to log. */+export type DispatchOneWakeResult =+ | { outcome: "skip"; reason: SkipReason }+ | { outcome: "sent" }+ | { outcome: "delivered_nowhere"; machineId: string };++/**+ * The ONE place that decides what happens for a single `{ messageId,+ * botUserId }` wake candidate: rebuild from current D1 state, and forward if+ * `ready`. Every caller — `src/wake-worker`'s real queue consumer AND+ * `src/web`'s dev-only inline stand-in (local Cloudflare Queues can't bridge+ * separate `wrangler dev`/`next dev` processes, so `next dev` calls this+ * directly instead of going through `WAKE_QUEUE`) — calls this SAME function,+ * so "what a wake candidate resolves to" has exactly one implementation.+ * Callers own their own retry/ack-vs-log semantics on top; this never+ * swallows a `buildUnreadWakeCommand`/`sendWakeToMachine` throw (a transient+ * D1/network failure) — it propagates so the caller can retry.+ */+export async function dispatchOneUnreadWake(+ db: Database,+ env: { WS_DO_WORKER: FetcherLike },+ input: { messageId: string; botUserId: string }+): Promise<DispatchOneWakeResult> {+ const result = await buildUnreadWakeCommand(db, input);+ if (result.state === "skip") return { outcome: "skip", reason: result.reason };+ const { sent } = await sendWakeToMachine(env, result.machineId, result.command);+ return sent ? { outcome: "sent" } : { outcome: "delivered_nowhere", machineId: result.machineId };+}diff --git a/src/shared/src/constants.ts b/src/shared/src/constants.tsindex b849d9d12..319f880e2 100644--- a/src/shared/src/constants.ts+++ b/src/shared/src/constants.ts@@ -163,3 +163,5 @@ export const DEV_PASSWORD = "dev-password-000";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";export const DEV_EMAIL_WORKER_URL = process.env.DEV_EMAIL_WORKER_URL || "http://localhost:8787";+// `src/wake-worker/wrangler.toml`'s `[dev] port` — see wake-transport.ts.+export const DEV_WAKE_WORKER_URL = process.env.DEV_WAKE_WORKER_URL || "http://localhost:8790";diff --git a/src/shared/src/db/queries/community/agent-inbox.ts b/src/shared/src/db/queries/community/agent-inbox.tsindex 58bf01c61..cdd8ebf03 100644--- a/src/shared/src/db/queries/community/agent-inbox.ts+++ b/src/shared/src/db/queries/community/agent-inbox.ts@@ -21,7 +21,7 @@ import {} from "../../community-schema";import { user } from "../../schema";import type { Database } from "../../index";-import { formatRef, formatSeq, DM_SERVER, type Message, type Seq } from "../../../community-cli-contract";+import { formatRef, formatSeq, DM_SERVER, type Message, type Seq, type ChannelRef } from "../../../community-cli-contract";type RawAgentMessage = {id: string;@@ -177,6 +177,87 @@ export async function toAgentMessages(});}+/**+ * Strict single-scope ref resolver for `UnreadNotice.channel`+ * (`buildUnreadWakeCommand`, minimal-wake-queue-unread-notice plan §4). Unlike+ * `resolveScopeRefs` (used for message/inbox hydration, where an `/unknown/…`+ * fallback is tolerable UI degradation), a wake command's notice channel must+ * NEVER be a placeholder — a missing channel, missing DM, missing parent+ * channel, or missing parent message for a thread all resolve to `null` so+ * the caller treats it as `notice_channel_unresolvable` (ack/skip) rather+ * than waking an agent with a bogus ref it can't `inboxPull` against.+ */+export async function resolveUnreadNoticeChannel(+ db: Database,+ scope: { channelId?: string; dmConversationId?: string },+ botUserId: string+): Promise<ChannelRef | null> {+ if (scope.channelId) {+ const rows = await db+ .select({+ id: communityChannel.id,+ name: communityChannel.name,+ serverId: communityChannel.serverId,+ parentChannelId: communityChannel.parentChannelId,+ parentMessageId: communityChannel.parentMessageId,+ })+ .from(communityChannel)+ .where(eq(communityChannel.id, scope.channelId))+ .limit(1);+ const ch = rows[0];+ if (!ch) return null;++ if (ch.parentChannelId && ch.parentMessageId) {+ const [parentRows, rootRows] = await Promise.all([+ db+ .select({ name: communityChannel.name, serverId: communityChannel.serverId })+ .from(communityChannel)+ .where(eq(communityChannel.id, ch.parentChannelId))+ .limit(1),+ db+ .select({ seq: communityMessage.seq })+ .from(communityMessage)+ .where(eq(communityMessage.id, ch.parentMessageId))+ .limit(1),+ ]);+ const parent = parentRows[0];+ const root = rootRows[0];+ if (!parent || !root) return null;+ const serverName = await getServerName(db, parent.serverId);+ if (!serverName) return null;+ return formatRef({ server: serverName, channel: parent.name, threadRootSeq: root.seq });+ }++ const serverName = await getServerName(db, ch.serverId);+ if (!serverName) return null;+ return formatRef({ server: serverName, channel: ch.name });+ }++ if (scope.dmConversationId) {+ const rows = await db+ .select()+ .from(communityDmConversation)+ .where(eq(communityDmConversation.id, scope.dmConversationId))+ .limit(1);+ const dm = rows[0];+ if (!dm) return null;+ const peerId = dm.user1Id === botUserId ? dm.user2Id : dm.user1Id;+ if (!peerId) return null;+ return formatRef({ server: DM_SERVER, channel: peerId });+ }++ return null;+}++async function getServerName(db: Database, serverId: string): Promise<string | null> {+ const rows = await db+ .select({ name: communityServer.name })+ .from(communityServer)+ .where(eq(communityServer.id, serverId))+ .limit(1);+ return rows[0]?.name ?? null;+}+/** Single-row convenience wrapper around `toAgentMessages`. */export async function toAgentMessage(db: Database, row: RawAgentMessage, viewerId: string): Promise<Message> {const [msg] = await toAgentMessages(db, [row], viewerId);diff --git a/src/shared/src/db/queries/community/bot.ts b/src/shared/src/db/queries/community/bot.tsindex c9ea68525..812347110 100644--- a/src/shared/src/db/queries/community/bot.ts+++ b/src/shared/src/db/queries/community/bot.ts@@ -246,6 +246,40 @@ export async function findWakeCandidates(.map((r) => ({ botUserId: r.botUserId, name: r.name, machineId: r.machineId, runtime: r.runtime }));}+/**+ * Discriminated bot-state lookup for the unread-wake rebuild path+ * (`buildUnreadWakeCommand`). A single D1 hit that distinguishes exactly why+ * a bot isn't wake-able (missing / soft-deleted / no machine binding) from+ * the happy path — the caller `ack()`s the queue item for every non-`ready`+ * state, never `retry()`s a permanent miss.+ */+export type BotWakeContext =+ | { state: "bot_missing" }+ | { state: "bot_deleted" }+ | { state: "bot_unbound" }+ | { state: "ready"; botUserId: string; name: string; machineId: string; runtime: string };++export async function getBotWakeContext(db: Database, botUserId: string): Promise<BotWakeContext> {+ const rows = await db+ .select({+ id: user.id,+ name: user.name,+ isBot: user.isBot,+ deletedAt: user.deletedAt,+ machineId: communityBotBinding.machineId,+ runtime: communityBotBinding.runtime,+ })+ .from(user)+ .leftJoin(communityBotBinding, eq(communityBotBinding.userId, user.id))+ .where(eq(user.id, botUserId))+ .limit(1);+ const r = rows[0];+ if (!r || !r.isBot) return { state: "bot_missing" };+ if (r.deletedAt) return { state: "bot_deleted" };+ if (!r.machineId || !r.runtime) return { state: "bot_unbound" };+ return { state: "ready", botUserId: r.id, name: r.name, machineId: r.machineId, runtime: r.runtime };+}+/** Bots bound to this machine — daemon cold-start warmup uses this. */export async function listBotsForMachine(db: Database,diff --git a/src/shared/src/db/queries/community/member.ts b/src/shared/src/db/queries/community/member.tsindex 57ccb7de3..4c1ec4735 100644--- a/src/shared/src/db/queries/community/member.ts+++ b/src/shared/src/db/queries/community/member.ts@@ -1,5 +1,5 @@import { eq, and, ne, inArray, count, asc, or, gt, like, isNull, sql } from "drizzle-orm";-import { communityServerMember } from "../../community-schema";+import { communityServerMember, communityChannel, communityDmConversation } from "../../community-schema";import { user } from "../../schema";import type { Database } from "../../index";import {@@ -362,6 +362,57 @@ export function removeOwnerBotsFromServerStatement();}+/**+ * Wake-dispatch access re-check (unread-wake rebuild path,+ * `buildUnreadWakeCommand`) — scoped in SQL before returning, per+ * AGENTS.md's "scope the queries before, not check ownership after". A+ * queued wake item can be stale by the time it's consumed (membership+ * revoked, DM peer changed); this must return false rather than let the+ * caller wake a bot that lost access to the scope.+ *+ * Thread scopes are ordinary `communityChannel` rows (own id, own+ * `serverId`) — the same server-membership check as a top-level channel+ * covers them, no separate thread-membership concept exists.+ */+export async function canBotReadWakeScope(+ db: Database,+ botUserId: string,+ scope: { channelId?: string; dmConversationId?: string }+): Promise<boolean> {+ if (scope.channelId) {+ const rows = await db+ .select({ serverId: communityChannel.serverId })+ .from(communityChannel)+ .innerJoin(+ communityServerMember,+ and(+ eq(communityServerMember.serverId, communityChannel.serverId),+ eq(communityServerMember.userId, botUserId)+ )+ )+ .where(eq(communityChannel.id, scope.channelId))+ .limit(1);+ return rows.length > 0;+ }+ if (scope.dmConversationId) {+ const rows = await db+ .select({ id: communityDmConversation.id })+ .from(communityDmConversation)+ .where(+ and(+ eq(communityDmConversation.id, scope.dmConversationId),+ or(+ eq(communityDmConversation.user1Id, botUserId),+ eq(communityDmConversation.user2Id, botUserId)+ )+ )+ )+ .limit(1);+ return rows.length > 0;+ }+ return false;+}+export async function getCoMemberUserIds(db: Database, userId: string): Promise<string[]> {const userServerIds = db.select({ serverId: communityServerMember.serverId })diff --git a/src/shared/src/db/queries/community/message.ts b/src/shared/src/db/queries/community/message.tsindex 76543530a..359011cb4 100644--- a/src/shared/src/db/queries/community/message.ts+++ b/src/shared/src/db/queries/community/message.ts@@ -398,6 +398,37 @@ export async function getMessageByChannelAndSeq(return rows[0] ?? null;}+/**+ * Lean by-id lookup for the unread-wake rebuild path+ * (`buildUnreadWakeCommand`, plan §8/minimal-wake-queue-unread-notice). NO+ * author join and NO message-body selection — a missing/deleted author row+ * must not make an otherwise-real message look missing, and the wake+ * command never carries message content (the daemon prompts `inbox pull`).+ */+export async function getWakeMessageScopeById(+ db: Database,+ messageId: string+): Promise<{+ id: string;+ seq: number;+ authorId: string;+ channelId: string | null;+ dmConversationId: string | null;+} | null> {+ const rows = await db+ .select({+ id: communityMessage.id,+ seq: communityMessage.seq,+ authorId: communityMessage.authorId,+ channelId: communityMessage.channelId,+ dmConversationId: communityMessage.dmConversationId,+ })+ .from(communityMessage)+ .where(eq(communityMessage.id, messageId))+ .limit(1);+ return rows[0] ?? null;+}+export async function getMessage(db: Database, messageId: string) {const rows = await db.select({diff --git a/src/shared/src/db/queries/community/read-state.ts b/src/shared/src/db/queries/community/read-state.tsindex 6318b997a..155a15118 100644--- a/src/shared/src/db/queries/community/read-state.ts+++ b/src/shared/src/db/queries/community/read-state.ts@@ -342,3 +342,17 @@ export async function getReadState(.where(buildTargetFilter(data));return rows[0] ?? null;}++/**+ * Thin `lastReadSeq` accessor for the unread-wake rebuild path+ * (`buildUnreadWakeCommand`). No row (bot never read this scope) is "never+ * read" — same convention `findWakeCandidates` already uses (`?? 0`).+ */+export async function getWakeReadSeq(+ db: Database,+ botUserId: string,+ scope: { channelId?: string; dmConversationId?: string }+): Promise<number> {+ const state = await getReadState(db, { userId: botUserId, ...scope });+ return state?.lastReadSeq ?? 0;+}diff --git a/src/shared/src/index.ts b/src/shared/src/index.tsindex 2fc4c12bc..142b9b68f 100644--- a/src/shared/src/index.ts+++ b/src/shared/src/index.ts@@ -92,6 +92,7 @@ export {DEV_WEB_URL,DEV_WS_DO_URL,DEV_EMAIL_WORKER_URL,+ DEV_WAKE_WORKER_URL,MeetingStatus,TERMINAL_MEETING_STATUSES,COMMUNITY_BOT_LIMIT_PER_OWNER,@@ -363,6 +364,7 @@ export type {ResolveRequest as CommunityCliResolveRequest,ListChannelsRequest as CommunityCliListChannelsRequest,ServerApi as CommunityCliServerApi,+ UnreadNotice,HostCommand,HostReadyRuntime,HostReady,@@ -382,8 +384,9 @@ export type {} from "./runtime-config";export { RUNTIME_CONFIG_VERSION, makeRuntimeConfig } from "./runtime-config";-export { sendWakeToMachine } from "./community/wake-dispatch";-export type { WakePayload } from "./community/wake-dispatch";+export { sendWakeToMachine, buildUnreadWakeCommand, dispatchOneUnreadWake } from "./community/wake-dispatch";+export type { DispatchOneWakeResult } from "./community/wake-dispatch";+export type { WakePayload, BuildUnreadWakeResult } from "./community/wake-dispatch";export type { CommunityMachineSummary, CommunityMachineRuntime } from "./community-ws-events";export type {diff --git a/src/shared/src/runtime-config.ts b/src/shared/src/runtime-config.tsindex db47ebfd7..8b2f9a93d 100644--- a/src/shared/src/runtime-config.ts+++ b/src/shared/src/runtime-config.ts@@ -1,17 +1,18 @@/*** RuntimeConfig — the structured, versioned agent runtime configuration.*- * This is what the server stores per agent and pushes down in `agent:start`'s+ * This is what the server stores per agent and pushes down in `agent:wake`'s* `config`. It captures the FULL config surface — which runtime, which model,* which provider/endpoint, mode, reasoning effort — as structured data (not bare* strings), mirroring how a production daemon models it.** Lifted from `src/daemon/src/runtimeConfig.ts` into `@alook/shared` because- * `HostCommand`'s `agent:start.config` field needs this type, and the wake- * producer (`src/web`, a Worker) has no path to import from the CLI/daemon- * package. `src/daemon` re-exports `RuntimeConfig`/`makeRuntimeConfig` from- * here; `resolveLaunchFields`/`ResolvedLaunchFields` stay daemon-only- * (host-side launch resolution, not needed server-side).+ * `HostCommand`'s `agent:wake.config` field needs this type, and the wake+ * producer/consumer (`src/web` + `src/wake-worker`, both Workers) has no path+ * to import from the CLI/daemon package. `src/daemon` re-exports+ * `RuntimeConfig`/`makeRuntimeConfig` from here; `resolveLaunchFields`/+ * `ResolvedLaunchFields` stay daemon-only (host-side launch resolution, not+ * needed server-side).** The host doesn't act on `RuntimeConfig` directly; it `resolveLaunchFields()`s* it into flat launch fields (CLI args + env) that each driver consumes. Config@@ -58,7 +59,7 @@ export interface RuntimeConfig {envVars?: Record<string, string>;/*** Agent identity — the SERVER's truth about who this agent is, carried in the- * same config the server downlinks via `agent:start`. The daemon does not+ * same config the server downlinks via `agent:wake`. The daemon does not* invent these; it fills the LaunchContext from them.*/agentName?: string;diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.tsindex 83a4aac2c..5989d78dd 100644--- a/src/shared/src/schemas.ts+++ b/src/shared/src/schemas.ts@@ -869,7 +869,7 @@ export const CommunityMachineSummarySchema = z.object({availableRuntimes: z.array(CommunityMachineRuntimeSchema).default([]),/*** Last runtime error reported by the daemon (optimistically cleared on- * subsequent `agent:start` forward). Optional so pre-error summaries+ * subsequent `agent:wake` forward). Optional so pre-error summaries* omit the field entirely — undefined == "no known error."*/lastRuntimeError: zdiff --git a/src/shared/test/community/wake-dispatch-build.test.ts b/src/shared/test/community/wake-dispatch-build.test.tsnew file mode 100644index 000000000..c364fbbfd--- /dev/null+++ b/src/shared/test/community/wake-dispatch-build.test.ts@@ -0,0 +1,228 @@+import { describe, it, expect, vi, beforeEach } from "vitest";++const mockGetWakeMessageScopeById = vi.fn();+vi.mock("../../src/db/queries/community/message", () => ({+ getWakeMessageScopeById: (...a: unknown[]) => mockGetWakeMessageScopeById(...a),+}));++const mockGetBotWakeContext = vi.fn();+vi.mock("../../src/db/queries/community/bot", () => ({+ getBotWakeContext: (...a: unknown[]) => mockGetBotWakeContext(...a),+}));++const mockCanBotReadWakeScope = vi.fn();+vi.mock("../../src/db/queries/community/member", () => ({+ canBotReadWakeScope: (...a: unknown[]) => mockCanBotReadWakeScope(...a),+}));++const mockGetWakeReadSeq = vi.fn();+vi.mock("../../src/db/queries/community/read-state", () => ({+ getWakeReadSeq: (...a: unknown[]) => mockGetWakeReadSeq(...a),+}));++const mockResolveUnreadNoticeChannel = vi.fn();+vi.mock("../../src/db/queries/community/agent-inbox", () => ({+ resolveUnreadNoticeChannel: (...a: unknown[]) => mockResolveUnreadNoticeChannel(...a),+}));++import { buildUnreadWakeCommand } from "../../src/community/wake-dispatch";+import type { Database } from "../../src/db/index";++const fakeDb = {} as Database;++const MESSAGE_CHANNEL = {+ id: "msg_1",+ seq: 7,+ authorId: "u_human",+ channelId: "ch_1",+ dmConversationId: null,+};++const BOT_READY = {+ state: "ready" as const,+ botUserId: "bot_1",+ name: "zoe",+ machineId: "machine_1",+ runtime: "claude",+};++function seedHappyPath(overrides?: {+ message?: Partial<typeof MESSAGE_CHANNEL>;+ bot?: Partial<typeof BOT_READY>;+ canRead?: boolean;+ readSeq?: number;+ channel?: string | null;+}) {+ mockGetWakeMessageScopeById.mockResolvedValue({ ...MESSAGE_CHANNEL, ...overrides?.message });+ mockGetBotWakeContext.mockResolvedValue({ ...BOT_READY, ...overrides?.bot });+ mockCanBotReadWakeScope.mockResolvedValue(overrides?.canRead ?? true);+ mockGetWakeReadSeq.mockResolvedValue(overrides?.readSeq ?? 0);+ mockResolveUnreadNoticeChannel.mockResolvedValue(+ overrides?.channel === undefined ? "/srv_1/general" : overrides.channel,+ );+}++describe("buildUnreadWakeCommand", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it("ready: builds an agent:wake HostCommand from current D1 state for a channel message", async () => {+ seedHappyPath();++ const result = await buildUnreadWakeCommand(fakeDb, { messageId: "msg_1", botUserId: "bot_1" });++ expect(result.state).toBe("ready");+ if (result.state !== "ready") throw new Error("expected ready");+ expect(result.machineId).toBe("machine_1");+ expect(result.command).toMatchObject({+ type: "agent:wake",+ agentId: "bot_1",+ unreadNotice: { kind: "unread_notice", channel: "/srv_1/general", latestSeq: 7 },+ });+ expect(typeof result.command.launchId).toBe("string");+ expect(result.command.launchId.length).toBeGreaterThan(0);+ expect(result.command).toMatchObject({ config: { runtime: "claude" } });++ // Every downstream query is scoped with the SAME messageId/botUserId/scope.+ expect(mockGetWakeMessageScopeById).toHaveBeenCalledWith(fakeDb, "msg_1");+ expect(mockGetBotWakeContext).toHaveBeenCalledWith(fakeDb, "bot_1");+ expect(mockCanBotReadWakeScope).toHaveBeenCalledWith(fakeDb, "bot_1", { channelId: "ch_1" });+ expect(mockGetWakeReadSeq).toHaveBeenCalledWith(fakeDb, "bot_1", { channelId: "ch_1" });+ expect(mockResolveUnreadNoticeChannel).toHaveBeenCalledWith(fakeDb, { channelId: "ch_1" }, "bot_1");+ });++ it("ready: resolves a DM scope when the message has no channelId", async () => {+ seedHappyPath({+ message: { channelId: null, dmConversationId: "dm_1" },+ channel: "/.dm/@gustavo",+ });++ const result = await buildUnreadWakeCommand(fakeDb, { messageId: "msg_1", botUserId: "bot_1" });++ expect(result.state).toBe("ready");+ if (result.state !== "ready") throw new Error("expected ready");+ expect(result.command.unreadNotice).toEqual({+ kind: "unread_notice",+ channel: "/.dm/@gustavo",+ latestSeq: 7,+ });+ expect(mockCanBotReadWakeScope).toHaveBeenCalledWith(fakeDb, "bot_1", { dmConversationId: "dm_1" });+ expect(mockResolveUnreadNoticeChannel).toHaveBeenCalledWith(fakeDb, { dmConversationId: "dm_1" }, "bot_1");+ });++ it("ready: resolves a thread scope (channelId still set — thread channels ARE channels)", async () => {+ seedHappyPath({ channel: "/srv_1/general/#3" });++ const result = await buildUnreadWakeCommand(fakeDb, { messageId: "msg_1", botUserId: "bot_1" });++ expect(result.state).toBe("ready");+ if (result.state !== "ready") throw new Error("expected ready");+ expect(result.command.unreadNotice.channel).toBe("/srv_1/general/#3");+ });++ it("skip: message_missing when the message no longer exists", async () => {+ mockGetWakeMessageScopeById.mockResolvedValue(null);++ const result = await buildUnreadWakeCommand(fakeDb, { messageId: "msg_gone", botUserId: "bot_1" });++ expect(result).toEqual({ state: "skip", reason: "message_missing" });+ expect(mockGetBotWakeContext).not.toHaveBeenCalled();+ });++ it("skip: invalid_message_scope when the message has neither channelId nor dmConversationId", async () => {+ mockGetWakeMessageScopeById.mockResolvedValue({ ...MESSAGE_CHANNEL, channelId: null, dmConversationId: null });++ const result = await buildUnreadWakeCommand(fakeDb, { messageId: "msg_1", botUserId: "bot_1" });++ expect(result).toEqual({ state: "skip", reason: "invalid_message_scope" });+ });++ it("skip: self_authored when the message's author is the same bot (malformed/internal queue item)", async () => {+ mockGetWakeMessageScopeById.mockResolvedValue({ ...MESSAGE_CHANNEL, authorId: "bot_1" });++ const result = await buildUnreadWakeCommand(fakeDb, { messageId: "msg_1", botUserId: "bot_1" });++ expect(result).toEqual({ state: "skip", reason: "self_authored" });+ expect(mockGetBotWakeContext).not.toHaveBeenCalled();+ });++ it("skip: bot_missing when the bot user row is gone/never existed", async () => {+ mockGetWakeMessageScopeById.mockResolvedValue(MESSAGE_CHANNEL);+ mockGetBotWakeContext.mockResolvedValue({ state: "bot_missing" });++ const result = await buildUnreadWakeCommand(fakeDb, { messageId: "msg_1", botUserId: "bot_1" });++ expect(result).toEqual({ state: "skip", reason: "bot_missing" });+ expect(mockCanBotReadWakeScope).not.toHaveBeenCalled();+ });++ it("skip: bot_deleted when the bot user row is soft-deleted", async () => {+ mockGetWakeMessageScopeById.mockResolvedValue(MESSAGE_CHANNEL);+ mockGetBotWakeContext.mockResolvedValue({ state: "bot_deleted" });++ const result = await buildUnreadWakeCommand(fakeDb, { messageId: "msg_1", botUserId: "bot_1" });++ expect(result).toEqual({ state: "skip", reason: "bot_deleted" });+ });++ it("skip: bot_unbound when the bot has no current machine binding — always re-reads the CURRENT binding, not a stale one", async () => {+ mockGetWakeMessageScopeById.mockResolvedValue(MESSAGE_CHANNEL);+ mockGetBotWakeContext.mockResolvedValue({ state: "bot_unbound" });++ const result = await buildUnreadWakeCommand(fakeDb, { messageId: "msg_1", botUserId: "bot_1" });++ expect(result).toEqual({ state: "skip", reason: "bot_unbound" });+ });++ it("skip: bot_not_in_scope when the bot lost membership/participant access before the queue drained", async () => {+ seedHappyPath({ canRead: false });++ const result = await buildUnreadWakeCommand(fakeDb, { messageId: "msg_1", botUserId: "bot_1" });++ expect(result).toEqual({ state: "skip", reason: "bot_not_in_scope" });+ expect(mockGetWakeReadSeq).not.toHaveBeenCalled();+ });++ it("skip: already_read when lastReadSeq >= message.seq (an earlier inboxPull already caught the bot up)", async () => {+ seedHappyPath({ readSeq: 7 });++ const result = await buildUnreadWakeCommand(fakeDb, { messageId: "msg_1", botUserId: "bot_1" });++ expect(result).toEqual({ state: "skip", reason: "already_read" });+ expect(mockResolveUnreadNoticeChannel).not.toHaveBeenCalled();+ });++ it("skip: already_read also fires when lastReadSeq is strictly greater (batched catch-up past this seq)", async () => {+ seedHappyPath({ readSeq: 9 });++ const result = await buildUnreadWakeCommand(fakeDb, { messageId: "msg_1", botUserId: "bot_1" });++ expect(result).toEqual({ state: "skip", reason: "already_read" });+ });++ it("skip: notice_channel_unresolvable when the scope can't be strictly resolved to a ChannelRef (never falls back to /unknown/...)", async () => {+ seedHappyPath({ channel: null });++ const result = await buildUnreadWakeCommand(fakeDb, { messageId: "msg_1", botUserId: "bot_1" });++ expect(result).toEqual({ state: "skip", reason: "notice_channel_unresolvable" });+ });++ it("propagates a D1/query throw from the message lookup instead of returning a skip (caller must retry())", async () => {+ mockGetWakeMessageScopeById.mockRejectedValue(new Error("D1_ERROR: query failed"));++ await expect(+ buildUnreadWakeCommand(fakeDb, { messageId: "msg_1", botUserId: "bot_1" }),+ ).rejects.toThrow("D1_ERROR");+ });++ it("propagates a D1/query throw from any downstream lookup (bot context, membership, read-state, channel resolution)", async () => {+ mockGetWakeMessageScopeById.mockResolvedValue(MESSAGE_CHANNEL);+ mockGetBotWakeContext.mockRejectedValue(new Error("D1_ERROR: bot lookup failed"));++ await expect(+ buildUnreadWakeCommand(fakeDb, { messageId: "msg_1", botUserId: "bot_1" }),+ ).rejects.toThrow("D1_ERROR");+ });+});diff --git a/src/shared/test/community/wake-dispatch-one.test.ts b/src/shared/test/community/wake-dispatch-one.test.tsnew file mode 100644index 000000000..3e11dda4b--- /dev/null+++ b/src/shared/test/community/wake-dispatch-one.test.ts@@ -0,0 +1,120 @@+import { describe, it, expect, vi, beforeEach } from "vitest";++const mockGetWakeMessageScopeById = vi.fn();+vi.mock("../../src/db/queries/community/message", () => ({+ getWakeMessageScopeById: (...a: unknown[]) => mockGetWakeMessageScopeById(...a),+}));++const mockGetBotWakeContext = vi.fn();+vi.mock("../../src/db/queries/community/bot", () => ({+ getBotWakeContext: (...a: unknown[]) => mockGetBotWakeContext(...a),+}));++const mockCanBotReadWakeScope = vi.fn();+vi.mock("../../src/db/queries/community/member", () => ({+ canBotReadWakeScope: (...a: unknown[]) => mockCanBotReadWakeScope(...a),+}));++const mockGetWakeReadSeq = vi.fn();+vi.mock("../../src/db/queries/community/read-state", () => ({+ getWakeReadSeq: (...a: unknown[]) => mockGetWakeReadSeq(...a),+}));++const mockResolveUnreadNoticeChannel = vi.fn();+vi.mock("../../src/db/queries/community/agent-inbox", () => ({+ resolveUnreadNoticeChannel: (...a: unknown[]) => mockResolveUnreadNoticeChannel(...a),+}));++import { dispatchOneUnreadWake } from "../../src/community/wake-dispatch";+import type { Database } from "../../src/db/index";++const fakeDb = {} as Database;++const MESSAGE_CHANNEL = {+ id: "msg_1",+ seq: 7,+ authorId: "u_human",+ channelId: "ch_1",+ dmConversationId: null,+};++const BOT_READY = {+ state: "ready" as const,+ botUserId: "bot_1",+ name: "zoe",+ machineId: "machine_1",+ runtime: "claude",+};++function seedReady() {+ mockGetWakeMessageScopeById.mockResolvedValue(MESSAGE_CHANNEL);+ mockGetBotWakeContext.mockResolvedValue(BOT_READY);+ mockCanBotReadWakeScope.mockResolvedValue(true);+ mockGetWakeReadSeq.mockResolvedValue(0);+ mockResolveUnreadNoticeChannel.mockResolvedValue("/srv_1/general");+}++function makeEnv(fetchImpl: (url: string, init?: RequestInit) => Promise<Response>) {+ return { WS_DO_WORKER: { fetch: vi.fn(fetchImpl) } as unknown as Fetcher };+}++/**+ * `dispatchOneUnreadWake` is the ONE per-candidate function both+ * `src/wake-worker`'s real queue consumer and `src/web`'s dev-only inline+ * stand-in call — these tests exercise it through its real+ * `buildUnreadWakeCommand`/`sendWakeToMachine` wiring end-to-end (query+ * modules mocked, `fetch` mocked), so neither caller needs its own+ * "what does a wake candidate resolve to" test coverage.+ */+describe("dispatchOneUnreadWake", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it("resolves to { outcome: 'sent' } when the rebuild is ready and the daemon is online", async () => {+ seedReady();+ const env = makeEnv(async () => new Response(JSON.stringify({ sent: 1 }), { status: 200 }));++ const result = await dispatchOneUnreadWake(fakeDb, env, { messageId: "msg_1", botUserId: "bot_1" });++ expect(result).toEqual({ outcome: "sent" });+ });++ it("resolves to { outcome: 'delivered_nowhere', machineId } when the daemon is offline", async () => {+ seedReady();+ const env = makeEnv(async () => new Response(JSON.stringify({ sent: 0 }), { status: 200 }));++ const result = await dispatchOneUnreadWake(fakeDb, env, { messageId: "msg_1", botUserId: "bot_1" });++ expect(result).toEqual({ outcome: "delivered_nowhere", machineId: "machine_1" });+ });++ it("resolves to { outcome: 'skip', reason } without ever calling fetch when the rebuild is a skip", async () => {+ mockGetWakeMessageScopeById.mockResolvedValue(null);+ const fetchMock = vi.fn();+ const env = makeEnv(fetchMock);++ const result = await dispatchOneUnreadWake(fakeDb, env, { messageId: "msg_gone", botUserId: "bot_1" });++ expect(result).toEqual({ outcome: "skip", reason: "message_missing" });+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it("propagates a throw from buildUnreadWakeCommand (caller decides retry vs log)", async () => {+ mockGetWakeMessageScopeById.mockRejectedValue(new Error("D1_ERROR: query failed"));+ const env = makeEnv(async () => new Response("{}", { status: 200 }));++ await expect(+ dispatchOneUnreadWake(fakeDb, env, { messageId: "msg_1", botUserId: "bot_1" }),+ ).rejects.toThrow("D1_ERROR");+ });++ it("propagates a throw from sendWakeToMachine (transient ws-do failure)", async () => {+ seedReady();+ const env = makeEnv(async () => new Response("boom", { status: 500 }));++ await expect(+ dispatchOneUnreadWake(fakeDb, env, { messageId: "msg_1", botUserId: "bot_1" }),+ ).rejects.toThrow();+ });+});diff --git a/src/shared/test/community/wake-dispatch.test.ts b/src/shared/test/community/wake-dispatch.test.tsindex 2ff149baf..53da6667f 100644--- a/src/shared/test/community/wake-dispatch.test.ts+++ b/src/shared/test/community/wake-dispatch.test.ts@@ -3,10 +3,11 @@ import { sendWakeToMachine } from "../../src/community/wake-dispatch";import type { HostCommand } from "../../src/community-cli-contract";const dummyCommand = {- type: "agent:start",+ type: "agent:wake",agentId: "bot-1",config: { version: 1, runtime: "claude" },launchId: "launch-1",+ unreadNotice: { kind: "unread_notice", channel: "/demo/general", latestSeq: 1 },} as unknown as HostCommand;function makeEnv(fetchImpl: (url: string, init?: RequestInit) => Promise<Response>) {@@ -14,9 +15,9 @@ function makeEnv(fetchImpl: (url: string, init?: RequestInit) => Promise<Respons}describe("sendWakeToMachine", () => {- it("POSTs the command verbatim to the ws-do forward-agent-start route", async () => {+ it("POSTs the command verbatim to the ws-do forward-agent-wake route", async () => {const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {- expect(url).toBe("http://internal/community-machine/by-id/machine-1/forward-agent-start");+ expect(url).toBe("http://internal/community-machine/by-id/machine-1/forward-agent-wake");expect(init?.method).toBe("POST");expect(JSON.parse(init!.body as string)).toEqual(dummyCommand);return new Response(JSON.stringify({ sent: 1 }), { status: 200 });@@ -61,7 +62,7 @@ describe("sendWakeToMachine", () => {it("encodes the machineId in the URL path", async () => {const fetchMock = vi.fn(async (url: string) => {- expect(url).toBe("http://internal/community-machine/by-id/machine%2Fwith%2Fslash/forward-agent-start");+ expect(url).toBe("http://internal/community-machine/by-id/machine%2Fwith%2Fslash/forward-agent-wake");return new Response(JSON.stringify({ sent: 0 }), { status: 200 });});const env = makeEnv(fetchMock);diff --git a/src/wake-worker/src/env.d.ts b/src/wake-worker/src/env.d.tsindex 9f2e10879..82a35f0bc 100644--- a/src/wake-worker/src/env.d.ts+++ b/src/wake-worker/src/env.d.ts@@ -1,3 +1,10 @@interface Env {WS_DO_WORKER: Fetcher+ /**+ * `alook-app` — the same D1 database `src/web/wrangler.toml` binds as+ * `DB` (minimal-wake-queue-unread-notice plan §3). The consumer reads+ * current message/bot/binding/read-state rows here to rebuild the+ * `agent:wake` command at consume time (`buildUnreadWakeCommand`).+ */+ DB: D1Database}diff --git a/src/wake-worker/src/index.test.ts b/src/wake-worker/src/index.test.tsindex 047b91468..6af95550c 100644--- a/src/wake-worker/src/index.test.ts+++ b/src/wake-worker/src/index.test.ts@@ -1,42 +1,45 @@import { describe, it, expect, vi, beforeEach } from "vitest"-const mockSendWakeToMachine = vi.fn()+const mockDispatchOneUnreadWake = vi.fn()+const mockCreateDb = vi.fn((..._a: unknown[]) => ({ __db: true }))vi.mock("@alook/shared", () => {const noopLogger = { debug: () => { }, info: () => { }, warn: () => { }, error: () => { }, child() { return this } }return {createLogger: () => noopLogger,- sendWakeToMachine: (...a: unknown[]) => mockSendWakeToMachine(...a),+ createDb: (...a: unknown[]) => mockCreateDb(...a),+ dispatchOneUnreadWake: (...a: unknown[]) => mockDispatchOneUnreadWake(...a),}})import handler from "./index"-function makeMsg(body: { botUserId: string; machineId: string; command: unknown }) {+function makeMsg(body: { messageId: string; botUserId: string }) {return { body, ack: vi.fn(), retry: vi.fn() }}describe("wake-worker queue consumer", () => {- const env = { WS_DO_WORKER: {} } as unknown as Env+ const env = { WS_DO_WORKER: {}, DB: {} } as unknown as EnvbeforeEach(() => {vi.clearAllMocks()})- it("acks on successful delivery ({ sent: true })", async () => {- mockSendWakeToMachine.mockResolvedValue({ sent: true })- const msg = makeMsg({ botUserId: "bot1", machineId: "m1", command: { type: "agent:start" } })+ it("resolves via dispatchOneUnreadWake and acks on successful delivery", async () => {+ mockDispatchOneUnreadWake.mockResolvedValue({ outcome: "sent" })+ const msg = makeMsg({ messageId: "msg1", botUserId: "bot1" })const batch = { messages: [msg] } as unknown as MessageBatch<unknown>await handler.queue(batch as never, env)- expect(mockSendWakeToMachine).toHaveBeenCalledWith(env, "m1", { type: "agent:start" })+ expect(mockCreateDb).toHaveBeenCalledWith(env.DB)+ expect(mockDispatchOneUnreadWake).toHaveBeenCalledWith({ __db: true }, env, { messageId: "msg1", botUserId: "bot1" })expect(msg.ack).toHaveBeenCalledTimes(1)expect(msg.retry).not.toHaveBeenCalled()})- it("acks (does not retry) when daemon is offline ({ sent: false }) — known-permanent state", async () => {- mockSendWakeToMachine.mockResolvedValue({ sent: false })- const msg = makeMsg({ botUserId: "bot1", machineId: "m1", command: { type: "agent:start" } })+ it("acks (does not retry) when daemon is offline (delivered_nowhere) — known-permanent state", async () => {+ mockDispatchOneUnreadWake.mockResolvedValue({ outcome: "delivered_nowhere", machineId: "m1" })+ const msg = makeMsg({ messageId: "msg1", botUserId: "bot1" })const batch = { messages: [msg] } as unknown as MessageBatch<unknown>await handler.queue(batch as never, env)@@ -45,9 +48,41 @@ describe("wake-worker queue consumer", () => {expect(msg.retry).not.toHaveBeenCalled()})- it("retries with backoff on a thrown (transient) error", async () => {- mockSendWakeToMachine.mockRejectedValue(new Error("ws-do 500"))- const msg = makeMsg({ botUserId: "bot1", machineId: "m1", command: { type: "agent:start" } })+ it("acks when the resolution is a skip", async () => {+ mockDispatchOneUnreadWake.mockResolvedValue({ outcome: "skip", reason: "already_read" })+ const msg = makeMsg({ messageId: "msg1", botUserId: "bot1" })+ const batch = { messages: [msg] } as unknown as MessageBatch<unknown>++ await handler.queue(batch as never, env)++ expect(msg.ack).toHaveBeenCalledTimes(1)+ expect(msg.retry).not.toHaveBeenCalled()+ })++ it.each([+ "message_missing",+ "invalid_message_scope",+ "self_authored",+ "bot_missing",+ "bot_deleted",+ "bot_unbound",+ "bot_not_in_scope",+ "notice_channel_unresolvable",+ "already_read",+ ] as const)("acks for skip reason %s", async (reason) => {+ mockDispatchOneUnreadWake.mockResolvedValue({ outcome: "skip", reason })+ const msg = makeMsg({ messageId: "msg1", botUserId: "bot1" })+ const batch = { messages: [msg] } as unknown as MessageBatch<unknown>++ await handler.queue(batch as never, env)++ expect(msg.ack).toHaveBeenCalledTimes(1)+ expect(msg.retry).not.toHaveBeenCalled()+ })++ it("retries with backoff when dispatchOneUnreadWake throws (D1 exception or transient sendWakeToMachine failure)", async () => {+ mockDispatchOneUnreadWake.mockRejectedValue(new Error("D1 query failed"))+ const msg = makeMsg({ messageId: "msg1", botUserId: "bot1" })const batch = { messages: [msg] } as unknown as MessageBatch<unknown>await handler.queue(batch as never, env)@@ -57,15 +92,15 @@ describe("wake-worker queue consumer", () => {})it("processes every message in the batch independently — one failure doesn't block others", async () => {- mockSendWakeToMachine- .mockResolvedValueOnce({ sent: true })+ mockDispatchOneUnreadWake+ .mockResolvedValueOnce({ outcome: "sent" }).mockRejectedValueOnce(new Error("boom"))- .mockResolvedValueOnce({ sent: false })+ .mockResolvedValueOnce({ outcome: "skip", reason: "already_read" })const msgs = [- makeMsg({ botUserId: "bot1", machineId: "m1", command: {} }),- makeMsg({ botUserId: "bot2", machineId: "m2", command: {} }),- makeMsg({ botUserId: "bot3", machineId: "m3", command: {} }),+ makeMsg({ messageId: "msg1", botUserId: "bot1" }),+ makeMsg({ messageId: "msg2", botUserId: "bot2" }),+ makeMsg({ messageId: "msg3", botUserId: "bot3" }),]const batch = { messages: msgs } as unknown as MessageBatch<unknown>@@ -76,3 +111,138 @@ describe("wake-worker queue consumer", () => {expect(msgs[2]!.ack).toHaveBeenCalledTimes(1)})})++describe("wake-worker dev-only HTTP entrypoint (fetch)", () => {+ const env = { WS_DO_WORKER: {}, DB: {} } as unknown as Env++ beforeEach(() => {+ vi.clearAllMocks()+ })++ function makeRequest(method: string, body?: unknown) {+ return new Request("http://internal/", {+ method,+ body: body === undefined ? undefined : JSON.stringify(body),+ })+ }++ it("resolves every candidate in the body via dispatchOneUnreadWake — the SAME function queue() calls", async () => {+ mockDispatchOneUnreadWake.mockResolvedValue({ outcome: "sent" })+ const payloads = [+ { messageId: "msg1", botUserId: "bot1" },+ { messageId: "msg1", botUserId: "bot2" },+ ]++ const res = await handler.fetch!(makeRequest("POST", payloads), env)++ expect(res.status).toBe(202)+ expect(mockCreateDb).toHaveBeenCalledWith(env.DB)+ expect(mockDispatchOneUnreadWake).toHaveBeenCalledTimes(2)+ expect(mockDispatchOneUnreadWake).toHaveBeenCalledWith({ __db: true }, env, payloads[0])+ expect(mockDispatchOneUnreadWake).toHaveBeenCalledWith({ __db: true }, env, payloads[1])+ })++ it("returns 202 even when a skip/delivered_nowhere outcome resolves (no queue infra to ack/retry against)", async () => {+ mockDispatchOneUnreadWake.mockResolvedValue({ outcome: "skip", reason: "already_read" })++ const res = await handler.fetch!(makeRequest("POST", [{ messageId: "msg1", botUserId: "bot1" }]), env)++ expect(res.status).toBe(202)+ })++ it("still returns 202 when one candidate rejects — siblings are unaffected, failure is only logged", async () => {+ mockDispatchOneUnreadWake+ .mockResolvedValueOnce({ outcome: "sent" })+ .mockRejectedValueOnce(new Error("D1 exploded"))++ const res = await handler.fetch!(+ makeRequest("POST", [+ { messageId: "msg1", botUserId: "bot1" },+ { messageId: "msg2", botUserId: "bot2" },+ ]),+ env,+ )++ expect(res.status).toBe(202)+ expect(mockDispatchOneUnreadWake).toHaveBeenCalledTimes(2)+ })++ it("returns 400 on invalid JSON body", async () => {+ const res = await handler.fetch!(new Request("http://internal/", { method: "POST", body: "not json" }), env)++ expect(res.status).toBe(400)+ expect(mockDispatchOneUnreadWake).not.toHaveBeenCalled()+ })++ it("returns 405 for non-POST methods", async () => {+ const res = await handler.fetch!(makeRequest("GET"), env)++ expect(res.status).toBe(405)+ expect(mockDispatchOneUnreadWake).not.toHaveBeenCalled()+ })+})++/**+ * Equivalence contract: `queue()` (real Cloudflare Queue traffic) and+ * `fetch()` (dev-only stand-in `wake-transport.ts`'s dev HTTP transport+ * calls) MUST resolve a given `WakePayload` identically — same+ * `dispatchOneUnreadWake` call, same args — because they share the exact+ * same `resolveAndLog` helper. This single table is exercised against BOTH+ * entrypoints so a future change that special-cases one of them (instead of+ * `resolveAndLog`) fails a test here, not just in production later.+ *+ * What this table deliberately does NOT assert as equivalent — and never+ * will, see plans/minimal-wake-queue-unread-notice.md — is+ * retry-on-transient-failure: `queue()` retries via Cloudflare's+ * backoff/DLQ; `fetch()` has no queue infra behind it, so a rejection is+ * just logged. That's covered by the entrypoint-specific `describe` blocks+ * above, not here.+ */+const RESOLUTION_SCENARIOS = [+ { name: "sent", outcome: { outcome: "sent" as const } },+ { name: "delivered_nowhere", outcome: { outcome: "delivered_nowhere" as const, machineId: "m1" } },+ { name: "skip: already_read", outcome: { outcome: "skip" as const, reason: "already_read" as const } },+ { name: "skip: bot_not_in_scope", outcome: { outcome: "skip" as const, reason: "bot_not_in_scope" as const } },+]++describe("wake-worker queue() vs fetch() — same resolution for the same candidate", () => {+ const env = { WS_DO_WORKER: {}, DB: {} } as unknown as Env++ beforeEach(() => {+ vi.clearAllMocks()+ })++ it.each(RESOLUTION_SCENARIOS)("calls dispatchOneUnreadWake with identical args for scenario: $name", async ({ outcome }) => {+ const item = { messageId: "msg1", botUserId: "bot1" }++ mockDispatchOneUnreadWake.mockResolvedValue(outcome)+ await handler.queue({ messages: [{ body: item, ack: vi.fn(), retry: vi.fn() }] } as never, env)+ const queueCallArgs = mockDispatchOneUnreadWake.mock.calls[0]++ vi.clearAllMocks()+ mockDispatchOneUnreadWake.mockResolvedValue(outcome)+ await handler.fetch!(new Request("http://internal/", { method: "POST", body: JSON.stringify([item]) }), env)+ const fetchCallArgs = mockDispatchOneUnreadWake.mock.calls[0]++ expect(fetchCallArgs).toEqual(queueCallArgs)+ })++ it("both entrypoints let a sibling's success/skip proceed when one candidate throws", async () => {+ const items = [+ { messageId: "msg1", botUserId: "bot1" },+ { messageId: "msg2", botUserId: "bot2" },+ ]++ mockDispatchOneUnreadWake.mockRejectedValueOnce(new Error("boom")).mockResolvedValueOnce({ outcome: "sent" })+ const msgs = items.map((body) => ({ body, ack: vi.fn(), retry: vi.fn() }))+ await handler.queue({ messages: msgs } as never, env)+ expect(msgs[0]!.retry).toHaveBeenCalledTimes(1)+ expect(msgs[1]!.ack).toHaveBeenCalledTimes(1)++ vi.clearAllMocks()+ mockDispatchOneUnreadWake.mockRejectedValueOnce(new Error("boom")).mockResolvedValueOnce({ outcome: "sent" })+ const res = await handler.fetch!(new Request("http://internal/", { method: "POST", body: JSON.stringify(items) }), env)+ expect(res.status).toBe(202)+ expect(mockDispatchOneUnreadWake).toHaveBeenCalledTimes(2)+ })+})diff --git a/src/wake-worker/src/index.ts b/src/wake-worker/src/index.tsindex abff454c0..1a3429c56 100644--- a/src/wake-worker/src/index.ts+++ b/src/wake-worker/src/index.ts@@ -1,39 +1,94 @@-import { createLogger, sendWakeToMachine } from "@alook/shared"-import type { WakePayload } from "@alook/shared"+import { createLogger, createDb, dispatchOneUnreadWake } from "@alook/shared"+import type { WakePayload, Database } from "@alook/shared"const log = createLogger({ service: "wake-worker" })/**- * `alook-wake-worker` — Cloudflare Queue consumer for `alook-wake` (plan- * §8/#13). Dumb, stateless forwarder: no D1 binding, does zero `HostCommand`- * construction of its own (the `src/web` producer already built the full- * command with D1 access). Fresh invocation per batch → own subrequest- * budget; in practice exactly one subrequest (`sendWakeToMachine`) per- * message.+ * Resolve ONE wake candidate via `dispatchOneUnreadWake` and log its+ * (non-error) outcome. Shared by both entrypoints below — `queue()` (real+ * traffic) and `fetch()` (dev-only stand-in for the local Cloudflare Queue,+ * see its doc comment) — so the log lines and interpretation logic exist+ * exactly once regardless of which entrypoint received the item. Throws+ * propagate untouched; each caller decides retry (queue) vs best-effort+ * (dev HTTP shim) on its own.*/+async function resolveAndLog(db: Database, env: Env, item: WakePayload) {+ const result = await dispatchOneUnreadWake(db, env, item)+ if (result.outcome === "skip") {+ // Every skip reason is a permanent current-state miss — caller must ack, never retry.+ log.info("wake_skipped", { botUserId: item.botUserId, messageId: item.messageId, reason: result.reason })+ } else if (result.outcome === "delivered_nowhere") {+ // ws-do resolved cleanly but the daemon is offline — a known-permanent+ // state for this attempt (plan §3's error contract). Daemon reconnect+ // warmup recovers; retrying would just spin, so this also acks.+ log.info("wake_delivered_nowhere", { botUserId: item.botUserId, machineId: result.machineId })+ }+ return result+}+export default {+ /**+ * `alook-wake-worker` — Cloudflare Queue consumer for `alook-wake`+ * (minimal-wake-queue-unread-notice plan §3). Owns a `DB` binding to the+ * same `alook-app` database `src/web` writes to: for every minimal+ * `{ messageId, botUserId }` queue item, `dispatchOneUnreadWake` re-reads+ * CURRENT D1 state and only then forwards a freshly built `agent:wake`+ * `HostCommand`. This is what keeps a stale queue item from waking an old+ * machine, an already-caught-up bot, or a bot that lost access to the+ * scope since it was enqueued.+ */async queue(batch: MessageBatch<WakePayload>, env: Env): Promise<void> {+ const db = createDb(env.DB)for (const msg of batch.messages) {try {- const { sent } = await sendWakeToMachine(env, msg.body.machineId, msg.body.command)- if (!sent) {- log.info("wake_delivered_nowhere", { botUserId: msg.body.botUserId, machineId: msg.body.machineId })- }- // Both `{ sent: true }` and `{ sent: false }` ack — `false` means the- // ws-do route resolved cleanly but the daemon is offline, a- // known-permanent state for this attempt (plan §8's error contract).- // Daemon reconnect warmup recovers; retrying here would just spin.+ await resolveAndLog(db, env, msg.body)msg.ack()} catch (err) {- // Transient failure (5xx / network) — retry with backoff. After- // `max_retries` (wrangler.toml: 3), the message lands in the DLQ.+ // Transient failure (D1 exception, 5xx / network) — retry with+ // backoff. After `max_retries` (wrangler.toml: 3), the message lands+ // in the DLQ.log.warn("wake_dispatch_failed_retrying", {botUserId: msg.body.botUserId,- machineId: msg.body.machineId,+ messageId: msg.body.messageId,err: String(err),})msg.retry({ delaySeconds: 5 })}}},++ /**+ * Dev-only HTTP stand-in for the local Cloudflare Queue. Local Queues+ * simulation cannot bridge separate `wrangler dev`/`next dev` processes+ * (plans/minimal-wake-queue-unread-notice.md), so `src/web`'s+ * `wake-transport.ts` calls this route (via the `WAKE_WORKER` service+ * binding, `NODE_ENV === "development"` only) instead of+ * `WAKE_QUEUE.sendBatch(...)`. Body is a JSON `WakePayload[]` — same shape+ * a queue batch's message bodies would carry. Runs the SAME+ * `resolveAndLog`/`dispatchOneUnreadWake` real orchestration `queue()`+ * does, including the real D1 read and the real forward to `alook-ws-do`+ * — this is the actual worker process handling actual wake candidates,+ * not a simulation of it. Best-effort: no queue infra backs this, so one+ * candidate's failure is logged but never blocks siblings or the response.+ */+ async fetch(request: Request, env: Env): Promise<Response> {+ if (request.method !== "POST") return new Response("method not allowed", { status: 405 })++ let payloads: WakePayload[]+ try {+ payloads = await request.json()+ } catch {+ return new Response("invalid json body", { status: 400 })+ }++ const db = createDb(env.DB)+ const results = await Promise.allSettled(payloads.map((p) => resolveAndLog(db, env, p)))+ for (let i = 0; i < results.length; i++) {+ const r = results[i]!+ if (r.status === "rejected") {+ log.warn("dev_http_wake_dispatch_failed", { botUserId: payloads[i]!.botUserId, messageId: payloads[i]!.messageId, err: String(r.reason) })+ }+ }+ return new Response(null, { status: 202 })+ },}diff --git a/src/wake-worker/wrangler.toml b/src/wake-worker/wrangler.tomlindex 5f2d047f9..c98dd10c2 100644--- a/src/wake-worker/wrangler.toml+++ b/src/wake-worker/wrangler.toml@@ -22,12 +22,19 @@ destinations = ["grafana-traces"]port = 8790inspector_port = 9232-# Sole binding this worker needs (plan §8) — doName resolution happens-# inside `alook-ws-do`'s own D1-backed route, not here. No D1 binding.[[services]]binding = "WS_DO_WORKER"service = "alook-ws-do"+# Same `alook-app` database `src/web/wrangler.toml` binds as `DB`+# (minimal-wake-queue-unread-notice plan §3) — the consumer re-derives the+# `agent:wake` command from current D1 state at consume time instead of+# trusting a possibly-stale queue-carried command.+[[d1_databases]]+binding = "DB"+database_id = "1593b87c-d8a8-4cdf-b6c0-c80d94442654"+database_name = "alook-app"+[[queues.consumers]]queue = "alook-wake"max_batch_size = 25diff --git a/src/web/src/env.d.ts b/src/web/src/env.d.tsindex 9ea2308d9..be5414c8a 100644--- a/src/web/src/env.d.ts+++ b/src/web/src/env.d.ts@@ -6,6 +6,7 @@ declare namespace Cloudflare {WS_DO_WORKER: FetcherEMAIL_WORKER: FetcherWAKE_QUEUE: Queue<import("@alook/shared").WakePayload>+ WAKE_WORKER: FetcherWORKER_SELF_REFERENCE: FetcherNEXT_INC_CACHE_R2_BUCKET: R2BucketNEXT_TAG_CACHE_D1: D1Database@@ -26,6 +27,7 @@ declare namespace Cloudflare {DEVICE_CLIENT_IDS?: stringNODE_ENV?: stringDEV_WS_DO_URL?: string+ DEV_WAKE_WORKER_URL?: string}}diff --git a/src/web/src/lib/broadcast.ts b/src/web/src/lib/broadcast.tsindex bed5001bf..e2502a9f3 100644--- a/src/web/src/lib/broadcast.ts+++ b/src/web/src/lib/broadcast.ts@@ -1,6 +1,7 @@import { getCloudflareContext } from "@opennextjs/cloudflare"import type { WsMessage, DaemonPushMessage } from "@alook/shared"import { DEV_WS_DO_URL, createLogger } from "@alook/shared"+import { fetchViaBindingOrDevFallback } from "./dev-binding-fetch"const log = createLogger({ service: "broadcast" })@@ -12,8 +13,9 @@ const log = createLogger({ service: "broadcast" })* non-OK status (5xx), falls through to an HTTP fetch against* `env.DEV_WS_DO_URL` (or the shared default in `@alook/shared`).*- * Owns the "try binding → non-OK/throw → HTTP fallback" pattern in one- * place so callers don't reinvent it (and don't drift on the fallback URL).+ * Thin wrapper around `fetchViaBindingOrDevFallback` — see that module for+ * the actual "try binding → non-OK/throw → HTTP fallback" decision tree so+ * callers (this + `wake-transport.ts`) don't reinvent it.** Pass `opts.label` / `opts.type` to enrich the on-call diagnostic emitted* when the binding returns non-OK — e.g. `{ label: userId, type: message.type }`.@@ -24,72 +26,12 @@ export async function wsDoFetch(init: RequestInit,opts?: { label?: string; type?: string },): Promise<Response> {- // Try service binding first.- const binding = env.WS_DO_WORKER- let bindingAttempted = false- if (binding) {- bindingAttempted = true- try {- const res = await binding.fetch(`http://internal${path}`, init)- if (res.ok) return res- // 4xx = client error — don't retry; fallback will return the same status.- if (res.status >= 400 && res.status < 500) {- log.warn("broadcast service-binding non-ok (client-error)", {- label: opts?.label,- type: opts?.type,- path,- status: res.status,- })- return res- }- // 5xx — fall through to HTTP fallback so the message isn't silently dropped.- log.warn("broadcast service-binding non-ok", {- label: opts?.label,- type: opts?.type,- path,- status: res.status,- })- } catch (err) {- log.warn("broadcast service-binding threw, falling back", {- label: opts?.label,- type: opts?.type,- path,- err: String(err),- })- }- }-- // HTTP fallback.- const base = env.DEV_WS_DO_URL || DEV_WS_DO_URL- try {- const res = await fetch(`${base}${path}`, init)- if (!res.ok) {- log.error("broadcast HTTP fallback non-ok", {- label: opts?.label,- type: opts?.type,- path,- status: res.status,- url: base,- })- } else if (bindingAttempted) {- // Only meaningful when the fallback rescued a failed binding call.- log.info("broadcast HTTP fallback recovered", {- label: opts?.label,- type: opts?.type,- path,- })- }- return res- } catch (err) {- log.error("broadcast HTTP fallback threw", {- label: opts?.label,- type: opts?.type,- path,- url: base,- err: String(err),- })- throw err- }+ return fetchViaBindingOrDevFallback(env.WS_DO_WORKER, env.DEV_WS_DO_URL || DEV_WS_DO_URL, path, init, {+ logPrefix: "broadcast",+ log,+ label: opts?.label,+ type: opts?.type,+ })}async function doSend(@@ -118,11 +60,11 @@ function sendBroadcast(url: string, body: string, opts: { label: string; type: sconst promise = doSend(url, body, opts)try {const { ctx } = getCloudflareContext()- ctx.waitUntil(promise.catch(() => {}))+ ctx.waitUntil(promise.catch(() => { }))} catch {// Not in CF context — promise runs on its own}- return promise.then(() => {})+ return promise.then(() => { })}export function broadcastToUser(userId: string, message: WsMessage): Promise<void> {@@ -144,7 +86,7 @@ export function broadcastToDaemon(daemonId: string, message: DaemonPushMessage):// CF worker may terminate before the fetch completes if the response is sent early;// waitUntil keeps the isolate alive until the broadcast resolves.const { ctx } = getCloudflareContext()- ctx.waitUntil(promise.catch(() => {}))+ ctx.waitUntil(promise.catch(() => { }))} catch {// Not in CF context — promise runs on its own}diff --git a/src/web/src/lib/community/fanout.test.ts b/src/web/src/lib/community/fanout.test.tsindex f4e9ccd39..b6ee6d8fe 100644--- a/src/web/src/lib/community/fanout.test.ts+++ b/src/web/src/lib/community/fanout.test.ts@@ -115,13 +115,11 @@ describe("fanOutToServerMembers", () => {})})-describe("wake dispatch (plan §8) — only fires for MESSAGE_CREATE with a wakeMessageRow", () => {+describe("wake dispatch (minimal-wake-queue-unread-notice) — only fires for MESSAGE_CREATE with a wakeMessageRow", () => {const wakeMessageRow = {id: "msg_1",seq: 7,authorId: "u1",- content: "hello",- createdAt: "2026-01-01T00:00:00.000Z",channelId: "c1",dmConversationId: null,}diff --git a/src/web/src/lib/community/message-handler.ts b/src/web/src/lib/community/message-handler.tsindex 537202c4b..1aac42e9a 100644--- a/src/web/src/lib/community/message-handler.ts+++ b/src/web/src/lib/community/message-handler.ts@@ -276,17 +276,17 @@ export async function createCommunityMessage(params: {})),})- // Wake-dispatch row (plan §8) — the same `row` already fetched above via- // `getMessage` (which now selects `seq`). Passed alongside the- // MESSAGE_CREATE event so `fanOutToChannel`/`fanOutToDM` can enqueue bot- // wakes using the SAME recipient list already resolved for the human-WS- // broadcast, no second membership query.+ // Wake-dispatch row (minimal-wake-queue-unread-notice plan §1/§5) — the+ // same `row` already fetched above via `getMessage` (which now selects+ // `seq`). Passed alongside the MESSAGE_CREATE event so+ // `fanOutToChannel`/`fanOutToDM` can enqueue bot wakes using the SAME+ // recipient list already resolved for the human-WS broadcast, no second+ // membership query. Deliberately no `content`/`createdAt` — the queue+ // payload only ever carries `{ messageId, botUserId }`.const wakeMessageRow = {id: row.id,seq: row.seq,authorId: row.authorId,- content: row.content,- createdAt: row.createdAt,channelId: row.channelId,dmConversationId: row.dmConversationId,}diff --git a/src/web/src/lib/community/wake-producer.test.ts b/src/web/src/lib/community/wake-producer.test.tsindex 97785781d..cf1e67271 100644--- a/src/web/src/lib/community/wake-producer.test.ts+++ b/src/web/src/lib/community/wake-producer.test.ts@@ -1,44 +1,52 @@-import { describe, it, expect, vi, beforeEach } from "vitest"+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"const mockCtxWaitUntil = vi.fn((p: Promise<unknown>) => p)const mockGetCloudflareContext = vi.fn(() => ({- env: { DB: {}, WAKE_QUEUE: { sendBatch: mockSendBatch } },+ env: { DB: {}, WAKE_QUEUE: { __queue: true } },ctx: { waitUntil: mockCtxWaitUntil },}))vi.mock("@opennextjs/cloudflare", () => ({getCloudflareContext: (...a: unknown[]) => mockGetCloudflareContext(...(a as [])),}))-const mockSendBatch = vi.fn(async () => { })const mockFindWakeCandidates = vi.fn()-const mockToAgentMessage = vi.fn()const mockWarn = vi.fn()+const mockInfo = vi.fn()vi.mock("@alook/shared", async () => {const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")return {...actual,createDb: vi.fn(() => ({})),- createLogger: () => ({ info: vi.fn(), warn: (...a: unknown[]) => mockWarn(...a), error: vi.fn(), debug: vi.fn() }),+ createLogger: () => ({+ info: (...a: unknown[]) => mockInfo(...a),+ warn: (...a: unknown[]) => mockWarn(...a),+ error: vi.fn(),+ debug: vi.fn(),+ }),queries: {communityBot: {findWakeCandidates: (...a: unknown[]) => mockFindWakeCandidates(...a),},- communityAgentInbox: {- toAgentMessage: (...a: unknown[]) => mockToAgentMessage(...a),- },},}})+const mockQueueSend = vi.fn()+const mockDevHttpSend = vi.fn()+const mockCreateQueueWakeTransport = vi.fn(() => ({ send: mockQueueSend }))+const mockCreateDevHttpWakeTransport = vi.fn(() => ({ send: mockDevHttpSend }))+vi.mock("./wake-transport", () => ({+ createQueueWakeTransport: (...a: unknown[]) => mockCreateQueueWakeTransport(...a),+ createDevHttpWakeTransport: (...a: unknown[]) => mockCreateDevHttpWakeTransport(...a),+}))+import { enqueueBotWakes } from "./wake-producer"const messageRow = {id: "msg_1",seq: 7,authorId: "human_1",- content: "hello",- createdAt: "2026-01-01T00:00:00.000Z",channelId: "c1",dmConversationId: null,}@@ -46,32 +54,27 @@ const messageRow = {describe("enqueueBotWakes", () => {beforeEach(() => {vi.clearAllMocks()- mockSendBatch.mockResolvedValue(undefined)- mockToAgentMessage.mockResolvedValue({- seq: "#7",- channel: "/studio/general",- sender: "@human",- content: { text: "hello" },- time: messageRow.createdAt,- })+ mockQueueSend.mockResolvedValue(undefined)+ mockDevHttpSend.mockResolvedValue(undefined)})- it("no-ops when recipients is empty — never queries or enqueues", async () => {+ it("no-ops when recipients is empty — never queries or picks a transport", async () => {await enqueueBotWakes({ recipients: [], channelId: "c1", messageRow })expect(mockFindWakeCandidates).not.toHaveBeenCalled()- expect(mockSendBatch).not.toHaveBeenCalled()+ expect(mockCreateQueueWakeTransport).not.toHaveBeenCalled()+ expect(mockCreateDevHttpWakeTransport).not.toHaveBeenCalled()})- it("no-ops when no candidates are behind — zero sendBatch calls, not an empty one", async () => {+ it("no-ops when no candidates are behind — zero transport.send calls, not an empty one", async () => {mockFindWakeCandidates.mockResolvedValue([])await enqueueBotWakes({ recipients: ["bot1"], channelId: "c1", messageRow })- expect(mockSendBatch).not.toHaveBeenCalled()+ expect(mockQueueSend).not.toHaveBeenCalled()})- it("builds a HostCommand per candidate and sends a single batch", async () => {+ it("builds a minimal { messageId, botUserId } payload per candidate and sends a single batch via the queue transport", async () => {mockFindWakeCandidates.mockResolvedValue([{ botUserId: "bot1", name: "zoe", machineId: "m1", runtime: "claude" },{ botUserId: "bot2", name: "kai", machineId: "m2", runtime: "codex" },@@ -83,38 +86,17 @@ describe("enqueueBotWakes", () => {{},{ recipients: ["bot1", "bot2"], channelId: "c1", dmConversationId: undefined, newSeq: 7 },)- expect(mockSendBatch).toHaveBeenCalledTimes(1)- const [messages] = mockSendBatch.mock.calls[0]!- expect(messages).toHaveLength(2)- expect(messages[0].body.botUserId).toBe("bot1")- expect(messages[0].body.machineId).toBe("m1")- expect(messages[0].body.command.type).toBe("agent:start")- expect(messages[0].body.command.agentId).toBe("bot1")- expect(messages[0].body.command.config.runtime).toBe("claude")- expect(messages[0].body.command.wakeMessage).toEqual({- seq: "#7",- channel: "/studio/general",- sender: "@human",- content: { text: "hello" },- time: messageRow.createdAt,- })- expect(messages[1].body.botUserId).toBe("bot2")- })-- it("hydrates wakeMessage once (viewer = first candidate), not once per candidate", async () => {- mockFindWakeCandidates.mockResolvedValue([- { botUserId: "bot1", name: "zoe", machineId: "m1", runtime: "claude" },- { botUserId: "bot2", name: "kai", machineId: "m2", runtime: "codex" },- { botUserId: "bot3", name: "ivy", machineId: "m3", runtime: "gemini" },+ expect(mockCreateQueueWakeTransport).toHaveBeenCalledTimes(1)+ expect(mockCreateDevHttpWakeTransport).not.toHaveBeenCalled()+ expect(mockQueueSend).toHaveBeenCalledTimes(1)+ const [payloads] = mockQueueSend.mock.calls[0]!+ expect(payloads).toEqual([+ { messageId: "msg_1", botUserId: "bot1" },+ { messageId: "msg_1", botUserId: "bot2" },])-- await enqueueBotWakes({ recipients: ["bot1", "bot2", "bot3"], channelId: "c1", messageRow })-- expect(mockToAgentMessage).toHaveBeenCalledTimes(1)- expect(mockToAgentMessage).toHaveBeenCalledWith({}, { ...messageRow, content: "hello" }, "bot1")})- it("chunks into 100-message sendBatch slices for large fanouts", async () => {+ it("chunks into 100-candidate slices for large fanouts", async () => {const candidates = Array.from({ length: 250 }, (_, i) => ({botUserId: `bot${i}`,name: `bot${i}`,@@ -129,13 +111,13 @@ describe("enqueueBotWakes", () => {messageRow,})- expect(mockSendBatch).toHaveBeenCalledTimes(3)- expect(mockSendBatch.mock.calls[0]![0]).toHaveLength(100)- expect(mockSendBatch.mock.calls[1]![0]).toHaveLength(100)- expect(mockSendBatch.mock.calls[2]![0]).toHaveLength(50)+ expect(mockQueueSend).toHaveBeenCalledTimes(3)+ expect(mockQueueSend.mock.calls[0]![0]).toHaveLength(100)+ expect(mockQueueSend.mock.calls[1]![0]).toHaveLength(100)+ expect(mockQueueSend.mock.calls[2]![0]).toHaveLength(50)})- it("partial chunk failure: sibling chunks still enqueue, failure is logged, call does not throw", async () => {+ it("partial chunk failure: sibling chunks still send, failure is logged, call does not throw", async () => {const candidates = Array.from({ length: 250 }, (_, i) => ({botUserId: `bot${i}`,name: `bot${i}`,@@ -143,7 +125,7 @@ describe("enqueueBotWakes", () => {runtime: "claude",}))mockFindWakeCandidates.mockResolvedValue(candidates)- mockSendBatch+ mockQueueSend.mockResolvedValueOnce(undefined).mockRejectedValueOnce(new Error("queue unavailable")).mockResolvedValueOnce(undefined)@@ -152,7 +134,7 @@ describe("enqueueBotWakes", () => {enqueueBotWakes({ recipients: candidates.map((c) => c.botUserId), channelId: "c1", messageRow }),).resolves.toBeUndefined()- expect(mockSendBatch).toHaveBeenCalledTimes(3)+ expect(mockQueueSend).toHaveBeenCalledTimes(3)expect(mockWarn).toHaveBeenCalledWith("wake_batch_chunk_failed",expect.objectContaining({@@ -174,7 +156,7 @@ describe("enqueueBotWakes", () => {it("falls back to running standalone (no throw) when not in a CF request context", async () => {mockGetCloudflareContext.mockImplementationOnce(() => ({- env: { DB: {}, WAKE_QUEUE: { sendBatch: mockSendBatch } },+ env: { DB: {}, WAKE_QUEUE: { __queue: true } },ctx: { waitUntil: () => { throw new Error("no request context") } },}))mockFindWakeCandidates.mockResolvedValue([])@@ -182,3 +164,50 @@ describe("enqueueBotWakes", () => {await expect(enqueueBotWakes({ recipients: ["bot1"], channelId: "c1", messageRow })).resolves.toBeUndefined()})})++describe("enqueueBotWakes — dev HTTP transport selection (NODE_ENV=development)", () => {+ const originalNodeEnv = process.env.NODE_ENV++ beforeEach(() => {+ vi.clearAllMocks()+ mockQueueSend.mockResolvedValue(undefined)+ mockDevHttpSend.mockResolvedValue(undefined)+ process.env.NODE_ENV = "development"+ })++ afterEach(() => {+ process.env.NODE_ENV = originalNodeEnv+ })++ it("picks the dev HTTP transport instead of the queue transport", async () => {+ mockFindWakeCandidates.mockResolvedValue([+ { botUserId: "bot1", name: "zoe", machineId: "m1", runtime: "claude" },+ { botUserId: "bot2", name: "kai", machineId: "m2", runtime: "codex" },+ ])++ await enqueueBotWakes({ recipients: ["bot1", "bot2"], channelId: "c1", messageRow })++ expect(mockCreateDevHttpWakeTransport).toHaveBeenCalledTimes(1)+ expect(mockCreateQueueWakeTransport).not.toHaveBeenCalled()+ expect(mockDevHttpSend).toHaveBeenCalledTimes(1)+ expect(mockQueueSend).not.toHaveBeenCalled()+ expect(mockDevHttpSend).toHaveBeenCalledWith([+ { messageId: "msg_1", botUserId: "bot1" },+ { messageId: "msg_1", botUserId: "bot2" },+ ])+ })++ it("logs and does not throw when the dev HTTP transport rejects", async () => {+ mockFindWakeCandidates.mockResolvedValue([{ botUserId: "bot1", name: "zoe", machineId: "m1", runtime: "claude" }])+ mockDevHttpSend.mockRejectedValue(new Error("alook-wake-worker unreachable"))++ await expect(+ enqueueBotWakes({ recipients: ["bot1"], channelId: "c1", messageRow }),+ ).resolves.toBeUndefined()++ expect(mockWarn).toHaveBeenCalledWith(+ "wake_batch_chunk_failed",+ expect.objectContaining({ err: expect.stringContaining("alook-wake-worker unreachable") }),+ )+ })+})diff --git a/src/web/src/lib/community/wake-producer.ts b/src/web/src/lib/community/wake-producer.tsindex 459b70bb6..77893d76c 100644--- a/src/web/src/lib/community/wake-producer.ts+++ b/src/web/src/lib/community/wake-producer.ts@@ -1,30 +1,42 @@/**- * Push-wake producer (plan §8) — after a message lands and the human-WS- * fanout has broadcast it, this filters the fanout's recipient set down to- * "bots that are actually behind on this scope" and enqueues one- * `WAKE_QUEUE` payload per candidate, each carrying a fully-built- * `HostCommand` (`agent:start`). The `alook-wake-worker` consumer (separate- * deploy unit) is a dumb forwarder with no D1 access — all the D1-backed- * construction (bot name/runtime/machine, `toAgentMessage` hydration)- * happens HERE, where the D1 binding actually lives.+ * Push-wake producer — after a message lands and the human-WS fanout has+ * broadcast it, this filters the fanout's recipient set down to "bots that+ * are actually behind on this scope" and hands one minimal `{ messageId,+ * botUserId }` payload per candidate off to a `WakeTransport`+ * (minimal-wake-queue-unread-notice plan §1/§5). Deliberately carries NO+ * `HostCommand`, `machineId`, runtime, or message content — the consumer+ * (real `alook-wake-worker`, in both transports — see `wake-transport.ts`)+ * rebuilds the `agent:wake` command from CURRENT D1 state at consume time+ * (`dispatchOneUnreadWake`/`buildUnreadWakeCommand`), so a stale item never+ * wakes an old machine or carries stale content.+ *+ * This module owns ONLY "who are the candidates" — it never talks to+ * `WAKE_QUEUE`/`WAKE_WORKER` directly and never re-implements what happens+ * to a candidate. See `wake-transport.ts` for which transport runs in which+ * environment and why (local Cloudflare Queues can't bridge separate+ * `wrangler dev`/`next dev` processes today).*/import { getCloudflareContext } from "@opennextjs/cloudflare"-import { createDb, queries, createLogger, makeRuntimeConfig } from "@alook/shared"-import type { HostCommand, WakePayload } from "@alook/shared"-import { nanoid } from "nanoid"+import { createDb, queries, createLogger } from "@alook/shared"+import type { WakePayload } from "@alook/shared"+import { createQueueWakeTransport, createDevHttpWakeTransport } from "./wake-transport"+import type { WakeTransport } from "./wake-transport"const log = createLogger({ service: "community-wake-producer" })-// Cloudflare Queues caps a single `sendBatch` call at 100 messages.-const QUEUE_BATCH_SIZE = 100+// Cloudflare Queues caps a single `sendBatch` call at 100 messages; kept the+// same batch size for the dev HTTP transport for a uniform code path.+const WAKE_BATCH_SIZE = 100-/** The just-inserted message row — must include `seq` (see `getMessage`'s select). */+/**+ * The just-inserted message row — lean, no body/preview (plan §1/§5): only+ * what `findWakeCandidates`' unread filter needs. Must include `seq` (see+ * `getMessage`'s select).+ */export interface WakeMessageRow {id: stringseq: numberauthorId: string- content: string | null- createdAt: stringchannelId: string | nulldmConversationId: string | null}@@ -43,7 +55,7 @@ export interface EnqueueBotWakesOpts {* context and registers `ctx.waitUntil(...)` synchronously in its own first* tick (before any `await`), so the enclosing request's response can be* written and the isolate can still be kept alive long enough for the- * `sendBatch` calls to land. Callers MUST invoke this before the response is+ * transport call to land. Callers MUST invoke this before the response is* sent (same requirement as `broadcastToUser`/`fanOutToChannel`) — calling it* after the response has already been returned risks the `waitUntil`* registration being dropped.@@ -62,6 +74,18 @@ export function enqueueBotWakes(opts: EnqueueBotWakesOpts): Promise<void> {return promise}+/**+ * `NODE_ENV === "development"` (never `test`, `production`, or an+ * opennextjs-cloudflare preview/deploy build — all of which set `NODE_ENV`+ * to something else) is the only case that gets the dev HTTP transport;+ * every other environment keeps the real Cloudflare Queue.+ */+function selectWakeTransport(env: Env): WakeTransport {+ return process.env.NODE_ENV === "development"+ ? createDevHttpWakeTransport(env)+ : createQueueWakeTransport(env.WAKE_QUEUE)+}+async function doEnqueueBotWakes(env: Env, opts: EnqueueBotWakesOpts): Promise<void> {const { recipients, channelId, dmConversationId, messageRow } = optsif (recipients.length === 0) return@@ -75,45 +99,18 @@ async function doEnqueueBotWakes(env: Env, opts: EnqueueBotWakesOpts): Promise<v})if (candidates.length === 0) return- // Channel refs don't depend on `viewerId` at all; DM refs do, but a DM- // scope only ever has (at most) one bot candidate since a DM has exactly- // two participants — either way, hydrating once with the first- // candidate's identity is correct and avoids N redundant DB round-trips.- const wakeMessage = await queries.communityAgentInbox.toAgentMessage(- db,- { ...messageRow, content: messageRow.content ?? "" },- candidates[0]!.botUserId- )-- const payloads: WakePayload[] = candidates.map((c) => {- // Known, accepted gap (plan §8): `community_bot_binding` stores only a- // bare `runtime` string today — no model/mode/provider/instruction- // columns exist yet. Bots wake with runtime-default model/mode and no- // custom instruction until a future "bot profile config" feature adds- // those columns; this is not an oversight.- const config = makeRuntimeConfig({- runtime: c.runtime,- agentName: c.name ?? c.botUserId,- agentHandle: `@${c.name ?? c.botUserId}`,- })- const command: HostCommand = {- type: "agent:start",- agentId: c.botUserId,- config,- launchId: nanoid(),- wakeMessage,- }- return { botUserId: c.botUserId, machineId: c.machineId, command }- })+ const payloads: WakePayload[] = candidates.map((c) => ({+ messageId: messageRow.id,+ botUserId: c.botUserId,+ }))const chunks: WakePayload[][] = []- for (let i = 0; i < payloads.length; i += QUEUE_BATCH_SIZE) {- chunks.push(payloads.slice(i, i + QUEUE_BATCH_SIZE))+ for (let i = 0; i < payloads.length; i += WAKE_BATCH_SIZE) {+ chunks.push(payloads.slice(i, i + WAKE_BATCH_SIZE))}- const results = await Promise.allSettled(- chunks.map((chunk) => env.WAKE_QUEUE.sendBatch(chunk.map((body) => ({ body }))))- )+ const transport = selectWakeTransport(env)+ const results = await Promise.allSettled(chunks.map((chunk) => transport.send(chunk)))for (let i = 0; i < results.length; i++) {const r = results[i]!if (r.status === "rejected") {diff --git a/src/web/src/lib/community/wake-transport.test.ts b/src/web/src/lib/community/wake-transport.test.tsnew file mode 100644index 000000000..641a04da3--- /dev/null+++ b/src/web/src/lib/community/wake-transport.test.ts@@ -0,0 +1,109 @@+import { describe, it, expect, vi, beforeEach, afterAll } from "vitest"++const mockInfo = vi.fn()+const mockWarn = vi.fn()+const mockError = vi.fn()++vi.mock("@alook/shared", async () => {+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")+ return {+ ...actual,+ createLogger: () => ({+ info: (...a: unknown[]) => mockInfo(...a),+ warn: (...a: unknown[]) => mockWarn(...a),+ error: (...a: unknown[]) => mockError(...a),+ debug: vi.fn(),+ }),+ }+})++import { createQueueWakeTransport, createDevHttpWakeTransport } from "./wake-transport"++const payloads = [+ { messageId: "msg_1", botUserId: "bot1" },+ { messageId: "msg_1", botUserId: "bot2" },+]++describe("createQueueWakeTransport", () => {+ it("sends the payloads as a single sendBatch call, one body per candidate", async () => {+ const mockSendBatch = vi.fn(async () => { })+ const transport = createQueueWakeTransport({ sendBatch: mockSendBatch } as unknown as Queue<unknown>)++ await transport.send(payloads)++ expect(mockSendBatch).toHaveBeenCalledTimes(1)+ const [messages] = mockSendBatch.mock.calls[0]!+ expect(messages).toEqual([{ body: payloads[0] }, { body: payloads[1] }])+ })++ it("propagates a sendBatch rejection (caller decides how to handle per-chunk failure)", async () => {+ const mockSendBatch = vi.fn(async () => { throw new Error("queue unavailable") })+ const transport = createQueueWakeTransport({ sendBatch: mockSendBatch } as unknown as Queue<unknown>)++ await expect(transport.send(payloads)).rejects.toThrow("queue unavailable")+ })+})++describe("createDevHttpWakeTransport", () => {+ const originalFetch = globalThis.fetch+ const mockGlobalFetch = vi.fn<(...args: unknown[]) => Promise<Response>>()++ beforeEach(() => {+ vi.clearAllMocks()+ globalThis.fetch = mockGlobalFetch as unknown as typeof fetch+ })++ afterAll(() => {+ globalThis.fetch = originalFetch+ })++ function makeEnv(bindingFetch?: (...a: unknown[]) => Promise<Response>) {+ return {+ WAKE_WORKER: bindingFetch ? { fetch: bindingFetch } : undefined,+ DEV_WAKE_WORKER_URL: "http://dev-wake:8790",+ } as unknown as Env+ }++ it("POSTs the full payload batch as JSON to the alook-wake-worker binding", async () => {+ const bindingFetch = vi.fn(async (url: string, init?: RequestInit) => {+ expect(url).toBe("http://internal/")+ expect(init?.method).toBe("POST")+ expect(JSON.parse(init!.body as string)).toEqual(payloads)+ return new Response(null, { status: 202 })+ })+ const transport = createDevHttpWakeTransport(makeEnv(bindingFetch))++ await expect(transport.send(payloads)).resolves.toBeUndefined()+ expect(bindingFetch).toHaveBeenCalledTimes(1)+ expect(mockGlobalFetch).not.toHaveBeenCalled()+ })++ it("falls back to the raw dev HTTP URL when the binding is absent", async () => {+ mockGlobalFetch.mockResolvedValue(new Response(null, { status: 202 }))+ const transport = createDevHttpWakeTransport(makeEnv())++ await transport.send(payloads)++ expect(mockGlobalFetch).toHaveBeenCalledTimes(1)+ expect(String(mockGlobalFetch.mock.calls[0]![0])).toBe("http://dev-wake:8790/")+ })++ it("falls back to HTTP when the binding throws (getPlatformProxy binding unreachable)", async () => {+ const bindingFetch = vi.fn(async () => { throw new Error("binding missing") })+ mockGlobalFetch.mockResolvedValue(new Response(null, { status: 202 }))+ const transport = createDevHttpWakeTransport(makeEnv(bindingFetch))++ await transport.send(payloads)++ expect(bindingFetch).toHaveBeenCalledTimes(1)+ expect(mockGlobalFetch).toHaveBeenCalledTimes(1)+ })++ it("throws when both the binding and the HTTP fallback respond non-OK (caller logs, dev-only best effort)", async () => {+ const bindingFetch = vi.fn(async () => new Response("boom", { status: 500 }))+ mockGlobalFetch.mockResolvedValue(new Response("still bad", { status: 500 }))+ const transport = createDevHttpWakeTransport(makeEnv(bindingFetch))++ await expect(transport.send(payloads)).rejects.toThrow(/500/)+ })+})diff --git a/src/web/src/lib/community/wake-transport.ts b/src/web/src/lib/community/wake-transport.tsnew file mode 100644index 000000000..832f82a1d--- /dev/null+++ b/src/web/src/lib/community/wake-transport.ts@@ -0,0 +1,62 @@+import { createLogger, DEV_WAKE_WORKER_URL } from "@alook/shared"+import type { WakePayload } from "@alook/shared"+import { fetchViaBindingOrDevFallback } from "../dev-binding-fetch"++const log = createLogger({ service: "wake-transport" })++/**+ * How `enqueueBotWakes` hands a batch of wake candidates off to whatever+ * will actually resolve them. Exactly two implementations below — neither+ * caller (`wake-producer.ts`) ever talks to `WAKE_QUEUE`/`WAKE_WORKER`+ * directly, and neither ever re-implements "rebuild from D1, skip or+ * forward" (that logic lives once, in `@alook/shared`'s+ * `dispatchOneUnreadWake`, and is exercised by whichever transport actually+ * runs it).+ */+export interface WakeTransport {+ send(payloads: WakePayload[]): Promise<void>+}++/** Production (and any non-`development` environment): the real Cloudflare Queue. */+export function createQueueWakeTransport(queue: Queue<WakePayload>): WakeTransport {+ return {+ async send(payloads) {+ await queue.sendBatch(payloads.map((body) => ({ body })))+ },+ }+}++/**+ * Dev-only. Local Cloudflare Queues simulation cannot bridge separate+ * `wrangler dev`/`next dev` processes (plans/minimal-wake-queue-unread-notice.md)+ * — every `WAKE_QUEUE.sendBatch()` call from `next dev` lands nowhere. This+ * transport instead calls the REAL `alook-wake-worker` process directly over+ * HTTP (its `fetch()` dev entrypoint, see `src/wake-worker/src/index.ts`),+ * via the `WAKE_WORKER` service binding with the same binding-first/+ * HTTP-fallback reliability pattern `broadcast.ts` uses for `WS_DO_WORKER`+ * (`next dev`'s `getPlatformProxy` service bindings to separately-run+ * `wrangler dev` workers are not reliably reachable on their own). The+ * candidate then gets resolved by `alook-wake-worker`'s own process, against+ * the real D1 database, with a real forward to `alook-ws-do` — the actual+ * production code path, not a local stand-in for it.+ */+export function createDevHttpWakeTransport(env: Env): WakeTransport {+ return {+ async send(payloads) {+ const res = await fetchViaBindingOrDevFallback(+ env.WAKE_WORKER,+ env.DEV_WAKE_WORKER_URL || DEV_WAKE_WORKER_URL,+ "/",+ {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify(payloads),+ },+ { logPrefix: "wake_transport", log, label: `${payloads.length}_candidates` },+ )+ if (!res.ok) {+ throw new Error(`dev wake transport: alook-wake-worker responded ${res.status}`)+ }+ },+ }+}diff --git a/src/web/src/lib/dev-binding-fetch.test.ts b/src/web/src/lib/dev-binding-fetch.test.tsnew file mode 100644index 000000000..4ccfd7fa1--- /dev/null+++ b/src/web/src/lib/dev-binding-fetch.test.ts@@ -0,0 +1,99 @@+import { describe, it, expect, vi, beforeEach, afterAll } from "vitest"+import { Logger } from "@alook/shared"+import { fetchViaBindingOrDevFallback } from "./dev-binding-fetch"++const originalFetch = globalThis.fetch+const mockFetch = vi.fn<(...args: unknown[]) => Promise<Response>>()+const log = new Logger({ service: "test", level: "silent" })++beforeEach(() => {+ vi.clearAllMocks()+ globalThis.fetch = mockFetch as unknown as typeof fetch+})++afterAll(() => {+ globalThis.fetch = originalFetch+})++describe("fetchViaBindingOrDevFallback", () => {+ it("returns the binding response directly when it is OK", async () => {+ const bindingFetch = vi.fn(async () => new Response("ok", { status: 200 }))++ const res = await fetchViaBindingOrDevFallback(+ { fetch: bindingFetch },+ "http://dev:1234",+ "/x",+ { method: "POST" },+ { logPrefix: "test", log },+ )++ expect(res.status).toBe(200)+ expect(bindingFetch).toHaveBeenCalledWith("http://internal/x", { method: "POST" })+ expect(mockFetch).not.toHaveBeenCalled()+ })++ it("returns the binding's 4xx as-is without trying the HTTP fallback", async () => {+ const bindingFetch = vi.fn(async () => new Response("nope", { status: 404 }))++ const res = await fetchViaBindingOrDevFallback(+ { fetch: bindingFetch },+ "http://dev:1234",+ "/x",+ { method: "POST" },+ { logPrefix: "test", log },+ )++ expect(res.status).toBe(404)+ expect(mockFetch).not.toHaveBeenCalled()+ })++ it("falls back to the raw URL when the binding throws", async () => {+ const bindingFetch = vi.fn(async () => { throw new Error("no binding") })+ mockFetch.mockResolvedValue(new Response("ok", { status: 200 }))++ const res = await fetchViaBindingOrDevFallback(+ { fetch: bindingFetch },+ "http://dev:1234",+ "/x",+ { method: "POST" },+ { logPrefix: "test", log },+ )++ expect(res.status).toBe(200)+ expect(String(mockFetch.mock.calls[0]![0])).toBe("http://dev:1234/x")+ })++ it("falls back to the raw URL on a binding 5xx", async () => {+ const bindingFetch = vi.fn(async () => new Response("boom", { status: 502 }))+ mockFetch.mockResolvedValue(new Response("ok", { status: 200 }))++ const res = await fetchViaBindingOrDevFallback(+ { fetch: bindingFetch },+ "http://dev:1234",+ "/x",+ { method: "POST" },+ { logPrefix: "test", log },+ )++ expect(res.status).toBe(200)+ expect(mockFetch).toHaveBeenCalledTimes(1)+ })++ it("goes straight to the fallback URL when no binding is passed", async () => {+ mockFetch.mockResolvedValue(new Response("ok", { status: 200 }))++ const res = await fetchViaBindingOrDevFallback(undefined, "http://dev:1234", "/x", { method: "GET" }, { logPrefix: "test", log })++ expect(res.status).toBe(200)+ expect(String(mockFetch.mock.calls[0]![0])).toBe("http://dev:1234/x")+ })++ it("rethrows when both the binding and the fallback fail", async () => {+ const bindingFetch = vi.fn(async () => { throw new Error("no binding") })+ mockFetch.mockRejectedValue(new Error("network down"))++ await expect(+ fetchViaBindingOrDevFallback({ fetch: bindingFetch }, "http://dev:1234", "/x", { method: "POST" }, { logPrefix: "test", log }),+ ).rejects.toThrow("network down")+ })+})diff --git a/src/web/src/lib/dev-binding-fetch.ts b/src/web/src/lib/dev-binding-fetch.tsnew file mode 100644index 000000000..848a996aa--- /dev/null+++ b/src/web/src/lib/dev-binding-fetch.ts@@ -0,0 +1,60 @@+import type { Logger } from "@alook/shared"++interface FetcherLike {+ fetch(input: string, init?: RequestInit): Promise<Response>+}++/**+ * Service-binding-first, dev-HTTP-fallback fetch. Extracted from+ * `broadcast.ts`'s original `wsDoFetch` (that's still the canonical+ * caller/behavior spec — see its tests) because `wake-transport.ts` needs+ * the EXACT same shape of fallback for `WAKE_WORKER`: `next dev`'s+ * `getPlatformProxy` service bindings to separately-run `wrangler dev`+ * workers are not reliably reachable, so every cross-worker call from+ * `src/web` needs "try the real binding, fall back to a plain HTTP URL at+ * the worker's `[dev] port`" — never duplicate this decision tree per+ * binding.+ *+ * Falls back to `fallbackBaseUrl` when the binding is absent, throws, or+ * returns a 5xx. Never falls back on a 4xx (client error — the caller's+ * request was bad, retrying via HTTP won't help, and would just hide the+ * real error behind a second, unrelated one).+ */+export async function fetchViaBindingOrDevFallback(+ binding: FetcherLike | undefined,+ fallbackBaseUrl: string,+ path: string,+ init: RequestInit,+ opts: { logPrefix: string; log: Logger; label?: string; type?: string },+): Promise<Response> {+ const { logPrefix, log, label, type } = opts+ let bindingAttempted = false++ if (binding) {+ bindingAttempted = true+ try {+ const res = await binding.fetch(`http://internal${path}`, init)+ if (res.ok) return res+ if (res.status >= 400 && res.status < 500) {+ log.warn(`${logPrefix} service-binding non-ok (client-error)`, { label, type, path, status: res.status })+ return res+ }+ log.warn(`${logPrefix} service-binding non-ok`, { label, type, path, status: res.status })+ } catch (err) {+ log.warn(`${logPrefix} service-binding threw, falling back`, { label, type, path, err: String(err) })+ }+ }++ try {+ const res = await fetch(`${fallbackBaseUrl}${path}`, init)+ if (!res.ok) {+ log.error(`${logPrefix} HTTP fallback non-ok`, { label, type, path, status: res.status, url: fallbackBaseUrl })+ } else if (bindingAttempted) {+ log.info(`${logPrefix} HTTP fallback recovered`, { label, type, path })+ }+ return res+ } catch (err) {+ log.error(`${logPrefix} HTTP fallback threw`, { label, type, path, url: fallbackBaseUrl, err: String(err) })+ throw err+ }+}diff --git a/src/web/wrangler.toml b/src/web/wrangler.tomlindex c6a966ab4..cdbcc9495 100644--- a/src/web/wrangler.toml+++ b/src/web/wrangler.toml@@ -77,6 +77,15 @@ service = "alook-email-worker"binding = "WAKE_QUEUE"queue = "alook-wake"+# Dev-only direct path to the `alook-wake-worker` HTTP dev endpoint — local+# Cloudflare Queues can't bridge separate `wrangler dev`/`next dev` processes+# (see plans/minimal-wake-queue-unread-notice.md), so `wake-transport.ts` uses+# this binding (with an HTTP fallback, like `WS_DO_WORKER`) instead of+# `WAKE_QUEUE` when `NODE_ENV === "development"`. Unused in production.+[[services]]+binding = "WAKE_WORKER"+service = "alook-wake-worker"+[[kv_namespaces]]binding = "RATE_LIMIT_KV"id = "a3d035bea7bc49d99377b82ec21ce4c1"diff --git a/src/ws-do/src/index.test.ts b/src/ws-do/src/index.test.tsindex d3123fc49..028df0dfb 100644--- a/src/ws-do/src/index.test.ts+++ b/src/ws-do/src/index.test.ts@@ -262,16 +262,16 @@ describe("ws-do router", () => {})})- describe("POST /community-machine/by-id/:machineId/forward-agent-start", () => {+ describe("POST /community-machine/by-id/:machineId/forward-agent-wake", () => {beforeEach(() => {mockGetActiveDoNamesForMachine.mockReset()mockGetActiveDoNamesForMachine.mockResolvedValue([])})it("zero active doNames → { sent: 0 } without touching any DO", async () => {- const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-start", {+ const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-wake", {method: "POST",- body: JSON.stringify({ type: "agent:start" }),+ body: JSON.stringify({ type: "agent:wake" }),})const res = await handler.fetch(req, env as any)@@ -285,16 +285,16 @@ describe("ws-do router", () => {mockGetActiveDoNamesForMachine.mockResolvedValue(["do-abc"])doMock.stubFetch.mockResolvedValue(new Response(JSON.stringify({ sent: 1 }), { status: 200 }))- const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-start", {+ const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-wake", {method: "POST",headers: { "content-type": "application/json" },- body: JSON.stringify({ type: "agent:start", agentId: "bot-1" }),+ body: JSON.stringify({ type: "agent:wake", agentId: "bot-1" }),})const res = await handler.fetch(req, env as any)expect(doMock.idFromName).toHaveBeenCalledWith("community-machine:do-abc")const stubReq = doMock.stubFetch.mock.calls[0][0] as Request- expect(stubReq.url).toBe("http://internal/forward-agent-start")+ expect(stubReq.url).toBe("http://internal/forward-agent-wake")expect(res.status).toBe(200)expect(await res.json()).toEqual({ sent: 1 })})@@ -303,9 +303,9 @@ describe("ws-do router", () => {mockGetActiveDoNamesForMachine.mockResolvedValue(["do-abc"])doMock.stubFetch.mockResolvedValue(new Response(JSON.stringify({ sent: 0 }), { status: 200 }))- const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-start", {+ const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-wake", {method: "POST",- body: JSON.stringify({ type: "agent:start" }),+ body: JSON.stringify({ type: "agent:wake" }),})const res = await handler.fetch(req, env as any)@@ -322,9 +322,9 @@ describe("ws-do router", () => {return Promise.resolve(new Response(JSON.stringify({ sent }), { status: 200 }))})- const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-start", {+ const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-wake", {method: "POST",- body: JSON.stringify({ type: "agent:start" }),+ body: JSON.stringify({ type: "agent:wake" }),})const res = await handler.fetch(req, env as any)@@ -343,9 +343,9 @@ describe("ws-do router", () => {return Promise.resolve(new Response(JSON.stringify({ sent: 1 }), { status: 200 }))})- const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-start", {+ const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-wake", {method: "POST",- body: JSON.stringify({ type: "agent:start" }),+ body: JSON.stringify({ type: "agent:wake" }),})const res = await handler.fetch(req, env as any)@@ -357,14 +357,14 @@ describe("ws-do router", () => {mockGetActiveDoNamesForMachine.mockResolvedValue(["do-a"])doMock.stubFetch.mockRejectedValue(new Error("network error"))- const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-start", {+ const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-wake", {method: "POST",- body: JSON.stringify({ type: "agent:start" }),+ body: JSON.stringify({ type: "agent:wake" }),})const res = await handler.fetch(req, env as any)expect(res.status).toBe(503)- expect(await res.json()).toEqual({ error: "failed to forward agent start" })+ expect(await res.json()).toEqual({ error: "failed to forward agent wake" })})it("non-2xx or malformed DO responses with no delivery → retryable 503", async () => {@@ -376,22 +376,22 @@ describe("ws-do router", () => {return Promise.resolve(new Response(JSON.stringify({ sent: "bad" }), { status: 200 }))})- const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-start", {+ const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-wake", {method: "POST",- body: JSON.stringify({ type: "agent:start" }),+ body: JSON.stringify({ type: "agent:wake" }),})const res = await handler.fetch(req, env as any)expect(res.status).toBe(503)- expect(await res.json()).toEqual({ error: "failed to forward agent start" })+ expect(await res.json()).toEqual({ error: "failed to forward agent wake" })})it("DB lookup failure → retryable 503, not offline { sent: 0 }", async () => {mockGetActiveDoNamesForMachine.mockRejectedValue(new Error("d1 unreachable"))- const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-start", {+ const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-wake", {method: "POST",- body: JSON.stringify({ type: "agent:start" }),+ body: JSON.stringify({ type: "agent:wake" }),})const res = await handler.fetch(req, env as any)diff --git a/src/ws-do/src/index.ts b/src/ws-do/src/index.tsindex 626115454..12f2ab78f 100644--- a/src/ws-do/src/index.ts+++ b/src/ws-do/src/index.ts@@ -134,19 +134,19 @@ export default {return Response.json({ sent: delivered })}- // POST /community-machine/by-id/<machineId>/forward-agent-start — sibling- // of the `/push` route above, for the community-agent-cli-bridge wake- // path (plan §8/§13). Forwards an already-built `HostCommand`- // (`agent:start`) verbatim to every live DO for this machine's active- // credential(s), then aggregates by parsing each DO's own `{ sent: N }`- // response — unlike `/push`, we must NOT just count `res.ok`: a 200 with+ // POST /community-machine/by-id/<machineId>/forward-agent-wake — sibling+ // of the `/push` route above, for the minimal-wake-queue-unread-notice+ // wake path. Forwards an already-built `HostCommand` (`agent:wake`)+ // verbatim to every live DO for this machine's active credential(s),+ // then aggregates by parsing each DO's own `{ sent: N }` response —+ // unlike `/push`, we must NOT just count `res.ok`: a 200 with// `{ sent: 0 }` means that DO has no authenticated daemon socket at all,// which must not be reported as delivered.- const forwardAgentStart = url.pathname.match(/^\/community-machine\/by-id\/([^/]+)\/forward-agent-start$/)- if (forwardAgentStart && request.method === "POST") {- const machineId = decodeURIComponent(forwardAgentStart[1])+ const forwardAgentWake = url.pathname.match(/^\/community-machine\/by-id\/([^/]+)\/forward-agent-wake$/)+ if (forwardAgentWake && request.method === "POST") {+ const machineId = decodeURIComponent(forwardAgentWake[1])const reqLog = log.child({ traceId, machineId })- reqLog.debug("forwarding agent:start to machine")+ reqLog.debug("forwarding agent:wake to machine")let doNames: string[] = []try {@@ -168,7 +168,7 @@ export default {const stub = env.WS_DO.get(doId)try {const res = await stub.fetch(- new Request("http://internal/forward-agent-start", {+ new Request("http://internal/forward-agent-wake", {method: "POST",headers: { "content-type": "application/json" },body: bodyText,@@ -189,7 +189,7 @@ export default {}}if (delivered === 0 && transientFailure) {- return Response.json({ error: "failed to forward agent start" }, { status: 503 })+ return Response.json({ error: "failed to forward agent wake" }, { status: 503 })}return Response.json({ sent: delivered })}diff --git a/src/ws-do/src/ws-durable.ts b/src/ws-do/src/ws-durable.tsindex e20eb5416..86ef7f287 100644--- a/src/ws-do/src/ws-durable.ts+++ b/src/ws-do/src/ws-durable.ts@@ -120,8 +120,8 @@ export class WebSocketDurableObject extends DurableObject<Env> {})}- if (url.pathname === "/forward-agent-start" && request.method === "POST") {- // Forward an `agent:start` frame to the connected daemon and clear+ if (url.pathname === "/forward-agent-wake" && request.method === "POST") {+ // Forward an `agent:wake` frame to the connected daemon and clear// any lastRuntimeError overlay optimistically (with a fan-out) so the// web card stops rendering the stale error immediately. If the daemon// replies with another `session.error`, the overlay is re-stashed on@@ -578,19 +578,23 @@ export class WebSocketDurableObject extends DurableObject<Env> {}// Agent command ack frames — daemon → server reply protocol. New in v0.2.- // `agent_started_ack` / `agent_stopped_ack` / extended `agent_deliver_ack`- // carry `status: "ok" | "error"` + optional `{ code, message }`.- // No persistent write: there is no `communityAgentRuntime` table (checked)- // and adding one is scope creep. Log for observability only; owner-visible- // surfacing goes through the daemon-side error propagation to the bot- // process (which can DM the owner).+ // `agent_wake_ack` means "daemon accepted/handled the wake command," NOT+ // "process started" (a wake may spawn, notify an already-running+ // process, or coalesce for later — see `HostControlChannel.reportWakeAck`).+ // `agent_stopped_ack` carries `status: "ok" | "error"` + optional+ // `{ code, message }`. No persistent write: there is no+ // `communityAgentRuntime` table (checked) and adding one is scope creep.+ // Log for observability only; owner-visible surfacing goes through the+ // daemon-side error propagation to the bot process (which can DM the+ // owner). `agent_deliver_ack` no longer exists — the server never+ // decides start-vs-deliver, so there is nothing for the daemon to ack+ // beyond the wake command itself.if (parsed && typeof parsed === "object" && "type" in parsed &&typeof (parsed as { type: unknown }).type === "string" &&(- (parsed as { type: string }).type === "agent_started_ack" ||- (parsed as { type: string }).type === "agent_stopped_ack" ||- (parsed as { type: string }).type === "agent_deliver_ack"+ (parsed as { type: string }).type === "agent_wake_ack" ||+ (parsed as { type: string }).type === "agent_stopped_ack")) {const ack = parsed as {@@ -706,7 +710,7 @@ export class WebSocketDurableObject extends DurableObject<Env> {/*** Compose a summary + the current DO-local `lastRuntimeError` overlay (if* any). The overlay is transient — cleared optimistically when the DO- * forwards `agent:start` to the daemon, and on `forceClose`.+ * forwards `agent:wake` to the daemon, and on `forceClose`.*/private async summaryWithOverlay(row: Parameters<typeof queries.communityMachine.toSummary>[0]@@ -722,9 +726,9 @@ export class WebSocketDurableObject extends DurableObject<Env> {/*** Send a frame to the connected community-machine daemon (if any). Used by- * `agent:start` forwarding — the community control plane isn't fully wired- * yet, but the surface exists so the eventual emitter routes through here- * (and picks up the optimistic overlay clear for free).+ * `agent:wake` forwarding (minimal-wake-queue-unread-notice plan §3) — the+ * `alook-wake-worker` consumer POSTs an already-built `agent:wake`+ * `HostCommand` to `/forward-agent-wake`, which routes here.*/private forwardToCommunityMachine(message: string): number {let sent = 0@@ -753,7 +757,7 @@ export class WebSocketDurableObject extends DurableObject<Env> {/*** Fan out a fresh `community:machine.updated` for the row + current* overlay state. Used by session.error stash, optimistic clear on- * `agent:start`, and forceClose.+ * `agent:wake`, and forceClose.*/private async fanOutMachineUpdated(userId: string, machineId: string): Promise<void> {const db = createDb(this.env.DB)