Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat: improve sp

Gusbf5b7c80c8fd
diff --git a/src/daemon/README.md b/src/daemon/README.md
index 2407fd1e7..a07d235d0 100644
--- a/src/daemon/README.md
+++ b/src/daemon/README.md
@@ -80,9 +80,11 @@ launched with `--input-format stream-json --output-format stream-json
### Per-turn runtimes (gemini, copilot, cursor, opencode, antigravity)
The process handles exactly one turn and exits. `supportsStdinNotification` is
`false` and `encodeStdinMessage` returns `null`. A new message means a **brand-new
-process**; the agent re-checks the inbox each wake (`messageNotificationStyle:
-"poll"`). `opencode` is a special per-turn case: it defers spawning until a
-concrete message and terminates the process on turn end.
+process**; the agent re-checks the inbox each wake. This lifecycle
+(`lifecycle.kind: "per_turn"`) drives the `## Message Notifications` section
+generated by `buildCliSystemPrompt` — no driver hand-writes this reminder.
+`opencode` is a special per-turn case: it defers spawning until a concrete
+message and terminates the process on turn end.
---
@@ -259,7 +261,7 @@ gated:
messages by target (channel / DM / thread) and projects each into the
metadata-only summary surfaced as an `[inbox notice: …]` (count, first,
latest, sender, flags). No bodies — the agent pulls those with
- `alook message check`.
+ `alook inbox pull`.
- **`inbox/stateMachine.ts`** — `planAgentInboxSideEffect` is the "don't reply on
stale context" guard. Before an outward action (`send` / `task_claim` /
`task_update`) it compares the model's seen `seq` boundary against pending
diff --git a/src/daemon/src/credentials/credentialProxy.test.ts b/src/daemon/src/credentials/credentialProxy.test.ts
index 08fb412df..55db9ac7f 100644
--- a/src/daemon/src/credentials/credentialProxy.test.ts
+++ b/src/daemon/src/credentials/credentialProxy.test.ts
@@ -165,9 +165,9 @@ describe("startCredentialProxy (zero-trust end to end)", () => {
upstreamClose = upstream.close;
const broker = new CredentialBroker({ upstreamBaseUrl: upstream.url });
proxy = await startCredentialProxy(broker);
- const reg = broker.mint("a", "l", ["send", "read"], REAL_KEY); // no "tasks"
+ const reg = broker.mint("a", "l", ["read"], REAL_KEY); // no "send"
- const r = await post(proxy.url, reg.voucher, "/tasks/claim");
+ const r = await post(proxy.url, reg.voucher, "/send");
expect(r.status).toBe(403);
expect(upstream.seen.length).toBe(0);
});
diff --git a/src/daemon/src/credentials/credentialProxy.ts b/src/daemon/src/credentials/credentialProxy.ts
index 82643125d..d60876b89 100644
--- a/src/daemon/src/credentials/credentialProxy.ts
+++ b/src/daemon/src/credentials/credentialProxy.ts
@@ -236,8 +236,6 @@ export const DEFAULT_CAPABILITY_RESOLVER: CapabilityResolver = (_method, pathnam
if (pathname.includes("/send")) return "send";
if (pathname.includes("/history") || pathname.includes("/search") || pathname.includes("/inbox"))
return "read";
- if (pathname.includes("/tasks")) return "tasks";
- if (pathname.includes("/react")) return "reactions";
if (pathname.includes("/server") || pathname.includes("/channel")) return "server";
return undefined;
};
diff --git a/src/daemon/src/daemon/createDaemon.test.ts b/src/daemon/src/daemon/createDaemon.test.ts
index 101cbef8f..bcaf90850 100644
--- a/src/daemon/src/daemon/createDaemon.test.ts
+++ b/src/daemon/src/daemon/createDaemon.test.ts
@@ -44,7 +44,7 @@ class FakeSocket {
close(): void {
this.emit("close");
}
- ping(): void {}
+ ping(): void { }
emit(event: string, arg?: unknown): void {
(this.handlers[event] ?? []).forEach((h) => h(arg));
}
@@ -68,7 +68,7 @@ function fullFakeDriver(id: string): Driver {
probe: () => ({ status: "healthy" as const, version: "test" }),
spawn: async () => {
const proc = new EventEmitter() as unknown as { kill: () => void };
- proc.kill = () => {};
+ proc.kill = () => { };
return { process: proc as never };
},
parseLine: () => [],
@@ -280,4 +280,63 @@ describe("createDaemon — logging", () => {
).toBe(true);
await daemon.stop();
});
+
+ it("calls resync-wakes with the machine key bearer on open and logs the woken count", async () => {
+ global.fetch = vi.fn(async (url: string | URL, init?: RequestInit) => {
+ const href = String(url);
+ if (href.includes("/resync-wakes")) {
+ expect((init?.headers as Record<string, string>).authorization).toBe("Bearer cmk_resync");
+ return new Response(JSON.stringify({ woken: 2 }), { status: 200 });
+ }
+ return new Response(JSON.stringify({ bots: [] }), { status: 200 });
+ }) as unknown as typeof fetch;
+
+ const sockets: FakeSocket[] = [];
+ const logger = stubLogger();
+ const daemon = await createDaemon({
+ machineKey: "cmk_resync",
+ serverUrl: "http://localhost:9999",
+ serverWsUrl: "ws://x",
+ webSocketFactory: factory(sockets) as any,
+ runtimeReport: [],
+ driverFor: () => fakeDriver,
+ capabilities: [],
+ logger,
+ });
+ sockets[0].emit("open");
+ await new Promise((r) => setTimeout(r, 20));
+
+ expect(
+ logger.calls.info.some(([, m, d]) => m === "wake resync completed" && (d[0] as any).woken === 2),
+ ).toBe(true);
+ await daemon.stop();
+ });
+
+ it("logs (never throws) when resync-wakes fails", async () => {
+ global.fetch = vi.fn(async (url: string | URL) => {
+ const href = String(url);
+ if (href.includes("/resync-wakes")) {
+ return new Response("boom", { status: 500 });
+ }
+ return new Response(JSON.stringify({ bots: [] }), { status: 200 });
+ }) as unknown as typeof fetch;
+
+ const sockets: FakeSocket[] = [];
+ const logger = stubLogger();
+ const daemon = await createDaemon({
+ machineKey: "cmk_resync_fail",
+ serverUrl: "http://localhost:9999",
+ serverWsUrl: "ws://x",
+ webSocketFactory: factory(sockets) as any,
+ runtimeReport: [],
+ driverFor: () => fakeDriver,
+ capabilities: [],
+ logger,
+ });
+ sockets[0].emit("open");
+ await new Promise((r) => setTimeout(r, 20));
+
+ expect(logger.calls.warn.some(([, m]) => m === "wake resync failed")).toBe(true);
+ await daemon.stop();
+ });
});
diff --git a/src/daemon/src/daemon/createDaemon.ts b/src/daemon/src/daemon/createDaemon.ts
index 40a34d677..96fa5cd24 100644
--- a/src/daemon/src/daemon/createDaemon.ts
+++ b/src/daemon/src/daemon/createDaemon.ts
@@ -176,6 +176,31 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa
log.warn("cold-start bot-cache warmup exhausted its ceiling", { ceilingMs: WARMUP_CEILING_MS, attempts: attempt });
}
+ /**
+ * Ask the server to re-check each of this machine's bots for unread work
+ * and re-wake any that have some. Recovers a message that arrived while
+ * this daemon was offline: the wake-queue consumer acks (never retries) a
+ * `delivered_nowhere` outcome, so without this call that wake is gone for
+ * good once the daemon reconnects. The daemon drives WHEN this runs; the
+ * server alone decides WHAT an `agent:wake` looks like (same
+ * `dispatchOneUnreadWake` rebuild the queue consumer uses) — this call
+ * carries no addressing/config, just "check now". Best-effort: logged, never
+ * thrown, never blocks the rest of connect.
+ */
+ async function resyncPendingWakes(): Promise<void> {
+ try {
+ const res = await fetch(`${opts.serverUrl}/api/community/daemon/resync-wakes`, {
+ method: "POST",
+ headers: { authorization: `Bearer ${opts.machineKey}` },
+ });
+ if (!res.ok) throw new Error(`resync-wakes ${res.status}`);
+ const json = (await res.json()) as { woken?: number };
+ log.info("wake resync completed", { woken: json.woken ?? 0 });
+ } catch (err) {
+ log.warn("wake resync failed", { err: err instanceof Error ? err.message : String(err) });
+ }
+ }
+
const enrollAgent = async (agentId: string): Promise<string> => {
const existing = enrolledKeys.get(agentId);
if (existing) return existing;
@@ -348,9 +373,11 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa
handleBotFrame(cmd);
});
// Warmup on every (re)connect — including the first open. `onOpen` fires
- // after resync completes.
+ // after resync completes. Wake-resync runs alongside it so a message
+ // dropped while this daemon was offline gets a second chance right away.
channel.onOpen(() => {
void coldStartWarmup();
+ void resyncPendingWakes();
});
channel.connect();
diff --git a/src/daemon/src/drivers/antigravity.ts b/src/daemon/src/drivers/antigravity.ts
index 99c73945a..5474dbf21 100644
--- a/src/daemon/src/drivers/antigravity.ts
+++ b/src/daemon/src/drivers/antigravity.ts
@@ -89,13 +89,6 @@ export class AntigravityDriver implements Driver {
}
buildSystemPrompt(config: LaunchConfig): string {
- return buildCliTransportSystemPrompt(config, {
- extraCriticalRules: [],
- postStartupNotes: [
- "**Antigravity runtime note:** The host launches you as a per-turn process. Complete the current wake using `alook` commands, then stop; the host will restart you when new messages arrive.",
- ],
- includeStdinNotificationSection: false,
- messageNotificationStyle: "poll",
- });
+ return buildCliTransportSystemPrompt(config, { lifecycleKind: this.lifecycle.kind });
}
}
diff --git a/src/daemon/src/drivers/claude.ts b/src/daemon/src/drivers/claude.ts
index 36b9d8c5e..625a3d1d0 100644
--- a/src/daemon/src/drivers/claude.ts
+++ b/src/daemon/src/drivers/claude.ts
@@ -17,7 +17,6 @@ import {
resolveClaudeLaunchCommand,
buildClaudeSpawnSpec,
} from "./claudeLaunch.js";
-import { writeAgentFile } from "./agentFile.js";
import { ClaudeEventNormalizer } from "./claudeEventNormalizer.js";
import { probeClaude } from "./probe.js";
@@ -44,10 +43,10 @@ export class ClaudeDriver implements Driver {
const cliConfig = ctx.agentCliPath
? { ...DEFAULT_CLI_CONFIG, hostCliPath: ctx.agentCliPath }
: undefined;
+ // prepareCliTransport writes AGENTS.md (+ CLAUDE.md symlink) into the
+ // workdir as part of the shared transport setup — Claude Code auto-reads
+ // CLAUDE.md from cwd, no CLI flag needed.
const { spawnEnv } = await prepareCliTransport(ctx, buildClaudeProviderIsolationEnv(ctx), cliConfig);
- // Write system prompt as AGENTS.md in workdir — Claude Code auto-reads
- // CLAUDE.md (symlinked to AGENTS.md) from cwd, no CLI flag needed.
- writeAgentFile(ctx.workingDirectory, ctx.standingPrompt);
const args = buildClaudeArgs(ctx.config);
// Let Claude detect it is NOT nested in another Claude Code session.
@@ -91,11 +90,6 @@ export class ClaudeDriver implements Driver {
}
buildSystemPrompt(config: LaunchConfig): string {
- return buildCliTransportSystemPrompt(config, {
- extraCriticalRules: [],
- postStartupNotes: [],
- includeStdinNotificationSection: true,
- messageNotificationStyle: "direct",
- });
+ return buildCliTransportSystemPrompt(config, { lifecycleKind: this.lifecycle.kind });
}
}
diff --git a/src/daemon/src/drivers/cliTransport.test.ts b/src/daemon/src/drivers/cliTransport.test.ts
index 4dcd5162a..f07f2c6ef 100644
--- a/src/daemon/src/drivers/cliTransport.test.ts
+++ b/src/daemon/src/drivers/cliTransport.test.ts
@@ -96,3 +96,26 @@ describe("prepareCliTransport — layered spawn env", () => {
expect(fs.lstatSync(link).isSymbolicLink()).toBe(true);
});
});
+
+describe("prepareCliTransport — unified AGENTS.md packing", () => {
+ it("writes AGENTS.md (+ CLAUDE.md symlink) into the workdir when standingPrompt is non-empty", async () => {
+ const wd = mkTmp();
+ await prepareCliTransport(baseCtx(wd, { standingPrompt: "You are an AI agent." }), {}, undefined, "linux");
+ expect(fs.readFileSync(path.join(wd, "AGENTS.md"), "utf-8")).toBe("You are an AI agent.");
+ expect(fs.lstatSync(path.join(wd, "CLAUDE.md")).isSymbolicLink()).toBe(true);
+ });
+
+ it("does not write AGENTS.md when standingPrompt is empty", async () => {
+ const wd = mkTmp();
+ await prepareCliTransport(baseCtx(wd), {}, undefined, "linux");
+ expect(fs.existsSync(path.join(wd, "AGENTS.md"))).toBe(false);
+ });
+
+ it("every child-process driver gets the same file regardless of its own delivery mechanism", async () => {
+ // Simulates what claude/kimi/codex/gemini/etc. all do: call prepareCliTransport
+ // with a real standingPrompt before their driver-specific spawn logic.
+ const wd = mkTmp();
+ await prepareCliTransport(baseCtx(wd, { standingPrompt: "standing prompt content" }), { NO_COLOR: "1" }, undefined, "linux");
+ expect(fs.readFileSync(path.join(wd, "AGENTS.md"), "utf-8")).toBe("standing prompt content");
+ });
+});
diff --git a/src/daemon/src/drivers/cliTransport.ts b/src/daemon/src/drivers/cliTransport.ts
index 0782a2e38..a6dd223bd 100644
--- a/src/daemon/src/drivers/cliTransport.ts
+++ b/src/daemon/src/drivers/cliTransport.ts
@@ -21,6 +21,19 @@
* - authenticate back to the host, and
* - see the neutral `<PREFIX>_*` runtime-context env vars.
*
+ * It also writes the assembled standing prompt as `AGENTS.md` (+ `CLAUDE.md`
+ * symlink) into the agent's workdir — the ONE packing step every child-process
+ * driver relies on, mirroring `src/cli/daemon/execenv/index.ts`'s
+ * `writeInstructionFileIfChanged`, which does the same thing unconditionally
+ * regardless of which runtime is about to be spawned. Every mainstream
+ * coding-agent CLI this backend drives (Claude Code, Codex, Kimi, OpenCode,
+ * Gemini, Cursor, Copilot, Antigravity) auto-reads `AGENTS.md`/`CLAUDE.md`
+ * from cwd, so no driver needs its own bespoke delivery channel — there is
+ * exactly one packing mechanism, not nine. (`pi` is the sole exception: it
+ * runs in-process with no child process, so it doesn't go through
+ * `prepareCliTransport` at all — it calls `writeAgentFile` directly with the
+ * same file, for the same reason: its SDK auto-reads `AGENTS.md` from cwd.)
+ *
* AUTH IS ZERO-TRUST ONLY. The host must pass `ctx.credentialProxy` (a running
* `CredentialBroker` + proxy URL); the transport mints a per-launch voucher and
* injects `<PREFIX>_PROXY_URL` + `<PREFIX>_PROXY_TOKEN_FILE` as a sensitive layer.
@@ -35,6 +48,7 @@ import { buildCliSystemPrompt, type SystemPromptOpts } from "./systemPrompt.js";
import { resolveLaunchFieldsOrDefault } from "../runtimeConfig.js";
import { writeCliLink } from "./cliLink.js";
import { mergeEnvLayers, platformEnv, runtimeContextEnv, type EnvLayer } from "./spawnEnv.js";
+import { writeAgentFile } from "./agentFile.js";
export interface PreparedCliTransport {
/** Per-launch state directory created under the working directory. */
@@ -140,6 +154,11 @@ export async function prepareCliTransport(
const stateDir = path.join(ctx.workingDirectory, cli.stateDirName);
await fs.promises.mkdir(stateDir, { recursive: true });
+ // Unified packing step for every child-process driver: write the standing
+ // prompt as AGENTS.md (+ CLAUDE.md symlink) so any runtime that auto-reads
+ // it from cwd picks it up, with no driver-specific plumbing required.
+ if (ctx.standingPrompt) writeAgentFile(ctx.workingDirectory, ctx.standingPrompt);
+
// Decouple the agent-facing `cliName` from the host binary via a filesystem
// link in a PATH-prepended bin dir (symlink on POSIX, .cmd shim on Windows).
const binDir = writeCliLink(stateDir, cli.cliName, cli.hostCliPath, platform);
@@ -150,7 +169,7 @@ export async function prepareCliTransport(
if (!ctx.credentialProxy) {
throw new Error(
"prepareCliTransport: ctx.credentialProxy is required — start a credential proxy " +
- "(see src/credentials) and pass { broker, proxyUrl }. There is no plaintext mode.",
+ "(see src/credentials) and pass { broker, proxyUrl }. There is no plaintext mode.",
);
}
const reg = ctx.credentialProxy.broker.mint(
diff --git a/src/daemon/src/drivers/codex.ts b/src/daemon/src/drivers/codex.ts
index 6743672d5..361cb5865 100644
--- a/src/daemon/src/drivers/codex.ts
+++ b/src/daemon/src/drivers/codex.ts
@@ -109,12 +109,14 @@ export class CodexDriver implements Driver {
const f = resolveLaunchFieldsOrDefault(ctx.config.runtimeConfig);
const resuming = Boolean(ctx.config.sessionId);
+ // The standing prompt reaches Codex via the AGENTS.md that
+ // prepareCliTransport writes into the workdir (unified packing) —
+ // Codex auto-reads it from cwd, no developerInstructions param needed.
const params: Record<string, unknown> = {
cwd: ctx.workingDirectory,
approvalPolicy: "never",
sandbox: "danger-full-access",
sandbox_mode: "danger-full-access",
- developerInstructions: ctx.standingPrompt,
experimentalRawEvents: true,
};
if (resuming) params.threadId = ctx.config.sessionId;
@@ -165,13 +167,6 @@ export class CodexDriver implements Driver {
}
buildSystemPrompt(config: LaunchConfig): string {
- return buildCliTransportSystemPrompt(config, {
- extraCriticalRules: [],
- postStartupNotes: [
- "**IMPORTANT**: Your process stays alive across turns. Use `alook message check` to pull pending messages at natural breakpoints.",
- ],
- includeStdinNotificationSection: true,
- messageNotificationStyle: "direct",
- });
+ return buildCliTransportSystemPrompt(config, { lifecycleKind: this.lifecycle.kind });
}
}
diff --git a/src/daemon/src/drivers/copilot.ts b/src/daemon/src/drivers/copilot.ts
index 9c15dc954..196c864b5 100644
--- a/src/daemon/src/drivers/copilot.ts
+++ b/src/daemon/src/drivers/copilot.ts
@@ -96,13 +96,6 @@ export class CopilotDriver implements Driver {
}
buildSystemPrompt(config: LaunchConfig): string {
- return buildCliTransportSystemPrompt(config, {
- extraCriticalRules: [],
- postStartupNotes: [
- "**Copilot runtime note:** The host launches you as a per-turn process. Complete the current wake using `alook` commands, then stop; the host will restart you when new messages arrive.",
- ],
- includeStdinNotificationSection: false,
- messageNotificationStyle: "poll",
- });
+ return buildCliTransportSystemPrompt(config, { lifecycleKind: this.lifecycle.kind });
}
}
diff --git a/src/daemon/src/drivers/cursor.ts b/src/daemon/src/drivers/cursor.ts
index 790eee127..abcea971f 100644
--- a/src/daemon/src/drivers/cursor.ts
+++ b/src/daemon/src/drivers/cursor.ts
@@ -100,13 +100,6 @@ export class CursorDriver implements Driver {
}
buildSystemPrompt(config: LaunchConfig): string {
- return buildCliTransportSystemPrompt(config, {
- extraCriticalRules: [],
- postStartupNotes: [
- "**Cursor runtime note:** The host launches you as a per-turn process. Complete the current wake using `alook` commands, then stop; the host will restart you when new messages arrive.",
- ],
- includeStdinNotificationSection: false,
- messageNotificationStyle: "poll",
- });
+ return buildCliTransportSystemPrompt(config, { lifecycleKind: this.lifecycle.kind });
}
}
diff --git a/src/daemon/src/drivers/gemini.ts b/src/daemon/src/drivers/gemini.ts
index 3e14818e0..92e16896f 100644
--- a/src/daemon/src/drivers/gemini.ts
+++ b/src/daemon/src/drivers/gemini.ts
@@ -105,13 +105,6 @@ export class GeminiDriver implements Driver {
}
buildSystemPrompt(config: LaunchConfig): string {
- return buildCliTransportSystemPrompt(config, {
- extraCriticalRules: [],
- postStartupNotes: [
- "**Gemini runtime note:** The host launches you as a per-turn process. Complete the current wake using `alook` commands, then stop; the host will restart you when new messages arrive.",
- ],
- includeStdinNotificationSection: false,
- messageNotificationStyle: "poll",
- });
+ return buildCliTransportSystemPrompt(config, { lifecycleKind: this.lifecycle.kind });
}
}
diff --git a/src/daemon/src/drivers/kimi.ts b/src/daemon/src/drivers/kimi.ts
index a1fa30848..e883afe13 100644
--- a/src/daemon/src/drivers/kimi.ts
+++ b/src/daemon/src/drivers/kimi.ts
@@ -1,10 +1,11 @@
/**
* Kimi driver — persistent child-process CLI over JSON-RPC, DIRECT steering.
*
- * `kimi --wire --yolo --agent-file <file> --session <id>` runs a long-lived
- * process speaking JSON-RPC 2.0 over stdio (the "wire" protocol). On spawn we
- * send `initialize` then a `prompt`; thereafter idle messages are `prompt` and
- * busy messages are `steer`.
+ * `kimi --wire --yolo --session <id>` runs a long-lived process speaking
+ * JSON-RPC 2.0 over stdio (the "wire" protocol). The standing prompt is
+ * delivered via the `AGENTS.md` that `prepareCliTransport` writes into the
+ * workdir (Kimi auto-reads it from cwd). On spawn we send `initialize` then a
+ * `prompt`; thereafter idle messages are `prompt` and busy messages are `steer`.
*/
import { spawn } from "child_process";
import { randomUUID } from "crypto";
@@ -45,15 +46,13 @@ export class KimiDriver implements Driver {
async spawn(ctx: LaunchContext): Promise<SpawnResult> {
this.sessionId = ctx.config.sessionId || randomUUID();
const isResume = Boolean(ctx.config.sessionId);
- const { stateDir, spawnEnv } = await prepareCliTransport(ctx, { NO_COLOR: "1" });
-
- // The standing prompt is delivered to Kimi via an agent file.
- const agentFilePath = `${stateDir}/kimi-agent.md`;
- const fs = await import("fs");
- fs.writeFileSync(agentFilePath, ctx.standingPrompt, { mode: 0o600 });
+ // The standing prompt reaches Kimi via the AGENTS.md that prepareCliTransport
+ // writes into the workdir (unified packing — see cliTransport.ts) — Kimi
+ // auto-reads it from cwd, no --agent-file flag needed.
+ const { spawnEnv } = await prepareCliTransport(ctx, { NO_COLOR: "1" });
const f = resolveLaunchFieldsOrDefault(ctx.config.runtimeConfig);
- const args = ["--wire", "--yolo", "--agent-file", agentFilePath, "--session", this.sessionId];
+ const args = ["--wire", "--yolo", "--session", this.sessionId];
if (f.model) args.push("--model", f.model);
const command = resolveCommandOnPath("kimi") ?? "kimi";
@@ -155,11 +154,6 @@ export class KimiDriver implements Driver {
}
buildSystemPrompt(config: LaunchConfig): string {
- return buildCliTransportSystemPrompt(config, {
- extraCriticalRules: [],
- postStartupNotes: [],
- includeStdinNotificationSection: true,
- messageNotificationStyle: "direct",
- });
+ return buildCliTransportSystemPrompt(config, { lifecycleKind: this.lifecycle.kind });
}
}
diff --git a/src/daemon/src/drivers/opencode.ts b/src/daemon/src/drivers/opencode.ts
index ec3d30949..00416d753 100644
--- a/src/daemon/src/drivers/opencode.ts
+++ b/src/daemon/src/drivers/opencode.ts
@@ -4,8 +4,9 @@
* Distinctive lifecycle: it DEFERS spawning until a concrete message arrives
* (bookkeeping-only wakes don't launch a process) and explicitly TERMINATES the
* process when the turn ends (rather than relying on natural exit). The
- * standing prompt is injected via `OPENCODE_CONFIG_CONTENT` (a `host` agent
- * definition), and the user message is the trailing `-- <prompt>` positional.
+ * standing prompt reaches OpenCode via the `AGENTS.md` that `prepareCliTransport`
+ * writes into the workdir (OpenCode auto-reads it from cwd); the user message
+ * is the trailing `-- <prompt>` positional.
*/
import { spawn } from "child_process";
import type { Driver, LaunchConfig, LaunchContext, ParsedEvent, SpawnResult } from "../types.js";
@@ -46,14 +47,12 @@ export class OpenCodeDriver implements Driver {
async spawn(ctx: LaunchContext): Promise<SpawnResult> {
this.sessionId = ctx.config.sessionId ?? null;
const f = resolveLaunchFieldsOrDefault(ctx.config.runtimeConfig);
- const { spawnEnv } = await prepareCliTransport(ctx, {
- NO_COLOR: "1",
- OPENCODE_CONFIG_CONTENT: JSON.stringify({ agent: { host: { prompt: ctx.standingPrompt } } }),
- });
+ // prepareCliTransport writes AGENTS.md into the workdir (unified packing) —
+ // OpenCode auto-reads it from cwd, no custom `host` agent config needed.
+ const { spawnEnv } = await prepareCliTransport(ctx, { NO_COLOR: "1" });
const args = ["run", "--format", "json", "--dangerously-skip-permissions", "--pure", "--dir", ctx.workingDirectory];
if (f.model) args.push("--model", f.model);
- args.push("--agent", "host");
if (ctx.config.sessionId) args.push("--session", ctx.config.sessionId);
const promptArg = ctx.prompt === ctx.standingPrompt ? "No new messages are pending. Stop now." : ctx.prompt;
args.push("--", promptArg);
@@ -114,13 +113,6 @@ export class OpenCodeDriver implements Driver {
}
buildSystemPrompt(config: LaunchConfig): string {
- return buildCliTransportSystemPrompt(config, {
- extraCriticalRules: [],
- postStartupNotes: [
- "**OpenCode runtime note:** The host launches you as a per-turn process. Complete the current wake using `alook` commands, then stop; the host will restart you when new messages arrive.",
- ],
- includeStdinNotificationSection: false,
- messageNotificationStyle: "poll",
- });
+ return buildCliTransportSystemPrompt(config, { lifecycleKind: this.lifecycle.kind });
}
}
diff --git a/src/daemon/src/drivers/pi.test.ts b/src/daemon/src/drivers/pi.test.ts
new file mode 100644
index 000000000..63acfbf0a
--- /dev/null
+++ b/src/daemon/src/drivers/pi.test.ts
@@ -0,0 +1,76 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
+import * as fs from "fs";
+import * as os from "os";
+import * as path from "path";
+import { PiDriver } from "./pi";
+import { CANONICAL_FILE, SYMLINK_ALIASES } from "./agentFile";
+import type { LaunchContext } from "../types";
+
+let tmpDir: string;
+
+beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "pi-driver-test-"));
+});
+afterEach(() => {
+ fs.rmSync(tmpDir, { recursive: true, force: true });
+});
+
+function baseCtx(overrides: Partial<LaunchContext> = {}): LaunchContext {
+ return {
+ agentId: "agent_1",
+ workingDirectory: tmpDir,
+ standingPrompt: "You are Pi.",
+ prompt: "hello",
+ config: {},
+ credentialProxy: {} as LaunchContext["credentialProxy"],
+ ...overrides,
+ };
+}
+
+function fakeDeps() {
+ const session = {
+ prompt: vi.fn().mockResolvedValue(undefined),
+ steer: vi.fn(),
+ abort: vi.fn(),
+ dispose: vi.fn(),
+ isStreaming: false,
+ subscribe: vi.fn(),
+ };
+ const createAgentSession = vi.fn().mockResolvedValue({ session, sessionId: "sess_1" });
+ const buildSpawnEnv = vi.fn().mockResolvedValue({});
+ return { buildSpawnEnv, createAgentSession, session };
+}
+
+describe("PiDriver.createSession — AGENTS.md packing", () => {
+ it("writes AGENTS.md into the workdir instead of passing standingPrompt to the SDK", async () => {
+ const driver = new PiDriver();
+ const deps = fakeDeps();
+
+ await driver.createSession(baseCtx(), deps);
+
+ expect(fs.readFileSync(path.join(tmpDir, CANONICAL_FILE), "utf-8")).toBe("You are Pi.");
+ expect(fs.lstatSync(path.join(tmpDir, SYMLINK_ALIASES[0])).isSymbolicLink()).toBe(true);
+
+ const sessionOpts = deps.createAgentSession.mock.calls[0][0];
+ expect(sessionOpts).not.toHaveProperty("standingPrompt");
+ });
+
+ it("does not rewrite AGENTS.md when the standing prompt is unchanged (hash dedup)", async () => {
+ const driver = new PiDriver();
+ await driver.createSession(baseCtx(), fakeDeps());
+ const firstMtime = fs.statSync(path.join(tmpDir, CANONICAL_FILE)).mtimeMs;
+
+ // Second session, identical standingPrompt — file content must be untouched.
+ await new Promise((r) => setTimeout(r, 5));
+ await driver.createSession(baseCtx(), fakeDeps());
+ const secondMtime = fs.statSync(path.join(tmpDir, CANONICAL_FILE)).mtimeMs;
+
+ expect(secondMtime).toBe(firstMtime);
+ });
+
+ it("skips the write when standingPrompt is empty", async () => {
+ const driver = new PiDriver();
+ await driver.createSession(baseCtx({ standingPrompt: "" }), fakeDeps());
+ expect(fs.existsSync(path.join(tmpDir, CANONICAL_FILE))).toBe(false);
+ });
+});
diff --git a/src/daemon/src/drivers/pi.ts b/src/daemon/src/drivers/pi.ts
index 82975074a..4e31de165 100644
--- a/src/daemon/src/drivers/pi.ts
+++ b/src/daemon/src/drivers/pi.ts
@@ -6,10 +6,16 @@
* auth/settings registry (Google / OpenAI / OpenRouter). Sessions persist as
* JSONL; a custom bash tool is injected so shell calls inherit the CLI-transport
* env. Steering is `direct` (guarded by `session.isStreaming`).
+ *
+ * The standing prompt is delivered via `AGENTS.md` written directly into the
+ * workdir (Pi never calls `prepareCliTransport`, so it can't get the file for
+ * free the way child-process drivers do — it writes it itself, same file,
+ * same convention).
*/
import { createRequire } from "module";
import type { Driver, LaunchConfig, LaunchContext, ParsedEvent, SpawnResult } from "../types.js";
import { buildCliTransportSystemPrompt } from "./cliTransport.js";
+import { writeAgentFile } from "./agentFile.js";
import { SdkRuntimeSession, type SdkSessionHandle } from "../runtime/sdkRuntimeSession.js";
import { resolveLaunchFieldsOrDefault } from "../runtimeConfig.js";
@@ -107,11 +113,14 @@ export class PiDriver implements Driver {
},
): Promise<SdkRuntimeSession> {
const spawnEnv = await deps.buildSpawnEnv();
+ // Pi has no child process, so it never goes through prepareCliTransport —
+ // write AGENTS.md here directly (same unified packing every other driver
+ // gets); Pi's SDK auto-reads it from cwd, same as the CLI drivers.
+ if (ctx.standingPrompt) writeAgentFile(ctx.workingDirectory, ctx.standingPrompt);
const f = resolveLaunchFieldsOrDefault(ctx.config.runtimeConfig);
const { session, sessionId } = await deps.createAgentSession({
cwd: ctx.workingDirectory,
sessionId: ctx.config.sessionId,
- standingPrompt: ctx.standingPrompt,
model: f.model,
thinkingLevel: f.reasoningEffort,
spawnEnv, // injected into the custom bash tool
@@ -150,13 +159,6 @@ export class PiDriver implements Driver {
}
buildSystemPrompt(config: LaunchConfig): string {
- return buildCliTransportSystemPrompt(config, {
- extraCriticalRules: [],
- postStartupNotes: [
- "**Pi runtime note:** The host keeps Pi running as a persistent SDK session. While you are working, the host may send inbox-count notifications into the current turn; call `alook message check` at natural breakpoints.",
- ],
- includeStdinNotificationSection: true,
- messageNotificationStyle: "direct",
- });
+ return buildCliTransportSystemPrompt(config, { lifecycleKind: this.lifecycle.kind });
}
}
diff --git a/src/daemon/src/drivers/systemPrompt.test.ts b/src/daemon/src/drivers/systemPrompt.test.ts
index c0dbccc67..ed472a434 100644
--- a/src/daemon/src/drivers/systemPrompt.test.ts
+++ b/src/daemon/src/drivers/systemPrompt.test.ts
@@ -15,13 +15,10 @@ const baseConfig: LaunchConfig = {
},
};
-describe("buildCliSystemPrompt — host-neutral slim default", () => {
- const prompt = buildCliSystemPrompt(baseConfig, {
- messageNotificationStyle: "direct",
- includeStdinNotificationSection: true,
- });
+describe("buildCliSystemPrompt — Alook default", () => {
+ const prompt = buildCliSystemPrompt(baseConfig, { lifecycleKind: "persistent" });
- it("keeps the host-neutral core sections", () => {
+ it("keeps the core sections", () => {
expect(prompt).toContain("You are an AI agent operating in");
expect(prompt).toContain("## CLI tool");
expect(prompt).toContain("## Sending & receiving messages");
@@ -33,8 +30,7 @@ describe("buildCliSystemPrompt — host-neutral slim default", () => {
expect(prompt).toContain("## Message Notifications");
});
- it("does NOT bake in any platform's protocol conventions", () => {
- // Platform-specific details belong to the host's communicationGuide.
+ it("does NOT bake in any other product's protocol conventions", () => {
expect(prompt).not.toContain("RFC 5424");
expect(prompt).not.toContain(":shortid");
expect(prompt).not.toContain("todo → in_progress");
@@ -42,52 +38,37 @@ describe("buildCliSystemPrompt — host-neutral slim default", () => {
expect(prompt).not.toMatch(/##\s*CRITICAL RULES/);
});
- it("uses the configured cli name everywhere", () => {
- const p = buildCliSystemPrompt(baseConfig, { cli: "mock-cli", messageNotificationStyle: "direct" });
- expect(p).toContain("`mock-cli`");
- expect(p).not.toContain("`alook`");
+ it("no longer has the removed Additional rules / Notes / communicationGuide sections", () => {
+ expect(prompt).not.toContain("## Additional rules");
+ expect(prompt).not.toMatch(/##\s*Notes\b/);
+ });
+
+ it("hardcodes the alook CLI name and Alook platform label everywhere", () => {
+ expect(prompt).toContain("`alook`");
+ expect(prompt).toContain("You are an AI agent operating in Alook.");
});
});
-describe("buildCliSystemPrompt — runtime-driven notification section", () => {
- it("direct (steering) describes busy-time notices", () => {
- const p = buildCliSystemPrompt(baseConfig, { messageNotificationStyle: "direct" });
+describe("buildCliSystemPrompt — lifecycle-driven notification section", () => {
+ it("persistent describes busy-time inbox notices", () => {
+ const p = buildCliSystemPrompt(baseConfig, { lifecycleKind: "persistent" });
expect(p).toContain("inbox notice");
expect(p).toContain("inbox pull");
});
- it("poll (per-turn) describes re-checking each wake", () => {
- const p = buildCliSystemPrompt(baseConfig, { messageNotificationStyle: "poll" });
+ it("per_turn describes finishing the wake and stopping instead of polling", () => {
+ const p = buildCliSystemPrompt(baseConfig, { lifecycleKind: "per_turn" });
expect(p).toContain("once per wake");
- expect(p).toContain("inbox pull");
- });
-
- it("omits the notification section when disabled", () => {
- const p = buildCliSystemPrompt(baseConfig, { includeStdinNotificationSection: false });
- expect(p).not.toContain("## Message Notifications");
+ expect(p).not.toContain("inbox notice");
});
});
-describe("buildCliSystemPrompt — host injection points", () => {
- it("appends the host communicationGuide verbatim", () => {
- const guide = "## Communication\nUse `mock-cli message send` with the [target=…] header.";
- const p = buildCliSystemPrompt(baseConfig, { communicationGuide: guide });
- expect(p).toContain(guide);
- });
-
- it("appends extraCriticalRules and postStartupNotes when provided", () => {
- const p = buildCliSystemPrompt(baseConfig, {
- extraCriticalRules: ["Claim a task before working on it."],
- postStartupNotes: ["Process stays alive across turns."],
- });
- expect(p).toContain("## Additional rules");
- expect(p).toContain("Claim a task before working on it.");
- expect(p).toContain("## Notes");
- expect(p).toContain("Process stays alive across turns.");
- });
-
+describe("buildCliSystemPrompt — role injection", () => {
it("includes the role when config.description is set", () => {
- const p = buildCliSystemPrompt({ ...baseConfig, description: "You are the onboarding assistant." }, {});
+ const p = buildCliSystemPrompt(
+ { ...baseConfig, description: "You are the onboarding assistant." },
+ { lifecycleKind: "persistent" },
+ );
expect(p).toContain("## Role");
expect(p).toContain("You are the onboarding assistant.");
});
diff --git a/src/daemon/src/drivers/systemPrompt.ts b/src/daemon/src/drivers/systemPrompt.ts
index b7b5f21ca..65ff23256 100644
--- a/src/daemon/src/drivers/systemPrompt.ts
+++ b/src/daemon/src/drivers/systemPrompt.ts
@@ -1,5 +1,5 @@
/**
- * Shared system-prompt builder (host-neutral).
+ * Shared system-prompt builder.
*
* Every CLI driver's `buildSystemPrompt` funnels through here. The prompt is
* assembled from a fixed sequence of sections:
@@ -12,67 +12,68 @@
* 7. Communication style & etiquette
* 8. Channel awareness
* 9. Workspace & Memory
- * 10. Message notifications
- * 11. Host communicationGuide / extra rules / initial role
+ * 10. Message notifications (auto-generated from `lifecycleKind`)
+ * 11. Role (from `config.description`, when set)
*
- * This builder intentionally hardcodes NO platform. The host's CLI name and
- * platform label are parameters (`SystemPromptOpts.cli` / `.platformName`),
- * defaulting to the `alook` placeholder. A real deployment passes its own CLI
- * guide via `opts.communicationGuide` rather than baking it in.
+ * Alook is the product — there's no other host to be neutral toward, so the
+ * CLI name (`alook`) and platform label (`Alook`) are hardcoded, not
+ * configurable options.
+ *
+ * ONE generation path, not nine: every driver passes only `lifecycleKind`
+ * (`"persistent" | "per_turn"`, taken straight from `driver.lifecycle.kind`)
+ * — there is no per-driver hand-typed reminder text. Section 10 is derived
+ * entirely from that one value, so every driver of the same lifecycle kind
+ * gets identical, complete notification/reminder guidance with zero
+ * duplication or drift between drivers.
*/
import type { LaunchConfig } from "../types.js";
+const CLI = "alook";
+
export interface SystemPromptOpts {
- extraCriticalRules?: string[];
- postStartupNotes?: string[];
- includeStdinNotificationSection?: boolean;
- messageNotificationStyle?: "direct" | "poll" | "inline";
- /** Host CLI command name the agent uses (default: the mock `alook`). */
- cli?: string;
- /** Host platform label used in the identity line (default: generic). */
- platformName?: string;
/**
- * Optional host-supplied communication-guide section. When omitted, a generic
- * placeholder is used. Hosts inject their real CLI guide here — keeping any
- * platform-specific command documentation OUT of this backend.
+ * Drives the auto-generated `## Message Notifications` section: whether
+ * this runtime's process stays alive across turns (`"persistent"`) or
+ * handles exactly one turn and exits (`"per_turn"`). Pass
+ * `driver.lifecycle.kind` directly — do not hand-write reminder text per
+ * driver.
*/
- communicationGuide?: string;
+ lifecycleKind: "persistent" | "per_turn";
}
/* ------------------------------------------------------------------ */
/* Section builders */
/* ------------------------------------------------------------------ */
-
-function cliToolsSection(cli: string): string {
+function cliToolsSection(): string {
return [
"## CLI tool",
"",
- `\`${cli}\` is your only way to send or receive messages. Commands:`,
+ `\`${CLI}\` is your only way to send or receive messages. Commands:`,
"",
- `1. \`${cli} inbox pull\` — fetch unread messages.`,
- `2. \`${cli} message send\` — send a message to a channel, DM, or thread.`,
+ `1. \`${CLI} inbox pull\` — fetch unread messages.`,
+ `2. \`${CLI} message send\` — send a message to a channel, DM, or thread.`,
"",
- `Run \`${cli} <subcommand> -h\` for full usage and flags.`,
+ `Run \`${CLI} <subcommand> -h\` for full usage and flags.`,
].join("\n");
}
-function messagingHowToSection(cli: string): string {
+function messagingHowToSection(): string {
return [
"## Sending & receiving messages",
"",
- `- Read incoming messages with \`${cli} inbox pull\`.`,
+ `- Read incoming messages with \`${CLI} inbox pull\`.`,
"- Send a reply — two options depending on length:",
- ` - Short: \`${cli} message send --target <ref> --text "brief reply"\``,
- ` - Long: write body to a file, then \`${cli} message send --target <ref> --file /path/to/msg.txt\``,
+ ` - Short: \`${CLI} message send --target <ref> --text "brief reply"\``,
+ ` - Long: write body to a file, then \`${CLI} message send --target <ref> --file /path/to/msg.txt\``,
"- Address your reply to where the message came from.",
"- **Channel alignment**: you cannot send to a channel with unread messages. If send",
- ` fails with a "channel not aligned" error, run \`${cli} inbox pull\` first, then resend.`,
+ ` fails with a "channel not aligned" error, run \`${CLI} inbox pull\` first, then resend.`,
"- Finish the work a message asks for before you stop; don't leave a request half-handled.",
].join("\n");
}
-function channelRefSection(cli: string): string {
+function channelRefSection(): string {
return [
"## Channel refs & message format",
"",
@@ -93,7 +94,7 @@ function channelRefSection(cli: string): string {
"",
"### Message shape",
"",
- `When you call \`${cli} inbox pull\`, you receive messages as JSON objects:`,
+ `When you call \`${CLI} inbox pull\`, you receive messages as JSON objects:`,
"",
"```json",
'{"seq": "#3", "channel": "/demo/general", "sender": "@gustavo", "content": {"text": "hello"}, "time": "2026-06-01T12:00:00Z"}',
@@ -108,7 +109,7 @@ function channelRefSection(cli: string): string {
"",
"### CLI output format",
"",
- `All \`${cli}\` commands output a single JSON line (envelope):`,
+ `All \`${CLI}\` commands output a single JSON line (envelope):`,
'- Success: `{"success": { ... }}`',
'- Error: `{"error": "message", "hint": "optional recovery hint"}`',
].join("\n");
@@ -125,14 +126,14 @@ function credentialHygieneSection(): string {
].join("\n");
}
-function startupSequenceSection(cli: string): string {
+function startupSequenceSection(): string {
return [
"## On wake",
"",
"Each time you're woken up:",
"1. Acknowledge any message already in front of you.",
"2. Read `./memory.md` + latest context timeline to restore state.",
- `3. If notified of unread messages, run \`${cli} inbox pull\` to fetch them.`,
+ `3. If notified of unread messages, run \`${CLI} inbox pull\` to fetch them.`,
"4. Do the work, reply, finish completely before stopping.",
].join("\n");
}
@@ -152,6 +153,7 @@ function communicationStyleSection(): string {
"- Let the person who did the work report on it.",
"- Before going idle, unblock anyone waiting on you.",
"- Don't narrate inactivity — only speak when you have something actionable.",
+ "- Talk in the same language as the sender.",
].join("\n");
}
@@ -192,19 +194,35 @@ function workspaceMemorySection(): string {
].join("\n");
}
-function messageNotificationSection(style: SystemPromptOpts["messageNotificationStyle"], cli: string): string {
- if (style === "poll") {
+/**
+ * The ONE place that decides what an agent needs to know about message
+ * delivery, derived entirely from `lifecycleKind` — no driver hand-types this.
+ *
+ * - `persistent`: the process stays alive across turns, so busy-time inbox
+ * notices can arrive mid-turn; the agent pulls bodies at a natural
+ * breakpoint instead of blocking.
+ * - `per_turn`: the process handles exactly one turn and exits; there is
+ * nothing to poll for mid-turn — finish the current wake, then stop, and
+ * the host spawns a fresh process for the next message.
+ */
+function messageNotificationSection(lifecycleKind: SystemPromptOpts["lifecycleKind"]): string {
+ if (lifecycleKind === "per_turn") {
return [
"## Message Notifications",
- "You run once per wake. Do your work, then stop. The host restarts you on new messages.",
- `Pull the inbox with \`${cli} inbox pull\` at the start of each wake.`,
+ "",
+ "You run once per wake, then your process exits — there is nothing to poll for mid-turn.",
+ "Finish the current wake's work, then stop. The host spawns a brand-new process for the",
+ "next message; it re-checks the inbox at the start of that new wake.",
].join("\n");
}
return [
"## Message Notifications",
- "Alook may inject a lightweight inbox notice mid-turn (no message bodies included).",
- `It's non-urgent — finish your current step, then run \`${cli} inbox pull\` to fetch bodies.`,
- "A notification without bodies still means messages are waiting.",
+ "",
+ "Your process stays alive across turns. Alook may inject a lightweight inbox notice",
+ "mid-turn (no message bodies included) — a notification without bodies still means",
+ "messages are waiting.",
+ `It's non-urgent: finish your current step, then run \`${CLI} inbox pull\` at a natural`,
+ "breakpoint to fetch the bodies.",
].join("\n");
}
@@ -215,45 +233,29 @@ function messageNotificationSection(style: SystemPromptOpts["messageNotification
/**
* Assemble the standing/system prompt.
*
- * Host-NEUTRAL: the backend asserts what's universally true for any agent
- * workspace — identity, CLI tool, messaging shape, credential hygiene, startup
- * sequence, communication style, channel awareness, workspace/memory model, and
- * notification handling. Platform-specific details (message header format, CLI
- * command catalog, thread/task model) are injected by the host via
- * `communicationGuide`.
+ * Asserts what's universally true for any Alook agent workspace — identity,
+ * CLI tool, messaging shape, credential hygiene, startup sequence,
+ * communication style, channel awareness, workspace/memory model, and
+ * notification handling. The only per-driver input is `lifecycleKind`.
*/
export function buildCliSystemPrompt(config: LaunchConfig, opts: SystemPromptOpts): string {
- const cli = opts.cli ?? "alook";
- const platformName = opts.platformName ?? "a collaborative agent workspace";
-
- const identityParts = [`You are an AI agent operating in ${platformName}.`];
+ const identityParts = ["You are an AI agent operating in Alook."];
if (config.agentName) identityParts.push(`Your name is ${config.agentName}.`);
if (config.agentHandle) identityParts.push(`Your handle is \`${config.agentHandle}\` (others use this to @mention you).`);
const sections: string[] = [
identityParts.join(" "),
- cliToolsSection(cli),
- messagingHowToSection(cli),
- channelRefSection(cli),
+ cliToolsSection(),
+ messagingHowToSection(),
+ channelRefSection(),
credentialHygieneSection(),
- startupSequenceSection(cli),
+ startupSequenceSection(),
communicationStyleSection(),
channelAwarenessSection(),
workspaceMemorySection(),
+ messageNotificationSection(opts.lifecycleKind),
];
- if (opts.includeStdinNotificationSection !== false) {
- sections.push(messageNotificationSection(opts.messageNotificationStyle, cli));
- }
-
- if (opts.communicationGuide) sections.push(opts.communicationGuide);
- if (opts.extraCriticalRules?.length) {
- sections.push("## Additional rules\n" + opts.extraCriticalRules.map((r) => `- ${r}`).join("\n"));
- }
- if (opts.postStartupNotes?.length) {
- sections.push("## Notes\n" + opts.postStartupNotes.map((n) => `- ${n}`).join("\n"));
- }
-
if (config.description) {
sections.push("## Role\n" + config.description);
}
diff --git a/src/daemon/src/inbox/projection.ts b/src/daemon/src/inbox/projection.ts
index 8517dd117..31a347c30 100644
--- a/src/daemon/src/inbox/projection.ts
+++ b/src/daemon/src/inbox/projection.ts
@@ -8,7 +8,7 @@
* Messages are bucketed by their resolved `target` (channel / DM / thread),
* each bucket summarized (count, first, latest, sender, flags), and the
* buckets sorted by most-recent activity. The summary is metadata only — it
- * never carries message bodies; the agent pulls those with `alook message check`.
+ * never carries message bodies; the agent pulls those with `alook inbox pull`.
*
* Generic agent-backend abstraction (host-neutral).
*/
diff --git a/src/daemon/src/server/enrollment.test.ts b/src/daemon/src/server/enrollment.test.ts
index 52e5f71fa..42bc76f7e 100644
--- a/src/daemon/src/server/enrollment.test.ts
+++ b/src/daemon/src/server/enrollment.test.ts
@@ -44,4 +44,23 @@ describe("MockServer enrollment (machine credential surface)", () => {
const machineKey = s.enrollMachine();
await expect(s.mintAgentCredential({ machineKey, agentId: "agent_nope" })).rejects.toThrow(/not found/i);
});
+
+ it("rejects minting for an agent bound to a different machine", async () => {
+ const s = new MockServer();
+ const { user } = await s.createUser({ name: "u" });
+ const machineA = s.enrollMachine();
+ const machineB = s.enrollMachine();
+ const { agent } = await s.createAgent({ userId: user.id, name: "cindy", runtime: "mock", machineKey: machineA });
+ await expect(s.mintAgentCredential({ machineKey: machineB, agentId: agent.id })).rejects.toThrow(/not bound/i);
+ // The bound machine still mints fine.
+ const { runnerKey } = await s.mintAgentCredential({ machineKey: machineA, agentId: agent.id });
+ expect(runnerKey.startsWith("sk_agent_")).toBe(true);
+ });
+
+ it("agents created without a machineKey remain unbound (no regression)", async () => {
+ const { s, agentId } = await withAgent();
+ const anyMachine = s.enrollMachine();
+ const { runnerKey } = await s.mintAgentCredential({ machineKey: anyMachine, agentId });
+ expect(runnerKey.startsWith("sk_agent_")).toBe(true);
+ });
});
diff --git a/src/daemon/src/server/mockServer.ts b/src/daemon/src/server/mockServer.ts
index 05893710f..9f74b07b7 100644
--- a/src/daemon/src/server/mockServer.ts
+++ b/src/daemon/src/server/mockServer.ts
@@ -111,6 +111,14 @@ export class MockServer implements ServerApi, AdminApi, EnrollmentApi {
private readonly machineKeys = new Set<string>();
/** runnerKey → agentId, so a swapped-in runner key is traceable (tier-2). */
private readonly runnerKeys = new Map<string, string>();
+ /**
+ * agentId → machineKey, when `createAgent` was given one. Mirrors production's
+ * bot↔machine binding (`communityBotBinding`) so `mintAgentCredential` can
+ * reject a mint attempted from a different machine. Agents created without a
+ * `machineKey` are left unbound (no check performed) for backward
+ * compatibility with callers that don't care about this invariant.
+ */
+ private readonly agentMachineKey = new Map<string, string>();
constructor(seed?: MockServerSeed) {
this.seed = seed;
@@ -146,7 +154,13 @@ export class MockServer implements ServerApi, AdminApi, EnrollmentApi {
if (!this.agentHandles.has(req.agentId)) {
throw apiError("NOT_FOUND", `agent ${req.agentId} not found`);
}
- // MVP: no machine↔agent binding check yet (TODO once that table exists).
+ // Mirrors the production enroll-agent route: an agent bound to a machine
+ // can only be minted a runner key from THAT machine's key. Agents created
+ // without a `machineKey` (most tests) are left unbound and unchecked.
+ const boundTo = this.agentMachineKey.get(req.agentId);
+ if (boundTo && boundTo !== req.machineKey) {
+ throw apiError("NOT_FOUND", `agent ${req.agentId} not bound to this machine`);
+ }
const runnerKey = `sk_agent_${crypto.randomBytes(24).toString("base64url")}`;
this.runnerKeys.set(runnerKey, req.agentId);
return { runnerKey };
@@ -448,10 +462,12 @@ export class MockServer implements ServerApi, AdminApi, EnrollmentApi {
name: string;
runtime?: string;
instruction?: string;
+ machineKey?: string;
}): Promise<{ agent: Agent }> {
// Agent is the user's asset — created independent of any server.
const agent: Agent = { id: this.mkId("agent"), name: req.name, userId: req.userId };
this.agentHandles.set(agent.id, `@${req.name}`);
+ if (req.machineKey) this.agentMachineKey.set(agent.id, req.machineKey);
// The agent's identity (name + instruction) lives in its RuntimeConfig — the
// same config downlinked via agent:wake — so the daemon gets it from the
// server, not by inventing it.
diff --git a/src/shared/src/community-cli-contract.ts b/src/shared/src/community-cli-contract.ts
index ba8f6cd4a..355eaefd4 100644
--- a/src/shared/src/community-cli-contract.ts
+++ b/src/shared/src/community-cli-contract.ts
@@ -538,8 +538,18 @@ export interface AdminApi {
/**
* Create an agent. An agent is a USER's asset and exists independently of any
* server — it joins servers later via `addAgentToServer`. No server here.
+ *
+ * `machineKey` optionally binds the agent to that machine (mirrors production's
+ * bot↔machine binding), enabling `EnrollmentApi.mintAgentCredential` to reject
+ * a mint from a different machine. Omitting it leaves the agent unbound.
*/
- createAgent(req: { userId: UserId; name: string; runtime?: string; instruction?: string }): Promise<{ agent: Agent }>;
+ createAgent(req: {
+ userId: UserId;
+ name: string;
+ runtime?: string;
+ instruction?: string;
+ machineKey?: string;
+ }): Promise<{ agent: Agent }>;
createServer(req: { name: string }): Promise<{ server: Server }>;
/** Membership is a separate agent↔server relation; an agent may join many. */
addAgentToServer(req: { agentId: AgentId; server: ServerId }): Promise<void>;
@@ -579,8 +589,10 @@ export interface EnrollmentApi {
* machineKey (401 if unknown) and that the agent exists (404 if not). Returns a
* scoped, revocable `sk_agent_` runner key the daemon's proxy swaps in.
*
- * MVP: does NOT yet enforce that `agentId` is bound to this machine (no
- * machine↔agent assignment table) — TODO once that ownership model exists.
+ * Implementations MUST also enforce that `agentId` is bound to THIS machine
+ * (404 if bound elsewhere or unbound) — see the production `enroll-agent`
+ * route's binding check, mirrored by `MockServer` when `createAgent` was
+ * given a `machineKey`.
*/
mintAgentCredential(req: { machineKey: string; agentId: AgentId }): Promise<{ runnerKey: string; expiresAt?: number }>;
}
diff --git a/src/shared/src/db/queries/community/agent-inbox.ts b/src/shared/src/db/queries/community/agent-inbox.ts
index cdd8ebf03..f82d50326 100644
--- a/src/shared/src/db/queries/community/agent-inbox.ts
+++ b/src/shared/src/db/queries/community/agent-inbox.ts
@@ -455,6 +455,59 @@ export async function toInboxRows(
});
}
+/**
+ * The single most-recent unread message id for a bot, across ALL its scopes
+ * (channels + DMs combined) — feeds `dispatchOneUnreadWake`'s `{ messageId,
+ * botUserId }` input for a daemon-initiated wake resync (as opposed to
+ * `getInboxSnapshotForAgent`'s per-scope aggregation, which has no single
+ * message id to hand back). "Most recent" is by `createdAt`, since `seq` is a
+ * per-scope counter and isn't comparable across scopes (see
+ * `listUnreadMessagesForAgent`'s doc comment). Same scope/membership/
+ * exclude-self-authored predicates as `listUnreadMessagesForAgent`. Returns
+ * `null` when the bot has no unread anywhere.
+ */
+export async function getLatestUnreadMessageForAgent(
+ db: Database,
+ botUserId: string
+): Promise<{ messageId: string } | null> {
+ const rows = await db
+ .select({ id: communityMessage.id })
+ .from(communityMessage)
+ .leftJoin(communityChannel, eq(communityChannel.id, communityMessage.channelId))
+ .leftJoin(
+ communityServerMember,
+ and(eq(communityServerMember.serverId, communityChannel.serverId), eq(communityServerMember.userId, botUserId))
+ )
+ .leftJoin(communityDmConversation, eq(communityDmConversation.id, communityMessage.dmConversationId))
+ .leftJoin(
+ communityReadState,
+ and(
+ eq(communityReadState.userId, botUserId),
+ or(
+ eq(communityReadState.channelId, communityMessage.channelId),
+ eq(communityReadState.dmConversationId, communityMessage.dmConversationId)
+ )
+ )
+ )
+ .where(
+ and(
+ ne(communityMessage.authorId, botUserId),
+ sql`${communityMessage.seq} > COALESCE(${communityReadState.lastReadSeq}, 0)`,
+ or(
+ and(isNotNull(communityMessage.channelId), eq(communityServerMember.userId, botUserId)),
+ and(
+ isNotNull(communityMessage.dmConversationId),
+ or(eq(communityDmConversation.user1Id, botUserId), eq(communityDmConversation.user2Id, botUserId))
+ )
+ )
+ )
+ )
+ .orderBy(desc(communityMessage.createdAt))
+ .limit(1);
+
+ return rows[0] ? { messageId: rows[0].id } : null;
+}
+
/**
* Seq-anchored pagination for `read` — the existing `listMessages` orders by
* `createdAt` and has no `around` support, so this is a dedicated query.
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index 142b9b68f..51a27070b 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -247,7 +247,6 @@ export {
CommunityBotCreateRequestSchema,
CommunityBotPatchRequestSchema,
CommunityBotAddToServerRequestSchema,
- CommunityDaemonSendAsBotRequestSchema,
CommunityAgentCursorSchema,
CommunityAgentSendRequestSchema,
CommunityAgentInboxPullRequestSchema,
@@ -317,7 +316,6 @@ export type {
CommunityBotCreateRequest,
CommunityBotPatchRequest,
CommunityBotAddToServerRequest,
- CommunityDaemonSendAsBotRequest,
CommunityAgentCursor,
CommunityAgentSendRequest,
CommunityAgentInboxPullRequest,
diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.ts
index 5989d78dd..05e8ea14a 100644
--- a/src/shared/src/schemas.ts
+++ b/src/shared/src/schemas.ts
@@ -1025,20 +1025,6 @@ export type CommunityBotAddToServerRequest = z.infer<
typeof CommunityBotAddToServerRequestSchema
>;
-export const CommunityDaemonSendAsBotRequestSchema = z.object({
- // Target — channel or dm — plus target id.
- target: z.enum(["channel", "dm"]),
- targetId: z.string().min(1),
- content: z.string().max(4000),
- replyToId: z.string().optional(),
- mentionType: z.enum(["everyone", "here", "user"]).optional(),
- embeds: z.array(z.unknown()).optional(),
- attachments: z.array(z.unknown()).optional(),
-});
-export type CommunityDaemonSendAsBotRequest = z.infer<
- typeof CommunityDaemonSendAsBotRequestSchema
->;
-
// ---------------------------------------------------------------------------
// Community agent CLI bridge — `withAgentRunnerAuth`-mounted `/api/community/agent/*`
// request/response validators. Mirror the lifted `@alook/shared/community-cli-contract`
diff --git a/src/shared/test/queries/community-agent-inbox.test.ts b/src/shared/test/queries/community-agent-inbox.test.ts
index d1d556a01..8c12282a3 100644
--- a/src/shared/test/queries/community-agent-inbox.test.ts
+++ b/src/shared/test/queries/community-agent-inbox.test.ts
@@ -183,6 +183,41 @@ describe("listUnreadMessagesForAgent", () => {
});
});
+describe("getLatestUnreadMessageForAgent", () => {
+ it("returns null when there's no unread anywhere", async () => {
+ const db = createSequentialDb([[]]);
+ const result = await agentInbox.getLatestUnreadMessageForAgent(db, "bot_1");
+ expect(result).toBeNull();
+ });
+
+ it("returns the single most-recent unread message id, ordered by createdAt desc limit 1", async () => {
+ // The mock DB only records the LAST call to each chain method, so this
+ // exercises the id extraction — the createdAt-desc/limit-1 ordering
+ // itself is asserted via the `.orderBy`/`.limit` call-args check below.
+ const db = createSequentialDb([[{ id: "m_latest" }]]);
+ const result = await agentInbox.getLatestUnreadMessageForAgent(db, "bot_1");
+ expect(result).toEqual({ messageId: "m_latest" });
+ });
+
+ it("orders by createdAt desc and limits to 1 (comparable across channel + DM scopes, unlike seq)", async () => {
+ const db = createSequentialDb([[]]);
+ await agentInbox.getLatestUnreadMessageForAgent(db, "bot_1");
+ const chainResult = db.select.mock.results[0]!.value;
+ expect(chainResult.orderBy).toHaveBeenCalledTimes(1);
+ expect(chainResult.limit).toHaveBeenCalledWith(1);
+ });
+
+ it("joins scope tables before unread filtering (same predicates as listUnreadMessagesForAgent)", async () => {
+ const db = createSequentialDb([[]]);
+ await agentInbox.getLatestUnreadMessageForAgent(db, "bot_1");
+ const chainResult = db.select.mock.results[0]!.value;
+ expect(chainResult.leftJoin).toHaveBeenCalledTimes(4);
+ expect(chainResult.leftJoin.mock.invocationCallOrder[0]).toBeLessThan(
+ chainResult.where.mock.invocationCallOrder[0]
+ );
+ });
+});
+
describe("getInboxSnapshotForAgent", () => {
it("returns [] and skips the user-name lookup when there's no pending unread", async () => {
const db = createSequentialDb([[]]);
diff --git a/src/web/src/app/api/community/daemon/bots/[botId]/messages/route.test.ts b/src/web/src/app/api/community/daemon/bots/[botId]/messages/route.test.ts
deleted file mode 100644
index 040f4e9df..000000000
--- a/src/web/src/app/api/community/daemon/bots/[botId]/messages/route.test.ts
+++ /dev/null
@@ -1,121 +0,0 @@
-import { describe, it, expect, vi, beforeEach } from "vitest"
-import { NextRequest } from "next/server"
-
-vi.mock("@opennextjs/cloudflare", () => ({
- getCloudflareContext: vi.fn(async () => ({ env: { DB: {} } })),
-}))
-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
-
-const mockFindActiveCredential = vi.fn()
-const mockGetUserInternal = vi.fn()
-const mockGetBotBinding = vi.fn()
-const mockGetChannel = vi.fn()
-const mockGetMember = vi.fn()
-const mockGetDM = vi.fn()
-const mockIsBlocked = vi.fn()
-
-vi.mock("@alook/shared", async () => {
- const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
- return {
- ...actual,
- queries: {
- ...actual.queries,
- communityMachine: { findActiveCredentialByBearer: (...a: unknown[]) => mockFindActiveCredential(...a) },
- user: { getUserInternal: (...a: unknown[]) => mockGetUserInternal(...a) },
- communityBot: { getBotBinding: (...a: unknown[]) => mockGetBotBinding(...a) },
- communityChannel: { getChannel: (...a: unknown[]) => mockGetChannel(...a) },
- communityMember: { getMember: (...a: unknown[]) => mockGetMember(...a) },
- communityDm: { getDM: (...a: unknown[]) => mockGetDM(...a) },
- communityFriendship: { isBlocked: (...a: unknown[]) => mockIsBlocked(...a) },
- },
- }
-})
-
-// `createCommunityMessage`'s own audit-emission logic is unit-tested in
-// `message-handler.test.ts` (plan §10) — this route test's only job is
-// verifying THIS route calls it with `source: "daemon-http"` and does NOT
-// also fire its own `logAudit` (the duplicate-audit regression this route
-// used to have before the relocation, see route.ts's inline comments).
-const mockCreateCommunityMessage = vi.fn()
-vi.mock("@/lib/community/message-handler", () => ({
- createCommunityMessage: (...a: unknown[]) => mockCreateCommunityMessage(...a),
-}))
-
-const mockLogAudit = vi.fn()
-vi.mock("@/lib/community/audit", async () => {
- const actual = await vi.importActual<typeof import("@/lib/community/audit")>("@/lib/community/audit")
- return { ...actual, logAudit: (...a: unknown[]) => mockLogAudit(...a) }
-})
-
-import { POST } from "./route"
-
-function req(body: unknown, headers: Record<string, string> = {}): NextRequest {
- return new NextRequest("http://localhost/api/community/daemon/bots/bot_1/messages", {
- method: "POST",
- headers: { "content-type": "application/json", ...headers },
- body: typeof body === "string" ? body : JSON.stringify(body),
- })
-}
-
-function ctxParams() {
- return { params: Promise.resolve({ botId: "bot_1" }) }
-}
-
-describe("POST /api/community/daemon/bots/[botId]/messages", () => {
- beforeEach(() => {
- vi.clearAllMocks()
- mockFindActiveCredential.mockResolvedValue({ credentialId: "cmk_1", userId: "u_owner", machineId: "cm_1" })
- mockGetUserInternal.mockResolvedValue({ isBot: true, ownerUserId: "u_owner", deletedAt: null })
- mockGetBotBinding.mockResolvedValue({ machineId: "cm_1", runtime: "claude" })
- })
-
- it("channel send: calls createCommunityMessage with source 'daemon-http' and never calls logAudit itself", async () => {
- mockGetChannel.mockResolvedValue({ id: "ch_1", serverId: "srv_1" })
- mockGetMember.mockResolvedValue({ userId: "bot_1" })
- mockCreateCommunityMessage.mockResolvedValue({ ok: true, row: { id: "m_1" } })
-
- const res = await POST(
- req({ target: "channel", targetId: "ch_1", content: "hi" }, { Authorization: "Bearer cmk_1" }),
- ctxParams()
- )
-
- expect(res.status).toBe(200)
- expect(await res.json()).toEqual({ messageId: "m_1" })
- expect(mockCreateCommunityMessage).toHaveBeenCalledTimes(1)
- expect(mockCreateCommunityMessage).toHaveBeenCalledWith(
- expect.objectContaining({ authorId: "bot_1", source: "daemon-http" })
- )
- // The route itself must never call logAudit — that's exclusively
- // `createCommunityMessage`'s job now (which is mocked away here).
- expect(mockLogAudit).not.toHaveBeenCalled()
- })
-
- it("DM send: calls createCommunityMessage with source 'daemon-http' and never calls logAudit itself", async () => {
- mockGetDM.mockResolvedValue({ id: "dm_1", user1Id: "bot_1", user2Id: "peer_1" })
- mockIsBlocked.mockResolvedValue(false)
- mockCreateCommunityMessage.mockResolvedValue({ ok: true, row: { id: "m_dm_1" } })
-
- const res = await POST(
- req({ target: "dm", targetId: "dm_1", content: "hey" }, { Authorization: "Bearer cmk_1" }),
- ctxParams()
- )
-
- expect(res.status).toBe(200)
- expect(await res.json()).toEqual({ messageId: "m_dm_1" })
- expect(mockCreateCommunityMessage).toHaveBeenCalledWith(
- expect.objectContaining({ authorId: "bot_1", source: "daemon-http" })
- )
- expect(mockLogAudit).not.toHaveBeenCalled()
- })
-
- it("403 bot_not_a_member when the bot isn't in the target channel's server — no message created", async () => {
- mockGetChannel.mockResolvedValue({ id: "ch_1", serverId: "srv_1" })
- mockGetMember.mockResolvedValue(null)
- const res = await POST(
- req({ target: "channel", targetId: "ch_1", content: "hi" }, { Authorization: "Bearer cmk_1" }),
- ctxParams()
- )
- expect(res.status).toBe(403)
- expect(mockCreateCommunityMessage).not.toHaveBeenCalled()
- })
-})
diff --git a/src/web/src/app/api/community/daemon/bots/[botId]/messages/route.ts b/src/web/src/app/api/community/daemon/bots/[botId]/messages/route.ts
deleted file mode 100644
index aa14647b2..000000000
--- a/src/web/src/app/api/community/daemon/bots/[botId]/messages/route.ts
+++ /dev/null
@@ -1,113 +0,0 @@
-import { NextResponse, type NextRequest } from "next/server"
-import { queries, CommunityDaemonSendAsBotRequestSchema } from "@alook/shared"
-import { getDb } from "@/lib/db"
-import { withCommunityDaemonAuth } from "@/lib/middleware/community-daemon-auth"
-import { createCommunityMessage } from "@/lib/community/message-handler"
-import { requireNotBlocked } from "@/lib/community/permissions"
-
-/**
- * POST /api/community/daemon/bots/[botId]/messages
- *
- * Author a message AS a bot. Daemon-auth path — the daemon holds the `cmk_`
- * that identifies its machine, and the bot must be
- * - owned by ctx.userId
- * - bound to ctx.machineId
- * - a member of the target channel/DM (for channel targets)
- */
-export const POST = withCommunityDaemonAuth(async (req: NextRequest, ctx) => {
- const botId = ctx.params?.botId as string
- const db = getDb(ctx.env.DB)
-
- let raw: unknown
- try {
- raw = await req.json()
- } catch {
- return NextResponse.json({ error: "invalid JSON body" }, { status: 400 })
- }
- const parsed = CommunityDaemonSendAsBotRequestSchema.safeParse(raw)
- if (!parsed.success) {
- return NextResponse.json(
- { error: "invalid payload", details: parsed.error.flatten() },
- { status: 400 },
- )
- }
-
- // Ownership + machine binding — same shape as enroll-agent gate.
- const target = await queries.user.getUserInternal(db, botId)
- if (
- !target ||
- target.isBot !== true ||
- target.ownerUserId !== ctx.userId ||
- target.deletedAt !== null
- ) {
- return NextResponse.json({ error: "bot not found" }, { status: 404 })
- }
- const binding = await queries.communityBot.getBotBinding(db, botId)
- if (!binding || binding.machineId !== ctx.machineId) {
- return NextResponse.json({ error: "bot not on this machine" }, { status: 404 })
- }
-
- const body = parsed.data
-
- if (body.target === "channel") {
- const channel = await queries.communityChannel.getChannel(db, body.targetId)
- if (!channel) return NextResponse.json({ error: "channel not found" }, { status: 404 })
- // Bot must be a member of the channel's server.
- const member = await queries.communityMember.getMember(db, channel.serverId, botId)
- if (!member) return NextResponse.json({ error: "bot_not_a_member" }, { status: 403 })
-
- const result = await createCommunityMessage({
- db,
- authorId: botId,
- target: { kind: "channel", channelId: body.targetId, serverId: channel.serverId },
- body: {
- content: body.content,
- replyToId: body.replyToId,
- mentionType: body.mentionType,
- attachments: body.attachments,
- },
- source: "daemon-http",
- })
- if (!result.ok) {
- return NextResponse.json({ error: result.error }, { status: result.status })
- }
- // MESSAGE_AUTHORED_AS_BOT audit now fires from inside createCommunityMessage
- // itself (plan §10) — do not re-add a call here, or every bot message gets
- // audited twice.
- return NextResponse.json({ messageId: result.row.id })
- }
-
- // dm target
- const dm = await queries.communityDm.getDM(db, body.targetId)
- if (!dm) return NextResponse.json({ error: "dm not found" }, { status: 404 })
- const inDm = dm.user1Id === botId || dm.user2Id === botId
- if (!inDm) return NextResponse.json({ error: "bot_not_a_member" }, { status: 403 })
- const otherUserId = dm.user1Id === botId ? dm.user2Id : dm.user1Id
- if (!otherUserId) return NextResponse.json({ error: "dm peer missing" }, { status: 404 })
-
- // Block gate — a bot must not be able to reach a peer who has blocked it
- // (or vice versa). Mirrors the user-authored DM send path.
- const notBlocked = await requireNotBlocked(db, botId, otherUserId)
- if (!notBlocked.ok) {
- return NextResponse.json({ error: notBlocked.error }, { status: notBlocked.status })
- }
-
- const result = await createCommunityMessage({
- db,
- authorId: botId,
- target: { kind: "dm", dmId: dm.id, otherUserId },
- body: {
- content: body.content,
- replyToId: body.replyToId,
- attachments: body.attachments,
- },
- source: "daemon-http",
- })
- if (!result.ok) {
- return NextResponse.json({ error: result.error }, { status: result.status })
- }
- // MESSAGE_AUTHORED_AS_BOT audit now fires from inside createCommunityMessage
- // itself (plan §10) — do not re-add a call here, or every bot message gets
- // audited twice.
- return NextResponse.json({ messageId: result.row.id })
-})
diff --git a/src/web/src/app/api/community/daemon/enroll-agent/route.ts b/src/web/src/app/api/community/daemon/enroll-agent/route.ts
index 47cac435b..8545eb450 100644
--- a/src/web/src/app/api/community/daemon/enroll-agent/route.ts
+++ b/src/web/src/app/api/community/daemon/enroll-agent/route.ts
@@ -11,9 +11,10 @@ import { withCommunityDaemonAuth } from "@/lib/middleware/community-daemon-auth"
* POST /api/community/daemon/enroll-agent
*
* Given a valid Bearer `cmk_...` credential, mint (or reuse) a per-agent
- * runner key (`crk_...`) scoped to (userId, machineId, agentId). The daemon
- * uses this via its local credential proxy when it launches subprocess
- * CLIs — v1 has no data-plane consumer yet, but the wire is settled.
+ * runner key (`crk_...`) scoped to (userId, machineId, agentId). The daemon's
+ * `CredentialBroker` swaps this runner key in for the agent's per-launch
+ * voucher at its local credential proxy, so subprocess CLIs never see it
+ * directly — they only reach `/api/community/agent/*` through that proxy.
*/
export const POST = withCommunityDaemonAuth(async (req, ctx) => {
let raw: unknown
diff --git a/src/web/src/app/api/community/daemon/resync-wakes/route.test.ts b/src/web/src/app/api/community/daemon/resync-wakes/route.test.ts
new file mode 100644
index 000000000..f599a00c7
--- /dev/null
+++ b/src/web/src/app/api/community/daemon/resync-wakes/route.test.ts
@@ -0,0 +1,109 @@
+import { describe, it, expect, vi, beforeEach } from "vitest"
+import { NextRequest } from "next/server"
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(async () => ({ env: { DB: {} } })),
+}))
+
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
+
+const mockFindCred = vi.fn()
+const mockListBotsForMachine = vi.fn()
+const mockGetLatestUnreadMessageForAgent = vi.fn()
+const mockDispatchOneUnreadWake = vi.fn()
+
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<any>("@alook/shared")
+ return {
+ ...actual,
+ dispatchOneUnreadWake: (...a: unknown[]) => mockDispatchOneUnreadWake(...a),
+ queries: {
+ communityMachine: {
+ findActiveCredentialByBearer: (...a: unknown[]) => mockFindCred(...a),
+ },
+ communityBot: {
+ listBotsForMachine: (...a: unknown[]) => mockListBotsForMachine(...a),
+ },
+ communityAgentInbox: {
+ getLatestUnreadMessageForAgent: (...a: unknown[]) => mockGetLatestUnreadMessageForAgent(...a),
+ },
+ },
+ }
+})
+
+import { POST } from "./route"
+
+function req(headers: Record<string, string> = {}): NextRequest {
+ return new NextRequest("http://localhost/api/community/daemon/resync-wakes", {
+ method: "POST",
+ headers,
+ })
+}
+
+describe("POST /api/community/daemon/resync-wakes", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockFindCred.mockResolvedValue({ credentialId: "cmk_ok", userId: "u_1", machineId: "cm_1" })
+ })
+
+ it("returns { woken: 0 } and does nothing when the machine has no bots", async () => {
+ mockListBotsForMachine.mockResolvedValue([])
+ const res = await POST(req({ Authorization: "Bearer cmk_ok" }))
+ expect(res.status).toBe(200)
+ expect(await res.json()).toEqual({ woken: 0 })
+ expect(mockGetLatestUnreadMessageForAgent).not.toHaveBeenCalled()
+ expect(mockDispatchOneUnreadWake).not.toHaveBeenCalled()
+ })
+
+ it("dispatches a wake for a bot with pending unread and counts it", async () => {
+ mockListBotsForMachine.mockResolvedValue([{ id: "bot_1", name: "cindy", description: "" }])
+ mockGetLatestUnreadMessageForAgent.mockResolvedValue({ messageId: "msg_1" })
+ mockDispatchOneUnreadWake.mockResolvedValue({ outcome: "sent" })
+
+ const res = await POST(req({ Authorization: "Bearer cmk_ok" }))
+
+ expect(mockDispatchOneUnreadWake).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.anything(),
+ { messageId: "msg_1", botUserId: "bot_1" }
+ )
+ expect(await res.json()).toEqual({ woken: 1 })
+ })
+
+ it("skips bots with no pending unread — not counted, dispatch never called for them", async () => {
+ mockListBotsForMachine.mockResolvedValue([{ id: "bot_1", name: "cindy", description: "" }])
+ mockGetLatestUnreadMessageForAgent.mockResolvedValue(null)
+
+ const res = await POST(req({ Authorization: "Bearer cmk_ok" }))
+
+ expect(mockDispatchOneUnreadWake).not.toHaveBeenCalled()
+ expect(await res.json()).toEqual({ woken: 0 })
+ })
+
+ it("does not count a skip/delivered_nowhere outcome as woken", async () => {
+ mockListBotsForMachine.mockResolvedValue([
+ { id: "bot_1", name: "a", description: "" },
+ { id: "bot_2", name: "b", description: "" },
+ ])
+ mockGetLatestUnreadMessageForAgent.mockResolvedValue({ messageId: "msg_x" })
+ mockDispatchOneUnreadWake
+ .mockResolvedValueOnce({ outcome: "skip", reason: "already_read" })
+ .mockResolvedValueOnce({ outcome: "delivered_nowhere", machineId: "cm_1" })
+
+ const res = await POST(req({ Authorization: "Bearer cmk_ok" }))
+
+ expect(await res.json()).toEqual({ woken: 0 })
+ })
+
+ it("401 without Authorization", async () => {
+ const res = await POST(req())
+ expect(res.status).toBe(401)
+ expect(mockListBotsForMachine).not.toHaveBeenCalled()
+ })
+
+ it("401 with unknown credential", async () => {
+ mockFindCred.mockResolvedValue(null)
+ const res = await POST(req({ Authorization: "Bearer cmk_bad" }))
+ expect(res.status).toBe(401)
+ })
+})
diff --git a/src/web/src/app/api/community/daemon/resync-wakes/route.ts b/src/web/src/app/api/community/daemon/resync-wakes/route.ts
new file mode 100644
index 000000000..e112993d3
--- /dev/null
+++ b/src/web/src/app/api/community/daemon/resync-wakes/route.ts
@@ -0,0 +1,38 @@
+import { NextResponse } from "next/server"
+import { queries, dispatchOneUnreadWake } from "@alook/shared"
+import { getDb } from "@/lib/db"
+import { withCommunityDaemonAuth } from "@/lib/middleware/community-daemon-auth"
+
+/**
+ * POST /api/community/daemon/resync-wakes
+ *
+ * Daemon-initiated recovery for the "message sent while the daemon was
+ * offline" gap: `WAKE_QUEUE`'s consumer acks (never retries) a wake whose
+ * daemon was unreachable at delivery time (`dispatchOneUnreadWake`'s
+ * `delivered_nowhere` outcome) — that queue item is gone for good. Rather
+ * than the server pushing a catch-up wake on its own when the daemon's WS
+ * reconnects, the DAEMON proactively calls this route right after it opens
+ * its control-plane connection (`channel.onOpen()`), asking "do any of my
+ * bots still have unread work?".
+ *
+ * This route decides nothing new about addressing/config — for every bot
+ * bound to `ctx.machineId` with pending unread, it calls the SAME
+ * `dispatchOneUnreadWake` the real `alook-wake-worker` queue consumer uses,
+ * which re-reads current D1 state and forwards a freshly built `agent:wake`.
+ * Because the daemon's WS just connected, `sendWakeToMachine` finds a live
+ * socket this time and delivers immediately.
+ */
+export const POST = withCommunityDaemonAuth(async (_req, ctx) => {
+ const db = getDb(ctx.env.DB)
+ const bots = await queries.communityBot.listBotsForMachine(db, ctx.machineId)
+
+ let woken = 0
+ for (const bot of bots) {
+ const latest = await queries.communityAgentInbox.getLatestUnreadMessageForAgent(db, bot.id)
+ if (!latest) continue
+ const result = await dispatchOneUnreadWake(db, ctx.env, { messageId: latest.messageId, botUserId: bot.id })
+ if (result.outcome === "sent") woken++
+ }
+
+ return NextResponse.json({ woken })
+})
diff --git a/src/web/src/lib/middleware/community-agent-runner-auth.ts b/src/web/src/lib/middleware/community-agent-runner-auth.ts
index 61c005565..c38ae05c3 100644
--- a/src/web/src/lib/middleware/community-agent-runner-auth.ts
+++ b/src/web/src/lib/middleware/community-agent-runner-auth.ts
@@ -3,7 +3,7 @@ import { getCloudflareContext } from "@opennextjs/cloudflare"
import { queries } from "@alook/shared"
import { getDb } from "@/lib/db"
-export interface AgentRunnerAuthContext {
+interface AgentRunnerAuthContext {
env: Env
/** The BOT's own user id — `row.agentId` from `findActiveAgentRunnerKeyByBearer`. */
botUserId: string