Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

community(reset/nap): re-home audit + awake-time to daemon completion signal

Guse4ce064473c0
diff --git a/src/daemon/src/manager/agentRouter.ts b/src/daemon/src/manager/agentRouter.ts
index edf350231..f03ebc029 100644
--- a/src/daemon/src/manager/agentRouter.ts
+++ b/src/daemon/src/manager/agentRouter.ts
@@ -345,6 +345,7 @@ export class AgentRouter {
type: "session.error",
code: "runtime_not_available",
agentId,
+ launchId,
payload: { requested: err.requested ?? null, available: err.available },
};
await this.opts.channel.reportSessionError?.(frame);
@@ -453,6 +454,7 @@ export class AgentRouter {
type: "session.error",
code: "runtime_not_available",
agentId: cmd.agentId,
+ launchId: cmd.launchId,
payload: {
requested: err.requested ?? null,
available: err.available,
diff --git a/src/shared/src/community-cli-contract.ts b/src/shared/src/community-cli-contract.ts
index 0123c122c..2469673dc 100644
--- a/src/shared/src/community-cli-contract.ts
+++ b/src/shared/src/community-cli-contract.ts
@@ -782,7 +782,14 @@ export type BotAuditEventPayload =
message: string;
model: string | null;
};
- };
+ }
+ // Reset/nap completion events, emitted upward by the DO when the reborn
+ // agent's `agent_session` frame lands (not at dispatch). `trigger`
+ // distinguishes the entry-point so my-bots can read "was reset" vs "slept";
+ // `actorId` never travels — it is the bot owner, resolved server-side at the
+ // landing (reset is owner-only). See plans/reset-nap-completion-rehome.md.
+ | { kind: "session_reset"; payload: { trigger: "single" | "reset_all" } }
+ | { kind: "nap"; payload: { trigger: "nap" } };
export interface HostBotAuditEventFrame {
type: "bot_audit_event";
@@ -800,6 +807,7 @@ export interface SessionErrorFrame {
type: "session.error";
code: "runtime_not_available";
agentId?: AgentId;
+ launchId?: string;
payload?: Record<string, unknown>;
}
diff --git a/src/shared/src/community-ws-events.ts b/src/shared/src/community-ws-events.ts
index 1b7568b97..b32559d15 100644
--- a/src/shared/src/community-ws-events.ts
+++ b/src/shared/src/community-ws-events.ts
@@ -529,7 +529,7 @@ export type CommunityBotAuditEvent = {
type: "community:bot.audit_event"
botId: string
id: string
- 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: unknown
sessionId?: string | null
launchId?: string | null
diff --git a/src/shared/src/db/queries/community/bot-audit-log.ts b/src/shared/src/db/queries/community/bot-audit-log.ts
index 84aa2fe1d..b5592e3fa 100644
--- a/src/shared/src/db/queries/community/bot-audit-log.ts
+++ b/src/shared/src/db/queries/community/bot-audit-log.ts
@@ -230,35 +230,36 @@ export async function insertBotAuditWakeTrigger(
*/
export async function insertBotAuditSessionReset(
db: Database,
- data: { botId: string; actorId: string }
+ data: { botId: string; launchId: string; trigger: "single" | "reset_all" }
): Promise<{ id: string; createdAt: string } | null> {
return insertBotActivityEventAndPrune(db, {
botId: data.botId,
sessionId: null,
- launchId: null,
+ launchId: data.launchId,
kind: "session_reset",
- payload: JSON.stringify({}),
+ payload: JSON.stringify({ trigger: data.trigger }),
});
}
/**
* 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.
+ * the bot itself (self-initiated), so no `actorId`; `trigger` is the constant
+ * `"nap"` so my-bots reads "slept" vs a "was reset". Written when the reborn
+ * agent's `agent_session` lands (completion), NOT at dispatch — so a nap that
+ * dispatches but whose cold-start fails writes no row (the DO evicts the
+ * pending map entry on the failure frame instead). See
+ * plans/reset-nap-completion-rehome.md.
*/
export async function insertBotAuditNap(
db: Database,
- data: { botId: string }
+ data: { botId: string; launchId: string }
): Promise<{ id: string; createdAt: string } | null> {
return insertBotActivityEventAndPrune(db, {
botId: data.botId,
sessionId: null,
- launchId: null,
+ launchId: data.launchId,
kind: "nap",
- payload: JSON.stringify({}),
+ payload: JSON.stringify({ trigger: "nap" }),
});
}
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index f6fca9de7..66732216f 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -263,6 +263,8 @@ export {
AgentActivityMessageSchema,
AgentTypingMessageSchema,
AgentTypingStopMessageSchema,
+ AgentSessionMessageSchema,
+ AgentWakeAckMessageSchema,
COMMUNITY_RUNTIME_ID_MAX,
COMMUNITY_RUNTIME_VERSION_MAX,
COMMUNITY_RUNTIME_LIST_MAX,
@@ -293,6 +295,7 @@ export {
AuditLogWakeTriggerPayloadSchema,
AuditLogModelChangedPayloadSchema,
AuditLogSessionResetPayloadSchema,
+ AuditLogNapPayloadSchema,
AuditLogErrorPayloadSchema,
HostBotAuditEventFrameSchema,
} from "./schemas";
@@ -357,6 +360,8 @@ export type {
AgentActivityMessage,
AgentTypingMessage,
AgentTypingStopMessage,
+ AgentSessionMessage,
+ AgentWakeAckMessage,
CommunityBotCreateRequest,
CommunityBotPatchRequest,
CommunityBotAddToServerRequest,
diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.ts
index 3a2c57dc4..0a6db95bf 100644
--- a/src/shared/src/schemas.ts
+++ b/src/shared/src/schemas.ts
@@ -925,6 +925,7 @@ export const SessionErrorFrameSchema = z.object({
type: z.literal("session.error"),
code: z.enum(["runtime_not_available"]),
agentId: z.string().optional(),
+ launchId: z.string().optional(),
payload: z.record(z.string(), z.unknown()).optional(),
});
export type SessionErrorFrame = z.infer<typeof SessionErrorFrameSchema>;
@@ -962,6 +963,39 @@ export const AgentTypingStopMessageSchema = z.object({
});
export type AgentTypingStopMessage = z.infer<typeof AgentTypingStopMessageSchema>;
+/**
+ * `agent_session` frame — daemon → server. Emitted per live agent once it is
+ * really up and has a session (reborn-ready), carrying the `launchId` of the
+ * launch that produced it. This is the completion signal the reset/nap
+ * audit+awake re-home hangs on: the DO correlates `launchId` back to the
+ * pending (launchId → trigger) map it recorded at dispatch, writes the audit +
+ * awake stamp exactly once, then drops the map entry. See
+ * plans/reset-nap-completion-rehome.md.
+ */
+export const AgentSessionMessageSchema = z.object({
+ type: z.literal("agent_session"),
+ agentId: z.string().min(1),
+ sessionId: z.string().min(1),
+ launchId: z.string().min(1),
+});
+export type AgentSessionMessage = z.infer<typeof AgentSessionMessageSchema>;
+
+/**
+ * `agent_wake_ack` frame — daemon → server. Acknowledges a wake/reset/nap
+ * command. `status: "error"` on the non-runtime failure branch of
+ * `runRestartCommand` (enroll fail, spawn threw) — used by the reset/nap
+ * re-home to evict the pending attribution map entry on a cold-start failure
+ * (the twin branch, `runtime_not_available`, arrives as `session.error`).
+ */
+export const AgentWakeAckMessageSchema = z.object({
+ type: z.literal("agent_wake_ack"),
+ agentId: z.string().min(1),
+ launchId: z.string().min(1),
+ status: z.enum(["ok", "error"]),
+ error: z.object({ code: z.string().optional(), message: z.string().optional() }).optional(),
+});
+export type AgentWakeAckMessage = z.infer<typeof AgentWakeAckMessageSchema>;
+
export const CommunityPairTokenResponseSchema = z.object({
tokenId: z.string(),
@@ -1331,9 +1365,30 @@ export const AuditLogWakeTriggerPayloadSchema = z.object({
});
export type AuditLogWakeTriggerPayload = z.infer<typeof AuditLogWakeTriggerPayloadSchema>;
-export const AuditLogSessionResetPayloadSchema = z.object({});
+/**
+ * `session_reset` payload — an owner-triggered reset that has actually
+ * completed (written when the reborn agent's `agent_session` lands, not at
+ * dispatch). `trigger` distinguishes a single-bot reset from a machine-wide
+ * "reset all" so my-bots can label them. No `actorId`: reset is owner-only, so
+ * the actor is the bot owner, resolved server-side at the landing — it never
+ * travels on the wire. (Rows written before this shape carried `{}` and parse
+ * to null, which the lenient client parser tolerates.)
+ */
+export const AuditLogSessionResetPayloadSchema = z.object({
+ trigger: z.enum(["single", "reset_all"]),
+});
export type AuditLogSessionResetPayload = z.infer<typeof AuditLogSessionResetPayloadSchema>;
+/**
+ * `nap` payload — the agent reset ITS OWN session via `alook nap`. Twin of
+ * `session_reset` but self-initiated, so `trigger` is always `"nap"` and there
+ * is no actor. Written at the same completion landing.
+ */
+export const AuditLogNapPayloadSchema = z.object({
+ trigger: z.literal("nap"),
+});
+export type AuditLogNapPayload = z.infer<typeof AuditLogNapPayloadSchema>;
+
/**
* `model_changed` payload — the owner switched a bot's LLM model. `from`/`to`
* are the full stored ids; `null` means the runtime's default. Written only
@@ -1372,6 +1427,7 @@ export const BotAuditEventSchema = z.discriminatedUnion("kind", [
z.object({ kind: z.literal("thinking"), payload: AuditLogThinkingPayloadSchema }),
z.object({ kind: z.literal("wake_trigger"), payload: AuditLogWakeTriggerPayloadSchema }),
z.object({ kind: z.literal("session_reset"), payload: AuditLogSessionResetPayloadSchema }),
+ z.object({ kind: z.literal("nap"), payload: AuditLogNapPayloadSchema }),
z.object({ kind: z.literal("model_changed"), payload: AuditLogModelChangedPayloadSchema }),
z.object({ kind: z.literal("error"), payload: AuditLogErrorPayloadSchema }),
]);
@@ -1383,6 +1439,7 @@ export const BotAuditEventKindSchema = z.enum([
"thinking",
"wake_trigger",
"session_reset",
+ "nap",
"model_changed",
"error",
]);
diff --git a/src/web/src/app/api/community/bots/[id]/reset-session/route.test.ts b/src/web/src/app/api/community/bots/[id]/reset-session/route.test.ts
index dda4e67a0..bfe10599c 100644
--- a/src/web/src/app/api/community/bots/[id]/reset-session/route.test.ts
+++ b/src/web/src/app/api/community/bots/[id]/reset-session/route.test.ts
@@ -130,14 +130,9 @@ describe("POST /api/community/bots/[id]/reset-session", () => {
expect(mockBroadcastToUser).not.toHaveBeenCalled()
})
- it("owner + bound + daemon online (sent:1) → 200 with exactly one audit row + one broadcast", async () => {
+ it("owner + bound + daemon online (sent:1) → 200 dispatch-only; audit/awake/broadcast re-homed to daemon completion, NOT written here", async () => {
seedOwnedAndBound()
mockPushAgentResetToMachine.mockResolvedValue({ sent: 1 })
- mockInsertBotAuditSessionReset.mockResolvedValue({
- id: "evt_1",
- createdAt: "2026-07-24T09:00:00.000Z",
- })
- mockBroadcastToUser.mockResolvedValue(undefined)
const res = await POST(req(), ctx)
expect(res.status).toBe(200)
@@ -152,36 +147,19 @@ describe("POST /api/community/bots/[id]/reset-session", () => {
expect(args.launchId.length).toBeGreaterThan(0)
expect(args.config).toBeDefined()
- expect(mockInsertBotAuditSessionReset).toHaveBeenCalledTimes(1)
- expect(mockInsertBotAuditSessionReset).toHaveBeenCalledWith(expect.anything(), {
- botId: "b1",
- actorId: "owner_1",
- })
- // Single-source invariant: lastRefreshContextAt is stamped exactly once, in
- // lockstep with the audit row, reusing that row's OWN createdAt — so the
- // my-bots "last refreshed" timestamp can never drift from the audit event.
- expect(mockTouchBotRefreshContext).toHaveBeenCalledTimes(1)
- expect(mockTouchBotRefreshContext).toHaveBeenCalledWith(
- expect.anything(),
- "b1",
- "2026-07-24T09:00:00.000Z",
- )
- expect(mockBroadcastToUser).toHaveBeenCalledTimes(1)
- expect(mockBroadcastToUser).toHaveBeenCalledWith(
- "owner_1",
- expect.objectContaining({
- type: "community:bot.audit_event",
- kind: "session_reset",
- botId: "b1",
- }),
- )
+ // The `session_reset` audit row + lastRefreshContextAt stamp + broadcast are
+ // re-homed to the daemon completion signal (agent_session frame at
+ // reborn-ready), so the record reflects "the reset actually completed," not
+ // "the command was dispatched." The route must NOT write any of them.
+ // See plans/reset-nap-completion-rehome.md.
+ expect(mockInsertBotAuditSessionReset).not.toHaveBeenCalled()
+ expect(mockTouchBotRefreshContext).not.toHaveBeenCalled()
+ expect(mockBroadcastToUser).not.toHaveBeenCalled()
})
it("regression: reset sends the bot's configured model in config.model (not default)", async () => {
seedOwnedAndBound()
mockPushAgentResetToMachine.mockResolvedValue({ sent: 1 })
- mockInsertBotAuditSessionReset.mockResolvedValue({ id: "evt_1", createdAt: "2026-07-26T00:00:00.000Z" })
- mockBroadcastToUser.mockResolvedValue(undefined)
const res = await POST(req(), ctx)
expect(res.status).toBe(200)
diff --git a/src/web/src/app/api/community/bots/[id]/reset-session/route.ts b/src/web/src/app/api/community/bots/[id]/reset-session/route.ts
index 140863a2e..e65e3ed53 100644
--- a/src/web/src/app/api/community/bots/[id]/reset-session/route.ts
+++ b/src/web/src/app/api/community/bots/[id]/reset-session/route.ts
@@ -1,19 +1,21 @@
import { nanoid } from "nanoid"
-import { queries, makeRuntimeConfig, resolveModelConfig, formatHandle, WS_EVENTS } from "@alook/shared"
+import { queries, makeRuntimeConfig, resolveModelConfig, formatHandle } from "@alook/shared"
import { getDb } from "@/lib/db"
import { withAuth } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
-import { broadcastToUser } from "@/lib/broadcast"
import { pushAgentResetToMachine } from "@/lib/community/bot-push"
/**
* Owner-triggered synchronous session reset.
*
* Flow: owner-scoped bot lookup → build RuntimeConfig → push `agent:reset`
- * over WS to the bot's daemon → if delivered (`sent > 0`), write the
- * `session_reset` audit row and broadcast it. If the daemon is offline
- * (`sent === 0`), return 409 and NEVER touch the audit log — the audit row
- * signals a real reset landed at the daemon, not a click.
+ * over WS to the bot's daemon → if delivered (`sent > 0`), return. If the
+ * daemon is offline (`sent === 0`), return 409.
+ *
+ * The `session_reset` audit row + awake-time stamp + broadcast are NOT written
+ * here: they are re-homed to the daemon completion signal (the `agent_session`
+ * frame at reborn-ready), so the record reflects "the reset actually completed"
+ * rather than "the command was dispatched." See plans/reset-nap-completion-rehome.md.
*/
export const POST = withAuth(async (_req, ctx) => {
const id = ctx.params?.id as string
@@ -44,30 +46,5 @@ export const POST = withAuth(async (_req, ctx) => {
return writeError("bot is offline — bring it online before resetting", 409)
}
- const inserted = await queries.communityBotAuditLog.insertBotAuditSessionReset(db, {
- botId: id,
- actorId: ctx.userId,
- })
- if (inserted) {
- // Stamp lastRefreshContextAt at the SAME chokepoint (single write point),
- // in lockstep with the audit row landing — the my-bots "last refreshed"
- // indicator can never drift from the session_reset audit event.
- await queries.communityBot.touchBotRefreshContext(db, id, inserted.createdAt)
- try {
- await broadcastToUser(ctx.userId, {
- type: WS_EVENTS.BOT_AUDIT_EVENT,
- botId: id,
- id: inserted.id,
- kind: "session_reset",
- payload: {},
- sessionId: null,
- launchId: null,
- createdAt: inserted.createdAt,
- })
- } catch {
- // Best-effort — D1 row is authoritative.
- }
- }
-
return writeJSON({ ok: true })
})
diff --git a/src/web/src/app/api/community/nap/route.test.ts b/src/web/src/app/api/community/nap/route.test.ts
index 90598fd76..9113d3375 100644
--- a/src/web/src/app/api/community/nap/route.test.ts
+++ b/src/web/src/app/api/community/nap/route.test.ts
@@ -106,44 +106,27 @@ describe("POST /api/community/nap", () => {
expect(mockTouchBotRefreshContext).not.toHaveBeenCalled()
})
- it("daemon online (sent:1) → 200, writes one nap audit row and stamps lastRefreshContextAt once with the audit row's OWN createdAt", async () => {
+ it("daemon online (sent:1) → 200 dispatch-only; nap audit + awake stamp re-homed to daemon completion, NOT written here", async () => {
mockGetBotWakeContext.mockResolvedValue(READY_CTX)
mockPushAgentNapToMachine.mockResolvedValue({ sent: 1 })
- mockInsertBotAuditNap.mockResolvedValue({
- id: "evt_1",
- createdAt: "2026-07-30T09:00:00.000Z",
- })
const res = await POST(req())
expect(res.status).toBe(200)
const body = (await res.json()) as { napped: boolean }
expect(body.napped).toBe(true)
- expect(mockInsertBotAuditNap).toHaveBeenCalledTimes(1)
- expect(mockInsertBotAuditNap).toHaveBeenCalledWith(expect.anything(), { botId: "b1" })
-
- // Single-source invariant (mirror of reset-session): lastRefreshContextAt is
- // stamped exactly once, in lockstep with the nap audit row, reusing that
- // row's OWN createdAt — so the my-bots "last refreshed" indicator can never
- // drift from the nap audit event. (Ported onto the moved /community/nap route
- // during the rebase — the /agent/nap this feature originally patched is gone.)
- expect(mockTouchBotRefreshContext).toHaveBeenCalledTimes(1)
- expect(mockTouchBotRefreshContext).toHaveBeenCalledWith(
- expect.anything(),
- "b1",
- "2026-07-30T09:00:00.000Z",
- )
- })
-
- it("audit insert returns null (not inserted) → does NOT stamp lastRefreshContextAt", async () => {
- mockGetBotWakeContext.mockResolvedValue(READY_CTX)
- mockPushAgentNapToMachine.mockResolvedValue({ sent: 1 })
- mockInsertBotAuditNap.mockResolvedValue(null)
-
- const res = await POST(req())
- expect(res.status).toBe(200)
- // inserted guard: no audit row landed → no stamp (touch rides the audit row).
- expect(mockInsertBotAuditNap).toHaveBeenCalledTimes(1)
+ expect(mockPushAgentNapToMachine).toHaveBeenCalledTimes(1)
+ const [, machineId, args] = mockPushAgentNapToMachine.mock.calls[0]!
+ expect(machineId).toBe("mac_1")
+ expect(args).toMatchObject({ agentId: "b1", handoff: "note to future self" })
+ expect(typeof args.launchId).toBe("string")
+ expect(args.launchId.length).toBeGreaterThan(0)
+
+ // The `nap` audit row + lastRefreshContextAt stamp are re-homed to the daemon
+ // completion signal (agent_session frame at reborn-ready), so the record
+ // reflects "the nap actually completed," not "the command was dispatched."
+ // The route must NOT write either. See plans/reset-nap-completion-rehome.md.
+ expect(mockInsertBotAuditNap).not.toHaveBeenCalled()
expect(mockTouchBotRefreshContext).not.toHaveBeenCalled()
})
})
diff --git a/src/web/src/app/api/community/nap/route.ts b/src/web/src/app/api/community/nap/route.ts
index 4d606e8e9..6015729cd 100644
--- a/src/web/src/app/api/community/nap/route.ts
+++ b/src/web/src/app/api/community/nap/route.ts
@@ -75,16 +75,10 @@ export const POST = withCommunityActor(async (req: NextRequest, ctx) => {
)
}
- // Audit on delivery only (mirrors reset/model-switch). No notification.
- // Stamp lastRefreshContextAt at the SAME chokepoint (single write point),
- // reusing the audit row's own createdAt so the my-bots "last refreshed"
- // indicator can never drift from the nap audit event. (Ported from the
- // incoming my-bots refresh feature onto this moved /community/nap route
- // during the rebase — the /agent/nap it originally patched was deleted here.)
- const inserted = await queries.communityBotAuditLog.insertBotAuditNap(db, { botId: botUserId })
- if (inserted) {
- await queries.communityBot.touchBotRefreshContext(db, botUserId, inserted.createdAt)
- }
+ // The `nap` audit row + awake-time stamp are NOT written here: they are
+ // re-homed to the daemon completion signal (the `agent_session` frame at
+ // reborn-ready), so the record reflects "the nap actually completed" rather
+ // than "the command was dispatched." See plans/reset-nap-completion-rehome.md.
return NextResponse.json({ napped: true })
})
diff --git a/src/web/src/components/community/bots/bot-activity-row.tsx b/src/web/src/components/community/bots/bot-activity-row.tsx
index 439d500b0..40ac0c015 100644
--- a/src/web/src/components/community/bots/bot-activity-row.tsx
+++ b/src/web/src/components/community/bots/bot-activity-row.tsx
@@ -57,6 +57,7 @@ function kindMeta(kind: AuditKind): { label: string; tone: string } {
if (kind === "tool_call") return { label: "tool", tone: "text-muted-foreground" }
if (kind === "wake_trigger") return { label: "wake", tone: "text-foreground/70" }
if (kind === "session_reset") return { label: "reset", tone: "text-foreground/70" }
+ if (kind === "nap") return { label: "nap", tone: "text-foreground/70" }
if (kind === "model_changed") return { label: "model", tone: "text-foreground/70" }
if (kind === "error") return { label: "err", tone: "text-destructive" }
return { label: "think", tone: "text-muted-foreground/70" }
@@ -112,6 +113,19 @@ function RowBody({
</div>
)
}
+ if (event.kind === "nap") {
+ return (
+ <div
+ data-testid="bot-activity-event-nap"
+ className="truncate font-mono text-[13px] text-foreground"
+ >
+ <span>Reset its own session</span>{" "}
+ <span className="text-muted-foreground">
+ — the bot napped and will start fresh on its next message.
+ </span>
+ </div>
+ )
+ }
if (event.kind === "model_changed") {
const p = event.payload as { from?: string | null; to?: string | null } | null
// Developer-facing audit surface — print the RAW stored ids (no card-style
diff --git a/src/web/src/hooks/community/use-bot-audit-log.ts b/src/web/src/hooks/community/use-bot-audit-log.ts
index f3e7c1e5a..515e48ef2 100644
--- a/src/web/src/hooks/community/use-bot-audit-log.ts
+++ b/src/web/src/hooks/community/use-bot-audit-log.ts
@@ -10,7 +10,7 @@ import { apiFetch } from "@/lib/api/client"
import { communityKeys } from "@/lib/query-keys"
import { useBotAuditEventsForBot } from "@/stores/community/ws"
-export type AuditKind = "cli_invocation" | "tool_call" | "thinking" | "wake_trigger" | "session_reset" | "model_changed" | "error"
+export type AuditKind = "cli_invocation" | "tool_call" | "thinking" | "wake_trigger" | "session_reset" | "nap" | "model_changed" | "error"
export type AuditEvent = {
id: string
diff --git a/src/web/src/lib/community/audit-log-payload.test.ts b/src/web/src/lib/community/audit-log-payload.test.ts
index 3f5d5182c..150b900a4 100644
--- a/src/web/src/lib/community/audit-log-payload.test.ts
+++ b/src/web/src/lib/community/audit-log-payload.test.ts
@@ -55,8 +55,31 @@ describe("parseAuditLogPayload", () => {
to: "claude-opus-4-6",
})
})
- it("parses an empty session_reset payload", () => {
- expect(parseAuditLogPayload("session_reset", JSON.stringify({}))).toEqual({})
+ it("parses a well-shaped session_reset payload (single/reset_all trigger)", () => {
+ expect(parseAuditLogPayload("session_reset", JSON.stringify({ trigger: "single" }))).toEqual({
+ trigger: "single",
+ })
+ expect(parseAuditLogPayload("session_reset", JSON.stringify({ trigger: "reset_all" }))).toEqual({
+ trigger: "reset_all",
+ })
+ })
+ it("degrades a legacy empty session_reset payload to null (written before trigger existed)", () => {
+ // Rows written by the old dispatch-time route carried `{}` — after the
+ // schema tightened to require `trigger`, they parse to null rather than
+ // throwing, and RowBody renders the static reset text (never a blank row).
+ expect(parseAuditLogPayload("session_reset", JSON.stringify({}))).toBe(null)
+ })
+ it("rejects a session_reset payload with an out-of-domain trigger", () => {
+ expect(parseAuditLogPayload("session_reset", JSON.stringify({ trigger: "nap" }))).toBe(null)
+ })
+ it("parses a well-shaped nap payload (trigger literal)", () => {
+ expect(parseAuditLogPayload("nap", JSON.stringify({ trigger: "nap" }))).toEqual({ trigger: "nap" })
+ })
+ it("degrades a legacy empty nap payload to null", () => {
+ expect(parseAuditLogPayload("nap", JSON.stringify({}))).toBe(null)
+ })
+ it("rejects a nap payload with an out-of-domain trigger (no cross-kind smuggle)", () => {
+ expect(parseAuditLogPayload("nap", JSON.stringify({ trigger: "single" }))).toBe(null)
})
it("parses a well-shaped error payload (so history rows keep their message, not the fallback)", () => {
const payload = {
diff --git a/src/web/src/lib/community/audit-log-payload.ts b/src/web/src/lib/community/audit-log-payload.ts
index c22af1624..1c33dd3b2 100644
--- a/src/web/src/lib/community/audit-log-payload.ts
+++ b/src/web/src/lib/community/audit-log-payload.ts
@@ -5,6 +5,7 @@ import {
AuditLogWakeTriggerPayloadSchema,
AuditLogModelChangedPayloadSchema,
AuditLogSessionResetPayloadSchema,
+ AuditLogNapPayloadSchema,
AuditLogErrorPayloadSchema,
} from "@alook/shared"
@@ -49,6 +50,10 @@ export function parseAuditLogPayload(
const r = AuditLogSessionResetPayloadSchema.safeParse(json)
return r.success ? r.data : null
}
+ case "nap": {
+ const r = AuditLogNapPayloadSchema.safeParse(json)
+ return r.success ? r.data : null
+ }
case "error": {
const r = AuditLogErrorPayloadSchema.safeParse(json)
return r.success ? r.data : null
diff --git a/src/web/src/stores/community/ws.ts b/src/web/src/stores/community/ws.ts
index 8944c0073..7a1a475bf 100644
--- a/src/web/src/stores/community/ws.ts
+++ b/src/web/src/stores/community/ws.ts
@@ -39,7 +39,7 @@ export const BOT_AUDIT_RING_MAX = 200
export type BotAuditEventEntry = {
id: string
botId: string
- 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: unknown
sessionId?: string | null
launchId?: string | null
diff --git a/src/ws-do/src/ws-durable.test.ts b/src/ws-do/src/ws-durable.test.ts
index 170da86a9..d3ff7cfda 100644
--- a/src/ws-do/src/ws-durable.test.ts
+++ b/src/ws-do/src/ws-durable.test.ts
@@ -93,6 +93,9 @@ const mockIsBotOnline = vi.fn<(db: unknown, botUserId: string) => Promise<boolea
const mockGetBotBinding = vi.fn<(db: unknown, botId: string) => Promise<{ machineId: string; runtime: string } | null>>().mockResolvedValue(null)
const mockGetBotBindingWithOwner = vi.fn<(db: unknown, botId: string) => Promise<{ machineId: string; runtime: string; ownerUserId: string; name: string; discriminator: string } | null>>().mockResolvedValue(null)
const mockInsertBotActivityEventAndPrune = vi.fn<(db: unknown, data: unknown) => Promise<{ id: string; createdAt: string } | null>>().mockResolvedValue(null)
+const mockInsertBotAuditSessionReset = vi.fn<(db: unknown, data: unknown) => Promise<{ id: string; createdAt: string } | null>>().mockResolvedValue(null)
+const mockInsertBotAuditNap = vi.fn<(db: unknown, data: unknown) => Promise<{ id: string; createdAt: string } | null>>().mockResolvedValue(null)
+const mockTouchBotRefreshContext = vi.fn<(db: unknown, botId: string, now: string) => Promise<void>>().mockResolvedValue(undefined)
const mockUpdateProfile = vi
.fn<(db: unknown, userId: string, data: { statusEmoji?: string | null; statusText?: string | null }) => Promise<unknown>>()
.mockResolvedValue({})
@@ -134,7 +137,7 @@ vi.mock("@alook/shared", () => {
// without pulling in zod (which isn't a direct dep of @alook/ws-do).
const SessionErrorFrameSchema = {
safeParse(v: unknown) {
- const m = v as { type?: unknown; code?: unknown; agentId?: unknown; payload?: unknown }
+ const m = v as { type?: unknown; code?: unknown; agentId?: unknown; launchId?: unknown; payload?: unknown }
if (m?.type !== "session.error" || m?.code !== "runtime_not_available") {
return { success: false } as const
}
@@ -144,6 +147,9 @@ vi.mock("@alook/shared", () => {
type: "session.error" as const,
code: "runtime_not_available" as const,
agentId: typeof m.agentId === "string" ? (m.agentId as string) : undefined,
+ // launchId rides the frame now (Melisa's source half) — the DO uses
+ // it to evict pending reset/nap attribution on cold-start branch A.
+ launchId: typeof m.launchId === "string" ? (m.launchId as string) : undefined,
payload: (m.payload as Record<string, unknown> | undefined) ?? undefined,
},
}
@@ -204,6 +210,24 @@ vi.mock("@alook/shared", () => {
}
},
}
+ const AgentSessionMessageSchema = {
+ safeParse(v: unknown) {
+ const m = v as { type?: unknown; agentId?: unknown; sessionId?: unknown; launchId?: unknown }
+ if (m?.type !== "agent_session") return { success: false } as const
+ if (typeof m.agentId !== "string" || m.agentId.length === 0) return { success: false } as const
+ if (typeof m.sessionId !== "string" || m.sessionId.length === 0) return { success: false } as const
+ if (typeof m.launchId !== "string" || m.launchId.length === 0) return { success: false } as const
+ return {
+ success: true as const,
+ data: {
+ type: "agent_session" as const,
+ agentId: m.agentId,
+ sessionId: m.sessionId,
+ launchId: m.launchId,
+ },
+ }
+ },
+ }
const HostBotAuditEventFrameSchema = {
safeParse(v: unknown) {
const m = v as { type?: unknown; agentId?: unknown; sessionId?: unknown; launchId?: unknown; event?: unknown }
@@ -270,6 +294,7 @@ vi.mock("@alook/shared", () => {
AgentActivityMessageSchema,
AgentTypingMessageSchema,
AgentTypingStopMessageSchema,
+ AgentSessionMessageSchema,
HostBotAuditEventFrameSchema,
// Deterministic preset picker so the assertion can pin exact
// `statusEmoji`/`statusText` values regardless of the injected `seed`.
@@ -360,9 +385,12 @@ vi.mock("@alook/shared", () => {
listBotsForMachine: (...a: [unknown, string]) => mockListBotsForMachine(...a),
getBotBinding: (...a: [unknown, string]) => mockGetBotBinding(...a),
getBotBindingWithOwner: (...a: [unknown, string]) => mockGetBotBindingWithOwner(...a),
+ touchBotRefreshContext: (...a: [unknown, string, string]) => mockTouchBotRefreshContext(...a),
},
communityBotAuditLog: {
insertBotActivityEventAndPrune: (...a: any[]) => mockInsertBotActivityEventAndPrune(...a),
+ insertBotAuditSessionReset: (...a: any[]) => mockInsertBotAuditSessionReset(...a),
+ insertBotAuditNap: (...a: any[]) => mockInsertBotAuditNap(...a),
},
user: {
getUserInternal: (...a: [unknown, string]) => mockGetUserInternal(...a),
@@ -1909,6 +1937,206 @@ describe("WebSocketDurableObject", () => {
})
})
+ describe("community-machine — reset/nap completion re-home (agent_session landing)", () => {
+ beforeEach(() => {
+ mockInsertBotAuditSessionReset.mockReset()
+ mockInsertBotAuditNap.mockReset()
+ mockTouchBotRefreshContext.mockReset()
+ mockGetBotBindingWithOwner.mockReset()
+ mockStubFetch.mockClear()
+ mockInsertBotAuditSessionReset.mockResolvedValue({ id: "bae_reset", createdAt: "2025-06-01T10:00:00.000Z" })
+ mockInsertBotAuditNap.mockResolvedValue({ id: "bae_nap", createdAt: "2025-06-01T11:00:00.000Z" })
+ mockTouchBotRefreshContext.mockResolvedValue(undefined)
+ mockGetBotBindingWithOwner.mockResolvedValue({
+ machineId: "cm_1",
+ runtime: "codex",
+ ownerUserId: "owner_1",
+ name: "Bot",
+ discriminator: "0007",
+ })
+ })
+
+ function machineWs() {
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "community-machine", machineId: "cm_1", userId: "u_1", authenticated: true })
+ return ws
+ }
+
+ function seedIdentity(store: Map<string, unknown>) {
+ store.set("community-machine-identity", { userId: "u_1", machineId: "cm_1", credentialHash: "0".repeat(64) })
+ }
+
+ // Helper: push a frame through /push (records pending attribution), matching
+ // how the index worker forwards reset/nap frames to this DO.
+ async function pushFrame(durable: any, body: unknown) {
+ await durable.fetch(
+ new (globalThis.Request as any)("http://internal/push", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(body),
+ }),
+ )
+ }
+
+ function auditBroadcast() {
+ return mockStubFetch.mock.calls
+ .map((c: any[]) => c[0] as Request)
+ .find((r: Request) => r.url.endsWith("/broadcast"))
+ }
+
+ it("single reset: agent_session writes session_reset audit + stamps awake in lockstep + broadcasts", async () => {
+ const { durable, store } = createDO()
+ seedIdentity(store)
+ // Dispatch: an agent:reset frame is forwarded → records launchId→single.
+ await pushFrame(durable, { type: "agent:reset", agentId: "bot_1", config: {}, launchId: "l_reset" })
+ // Completion: the reborn agent's agent_session lands.
+ await durable.webSocketMessage(
+ machineWs() as any,
+ JSON.stringify({ type: "agent_session", agentId: "bot_1", sessionId: "s_new", launchId: "l_reset" }),
+ )
+
+ // Audit written server-side with the trigger derived from the endpoint.
+ expect(mockInsertBotAuditSessionReset).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ botId: "bot_1", launchId: "l_reset", trigger: "single" }),
+ )
+ expect(mockInsertBotAuditNap).not.toHaveBeenCalled()
+ // LOCKSTEP invariant: touch uses the audit row's own createdAt, not another clock.
+ expect(mockTouchBotRefreshContext).toHaveBeenCalledWith(expect.anything(), "bot_1", "2025-06-01T10:00:00.000Z")
+ // Broadcast to the owner carries the session_reset event.
+ const call = auditBroadcast()
+ expect(call).toBeDefined()
+ const body = JSON.parse(await (call!).clone().text()) as Record<string, unknown>
+ expect(body).toEqual({
+ type: "community:bot.audit_event",
+ botId: "bot_1",
+ id: "bae_reset",
+ kind: "session_reset",
+ payload: { trigger: "single" },
+ sessionId: null,
+ launchId: "l_reset",
+ createdAt: "2025-06-01T10:00:00.000Z",
+ })
+ })
+
+ it("batch reset: each agent's agent_session writes session_reset with trigger reset_all", async () => {
+ const { durable, store } = createDO()
+ seedIdentity(store)
+ // Dispatch: ONE machine:reset_all frame carrying two launches.
+ await pushFrame(durable, {
+ type: "machine:reset_all",
+ resets: [
+ { agentId: "bot_1", config: {}, launchId: "l_a" },
+ { agentId: "bot_2", config: {}, launchId: "l_b" },
+ ],
+ })
+ // Both agents reborn — two agent_session frames.
+ await durable.webSocketMessage(
+ machineWs() as any,
+ JSON.stringify({ type: "agent_session", agentId: "bot_1", sessionId: "s_a", launchId: "l_a" }),
+ )
+ await durable.webSocketMessage(
+ machineWs() as any,
+ JSON.stringify({ type: "agent_session", agentId: "bot_2", sessionId: "s_b", launchId: "l_b" }),
+ )
+
+ expect(mockInsertBotAuditSessionReset).toHaveBeenCalledTimes(2)
+ expect(mockInsertBotAuditSessionReset).toHaveBeenNthCalledWith(
+ 1,
+ expect.anything(),
+ expect.objectContaining({ botId: "bot_1", launchId: "l_a", trigger: "reset_all" }),
+ )
+ expect(mockInsertBotAuditSessionReset).toHaveBeenNthCalledWith(
+ 2,
+ expect.anything(),
+ expect.objectContaining({ botId: "bot_2", launchId: "l_b", trigger: "reset_all" }),
+ )
+ expect(mockTouchBotRefreshContext).toHaveBeenCalledTimes(2)
+ })
+
+ it("nap: agent_session writes nap audit (trigger nap) + stamps awake in lockstep + broadcasts", async () => {
+ const { durable, store } = createDO()
+ seedIdentity(store)
+ await pushFrame(durable, { type: "agent:nap", agentId: "bot_1", config: {}, launchId: "l_nap", handoff: "note" })
+ await durable.webSocketMessage(
+ machineWs() as any,
+ JSON.stringify({ type: "agent_session", agentId: "bot_1", sessionId: "s_new", launchId: "l_nap" }),
+ )
+
+ expect(mockInsertBotAuditNap).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ botId: "bot_1", launchId: "l_nap" }),
+ )
+ expect(mockInsertBotAuditSessionReset).not.toHaveBeenCalled()
+ expect(mockTouchBotRefreshContext).toHaveBeenCalledWith(expect.anything(), "bot_1", "2025-06-01T11:00:00.000Z")
+ const body = JSON.parse(await (auditBroadcast()!).clone().text()) as Record<string, unknown>
+ expect(body).toMatchObject({ kind: "nap", payload: { trigger: "nap" }, launchId: "l_nap" })
+ })
+
+ it("fire-once: a replayed agent_session for the same launch writes nothing the second time", async () => {
+ const { durable, store } = createDO()
+ seedIdentity(store)
+ await pushFrame(durable, { type: "agent:reset", agentId: "bot_1", config: {}, launchId: "l_reset" })
+ const frame = JSON.stringify({ type: "agent_session", agentId: "bot_1", sessionId: "s_new", launchId: "l_reset" })
+ await durable.webSocketMessage(machineWs() as any, frame)
+ await durable.webSocketMessage(machineWs() as any, frame) // replay
+
+ // Exactly one write despite two agent_session frames — the pending entry
+ // was consumed (deleted) on the first.
+ expect(mockInsertBotAuditSessionReset).toHaveBeenCalledTimes(1)
+ expect(mockTouchBotRefreshContext).toHaveBeenCalledTimes(1)
+ })
+
+ it("no pending launch: an ordinary agent_session (never a reset/nap) writes nothing", async () => {
+ const { durable, store } = createDO()
+ seedIdentity(store)
+ // No /push recorded this launch — a plain wake session.
+ await durable.webSocketMessage(
+ machineWs() as any,
+ JSON.stringify({ type: "agent_session", agentId: "bot_1", sessionId: "s_new", launchId: "l_plain" }),
+ )
+ expect(mockInsertBotAuditSessionReset).not.toHaveBeenCalled()
+ expect(mockInsertBotAuditNap).not.toHaveBeenCalled()
+ expect(mockTouchBotRefreshContext).not.toHaveBeenCalled()
+ })
+
+ it("cold-start fail branch B (agent_wake_ack error): evicts pending, no audit/awake, and a later replayed agent_session stays silent", async () => {
+ const { durable, store } = createDO()
+ seedIdentity(store)
+ await pushFrame(durable, { type: "agent:reset", agentId: "bot_1", config: {}, launchId: "l_reset" })
+ // Enroll fail / spawn threw → wake_ack error for this launch.
+ await durable.webSocketMessage(
+ machineWs() as any,
+ JSON.stringify({ type: "agent_wake_ack", agentId: "bot_1", launchId: "l_reset", status: "error", error: { code: "spawn_threw", message: "boom" } }),
+ )
+ // If (impossibly) an agent_session arrives later, the entry is already gone
+ // → nothing written. This is the red-line-② positive proof.
+ await durable.webSocketMessage(
+ machineWs() as any,
+ JSON.stringify({ type: "agent_session", agentId: "bot_1", sessionId: "s_new", launchId: "l_reset" }),
+ )
+ expect(mockInsertBotAuditSessionReset).not.toHaveBeenCalled()
+ expect(mockTouchBotRefreshContext).not.toHaveBeenCalled()
+ })
+
+ it("cold-start fail branch A (session.error runtime_not_available): evicts pending, no audit/awake", async () => {
+ const { durable, store } = createDO()
+ seedIdentity(store)
+ await pushFrame(durable, { type: "agent:reset", agentId: "bot_1", config: {}, launchId: "l_reset" })
+ // Runtime not installed → session.error carrying the launchId (Melisa's source half).
+ await durable.webSocketMessage(
+ machineWs() as any,
+ JSON.stringify({ type: "session.error", code: "runtime_not_available", agentId: "bot_1", launchId: "l_reset", payload: { requested: "codex", available: [] } }),
+ )
+ await durable.webSocketMessage(
+ machineWs() as any,
+ JSON.stringify({ type: "agent_session", agentId: "bot_1", sessionId: "s_new", launchId: "l_reset" }),
+ )
+ expect(mockInsertBotAuditSessionReset).not.toHaveBeenCalled()
+ expect(mockTouchBotRefreshContext).not.toHaveBeenCalled()
+ })
+ })
+
describe("community-machine — ready frame reconciles bot activity", () => {
beforeEach(() => {
mockUpsertMachineByMachineId.mockReset()
diff --git a/src/ws-do/src/ws-durable.ts b/src/ws-do/src/ws-durable.ts
index db8aa0b0a..5d1c141a7 100644
--- a/src/ws-do/src/ws-durable.ts
+++ b/src/ws-do/src/ws-durable.ts
@@ -11,6 +11,7 @@ import {
AgentActivityMessageSchema,
AgentTypingMessageSchema,
AgentTypingStopMessageSchema,
+ AgentSessionMessageSchema,
HostBotAuditEventFrameSchema,
pickBotActivityPreset,
RUNNING_PRESETS,
@@ -71,6 +72,17 @@ interface CommunityMachineHandle {
const IDENTITY_KEY = "community-machine-identity"
const HANDLE_KEY = "community-machine-handle"
const RUNTIME_ERROR_KEY = "community-machine-runtime-error"
+// Per-launch pending reset/nap attribution. Written when a reset/nap frame is
+// forwarded to this machine's daemon (dispatch), read + deleted when the
+// reborn agent's `agent_session` lands (completion). ctx.storage, NOT an
+// in-memory Map: the DO can hibernate between dispatch and agent_session, and
+// a dropped entry would make a real reset silently write nothing (fire-once
+// reads it as "never dispatched"). See plans/reset-nap-completion-rehome.md §6.
+const RESET_PENDING_PREFIX = "reset-pending:"
+const resetPendingKey = (launchId: string) => RESET_PENDING_PREFIX + launchId
+
+/** Trigger for a pending reset/nap launch — the entry-point that dispatched it. */
+type ResetTrigger = "single" | "reset_all" | "nap"
export class WebSocketDurableObject extends DurableObject<Env> {
/**
@@ -174,6 +186,14 @@ export class WebSocketDurableObject extends DurableObject<Env> {
// daemon. Best-effort — if the daemon isn't connected, drops silently.
// Cold-start warmup on reconnect re-syncs authoritative state.
const body = await request.text()
+ // Reset/nap/reset_all frames pass through here on their way to the
+ // daemon — the moment we know both the launchId(s) AND which entry-point
+ // dispatched them. Record the pending attribution NOW (first-write, never
+ // later than the reborn `agent_session` could arrive — §6.2) so the
+ // completion landing can look it up. Trigger is derived from the frame
+ // type, so it structurally cannot disagree with the endpoint (§ Cecilia
+ // #933). Done before the forward so a fast cold-start can't beat the write.
+ await this.recordPendingResets(body)
const sent = this.forwardToCommunityMachine(body)
return new Response(JSON.stringify({ sent }), {
headers: { "Content-Type": "application/json" },
@@ -740,6 +760,7 @@ export class WebSocketDurableObject extends DurableObject<Env> {
const ack = parsed as {
type: string
agentId?: string
+ launchId?: string
status?: string
error?: { code?: string; message?: string }
}
@@ -751,6 +772,15 @@ export class WebSocketDurableObject extends DurableObject<Env> {
code: ack.error?.code,
message: ack.error?.message,
})
+ // Cold-start failure branch B (enroll fail / spawn threw): the reborn
+ // agent will never emit `agent_session`, so evict any pending
+ // reset/nap attribution for this launch — leaving it would leak an
+ // entry in ctx.storage forever, and (correctly) no audit/awake is ever
+ // written for a reset that never completed (red line ②). Branch A
+ // (runtime_not_available) arrives as `session.error` below.
+ if (ack.type === "agent_wake_ack" && typeof ack.launchId === "string" && ack.launchId.length > 0) {
+ await this.evictPendingReset(ack.launchId)
+ }
} else if (ack.status === "ok") {
log.debug("agent command ack ok", {
machineId: identity.machineId,
@@ -772,6 +802,16 @@ export class WebSocketDurableObject extends DurableObject<Env> {
const available = availableRaw.filter((v): v is string => typeof v === "string")
const overlay = { requested, available, at: new Date().toISOString() }
await this.ctx.storage.put(RUNTIME_ERROR_KEY, overlay)
+ // Cold-start failure branch A (runtime not installed): the agent never
+ // reborns, so evict any pending reset/nap attribution for this launch —
+ // the twin of the `agent_wake_ack` error evict above. This is the branch
+ // that would otherwise leak (a runtime-missing reset of a bound-idle
+ // agent is the common batch-reset failure — Blair #922). `launchId` is
+ // carried on the frame now (Melisa's source half).
+ const launchId = sessionErrorParse.data.launchId
+ if (typeof launchId === "string" && launchId.length > 0) {
+ await this.evictPendingReset(launchId)
+ }
await this.fanOutMachineUpdated(identity.userId, identity.machineId).catch(() => { })
return
}
@@ -891,6 +931,68 @@ export class WebSocketDurableObject extends DurableObject<Env> {
return
}
+ // `agent_session` — the reborn agent is really up and has a session. This
+ // is the completion signal for a reset/nap: if this launch has pending
+ // attribution (recorded at dispatch in `/push`), write its audit + awake
+ // stamp + broadcast NOW (not at dispatch), then consume the entry so a
+ // replayed `agent_session` for the same launch can't double-write
+ // (fire-once, §6.1). A launch with no pending entry (an ordinary wake, or
+ // an already-consumed reset) falls through with no write.
+ const sessionParse = AgentSessionMessageSchema.safeParse(parsed)
+ if (sessionParse.success) {
+ const { agentId, launchId } = sessionParse.data
+ const trigger = await this.ctx.storage.get<ResetTrigger>(resetPendingKey(launchId))
+ if (!trigger) return // not a reset/nap launch, or already consumed
+ const db = createDb(this.env.DB)
+ await this.handleFrameForBoundBot({
+ frameType: "agent_session",
+ agentId,
+ machineId: identity.machineId,
+ writeCategory: "ws_frame_dropped_write",
+ resolveBinding: () => queries.communityBot.getBotBindingWithOwner(db, agentId),
+ isMatch: (binding) => binding.machineId === identity.machineId,
+ write: async (binding) => {
+ // Per-kind audit — nap and reset stay distinct kinds so my-bots reads
+ // "slept" vs "was reset" (red line ④). actorId never travels: reset
+ // is owner-only, so the actor IS the bot owner, resolved right here
+ // from the binding (red line ⑥ — attribution stays server-side).
+ const inserted =
+ trigger === "nap"
+ ? await queries.communityBotAuditLog.insertBotAuditNap(db, {
+ botId: agentId,
+ launchId,
+ })
+ : await queries.communityBotAuditLog.insertBotAuditSessionReset(db, {
+ botId: agentId,
+ launchId,
+ trigger,
+ })
+ if (!inserted) return
+ // Stamp awake (lastRefreshContextAt) in lockstep with the audit row,
+ // using the row's createdAt so the my-bots "Awake Nh" indicator can
+ // never drift from the audit event.
+ await queries.communityBot.touchBotRefreshContext(db, agentId, inserted.createdAt)
+ const payload = trigger === "nap" ? { trigger: "nap" } : { trigger }
+ await this.notifyUserDO(binding.ownerUserId, {
+ type: WS_EVENTS.BOT_AUDIT_EVENT,
+ botId: agentId,
+ id: inserted.id,
+ kind: trigger === "nap" ? "nap" : "session_reset",
+ payload,
+ sessionId: null,
+ launchId,
+ createdAt: inserted.createdAt,
+ }).catch(() => { })
+ },
+ })
+ // Consume the pending entry regardless of the write's fate: a replayed
+ // agent_session must never re-write, and the audit row (if it landed) is
+ // the durable record. A failed write (binding gone) also clears — the
+ // launch is done either way.
+ await this.evictPendingReset(launchId)
+ return
+ }
+
// `bot_audit_event` — daemon reports a bot activity event (cli_invocation,
// tool_call, or thinking). Insert + rolling-500 prune land atomically via
// `db.batch`; server stamps `createdAt` (never trust the daemon clock).
@@ -1095,6 +1197,49 @@ export class WebSocketDurableObject extends DurableObject<Env> {
return sent
}
+ /**
+ * Record pending reset/nap attribution from a frame about to be forwarded to
+ * the daemon. Each launchId → its trigger, keyed by the frame type:
+ * - `agent:reset` → one launch, trigger `single`
+ * - `machine:reset_all` → N launches (resets[]), trigger `reset_all`
+ * - `agent:nap` → one launch, trigger `nap`
+ * Any other frame type is a no-op. The entry is consumed (deleted) when the
+ * reborn `agent_session` lands, or evicted on a cold-start failure frame
+ * (`agent_wake_ack` error / `session.error`). Best-effort parse — a malformed
+ * frame just records nothing and forwards as before.
+ */
+ private async recordPendingResets(body: string): Promise<void> {
+ let frame: unknown
+ try {
+ frame = JSON.parse(body)
+ } catch {
+ return
+ }
+ if (!frame || typeof frame !== "object") return
+ const f = frame as { type?: unknown }
+ const put = async (launchId: unknown, trigger: ResetTrigger) => {
+ if (typeof launchId !== "string" || launchId.length === 0) return
+ await this.ctx.storage.put<ResetTrigger>(resetPendingKey(launchId), trigger)
+ }
+ if (f.type === "agent:reset") {
+ await put((f as { launchId?: unknown }).launchId, "single")
+ } else if (f.type === "agent:nap") {
+ await put((f as { launchId?: unknown }).launchId, "nap")
+ } else if (f.type === "machine:reset_all") {
+ const resets = (f as { resets?: unknown }).resets
+ if (Array.isArray(resets)) {
+ for (const r of resets) {
+ if (r && typeof r === "object") await put((r as { launchId?: unknown }).launchId, "reset_all")
+ }
+ }
+ }
+ }
+
+ /** Drop a pending reset/nap entry (consumed on completion, or evicted on failure). */
+ private async evictPendingReset(launchId: string): Promise<void> {
+ await this.ctx.storage.delete(resetPendingKey(launchId))
+ }
+
/** Optimistic overlay clear — no-op when nothing is stashed. */
private async clearRuntimeErrorOverlay(): Promise<void> {
const overlay = await this.ctx.storage.get(RUNTIME_ERROR_KEY)