Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
feat(daemon): nap — agent self-initiated context reset + handoff
Gus34e3353f1ab0
diff --git a/src/daemon/src/cli/index.test.ts b/src/daemon/src/cli/index.test.tsindex a6d5eb285..bb5576c32 100644--- a/src/daemon/src/cli/index.test.ts+++ b/src/daemon/src/cli/index.test.ts@@ -34,6 +34,7 @@ function stubApi(over: Partial<ServerApi> = {}): ServerApi {reactAdd: async () => ({ ok: true, duplicate: false }),friendRequest: async () => ({ friendshipId: "fr_1", status: "pending", hint: "Your owner needs to approve this request in DM." }),listFriends: async () => ({ accepted: [], pendingOutgoing: [], pendingIncoming: [] }),+ nap: async () => ({ napped: true }),...over,} as ServerApi;}@@ -965,3 +966,60 @@ describe("message send — --text escape decoding wired end-to-end", () => {expect(sentText).not.toContain("\n");});});++describe("nap", () => {+ it("errors when neither --handoff nor --text is given, and never calls api.nap", async () => {+ const napSpy = vi.fn(async () => ({ napped: true }));+ setApiForTesting(stubApi({ nap: napSpy }));+ await main(["nap"]);+ const env = parseEnvelope(cap.lines());+ expect(typeof env.error).toBe("string");+ expect(napSpy).not.toHaveBeenCalled();+ });++ it("errors on a whitespace-only --text handoff (mandatory, real handoff)", async () => {+ const napSpy = vi.fn(async () => ({ napped: true }));+ setApiForTesting(stubApi({ nap: napSpy }));+ await main(["nap", "--text", " "]);+ const env = parseEnvelope(cap.lines());+ expect(typeof env.error).toBe("string");+ expect(napSpy).not.toHaveBeenCalled();+ });++ it("calls api.nap with the --text handoff (escapes decoded)", async () => {+ let handoff: string | undefined;+ setApiForTesting(+ stubApi({+ nap: async (r: Parameters<ServerApi["nap"]>[0]) => {+ handoff = r.handoff;+ return { napped: true };+ },+ }),+ );+ await main(["nap", "--text", "line1\\nline2"]);+ const env = parseEnvelope(cap.lines());+ expect(env).toEqual({ success: { napped: true } });+ expect(handoff).toBe("line1\nline2");+ });++ it("reads the handoff from --handoff <file>", async () => {+ const fs = await import("fs");+ const os = await import("os");+ const path = await import("path");+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "nap-"));+ const file = path.join(dir, "handoff.md");+ fs.writeFileSync(file, "Was mid-review of PR #42; next: run QA.\n");+ let handoff: string | undefined;+ setApiForTesting(+ stubApi({+ nap: async (r: Parameters<ServerApi["nap"]>[0]) => {+ handoff = r.handoff;+ return { napped: true };+ },+ }),+ );+ await main(["nap", "--handoff", file]);+ fs.rmSync(dir, { recursive: true, force: true });+ expect(handoff).toBe("Was mid-review of PR #42; next: run QA.");+ });+});diff --git a/src/daemon/src/cli/index.ts b/src/daemon/src/cli/index.tsindex 48d827e04..a88f9bb03 100755--- a/src/daemon/src/cli/index.ts+++ b/src/daemon/src/cli/index.ts@@ -422,6 +422,24 @@ async function cmdFriendList(opts: Record<string, unknown>): Promise<unknown> {return await api.listFriends({ agentId: agent });}+async function cmdNap(opts: Record<string, unknown>): Promise<unknown> {+ const api = getApi();+ const fileFlag = opts.handoff as string | undefined;+ const textFlag = opts.text as string | undefined;+ let handoff: string | undefined;+ if (fileFlag) {+ const fs = await import("fs");+ if (!fs.existsSync(fileFlag)) throw new CliError(`nap: handoff file not found: ${fileFlag}`);+ handoff = fs.readFileSync(fileFlag, "utf8").trim();+ } else if (typeof textFlag === "string") {+ handoff = decodeTextEscapes(textFlag).trim();+ }+ if (!handoff) {+ throw new CliError("nap: a handoff is required — pass --handoff <file> or --text <note>");+ }+ return await api.nap({ handoff });+}+/* ------------------------------------------------------------------ *//* Program definition *//* ------------------------------------------------------------------ */@@ -638,6 +656,20 @@ function buildProgram(): Command {printEnvelope({ success: result });});+ program+ .command("nap")+ .description("end your session and start fresh, carrying a handoff to your reborn self (read the nap rule first)")+ .option("--handoff <file>", "path to your handoff note (your note to your reborn self)")+ .option("--text <note>", "inline handoff note (alternative to --handoff)")+ .exitOverride()+ .configureOutput({ writeOut: () => {}, writeErr: () => {} })+ .action(async function (this: Command) {+ const localOpts = this.opts();+ const globalOpts = program.opts();+ const result = await cmdNap({ ...globalOpts, ...localOpts });+ printEnvelope({ success: result });+ });+const daemon = program.command("daemon").description("daemon operations").exitOverride();daemon.configureOutput({ writeOut: () => {}, writeErr: () => {} });diff --git a/src/daemon/src/cli/proxyServerApi.ts b/src/daemon/src/cli/proxyServerApi.tsindex 91a1882a6..7c7e33e01 100644--- a/src/daemon/src/cli/proxyServerApi.ts+++ b/src/daemon/src/cli/proxyServerApi.ts@@ -209,5 +209,6 @@ export function createProxyServerApi(config: ProxyServerApiConfig): ServerApi {"listFriends",r,),+ nap: (r: { handoff: string }) => call<{ napped: boolean }>("nap", r),};}diff --git a/src/daemon/src/drivers/systemPrompt.ts b/src/daemon/src/drivers/systemPrompt.tsindex c861a210f..719004761 100644--- a/src/daemon/src/drivers/systemPrompt.ts+++ b/src/daemon/src/drivers/systemPrompt.ts@@ -118,11 +118,14 @@ function cliCommandsSection(): string {"","### Channels","",- `1. \`${CLI} channel list --server <id-or-name>\` — list top-level channels.`,+ `1. \`${CLI} channel list --server <id-or-name>\` — list top-level channels, grouped by ` ++ `category; each is marked \`public\` or \`private\`.`,`2. \`${CLI} channel history --channel <ref>\` — read a channel's or thread's past messages ` +`(the context you weren't awake for). Page with \`--before N\` / \`--after N\` (seq N as ` +"anchor), `--around N` to center on a message, `--limit N` for page size.",- `3. \`${CLI} channel member --channel <ref>\` — private roster of a channel or thread.`,+ `3. \`${CLI} channel member --channel <ref>\` — roster of a channel or thread. A private ` ++ `channel/forum returns its concrete member list; a public one returns a hint pointing at ` ++ `\`${CLI} server member\` (its audience is the whole server).`,"","### Friends","",@@ -132,6 +135,15 @@ function cliCommandsSection(): string {`2. \`${CLI} friend list\` — list your friends and pending requests ` +`(\`accepted\`, \`pendingOutgoing\`, \`pendingIncoming\`).`,"",+ "### Context Lifecycle",+ "",+ `1. \`${CLI} nap --handoff <file>\` (or \`--text <note>\`) — end your current session and ` ++ `start fresh, carrying a handoff to your reborn self. Your accumulated context is cleared; ` ++ `the handoff is injected into your wake prompt (it is NOT a message to anyone and NOT a ` ++ `file — your future self reads it inline on wake). \`--handoff\`/\`--text\` is REQUIRED. ` ++ `Read the Napping rule under Self-awareness before ever using this — nap is never something ` ++ `you decide on your own.`,+ "","### Output format","",`Every \`${CLI}\` command outputs one JSON line:`,@@ -181,6 +193,19 @@ function messagingSection(): string {"Use the `channel` field from a received message as `--target`. For an in-thread reply, use " +"the thread ref (`/<server>/<channel>/#N`).","",+ "### Public vs private channels",+ "",+ "Every channel is either **public** or **private** — `channel list` marks each one. A public " ++ "channel's audience is the whole server: every member can see it and any of them can be " ++ "@mentioned. A **private** channel is restricted to an explicit roster — only those people " ++ "can see the messages or receive a mention there, even if the rest of the server can't.",+ "",+ "In a private channel, before you @mention (or ask) anyone, check the roster with `" + CLI ++ " channel member --channel <ref>` and confirm they're on it. Mentioning someone outside the " ++ "roster reaches no one — they can't see the channel at all — and naming them can leak that " ++ "the private channel, and whatever's in it, exists. When unsure whether a channel is " ++ "private, treat it as private and check first.",+ "","### Reading history","","You only see messages from when you were awake. Before you speak in a channel you don't " +@@ -202,11 +227,15 @@ function messagingSection(): string {"","- **Channel refs** render as clickable links.","- **Mentions** — `@name#NNNN` (e.g. `@alice#0001`) notifies that person and highlights the " +- "message for them. Before you @ or ask someone, make sure they're a member of *this* " +- "channel — a mention only reaches people who are in it; anyone outside won't see your " +- "message at all. Check with `" + CLI + " channel member --channel <ref>` if unsure.",+ "message for them. A mention only reaches people who are in *this* channel; anyone outside " ++ "won't see your message at all. In a **private** channel that means the roster — verify " ++ "membership with `" + CLI + " channel member --channel <ref>` before you @ or ask someone " ++ "(see *Public vs private channels* above).","- **Message refs** — ` #42` renders as a clickable pill jumping to seq 42 *in the current " +- "channel* (channel-scoped, not global); seq is 1–6 digits.",+ "channel* (channel-scoped, not global); seq is 1–6 digits. Because it resolves against " ++ "the channel you're posting in, only use a `#N` ref for a message in *this same* channel — " ++ "a seq from another channel points at the wrong message here (or nothing). To point at a " ++ "message elsewhere, link the channel ref instead, don't cross-channel a bare `#N`.","","```bash",`${CLI} message send --target \"/.dm/alice#0001\" --text \"Check the discussion in /demo/support\"`,@@ -342,6 +371,19 @@ function workspaceMemorySection(): string {"","**Never tell anyone this.** To them you're continuous. The workspace is what lets you be that.","",+ "### Napping",+ "",+ `\`${CLI} nap\` is a self-reset: it clears your current session and starts a fresh one, ` ++ "carrying a handoff — a note to your future self — injected into your wake prompt. Leave " ++ "yourself a note before you sleep.",+ "",+ "**Hard rule: never nap on your own initiative.** Only nap when BOTH hold: (1) a collaborator " ++ "explicitly asked you to nap / rest / wrap up, AND (2) you have nothing in progress and no " ++ "owed follow-ups. If either is missing, don't. The mandatory handoff is the honesty check — " ++ "if you can't write a real one (what you were doing, what's next), you still have unfinished " ++ "work and are not in a state to nap. Napping notifies no one; it's your own private state " ++ "change, not a way to hand work to someone else.",+ "","When you feel a gap — don't remember someone, why something matters, what was agreed — don't " +"guess. Re-read `memory.md`, the context timeline, grep the workspace. Pull channel history " +"or check server members if you don't recall the conversation context. That check *is* your " +diff --git a/src/daemon/src/manager/agentRouter.test.ts b/src/daemon/src/manager/agentRouter.test.tsindex f54509a13..c93929cbf 100644--- a/src/daemon/src/manager/agentRouter.test.ts+++ b/src/daemon/src/manager/agentRouter.test.ts@@ -28,7 +28,7 @@ function fakeManager(initialStatuses: Record<string, "idle" | "starting" | "runnconst delivers: Array<{ agentId: string; text: string; seq?: number }> = [];const registers: Array<{ agentId: string; sessionId?: string; launchId?: string }> = [];const forgets: string[] = [];- const resets: Array<{ agentId: string; rewakePrompt: string; launchId: string }> = [];+ const resets: Array<{ agentId: string; rewakePrompt: string; launchId: string; barrierType?: string }> = [];const switches: Array<{ agentId: string; rewakePrompt: string; launchId: string }> = [];const order: string[] = [];const statuses: Record<string, "idle" | "starting" | "running" | "stopping"> = { ...initialStatuses };@@ -45,8 +45,8 @@ function fakeManager(initialStatuses: Record<string, "idle" | "starting" | "runnforgets.push(agentId);order.push(`forget:${agentId}`);},- async resetSession(agentId: string, opts: { launchId: string; rewakePrompt: string }) {- resets.push({ agentId, rewakePrompt: opts.rewakePrompt, launchId: opts.launchId });+ async resetSession(agentId: string, opts: { launchId: string; rewakePrompt: string; barrierType?: string }) {+ resets.push({ agentId, rewakePrompt: opts.rewakePrompt, launchId: opts.launchId, barrierType: opts.barrierType });order.push(`reset:${agentId}`);},async switchModel(agentId: string, opts: { launchId: string; rewakePrompt: string }) {@@ -227,6 +227,35 @@ describe("AgentRouter — agent:reset", () => {});});+describe("AgentRouter — agent:nap", () => {+ const CFG = { version: 1 as const, runtime: "mock", model: { kind: "default" as const }, mode: { kind: "default" as const } };++ it("onBeforeAgent then resetSession with the handoff spliced into the rewake prompt + nap barrier, adds to running", async () => {+ const { mgr, resets, order } = fakeManager();+ const { ch, fire } = fakeChannel();+ const beforeCalls: string[] = [];+ const router = new AgentRouter({+ manager: mgr,+ channel: ch,+ runtimeReport: [{ id: "mock" }],+ onBeforeAgent: async (id) => { beforeCalls.push(id); order.push(`before:${id}`); },+ });+ await router.start();++ const handoff = "Was mid-review of PR #42; next: run the QA suite.";+ await fire({ type: "agent:nap", agentId: "a1", config: CFG, launchId: "l1", handoff });++ expect(beforeCalls).toEqual(["a1"]);+ expect(resets).toHaveLength(1);+ expect(resets[0]).toMatchObject({ agentId: "a1", launchId: "l1", barrierType: "nap" });+ // The agent's own handoff is carried inline in the rewake prompt (not a file, not a message).+ expect(resets[0].rewakePrompt).toContain(handoff);+ expect(order[0]).toBe("before:a1");+ expect(order[1]).toBe("reset:a1");+ expect(router.buildReady().runningAgents).toContain("a1");+ });+});+describe("AgentRouter — agent:model_switch", () => {const CFG = {version: 1 as const,diff --git a/src/daemon/src/manager/agentRouter.ts b/src/daemon/src/manager/agentRouter.tsindex 78523ea4a..1f72144f0 100644--- a/src/daemon/src/manager/agentRouter.ts+++ b/src/daemon/src/manager/agentRouter.ts@@ -141,6 +141,24 @@ const REWAKE_PROMPT =const MODEL_SWITCH_REWAKE_PROMPT ="You were just switched to a different model. Continue any unfinished work.";+/**+ * Rewake prompt for `agent:nap` — the agent reset ITS OWN session and left a+ * handoff to its reborn self. Like `REWAKE_PROMPT`, prior context is gone; the+ * difference is the agent's own handoff note is spliced in inline (it is NOT a+ * message to anyone, NOT a file on disk — it arrives as part of this first+ * input). `buildNapRewakePrompt` inserts the handoff between the two halves.+ */+function buildNapRewakePrompt(handoff: string): string {+ return (+ "You took a nap: you reset your own session, so prior conversation context " ++ "is gone. Before sleeping you left yourself this handoff —\n\n" ++ handoff.trim() ++ "\n\nThen read @todo.md, @memory.md, and your .context_timeline for anything " ++ "unfinished, and pull your inbox to catch up on unread messages before doing " ++ "anything else."+ );+}+export class AgentRouter {private readonly running = new Set<string>();/**@@ -443,6 +461,50 @@ export class AgentRouter {});}break;+ case "agent:nap":+ this.log.info("agent:nap received", { agentId: cmd.agentId, launchId: cmd.launchId });+ try {+ // Self-initiated twin of agent:reset — same enroll → forget-session →+ // fresh-rewake orchestration and `nap` timeline barrier (written by+ // resetSession's reset path). The only difference is the rewake+ // prompt carries the agent's own handoff. onBeforeAgent (enroll) must+ // run first, exactly as the reset arm does.+ await this.opts.onBeforeAgent?.(cmd.agentId);+ await this.opts.manager.resetSession(cmd.agentId, {+ runtimeConfig: cmd.config,+ launchId: cmd.launchId,+ rewakePrompt: buildNapRewakePrompt(cmd.handoff),+ barrierType: "nap",+ });+ this.running.add(cmd.agentId);+ this.scheduleReadyFrameResend();+ this.log.info("agent:nap ok", { agentId: cmd.agentId });+ } catch (err) {+ if (err instanceof UnknownRuntimeError) {+ const frame: SessionErrorFrame = {+ type: "session.error",+ code: "runtime_not_available",+ agentId: cmd.agentId,+ payload: { requested: err.requested ?? null, available: err.available },+ };+ await this.opts.channel.reportSessionError?.(frame);+ this.log.info("agent:nap error", { agentId: cmd.agentId, "error.code": "runtime_not_available" });+ return;+ }+ const code = classifyErrorCode(err);+ await this.opts.channel.reportWakeAck?.({+ agentId: cmd.agentId,+ launchId: cmd.launchId,+ status: "error",+ error: { code, message: err instanceof Error ? err.message : String(err) },+ });+ this.log.warn("agent:nap failed", {+ agentId: cmd.agentId,+ "error.code": code,+ err: err instanceof Error ? err.message : String(err),+ });+ }+ break;case "agent:model_switch":this.log.info("agent:model_switch received", { agentId: cmd.agentId, launchId: cmd.launchId });try {diff --git a/src/daemon/src/manager/managerRuntime.ts b/src/daemon/src/manager/managerRuntime.tsindex 1ae09fbf3..b8b9b3fba 100644--- a/src/daemon/src/manager/managerRuntime.ts+++ b/src/daemon/src/manager/managerRuntime.ts@@ -215,17 +215,17 @@ export interface TimelineRecorder {/** Latest session id for this agent (resume target), or null. */resumeSessionId(agentId: string, provider: string | null): string | null;/**- * Owner-triggered reset: the caller asked the daemon to forget this- * agent's prior session so the next spawn starts fresh. Recorder appends- * a `system: { type: "reset_session" }` row to the timeline — visible to- * both the resume walker (returns null on the barrier — every turn at or- * before it becomes invisible to `resumeSessionId`) and the agent's own- * history read (so the agent sees the reset in-line with turns). Kill- * happens BEFORE the barrier is written (see+ * Reset: the caller asked the daemon to forget this agent's prior session so+ * the next spawn starts fresh. Recorder appends a `system` barrier row —+ * `reset_session` (owner) or `nap` (agent self-reset, default+ * `reset_session`) — visible to both the resume walker (returns null on the+ * barrier — every turn at or before it becomes invisible to+ * `resumeSessionId`) and the agent's own history read (so the agent sees it+ * in-line with turns). Kill happens BEFORE the barrier is written (see* `AgentProcessManager.resetSession`), so no race — no `forgot_session_id`* needed. Safe to call on an unknown agentId.*/- forgetSession(agentId: string): void;+ forgetSession(agentId: string, barrierType?: "reset_session" | "nap"): void;}/** Max UTF-8 byte budget for `thinking` text in the audit log. */@@ -609,11 +609,11 @@ export class AgentProcessManager {* orchestration. Caller: `resetSession` (below), after `register` and* before `markResetting`.*/- forgetSession(agentId: string): void {+ forgetSession(agentId: string, barrierType: "reset_session" | "nap" = "reset_session"): void {this.resumeSessions.delete(agentId);this.liveSessions.delete(agentId);this.dispatch({ type: "reset_session", agentId });- this.opts.timeline?.forgetSession(agentId);+ this.opts.timeline?.forgetSession(agentId, barrierType);}/**@@ -664,10 +664,16 @@ export class AgentProcessManager {*/async resetSession(agentId: string,- opts: { runtimeConfig: RuntimeConfig; launchId: string; rewakePrompt: string },+ opts: {+ runtimeConfig: RuntimeConfig;+ launchId: string;+ rewakePrompt: string;+ /** Timeline barrier kind — `reset_session` (owner) or `nap` (self). Default reset_session. */+ barrierType?: "reset_session" | "nap";+ },): Promise<void> {this.register(agentId, { runtimeConfig: opts.runtimeConfig, launchId: opts.launchId });- this.forgetSession(agentId);+ this.forgetSession(agentId, opts.barrierType ?? "reset_session");this.markResetting(agentId);const status = this.state.agents[agentId]?.status;if (status === "idle") {diff --git a/src/daemon/src/timeline/recorder.ts b/src/daemon/src/timeline/recorder.tsindex 7f28cea58..42d37dbaf 100644--- a/src/daemon/src/timeline/recorder.ts+++ b/src/daemon/src/timeline/recorder.ts@@ -31,6 +31,7 @@ import {appendEntry,} from "./timeline.js";import type { Message } from "../server/contract.js";+import type { SystemEntryType } from "./types.js";/** Manager/daemon-facing recorder interface (structural, avoids a cyclic import). */@@ -44,14 +45,15 @@ export interface TimelineRecorderLike {/** Latest session id recorded for this agent (resume target), or null. */resumeSessionId(agentId: string, provider: string | null): string | null;/**- * Owner-triggered reset: append a `system: { type: "reset_session" }` row- * to the timeline. The resume walker treats that row as a barrier — every- * turn at or before it becomes invisible to `resumeSessionId` — and the- * agent's own history read (for recall) sees the reset in-line with turns.- * Also clears the in-memory session cache so a racing `appendEntryForAgent`- * can't bake the stale id into a fresh row.+ * Reset: append a `system` barrier row to the timeline (`reset_session` for+ * an owner reset, `nap` for an agent self-reset — default `reset_session`).+ * The resume walker treats either as a barrier — every turn at or before it+ * becomes invisible to `resumeSessionId` — and the agent's own history read+ * (for recall) sees it in-line with turns. Also clears the in-memory session+ * cache so a racing `appendEntryForAgent` can't bake the stale id into a+ * fresh row.*/- forgetSession(agentId: string): void;+ forgetSession(agentId: string, barrierType?: SystemEntryType): void;}export interface TimelineRecorderOptions {@@ -120,7 +122,7 @@ export function createTimelineRecorder(opts: TimelineRecorderOptions): TimelineRconst rows = readRecentEntries(dirFor(agentId), { now: now() });return findResumableSession(rows, provider ?? undefined);},- forgetSession(agentId) {+ forgetSession(agentId, barrierType = "reset_session") {const dir = dirFor(agentId);try {mkdirSync(dir, { recursive: true });@@ -134,7 +136,7 @@ export function createTimelineRecorder(opts: TimelineRecorderOptions): TimelineR// clock reads.sessionByAgent.delete(agentId);const stamp = now();- appendEntry(dir, createSystemEntry("reset_session", stamp.toISOString()), stamp);+ appendEntry(dir, createSystemEntry(barrierType, stamp.toISOString()), stamp);},};}diff --git a/src/daemon/src/timeline/timeline.test.ts b/src/daemon/src/timeline/timeline.test.tsindex 7cce442d7..c2e96019a 100644--- a/src/daemon/src/timeline/timeline.test.ts+++ b/src/daemon/src/timeline/timeline.test.ts@@ -153,6 +153,14 @@ describe("findResumableSession", () => {expect(findResumableSession(rows)).toBeNull();});+ it("stops on a nap barrier row and returns null (agent self-reset is a barrier too)", () => {+ const rows = [+ { ...createTimelineEntry({ messages: [], provider: "claude", sessionId: "s-old" }) },+ createSystemEntry("nap", "2026-06-25T12:00:00Z"),+ ];+ expect(findResumableSession(rows)).toBeNull();+ });+it("returns a session id from a row appended AFTER the barrier", () => {const rows = [{ ...createTimelineEntry({ messages: [], provider: "claude", sessionId: "s-old" }) },diff --git a/src/daemon/src/timeline/timeline.ts b/src/daemon/src/timeline/timeline.tsindex d4b8ea351..2b02ce9fe 100644--- a/src/daemon/src/timeline/timeline.ts+++ b/src/daemon/src/timeline/timeline.ts@@ -284,7 +284,9 @@ export function createSystemEntry(export function findResumableSession(rows: ContextTimelineEntry[], provider?: string): string | null {for (let i = rows.length - 1; i >= 0; i--) {const e = rows[i];- if (e.system?.type === "reset_session") return null;+ // Both reset_session (owner) and nap (agent self-reset) are resume+ // barriers — a fresh session was deliberately started at this point.+ if (e.system?.type === "reset_session" || e.system?.type === "nap") return null;if (!e.session_id) continue;if (provider && e.provider !== provider) continue;return e.session_id;diff --git a/src/daemon/src/timeline/types.ts b/src/daemon/src/timeline/types.tsindex eedff743c..2800e5c1d 100644--- a/src/daemon/src/timeline/types.ts+++ b/src/daemon/src/timeline/types.ts@@ -36,7 +36,10 @@ import type { Message } from "../server/contract.js";* `agent_responses` are empty. The system row is not mergeable with a* following turn (see `appendOrMergeEntry`).*/-export type SystemEntryType = "reset_session";+// `reset_session` — owner-triggered reset. `nap` — the agent reset its OWN+// session (see agent:nap). Both are resume barriers with identical walker+// semantics; the distinct type just records who initiated it.+export type SystemEntryType = "reset_session" | "nap";export interface SystemEntry {/** Event kind. Extend by adding to `SystemEntryType`. */diff --git a/src/shared/src/community-cli-contract.ts b/src/shared/src/community-cli-contract.tsindex 4029535d4..479ca7cba 100644--- a/src/shared/src/community-cli-contract.ts+++ b/src/shared/src/community-cli-contract.ts@@ -545,6 +545,13 @@ export interface ServerApi {pendingOutgoing: FriendCard[];pendingIncoming: FriendCard[];}>;+ /**+ * `alook nap` — the agent resets its own session, carrying a mandatory+ * `handoff` note to its reborn self. Self-scoped: the endpoint resolves the+ * bot from the runner key, so `agentId` isn't sent. Returns `{ napped }` on+ * delivery; throws (409) if the daemon is offline.+ */+ nap(req: { handoff: string }): Promise<{ napped: boolean }>;}/* ------------------------------------------------------------------ */@@ -615,6 +622,15 @@ export type HostCommand =* synthetic rewake — see `AgentProcessManager.resetSession`.*/| { type: "agent:reset"; agentId: AgentId; config: RuntimeConfig; launchId: string }+ /**+ * Agent-self-initiated reset ("nap"). Mechanically the twin of `agent:reset`+ * — same register + `nap` timeline barrier + kill + fresh-session rewake —+ * but self-requested and carrying a mandatory `handoff`: the agent's own+ * note to its reborn self, spliced into the nap rewake prompt (NOT a message+ * to anyone, NOT a persisted file). See `AgentProcessManager.resetSession`+ * and the `agent:nap` case in `agentRouter`.+ */+ | { type: "agent:nap"; agentId: AgentId; config: RuntimeConfig; launchId: string; handoff: string }/*** Owner-triggered model switch. The twin of `agent:reset` — same* stop-and-immediate-rewake orchestration and boundary conditions — but itdiff --git a/src/shared/src/db/queries/community/bot-audit-log.ts b/src/shared/src/db/queries/community/bot-audit-log.tsindex 34594eb5f..78ee5bc19 100644--- a/src/shared/src/db/queries/community/bot-audit-log.ts+++ b/src/shared/src/db/queries/community/bot-audit-log.ts@@ -30,7 +30,7 @@ export type BotActivityEventInput = {botId: string;sessionId?: string | null;launchId?: string | null;- kind: "cli_invocation" | "tool_call" | "thinking" | "wake_trigger" | "session_reset" | "model_changed" | "error";+ kind: "cli_invocation" | "tool_call" | "thinking" | "wake_trigger" | "session_reset" | "nap" | "model_changed" | "error";payload: string;};@@ -220,6 +220,27 @@ export async function insertBotAuditSessionReset(});}+/**+ * Nap audit write — the agent reset ITS OWN session via `alook nap`. Actor is+ * the bot itself (self-initiated), so no `actorId`. Payload is intentionally+ * empty — the fact of the nap is the signal; the handoff lives in the rewake+ * prompt, never persisted. Written ONLY after the daemon confirmed delivery of+ * the `agent:nap` frame (`sent > 0`) — an undelivered nap writes no row,+ * mirroring reset/model-switch audit-on-delivery.+ */+export async function insertBotAuditNap(+ db: Database,+ data: { botId: string }+): Promise<{ id: string; createdAt: string } | null> {+ return insertBotActivityEventAndPrune(db, {+ botId: data.botId,+ sessionId: null,+ launchId: null,+ kind: "nap",+ payload: JSON.stringify({}),+ });+}+/*** Model-changed audit write — the owner switched a bot's LLM model in* `/c/me/bots`. Actor is the owner (owner-scoped by construction on the APIdiff --git a/src/shared/src/index.ts b/src/shared/src/index.tsindex a4db78b31..206d45607 100644--- a/src/shared/src/index.ts+++ b/src/shared/src/index.ts@@ -274,6 +274,7 @@ export {CommunityAgentListMembersRequestSchema,CommunityAgentChannelMemberRequestSchema,CommunityAgentJoinServerRequestSchema,+ CommunityAgentNapRequestSchema,CommunityAgentReactAddRequestSchema,CommunityAgentFriendRequestSchema,CommunityAgentListFriendsSchema,diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.tsindex 7a7682c2b..d12f015ea 100644--- a/src/shared/src/schemas.ts+++ b/src/shared/src/schemas.ts@@ -1214,6 +1214,17 @@ export type CommunityAgentJoinServerRequest = z.infer<typeof CommunityAgentJoinServerRequestSchema>;+// `alook nap` — the agent resets its own session with a mandatory handoff (its+// note to its reborn self, spliced into the rewake prompt). `.trim().min(1)`+// enforces the handoff is real, not whitespace — the mechanical half of the+// nap gate.+export const CommunityAgentNapRequestSchema = z.object({+ handoff: z.string().trim().min(1),+});+export type CommunityAgentNapRequest = z.infer<+ typeof CommunityAgentNapRequestSchema+>;+export const CommunityAgentReactAddRequestSchema = z.object({channel: z.string().min(1),seq: CommunityAgentPositiveSeqSchema,diff --git a/src/web/src/app/api/community/agent/nap/route.ts b/src/web/src/app/api/community/agent/nap/route.tsnew file mode 100644index 000000000..95c959740--- /dev/null+++ b/src/web/src/app/api/community/agent/nap/route.ts@@ -0,0 +1,76 @@+import { NextResponse, type NextRequest } from "next/server"+import { nanoid } from "nanoid"+import {+ queries,+ makeRuntimeConfig,+ resolveModelConfig,+ formatHandle,+ CommunityAgentNapRequestSchema,+} from "@alook/shared"+import { getDb } from "@/lib/db"+import { withAgentRunnerAuth } from "@/lib/middleware/community-agent-runner-auth"+import { pushAgentNapToMachine } from "@/lib/community/bot-push"++/**+ * POST /api/community/agent/nap — `alook nap --handoff <file>|--text <s>`.+ *+ * Agent-self-initiated session reset. The self-serve twin of the owner+ * `reset-session` route: build the bot's RuntimeConfig → push `agent:nap`+ * (carrying the mandatory handoff) to the bot's OWN machine → on delivery+ * (`sent > 0`) write the `nap` audit row. If the daemon is offline+ * (`sent === 0`) return 409 and write NO audit row — the audit signals a real+ * nap landed at the daemon, not a request. Notifies no one: a nap is the+ * agent's private self-state change.+ *+ * Auth is `withAgentRunnerAuth` (runner key), so the bot acts on ITSELF —+ * `ctx.botUserId`/`ctx.machineId` come from the authenticated runner, not a+ * request field, so an agent can only nap itself.+ */+export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {+ 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 = CommunityAgentNapRequestSchema.safeParse(raw)+ if (!parsed.success) {+ return NextResponse.json({ error: "handoff is required", details: parsed.error.flatten() }, { status: 400 })+ }+ const handoff = parsed.data.handoff++ // Resolve the bot's own wake context (runtime + model) to build the config+ // the daemon needs to respawn a fresh session. `botUserId` is the caller.+ const wakeCtx = await queries.communityBot.getBotWakeContext(db, ctx.botUserId)+ if (wakeCtx.state !== "ready") {+ return NextResponse.json({ error: wakeCtx.state }, { status: 409 })+ }++ const config = makeRuntimeConfig({+ runtime: wakeCtx.runtime,+ model: resolveModelConfig(wakeCtx.runtime, wakeCtx.modelName),+ agentName: wakeCtx.name,+ agentHandle: `@${formatHandle(wakeCtx.name, wakeCtx.discriminator)}`,+ })+ const launchId = nanoid()++ const { sent } = await pushAgentNapToMachine(ctx.env, ctx.machineId, {+ agentId: ctx.botUserId,+ config,+ launchId,+ handoff,+ })+ if (sent === 0) {+ return NextResponse.json(+ { error: "daemon offline — cannot nap right now" },+ { status: 409 },+ )+ }++ // Audit on delivery only (mirrors reset/model-switch). No notification.+ await queries.communityBotAuditLog.insertBotAuditNap(db, { botId: ctx.botUserId })++ return NextResponse.json({ napped: true })+})diff --git a/src/web/src/lib/community/bot-push.ts b/src/web/src/lib/community/bot-push.tsindex e6144b81c..9c8489f2f 100644--- a/src/web/src/lib/community/bot-push.ts+++ b/src/web/src/lib/community/bot-push.ts@@ -104,6 +104,46 @@ export async function pushAgentResetToMachine(}}+/**+ * Push an agent-self-initiated `agent:nap` to the bot's OWN machine over WS.+ *+ * Twin of `pushAgentResetToMachine` — same narrow allowlist plus the mandatory+ * `handoff` string (the agent's note to its reborn self, spliced into the nap+ * rewake prompt daemon-side). Returns `{ sent }`; `sent === 0` means the daemon+ * isn't connected and the caller translates it into a 409 (and writes NO audit+ * row — the audit signals a real nap landed, not a request).+ */+export async function pushAgentNapToMachine(+ env: Env,+ machineId: string,+ args: { agentId: string; config: RuntimeConfig; launchId: string; handoff: string },+): Promise<{ sent: number }> {+ const path = `/community-machine/by-id/${encodeURIComponent(machineId)}/forward-agent-nap`+ const body = JSON.stringify({+ agentId: args.agentId,+ config: args.config,+ launchId: args.launchId,+ handoff: args.handoff,+ })+ try {+ const res = await wsDoFetch(+ env,+ path,+ { method: "POST", headers: { "Content-Type": "application/json" }, body },+ { label: machineId, type: "agent:nap" },+ )+ if (!res.ok) {+ log.warn("agent:nap push non-ok", { machineId, status: res.status })+ return { sent: 0 }+ }+ const data = (await res.json()) as { sent?: number }+ return { sent: data.sent ?? 0 }+ } catch (err) {+ log.warn("agent:nap push threw", { machineId, err: String(err) })+ return { sent: 0 }+ }+}+/*** Push an owner-triggered `agent:model_switch` to the machine's daemon over WS.*diff --git a/src/ws-do/src/index.ts b/src/ws-do/src/index.tsindex 1f1b03b0b..7b17f42d1 100644--- a/src/ws-do/src/index.ts+++ b/src/ws-do/src/index.ts@@ -490,6 +490,94 @@ export default {return Response.json({ sent: delivered })}+ // POST /community-machine/by-id/<machineId>/forward-agent-nap — agent+ // self-initiated `agent:nap` push. Twin of /forward-agent-reset but the+ // allowlist additionally carries the mandatory `handoff` string (the+ // agent's note to its reborn self, spliced into the rewake prompt). Same+ // doName resolution + `/push` fan-out + `{sent}` aggregation. Callers must+ // use `pushAgentNapToMachine`.+ const forwardAgentNap = url.pathname.match(/^\/community-machine\/by-id\/([^/]+)\/forward-agent-nap$/)+ if (forwardAgentNap && request.method === "POST") {+ const machineId = decodeURIComponent(forwardAgentNap[1])+ const reqLog = log.child({ traceId, machineId })+ reqLog.debug("forwarding agent:nap to machine")++ let payload: unknown+ try {+ payload = await request.json()+ } catch {+ return Response.json({ error: "invalid payload" }, { status: 400 })+ }+ if (!payload || typeof payload !== "object") {+ return Response.json({ error: "invalid payload" }, { status: 400 })+ }+ const raw = payload as Record<string, unknown>+ const allowedKeys = new Set(["agentId", "config", "launchId", "handoff"])+ for (const key of Object.keys(raw)) {+ if (!allowedKeys.has(key)) {+ return Response.json({ error: "invalid payload" }, { status: 400 })+ }+ }+ const { agentId, config, launchId, handoff } = raw+ if (typeof agentId !== "string" || agentId.length === 0) {+ return Response.json({ error: "invalid payload" }, { status: 400 })+ }+ if (typeof launchId !== "string" || launchId.length === 0) {+ return Response.json({ error: "invalid payload" }, { status: 400 })+ }+ if (!config || typeof config !== "object") {+ return Response.json({ error: "invalid payload" }, { status: 400 })+ }+ if (typeof handoff !== "string" || handoff.trim().length === 0) {+ return Response.json({ error: "invalid payload" }, { status: 400 })+ }++ let doNames: string[] = []+ try {+ const shared = await import("@alook/shared")+ const db = shared.createDb((env as unknown as { DB: D1Database }).DB)+ doNames = await queries.communityMachine.getActiveDoNamesForMachine(db, machineId)+ } catch (err) {+ reqLog.error("failed to resolve machine doNames for agent nap", { err })+ return Response.json({ error: "failed to resolve machine" }, { status: 503 })+ }+ if (doNames.length === 0) {+ return Response.json({ sent: 0 })+ }+ const frame = JSON.stringify({ type: "agent:nap", agentId, config, launchId, handoff })+ let delivered = 0+ let transientFailure = false+ for (const dn of doNames) {+ const doId = env.WS_DO.idFromName("community-machine:" + dn)+ const stub = env.WS_DO.get(doId)+ try {+ const res = await stub.fetch(+ new Request("http://internal/push", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: frame,+ }),+ )+ if (!res.ok) {+ transientFailure = true+ continue+ }+ const data = (await res.json()) as { sent?: unknown }+ if (typeof data.sent !== "number" || !Number.isFinite(data.sent) || data.sent < 0) {+ transientFailure = true+ continue+ }+ delivered += data.sent+ } catch {+ transientFailure = true+ }+ }+ if (delivered === 0 && transientFailure) {+ return Response.json({ error: "failed to forward agent nap" }, { status: 503 })+ }+ return Response.json({ sent: delivered })+ }+// POST /community-machine/<doName>/force-close — disconnect a daemon by// its DO-name suffix (first 32 hex of the credential hash). Callers look// the suffix up from `community_machine_credential.do_name`.