Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

community(batch-reset): server/contract half — machine:reset_all command + API

Gus75e0afeb6a38
diff --git a/src/shared/src/community-cli-contract.ts b/src/shared/src/community-cli-contract.ts
index 951ee69da..0123c122c 100644
--- a/src/shared/src/community-cli-contract.ts
+++ b/src/shared/src/community-cli-contract.ts
@@ -663,6 +663,23 @@ export type HostCommand =
* new model, never wrong about it. See `AgentProcessManager.switchModel`.
*/
| { type: "agent:model_switch"; agentId: AgentId; config: RuntimeConfig; launchId: string }
+ /**
+ * Owner-triggered BATCH reset — reset every agent bound to this machine in a
+ * SINGLE command (not N fanned-out `agent:reset` frames). The server
+ * enumerates the machine's full binding set and packs one `resets` entry per
+ * agent (each the payload of a normal `agent:reset`: agentId + config +
+ * launchId). The daemon loops `AgentProcessManager.resetSession` over the
+ * array, reusing the exact per-agent reset path — so a bound-but-idle agent
+ * cold-starts (register + fresh session), same as a single reset on an idle
+ * bot. Each per-agent reset is independent (a failure is a per-agent error
+ * ack, not a batch abort). The daemon MUST gate each `agentId` on its own
+ * `botsById` (bound) set — an agentId it doesn't own is a no-op+warn (defends
+ * the reconnect transient + closes the pre-existing "register+spawn any
+ * agentId" hole). Routed by machineId to the single daemon that owns it (one
+ * live credential per machineId). See the `machine:reset_all` case in
+ * `agentRouter` and plans/daemon-batch-reset.md.
+ */
+ | { type: "machine:reset_all"; resets: Array<{ 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,
@@ -1245,6 +1262,16 @@ export const HostCommandSchema = z.discriminatedUnion("type", [
config: z.unknown(),
launchId: z.string().min(1),
}),
+ z.object({
+ type: z.literal("machine:reset_all"),
+ resets: z.array(
+ z.object({
+ agentId: z.string().min(1),
+ config: z.unknown(),
+ launchId: z.string().min(1),
+ }),
+ ),
+ }),
// The `bot:*` arms are NOT what #6 targets — the daemon acts on `agent:*`;
// `bot:*` merely mutate/evict the `botsById` cache at the createDaemon layer.
// Per the CTO scope ("bot:* covered for union-completeness, no bespoke
diff --git a/src/shared/src/db/queries/community/bot.ts b/src/shared/src/db/queries/community/bot.ts
index 220b02535..ec45a2644 100644
--- a/src/shared/src/db/queries/community/bot.ts
+++ b/src/shared/src/db/queries/community/bot.ts
@@ -367,7 +367,13 @@ export async function getBotWakeContext(db: Database, botUserId: string): Promis
};
}
-/** Bots bound to this machine — daemon cold-start warmup uses this. */
+/**
+ * Bots bound to this machine — daemon cold-start warmup uses this, AND batch
+ * reset (`machine:reset_all`) enumerates the same binding set. `runtime` +
+ * `modelName` come off the binding row (the runtime pairing) so a caller can
+ * build a per-agent RuntimeConfig without a second query (batch reset needs
+ * them; warmup ignores the extra fields).
+ */
export async function listBotsForMachine(
db: Database,
machineId: string
@@ -379,6 +385,8 @@ export async function listBotsForMachine(
description: string;
ownerName: string;
ownerDiscriminator: string;
+ runtime: string;
+ modelName: string | null;
}>
> {
// Guard against orphaned bots: if a future flow soft-deletes an owner user
@@ -392,6 +400,8 @@ export async function listBotsForMachine(
description: communityUserProfile.aboutMe,
ownerName: owner.name,
ownerDiscriminator: owner.discriminator,
+ runtime: communityBotBinding.runtime,
+ modelName: communityBotBinding.modelName,
})
.from(user)
.innerJoin(communityBotBinding, eq(communityBotBinding.userId, user.id))
@@ -415,6 +425,8 @@ export async function listBotsForMachine(
description: r.description ?? "",
ownerName: r.ownerName,
ownerDiscriminator: r.ownerDiscriminator,
+ runtime: r.runtime,
+ modelName: r.modelName ?? null,
}));
}
diff --git a/src/shared/test/queries/community-bot.test.ts b/src/shared/test/queries/community-bot.test.ts
index 827d34dba..e7fdf2f6f 100644
--- a/src/shared/test/queries/community-bot.test.ts
+++ b/src/shared/test/queries/community-bot.test.ts
@@ -211,6 +211,8 @@ describe("listBotsForMachine", () => {
description: "does things",
ownerName: "gustavo",
ownerDiscriminator: "5678",
+ runtime: "claude",
+ modelName: "claude-opus-4-6",
},
])
const result = await q.listBotsForMachine(chain, "machine_1")
@@ -222,10 +224,30 @@ describe("listBotsForMachine", () => {
description: "does things",
ownerName: "gustavo",
ownerDiscriminator: "5678",
+ runtime: "claude",
+ modelName: "claude-opus-4-6",
},
])
})
+ it("defaults modelName to null when the binding has none", async () => {
+ const chain = makeJoinChain([
+ {
+ id: "bot_1",
+ name: "helper",
+ discriminator: "1234",
+ description: "does things",
+ ownerName: "gustavo",
+ ownerDiscriminator: "5678",
+ runtime: "claude",
+ modelName: null,
+ },
+ ])
+ const result = await q.listBotsForMachine(chain, "machine_1")
+ expect(result[0]?.runtime).toBe("claude")
+ expect(result[0]?.modelName).toBeNull()
+ })
+
it("defaults description to empty string when the profile row is missing", async () => {
const chain = makeJoinChain([
{ id: "bot_1", name: "helper", discriminator: "1234", description: null, ownerName: "gustavo", ownerDiscriminator: "5678" },
diff --git a/src/web/src/app/api/community/machines/[id]/reset-agents/route.test.ts b/src/web/src/app/api/community/machines/[id]/reset-agents/route.test.ts
new file mode 100644
index 000000000..2fac318e1
--- /dev/null
+++ b/src/web/src/app/api/community/machines/[id]/reset-agents/route.test.ts
@@ -0,0 +1,140 @@
+import { describe, it, expect, vi, beforeEach } from "vitest"
+import { NextRequest } from "next/server"
+
+const mockGetMachineByIdForUser = vi.fn()
+const mockListBotsForMachine = vi.fn()
+const mockPushBatchResetToMachine = 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: {
+ communityMachine: {
+ getMachineByIdForUser: (...a: unknown[]) => mockGetMachineByIdForUser(...a),
+ },
+ communityBot: {
+ listBotsForMachine: (...a: unknown[]) => mockListBotsForMachine(...a),
+ },
+ },
+ }
+})
+
+vi.mock("@/lib/community/bot-push", () => ({
+ pushBatchResetToMachine: (...a: unknown[]) => mockPushBatchResetToMachine(...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/machines/mac_1/reset-agents", {
+ method: "POST",
+ })
+}
+
+const ctx = { params: { id: "mac_1" } } as any
+
+// Two bots bound to the machine — one with a configured model, one default —
+// AND deliberately one that would be idle (scope ②: batch resets ALL bound,
+// running or not; the route doesn't filter by running state).
+const BOUND_BOTS = [
+ { id: "b1", name: "zoe", discriminator: "0042", description: "", ownerName: "o", ownerDiscriminator: "0001", runtime: "claude", modelName: "claude-opus-4-6" },
+ { id: "b2", name: "max", discriminator: "0043", description: "", ownerName: "o", ownerDiscriminator: "0001", runtime: "claude", modelName: null },
+]
+
+describe("POST /api/community/machines/[id]/reset-agents (batch reset)", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it("non-owner (machine not owned) → 404, never enumerates bots, never pushes", async () => {
+ mockGetMachineByIdForUser.mockResolvedValue(null)
+
+ const res = await POST(req(), ctx)
+ expect(res.status).toBe(404)
+ expect(mockListBotsForMachine).not.toHaveBeenCalled()
+ expect(mockPushBatchResetToMachine).not.toHaveBeenCalled()
+ })
+
+ it("owner but no bots bound → 200 {dispatched:0}, never pushes", async () => {
+ mockGetMachineByIdForUser.mockResolvedValue({ id: "mac_1", userId: "owner_1" })
+ mockListBotsForMachine.mockResolvedValue([])
+
+ const res = await POST(req(), ctx)
+ expect(res.status).toBe(200)
+ const body = await res.json() as { dispatched: number }
+ expect(body.dispatched).toBe(0)
+ expect(mockPushBatchResetToMachine).not.toHaveBeenCalled()
+ })
+
+ it("owner + bots bound + daemon offline (sent:0) → 409", async () => {
+ mockGetMachineByIdForUser.mockResolvedValue({ id: "mac_1", userId: "owner_1" })
+ mockListBotsForMachine.mockResolvedValue(BOUND_BOTS)
+ mockPushBatchResetToMachine.mockResolvedValue({ sent: 0 })
+
+ const res = await POST(req(), ctx)
+ expect(res.status).toBe(409)
+ expect(mockPushBatchResetToMachine).toHaveBeenCalledTimes(1)
+ })
+
+ it("owner + bots bound + daemon online → 200 {dispatched:N} with ONE batch frame carrying all agents", async () => {
+ mockGetMachineByIdForUser.mockResolvedValue({ id: "mac_1", userId: "owner_1" })
+ mockListBotsForMachine.mockResolvedValue(BOUND_BOTS)
+ mockPushBatchResetToMachine.mockResolvedValue({ sent: 2 })
+
+ const res = await POST(req(), ctx)
+ expect(res.status).toBe(200)
+ const body = await res.json() as { dispatched: number }
+ expect(body.dispatched).toBe(2)
+
+ // ONE push (batch), NOT N single pushes (Gus: dedicated command, not fan-out).
+ expect(mockPushBatchResetToMachine).toHaveBeenCalledTimes(1)
+ const [_env, machineId, resets] = mockPushBatchResetToMachine.mock.calls[0]!
+ expect(machineId).toBe("mac_1")
+ expect(resets).toHaveLength(2)
+ expect(resets.map((r: any) => r.agentId).sort()).toEqual(["b1", "b2"])
+ // Each entry carries its own launchId + config.
+ for (const r of resets) {
+ expect(typeof r.launchId).toBe("string")
+ expect(r.launchId.length).toBeGreaterThan(0)
+ expect(r.config).toBeDefined()
+ }
+ })
+
+ it("regression: per-agent config carries the bot's configured model (not default), resolved independently", async () => {
+ mockGetMachineByIdForUser.mockResolvedValue({ id: "mac_1", userId: "owner_1" })
+ mockListBotsForMachine.mockResolvedValue(BOUND_BOTS)
+ mockPushBatchResetToMachine.mockResolvedValue({ sent: 2 })
+
+ await POST(req(), ctx)
+ const [, , resets] = mockPushBatchResetToMachine.mock.calls[0]!
+ const b1 = resets.find((r: any) => r.agentId === "b1")!
+ const b2 = resets.find((r: any) => r.agentId === "b2")!
+ // b1 has a named model, b2 falls back to default — resolved per-agent.
+ expect(b1.config.model).toEqual({ kind: "named", name: "claude-opus-4-6" })
+ expect(b2.config.model).toEqual({ kind: "default" })
+ })
+})
diff --git a/src/web/src/app/api/community/machines/[id]/reset-agents/route.ts b/src/web/src/app/api/community/machines/[id]/reset-agents/route.ts
new file mode 100644
index 000000000..a6837c270
--- /dev/null
+++ b/src/web/src/app/api/community/machines/[id]/reset-agents/route.ts
@@ -0,0 +1,58 @@
+import { nanoid } from "nanoid"
+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 { pushBatchResetToMachine } from "@/lib/community/bot-push"
+
+/**
+ * Owner-triggered BATCH reset — reset EVERY agent bound to a machine in one
+ * command (my-bots machine-category "Reset all" button).
+ *
+ * Flow: owner-scope the machine → enumerate its full binding set
+ * (`listBotsForMachine`, all bound bots regardless of running state — a
+ * bound-but-idle bot cold-starts on reset, scope ②) → build a per-agent
+ * RuntimeConfig (same as single-reset) → push ONE `machine:reset_all` frame to
+ * the machine's daemon (server packs the array; the daemon does NOT re-enumerate
+ * and gates each agentId on its own `botsById`). If delivered (`sent > 0`)
+ * return `{ dispatched: N }`; if the daemon is offline (`sent === 0`) return 409.
+ *
+ * v1 is DISPATCH-level (Gus 架构#825): we confirm the daemon RECEIVED the batch,
+ * not per-agent reset completion — matching single-reset's fire-and-confirm-
+ * delivery honesty. No per-agent success tracking (that'd be a v2 correlated-ack
+ * path the control channel doesn't have). See plans/daemon-batch-reset.md.
+ */
+export const POST = withAuth(async (_req, ctx) => {
+ const machineId = ctx.params?.id as string
+ if (!machineId) return writeError("machine id is required", 400)
+ const db = getDb(ctx.env.DB)
+
+ // Owner-scope: the machine must belong to the caller (query-layer
+ // listBotsForMachine is not owner-scoped by design — the check lives here).
+ const machine = await queries.communityMachine.getMachineByIdForUser(db, ctx.userId, machineId)
+ if (!machine) return writeError("machine not found", 404)
+
+ const bots = await queries.communityBot.listBotsForMachine(db, machineId)
+ if (bots.length === 0) {
+ // Nothing bound to this machine — nothing to reset.
+ return writeJSON({ dispatched: 0 })
+ }
+
+ const resets = bots.map((bot) => ({
+ agentId: bot.id,
+ config: makeRuntimeConfig({
+ runtime: bot.runtime,
+ model: resolveModelConfig(bot.runtime, bot.modelName),
+ agentName: bot.name,
+ agentHandle: `@${formatHandle(bot.name, bot.discriminator)}`,
+ }),
+ launchId: nanoid(),
+ }))
+
+ const { sent } = await pushBatchResetToMachine(ctx.env, machineId, resets)
+ if (sent === 0) {
+ return writeError("machine is offline — bring its daemon online before resetting", 409)
+ }
+
+ return writeJSON({ dispatched: resets.length })
+})
diff --git a/src/web/src/lib/community/bot-push.ts b/src/web/src/lib/community/bot-push.ts
index 9c8489f2f..ebd41e053 100644
--- a/src/web/src/lib/community/bot-push.ts
+++ b/src/web/src/lib/community/bot-push.ts
@@ -104,6 +104,57 @@ export async function pushAgentResetToMachine(
}
}
+/**
+ * Push an owner-triggered BATCH reset (`machine:reset_all`) to a machine's
+ * daemon over WS — one frame carrying every agent's reset payload, NOT N
+ * fanned-out `agent:reset` calls.
+ *
+ * Narrowly typed (only the reset array) so no caller can smuggle another
+ * command shape. Returns `{ sent }` — `sent === 0` means the daemon isn't
+ * connected; the caller translates that into a 409.
+ */
+export async function pushBatchResetToMachine(
+ env: Env,
+ machineId: string,
+ resets: Array<{ agentId: string; config: RuntimeConfig; launchId: string }>,
+): Promise<{ sent: number }> {
+ const path = `/community-machine/by-id/${encodeURIComponent(machineId)}/forward-batch-reset`
+ const body = JSON.stringify({
+ resets: resets.map((r) => ({
+ agentId: r.agentId,
+ config: r.config,
+ launchId: r.launchId,
+ })),
+ })
+ try {
+ const res = await wsDoFetch(
+ env,
+ path,
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body,
+ },
+ { label: machineId, type: "machine:reset_all" },
+ )
+ if (!res.ok) {
+ log.warn("machine:reset_all 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("machine:reset_all push threw", {
+ machineId,
+ err: String(err),
+ })
+ return { sent: 0 }
+ }
+}
+
/**
* Push an agent-self-initiated `agent:nap` to the bot's OWN machine over WS.
*
diff --git a/src/ws-do/src/index.ts b/src/ws-do/src/index.ts
index 83757f7af..46579094d 100644
--- a/src/ws-do/src/index.ts
+++ b/src/ws-do/src/index.ts
@@ -404,6 +404,110 @@ export default {
return Response.json({ sent: delivered })
}
+ // POST /community-machine/by-id/<machineId>/forward-batch-reset —
+ // owner-triggered `machine:reset_all` push (batch reset all agents on the
+ // machine in ONE frame, not N fanned-out agent:reset). Twin of
+ // /forward-agent-reset: same doName resolution + `/push` fan-out + `{sent}`
+ // aggregation, but the body is a `resets` array (each item the narrow
+ // {agentId, config, launchId}) and the frame type is `machine:reset_all`.
+ // Callers must use `pushBatchResetToMachine`.
+ const forwardBatchReset = url.pathname.match(/^\/community-machine\/by-id\/([^/]+)\/forward-batch-reset$/)
+ if (forwardBatchReset && request.method === "POST") {
+ const machineId = decodeURIComponent(forwardBatchReset[1])
+ const reqLog = log.child({ traceId, machineId })
+ reqLog.debug("forwarding machine:reset_all 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>
+ // Only `resets` allowed at the top level.
+ for (const key of Object.keys(raw)) {
+ if (key !== "resets") {
+ return Response.json({ error: "invalid payload" }, { status: 400 })
+ }
+ }
+ if (!Array.isArray(raw.resets)) {
+ return Response.json({ error: "invalid payload" }, { status: 400 })
+ }
+ // Validate each reset entry against the same narrow allowlist as
+ // forward-agent-reset — no extra fields, all three required.
+ const resets: Array<{ agentId: string; config: unknown; launchId: string }> = []
+ for (const item of raw.resets) {
+ if (!item || typeof item !== "object") {
+ return Response.json({ error: "invalid payload" }, { status: 400 })
+ }
+ const r = item as Record<string, unknown>
+ const allowedKeys = new Set(["agentId", "config", "launchId"])
+ for (const key of Object.keys(r)) {
+ if (!allowedKeys.has(key)) {
+ return Response.json({ error: "invalid payload" }, { status: 400 })
+ }
+ }
+ if (typeof r.agentId !== "string" || r.agentId.length === 0) {
+ return Response.json({ error: "invalid payload" }, { status: 400 })
+ }
+ if (typeof r.launchId !== "string" || r.launchId.length === 0) {
+ return Response.json({ error: "invalid payload" }, { status: 400 })
+ }
+ if (!r.config || typeof r.config !== "object") {
+ return Response.json({ error: "invalid payload" }, { status: 400 })
+ }
+ resets.push({ agentId: r.agentId, config: r.config, launchId: r.launchId })
+ }
+
+ 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 batch 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: "machine:reset_all", resets })
+ 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 batch reset" }, { status: 503 })
+ }
+ return Response.json({ sent: delivered })
+ }
+
// POST /community-machine/by-id/<machineId>/forward-agent-model-switch —
// owner-triggered `agent:model_switch` push. A verbatim twin of
// /forward-agent-reset (same narrow `{agentId, config, launchId}` allowlist,