Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(daemon, community): agent session reset with timeline barrier

Gus462a909a3ec1
diff --git a/src/daemon/src/manager/agentRouter.test.ts b/src/daemon/src/manager/agentRouter.test.ts
index ad42987ed..7e3a8b02b 100644
--- a/src/daemon/src/manager/agentRouter.test.ts
+++ b/src/daemon/src/manager/agentRouter.test.ts
@@ -27,13 +27,26 @@ function stubLogger(): Logger & { calls: Record<"debug" | "info" | "warn" | "err
function fakeManager(initialStatuses: Record<string, "idle" | "starting" | "running" | "stopping"> = {}) {
const 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 order: string[] = [];
const statuses: Record<string, "idle" | "starting" | "running" | "stopping"> = { ...initialStatuses };
const mgr = {
register(agentId: string, launch?: { sessionId?: string; launchId?: string }) {
registers.push({ agentId, sessionId: launch?.sessionId, launchId: launch?.launchId });
+ order.push(`register:${agentId}`);
},
deliver(agentId: string, m: { seq?: number; text: string }) {
delivers.push({ agentId, text: m.text, seq: m.seq });
+ order.push(`deliver:${agentId}`);
+ },
+ forgetSession(agentId: string) {
+ forgets.push(agentId);
+ order.push(`forget:${agentId}`);
+ },
+ async resetSession(agentId: string, opts: { launchId: string; rewakePrompt: string }) {
+ resets.push({ agentId, rewakePrompt: opts.rewakePrompt, launchId: opts.launchId });
+ order.push(`reset:${agentId}`);
},
stop() {},
liveSessionReports: () => [],
@@ -43,7 +56,7 @@ function fakeManager(initialStatuses: Record<string, "idle" | "starting" | "runn
return { agents };
},
} as unknown as AgentProcessManager;
- return { mgr, delivers, registers, statuses };
+ return { mgr, delivers, registers, statuses, forgets, resets, order };
}
/** Fake channel capturing acks + the command handler the router registers. */
@@ -138,6 +151,75 @@ describe("AgentRouter — agent:wake", () => {
});
});
+describe("AgentRouter — agent:reset", () => {
+ const CFG = { version: 1 as const, runtime: "mock", model: { kind: "default" as const }, mode: { kind: "default" as const } };
+
+ it("calls onBeforeAgent then manager.resetSession exactly once with a rewake prompt, adds to running set", 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();
+
+ await fire({ type: "agent:reset", agentId: "a1", config: CFG, launchId: "l1" });
+
+ expect(beforeCalls).toEqual(["a1"]);
+ expect(resets).toHaveLength(1);
+ expect(resets[0]).toMatchObject({ agentId: "a1", launchId: "l1" });
+ expect(resets[0].rewakePrompt.length).toBeGreaterThan(0);
+ // Ordering: onBeforeAgent completes before resetSession fires.
+ expect(order[0]).toBe("before:a1");
+ expect(order[1]).toBe("reset:a1");
+ expect(router.buildReady().runningAgents).toContain("a1");
+ });
+
+ it("a generic thrown error from resetSession is logged, doesn't crash, and does NOT add to running set", async () => {
+ const mgr = {
+ resetSession: async () => { throw new Error("boom"); },
+ liveSessionReports: () => [],
+ } as unknown as AgentProcessManager;
+ const { ch, fire } = fakeChannel();
+ const logger = stubLogger();
+ const router = new AgentRouter({ manager: mgr, channel: ch, runtimeReport: [{ id: "mock" }], logger });
+ await router.start();
+
+ await fire({ type: "agent:reset", agentId: "a1", config: CFG, launchId: "l1" });
+ expect(router.buildReady().runningAgents).not.toContain("a1");
+ expect(logger.calls.warn.some(([m]) => m === "agent:reset failed")).toBe(true);
+ });
+
+ it("UnknownRuntimeError from resetSession → forwards session.error{runtime_not_available}, running set untouched", async () => {
+ const throwing = new UnknownRuntimeError("gemini", ["claude", "codex"]);
+ const mgr = {
+ resetSession: async () => { throw throwing; },
+ liveSessionReports: () => [],
+ } as unknown as AgentProcessManager;
+ const { ch, sessionErrors, fire } = fakeChannel();
+ const router = new AgentRouter({ manager: mgr, channel: ch, runtimeReport: [{ id: "claude" }, { id: "codex" }] });
+ await router.start();
+
+ await fire({
+ type: "agent:reset",
+ agentId: "a1",
+ config: { ...CFG, runtime: "gemini" },
+ launchId: "l1",
+ });
+ expect(sessionErrors).toHaveLength(1);
+ expect(sessionErrors[0]).toMatchObject({
+ type: "session.error",
+ code: "runtime_not_available",
+ agentId: "a1",
+ payload: { requested: "gemini", available: ["claude", "codex"] },
+ });
+ expect(router.buildReady().runningAgents).not.toContain("a1");
+ });
+});
+
describe("AgentRouter — unknown runtime → session.error", () => {
it("catches UnknownRuntimeError from driverFor and forwards session.error{runtime_not_available}", async () => {
// Manager whose register() re-throws whatever driverFor throws — mimics
diff --git a/src/daemon/src/manager/agentRouter.ts b/src/daemon/src/manager/agentRouter.ts
index 0b8540504..da8f8598e 100644
--- a/src/daemon/src/manager/agentRouter.ts
+++ b/src/daemon/src/manager/agentRouter.ts
@@ -115,6 +115,24 @@ function defaultFormatUnreadNoticeText(notice: UnreadNotice): string {
return `You have unread messages in channel ${notice.channel}.`;
}
+/**
+ * Fixed prompt handed to the agent as the initial input of a reset-driven
+ * spawn. Wording rationale:
+ * - "reset by your owner" tells the agent this is an intentional external
+ * action, not a crash — avoids self-questioning.
+ * - `@todo.md` / `@memory.md` are the standing-prompt-established
+ * persistent notes.
+ * - `.context_timeline` is the daemon-written per-agent JSONL under the
+ * workdir; the walker's `reset_session` barrier only blocks resume, not
+ * the on-disk history — the agent CAN read pre-reset turn contents.
+ * - "pull your inbox" makes it explicit that any real unread messages
+ * queued during the reset window need to be processed.
+ */
+const REWAKE_PROMPT =
+ "Your session was reset by your owner. Prior conversation context is gone. " +
+ "Read @todo.md, @memory.md, and your .context_timeline for anything unfinished, " +
+ "then pull your inbox to catch up on unread messages before doing anything else.";
+
export class AgentRouter {
private readonly running = new Set<string>();
/**
@@ -369,6 +387,42 @@ export class AgentRouter {
return;
}
break;
+ case "agent:reset":
+ this.log.info("agent:reset received", { agentId: cmd.agentId, launchId: cmd.launchId });
+ try {
+ await this.opts.onBeforeAgent?.(cmd.agentId);
+ await this.opts.manager.resetSession(cmd.agentId, {
+ runtimeConfig: cmd.config,
+ launchId: cmd.launchId,
+ rewakePrompt: REWAKE_PROMPT,
+ });
+ this.running.add(cmd.agentId);
+ this.scheduleReadyFrameResend();
+ this.log.info("agent:reset 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:reset error", {
+ agentId: cmd.agentId,
+ "error.code": "runtime_not_available",
+ });
+ return;
+ }
+ this.log.warn("agent:reset failed", {
+ agentId: cmd.agentId,
+ err: err instanceof Error ? err.message : String(err),
+ });
+ }
+ break;
case "agent:stop":
this.log.info("agent:stop received", { agentId: cmd.agentId });
try {
diff --git a/src/daemon/src/manager/managerPolicy.test.ts b/src/daemon/src/manager/managerPolicy.test.ts
index 8e1c420c3..a468a80ab 100644
--- a/src/daemon/src/manager/managerPolicy.test.ts
+++ b/src/daemon/src/manager/managerPolicy.test.ts
@@ -341,3 +341,155 @@ describe("reduceManager — tick: stall + idle hibernation", () => {
expect(reduceManager(s, { type: "tick", nowMs: 10_000 }).effects).toEqual([]);
});
});
+
+describe("reduceManager — reset_session", () => {
+ it("nulls sessionId on a known agent without changing status/turnActive", () => {
+ let s = createInitialManagerState();
+ s = register(s, "a", PERSISTENT_GATED);
+ s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 0 }).state;
+ s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 0 }).state;
+ s = reduceManager(s, { type: "session", agentId: "a", sessionId: "sess-1" }).state;
+ expect(s.agents.a.sessionId).toBe("sess-1");
+ const prevStatus = s.agents.a.status;
+ const prevTurnActive = s.agents.a.turnActive;
+
+ const r = reduceManager(s, { type: "reset_session", agentId: "a" });
+ expect(r.effects).toEqual([]);
+ expect(r.state.agents.a.sessionId).toBeNull();
+ expect(r.state.agents.a.status).toBe(prevStatus);
+ expect(r.state.agents.a.turnActive).toBe(prevTurnActive);
+ });
+
+ it("no-op on an unknown agentId", () => {
+ const s = createInitialManagerState();
+ const r = reduceManager(s, { type: "reset_session", agentId: "ghost" });
+ expect(r.effects).toEqual([]);
+ expect(r.state.agents.ghost).toBeUndefined();
+ });
+});
+
+describe("reduceManager — begin_reset / rewake_after_reset", () => {
+ it("begin_reset sets resetting=true and emits no effects", () => {
+ let s = createInitialManagerState();
+ s = register(s, "a", PERSISTENT_GATED);
+ const r = reduceManager(s, { type: "begin_reset", agentId: "a" });
+ expect(r.effects).toEqual([]);
+ expect(r.state.agents.a.resetting).toBe(true);
+ });
+
+ it("rewake_after_reset appends to inbox and emits no effects", () => {
+ let s = createInitialManagerState();
+ s = register(s, "a", PERSISTENT_GATED);
+ const r = reduceManager(s, { type: "rewake_after_reset", agentId: "a", message: { text: "rewake" } });
+ expect(r.effects).toEqual([]);
+ expect(r.state.agents.a.inbox.map((m) => m.text)).toEqual(["rewake"]);
+ });
+
+ it("both events are no-ops on an unknown agent", () => {
+ const s = createInitialManagerState();
+ expect(reduceManager(s, { type: "begin_reset", agentId: "ghost" }).state.agents.ghost).toBeUndefined();
+ expect(
+ reduceManager(s, { type: "rewake_after_reset", agentId: "ghost", message: { text: "x" } }).state.agents.ghost,
+ ).toBeUndefined();
+ });
+});
+
+describe("reduceManager — onWake `resetting` gate", () => {
+ it("persistent+direct + running + resetting=true: wake queues to inbox only, NO send/gated_hold effect", () => {
+ let s = createInitialManagerState();
+ s = register(s, "a", PERSISTENT_DIRECT);
+ s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 1 }).state;
+ s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 2 }).state;
+ // Set resetting via the FSM event (bypassing onSpawned's auto-clear
+ // which fires before this event).
+ s = reduceManager(s, { type: "begin_reset", agentId: "a" }).state;
+ expect(s.agents.a.resetting).toBe(true);
+ expect(s.agents.a.status).toBe("running");
+
+ const r = reduceManager(s, { type: "wake", agentId: "a", message: { text: "unread" }, nowMs: 3 });
+ expect(r.effects).toEqual([]);
+ expect(r.state.agents.a.inbox.map((m) => m.text)).toEqual(["unread"]);
+ });
+
+ it("gated + running + turnActive + resetting=true: wake queues only, NO gated_hold effect", () => {
+ 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: "begin_reset", agentId: "a" }).state;
+
+ const r = reduceManager(s, { type: "wake", agentId: "a", message: { text: "unread" }, nowMs: 3 });
+ expect(r.effects).toEqual([]);
+ expect(r.state.agents.a.inbox.map((m) => m.text)).toEqual(["unread"]);
+ });
+
+ it("starting + resetting=true: wake queues (does NOT spawn a second process)", () => {
+ let s = createInitialManagerState();
+ s = register(s, "a", PERSISTENT_DIRECT);
+ s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 1 }).state;
+ // status=starting now
+ s = reduceManager(s, { type: "begin_reset", agentId: "a" }).state;
+
+ const r = reduceManager(s, { type: "wake", agentId: "a", message: { text: "unread" }, nowMs: 2 });
+ expect(r.effects).toEqual([]);
+ expect(r.state.agents.a.inbox.map((m) => m.text)).toEqual(["unread"]);
+ });
+
+ it("idle + resetting=true: wake IS EXEMPTED — still spawns (idle branch of reset orchestrator relies on this)", () => {
+ let s = createInitialManagerState();
+ s = register(s, "a", PERSISTENT_DIRECT);
+ s = reduceManager(s, { type: "begin_reset", agentId: "a" }).state;
+ expect(s.agents.a.resetting).toBe(true);
+ expect(s.agents.a.status).toBe("idle");
+
+ const r = reduceManager(s, { type: "wake", agentId: "a", message: { text: "rewake" }, nowMs: 1 });
+ expect(r.effects).toEqual([{ type: "spawn", agentId: "a", prompt: "rewake", resumeSessionId: null }]);
+ expect(r.state.agents.a.status).toBe("starting");
+ });
+});
+
+describe("reduceManager — onExit / onSpawned clear resetting", () => {
+ it("onExit clears resetting and drains inbox (rewake + queued unread) into ONE spawn", () => {
+ let s = createInitialManagerState();
+ s = register(s, "a", PERSISTENT_DIRECT);
+ // Simulate live agent
+ s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 1 }).state;
+ s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 2 }).state;
+ // Begin reset: mark + enqueue rewake
+ s = reduceManager(s, { type: "begin_reset", agentId: "a" }).state;
+ s = reduceManager(s, { type: "rewake_after_reset", agentId: "a", message: { text: "REWAKE" } }).state;
+ // Real unread arrives during reset window — gate queues to inbox.
+ s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "unread" }, nowMs: 3 }).state;
+ expect(s.agents.a.inbox.map((m) => m.text)).toEqual(["REWAKE", "unread"]);
+
+ // Kill lands → exit
+ const r = reduceManager(s, { type: "exit", agentId: "a" });
+ expect(r.effects).toEqual([{ type: "spawn", agentId: "a", prompt: "REWAKE\nunread", resumeSessionId: null }]);
+ expect(r.state.agents.a.resetting).toBe(false);
+ });
+
+ it("onSpawned clears resetting (idle-branch reset spawn)", () => {
+ let s = createInitialManagerState();
+ s = register(s, "a", PERSISTENT_DIRECT);
+ s = reduceManager(s, { type: "begin_reset", agentId: "a" }).state;
+ // Idle-branch deliver emits spawn (idle exempt).
+ s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "REWAKE" }, nowMs: 1 }).state;
+ expect(s.agents.a.resetting).toBe(true);
+ const r = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 2 });
+ expect(r.state.agents.a.resetting).toBe(false);
+ });
+
+ it("spawn-failure path (exit fires with empty inbox) still clears resetting → no permanent reset-lock", () => {
+ let s = createInitialManagerState();
+ s = register(s, "a", PERSISTENT_DIRECT);
+ s = reduceManager(s, { type: "begin_reset", agentId: "a" }).state;
+ // Simulate driver.start() rejecting: `doSpawn` dispatches an immediate
+ // exit; by then drainInboxToPrompt already emptied the inbox into the
+ // (failed) spawn's prompt.
+ s = { ...s, agents: { ...s.agents, a: { ...s.agents.a, status: "starting", inbox: [] } } };
+ const r = reduceManager(s, { type: "exit", agentId: "a" });
+ expect(r.effects).toEqual([]);
+ expect(r.state.agents.a.status).toBe("idle");
+ expect(r.state.agents.a.resetting).toBe(false);
+ });
+});
diff --git a/src/daemon/src/manager/managerPolicy.ts b/src/daemon/src/manager/managerPolicy.ts
index 740072832..e8210607a 100644
--- a/src/daemon/src/manager/managerPolicy.ts
+++ b/src/daemon/src/manager/managerPolicy.ts
@@ -62,6 +62,16 @@ export interface AgentState {
lastProgressAt: number;
/** ms timestamp since which the agent has been idle (running, no turn, empty inbox); null if not idle. */
idleSince: number | null;
+ /**
+ * True during an owner-triggered reset window. Gates every inbound wake to
+ * inbox-only (no `spawn`, no `send`, no `gated_hold`) EXCEPT when the
+ * agent is currently `idle` — the orchestrator's idle branch relies on
+ * `deliver` still emitting a spawn to kick a fresh session; if the gate
+ * blocked idle too, the reset would silently reset-lock the agent. Cleared
+ * by `onExit` (kill-and-respawn path) and `onSpawned` (idle-branch spawn
+ * path). See plans/bot-reset-session-v2.md.
+ */
+ resetting: boolean;
/**
* Coarse gated-steering phase (tool/compaction/review boundaries). Only
* meaningfully consulted when `caps.busyDeliveryMode === "gated"`; kept on
@@ -96,6 +106,26 @@ export type ManagerEvent =
| { type: "turn_end"; agentId: string; nowMs: number }
| { type: "exit"; agentId: string }
| { type: "tick"; nowMs: number }
+ /**
+ * Owner-triggered "reset session". Nulls `AgentState.sessionId` so the next
+ * `doSpawn`'s resume chain resolves to null. Does NOT change `phase` — a
+ * live process keeps running; the reset only affects the NEXT spawn.
+ */
+ | { type: "reset_session"; agentId: string }
+ /**
+ * Owner-triggered reset window began. Sets `agent.resetting = true`. No
+ * effects — the orchestrator dispatches `deliver` (idle branch) or
+ * `enqueueRewake` immediately after, and `stop()` follows on live branch.
+ */
+ | { type: "begin_reset"; agentId: string }
+ /**
+ * Enqueue a synthetic rewake message into the agent's inbox WITHOUT
+ * emitting any effect. Used by the reset orchestrator's live/starting/
+ * stopping branch — a `send` toward the ManagedSession that `stop()` is
+ * about to delete would be silently dropped; the queued message rides the
+ * `onExit` drain-then-spawn path instead.
+ */
+ | { type: "rewake_after_reset"; agentId: string; message: AgentMsg }
/**
* Generic passthrough of a `ParsedEvent`'s `kind` string, forwarded for
* EVERY runtime event (not just the ones the reducer acts on) so the
@@ -150,6 +180,10 @@ export function reduceManager(state: ManagerState, event: ManagerEvent): ReduceR
a.turnActive = true;
a.lastProgressAt = event.nowMs;
a.idleSince = null;
+ // Belt for the idle-branch reset path where `deliver` triggered a
+ // spawn directly (no `exit` fires there). The kill-and-respawn path
+ // clears `resetting` in `onExit`; here we cover the parallel path.
+ if (a.resetting) a.resetting = false;
});
case "session":
@@ -157,6 +191,29 @@ export function reduceManager(state: ManagerState, event: ManagerEvent): ReduceR
a.sessionId = event.sessionId;
});
+ case "reset_session":
+ // No-op on an unknown agent — matches AgentProcessManager.forgetSession's
+ // "safe on unknown id" contract. On a known agent, just null the
+ // sessionId; phase/status/turnActive are unchanged so a live process
+ // keeps running through its current turn.
+ if (!state.agents[event.agentId]) return { state, effects: [] };
+ return mutate(state, event.agentId, (a) => {
+ a.sessionId = null;
+ });
+
+ case "begin_reset":
+ if (!state.agents[event.agentId]) return { state, effects: [] };
+ return mutate(state, event.agentId, (a) => {
+ a.resetting = true;
+ });
+
+ case "rewake_after_reset":
+ if (!state.agents[event.agentId]) return { state, effects: [] };
+ return mutate(state, event.agentId, (a) => {
+ a.inbox = [...a.inbox, event.message];
+ a.idleSince = null;
+ });
+
case "progress":
return mutate(state, event.agentId, (a) => {
a.lastProgressAt = event.nowMs;
@@ -188,6 +245,19 @@ function onWake(state: ManagerState, agentId: string, message: AgentMsg): Reduce
return { state, effects: [] };
}
+ // Reset window: gate every non-idle wake to inbox-only. Idle is exempted
+ // deliberately — the orchestrator's idle branch calls `deliver` right
+ // after `markResetting`, and if the gate blocked idle too the spawn would
+ // never fire, so `resetting` would stay stuck forever. Idle safety is
+ // fine: no live session to steer against, and the moment `deliver`'s
+ // spawn effect flips status to `starting`, subsequent wakes hit the
+ // regular gate branch. See plans/bot-reset-session-v2.md.
+ if (agent.resetting && agent.status !== "idle") {
+ agent.inbox = [...agent.inbox, message];
+ agent.idleSince = null;
+ return commit(state, agent, []);
+ }
+
// Always enqueue the message first; any wake clears the idle timer.
agent.inbox = [...agent.inbox, message];
agent.idleSince = null;
@@ -283,8 +353,16 @@ function onRuntimeSignal(state: ManagerState, agentId: string, kind: string): Re
if (!existing) return { state, effects: [] };
const agent = clone(existing);
+ // Reset window: never emit a `send` toward the dying session, even for gated
+ // drivers whose boundary flush would otherwise fire on a mid-shutdown
+ // tool_output. Doing so would drain REWAKE from the inbox into a doomed
+ // session and lose it before `onExit`'s drain-and-spawn runs. Still update
+ // the diagnostics ring buffer so recentEvents reflects the reset window.
const isGatedActive =
- agent.status === "running" && agent.turnActive && agent.caps.busyDeliveryMode === "gated";
+ !agent.resetting &&
+ agent.status === "running" &&
+ agent.turnActive &&
+ agent.caps.busyDeliveryMode === "gated";
if (!isGatedActive) {
// Still record the event for diagnostics — cheap and harmless even when
// not gated (the ring buffer is unused unless busyDeliveryMode is gated).
@@ -356,6 +434,13 @@ function onExit(state: ManagerState, agentId: string): ReduceResult {
if (!existing) return { state, effects: [] };
const agent = clone(existing);
agent.turnActive = false;
+ // Clear `resetting` unconditionally at the top — covers both the normal
+ // path (kill → exit → drain → spawn, resetting cleared before the spawn)
+ // AND the spawn-failure path (`doSpawn` dispatches an immediate `exit`
+ // with `inbox.length === 0`, taking the idle branch below). Without the
+ // top-level clear, the failure path would leave `resetting: true` and
+ // silently reset-lock the agent for every subsequent wake.
+ if (agent.resetting) agent.resetting = false;
// Per-turn: if more messages queued, immediately respawn for the next batch.
if (agent.inbox.length > 0) {
@@ -421,6 +506,7 @@ function freshAgent(agentId: string, caps: AgentRuntimeCaps): AgentState {
turnActive: false,
lastProgressAt: 0,
idleSince: null,
+ resetting: false,
apm: createInitialApmGatedSteeringState(),
};
}
diff --git a/src/daemon/src/manager/managerRuntime.ts b/src/daemon/src/manager/managerRuntime.ts
index 0b33a779d..2c67d0752 100644
--- a/src/daemon/src/manager/managerRuntime.ts
+++ b/src/daemon/src/manager/managerRuntime.ts
@@ -191,6 +191,18 @@ export interface TimelineRecorder {
appendResponseToLatest(agentId: string, text: string): void;
/** 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
+ * `AgentProcessManager.resetSession`), so no race — no `forgot_session_id`
+ * needed. Safe to call on an unknown agentId.
+ */
+ forgetSession(agentId: string): void;
}
/** Max UTF-8 byte budget for `thinking` text in the audit log. */
@@ -543,6 +555,108 @@ export class AgentProcessManager {
this.dispatch({ type: "wake", agentId, message, nowMs: this.now() });
}
+ /**
+ * Clear every cached source that could seed the next spawn's
+ * `resumeSessionId`, append the timeline barrier, and null the FSM
+ * sessionId. Does NOT touch the running process (existing contract) and
+ * does NOT block subsequent wakes — see `resetSession` for the full
+ * orchestration. Caller: `resetSession` (below), after `register` and
+ * before `markResetting`.
+ */
+ forgetSession(agentId: string): void {
+ this.resumeSessions.delete(agentId);
+ this.liveSessions.delete(agentId);
+ this.dispatch({ type: "reset_session", agentId });
+ this.opts.timeline?.forgetSession(agentId);
+ }
+
+ /**
+ * Append a synthetic rewake message to the agent's FSM inbox WITHOUT
+ * emitting any effect. Called by `resetSession`'s live-branch: `stop()` is
+ * about to kill the ManagedSession, so a `send` toward it (via `deliver`
+ * → `onWake` → `send` effect on a persistent+direct agent) would be
+ * silently dropped. The queued message rides the `onExit` drain-then-
+ * spawn path instead.
+ */
+ enqueueRewake(agentId: string, message: AgentMsg): void {
+ this.dispatch({ type: "rewake_after_reset", agentId, message });
+ }
+
+ /**
+ * Mark the agent as being in a reset window (`resetting = true`). Every
+ * subsequent non-idle wake queues to inbox instead of steering the dying
+ * session or spawning a duplicate — see `onWake` in managerPolicy. The
+ * flag clears automatically on `onExit` (kill-and-respawn path) and on
+ * `onSpawned` (idle-branch spawn path); the runtime does not dispatch an
+ * explicit "end reset" event.
+ */
+ markResetting(agentId: string): void {
+ this.dispatch({ type: "begin_reset", agentId });
+ }
+
+ /**
+ * Owner-triggered synchronous reset. Orchestrates the "kill and rewake"
+ * flow atomically:
+ * 1. `register` — idempotent; ensures the FSM knows the agent and its
+ * runtime caps (fresh daemon after restart, bot never woken since).
+ * 2. `forgetSession` — clears resume caches + writes the timeline
+ * barrier; nulls `AgentState.sessionId` via the reset_session event.
+ * 3. `markResetting` — flips `agent.resetting = true` so any wake that
+ * lands between here and the reset spawn just enqueues to inbox
+ * (no steer against the dying session, no duplicate spawn).
+ * 4. If idle: `deliver` — emits `spawn` for a fresh session with the
+ * rewake as the prompt. `resetting` is cleared by `onSpawned`.
+ * 5. If live/starting/stopping: `enqueueRewake` (no effect) then
+ * `stop`. The `exit` event fires later; `onExit` drains the inbox
+ * (rewake + any queued unreads) into a single fresh spawn and clears
+ * `resetting`.
+ *
+ * Steps 1–3 (and 4/5's initial dispatch) are all synchronous reducer
+ * dispatches inside a single Node tick — no incoming wake can interleave
+ * before `resetting = true` is set. Only `await stop()` yields the event
+ * loop; by then the gate is up.
+ */
+ async resetSession(
+ agentId: string,
+ opts: { runtimeConfig: RuntimeConfig; launchId: string; rewakePrompt: string },
+ ): Promise<void> {
+ this.register(agentId, { runtimeConfig: opts.runtimeConfig, launchId: opts.launchId });
+ this.forgetSession(agentId);
+ this.markResetting(agentId);
+ const status = this.state.agents[agentId]?.status;
+ if (status === "idle") {
+ // Idle branch: `deliver` emits a spawn directly via `onWake`. The
+ // resetting gate exempts idle so this fires; any real unread that
+ // races in during the same tick sees status=`starting` (post-spawn
+ // effect) and hits the gate, queueing to inbox for the same drain.
+ //
+ // `doSpawn` can throw synchronously (missing credentialProxy /
+ // sdkDriverDepsFor, or the driver's constructor throwing). Without a
+ // recovery step, the FSM would be stuck at `starting` with
+ // `resetting=true` forever — every subsequent wake would hit the
+ // non-idle gate and queue to inbox instead of respawning. Dispatch an
+ // `exit` so `onExit` clears `resetting` and returns the agent to `idle`,
+ // ready for the next wake.
+ try {
+ this.deliver(agentId, { text: opts.rewakePrompt });
+ } catch (err) {
+ this.log.error("agent reset idle-branch spawn threw synchronously", {
+ agentId,
+ err: err instanceof Error ? err.message : String(err),
+ });
+ this.dispatch({ type: "exit", agentId });
+ throw err;
+ }
+ return;
+ }
+ // Live / starting / stopping: enqueue the rewake so `onExit`'s drain
+ // picks it up. `stop()` yields the event loop; any inbound wake in the
+ // interim hits the gate and queues to inbox — landing in the SAME
+ // drain-and-spawn as the rewake.
+ this.enqueueRewake(agentId, { text: opts.rewakePrompt });
+ await this.stop(agentId);
+ }
+
start(): void {
if (this.tickTimer) return;
this.tickTimer = setInterval(() => this.dispatch({ type: "tick", nowMs: this.now() }), this.opts.tickIntervalMs);
diff --git a/src/daemon/src/manager/managerTimeline.test.ts b/src/daemon/src/manager/managerTimeline.test.ts
index 13d6a14ec..bf95b448d 100644
--- a/src/daemon/src/manager/managerTimeline.test.ts
+++ b/src/daemon/src/manager/managerTimeline.test.ts
@@ -9,6 +9,7 @@ function fakeRecorder(resume: Record<string, string> = {}) {
setSession: (agentId, sessionId) => calls.push(`session:${agentId}:${sessionId}`),
appendResponseToLatest: (agentId, text) => calls.push(`resp:${agentId}:${text}`),
resumeSessionId: (agentId) => resume[agentId] ?? null,
+ forgetSession: (agentId) => calls.push(`forget:${agentId}`),
};
return { rec, calls };
}
@@ -72,4 +73,132 @@ describe("manager ↔ timeline (daily log + resume)", () => {
mgr.deliver("agent_2", { seq: 1, text: "hi" });
expect(cap.ctx?.config.sessionId).toBe("sess-prev");
});
+
+ it("forgetSession clears resume caches so the next spawn resolves to null", () => {
+ // Recorder returns null after "forgetSession" would have cleared the barrier.
+ const { rec, calls } = fakeRecorder({ agent_3: "sess-old" });
+ const cap: { ctx?: LaunchContext } = {};
+ const { mgr } = manager(rec, cap);
+ mgr.register("agent_3", { sessionId: "sess-server", launchId: "l1" });
+ // Reset happens before deliver — after forget the recorder returns null.
+ mgr.forgetSession("agent_3");
+ // Simulate the recorder's post-forget behavior for the next resolve.
+ (rec as unknown as { resumeSessionId: (a: string) => string | null }).resumeSessionId = () => null;
+ mgr.deliver("agent_3", { seq: 1, text: "hi" });
+
+ expect(calls).toContain("forget:agent_3");
+ expect(cap.ctx?.config.sessionId).toBeUndefined();
+ });
+
+ it("forgetSession is a no-op on an unknown agentId (no throw)", () => {
+ const { rec } = fakeRecorder();
+ const cap: { ctx?: LaunchContext } = {};
+ const { mgr } = manager(rec, cap);
+ expect(() => mgr.forgetSession("nobody")).not.toThrow();
+ });
+});
+
+describe("manager.resetSession", () => {
+ const RUNTIME_CFG = {
+ version: 1 as const,
+ runtime: "mock",
+ model: { kind: "default" as const },
+ mode: { kind: "default" as const },
+ };
+
+ it("idle path: register → forgetSession → deliver rewake; spawn fires with sessionId=undefined and rewake prompt", async () => {
+ const { rec, calls } = fakeRecorder();
+ const cap: { ctx?: LaunchContext } = {};
+ const { mgr } = manager(rec, cap);
+ // Post-forget the recorder returns null.
+ (rec as unknown as { resumeSessionId: (a: string) => string | null }).resumeSessionId = () => null;
+
+ await mgr.resetSession("agent_idle", {
+ runtimeConfig: RUNTIME_CFG,
+ launchId: "reset-1",
+ rewakePrompt: "REWAKE_TEXT",
+ });
+
+ expect(calls).toContain("forget:agent_idle");
+ expect(cap.ctx?.config.sessionId).toBeUndefined();
+ expect(cap.ctx?.prompt).toBe("REWAKE_TEXT");
+ // The FSM lands in `starting` (spawn effect ran).
+ const snap = mgr.snapshot();
+ expect(snap.agents.agent_idle.resetting).toBe(false); // idle branch: onSpawned would clear; but spawned hasn't fired yet — this test just proves the effect fired.
+ // Actually resetting is cleared only on spawned, which we haven't emitted;
+ // still, correctness is proved by the spawn effect firing (ctx captured).
+ });
+
+ it("running path: enqueues rewake, calls stop, and on exit event drains inbox into ONE fresh spawn with sessionId=undefined", async () => {
+ const { rec } = fakeRecorder();
+ // Track handlers/sends per session; a new session is created on each spawn.
+ const sessionsCreated: Array<{
+ ctx: LaunchContext;
+ handlers: Record<string, ((arg?: unknown) => void)[]>;
+ stopCalled: boolean;
+ sends: Array<{ text: string; mode: string }>;
+ }> = [];
+ const mgr = new AgentProcessManager({
+ driverFor: () =>
+ ({ lifecycle: { kind: "persistent" }, supportsStdinNotification: true, busyDeliveryMode: "direct" }) as never,
+ baseContextFor: (agentId) => ({ agentId, workingDirectory: "/tmp/x", standingPrompt: "", config: {} }),
+ sessionFactory: ({ ctx }) => {
+ const entry: (typeof sessionsCreated)[number] = { ctx, handlers: {}, stopCalled: false, sends: [] };
+ sessionsCreated.push(entry);
+ return {
+ on: (ev: string, cb: (arg?: unknown) => void) => ((entry.handlers[ev] ??= []).push(cb)),
+ get currentSessionId() {
+ return null;
+ },
+ async start() {},
+ send(m: { text: string; mode: "busy" | "idle" }) {
+ entry.sends.push({ text: m.text, mode: m.mode });
+ return { ok: true };
+ },
+ async stop() {
+ entry.stopCalled = true;
+ },
+ };
+ },
+ timeline: rec,
+ tickIntervalMs: 10_000,
+ });
+ (rec as unknown as { resumeSessionId: (a: string) => string | null }).resumeSessionId = () => null;
+
+ mgr.register("agent_run", { runtimeConfig: RUNTIME_CFG, launchId: "l0" });
+ mgr.deliver("agent_run", { text: "first" });
+ // Wait for start() microtask so `spawned` dispatch has landed.
+ await Promise.resolve();
+ await Promise.resolve();
+
+ expect(sessionsCreated).toHaveLength(1);
+ const first = sessionsCreated[0]!;
+ expect(mgr.snapshot().agents.agent_run.status).toBe("running");
+
+ const resetPromise = mgr.resetSession("agent_run", {
+ runtimeConfig: RUNTIME_CFG,
+ launchId: "reset-1",
+ rewakePrompt: "REWAKE",
+ });
+ await resetPromise;
+
+ // stop() was called on the live session; no `send` was ever emitted
+ // toward it (live branch uses enqueueRewake, not deliver).
+ expect(first.stopCalled).toBe(true);
+ expect(first.sends).toEqual([]);
+ // Second session hasn't been created yet — waits for exit event.
+ expect(sessionsCreated).toHaveLength(1);
+ expect(mgr.snapshot().agents.agent_run.resetting).toBe(true);
+ expect(mgr.snapshot().agents.agent_run.inbox.map((m) => m.text)).toEqual(["REWAKE"]);
+
+ // Fire the session exit → onExit drains rewake into a fresh spawn.
+ first.handlers["exit"]!.forEach((h) => h());
+ await Promise.resolve();
+
+ expect(sessionsCreated).toHaveLength(2);
+ const second = sessionsCreated[1]!;
+ expect(second.ctx.prompt).toContain("REWAKE");
+ expect(second.ctx.config.sessionId).toBeUndefined();
+ expect(mgr.snapshot().agents.agent_run.resetting).toBe(false);
+ });
});
diff --git a/src/daemon/src/timeline/recorder.test.ts b/src/daemon/src/timeline/recorder.test.ts
index 0be6c8db6..9420c6e8d 100644
--- a/src/daemon/src/timeline/recorder.test.ts
+++ b/src/daemon/src/timeline/recorder.test.ts
@@ -111,3 +111,143 @@ describe("createTimelineRecorder (append-only, 4-field schema)", () => {
expect(rec.resumeSessionId("a", "claude")).toBe("sess-claude");
});
});
+
+describe("forgetSession — inline system row", () => {
+ it("appends a bare reset_session system row (no forgot_session_id) and clears the map", () => {
+ const dir = mkDir();
+ const rec = createTimelineRecorder({ timelineDirFor: () => dir, providerFor: () => "claude", now: NOW });
+ rec.setSession("agent_1", "sess-1");
+
+ rec.forgetSession("agent_1");
+ const rows = readRecentEntries(dir, { now: NOW() });
+ const last = rows[rows.length - 1];
+ expect(last.system?.type).toBe("reset_session");
+ expect((last.system as unknown as { forgot_session_id?: unknown }).forgot_session_id).toBeUndefined();
+ expect(last.session_id).toBeNull();
+ expect(last.messages).toEqual([]);
+ expect(last.agent_responses).toEqual([]);
+
+ // A subsequent append proves the in-memory session id was cleared —
+ // the new turn row carries null for session_id.
+ rec.appendEntryForAgent("agent_1", [msg("#1", "post-reset")]);
+ const afterRows = readRecentEntries(dir, { now: NOW() });
+ expect(afterRows[afterRows.length - 1].session_id).toBeNull();
+ });
+
+ it("writes a valid reset_session row on a fresh workdir with no in-memory session and no prior rows", () => {
+ const dir = mkDir();
+ const rec = createTimelineRecorder({ timelineDirFor: () => dir, providerFor: () => "claude", now: NOW });
+
+ rec.forgetSession("agent_1");
+ const rows = readRecentEntries(dir, { now: NOW() });
+ expect(rows).toHaveLength(1);
+ expect(rows[0].system?.type).toBe("reset_session");
+ });
+});
+
+describe("appendResponseToLatest — text-before-first-pull fallback", () => {
+ it("after a reset barrier, a text event before the first inbox pull opens a fresh turn row (does NOT clobber the barrier)", () => {
+ const dir = mkDir();
+ const rec = createTimelineRecorder({ timelineDirFor: () => dir, providerFor: () => "claude", now: NOW });
+
+ rec.setSession("a", "sess-1");
+ rec.appendEntryForAgent("a", [msg("#1", "hi")]);
+ rec.appendResponseToLatest("a", "old reply");
+
+ // Owner-triggered reset — barrier is the newest line now.
+ rec.forgetSession("a");
+
+ // Fresh spawn: session_init lands, then a text event BEFORE the agent
+ // pulls its inbox.
+ rec.setSession("a", "sess-2");
+ rec.appendResponseToLatest("a", "I'll check for unfinished work.");
+
+ const rows = readRecentEntries(dir, { now: NOW() });
+ // Row 0: original turn — untouched.
+ expect(rows[0].messages.map((m) => m.content.text)).toEqual(["hi"]);
+ expect(rows[0].agent_responses).toEqual(["old reply"]);
+ // Row 1: the barrier — MUST NOT carry the response.
+ expect(rows[1].system?.type).toBe("reset_session");
+ expect(rows[1].agent_responses).toEqual([]);
+ // Row 2: the fallback turn row, opened by appendResponseToLatest.
+ expect(rows[2].system).toBeUndefined();
+ expect(rows[2].session_id).toBe("sess-2");
+ expect(rows[2].provider).toBe("claude");
+ expect(rows[2].messages).toEqual([]);
+ expect(rows[2].agent_responses).toEqual(["I'll check for unfinished work."]);
+ });
+
+ it("subsequent inbox pull appends its OWN turn row (fallback row has a response, so appendOrMergeEntry won't merge)", () => {
+ const dir = mkDir();
+ const rec = createTimelineRecorder({ timelineDirFor: () => dir, providerFor: () => "claude", now: NOW });
+
+ rec.forgetSession("a"); // barrier
+ rec.setSession("a", "sess-2");
+ rec.appendResponseToLatest("a", "pre-pull chatter");
+ // Now the fresh spawn actually pulls inbox.
+ rec.appendEntryForAgent("a", [msg("#1", "unread")]);
+ rec.appendResponseToLatest("a", "post-pull reply");
+
+ const rows = readRecentEntries(dir, { now: NOW() });
+ // [barrier, fallback, pull]
+ expect(rows).toHaveLength(3);
+ expect(rows[0].system?.type).toBe("reset_session");
+ expect(rows[1].agent_responses).toEqual(["pre-pull chatter"]);
+ expect(rows[1].messages).toEqual([]);
+ expect(rows[2].messages.map((m) => m.content.text)).toEqual(["unread"]);
+ expect(rows[2].agent_responses).toEqual(["post-pull reply"]);
+ });
+
+ it("first-ever text event with no prior rows opens a fallback turn row", () => {
+ const dir = mkDir();
+ const rec = createTimelineRecorder({ timelineDirFor: () => dir, providerFor: () => "claude", now: NOW });
+
+ rec.setSession("a", "sess-1");
+ rec.appendResponseToLatest("a", "hello");
+
+ const rows = readRecentEntries(dir, { now: NOW() });
+ expect(rows).toHaveLength(1);
+ expect(rows[0].session_id).toBe("sess-1");
+ expect(rows[0].agent_responses).toEqual(["hello"]);
+ expect(rows[0].messages).toEqual([]);
+ });
+});
+
+describe("resumeSessionId honors the reset_session barrier", () => {
+ it("multi-turn survival: three rows all carrying sess-1 then reset → null", () => {
+ const dir = mkDir();
+ const rec = createTimelineRecorder({ timelineDirFor: () => dir, providerFor: () => "claude", now: NOW });
+ rec.setSession("a", "sess-1");
+ rec.appendEntryForAgent("a", [msg("#1", "t1")]);
+ rec.appendResponseToLatest("a", "r1");
+ rec.appendEntryForAgent("a", [msg("#2", "t2")]);
+ rec.appendResponseToLatest("a", "r2");
+ rec.appendEntryForAgent("a", [msg("#3", "t3")]);
+ rec.appendResponseToLatest("a", "r3");
+ rec.forgetSession("a");
+
+ expect(rec.resumeSessionId("a", "claude")).toBeNull();
+ });
+
+ it("future sessions unaffected: reset + newer row carrying sess-2 → returns sess-2", () => {
+ const dir = mkDir();
+ const rec = createTimelineRecorder({ timelineDirFor: () => dir, providerFor: () => "claude", now: NOW });
+ rec.setSession("a", "sess-1");
+ rec.appendEntryForAgent("a", [msg("#1", "old")]);
+ rec.appendResponseToLatest("a", "reply1");
+ rec.forgetSession("a");
+ rec.setSession("a", "sess-2");
+ rec.appendEntryForAgent("a", [msg("#2", "fresh")]);
+
+ expect(rec.resumeSessionId("a", "claude")).toBe("sess-2");
+ });
+
+ it("no reset → unchanged behavior (returns newest non-null session_id)", () => {
+ const dir = mkDir();
+ const rec = createTimelineRecorder({ timelineDirFor: () => dir, providerFor: () => "claude", now: NOW });
+ rec.setSession("a", "sess-only");
+ rec.appendEntryForAgent("a", [msg("#1", "x")]);
+
+ expect(rec.resumeSessionId("a", "claude")).toBe("sess-only");
+ });
+});
diff --git a/src/daemon/src/timeline/recorder.ts b/src/daemon/src/timeline/recorder.ts
index 703b1bf80..7f28cea58 100644
--- a/src/daemon/src/timeline/recorder.ts
+++ b/src/daemon/src/timeline/recorder.ts
@@ -21,9 +21,18 @@
* agent_responses, provider}` — no task id / datetime / status / pid.
*/
import { mkdirSync } from "fs";
-import { appendOrMergeEntry, updateLatestEntry, readRecentEntries, createTimelineEntry, findResumableSession } from "./timeline.js";
+import {
+ appendOrMergeEntry,
+ updateLatestEntry,
+ readRecentEntries,
+ createTimelineEntry,
+ createSystemEntry,
+ findResumableSession,
+ appendEntry,
+} from "./timeline.js";
import type { Message } from "../server/contract.js";
+
/** Manager/daemon-facing recorder interface (structural, avoids a cyclic import). */
export interface TimelineRecorderLike {
/** CONTROL plane: remember the runtime session id (baked into new entries). */
@@ -34,6 +43,15 @@ export interface TimelineRecorderLike {
appendResponseToLatest(agentId: string, text: string): void;
/** 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.
+ */
+ forgetSession(agentId: string): void;
}
export interface TimelineRecorderOptions {
@@ -74,11 +92,49 @@ export function createTimelineRecorder(opts: TimelineRecorderOptions): TimelineR
);
},
appendResponseToLatest(agentId, text) {
- updateLatestEntry(dirFor(agentId), (e) => e.agent_responses.push(text), { now: now() });
+ const dir = dirFor(agentId);
+ const updated = updateLatestEntry(dir, (e) => e.agent_responses.push(text), { now: now() });
+ if (updated) return;
+ // No turn row exists yet (or the newest row is a system barrier) — open
+ // a fresh, empty-messages turn row carrying the current session/provider
+ // and stamp this response onto it. Happens whenever a `text` event
+ // arrives before the fresh spawn's first inbox pull opened a row, e.g.
+ // right after `reset_session` where the barrier is the file's latest
+ // line and the rewake prompt makes the agent talk before pulling. A
+ // later inbox pull with real messages appends its own row (since this
+ // one already has a response, `appendOrMergeEntry` won't merge into it).
+ try {
+ mkdirSync(dir, { recursive: true });
+ } catch {
+ /* best-effort */
+ }
+ const entry = createTimelineEntry({
+ messages: [],
+ sessionId: sessionByAgent.get(agentId) ?? null,
+ provider: opts.providerFor?.(agentId) ?? null,
+ });
+ entry.agent_responses.push(text);
+ appendEntry(dir, entry, now());
},
resumeSessionId(agentId, provider) {
const rows = readRecentEntries(dirFor(agentId), { now: now() });
return findResumableSession(rows, provider ?? undefined);
},
+ forgetSession(agentId) {
+ const dir = dirFor(agentId);
+ try {
+ mkdirSync(dir, { recursive: true });
+ } catch {
+ /* best-effort — appendEntry handles a missing dir by returning false */
+ }
+ // Kill happens BEFORE this call (see `AgentProcessManager.resetSession`),
+ // so no race — clear the in-memory session map and append the barrier.
+ // One `now()` sample so the system-row `time` and the day-file the row
+ // is written into can't disagree on the boundary between two consecutive
+ // clock reads.
+ sessionByAgent.delete(agentId);
+ const stamp = now();
+ appendEntry(dir, createSystemEntry("reset_session", stamp.toISOString()), stamp);
+ },
};
}
diff --git a/src/daemon/src/timeline/timeline.test.ts b/src/daemon/src/timeline/timeline.test.ts
index 95c52f500..7cce442d7 100644
--- a/src/daemon/src/timeline/timeline.test.ts
+++ b/src/daemon/src/timeline/timeline.test.ts
@@ -8,6 +8,7 @@ import {
updateLatestEntry,
readRecentEntries,
createTimelineEntry,
+ createSystemEntry,
findResumableSession,
filenameForDate,
localISOString,
@@ -98,6 +99,27 @@ describe("updateLatestEntry", () => {
const dir = mkDir();
expect(updateLatestEntry(dir, () => {}, { now: NOW })).toBe(false);
});
+
+ it("returns false when the newest row is a system barrier (does NOT walk past it into a pre-barrier turn)", () => {
+ const dir = mkDir();
+ appendEntry(dir, createTimelineEntry({ messages: [msg("a")], sessionId: "s1", provider: "claude" }), NOW);
+ appendEntry(dir, createSystemEntry("reset_session", "2026-06-25T12:00:00Z"), NOW);
+ let mutated = false;
+ const ok = updateLatestEntry(dir, () => { mutated = true; }, { now: NOW });
+ expect(ok).toBe(false);
+ expect(mutated).toBe(false);
+ const rows = readRecentEntries(dir, { now: NOW });
+ // Neither row was touched — barrier stays clean, pre-barrier turn stays clean.
+ expect(rows[0].agent_responses).toEqual([]);
+ expect(rows[1].system?.type).toBe("reset_session");
+ expect(rows[1].agent_responses).toEqual([]);
+ });
+
+ it("returns false when the file has only system rows (no turn row to update)", () => {
+ const dir = mkDir();
+ appendEntry(dir, createSystemEntry("reset_session", "2026-06-25T12:00:00Z"), NOW);
+ expect(updateLatestEntry(dir, () => {}, { now: NOW })).toBe(false);
+ });
});
describe("findResumableSession", () => {
@@ -121,6 +143,42 @@ describe("findResumableSession", () => {
const rows = [{ ...createTimelineEntry({ messages: [], provider: "claude" }) }];
expect(findResumableSession(rows)).toBeNull();
});
+
+ it("stops on a reset_session barrier row and returns null", () => {
+ const rows = [
+ { ...createTimelineEntry({ messages: [], provider: "claude", sessionId: "s-old" }) },
+ { ...createTimelineEntry({ messages: [], provider: "claude", sessionId: "s-old" }) },
+ createSystemEntry("reset_session", "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" }) },
+ createSystemEntry("reset_session", "2026-06-25T12:00:00Z"),
+ { ...createTimelineEntry({ messages: [], provider: "claude", sessionId: "s-new" }) },
+ ];
+ expect(findResumableSession(rows)).toBe("s-new");
+ });
+
+ it("multiple resets: newest barrier stops the walk", () => {
+ const rows = [
+ { ...createTimelineEntry({ messages: [], provider: "claude", sessionId: "s-1" }) },
+ createSystemEntry("reset_session", "2026-06-25T12:00:00Z"),
+ { ...createTimelineEntry({ messages: [], provider: "claude", sessionId: "s-2" }) },
+ createSystemEntry("reset_session", "2026-06-25T12:01:00Z"),
+ ];
+ expect(findResumableSession(rows)).toBeNull();
+ });
+
+ it("provider constraint respected across a barrier", () => {
+ const rows = [
+ { ...createTimelineEntry({ messages: [], provider: "claude", sessionId: "s-claude" }) },
+ createSystemEntry("reset_session", "2026-06-25T12:00:00Z"),
+ ];
+ expect(findResumableSession(rows, "claude")).toBeNull();
+ });
});
describe("localISOString", () => {
diff --git a/src/daemon/src/timeline/timeline.ts b/src/daemon/src/timeline/timeline.ts
index 27c6f4d08..d4b8ea351 100644
--- a/src/daemon/src/timeline/timeline.ts
+++ b/src/daemon/src/timeline/timeline.ts
@@ -14,7 +14,7 @@
import { appendFileSync, readFileSync, writeFileSync, renameSync, existsSync } from "fs";
import { join } from "path";
import { acquireLock, releaseLock, lockPathFor } from "./filelock.js";
-import type { ContextTimelineEntry } from "./types.js";
+import type { ContextTimelineEntry, SystemEntryType } from "./types.js";
import type { Message } from "../server/contract.js";
import { localISOString } from "../util/localTime.js";
@@ -136,6 +136,8 @@ export function appendOrMergeEntry(timelineDir: string, entry: ContextTimelineEn
if (lines.length > 0) {
const latest = JSON.parse(lines[lines.length - 1]) as ContextTimelineEntry;
const mergeable =
+ !latest.system &&
+ !entry.system &&
latest.session_id === entry.session_id &&
latest.provider === entry.provider &&
latest.agent_responses.length === 0;
@@ -158,12 +160,22 @@ export function appendOrMergeEntry(timelineDir: string, entry: ContextTimelineEn
}
/**
- * Mutate the MOST-RECENT entry (the last appended row in the newest day file)
- * via `updater`, rewriting that file atomically under lock. This is how the
- * control plane (manager) targets "the agent's current turn" without threading a
- * task id across layers — the data plane appended that row on the inbox pull that
- * opened the turn, so it is the latest when responses/end arrive. Returns true if
- * a row was updated. Searches the newest day file with any rows first.
+ * Mutate the MOST-RECENT TURN entry via `updater`, rewriting that file
+ * atomically under lock. This is how the control plane (manager) targets
+ * "the agent's current turn" without threading a task id across layers —
+ * the data plane appended that row on the inbox pull that opened the turn,
+ * so it is the latest turn row when responses/end arrive.
+ *
+ * A system row (e.g. `reset_session` barrier) STOPS the walk and this
+ * function returns false. Rationale: the barrier's semantics are
+ * "everything before me belongs to a dead session"; a response landing
+ * AFTER the barrier belongs to the NEW session and must NOT attach to a
+ * pre-barrier turn row. When a barrier is the newest row (or a barrier
+ * sits above every candidate turn row), returning false lets the caller
+ * open a fresh turn row post-barrier instead.
+ *
+ * Returns false when the newest day file's newest non-empty row is a
+ * system row, or there is no row at all.
*/
export function updateLatestEntry(
timelineDir: string,
@@ -191,7 +203,12 @@ export function updateLatestEntry(
const lines = content.trimEnd().split("\n").filter(Boolean);
if (lines.length === 0) continue;
const entries = lines.map((l) => JSON.parse(l) as ContextTimelineEntry);
- updater(entries[entries.length - 1]); // last appended = most recent
+ // The newest row of the newest day file is authoritative: if it's a
+ // system barrier, we must NOT walk past it into a pre-barrier turn.
+ // Return false and let the caller open a fresh post-barrier turn row.
+ const latest = entries[entries.length - 1];
+ if (latest.system) return false;
+ updater(latest);
const tmpPath = join(timelineDir, `.${filename}.tmp`);
writeFileSync(tmpPath, entries.map((e) => JSON.stringify(e)).join("\n") + "\n");
renameSync(tmpPath, filePath);
@@ -226,21 +243,48 @@ export function createTimelineEntry(fields: NewEntryFields): ContextTimelineEntr
};
}
+/**
+ * Build a system entry. System rows are inlined in the JSONL alongside turns
+ * so the resume walker and any agent-facing reader see them in place. The
+ * first (and only) type today is `reset_session`.
+ */
+export function createSystemEntry(
+ type: SystemEntryType,
+ time: string,
+): ContextTimelineEntry {
+ return {
+ session_id: null,
+ messages: [],
+ agent_responses: [],
+ provider: null,
+ system: { type, time },
+ };
+}
+
/* ------------------------------------------------------------------ */
/* Queries (pure over already-read rows) */
/* ------------------------------------------------------------------ */
/**
* The agent's most recent session id — the resume target so its next launch
- * continues the prior runtime session. `rows` are in time order (readRecentEntries
- * preserves day-file order = append order = time order), so the resume target is
- * simply the LAST row carrying a session_id, optionally constrained to a provider
- * (don't resume a claude session into a codex launch). One session per agent and
- * each timeline lives in that agent's own workdir, so there's no thread keying.
+ * continues the prior runtime session. `rows` are in time order
+ * (`readRecentEntries` preserves day-file order = append order = time order),
+ * so the resume target is simply the LAST row carrying a session_id,
+ * optionally constrained to a provider (don't resume a claude session into
+ * a codex launch). One session per agent and each timeline lives in that
+ * agent's own workdir, so there's no thread keying.
+ *
+ * A `system: { type: "reset_session" }` row is a barrier: the walker returns
+ * null the moment it hits one going newest→oldest. Every turn at or before
+ * the reset becomes invisible to resume without editing those rows. Since
+ * kill happens BEFORE the barrier is written (see
+ * `AgentProcessManager.resetSession`), no `forgot_session_id` fallback is
+ * needed — no turn row can land after the barrier from the old session.
*/
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;
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.ts
index 61def4de5..eedff743c 100644
--- a/src/daemon/src/timeline/types.ts
+++ b/src/daemon/src/timeline/types.ts
@@ -16,23 +16,49 @@
import type { Message } from "../server/contract.js";
/**
- * A timeline row — exactly four fields (gustavo's final schema). Per-turn
- * history: what the agent SAW (`messages`, with their own timestamps) and what it
- * SAID (`agent_responses`), the runtime `session_id` (resume target), and the
- * `provider` that ran it. No task_id / datetime / status / pid / errmsg — the
- * log is append-only and time is carried by the messages themselves.
+ * A timeline row. Two shapes share the file, discriminated by `system`:
+ *
+ * - **Turn** (`system` absent): per-turn history — what the agent SAW
+ * (`messages`, with their own timestamps) and what it SAID
+ * (`agent_responses`), the runtime `session_id` (resume target), and the
+ * `provider` that ran it. The append-only log is time-ordered; each
+ * message carries its own `time`.
+ * - **System** (`system` set): an out-of-band event the daemon needs to
+ * record in-line with turns so both the resume walker AND the agent's
+ * own history read see it. First (and only) type today is
+ * `reset_session`: the owner asked to forget prior conversation. On
+ * resume, `findResumableSession` walks newest→oldest and STOPS if it
+ * hits a `reset_session` row before finding a session id — so every
+ * row at or before the reset is invisible for resume without touching
+ * the rows themselves.
+ *
+ * On a system row, `session_id`/`provider` are null and `messages`/
+ * `agent_responses` are empty. The system row is not mergeable with a
+ * following turn (see `appendOrMergeEntry`).
*/
+export type SystemEntryType = "reset_session";
+
+export interface SystemEntry {
+ /** Event kind. Extend by adding to `SystemEntryType`. */
+ type: SystemEntryType;
+ /** ISO timestamp when the event landed — the row is otherwise untimed. */
+ time: string;
+}
+
export interface ContextTimelineEntry {
- /** Agent runtime session id (null until the runtime reports session_init). */
+ /** Agent runtime session id (null until the runtime reports session_init; always null on system rows). */
session_id: string | null;
/**
* The messages the agent actually saw this turn — the verbatim payload of the
* `inbox pull` that opened this entry ("what I saw"), read against
* `agent_responses` ("what I said"). Carries each message's own `time`.
+ * Empty on system rows.
*/
messages: Message[];
- /** The agent's text outputs this turn ("what I said"). */
+ /** The agent's text outputs this turn ("what I said"). Empty on system rows. */
agent_responses: string[];
- /** Runtime id this turn ran under (resume can be constrained to a provider). */
+ /** Runtime id this turn ran under (resume can be constrained to a provider). Null on system rows. */
provider: string | null;
+ /** Present iff this row is a system event, not a turn. */
+ system?: SystemEntry;
}
diff --git a/src/shared/src/community-cli-contract.ts b/src/shared/src/community-cli-contract.ts
index 750506871..c58dd5ac9 100644
--- a/src/shared/src/community-cli-contract.ts
+++ b/src/shared/src/community-cli-contract.ts
@@ -529,6 +529,14 @@ export type HostCommand =
unreadNotice: UnreadNotice;
}
| { type: "agent:stop"; agentId: AgentId }
+ /**
+ * Owner-triggered reset. Carries `config` because the daemon may not have
+ * this agent registered yet (fresh daemon, bot never woken since last
+ * restart). Daemon MUST `register` the agent, write a `reset_session`
+ * system row to the timeline, kill any running process, and deliver a
+ * synthetic rewake — see `AgentProcessManager.resetSession`.
+ */
+ | { type: "agent:reset"; agentId: AgentId; config: RuntimeConfig; launchId: string }
// ─── Bot lifecycle events (server → daemon) ────────────────────────────
// Colon-namespaced to match the agent:* naming convention. Delivered to
// the specific machine's daemon connection via the WS DO. On the daemon,
diff --git a/src/shared/src/community-ws-events.ts b/src/shared/src/community-ws-events.ts
index 73b0fa8bb..d7e4f84ae 100644
--- a/src/shared/src/community-ws-events.ts
+++ b/src/shared/src/community-ws-events.ts
@@ -460,7 +460,7 @@ export type CommunityBotAuditEvent = {
type: "community:bot.audit_event"
botId: string
id: string
- kind: "cli_invocation" | "tool_call" | "thinking"
+ kind: "cli_invocation" | "tool_call" | "thinking" | "wake_trigger" | "session_reset"
payload: unknown
sessionId?: string | null
launchId?: string | null
diff --git a/src/shared/src/community/wake-dispatch.ts b/src/shared/src/community/wake-dispatch.ts
index d330e89be..886eea81a 100644
--- a/src/shared/src/community/wake-dispatch.ts
+++ b/src/shared/src/community/wake-dispatch.ts
@@ -103,7 +103,11 @@ export type SkipReason =
| "already_read";
export type BuildUnreadWakeResult =
- | { state: "ready"; machineId: string; command: HostCommand }
+ | {
+ state: "ready";
+ machineId: string;
+ command: HostCommand;
+ }
| { state: "skip"; reason: SkipReason };
/**
@@ -167,6 +171,7 @@ export async function buildUnreadWakeCommand(
agentName: botCtx.name,
agentHandle: `@${formatHandle(botCtx.name, botCtx.discriminator)}`,
});
+
const command: HostCommand = {
type: "agent:wake",
agentId: botCtx.botUserId,
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 8d32b57c5..930837089 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";
+ kind: "cli_invocation" | "tool_call" | "thinking" | "wake_trigger" | "session_reset";
payload: string;
};
@@ -198,3 +198,24 @@ export async function insertBotAuditWakeTrigger(
payload: JSON.stringify(data.payload),
});
}
+
+/**
+ * Session-reset audit write — the owner clicked "Reset session" on a bot in
+ * `/c/me/bots`. Actor is the owner (own by construction on the API route).
+ * Payload is intentionally empty — the fact of the reset is the audit signal;
+ * timestamp lives on the envelope. Gated on the "was the row newly-pending?"
+ * transition at the API route, so a repeat-click while a reset is already
+ * pending never lands a second row.
+ */
+export async function insertBotAuditSessionReset(
+ db: Database,
+ data: { botId: string; actorId: string }
+): Promise<{ id: string; createdAt: string } | null> {
+ return insertBotActivityEventAndPrune(db, {
+ botId: data.botId,
+ sessionId: null,
+ launchId: null,
+ kind: "session_reset",
+ payload: JSON.stringify({}),
+ });
+}
diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.ts
index cdf1ad391..7b14cd034 100644
--- a/src/shared/src/schemas.ts
+++ b/src/shared/src/schemas.ts
@@ -1281,11 +1281,15 @@ export const AuditLogWakeTriggerPayloadSchema = z.object({
});
export type AuditLogWakeTriggerPayload = z.infer<typeof AuditLogWakeTriggerPayloadSchema>;
+export const AuditLogSessionResetPayloadSchema = z.object({});
+export type AuditLogSessionResetPayload = z.infer<typeof AuditLogSessionResetPayloadSchema>;
+
export const BotAuditEventSchema = z.discriminatedUnion("kind", [
z.object({ kind: z.literal("cli_invocation"), payload: AuditLogCliInvocationPayloadSchema }),
z.object({ kind: z.literal("tool_call"), payload: AuditLogToolCallPayloadSchema }),
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 }),
]);
export type BotAuditEvent = z.infer<typeof BotAuditEventSchema>;
@@ -1294,6 +1298,7 @@ export const BotAuditEventKindSchema = z.enum([
"tool_call",
"thinking",
"wake_trigger",
+ "session_reset",
]);
export type BotAuditEventKind = z.infer<typeof BotAuditEventKindSchema>;
diff --git a/src/shared/test/community/wake-dispatch-build.test.ts b/src/shared/test/community/wake-dispatch-build.test.ts
index 2c0250c31..b32f0674a 100644
--- a/src/shared/test/community/wake-dispatch-build.test.ts
+++ b/src/shared/test/community/wake-dispatch-build.test.ts
@@ -109,6 +109,7 @@ describe("buildUnreadWakeCommand", () => {
agentId: "bot_1",
unreadNotice: { kind: "unread_notice", channel: "/srv_1/general", latestSeq: 7 },
});
+ if (result.command.type !== "agent:wake") throw new Error("expected agent:wake");
expect(typeof result.command.launchId).toBe("string");
expect(result.command.launchId.length).toBeGreaterThan(0);
expect(result.command).toMatchObject({ config: { runtime: "claude", agentHandle: "@zoe#0042" } });
@@ -122,10 +123,6 @@ describe("buildUnreadWakeCommand", () => {
});
it("ready: resolves a DM scope when the message has no channelId", async () => {
- // "/.dm/@gustavo" was never actually valid production output — prod never
- // puts "@" in a ref segment. `resolveUnreadNoticeChannel` now produces a
- // bare `name#0042` handle segment (mocked here, but shaped like the real
- // thing) since DM refs address peers by handle, not raw user id.
seedHappyPath({
message: { channelId: null, dmConversationId: "dm_1" },
channel: "/.dm/gustavo#0042",
@@ -135,6 +132,7 @@ describe("buildUnreadWakeCommand", () => {
expect(result.state).toBe("ready");
if (result.state !== "ready") throw new Error("expected ready");
+ if (result.command.type !== "agent:wake") throw new Error("expected agent:wake");
expect(result.command.unreadNotice).toEqual({
kind: "unread_notice",
channel: "/.dm/gustavo#0042",
@@ -152,9 +150,8 @@ describe("buildUnreadWakeCommand", () => {
expect(result.state).toBe("ready");
if (result.state !== "ready") throw new Error("expected ready");
+ if (result.command.type !== "agent:wake") throw new Error("expected agent:wake");
expect(result.command.unreadNotice.channel).toBe("/srv_1/general/#3");
- // Channel/thread wakes never carry dmConversationId — DM-only invariant
- // for the bot-typing indicator pipeline.
expect(result.command.unreadNotice.dmConversationId).toBeUndefined();
});
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
new file mode 100644
index 000000000..d95ef1fe0
--- /dev/null
+++ b/src/web/src/app/api/community/bots/[id]/reset-session/route.test.ts
@@ -0,0 +1,164 @@
+import { describe, it, expect, vi, beforeEach } from "vitest"
+import { NextRequest } from "next/server"
+
+const mockGetBotOwnedBy = vi.fn()
+const mockGetBotWakeContext = vi.fn()
+const mockInsertBotAuditSessionReset = vi.fn()
+const mockBroadcastToUser = vi.fn()
+const mockPushAgentResetToMachine = vi.fn()
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
+}))
+
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
+
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
+ return {
+ ...actual,
+ queries: {
+ communityBot: {
+ getBotOwnedBy: (...a: unknown[]) => mockGetBotOwnedBy(...a),
+ getBotWakeContext: (...a: unknown[]) => mockGetBotWakeContext(...a),
+ },
+ communityBotAuditLog: {
+ insertBotAuditSessionReset: (...a: unknown[]) => mockInsertBotAuditSessionReset(...a),
+ },
+ },
+ }
+})
+
+vi.mock("@/lib/broadcast", () => ({
+ broadcastToUser: (...a: unknown[]) => mockBroadcastToUser(...a),
+}))
+
+vi.mock("@/lib/community/bot-push", () => ({
+ pushAgentResetToMachine: (...a: unknown[]) => mockPushAgentResetToMachine(...a),
+}))
+
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: (handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params
+ return handler(req, { env: { DB: {} }, userId: ctx?.actor ?? "owner_1", email: "[email protected]", params })
+ },
+}))
+
+vi.mock("@/lib/middleware/helpers", async () => {
+ const { NextResponse } = require("next/server")
+ const actual = await vi.importActual<typeof import("@/lib/middleware/helpers")>("@/lib/middleware/helpers")
+ return {
+ ...actual,
+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),
+ writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),
+ }
+})
+
+import { POST } from "./route"
+
+function req() {
+ return new NextRequest("http://localhost/api/community/bots/b1/reset-session", {
+ method: "POST",
+ })
+}
+
+const ctx = { params: { id: "b1" } } as any
+
+const READY_CTX = {
+ state: "ready" as const,
+ botUserId: "b1",
+ name: "zoe",
+ discriminator: "0042",
+ machineId: "mac_1",
+ runtime: "claude",
+ ownerUserId: "owner_1",
+}
+
+function seedOwnedAndBound() {
+ mockGetBotOwnedBy.mockResolvedValue({ id: "b1", ownerUserId: "owner_1", machineId: "mac_1", runtime: "claude" })
+ mockGetBotWakeContext.mockResolvedValue(READY_CTX)
+}
+
+describe("POST /api/community/bots/[id]/reset-session", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it("non-owner → 404 (getBotOwnedBy already filters by ownerUserId) and never pushes / never touches audit", async () => {
+ mockGetBotOwnedBy.mockResolvedValue(null)
+
+ const res = await POST(req(), ctx)
+ expect(res.status).toBe(404)
+ expect(mockPushAgentResetToMachine).not.toHaveBeenCalled()
+ expect(mockInsertBotAuditSessionReset).not.toHaveBeenCalled()
+ expect(mockBroadcastToUser).not.toHaveBeenCalled()
+ })
+
+ it("bot has no active binding → 409 and never pushes / never touches audit", async () => {
+ mockGetBotOwnedBy.mockResolvedValue({ id: "b1", ownerUserId: "owner_1", machineId: null, runtime: null })
+
+ const res = await POST(req(), ctx)
+ expect(res.status).toBe(409)
+ expect(mockPushAgentResetToMachine).not.toHaveBeenCalled()
+ expect(mockInsertBotAuditSessionReset).not.toHaveBeenCalled()
+ })
+
+ it("bot wake context not ready (bot_unbound) → 409 and never pushes / never touches audit", async () => {
+ mockGetBotOwnedBy.mockResolvedValue({ id: "b1", ownerUserId: "owner_1", machineId: "mac_1", runtime: "claude" })
+ mockGetBotWakeContext.mockResolvedValue({ state: "bot_unbound" })
+
+ const res = await POST(req(), ctx)
+ expect(res.status).toBe(409)
+ expect(mockPushAgentResetToMachine).not.toHaveBeenCalled()
+ expect(mockInsertBotAuditSessionReset).not.toHaveBeenCalled()
+ })
+
+ it("owner + bound + daemon offline (sent:0) → 409 and never touches audit / never broadcasts", async () => {
+ seedOwnedAndBound()
+ mockPushAgentResetToMachine.mockResolvedValue({ sent: 0 })
+
+ const res = await POST(req(), ctx)
+ expect(res.status).toBe(409)
+ expect(mockPushAgentResetToMachine).toHaveBeenCalledTimes(1)
+ expect(mockInsertBotAuditSessionReset).not.toHaveBeenCalled()
+ expect(mockBroadcastToUser).not.toHaveBeenCalled()
+ })
+
+ it("owner + bound + daemon online (sent:1) → 200 with exactly one audit row + one broadcast", 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)
+ const body = await res.json() as { ok: boolean }
+ expect(body.ok).toBe(true)
+
+ expect(mockPushAgentResetToMachine).toHaveBeenCalledTimes(1)
+ const [_env, machineId, args] = mockPushAgentResetToMachine.mock.calls[0]!
+ expect(machineId).toBe("mac_1")
+ expect(args).toMatchObject({ agentId: "b1" })
+ expect(typeof args.launchId).toBe("string")
+ expect(args.launchId.length).toBeGreaterThan(0)
+ expect(args.config).toBeDefined()
+
+ expect(mockInsertBotAuditSessionReset).toHaveBeenCalledTimes(1)
+ expect(mockInsertBotAuditSessionReset).toHaveBeenCalledWith(expect.anything(), {
+ botId: "b1",
+ actorId: "owner_1",
+ })
+ expect(mockBroadcastToUser).toHaveBeenCalledTimes(1)
+ expect(mockBroadcastToUser).toHaveBeenCalledWith(
+ "owner_1",
+ expect.objectContaining({
+ type: "community:bot.audit_event",
+ kind: "session_reset",
+ botId: "b1",
+ }),
+ )
+ })
+})
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
new file mode 100644
index 000000000..397e106fc
--- /dev/null
+++ b/src/web/src/app/api/community/bots/[id]/reset-session/route.ts
@@ -0,0 +1,68 @@
+import { nanoid } from "nanoid"
+import { queries, makeRuntimeConfig, formatHandle, WS_EVENTS } 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.
+ */
+export const POST = withAuth(async (_req, ctx) => {
+ const id = ctx.params?.id as string
+ const db = getDb(ctx.env.DB)
+
+ const bot = await queries.communityBot.getBotOwnedBy(db, id, ctx.userId)
+ if (!bot) return writeError("bot not found", 404)
+
+ if (!bot.machineId) return writeError("bot has no active binding", 409)
+
+ const wakeCtx = await queries.communityBot.getBotWakeContext(db, id)
+ if (wakeCtx.state !== "ready") return writeError(wakeCtx.state, 409)
+
+ const config = makeRuntimeConfig({
+ runtime: wakeCtx.runtime,
+ agentName: wakeCtx.name,
+ agentHandle: `@${formatHandle(wakeCtx.name, wakeCtx.discriminator)}`,
+ })
+ const launchId = nanoid()
+
+ const { sent } = await pushAgentResetToMachine(ctx.env, bot.machineId, {
+ agentId: id,
+ config,
+ launchId,
+ })
+ if (sent === 0) {
+ 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) {
+ 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/components/community/bots/bot-activity-row.tsx b/src/web/src/components/community/bots/bot-activity-row.tsx
index fef9b4733..08bbf796e 100644
--- a/src/web/src/components/community/bots/bot-activity-row.tsx
+++ b/src/web/src/components/community/bots/bot-activity-row.tsx
@@ -56,6 +56,7 @@ function kindMeta(kind: AuditKind): { label: string; tone: string } {
if (kind === "cli_invocation") return { label: "daemon", tone: "text-foreground/70" }
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" }
return { label: "think", tone: "text-muted-foreground/70" }
}
@@ -96,6 +97,19 @@ function RowBody({
}
return <span className="font-mono text-[13px] text-foreground">{name}</span>
}
+ if (event.kind === "session_reset") {
+ return (
+ <div
+ data-testid="bot-activity-event-session_reset"
+ className="truncate font-mono text-[13px] text-foreground"
+ >
+ <span>Session reset requested</span>{" "}
+ <span className="text-muted-foreground">
+ — the bot will start a fresh session on its next message.
+ </span>
+ </div>
+ )
+ }
if (event.kind === "wake_trigger") {
const p = event.payload as {
channel?: string
diff --git a/src/web/src/components/community/bots/bot-list.tsx b/src/web/src/components/community/bots/bot-list.tsx
index 800c7c387..531b6338e 100644
--- a/src/web/src/components/community/bots/bot-list.tsx
+++ b/src/web/src/components/community/bots/bot-list.tsx
@@ -28,7 +28,7 @@ import {
import { AgentAvatar } from "@/components/avatar"
import { ProviderLogo } from "@/components/provider-logo"
import { useMachines } from "@/hooks/community/use-machines"
-import { useBots, useDeleteBot, type BotSummary } from "@/hooks/community/use-bots"
+import { useBots, useDeleteBot, useResetBotSession, type BotSummary } from "@/hooks/community/use-bots"
import { useCreateOrGetDm } from "@/hooks/community/mutations"
import { useOnlineUserIds } from "@/stores/community/ws"
import { CreateBotSheet } from "./create-bot-sheet"
@@ -65,7 +65,9 @@ export function BotList({ onBack }: { onBack?: () => void } = {}) {
const [activityBot, setActivityBot] = useState<BotSummary | null>(null)
const [activityOpen, setActivityOpen] = useState(false)
const [confirmDelete, setConfirmDelete] = useState<BotSummary | null>(null)
+ const [confirmReset, setConfirmReset] = useState<BotSummary | null>(null)
const del = useDeleteBot()
+ const resetSession = useResetBotSession()
const createOrGetDm = useCreateOrGetDm()
const chatWithBot = async (bot: BotSummary) => {
@@ -299,6 +301,12 @@ export function BotList({ onBack }: { onBack?: () => void } = {}) {
>
Edit
</DropdownMenuItem>
+ <DropdownMenuItem
+ data-testid={`bot-reset-session-item`}
+ onClick={() => setConfirmReset(bot)}
+ >
+ Reset
+ </DropdownMenuItem>
<DropdownMenuItem
variant="destructive"
onClick={() => setConfirmDelete(bot)}
@@ -360,6 +368,45 @@ export function BotList({ onBack }: { onBack?: () => void } = {}) {
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
+ <AlertDialog
+ open={!!confirmReset}
+ onOpenChange={(open) => !open && setConfirmReset(null)}
+ >
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Reset this bot&apos;s session?</AlertDialogTitle>
+ <AlertDialogDescription>
+ Its running process will stop and it&apos;ll start a fresh session
+ that picks up unfinished work from its notes.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction
+ data-testid="bot-reset-confirm"
+ onClick={async () => {
+ if (!confirmReset) return
+ try {
+ await resetSession.mutateAsync(confirmReset.id)
+ toast.success("Session reset.")
+ } catch (e) {
+ const status = (e as { status?: number } | undefined)?.status
+ const message = (e as { message?: string } | undefined)?.message ?? ""
+ if (status === 409 && message.toLowerCase().includes("offline")) {
+ toast.error("Bot is offline — bring it online before resetting.")
+ } else {
+ toastApiError(e, "Couldn't reset the bot's session")
+ }
+ } finally {
+ setConfirmReset(null)
+ }
+ }}
+ >
+ Reset
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
</div>
)
}
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 a0c454b6a..65baf6b2c 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"
+export type AuditKind = "cli_invocation" | "tool_call" | "thinking" | "wake_trigger" | "session_reset"
export type AuditEvent = {
id: string
diff --git a/src/web/src/hooks/community/use-bots.ts b/src/web/src/hooks/community/use-bots.ts
index 3372739d9..f51ab1d91 100644
--- a/src/web/src/hooks/community/use-bots.ts
+++ b/src/web/src/hooks/community/use-bots.ts
@@ -89,6 +89,22 @@ export function useDeleteBot() {
})
}
+export type ResetBotSessionResult = { ok: true }
+
+export function useResetBotSession() {
+ const qc = useQueryClient()
+ return useMutation({
+ mutationFn: (id: string) =>
+ apiFetch<ResetBotSessionResult>(
+ `/api/community/bots/${id}/reset-session`,
+ { method: "POST" },
+ ),
+ onSuccess: (_data, id) => {
+ qc.invalidateQueries({ queryKey: communityKeys.botAuditLog(id) })
+ },
+ })
+}
+
export type UploadBotAvatarArgs = { botId: string; file: File }
export type UploadBotAvatarResult = { url: string }
diff --git a/src/web/src/lib/community/bot-push.test.ts b/src/web/src/lib/community/bot-push.test.ts
new file mode 100644
index 000000000..ebb3568c0
--- /dev/null
+++ b/src/web/src/lib/community/bot-push.test.ts
@@ -0,0 +1,65 @@
+import { describe, it, expect, vi, beforeEach } from "vitest"
+
+const wsDoFetch = vi.fn()
+vi.mock("@/lib/broadcast", () => ({
+ wsDoFetch: (...a: unknown[]) => wsDoFetch(...a),
+}))
+
+import { pushAgentResetToMachine } from "./bot-push"
+
+const FAKE_ENV = { WS_DO_WORKER: {}, DEV_WS_DO_URL: undefined } as unknown as Env
+
+describe("pushAgentResetToMachine", () => {
+ beforeEach(() => {
+ wsDoFetch.mockReset()
+ })
+
+ const CFG = {
+ version: 1 as const,
+ runtime: "claude",
+ model: { kind: "default" as const },
+ mode: { kind: "default" as const },
+ }
+
+ it("POSTs to /forward-agent-reset with the narrow reset body and returns the ws-do { sent } count", async () => {
+ wsDoFetch.mockResolvedValue(new Response(JSON.stringify({ sent: 1 }), { status: 200 }))
+
+ const result = await pushAgentResetToMachine(FAKE_ENV, "machine-1", {
+ agentId: "bot-1",
+ config: CFG,
+ launchId: "l-1",
+ })
+
+ expect(result).toEqual({ sent: 1 })
+ expect(wsDoFetch).toHaveBeenCalledTimes(1)
+ const [, path, init] = wsDoFetch.mock.calls[0]!
+ expect(path).toBe("/community-machine/by-id/machine-1/forward-agent-reset")
+ expect(init.method).toBe("POST")
+ const body = JSON.parse(init.body as string)
+ expect(body).toEqual({ agentId: "bot-1", config: CFG, launchId: "l-1" })
+ // Narrow-typed: no `type` field snuck in — that's constructed inside ws-do.
+ expect(body.type).toBeUndefined()
+ })
+
+ it("returns { sent: 0 } when ws-do responds non-ok (treats as offline for the caller)", async () => {
+ wsDoFetch.mockResolvedValue(new Response("boom", { status: 503 }))
+
+ const result = await pushAgentResetToMachine(FAKE_ENV, "machine-1", {
+ agentId: "bot-1",
+ config: CFG,
+ launchId: "l-1",
+ })
+ expect(result).toEqual({ sent: 0 })
+ })
+
+ it("returns { sent: 0 } when the fetch itself throws (network down)", async () => {
+ wsDoFetch.mockRejectedValue(new Error("network"))
+
+ const result = await pushAgentResetToMachine(FAKE_ENV, "machine-1", {
+ agentId: "bot-1",
+ config: CFG,
+ launchId: "l-1",
+ })
+ expect(result).toEqual({ sent: 0 })
+ })
+})
diff --git a/src/web/src/lib/community/bot-push.ts b/src/web/src/lib/community/bot-push.ts
index 6844771bb..995e1993d 100644
--- a/src/web/src/lib/community/bot-push.ts
+++ b/src/web/src/lib/community/bot-push.ts
@@ -3,6 +3,7 @@ import type {
BotAddedFrame,
BotUpdatedFrame,
BotRemovedFrame,
+ RuntimeConfig,
} from "@alook/shared"
import { wsDoFetch } from "@/lib/broadcast"
@@ -54,3 +55,51 @@ export async function pushBotEventToMachine(
})
}
}
+
+/**
+ * Push an owner-triggered `agent:reset` to the machine's daemon over WS.
+ *
+ * Narrowly typed (only reset fields, no arbitrary HostCommand) so no caller
+ * can smuggle a different command shape onto the wire. Returns the ws-do
+ * response's `{ sent }` count — `sent === 0` means the daemon is not
+ * currently connected; the caller is expected to translate that into a 409.
+ */
+export async function pushAgentResetToMachine(
+ env: Env,
+ machineId: string,
+ args: { agentId: string; config: RuntimeConfig; launchId: string },
+): Promise<{ sent: number }> {
+ const path = `/community-machine/by-id/${encodeURIComponent(machineId)}/forward-agent-reset`
+ const body = JSON.stringify({
+ agentId: args.agentId,
+ config: args.config,
+ launchId: args.launchId,
+ })
+ try {
+ const res = await wsDoFetch(
+ env,
+ path,
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body,
+ },
+ { label: machineId, type: "agent:reset" },
+ )
+ if (!res.ok) {
+ log.warn("agent:reset 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:reset push threw", {
+ machineId,
+ err: String(err),
+ })
+ return { sent: 0 }
+ }
+}
diff --git a/src/web/src/stores/community/ws.ts b/src/web/src/stores/community/ws.ts
index dcaa00564..498d17aa2 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"
+ kind: "cli_invocation" | "tool_call" | "thinking" | "wake_trigger" | "session_reset"
payload: unknown
sessionId?: string | null
launchId?: string | null
diff --git a/src/ws-do/src/index.test.ts b/src/ws-do/src/index.test.ts
index f1e32b04d..ea78dac93 100644
--- a/src/ws-do/src/index.test.ts
+++ b/src/ws-do/src/index.test.ts
@@ -517,6 +517,71 @@ describe("ws-do router", () => {
})
})
+ describe("POST /community-machine/by-id/:machineId/forward-agent-reset", () => {
+ const validBody = {
+ agentId: "bot-1",
+ config: { version: 1, runtime: "claude", model: { kind: "default" }, mode: { kind: "default" } },
+ launchId: "l-1",
+ }
+
+ beforeEach(() => {
+ mockGetActiveDoNamesForMachine.mockReset()
+ mockGetActiveDoNamesForMachine.mockResolvedValue([])
+ })
+
+ it("rejects missing agentId with 400 without touching D1 or the DOs", async () => {
+ const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-reset", {
+ method: "POST",
+ body: JSON.stringify({ config: validBody.config, launchId: "l-1" }),
+ })
+ const res = await handler.fetch(req, env as any)
+ expect(res.status).toBe(400)
+ expect(mockGetActiveDoNamesForMachine).not.toHaveBeenCalled()
+ expect(doMock.stubFetch).not.toHaveBeenCalled()
+ })
+
+ it("rejects extra unexpected fields with 400", async () => {
+ const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-reset", {
+ method: "POST",
+ body: JSON.stringify({ ...validBody, sneaky: "value" }),
+ })
+ const res = await handler.fetch(req, env as any)
+ expect(res.status).toBe(400)
+ expect(doMock.stubFetch).not.toHaveBeenCalled()
+ })
+
+ it("zero active doNames → { sent: 0 } without touching any DO", async () => {
+ const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-reset", {
+ method: "POST",
+ body: JSON.stringify(validBody),
+ })
+ const res = await handler.fetch(req, env as any)
+ expect(res.status).toBe(200)
+ expect(await res.json()).toEqual({ sent: 0 })
+ expect(doMock.stubFetch).not.toHaveBeenCalled()
+ })
+
+ it("well-formed body → forwards a { type:'agent:reset', ... } frame to each DO's /push and aggregates sent", async () => {
+ mockGetActiveDoNamesForMachine.mockResolvedValue(["do-abc"])
+ doMock.stubFetch.mockResolvedValue(new Response(JSON.stringify({ sent: 1 }), { status: 200 }))
+
+ const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-reset", {
+ method: "POST",
+ body: JSON.stringify(validBody),
+ })
+ const res = await handler.fetch(req, env as any)
+
+ expect(doMock.idFromName).toHaveBeenCalledWith("community-machine:do-abc")
+ const stubReq = doMock.stubFetch.mock.calls[0][0] as Request
+ expect(stubReq.url).toBe("http://internal/push")
+ const forwardedBody = await stubReq.text()
+ const parsed = JSON.parse(forwardedBody)
+ expect(parsed).toEqual({ type: "agent:reset", agentId: "bot-1", config: validBody.config, launchId: "l-1" })
+ expect(res.status).toBe(200)
+ expect(await res.json()).toEqual({ sent: 1 })
+ })
+ })
+
describe("force-close routing", () => {
it("keys the DO by the do_name suffix", async () => {
doMock.stubFetch.mockResolvedValue(new Response(JSON.stringify({ closed: 1 })))
diff --git a/src/ws-do/src/index.ts b/src/ws-do/src/index.ts
index 7d5218ad7..c781b6455 100644
--- a/src/ws-do/src/index.ts
+++ b/src/ws-do/src/index.ts
@@ -119,7 +119,7 @@ export default {
// browser understands are broadcastable. An unknown `kind` reaches the
// owner UI as an untyped row (bot-activity-row.tsx renders it verbatim),
// so reject at the boundary instead.
- const AUDIT_KINDS = new Set(["cli_invocation", "tool_call", "thinking", "wake_trigger"])
+ const AUDIT_KINDS = new Set(["cli_invocation", "tool_call", "thinking", "wake_trigger", "session_reset"])
if (!AUDIT_KINDS.has(b.kind)) {
return new Response("invalid kind", { status: 400 })
}
@@ -319,6 +319,91 @@ export default {
return Response.json({ sent: delivered })
}
+ // POST /community-machine/by-id/<machineId>/forward-agent-reset — owner-
+ // triggered `agent:reset` push. Same shape as `/forward-agent-wake`: build
+ // the HostCommand from a narrow payload (`{ agentId, config, launchId }`),
+ // resolve the machine's active `do_names`, forward the frame to each DO's
+ // `/push` route, and aggregate `{ sent }`. Rejects any extra field —
+ // callers must use `pushAgentResetToMachine`.
+ const forwardAgentReset = url.pathname.match(/^\/community-machine\/by-id\/([^/]+)\/forward-agent-reset$/)
+ if (forwardAgentReset && request.method === "POST") {
+ const machineId = decodeURIComponent(forwardAgentReset[1])
+ const reqLog = log.child({ traceId, machineId })
+ reqLog.debug("forwarding agent:reset 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"])
+ for (const key of Object.keys(raw)) {
+ if (!allowedKeys.has(key)) {
+ return Response.json({ error: "invalid payload" }, { status: 400 })
+ }
+ }
+ const { agentId, config, launchId } = 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 })
+ }
+
+ 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 reset", { 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:reset", agentId, config, launchId })
+ 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 reset" }, { 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`.