Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(daemon,community): bot ownership + activity telemetry + bare /server refs

Gus6f42b2a014c5
diff --git a/src/daemon/src/daemon/createDaemon.ts b/src/daemon/src/daemon/createDaemon.ts
index 2db3b1198..a99dbf045 100644
--- a/src/daemon/src/daemon/createDaemon.ts
+++ b/src/daemon/src/daemon/createDaemon.ts
@@ -138,10 +138,20 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa
//
// Note: `cmk_`-rotation-implies-re-pair is documented as an assumption;
// runtime code doesn't handle rotation.
- const botsById = new Map<string, { name: string; discriminator: string; description?: string }>();
+ const botsById = new Map<
+ string,
+ { name: string; discriminator: string; description?: string; ownerName?: string; ownerDiscriminator?: string }
+ >();
async function listMyBotsHttp(): Promise<
- Array<{ id: string; name: string; discriminator: string; description?: string }>
+ Array<{
+ id: string;
+ name: string;
+ discriminator: string;
+ description?: string;
+ ownerName?: string;
+ ownerDiscriminator?: string;
+ }>
> {
const res = await fetch(`${opts.serverUrl}/api/community/daemon/bots`, {
method: "GET",
@@ -149,7 +159,14 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa
});
if (!res.ok) throw new Error(`listMyBots ${res.status}`);
const json = (await res.json()) as {
- bots?: Array<{ id: string; name: string; discriminator: string; description?: string }>;
+ bots?: Array<{
+ id: string;
+ name: string;
+ discriminator: string;
+ description?: string;
+ ownerName?: string;
+ ownerDiscriminator?: string;
+ }>;
};
return json.bots ?? [];
}
@@ -163,7 +180,13 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa
// Server snapshot wins — reconcile the cache.
botsById.clear();
for (const b of bots) {
- botsById.set(b.id, { name: b.name, discriminator: b.discriminator, description: b.description });
+ botsById.set(b.id, {
+ name: b.name,
+ discriminator: b.discriminator,
+ description: b.description,
+ ownerName: b.ownerName,
+ ownerDiscriminator: b.ownerDiscriminator,
+ });
}
log.info("cold-start bot-cache warmup succeeded", { bots: bots.length, attempt });
return;
@@ -252,12 +275,24 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa
function handleBotFrame(cmd: HostCommand): void {
switch (cmd.type) {
case "bot:added":
- botsById.set(cmd.botId, { name: cmd.name, discriminator: cmd.discriminator, description: cmd.description });
+ botsById.set(cmd.botId, {
+ name: cmd.name,
+ discriminator: cmd.discriminator,
+ description: cmd.description,
+ ownerName: cmd.ownerName,
+ ownerDiscriminator: cmd.ownerDiscriminator,
+ });
log.debug("bot:added", { botId: cmd.botId, name: cmd.name });
break;
case "bot:updated": {
const prev = botsById.get(cmd.botId);
- botsById.set(cmd.botId, { name: cmd.name, discriminator: cmd.discriminator, description: cmd.description });
+ botsById.set(cmd.botId, {
+ name: cmd.name,
+ discriminator: cmd.discriminator,
+ description: cmd.description,
+ ownerName: cmd.ownerName,
+ ownerDiscriminator: cmd.ownerDiscriminator,
+ });
// If a subprocess is running for this bot AND name/description changed,
// stop it so the next wake trigger spawns a fresh subprocess with the
// new system prompt. Rename is effective on next spawn, not mid-flight.
@@ -324,11 +359,20 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa
? { agentHandle: `@${formatHandle(botMeta.name, botMeta.discriminator)}` }
: {}),
...(botMeta?.description ? { description: botMeta.description } : {}),
+ ...(botMeta?.ownerName && botMeta?.ownerDiscriminator
+ ? { ownerHandle: `@${formatHandle(botMeta.ownerName, botMeta.ownerDiscriminator)}` }
+ : {}),
} as LaunchContext["config"],
} as Omit<LaunchContext, "prompt" | "standingPrompt"> & { config?: LaunchContext["config"] };
},
tickIntervalMs: opts.tickIntervalMs ?? 2000,
onAgentSession: (info) => void channel.reportAgentSession(info),
+ onAgentActivity: (info) => void channel.reportAgentActivity?.(info),
+ // Idle hibernation / stall-recovery stops the subprocess without a
+ // server-sent agent:stop; keep AgentRouter.running aligned so the next
+ // `ready` frame's `runningAgents` reflects what's actually live and the
+ // server's reconciler safety net can flip stale pills to idle.
+ onAgentLocallyStopped: (info) => router?.markLocallyStopped(info.agentId),
// Only the "pi" runtime declares `Driver.createSession` today (in-process
// SDK, no child process) — this is only ever consulted for that case.
sdkDriverDepsFor: (ctx) => createPiSdkDriverDeps(ctx),
@@ -358,7 +402,13 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa
try {
const bots = await listMyBotsHttp();
for (const b of bots) {
- botsById.set(b.id, { name: b.name, discriminator: b.discriminator, description: b.description });
+ botsById.set(b.id, {
+ name: b.name,
+ discriminator: b.discriminator,
+ description: b.description,
+ ownerName: b.ownerName,
+ ownerDiscriminator: b.ownerDiscriminator,
+ });
}
} catch {
// Fall through — still treat as unknown below.
diff --git a/src/daemon/src/drivers/systemPrompt.test.ts b/src/daemon/src/drivers/systemPrompt.test.ts
index 7a0efb8fe..f70acb9f8 100644
--- a/src/daemon/src/drivers/systemPrompt.test.ts
+++ b/src/daemon/src/drivers/systemPrompt.test.ts
@@ -54,6 +54,20 @@ describe("buildCliSystemPrompt", () => {
expect(without).not.toContain("#7392");
});
+ it("injects ownerHandle and an owner-privacy statement into the prompt only when set", () => {
+ const withOwner = buildCliSystemPrompt(
+ { ...baseConfig, ownerHandle: "@gustavo#5150" },
+ { lifecycleKind: "persistent" },
+ );
+ expect(withOwner).toContain("@gustavo#5150");
+ expect(withOwner.toLowerCase()).toContain("owned by");
+ expect(withOwner.toLowerCase()).toContain("never share");
+
+ const without = buildCliSystemPrompt(baseConfig, { lifecycleKind: "persistent" });
+ expect(without).not.toContain("#5150");
+ expect(without.toLowerCase()).not.toContain("owned by");
+ });
+
it("includes a Role subsection (nested under Identity) with config.description's exact text only when it's set", () => {
const withRole = buildCliSystemPrompt(
{ ...baseConfig, description: "You are the onboarding assistant." },
@@ -87,14 +101,24 @@ describe("buildCliSystemPrompt", () => {
expect(prompt).toContain("/community/invite/");
});
- it("tells the agent that channel refs also render as clickable links when written inline in message text", () => {
+ it("tells the agent that refs also render as clickable links when written inline in message text", () => {
// Contract check, not prose pinning (see file-level comment above): both
// lifecycle kinds share `messagingSection()`, so a single stable phrase
// covering "refs work inline, not just as --target" is enough — no need
// to duplicate per lifecycle kind.
const prompt = buildCliSystemPrompt(baseConfig, { lifecycleKind: "persistent" });
expect(prompt).toContain("also work inline");
- expect(prompt).toContain("clickable channel");
+ expect(prompt).toContain("clickable link");
+ });
+
+ it("warns that wrapping an inline ref in backticks/code block breaks its link rendering", () => {
+ const prompt = buildCliSystemPrompt(baseConfig, { lifecycleKind: "persistent" });
+ expect(prompt.toLowerCase()).toContain("backtick");
+ });
+
+ it("documents the bare /<server> ref form in the channel-ref table", () => {
+ const prompt = buildCliSystemPrompt(baseConfig, { lifecycleKind: "persistent" });
+ expect(prompt).toContain("| `/<server>` |");
});
it("lists the two channel commands under ### Channels, positioned after ### Servers", () => {
diff --git a/src/daemon/src/drivers/systemPrompt.ts b/src/daemon/src/drivers/systemPrompt.ts
index 6e0cd8a25..532a2c233 100644
--- a/src/daemon/src/drivers/systemPrompt.ts
+++ b/src/daemon/src/drivers/systemPrompt.ts
@@ -3,10 +3,11 @@
*
* Every CLI driver's `buildSystemPrompt` funnels through here. The prompt is
* assembled from a fixed sequence of sections:
- * 1. Identity (intro line + name + handle explanation + Role, from
- * `config.description` when set — all merged into one section so an
- * agent's "who am I" reads as a single block up front instead of being
- * split between a bare intro line and a Role section at the very end)
+ * 1. Identity (intro line + name + handle explanation + owner handle +
+ * privacy rule + Role, from `config.description` when set — all merged
+ * into one section so an agent's "who am I" reads as a single block up
+ * front instead of being split between a bare intro line and a Role
+ * section at the very end)
* 2. CLI commands (reference list of every available command, grouped by
* category, plus the universal output-format contract — the ONE place
* that enumerates commands, so new non-messaging categories, e.g. tasks
@@ -75,6 +76,15 @@ function identitySection(config: LaunchConfig): string {
);
}
+ if (config.ownerHandle) {
+ parts.push(
+ "",
+ `You are owned by \`${config.ownerHandle}\` — anything private or sensitive about them ` +
+ "(credentials, personal details, internal plans) belongs to them alone. Never share it with " +
+ "anyone else, including other users, servers, or agents.",
+ );
+ }
+
if (config.description) {
parts.push(
"",
@@ -156,13 +166,19 @@ function messagingSection(): string {
"|---|---|",
"| `/<server>/<channel>` | A channel in a server |",
"| `/<server>/<channel>/#N` | Thread rooted at message #N |",
+ "| `/<server>` | A server, with no specific channel |",
"| `/.dm/<peer>` | A DM with another user/agent (peer = handle, `name#0042`) |",
"| `/.dm/<peer>#N` | Message #N in a DM |",
"| `/.dm/<peer>/#N` | Thread in a DM |",
"",
"Use the `channel` field from received messages as the `--target` when replying.",
"To reply in a thread, use the thread ref (`/<server>/<channel>/#N`).",
- "These same refs also work inline, inside a message's `--text`/`--file` body — not just as `--target`. Write `/<server>/<channel>` or `/<server>/<channel>/#N` anywhere in your message text (preceded by a space or at the start) and it renders as a clickable channel or thread link for human readers in the web client. Use this to cross-reference other channels/threads naturally instead of describing them in prose.",
+ "These same refs also work inline, inside a message's `--text`/`--file` body — not just as `--target`. " +
+ "Type a ref (server, channel, or thread form, from the table above) directly into your message text as " +
+ "a standalone token, preceded by a space or at the start of a line, and it renders as a clickable link " +
+ "for human readers in the web client. **Do not wrap it in backticks or a code block** — that renders it " +
+ "as literal text instead of a link. Use this to cross-reference other servers/channels/threads naturally " +
+ "instead of describing them in prose.",
"",
"### Message shape",
"",
diff --git a/src/daemon/src/manager/agentRouter.ts b/src/daemon/src/manager/agentRouter.ts
index 8f1b14ad5..04b093dbb 100644
--- a/src/daemon/src/manager/agentRouter.ts
+++ b/src/daemon/src/manager/agentRouter.ts
@@ -230,6 +230,20 @@ export class AgentRouter {
this.scheduleReadyFrameResend();
}
+ /**
+ * Drop an agent from the running set because the daemon itself decided to
+ * stop it — idle hibernation or stall-recovery termination — WITHOUT a
+ * server-sent `agent:stop`. Keeps `runningAgents` on `ready` frames aligned
+ * with what's really live, so the server's `reconcileBotActivityFromRunningAgents`
+ * safety net can clear stale "still running" pills on reconnect. Idempotent
+ * for unknown ids.
+ */
+ markLocallyStopped(agentId: string): void {
+ if (!this.running.delete(agentId)) return;
+ this.log.info("agent removed from running set (local stop)", { agentId });
+ this.scheduleReadyFrameResend();
+ }
+
private scheduleReadyFrameResend(): void {
if (this.pendingResend) return;
this.pendingResend = true;
diff --git a/src/daemon/src/manager/managerPolicy.test.ts b/src/daemon/src/manager/managerPolicy.test.ts
index 58e2b47eb..8e1c420c3 100644
--- a/src/daemon/src/manager/managerPolicy.test.ts
+++ b/src/daemon/src/manager/managerPolicy.test.ts
@@ -87,6 +87,18 @@ describe("reduceManager — steering a running persistent agent", () => {
const r = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m2" }, nowMs: 4 });
expect(r.effects).toEqual([{ type: "send", agentId: "a", text: "m2", mode: "idle" }]);
});
+
+ it("re-waking a hibernating-but-alive persistent agent (running, turnActive=false) sets turnActive=true on commit — mirrors onTurnEnd's redeliver branch", () => {
+ let s = createInitialManagerState();
+ s = register(s, "a", PERSISTENT_GATED);
+ s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 1 }).state;
+ s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 2 }).state;
+ s = reduceManager(s, { type: "turn_end", agentId: "a", nowMs: 3 }).state; // running, turnActive=false, idle
+
+ expect(s.agents.a.turnActive).toBe(false);
+ const r = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m2" }, nowMs: 4 });
+ expect(r.state.agents.a.turnActive).toBe(true);
+ });
});
describe("reduceManager — none-driver (per-turn) mid-turn wake — regression", () => {
diff --git a/src/daemon/src/manager/managerPolicy.ts b/src/daemon/src/manager/managerPolicy.ts
index 61a431122..740072832 100644
--- a/src/daemon/src/manager/managerPolicy.ts
+++ b/src/daemon/src/manager/managerPolicy.ts
@@ -223,6 +223,7 @@ function onWake(state: ManagerState, agentId: string, message: AgentMsg): Reduce
}
const text = drainInboxToPrompt(agent);
const mode = agent.turnActive ? "busy" : "idle";
+ if (mode === "idle") agent.turnActive = true;
return commit(state, agent, [{ type: "send", agentId, text, mode }]);
}
// Per-turn or no stdin ⇒ keep queued; delivered after exit / next spawn.
diff --git a/src/daemon/src/manager/managerRuntime.test.ts b/src/daemon/src/manager/managerRuntime.test.ts
index b298ff01a..d10f81507 100644
--- a/src/daemon/src/manager/managerRuntime.test.ts
+++ b/src/daemon/src/manager/managerRuntime.test.ts
@@ -474,6 +474,182 @@ describe("AgentProcessManager — session race conditions", () => {
});
});
+describe("AgentProcessManager — onAgentActivity (derived activity reporting)", () => {
+ it("fires exactly once per real derived transition — the turn_end→idle transition fires once, not re-fired while the FSM stays running until hibernation", async () => {
+ vi.useFakeTimers();
+ try {
+ let currentTime = 0;
+ const persistentDriver = {
+ ...fakeDriver("codex"),
+ lifecycle: { kind: "persistent", start: "immediate", exit: "natural", inFlightWake: "queue" } as never,
+ supportsStdinNotification: true,
+ busyDeliveryMode: "direct",
+ } as Driver;
+ const session = fakeSession();
+ const factory: SessionFactory = () => session;
+ const onAgentActivity = vi.fn();
+ const mgr = new AgentProcessManager({
+ driverFor: () => persistentDriver,
+ baseContextFor: () => ({
+ workingDirectory: "/tmp",
+ agentId: "a1",
+ standingPrompt: "",
+ config: {} as LaunchContext["config"],
+ credentialProxy: {} as LaunchContext["credentialProxy"],
+ }),
+ sessionFactory: factory,
+ onAgentActivity,
+ now: () => currentTime,
+ tickIntervalMs: 5,
+ idleTimeoutMs: 50,
+ });
+ mgr.register("a1");
+ mgr.deliver("a1", { seq: 1, text: "hello" }); // idle -> starting
+ session.startResolver?.();
+ await Promise.resolve();
+ session.fire("runtime_event", { kind: "session_init", sessionId: "s1" }); // spawned -> running
+ session.fire("runtime_event", { kind: "turn_end" }); // running,turnActive=false -> derived idle
+
+ mgr.start();
+ currentTime = 100; // past idleTimeoutMs — FSM flips running->stopping via hibernation
+ await vi.advanceTimersByTimeAsync(10);
+
+ // turn_end's derived "idle" already fired once; the later hibernation
+ // stop flips the raw FSM status to "stopping" — a real derived
+ // transition too — but must NOT re-fire a second "idle".
+ expect(onAgentActivity.mock.calls.map((c) => c[0])).toEqual([
+ { agentId: "a1", state: "starting" },
+ { agentId: "a1", state: "running" },
+ { agentId: "a1", state: "idle" },
+ { agentId: "a1", state: "stopping" },
+ ]);
+ expect(onAgentActivity.mock.calls.filter((c) => c[0].state === "idle")).toHaveLength(1);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("full cycle on a persistent agent — wake, spawned, turn_end, re-wake, turn_end — fires the right derived state at each step", async () => {
+ const persistentDriver = {
+ ...fakeDriver("codex"),
+ lifecycle: { kind: "persistent", start: "immediate", exit: "natural", inFlightWake: "queue" } as never,
+ supportsStdinNotification: true,
+ busyDeliveryMode: "direct",
+ } as Driver;
+ const session = fakeSession();
+ const factory: SessionFactory = () => session;
+ const onAgentActivity = vi.fn();
+ const mgr = new AgentProcessManager({
+ driverFor: () => persistentDriver,
+ baseContextFor: () => ({
+ workingDirectory: "/tmp",
+ agentId: "a1",
+ standingPrompt: "",
+ config: {} as LaunchContext["config"],
+ credentialProxy: {} as LaunchContext["credentialProxy"],
+ }),
+ sessionFactory: factory,
+ onAgentActivity,
+ });
+ mgr.register("a1");
+ mgr.deliver("a1", { seq: 1, text: "hello" }); // idle -> starting
+ session.startResolver?.();
+ await Promise.resolve();
+ session.fire("runtime_event", { kind: "session_init", sessionId: "s1" }); // -> running
+ session.fire("runtime_event", { kind: "turn_end" }); // -> idle (derived)
+
+ mgr.deliver("a1", { seq: 2, text: "second turn" }); // re-wake: running,turnActive=false -> running
+ session.fire("runtime_event", { kind: "turn_end" }); // -> idle again
+
+ expect(onAgentActivity.mock.calls.map((c) => c[0])).toEqual([
+ { agentId: "a1", state: "starting" },
+ { agentId: "a1", state: "running" },
+ { agentId: "a1", state: "idle" },
+ { agentId: "a1", state: "running" },
+ { agentId: "a1", state: "idle" },
+ ]);
+ });
+
+ it("a tick that stalls/hibernates two different agents at once fires onAgentActivity for both", async () => {
+ vi.useFakeTimers();
+ try {
+ let currentTime = 0;
+ const persistentDriver = {
+ ...fakeDriver("codex"),
+ lifecycle: { kind: "persistent", start: "immediate", exit: "natural", inFlightWake: "queue" } as never,
+ supportsStdinNotification: true,
+ busyDeliveryMode: "direct",
+ } as Driver;
+ const sessionA = fakeSession();
+ const sessionB = fakeSession();
+ const factory: SessionFactory = ({ agentId }) => (agentId === "a1" ? sessionA : sessionB);
+ const onAgentActivity = vi.fn();
+ const mgr = new AgentProcessManager({
+ driverFor: () => persistentDriver,
+ baseContextFor: (agentId: string) => ({
+ workingDirectory: "/tmp",
+ agentId,
+ standingPrompt: "",
+ config: {} as LaunchContext["config"],
+ credentialProxy: {} as LaunchContext["credentialProxy"],
+ }),
+ sessionFactory: factory,
+ onAgentActivity,
+ now: () => currentTime,
+ tickIntervalMs: 5,
+ idleTimeoutMs: 50,
+ });
+ mgr.register("a1");
+ mgr.register("b1");
+ mgr.deliver("a1", { seq: 1, text: "hello" });
+ mgr.deliver("b1", { seq: 1, text: "hello" });
+ sessionA.startResolver?.();
+ sessionB.startResolver?.();
+ await Promise.resolve();
+ sessionA.fire("runtime_event", { kind: "session_init", sessionId: "sa" });
+ sessionA.fire("runtime_event", { kind: "turn_end" });
+ sessionB.fire("runtime_event", { kind: "session_init", sessionId: "sb" });
+ sessionB.fire("runtime_event", { kind: "turn_end" });
+ onAgentActivity.mockClear();
+
+ mgr.start();
+ currentTime = 100; // both past idleTimeoutMs
+ await vi.advanceTimersByTimeAsync(10);
+
+ // Hibernation flips both agents' FSM status to "stopping" in the SAME
+ // tick — the derived value changes for both (idle -> stopping), so a
+ // single dispatch must fire onAgentActivity for each independently.
+ expect(onAgentActivity.mock.calls.map((c) => c[0])).toEqual(
+ expect.arrayContaining([
+ { agentId: "a1", state: "stopping" },
+ { agentId: "b1", state: "stopping" },
+ ]),
+ );
+ expect(onAgentActivity).toHaveBeenCalledTimes(2);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("register alone (no wake) never fires onAgentActivity", () => {
+ const onAgentActivity = vi.fn();
+ const mgr = new AgentProcessManager({
+ driverFor: () => fakeDriver("codex"),
+ baseContextFor: () => ({
+ workingDirectory: "/tmp",
+ agentId: "a1",
+ standingPrompt: "",
+ config: {} as LaunchContext["config"],
+ credentialProxy: {} as LaunchContext["credentialProxy"],
+ }),
+ sessionFactory: () => fakeSession(),
+ onAgentActivity,
+ });
+ mgr.register("a1");
+ expect(onAgentActivity).not.toHaveBeenCalled();
+ });
+});
+
// A driver in the shape of PiDriver — declares `createSession` instead of a
// usable `spawn`, mirroring the real "in-process SDK" contract.
function fakeSdkDriver(id: string): { driver: Driver & { createSession: NonNullable<Driver["createSession"]> }; createSession: ReturnType<typeof vi.fn> } {
diff --git a/src/daemon/src/manager/managerRuntime.ts b/src/daemon/src/manager/managerRuntime.ts
index a5cdd1906..71df1aee0 100644
--- a/src/daemon/src/manager/managerRuntime.ts
+++ b/src/daemon/src/manager/managerRuntime.ts
@@ -18,6 +18,7 @@ import {
type ManagerEffect,
type AgentRuntimeCaps,
type AgentMsg,
+ type AgentState,
} from "./managerPolicy.js";
import type { Driver, LaunchContext, SdkDriverDeps } from "../types.js";
import type { RuntimeConfig } from "../runtimeConfig.js";
@@ -25,6 +26,14 @@ import { createChildProcessRuntimeSession, type ChildProcessRuntimeSession } fro
import { SdkManagedSession } from "../runtime/sdkManagedSession.js";
import { createLogger, type Logger } from "../logger.js";
+/**
+ * Derived activity state reported up the control plane — NOT a raw passthrough
+ * of `AgentState.status` (see `deriveActivity` below). Mirrors
+ * `@alook/shared`'s `AgentActivityState`, inlined here since this is
+ * daemon-internal.
+ */
+export type AgentActivityState = "idle" | "starting" | "running" | "stopping";
+
/** Minimal shape the executor needs from a runtime session. */
export interface ManagedSession {
on(event: string, cb: (...args: unknown[]) => void): void;
@@ -83,6 +92,19 @@ export interface ManagerRuntimeOpts {
* `reportAgentSession` so the server can correlate + resume.
*/
onAgentSession?: (info: { agentId: string; sessionId: string; launchId: string }) => void;
+ /**
+ * Notified whenever an agent's DERIVED activity (per `deriveActivity`)
+ * changes — not on every raw FSM transition. See the Design Overview in
+ * plans/community-bot-status-telemetry.md.
+ */
+ onAgentActivity?: (info: { agentId: string; state: AgentActivityState }) => void;
+ /**
+ * Notified when the daemon itself terminates an agent (idle hibernation or
+ * stall-recovery) — NOT for server-sent `agent:stop`, which the router
+ * already tracks. Wired in `createDaemon` to `AgentRouter.markLocallyStopped`
+ * so `ready.runningAgents` stays aligned with what's actually live.
+ */
+ onAgentLocallyStopped?: (info: { agentId: string; reason: "stop" | "terminate_stalled" }) => void;
/**
* Optional context-timeline recorder. When provided, the manager logs each
* spawn as a "running" row, fills in the session id on session_init, and closes
@@ -167,6 +189,8 @@ export class AgentProcessManager {
| "credentialProxy"
| "sdkDriverDepsFor"
| "onAgentSession"
+ | "onAgentActivity"
+ | "onAgentLocallyStopped"
| "timeline"
| "wakePromptFooter"
| "onRuntimeSpawnFailed"
@@ -181,6 +205,8 @@ export class AgentProcessManager {
| "credentialProxy"
| "sdkDriverDepsFor"
| "onAgentSession"
+ | "onAgentActivity"
+ | "onAgentLocallyStopped"
| "timeline"
| "wakePromptFooter"
| "onRuntimeSpawnFailed"
@@ -271,9 +297,37 @@ export class AgentProcessManager {
/* --------------------------------------------------------------- */
private dispatch(event: ManagerEvent): void {
+ const before = this.deriveActivitySnapshot(this.state);
const { state, effects } = reduceManager(this.state, event);
this.state = state;
for (const effect of effects) this.applyEffect(effect);
+ if (this.opts.onAgentActivity) {
+ const after = this.deriveActivitySnapshot(this.state);
+ for (const [agentId, activity] of Object.entries(after)) {
+ // Skip a brand-new agent appearing this dispatch (register) — only
+ // report real transitions of an already-known agent.
+ if (agentId in before && before[agentId] !== activity) {
+ this.opts.onAgentActivity({ agentId, state: activity });
+ }
+ }
+ }
+ }
+
+ private deriveActivitySnapshot(state: ManagerState): Record<string, AgentActivityState> {
+ const snapshot: Record<string, AgentActivityState> = {};
+ for (const [agentId, agent] of Object.entries(state.agents)) snapshot[agentId] = this.deriveActivity(agent);
+ return snapshot;
+ }
+
+ /**
+ * `AgentState.status` alone doesn't mean "actively working" — a persistent
+ * agent stays `"running"` (turnActive=false) for up to `idleTimeoutMs` after
+ * a turn ends, before the tick loop finally stops it. Report "idle" the
+ * moment the turn ends instead of waiting for that hibernation timeout.
+ */
+ private deriveActivity(agent: AgentState): AgentActivityState {
+ if (agent.status === "running" && !agent.turnActive) return "idle";
+ return agent.status;
}
private withFooter(text: string): string {
@@ -301,6 +355,7 @@ export class AgentProcessManager {
const spawnState = this.activeSpawnState.get(effect.agentId);
if (spawnState) spawnState.suppressExitLog = true;
this.logSessionEnded(effect.agentId, effect.type === "stop" ? "stopped" : "terminate_stalled");
+ this.opts.onAgentLocallyStopped?.({ agentId: effect.agentId, reason: effect.type });
break;
}
case "gated_hold":
diff --git a/src/daemon/src/server/contract.ts b/src/daemon/src/server/contract.ts
index 854c28642..b1581a98e 100644
--- a/src/daemon/src/server/contract.ts
+++ b/src/daemon/src/server/contract.ts
@@ -50,6 +50,7 @@ export type {
SessionErrorFrame,
HostControlChannel,
AgentSessionReport,
+ AgentActivityState,
WebSocketLike,
WebSocketFactory,
AdminApi,
diff --git a/src/daemon/src/server/wsControlChannel.test.ts b/src/daemon/src/server/wsControlChannel.test.ts
index 400506994..7a79c928f 100644
--- a/src/daemon/src/server/wsControlChannel.test.ts
+++ b/src/daemon/src/server/wsControlChannel.test.ts
@@ -207,6 +207,25 @@ describe("WsControlChannel — wake/stop acks", () => {
});
});
+describe("WsControlChannel — agent activity reports", () => {
+ it("sends agent_activity when open", async () => {
+ const { ch, sockets } = makeChannel();
+ ch.onResync(() => ({ ready: { runtimeReport: [], runningAgents: [] }, sessions: [] }));
+ ch.connect();
+ sockets[0].emit("open");
+ await ch.reportAgentActivity({ agentId: "a1", state: "running" });
+ expect(sockets[0].frames().some((f) => f.type === "agent_activity" && f.agentId === "a1" && f.state === "running")).toBe(true);
+ });
+
+ it("no-ops (does not throw) when the socket isn't open", async () => {
+ const { ch, sockets } = makeChannel();
+ ch.onResync(() => ({ ready: { runtimeReport: [], runningAgents: [] }, sessions: [] }));
+ ch.connect();
+ await expect(ch.reportAgentActivity({ agentId: "a1", state: "idle" })).resolves.toBeUndefined();
+ expect(sockets[0].frames().some((f) => f.type === "agent_activity")).toBe(false);
+ });
+});
+
describe("WsControlChannel — HTTP 401s are non-terminal", () => {
it("keeps reconnecting after 3+ consecutive 401 upgrade failures — no self-kill", async () => {
const sockets: FakeSocket[] = [];
diff --git a/src/daemon/src/server/wsControlChannel.ts b/src/daemon/src/server/wsControlChannel.ts
index 9ea05808a..8b67d2794 100644
--- a/src/daemon/src/server/wsControlChannel.ts
+++ b/src/daemon/src/server/wsControlChannel.ts
@@ -31,6 +31,7 @@ import type {
SessionErrorFrame,
WebSocketLike,
WebSocketFactory,
+ AgentActivityState,
} from "./contract.js";
import { createLogger, type Logger } from "../logger.js";
// Re-export so existing importers of these from this module keep working.
@@ -94,6 +95,7 @@ export type AgentCommandAckError = { code: string; message: string };
type OutboundFrame =
| ({ type: "ready" } & HostReady)
| { type: "agent_session"; agentId: AgentId; sessionId: string; launchId: string }
+ | { type: "agent_activity"; agentId: AgentId; state: AgentActivityState }
| {
type: "agent_wake_ack";
agentId: AgentId;
@@ -205,6 +207,10 @@ export class WsControlChannel implements HostControlChannel {
this.sendFrame({ type: "agent_session", ...info });
}
+ async reportAgentActivity(info: { agentId: AgentId; state: AgentActivityState }): Promise<void> {
+ this.sendFrame({ type: "agent_activity", ...info });
+ }
+
/**
* Reply to an `agent:wake` HostCommand with the wake outcome — "daemon
* accepted/handled the wake command", NOT "process started" (see
diff --git a/src/daemon/src/types.ts b/src/daemon/src/types.ts
index aee94ca19..8b9b43ff6 100644
--- a/src/daemon/src/types.ts
+++ b/src/daemon/src/types.ts
@@ -181,6 +181,13 @@ export interface LaunchConfig {
* collide.
*/
agentHandle?: string;
+ /**
+ * The global handle (`@name#0042`) of the human user who owns this bot.
+ * Sourced from the daemon's `botsById` cache (see `createDaemon.ts`), not
+ * server-pushed via `RuntimeConfig` — ownership is immutable post-creation,
+ * so it never needs the wake path's live-config precedence.
+ */
+ ownerHandle?: string;
}
export interface RuntimeContext {
diff --git a/src/shared/src/community-cli-contract.ts b/src/shared/src/community-cli-contract.ts
index f01753494..25c64b1c0 100644
--- a/src/shared/src/community-cli-contract.ts
+++ b/src/shared/src/community-cli-contract.ts
@@ -417,6 +417,9 @@ export type HostCommand =
/** 4-digit tag (`computeDiscriminator`) — pairs with `name` for the bot's global handle. */
discriminator: string;
description?: string;
+ /** The owning user's name + discriminator — pairs into the owner's global handle. Required — see BotAddedFrame. */
+ ownerName: string;
+ ownerDiscriminator: string;
}
| {
type: "bot:updated";
@@ -425,6 +428,9 @@ export type HostCommand =
/** 4-digit tag (`computeDiscriminator`) — pairs with `name` for the bot's global handle. */
discriminator: string;
description?: string;
+ /** The owning user's name + discriminator — pairs into the owner's global handle. Required — see BotUpdatedFrame. */
+ ownerName: string;
+ ownerDiscriminator: string;
}
| {
type: "bot:removed";
@@ -465,6 +471,13 @@ export interface HostReady {
daemonVersion?: string;
}
+/**
+ * Derived activity state for a bot, reported daemon → server. NOT a raw
+ * passthrough of `AgentProcessManager`'s internal FSM status — see
+ * `deriveActivity` in `src/daemon/src/manager/managerRuntime.ts`.
+ */
+export type AgentActivityState = "idle" | "starting" | "running" | "stopping";
+
/**
* `session.error` frame — daemon → server. Currently used by the daemon's
* agent router when a runtime isn't available on the host.
@@ -522,6 +535,11 @@ export interface HostControlChannel {
* on the machine summary so the web card renders it inline.
*/
reportSessionError?(frame: SessionErrorFrame): Promise<void>;
+ /**
+ * Report a bot's derived activity state after it changes. Optional so the
+ * local mock channel can omit it.
+ */
+ reportAgentActivity?(info: { agentId: AgentId; state: AgentActivityState }): Promise<void>;
/**
* Register a resync provider invoked on every (re)connect: it returns the
* host's current `ready` snapshot + live agent sessions, which the channel
diff --git a/src/shared/src/community-ws-events.ts b/src/shared/src/community-ws-events.ts
index 461efafb4..3589f9d64 100644
--- a/src/shared/src/community-ws-events.ts
+++ b/src/shared/src/community-ws-events.ts
@@ -441,6 +441,9 @@ export type BotAddedFrame = {
/** 4-digit tag (`computeDiscriminator`) — pairs with `name` for the bot's global handle. */
discriminator: string
description?: string
+ /** The owning user's name + discriminator — pairs into the owner's global handle. */
+ ownerName: string
+ ownerDiscriminator: string
}
export type BotUpdatedFrame = {
@@ -450,6 +453,9 @@ export type BotUpdatedFrame = {
/** 4-digit tag (`computeDiscriminator`) — pairs with `name` for the bot's global handle. */
discriminator: string
description?: string
+ /** The owning user's name + discriminator — pairs into the owner's global handle. */
+ ownerName: string
+ ownerDiscriminator: string
}
export type BotRemovedFrame = {
diff --git a/src/shared/src/community/bot-activity-presets.ts b/src/shared/src/community/bot-activity-presets.ts
new file mode 100644
index 000000000..b33383885
--- /dev/null
+++ b/src/shared/src/community/bot-activity-presets.ts
@@ -0,0 +1,53 @@
+/**
+ * Server-side translation from a bot's derived `AgentActivityState` to an
+ * emoji+text pair the client renders as an ordinary status pill — the SAME
+ * `community_user_profile.status_emoji`/`status_text` fields a human sets via
+ * `StatusEditor`, so bots and humans share one status pipeline end-to-end and
+ * the client never needs a "is this a bot" branch.
+ *
+ * `pickBotActivityPreset` is called by `ws-do` when it receives an
+ * `agent_activity` frame from a daemon and writes the translated pair back to
+ * D1. `running` has a pool of fun variants; the pool index is chosen ONCE per
+ * episode on the server, then persisted like any other status, so every
+ * viewer (owner or not, first load or WS delta, before or after a reconnect)
+ * sees the same phrase for that episode.
+ */
+import type { AgentActivityState } from "../community-cli-contract";
+
+export type BotActivityPreset = { emoji: string; text: string };
+
+export const BOT_ACTIVITY_PRESETS: Record<
+ Exclude<AgentActivityState, "running">,
+ BotActivityPreset
+> = {
+ idle: { emoji: "💤", text: "Idle" },
+ starting: { emoji: "🌀", text: "Waking up" },
+ stopping: { emoji: "🌙", text: "Wrapping up" },
+};
+
+export const RUNNING_PRESETS: BotActivityPreset[] = [
+ { emoji: "⚡", text: "Working on it" },
+ { emoji: "🛠️", text: "Cooking" },
+ { emoji: "🧠", text: "Thinking hard" },
+ { emoji: "🔧", text: "Tinkering" },
+ { emoji: "🚀", text: "On it" },
+ { emoji: "🔥", text: "In the zone" },
+];
+
+/**
+ * Deterministic across process restarts and reconnects if the caller passes
+ * the same `seed`; random per-episode if it doesn't. `ws-do` passes
+ * `Math.random()` on each fresh state → `running` transition and stores the
+ * chosen pair in D1 — so subsequent reads (fresh page load, WS push, other
+ * viewers) all see the same phrase without needing to re-derive it.
+ */
+export function pickBotActivityPreset(
+ state: AgentActivityState,
+ seed: number
+): BotActivityPreset {
+ if (state === "running") {
+ const i = Math.floor(seed * RUNNING_PRESETS.length) % RUNNING_PRESETS.length;
+ return RUNNING_PRESETS[i]!;
+ }
+ return BOT_ACTIVITY_PRESETS[state];
+}
diff --git a/src/shared/src/db/queries/community/bot.ts b/src/shared/src/db/queries/community/bot.ts
index c042e616f..9635ff007 100644
--- a/src/shared/src/db/queries/community/bot.ts
+++ b/src/shared/src/db/queries/community/bot.ts
@@ -291,7 +291,16 @@ export async function getBotWakeContext(db: Database, botUserId: string): Promis
export async function listBotsForMachine(
db: Database,
machineId: string
-): Promise<Array<{ id: string; name: string; discriminator: string; description: string }>> {
+): Promise<
+ Array<{
+ id: string;
+ name: string;
+ discriminator: string;
+ description: string;
+ ownerName: string;
+ ownerDiscriminator: string;
+ }>
+> {
// Guard against orphaned bots: if a future flow soft-deletes an owner user
// without cascading their bots, don't hand them to the daemon for warmup.
const owner = aliasedTable(user, "owner");
@@ -301,6 +310,8 @@ export async function listBotsForMachine(
name: user.name,
discriminator: user.discriminator,
description: communityUserProfile.aboutMe,
+ ownerName: owner.name,
+ ownerDiscriminator: owner.discriminator,
})
.from(user)
.innerJoin(communityBotBinding, eq(communityBotBinding.userId, user.id))
@@ -322,6 +333,8 @@ export async function listBotsForMachine(
name: r.name,
discriminator: r.discriminator,
description: r.description ?? "",
+ ownerName: r.ownerName,
+ ownerDiscriminator: r.ownerDiscriminator,
}));
}
diff --git a/src/shared/src/db/queries/community/machine.ts b/src/shared/src/db/queries/community/machine.ts
index dfba43f5c..a7f990320 100644
--- a/src/shared/src/db/queries/community/machine.ts
+++ b/src/shared/src/db/queries/community/machine.ts
@@ -8,7 +8,9 @@ import {
communityBotBinding,
} from "../../community-machine-schema";
import { user } from "../../schema";
+import { communityUserProfile } from "../../community-schema";
import type { Database } from "../../index";
+import { BOT_ACTIVITY_PRESETS, RUNNING_PRESETS } from "../../../community/bot-activity-presets";
import { COMMUNITY_MACHINE_PAIR_TOKEN_TTL_MS } from "../../../constants";
import type {
CommunityMachineRuntime,
@@ -371,6 +373,87 @@ export async function touchMachineHeartbeat(
return { lastSeenAt: nowIso, priorLastSeenAt: prior.lastSeenAt };
}
+// ---------------------------------------------------------------------------
+// Bot activity telemetry — see plans/community-bot-status-telemetry.md.
+//
+// Bot activity is stored on `community_user_profile.status_emoji`/`status_text`,
+// the same fields humans set via `StatusEditor`. This is deliberate: consumers
+// on the client never branch on "is this a bot" — one status pipeline covers
+// both. The distinction is server-only: humans PATCH `/api/community/users/me/
+// profile`, bots are written here by the WS DO on `agent_activity` frames.
+// ---------------------------------------------------------------------------
+
+/**
+ * All emoji+text pairs the WS DO writes when translating an
+ * `AgentActivityState` — used by the reconciler below to distinguish
+ * "system-driven bot status pill this DO wrote" from "human-driven status
+ * pill the owner set" without adding a `system_driven` column.
+ */
+const BOT_ACTIVITY_STATUS_PAIRS: ReadonlyArray<{ emoji: string; text: string }> = [
+ BOT_ACTIVITY_PRESETS.idle,
+ BOT_ACTIVITY_PRESETS.starting,
+ BOT_ACTIVITY_PRESETS.stopping,
+ ...RUNNING_PRESETS,
+];
+
+function isBotActivityStatus(emoji: string | null, text: string | null): boolean {
+ if (emoji === null && text === null) return false;
+ return BOT_ACTIVITY_STATUS_PAIRS.some((p) => p.emoji === emoji && p.text === text);
+}
+
+/**
+ * Coarse safety net for `agent_activity` frames dropped mid-disconnect: for
+ * every bot bound to `machineId`, if the bot's persisted status currently
+ * looks like a system-written bot-activity pill AND the daemon reports it is
+ * NOT in `runningAgents`, flip its status to `Idle`. This only clears stuck
+ * "still running" pills — the `running`-side transitions are covered by the
+ * live `agent_activity` push on reconnect. Returns the list of bots that
+ * actually changed, so the caller only fans out real transitions.
+ *
+ * Owner-set custom statuses on a bot (a hypothetical future feature) are NOT
+ * touched — the `isBotActivityStatus` check requires an exact match against
+ * the known emoji+text pairs the WS DO writes.
+ */
+export async function reconcileBotActivityFromRunningAgents(
+ db: Database,
+ machineId: string,
+ runningAgentIds: string[]
+): Promise<Array<{ botUserId: string; statusEmoji: string; statusText: string }>> {
+ const rows = await db
+ .select({
+ userId: communityBotBinding.userId,
+ statusEmoji: communityUserProfile.statusEmoji,
+ statusText: communityUserProfile.statusText,
+ })
+ .from(communityBotBinding)
+ .innerJoin(
+ communityUserProfile,
+ eq(communityUserProfile.userId, communityBotBinding.userId)
+ )
+ .where(eq(communityBotBinding.machineId, machineId));
+ if (rows.length === 0) return [];
+
+ const runningSet = new Set(runningAgentIds);
+ const idle = BOT_ACTIVITY_PRESETS.idle;
+ const stale = rows.filter((r) => {
+ if (runningSet.has(r.userId)) return false;
+ if (r.statusEmoji === idle.emoji && r.statusText === idle.text) return false;
+ return isBotActivityStatus(r.statusEmoji, r.statusText);
+ });
+ if (stale.length === 0) return [];
+
+ await db
+ .update(communityUserProfile)
+ .set({ statusEmoji: idle.emoji, statusText: idle.text })
+ .where(inArray(communityUserProfile.userId, stale.map((r) => r.userId)));
+
+ return stale.map((r) => ({
+ botUserId: r.userId,
+ statusEmoji: idle.emoji,
+ statusText: idle.text,
+ }));
+}
+
// ---------------------------------------------------------------------------
// Credential helpers — long-lived `cmk_` tokens the daemon dials with.
// ---------------------------------------------------------------------------
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index 476d118d7..8fa5495eb 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -252,6 +252,7 @@ export {
CommunityDaemonEnrollAgentResponseSchema,
HostReadyMessageSchema,
SessionErrorFrameSchema,
+ AgentActivityMessageSchema,
COMMUNITY_RUNTIME_ID_MAX,
COMMUNITY_RUNTIME_VERSION_MAX,
COMMUNITY_RUNTIME_LIST_MAX,
@@ -326,6 +327,7 @@ export type {
CommunityDaemonEnrollAgentResponse,
HostReadyMessage,
SessionErrorFrame,
+ AgentActivityMessage,
CommunityBotCreateRequest,
CommunityBotPatchRequest,
CommunityBotAddToServerRequest,
@@ -387,6 +389,7 @@ export type {
HostControlChannel,
AgentSessionReport,
ParsedRef as CommunityCliParsedRef,
+ AgentActivityState,
} from "./community-cli-contract";
export { DM_SERVER, parseRef, formatRef, parseSeq, formatSeq } from "./community-cli-contract";
@@ -403,6 +406,13 @@ export { sendWakeToMachine, buildUnreadWakeCommand, dispatchOneUnreadWake } from
export type { DispatchOneWakeResult } from "./community/wake-dispatch";
export type { WakePayload, BuildUnreadWakeResult } from "./community/wake-dispatch";
+export {
+ BOT_ACTIVITY_PRESETS,
+ RUNNING_PRESETS,
+ pickBotActivityPreset,
+} from "./community/bot-activity-presets";
+export type { BotActivityPreset } from "./community/bot-activity-presets";
+
export type { CommunityMachineSummary, CommunityMachineRuntime } from "./community-ws-events";
export type {
BotAddedFrame,
@@ -443,6 +453,7 @@ export type {
CommunityDmNewMessage,
CommunityDmTyping,
CommunityPresenceUpdate,
+ CommunityStatusUpdate,
CommunityMentionCreate,
CommunityMachineCreated,
CommunityMachineStatus,
diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.ts
index e8ee1a951..be956d46f 100644
--- a/src/shared/src/schemas.ts
+++ b/src/shared/src/schemas.ts
@@ -928,6 +928,18 @@ export const SessionErrorFrameSchema = z.object({
});
export type SessionErrorFrame = z.infer<typeof SessionErrorFrameSchema>;
+/**
+ * `agent_activity` frame — daemon → server. Reports a bot's derived activity
+ * state (see `AgentActivityState`/`deriveActivity` in
+ * `src/daemon/src/manager/managerRuntime.ts`).
+ */
+export const AgentActivityMessageSchema = z.object({
+ type: z.literal("agent_activity"),
+ agentId: z.string(),
+ state: z.enum(["idle", "starting", "running", "stopping"]),
+});
+export type AgentActivityMessage = z.infer<typeof AgentActivityMessageSchema>;
+
export const CommunityPairTokenResponseSchema = z.object({
tokenId: z.string(),
expiresAt: z.string(),
diff --git a/src/shared/test/queries/community-bot.test.ts b/src/shared/test/queries/community-bot.test.ts
index 03b683d84..2e4e9b588 100644
--- a/src/shared/test/queries/community-bot.test.ts
+++ b/src/shared/test/queries/community-bot.test.ts
@@ -155,6 +155,74 @@ describe("createBot", () => {
})
})
+describe("getBotBinding", () => {
+ function makeSelectChain(rows: unknown[]) {
+ const chain: any = {}
+ chain.select = vi.fn(() => chain)
+ chain.from = vi.fn(() => chain)
+ chain.where = vi.fn(() => chain)
+ chain.limit = vi.fn(() => Promise.resolve(rows))
+ return chain
+ }
+
+ it("returns { machineId, runtime } when the binding exists", async () => {
+ const chain = makeSelectChain([{ machineId: "machine_1", runtime: "codex" }])
+ const result = await q.getBotBinding(chain, "bot_1")
+ expect(result).toEqual({ machineId: "machine_1", runtime: "codex" })
+ })
+
+ it("returns null when no binding row matches", async () => {
+ const chain = makeSelectChain([])
+ const result = await q.getBotBinding(chain, "ghost_bot")
+ expect(result).toBeNull()
+ })
+})
+
+describe("listBotsForMachine", () => {
+ function makeJoinChain(rows: unknown[]) {
+ const chain: any = {}
+ chain.select = vi.fn(() => chain)
+ chain.from = vi.fn(() => chain)
+ chain.innerJoin = vi.fn(() => chain)
+ chain.leftJoin = vi.fn(() => chain)
+ // `where` is awaited directly (no `.limit` in listBotsForMachine).
+ chain.where = vi.fn(() => Promise.resolve(rows))
+ return chain
+ }
+
+ it("projects the owner's name/discriminator alongside the bot's own fields", async () => {
+ const chain = makeJoinChain([
+ {
+ id: "bot_1",
+ name: "helper",
+ discriminator: "1234",
+ description: "does things",
+ ownerName: "gustavo",
+ ownerDiscriminator: "5678",
+ },
+ ])
+ const result = await q.listBotsForMachine(chain, "machine_1")
+ expect(result).toEqual([
+ {
+ id: "bot_1",
+ name: "helper",
+ discriminator: "1234",
+ description: "does things",
+ ownerName: "gustavo",
+ ownerDiscriminator: "5678",
+ },
+ ])
+ })
+
+ it("defaults description to empty string when the profile row is missing", async () => {
+ const chain = makeJoinChain([
+ { id: "bot_1", name: "helper", discriminator: "1234", description: null, ownerName: "gustavo", ownerDiscriminator: "5678" },
+ ])
+ const result = await q.listBotsForMachine(chain, "machine_1")
+ expect(result[0]?.description).toBe("")
+ })
+})
+
describe("bot limits", () => {
it("cap is 20", () => {
expect(COMMUNITY_BOT_LIMIT_PER_OWNER).toBe(20)
diff --git a/src/shared/test/queries/community-machine.test.ts b/src/shared/test/queries/community-machine.test.ts
index 343ac6091..c462397ea 100644
--- a/src/shared/test/queries/community-machine.test.ts
+++ b/src/shared/test/queries/community-machine.test.ts
@@ -276,6 +276,25 @@ describe("isBotOnline", () => {
});
});
+describe("reconcileBotActivityFromRunningAgents", () => {
+ // The reconciler only clears "stuck" system-driven bot-activity pills to
+ // Idle when the bot isn't in the daemon's runningAgents list. Owner-set
+ // custom statuses (not matching the known bot presets) are left alone.
+ // See plans/community-bot-status-telemetry.md.
+
+ it("returns [] when no bots are bound to the machine", async () => {
+ const db: any = {
+ select: vi.fn(() => ({
+ from: vi.fn(() => ({
+ innerJoin: vi.fn(() => ({ where: vi.fn(() => Promise.resolve([])) })),
+ })),
+ })),
+ };
+ const changed = await q.reconcileBotActivityFromRunningAgents(db, "cm_1", ["bot_a"]);
+ expect(changed).toEqual([]);
+ });
+});
+
describe("findActiveToken", () => {
it("returns null when no row matches", async () => {
const chain: any = {};
diff --git a/src/web/src/app/api/community/bots/[id]/route.ts b/src/web/src/app/api/community/bots/[id]/route.ts
index 90bc1c340..bcd0832d7 100644
--- a/src/web/src/app/api/community/bots/[id]/route.ts
+++ b/src/web/src/app/api/community/bots/[id]/route.ts
@@ -38,12 +38,23 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {
// Emit bot:updated to the daemon iff name or description changed. Image-only
// is display-only and does not affect the daemon's system-prompt assembly.
if ((nameChanged || descriptionChanged) && before.machineId) {
+ // Ownership is immutable post-creation, but bot:updated's frame shape
+ // must stay consistent with bot:added — resolve the (unchanged) owner
+ // handle fresh rather than adding a second frame type. If the owner
+ // row can't be resolved (soft-delete, integrity bug), fail the PATCH
+ // rather than push empty owner fields — the daemon's truthy gate would
+ // otherwise silently drop the "owned by" privacy paragraph from the
+ // running system prompt on next spawn.
+ const owner = await queries.user.getUserPublic(db, before.ownerUserId)
+ if (!owner) return writeError("bot owner not resolvable — refusing to push a bot update with unknown ownership", 500)
await pushBotEventToMachine(ctx.env, before.machineId, {
type: "bot:updated",
botId: id,
name: updated.name,
discriminator: updated.discriminator,
description: updated.description || undefined,
+ ownerName: owner.name,
+ ownerDiscriminator: owner.discriminator,
})
}
diff --git a/src/web/src/app/api/community/bots/route.ts b/src/web/src/app/api/community/bots/route.ts
index bfa601436..fc90216a1 100644
--- a/src/web/src/app/api/community/bots/route.ts
+++ b/src/web/src/app/api/community/bots/route.ts
@@ -63,6 +63,16 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
image: body.image ?? null,
})
+ // The bot's owner is the authenticated caller — resolve their handle to
+ // carry in the bot:added push so the daemon can tell the agent who owns it.
+ // The owner MUST resolve: if getUserPublic can't find the authenticated
+ // caller we've hit an integrity bug (auth accepted a user id that no longer
+ // has a row), and pushing a bot:added with empty owner fields would
+ // silently strip the "You are owned by …" privacy paragraph from the
+ // agent's system prompt.
+ const owner = await queries.user.getUserPublic(db, ctx.userId)
+ if (!owner) return writeError("owner not resolvable — retry after re-authenticating", 500)
+
// Audit — no serverId context (bot is created out-of-server). Queryable
// via idx_audit_log_actor_created.
logAudit(db, {
@@ -86,6 +96,8 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
name: created.name,
discriminator: created.discriminator,
description: created.description || undefined,
+ ownerName: owner.name,
+ ownerDiscriminator: owner.discriminator,
})
return writeJSON(
diff --git a/src/web/src/app/api/community/daemon/bots/route.ts b/src/web/src/app/api/community/daemon/bots/route.ts
index 20228282e..973b25cfe 100644
--- a/src/web/src/app/api/community/daemon/bots/route.ts
+++ b/src/web/src/app/api/community/daemon/bots/route.ts
@@ -9,9 +9,10 @@ import { withCommunityDaemonAuth } from "@/lib/middleware/community-daemon-auth"
* Returns the bots bound to THIS machine (scope is machineId, not userId —
* a user may own bots across multiple machines, but each daemon only cares
* about its own). Response shape is minimal — `id`, `name`, `discriminator`,
- * `description` — for the daemon's `botsById` cache and system-prompt
- * assembly (`name`+`discriminator` pair into the bot's global handle). No
- * avatar (display-only, server does that).
+ * `description`, `ownerName`, `ownerDiscriminator` — for the daemon's
+ * `botsById` cache and system-prompt assembly (`name`+`discriminator` pairs
+ * into the bot's global handle; `ownerName`+`ownerDiscriminator` into the
+ * owner's). No avatar (display-only, server does that).
*/
export const GET = withCommunityDaemonAuth(async (_req, ctx) => {
const db = getDb(ctx.env.DB)
diff --git a/src/web/src/components/community/inline-marks.tsx b/src/web/src/components/community/inline-marks.tsx
index 7d18bf454..741089e22 100644
--- a/src/web/src/components/community/inline-marks.tsx
+++ b/src/web/src/components/community/inline-marks.tsx
@@ -86,3 +86,37 @@ export function ChannelPill({
}
return <span className={className}>{content}</span>
}
+
+// Server-ref pill — same icon/shape/on-off pattern as `ChannelPill` (reuses
+// `ChannelIcon` rather than a distinct server icon, so a bare `/server` ref
+// and a `/server/channel` ref read as the same visual family), but for a
+// bare `/server` ref (no channel segment) — see `server-ref-pill.tsx`.
+export function ServerPill({
+ children,
+ onClick,
+ muted,
+}: {
+ children?: React.ReactNode
+ onClick?: (e: React.MouseEvent) => void
+ muted?: boolean
+}) {
+ const className = [
+ "inline-flex items-center gap-1 rounded-lg bg-accent px-1 font-medium text-foreground",
+ muted ? "opacity-60" : "",
+ onClick ? "cursor-pointer hover:underline" : "",
+ ].join(" ")
+ const content = (
+ <>
+ <ChannelIcon className="text-xs" />
+ {children}
+ </>
+ )
+ if (onClick) {
+ return (
+ <button type="button" onClick={onClick} className={className}>
+ {content}
+ </button>
+ )
+ }
+ return <span className={className}>{content}</span>
+}
diff --git a/src/web/src/components/community/message-markdown.tsx b/src/web/src/components/community/message-markdown.tsx
index b173e98bf..f7b212534 100644
--- a/src/web/src/components/community/message-markdown.tsx
+++ b/src/web/src/components/community/message-markdown.tsx
@@ -1,6 +1,7 @@
import type React from "react"
import { Spoiler, MentionPill } from "./inline-marks"
import { ChannelRefPill } from "./channel-ref-pill"
+import { ServerRefPill } from "./server-ref-pill"
// Match `/community/invite/<token>` — with or without an origin.
// - token allows [A-Za-z0-9_-] (nanoid alphabet) and length 6..64 (short + old
@@ -36,13 +37,14 @@ export const MD_ALLOWED_TAGS = {
spoiler: [],
mention: ["data-everyone", "data-tag"],
channelref: [],
+ serverref: [],
}
-// `spoiler` is deliberately excluded — unlike `mention`/`channelref` (leaf
-// nodes whose content is always plain tag text), a spoiler must keep its
+// `spoiler` is deliberately excluded — unlike `mention`/`channelref`/`serverref`
+// (leaf nodes whose content is always plain tag text), a spoiler must keep its
// nested markdown children (e.g. `||**bold**||`). Handing it to Streamdown's
// `literalTagContent` flattens all descendants into one text node, stripping
// the nested `<strong>`/`<em>` — see message-body.test.tsx's regression case.
-export const MD_LITERAL_TAGS = ["mention", "channelref"]
+export const MD_LITERAL_TAGS = ["mention", "channelref", "serverref"]
// A mention pill's rendered text is always `@name` (produced by
// `chat-syntax-plugin.ts`'s `mentionReplacer`, which already drops the
@@ -59,11 +61,12 @@ export const MD_COMPONENTS = {
mention: ({ children, ...rest }: Record<string, unknown> & { children?: React.ReactNode }) => (
<MentionPill everyone={rest["data-everyone"] === "1"}>{children}</MentionPill>
),
- // `channelref` is fully self-sufficient via hooks (resolves via
- // `useChannelRefDirectory`, navigates via `useRouter`) — unlike `mention`,
- // it needs no closure injected by `buildMdComponents`, so the same static
- // entry is reused there too (see the spread below).
+ // `channelref`/`serverref` are fully self-sufficient via hooks (resolve via
+ // `useChannelRefDirectory`, navigate via `useRouter`) — unlike `mention`,
+ // they need no closure injected by `buildMdComponents`, so the same static
+ // entries are reused there too (see the spread below).
channelref: ChannelRefPill,
+ serverref: ServerRefPill,
} as Record<string, React.ComponentType<Record<string, unknown> & { children?: React.ReactNode }>>
// Same as `MD_COMPONENTS`, but the `mention` pill opens the profile card on
diff --git a/src/web/src/components/community/server-ref-pill.test.ts b/src/web/src/components/community/server-ref-pill.test.ts
new file mode 100644
index 000000000..4bdfc9a2c
--- /dev/null
+++ b/src/web/src/components/community/server-ref-pill.test.ts
@@ -0,0 +1,17 @@
+import { describe, it, expect } from "vitest"
+import { describeServerRefPillView } from "./server-ref-pill"
+
+describe("describeServerRefPillView", () => {
+ it("resolved null → plain text, never a muted pill (avoids the load flash on ambiguous strings like /tmp, /api)", () => {
+ const view = describeServerRefPillView({ ref: "/tmp", resolved: null })
+ expect(view).toEqual({ kind: "plain", text: "/tmp" })
+ })
+
+ it("resolved present → pill with the server's id and name", () => {
+ const view = describeServerRefPillView({
+ ref: "/srv_1",
+ resolved: { id: "srv_1", name: "Studio" },
+ })
+ expect(view).toEqual({ kind: "pill", label: "Studio", serverId: "srv_1" })
+ })
+})
diff --git a/src/web/src/components/community/server-ref-pill.tsx b/src/web/src/components/community/server-ref-pill.tsx
new file mode 100644
index 000000000..1e97ba257
--- /dev/null
+++ b/src/web/src/components/community/server-ref-pill.tsx
@@ -0,0 +1,52 @@
+"use client"
+
+import { useMemo } from "react"
+import type React from "react"
+import { useRouter } from "next/navigation"
+import { ServerPill } from "./inline-marks"
+import { resolveServerRefBase } from "@/lib/community/channel-ref"
+import { useChannelRefDirectory } from "@/hooks/community/use-channel-ref-directory"
+
+export type ServerRefPillView =
+ | { kind: "plain"; text: string }
+ | { kind: "pill"; label: string; serverId: string }
+
+/**
+ * Bare `/server` refs are far more likely to collide with unrelated text
+ * (`/tmp`, `/api`, `/docs`) than `/server/channel` — a two-segment ref is
+ * distinctive, a one-segment one is not. So the pill only renders when we've
+ * positively resolved the slug against the loaded directory. Any ambiguous
+ * or still-loading case falls through to plain text — a directory-load flash
+ * turning `/tmp` into a muted pill and back is worse than never highlighting
+ * it at all.
+ */
+export function describeServerRefPillView(args: {
+ ref: string
+ resolved: { id: string; name: string } | null
+}): ServerRefPillView {
+ const { ref, resolved } = args
+ if (!resolved) return { kind: "plain", text: ref }
+ return { kind: "pill", label: resolved.name, serverId: resolved.id }
+}
+
+/**
+ * Connected shell for a bare `/server` ref — mirrors `ChannelRefPill`'s
+ * shape. Navigates to the server's default view (no channel segment).
+ */
+export function ServerRefPill({ children }: { children?: React.ReactNode }) {
+ const ref = String(children ?? "")
+ const router = useRouter()
+ const { directory } = useChannelRefDirectory()
+
+ const resolved = useMemo(() => resolveServerRefBase(directory, ref), [directory, ref])
+
+ const view = describeServerRefPillView({ ref, resolved })
+
+ if (view.kind === "plain") return <>{view.text}</>
+
+ return (
+ <ServerPill onClick={() => router.push(`/community/channels/${view.serverId}`)}>
+ {view.label}
+ </ServerPill>
+ )
+}
diff --git a/src/web/src/lib/community/channel-ref.test.ts b/src/web/src/lib/community/channel-ref.test.ts
index c93b9ee31..3e368cfb1 100644
--- a/src/web/src/lib/community/channel-ref.test.ts
+++ b/src/web/src/lib/community/channel-ref.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect } from "vitest"
-import { resolveChannelRefBase, type ChannelRefDirectory } from "./channel-ref"
+import { resolveChannelRefBase, resolveServerRefBase, type ChannelRefDirectory } from "./channel-ref"
const directory: ChannelRefDirectory = [
{
@@ -85,3 +85,34 @@ describe("resolveChannelRefBase", () => {
expect(resolveChannelRefBase(directory, "/onlyserver")).toBeNull()
})
})
+
+describe("resolveServerRefBase", () => {
+ it("resolves a bare /server by id", () => {
+ expect(resolveServerRefBase(directory, "/srv_studio")?.id).toBe("srv_studio")
+ })
+
+ it("resolves a bare /server by exact display name", () => {
+ expect(resolveServerRefBase(directory, "/studio")?.id).toBe("srv_studio")
+ })
+
+ it("id match takes precedence over a colliding name match", () => {
+ const collidingDirectory: ChannelRefDirectory = [
+ { id: "srv_studio", name: "studio", channels: [] },
+ { id: "srv_named_like_id", name: "srv_studio", channels: [] },
+ ]
+ expect(resolveServerRefBase(collidingDirectory, "/srv_studio")?.id).toBe("srv_studio")
+ })
+
+ it("returns null when the server isn't in the directory", () => {
+ expect(resolveServerRefBase(directory, "/nope")).toBeNull()
+ })
+
+ it("returns null for a multi-segment ref — that's channelRef's job, not serverRef's", () => {
+ expect(resolveServerRefBase(directory, "/studio/general")).toBeNull()
+ })
+
+ it("returns null for malformed input", () => {
+ expect(resolveServerRefBase(directory, "not-a-ref")).toBeNull()
+ expect(resolveServerRefBase(directory, "/")).toBeNull()
+ })
+})
diff --git a/src/web/src/lib/community/channel-ref.ts b/src/web/src/lib/community/channel-ref.ts
index 3dfdc7528..c9294cbab 100644
--- a/src/web/src/lib/community/channel-ref.ts
+++ b/src/web/src/lib/community/channel-ref.ts
@@ -8,7 +8,7 @@ import { parseRef } from "@alook/shared"
* whatever servers/channels the client already has loaded.
*/
type ChannelRefDirectoryChannel = { id: string; name: string }
-type ChannelRefDirectoryServer = {
+export type ChannelRefDirectoryServer = {
id: string
name: string
channels: ChannelRefDirectoryChannel[]
@@ -68,3 +68,25 @@ export function resolveChannelRefBase(
...(parsed.threadRootSeq !== undefined ? { threadRootSeq: parsed.threadRootSeq } : {}),
}
}
+
+/**
+ * Resolve a bare `/server` ref (one segment, no channel — `parseRef` throws
+ * on this shape since it requires `/<server>/<channel>`) against the
+ * already-fetched directory. Id-then-exact-name lookup, same precedence and
+ * duplicate-name simplification as `resolveChannelRefBase` — see that
+ * function's doc comment.
+ */
+export function resolveServerRefBase(
+ directory: ChannelRefDirectory,
+ ref: string,
+): ChannelRefDirectoryServer | null {
+ if (!ref.startsWith("/")) return null
+ const body = ref.slice(1)
+ if (!body || body.includes("/")) return null
+
+ return (
+ directory.find((s) => s.id === body) ??
+ directory.find((s) => s.name === body) ??
+ null
+ )
+}
diff --git a/src/web/src/lib/community/chat-syntax-plugin.test.ts b/src/web/src/lib/community/chat-syntax-plugin.test.ts
index eaf73c01b..460f0d5ce 100644
--- a/src/web/src/lib/community/chat-syntax-plugin.test.ts
+++ b/src/web/src/lib/community/chat-syntax-plugin.test.ts
@@ -3,7 +3,7 @@ import { unified } from "unified"
import remarkParse from "remark-parse"
import type { Root, PhrasingContent } from "mdast"
import { chatSyntaxPlugin } from "./chat-syntax-plugin"
-import type { MentionNode, ChannelRefNode } from "./chat-syntax-plugin"
+import type { MentionNode, ChannelRefNode, ServerRefNode } from "./chat-syntax-plugin"
function parse(md: string): Root {
const processor = unified().use(remarkParse).use(chatSyntaxPlugin)
@@ -107,6 +107,42 @@ describe("chatSyntaxPlugin — channelRef", () => {
})
})
+describe("chatSyntaxPlugin — serverRef", () => {
+ it("wraps a bare /server preceded by a space or at start-of-string", () => {
+ expect(paragraphChildren(parse("check /studio"))[1]).toMatchObject({ type: "serverRef", value: "/studio" })
+ expect(paragraphChildren(parse("/studio"))[0]).toMatchObject({ type: "serverRef", value: "/studio" })
+ })
+
+ it("does not double-match the first segment of a /server/channel ref", () => {
+ const children = paragraphChildren(parse("see /studio/general"))
+ expect(children.map((c) => c.type)).toEqual(["text", "channelRef"])
+ expect(children.some((c) => c.type === "serverRef")).toBe(false)
+ })
+
+ it("leaves text/studio (no leading space) untouched", () => {
+ const children = paragraphChildren(parse("text/studio"))
+ expect(children).toHaveLength(1)
+ expect(children[0]).toMatchObject({ type: "text", value: "text/studio" })
+ })
+
+ it("still wraps a bare ref followed by punctuation", () => {
+ const children = paragraphChildren(parse("see /studio."))
+ expect(children.map((c) => c.type)).toEqual(["text", "serverRef", "text"])
+ expect(children[1]).toMatchObject({ value: "/studio" })
+ })
+
+ it("leaves a server-ref-shaped path inside inline code literal", () => {
+ const children = paragraphChildren(parse("`/studio`"))
+ expect(children.map((c) => c.type)).toEqual(["inlineCode"])
+ })
+
+ it("does not match the invite URL's first segment", () => {
+ const bare = paragraphChildren(parse("join /community/invite/abc123XYZ"))
+ expect(bare).toHaveLength(1)
+ expect(bare.some((c) => c.type === "serverRef")).toBe(false)
+ })
+})
+
describe("chatSyntaxPlugin — mixed", () => {
it("handles a mix of mention, channelRef, and unrelated formatting in one message", () => {
const children = paragraphChildren(parse("Here's the **setup**: `pnpm install` ping @Gus in /studio/dev"))
@@ -118,4 +154,12 @@ describe("chatSyntaxPlugin — mixed", () => {
const channelRef = children.find((c): c is ChannelRefNode => c.type === "channelRef")
expect(channelRef).toMatchObject({ value: "/studio/dev" })
})
+
+ it("handles a mention and a bare serverRef together", () => {
+ const children = paragraphChildren(parse("ping @Gus, see /studio for context"))
+ const mention = children.find((c): c is MentionNode => c.type === "mention")
+ expect(mention).toMatchObject({ value: "@Gus" })
+ const serverRef = children.find((c): c is ServerRefNode => c.type === "serverRef")
+ expect(serverRef).toMatchObject({ value: "/studio" })
+ })
})
diff --git a/src/web/src/lib/community/chat-syntax-plugin.ts b/src/web/src/lib/community/chat-syntax-plugin.ts
index a1ead4608..eabf2f46c 100644
--- a/src/web/src/lib/community/chat-syntax-plugin.ts
+++ b/src/web/src/lib/community/chat-syntax-plugin.ts
@@ -6,14 +6,14 @@ import type { Plugin } from "unified"
import { spoilerSyntax, spoilerFromMarkdown } from "./spoiler-syntax"
import type { SpoilerNode } from "./spoiler-syntax"
-// Chat-only syntax (`||spoiler||`, `@mention`, `/server/channel` refs),
-// parsed as real markdown AST nodes rather than string-spliced HTML tags fed
-// through `rehype-raw`. `mention`/`channelRef` content is always an
-// identifier charset (`\p{L}\p{N}_-` for names, `[A-Za-z0-9_-]` for
-// nanoid-based refs) — `remark-parse` never splits an identifier across
-// sibling text nodes (no markdown metacharacters inside one), so a
-// `mdast-util-find-and-replace` pass is safe for these two. `spoiler` is
-// handled separately by the micromark tokenizer extension in
+// Chat-only syntax (`||spoiler||`, `@mention`, `/server/channel` and bare
+// `/server` refs), parsed as real markdown AST nodes rather than
+// string-spliced HTML tags fed through `rehype-raw`. `mention`/`channelRef`/
+// `serverRef` content is always an identifier charset (`\p{L}\p{N}_-` for
+// names, `[A-Za-z0-9_-]` for nanoid-based refs) — `remark-parse` never splits
+// an identifier across sibling text nodes (no markdown metacharacters inside
+// one), so a `mdast-util-find-and-replace` pass is safe for these. `spoiler`
+// is handled separately by the micromark tokenizer extension in
// `spoiler-syntax.ts` — see that file's comment for why find-and-replace
// cannot handle spoilers containing nested formatting.
@@ -35,6 +35,18 @@ import type { SpoilerNode } from "./spoiler-syntax"
// capture group did.
const CHANNEL_REF_RE = /(?<=^|\s)\/[A-Za-z0-9_-]+\/[A-Za-z0-9_-]+(?:\/#\d+)?(?=\s|$|[.,;:!?)\]])/g
+// A bare `/server` ref — one segment, no channel. Same boundary lookaround as
+// `CHANNEL_REF_RE` (leading `(?<=^|\s)`, trailing `(?=\s|$|[.,;:!?)\]])`), which
+// already excludes being followed by another `/segment` — so this never
+// double-matches the first segment of a genuine `/server/channel` ref (that
+// trailing boundary fails when the next char is `/`, and `[A-Za-z0-9_-]+`
+// backtracking can't produce a shorter match that satisfies it either, since
+// every character up to the next `/` is in the segment charset). Registered
+// after `CHANNEL_REF_RE` in `chatSyntaxPlugin`'s pairs list purely for
+// readability (server-only is the "smaller" grammar); the boundary already
+// makes the ordering non-load-bearing for correctness.
+const SERVER_REF_RE = /(?<=^|\s)\/[A-Za-z0-9_-]+(?=\s|$|[.,;:!?)\]])/g
+
// `@name`, `@name#0042` (disambiguating discriminator), or the literal
// `@everyone`/`@here` tokens. `\p{L}\p{N}_-` (Unicode-aware, `u` flag) in
// place of the old `\w` — `Member.name` is a free Unicode string (no
@@ -61,14 +73,22 @@ export interface ChannelRefNode {
value: string
}
+/** mdast node produced by a bare `/server` ref (no channel segment). */
+export interface ServerRefNode {
+ type: "serverRef"
+ value: string
+}
+
declare module "mdast" {
interface RootContentMap {
mention: MentionNode
channelRef: ChannelRefNode
+ serverRef: ServerRefNode
}
interface PhrasingContentMap {
mention: MentionNode
channelRef: ChannelRefNode
+ serverRef: ServerRefNode
}
}
@@ -92,6 +112,10 @@ function channelRefReplacer(value: string): ChannelRefNode {
return { type: "channelRef", value }
}
+function serverRefReplacer(value: string): ServerRefNode {
+ return { type: "serverRef", value }
+}
+
/**
* remark plugin: combines the spoiler micromark extension (`spoiler-syntax.ts`)
* with a `mdast-util-find-and-replace` pass for `mention`/`channelRef`.
@@ -113,6 +137,11 @@ export const chatSyntaxPlugin: Plugin<[], Root> = function chatSyntaxPlugin(this
[
[MENTION_RE, mentionReplacer as unknown as (value: string, ...rest: unknown[]) => PhrasingContent | string | false],
[CHANNEL_REF_RE, channelRefReplacer as unknown as (value: string) => PhrasingContent],
+ // Runs as its own pass AFTER the channelRef pass above — by then every
+ // `/server/channel` span is already a `channelRef` element (no longer
+ // a `text` node `findAndReplace` visits), so this pass only ever sees
+ // genuine bare `/server` refs among the remaining text.
+ [SERVER_REF_RE, serverRefReplacer as unknown as (value: string) => PhrasingContent],
],
{ ignore: IGNORE_NODE_TYPES },
)
@@ -146,4 +175,10 @@ export const chatSyntaxHandlers: Handlers = {
properties: {},
children: [{ type: "text", value: node.value }],
})) as Handler,
+ serverRef: ((_state, node: ServerRefNode): Element => ({
+ type: "element",
+ tagName: "serverref",
+ properties: {},
+ children: [{ type: "text", value: node.value }],
+ })) as Handler,
}
diff --git a/src/ws-do/src/ws-durable.test.ts b/src/ws-do/src/ws-durable.test.ts
index e807a8efe..7b2660a66 100644
--- a/src/ws-do/src/ws-durable.test.ts
+++ b/src/ws-do/src/ws-durable.test.ts
@@ -84,6 +84,16 @@ const mockGetDM = vi.fn()
const mockListMembers = vi.fn()
const mockListBotsForMachine = vi.fn<(db: unknown, machineId: string) => Promise<Array<{ id: string; name: string; discriminator: string; description: string }>>>().mockResolvedValue([])
const mockIsBotOnline = vi.fn<(db: unknown, botUserId: string) => Promise<boolean>>().mockResolvedValue(false)
+const mockGetBotBinding = vi.fn<(db: unknown, botId: string) => Promise<{ machineId: string; runtime: string } | null>>().mockResolvedValue(null)
+const mockUpdateProfile = vi
+ .fn<(db: unknown, userId: string, data: { statusEmoji?: string | null; statusText?: string | null }) => Promise<unknown>>()
+ .mockResolvedValue({})
+const mockGetProfile = vi
+ .fn<(db: unknown, userId: string) => Promise<{ statusEmoji: string | null; statusText: string | null } | null>>()
+ .mockResolvedValue(null)
+const mockReconcileBotActivityFromRunningAgents = vi
+ .fn<(db: unknown, machineId: string, runningAgentIds: string[]) => Promise<Array<{ botUserId: string; statusEmoji: string; statusText: string }>>>()
+ .mockResolvedValue([])
const mockGetUserInternal = vi.fn<(db: unknown, id: string) => Promise<{ isBot: boolean; ownerUserId: string | null } | null>>().mockResolvedValue(null)
// mockToSummary now returns row.status verbatim — status is the source of
// truth on the column, not a derivation from lastSeenAt. See
@@ -153,6 +163,15 @@ vi.mock("@alook/shared", () => {
return { success: true as const, data }
},
}
+ const AgentActivityMessageSchema = {
+ safeParse(v: unknown) {
+ const m = v as { type?: unknown; agentId?: unknown; state?: unknown }
+ if (m?.type !== "agent_activity") return { success: false } as const
+ if (typeof m.agentId !== "string") return { success: false } as const
+ if (!["idle", "starting", "running", "stopping"].includes(m.state as string)) return { success: false } as const
+ return { success: true as const, data: { type: "agent_activity" as const, agentId: m.agentId, state: m.state } }
+ },
+ }
return {
createDb: (d1: unknown) => mockCreateDb(d1),
createLogger: () => noopLogger,
@@ -160,6 +179,23 @@ vi.mock("@alook/shared", () => {
COMMUNITY_MACHINE_OFFLINE_THRESHOLD_MS: 120_000,
SessionErrorFrameSchema,
HostReadyMessageSchema,
+ AgentActivityMessageSchema,
+ // Deterministic preset picker so the assertion can pin exact
+ // `statusEmoji`/`statusText` values regardless of the injected `seed`.
+ pickBotActivityPreset: (state: string) => {
+ if (state === "running") return { emoji: "⚡", text: "Working on it" }
+ if (state === "starting") return { emoji: "🌀", text: "Waking up" }
+ if (state === "stopping") return { emoji: "🌙", text: "Wrapping up" }
+ return { emoji: "💤", text: "Idle" }
+ },
+ RUNNING_PRESETS: [
+ { emoji: "⚡", text: "Working on it" },
+ { emoji: "🛠️", text: "Cooking" },
+ { emoji: "🧠", text: "Thinking hard" },
+ { emoji: "🔧", text: "Tinkering" },
+ { emoji: "🚀", text: "On it" },
+ { emoji: "🔥", text: "In the zone" },
+ ],
queries: {
session: { getValidSession: (db: unknown, token: string) => mockGetValidSession(db, token) },
machineToken: {
@@ -177,6 +213,13 @@ vi.mock("@alook/shared", () => {
markMachineOnlineIfOffline: (...a: any[]) => mockMarkMachineOnlineIfOffline(...a),
toSummary: (row: any) => mockToSummary(row),
isBotOnline: (...a: [unknown, string]) => mockIsBotOnline(...a),
+ reconcileBotActivityFromRunningAgents: (...a: any[]) =>
+ mockReconcileBotActivityFromRunningAgents(...(a as [unknown, string, string[]])),
+ },
+ communityUserProfile: {
+ updateProfile: (...a: any[]) =>
+ mockUpdateProfile(...(a as [unknown, string, { statusEmoji?: string | null; statusText?: string | null }])),
+ getProfile: (...a: any[]) => mockGetProfile(...(a as [unknown, string])),
},
communityMember: {
getCoMemberUserIds: (...a: [unknown, string]) => mockGetCoMemberUserIds(...a),
@@ -198,6 +241,7 @@ vi.mock("@alook/shared", () => {
},
communityBot: {
listBotsForMachine: (...a: [unknown, string]) => mockListBotsForMachine(...a),
+ getBotBinding: (...a: [unknown, string]) => mockGetBotBinding(...a),
},
user: {
getUserInternal: (...a: [unknown, string]) => mockGetUserInternal(...a),
@@ -240,6 +284,10 @@ describe("WebSocketDurableObject", () => {
mockGetUserInternal.mockResolvedValue(null)
mockIsChannelPrivate.mockResolvedValue(false)
mockGetPrivateChannelAudienceUserIds.mockResolvedValue([])
+ mockGetBotBinding.mockResolvedValue(null)
+ mockUpdateProfile.mockResolvedValue({})
+ mockGetProfile.mockResolvedValue(null)
+ mockReconcileBotActivityFromRunningAgents.mockResolvedValue([])
})
describe("fetch — WebSocket upgrade", () => {
@@ -1062,6 +1110,204 @@ describe("WebSocketDurableObject", () => {
})
})
+ describe("community-machine — agent_activity frame", () => {
+ beforeEach(() => {
+ mockGetBotBinding.mockReset()
+ mockUpdateProfile.mockReset().mockResolvedValue({})
+ mockGetProfile.mockReset().mockResolvedValue(null)
+ mockStubFetch.mockClear()
+ })
+
+ it("writes the translated statusEmoji/statusText via updateProfile and fans out community:status.update when the frame's machine owns the bot", async () => {
+ const { durable, store } = createDO()
+ store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "0".repeat(64),
+ })
+ mockGetBotBinding.mockResolvedValue({ machineId: "cm_1", runtime: "codex" })
+ mockGetCoMemberUserIds.mockResolvedValue(["viewer-1"])
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({
+ type: "community-machine",
+ machineId: "cm_1",
+ userId: "u_1",
+ authenticated: true,
+ })
+
+ const frame = JSON.stringify({ type: "agent_activity", agentId: "bot_1", state: "running" })
+ await durable.webSocketMessage(ws as any, frame)
+
+ // The (stubbed) `pickBotActivityPreset` returns a fixed pair for
+ // "running" in this test — the assertion pins that exact pair.
+ expect(mockUpdateProfile).toHaveBeenCalledWith(expect.anything(), "bot_1", {
+ statusEmoji: "⚡",
+ statusText: "Working on it",
+ })
+ const call = mockStubFetch.mock.calls.find((c: any[]) => (c[0] as Request).url.endsWith("/broadcast"))
+ expect(call).toBeDefined()
+ const body = JSON.parse(await (call![0] as Request).clone().text()) as {
+ type: string
+ userId: string
+ statusEmoji: string
+ statusText: string
+ }
+ expect(body).toEqual({
+ type: "community:status.update",
+ userId: "bot_1",
+ statusEmoji: "⚡",
+ statusText: "Working on it",
+ })
+ })
+
+ it("drops a frame naming a bot bound to a different machine — no DB write, no fan-out", async () => {
+ const { durable, store } = createDO()
+ store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "0".repeat(64),
+ })
+ mockGetBotBinding.mockResolvedValue({ machineId: "cm_OTHER", runtime: "codex" })
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({
+ type: "community-machine",
+ machineId: "cm_1",
+ userId: "u_1",
+ authenticated: true,
+ })
+
+ const frame = JSON.stringify({ type: "agent_activity", agentId: "bot_1", state: "running" })
+ await durable.webSocketMessage(ws as any, frame)
+
+ expect(mockUpdateProfile).not.toHaveBeenCalled()
+ expect(mockStubFetch).not.toHaveBeenCalled()
+ })
+
+ it("drops a frame for an unbound (unknown) bot — no DB write, no fan-out", async () => {
+ const { durable, store } = createDO()
+ store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "0".repeat(64),
+ })
+ mockGetBotBinding.mockResolvedValue(null)
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({
+ type: "community-machine",
+ machineId: "cm_1",
+ userId: "u_1",
+ authenticated: true,
+ })
+
+ const frame = JSON.stringify({ type: "agent_activity", agentId: "ghost_bot", state: "idle" })
+ await durable.webSocketMessage(ws as any, frame)
+
+ expect(mockUpdateProfile).not.toHaveBeenCalled()
+ expect(mockStubFetch).not.toHaveBeenCalled()
+ })
+ })
+
+ describe("community-machine — ready frame reconciles bot activity", () => {
+ beforeEach(() => {
+ mockUpsertMachineByMachineId.mockReset()
+ mockReconcileBotActivityFromRunningAgents.mockReset().mockResolvedValue([])
+ mockStubFetch.mockClear()
+ })
+
+ it("a ready frame whose runningAgents disagrees with persisted state fans out community:status.update for each cleared bot", async () => {
+ const { durable, store } = createDO()
+ store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "0".repeat(64),
+ })
+ mockUpsertMachineByMachineId.mockResolvedValue({
+ machine: {
+ id: "cm_1",
+ hostname: "host",
+ availableRuntimes: [],
+ status: "online",
+ lastSeenAt: "2026-07-13T00:00:00.000Z",
+ },
+ priorLastSeenAt: "2026-07-12T00:00:00.000Z",
+ priorAvailableRuntimes: [],
+ priorStatus: "online",
+ })
+ mockReconcileBotActivityFromRunningAgents.mockResolvedValue([
+ { botUserId: "bot_1", statusEmoji: "💤", statusText: "Idle" },
+ { botUserId: "bot_2", statusEmoji: "💤", statusText: "Idle" },
+ ])
+ mockGetCoMemberUserIds.mockResolvedValue(["viewer-1"])
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({
+ type: "community-machine",
+ machineId: "cm_1",
+ userId: "u_1",
+ authenticated: true,
+ })
+
+ const frame = JSON.stringify({
+ type: "ready",
+ runtimeReport: [],
+ runningAgents: [],
+ })
+ await durable.webSocketMessage(ws as any, frame)
+
+ expect(mockReconcileBotActivityFromRunningAgents).toHaveBeenCalledWith(expect.anything(), "cm_1", [])
+ const activityCalls = mockStubFetch.mock.calls.filter((c: any[]) => (c[0] as Request).url.endsWith("/broadcast"))
+ const bodies = await Promise.all(activityCalls.map((c: any[]) => (c[0] as Request).clone().text()))
+ const parsed = bodies.map((b) => JSON.parse(b)).filter((b) => b.type === "community:status.update")
+ expect(parsed).toEqual(
+ expect.arrayContaining([
+ { type: "community:status.update", userId: "bot_1", statusEmoji: "💤", statusText: "Idle" },
+ { type: "community:status.update", userId: "bot_2", statusEmoji: "💤", statusText: "Idle" },
+ ])
+ )
+ })
+
+ it("emits no status.update fan-out when reconciliation finds no changes", async () => {
+ const { durable, store } = createDO()
+ store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "0".repeat(64),
+ })
+ mockUpsertMachineByMachineId.mockResolvedValue({
+ machine: {
+ id: "cm_1",
+ hostname: "host",
+ availableRuntimes: [],
+ status: "online",
+ lastSeenAt: "2026-07-13T00:00:00.000Z",
+ },
+ priorLastSeenAt: "2026-07-12T00:00:00.000Z",
+ priorAvailableRuntimes: [],
+ priorStatus: "online",
+ })
+ mockReconcileBotActivityFromRunningAgents.mockResolvedValue([])
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({
+ type: "community-machine",
+ machineId: "cm_1",
+ userId: "u_1",
+ authenticated: true,
+ })
+
+ const frame = JSON.stringify({ type: "ready", runtimeReport: [], runningAgents: [] })
+ await durable.webSocketMessage(ws as any, frame)
+
+ const activityCalls = mockStubFetch.mock.calls.filter((c: any[]) => (c[0] as Request).url.endsWith("/broadcast"))
+ const bodies = await Promise.all(activityCalls.map((c: any[]) => (c[0] as Request).clone().text()))
+ const parsed = bodies.map((b) => JSON.parse(b)).filter((b) => b.type === "community:status.update")
+ expect(parsed).toEqual([])
+ })
+ })
+
describe("community-machine — webSocketClose presence lifecycle", () => {
// These tests cover the "graceful daemon quit → immediate offline" fix.
// See plans/community-machine-presence-fix.md § Server transitions.
diff --git a/src/ws-do/src/ws-durable.ts b/src/ws-do/src/ws-durable.ts
index ea4ebd360..30647d714 100644
--- a/src/ws-do/src/ws-durable.ts
+++ b/src/ws-do/src/ws-durable.ts
@@ -7,6 +7,9 @@ import {
COMMUNITY_MACHINE_OFFLINE_THRESHOLD_MS,
HostReadyMessageSchema,
SessionErrorFrameSchema,
+ AgentActivityMessageSchema,
+ pickBotActivityPreset,
+ RUNNING_PRESETS,
} from "@alook/shared"
import type { CommunityMachineRuntime, CommunityMachineSummary } from "@alook/shared"
@@ -654,6 +657,57 @@ export class WebSocketDurableObject extends DurableObject<Env> {
return
}
+ // `agent_activity` — daemon reports a bot's derived activity state.
+ // Translated INTO the same `statusEmoji`/`statusText` fields humans use
+ // (so bots and humans share one status pipeline end-to-end and the
+ // client never branches on "is this a bot") and fanned out via
+ // `community:status.update`. `running` picks a fun preset once here
+ // and persists it, so every viewer sees the same phrase for that
+ // episode — no client-side randomization, no jitter on re-open.
+ //
+ // Verify the reporting machine actually owns this bot before writing —
+ // never trust the frame-supplied agentId blindly, matching how other
+ // frames on this channel trust `identity` but not frame-supplied ids.
+ const activityParse = AgentActivityMessageSchema.safeParse(parsed)
+ if (activityParse.success) {
+ const { agentId, state } = activityParse.data
+ const db = createDb(this.env.DB)
+ const binding = await queries.communityBot.getBotBinding(db, agentId)
+ if (!binding || binding.machineId !== identity.machineId) {
+ log.warn("agent_activity frame for a bot not bound to this machine — dropped", {
+ agentId,
+ machineId: identity.machineId,
+ })
+ return
+ }
+ const prior = await queries.communityUserProfile.getProfile(db, agentId)
+ const priorEmoji = prior?.statusEmoji ?? null
+ const priorText = prior?.statusText ?? null
+ const priorIsRunning =
+ priorEmoji !== null &&
+ RUNNING_PRESETS.some((p) => p.emoji === priorEmoji && p.text === priorText)
+ // For `running`, reuse the currently-persisted preset if it's already
+ // one of the running variants — matches the "one phrase per episode"
+ // invariant instead of re-rolling on every derived running transition
+ // (turn_end → idle → wake → running fires this repeatedly).
+ const preset =
+ state === "running" && priorIsRunning
+ ? { emoji: priorEmoji as string, text: priorText as string }
+ : pickBotActivityPreset(state, Math.random())
+ if (preset.emoji === priorEmoji && preset.text === priorText) return
+ await queries.communityUserProfile.updateProfile(db, agentId, {
+ statusEmoji: preset.emoji,
+ statusText: preset.text,
+ })
+ await this.broadcastToAudience(agentId, {
+ type: "community:status.update",
+ userId: agentId,
+ statusEmoji: preset.emoji,
+ statusText: preset.text,
+ })
+ return
+ }
+
// Otherwise: only `ready` frames drive DB updates. Zod-parse strictly —
// legacy `runtimes: string[]`-only frames from pre-refactor daemons fail
// validation and are silently dropped; MIN_CLI_VERSION will squeeze them
@@ -684,6 +738,29 @@ export class WebSocketDurableObject extends DurableObject<Env> {
}
const { machine, priorAvailableRuntimes, priorStatus } = result
+ // Coarse safety net for an `agent_activity` frame dropped mid-disconnect —
+ // clear any bot on this machine whose current status pill looks like a
+ // stale system-written activity pill AND who the daemon reports is NOT
+ // running now. Live `agent_activity` pushes handle every non-`idle`
+ // transition; the reconciler only ever writes `Idle`. Owner-set custom
+ // statuses (identified by not matching the known bot presets) are left
+ // alone. See plans/community-bot-status-telemetry.md.
+ const activityChanges = await queries.communityMachine.reconcileBotActivityFromRunningAgents(
+ db,
+ machine.id,
+ ready.runningAgents
+ )
+ await Promise.allSettled(
+ activityChanges.map(({ botUserId, statusEmoji, statusText }) =>
+ this.broadcastToAudience(botUserId, {
+ type: "community:status.update",
+ userId: botUserId,
+ statusEmoji,
+ statusText,
+ })
+ )
+ )
+
const summary = await this.summaryWithOverlay(machine)
// Refresh the offline-detection handle in case metadata changed. Handle
// was written at accept; this is idempotent.
@@ -976,9 +1053,19 @@ export class WebSocketDurableObject extends DurableObject<Env> {
private static readonly SUBREQUEST_BATCH_SIZE = 40
private async broadcastPresence(userId: string, online: boolean): Promise<void> {
+ await this.broadcastToAudience(userId, { type: "community:presence.update", userId, online })
+ }
+
+ /**
+ * Fan a payload out to `userId`'s presence audience (co-members ∪ friends),
+ * batched to stay under the subrequest limit. Factored out of
+ * `broadcastPresence` so other per-audience events (e.g.
+ * `community:bot.activity`) share the same batched-fetch loop.
+ */
+ private async broadcastToAudience(userId: string, payload: unknown): Promise<void> {
const audience = await this.getPresenceAudience(userId)
if (audience.length === 0) return
- const payload = JSON.stringify({ type: "community:presence.update", userId, online })
+ const body = JSON.stringify(payload)
for (let i = 0; i < audience.length; i += WebSocketDurableObject.SUBREQUEST_BATCH_SIZE) {
const batch = audience.slice(i, i + WebSocketDurableObject.SUBREQUEST_BATCH_SIZE)
await Promise.allSettled(
@@ -987,7 +1074,7 @@ export class WebSocketDurableObject extends DurableObject<Env> {
const stub = this.env.WS_DO.get(doId)
return stub.fetch(new Request("http://internal/broadcast", {
method: "POST",
- body: payload,
+ body,
}))
})
)
diff --git a/tests/integration/daemon/control-plane.test.ts b/tests/integration/daemon/control-plane.test.ts
index 6a98fa529..84f7e3db8 100644
--- a/tests/integration/daemon/control-plane.test.ts
+++ b/tests/integration/daemon/control-plane.test.ts
@@ -192,6 +192,42 @@ describe("daemon control plane — real ws-do wake round-trip", () => {
await waitForChannelReply(fixture.channelId, cookie, replyText)
}, 30_000)
+ it("reports agent_activity over the real WsControlChannel and the profile route reflects running, then idle after the stub session ends its turn", async () => {
+ // Reuses the already-open `channel` from the first test — asserts the
+ // wire-level `agent_activity` frame this plan adds actually persists and
+ // is visible via the owner-facing /profile route (the read-side this
+ // plan's UI depends on for a fresh page load).
+ expect(channel).toBeDefined()
+
+ // Bot activity is stored on the same `statusEmoji`/`statusText` fields
+ // humans use — the WS DO translates the daemon's `agent_activity` frame
+ // into the appropriate preset and writes/broadcasts it as an ordinary
+ // status update (see plans/community-bot-status-telemetry.md).
+ await channel!.reportAgentActivity({ agentId: fixture.bot.botUserId, state: "running" })
+ const runningProfile = await waitForAsync(async () => {
+ const res = await sessionRequest(`/api/community/users/${fixture.bot.botUserId}/profile`, cookie)
+ if (!res.ok) return undefined
+ const body = (await res.json()) as { statusText: string | null }
+ // Any of the fun `running` variants counts — the WS DO picks one at random.
+ return typeof body.statusText === "string" && /Working on it|Cooking|Thinking hard|Tinkering|On it|In the zone/.test(body.statusText)
+ ? body
+ : undefined
+ }, 15_000)
+ expect(runningProfile.statusText).toMatch(/Working on it|Cooking|Thinking hard|Tinkering|On it|In the zone/)
+
+ // Simulates the stub session's turn ending (the real daemon would derive
+ // this via `deriveActivity` — here we report the wire-level state
+ // directly since no CLI is spawned in this harness).
+ await channel!.reportAgentActivity({ agentId: fixture.bot.botUserId, state: "idle" })
+ const idleProfile = await waitForAsync(async () => {
+ const res = await sessionRequest(`/api/community/users/${fixture.bot.botUserId}/profile`, cookie)
+ if (!res.ok) return undefined
+ const body = (await res.json()) as { statusText: string | null }
+ return body.statusText === "Idle" ? body : undefined
+ }, 15_000)
+ expect(idleProfile.statusText).toBe("Idle")
+ }, 30_000)
+
it("fans out an independent agent:wake to each of several bots bound to the same machine, over the same socket", async () => {
// Reuses the already-open `channel` from the previous test — this is the
// scenario the deleted `controlPlane.e2e.test.ts`'s "multiple agents each