feat(agent): per-session agent inbox (discussion #558)

A coordinator can leave text for a worker without typing into its pane.

- Store (src/web/agent-inbox.ts): read until ack by id, seen only for the
  receiver, 16 KiB/message, 512 KiB + 200 messages per inbox, full = 409
  CONFLICT (never drops the oldest), 12 h TTL from each message's createdAt.
- Routes (routes/inbox-routes.ts): POST/GET /api/sessions/:id/inbox
  (?wait= parks while nothing is unseen), POST .../inbox/ack (receiver
  only, 403 otherwise), GET /api/agent-inbox/summary (owner-scoped counts,
  not in toState()). Caller = resolveParentSessionId().
- Inbox waiters are the wait registry's third kind: same caps, ended by
  cancelAll/cancelEverything.
- Opt-in snapshot (agentInboxPersistEnabled, synced, default off):
  agent-inbox.json via dataPath(), 0600 tmp+rename, off deletes it, boot
  prune only after a successful restore. Dropped on delete, kept on detach.
- CLI: codeman agent post | inbox [--wait] | ack, INBOX column in ls.
- waitCapacityResponse/abortOnClientHangUp moved to route-helpers.ts
  unchanged.
- Docs: api-reference, README, CLAUDE.md, architecture-invariants, skill +
  plugin mirror.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
RandalixandClaude Opus 5.5 committed 2026-10-23 12:45:48 +02:00
1 parent 002de32a08
commit c6dfaa2cac
34 files changed
+2308 -83

No files matched your search

+181
View File
@@ -0,0 +1,181 @@
/**
* @fileoverview Agent inbox routes: post, read (optionally long-polling), ack, and an
* owner-scoped summary of counts. Store semantics live in `agent-inbox.ts`.
*
* Who is calling decides what a read or an ack does, so it is resolved here and never
* taken from the body. `resolveParentSessionId()` reads the `X-Codeman-Parent-Session`
* header `codeman agent` sends on every request and accepts it only for a live session
* the caller can see that has the same owner as the receiver (exact id, or a unique
* prefix of at least 8). Anything else is "no session": a post is from the user, and a
* read is a peek. What that buys: in multi-user mode a caller cannot name another
* owner's session. In single-user mode every local process holds the same
* credentials, so the header is a hint the client sets about itself.
*
* - `POST /api/sessions/:id/inbox` stores a message. `from` is the resolved caller or
* null. A full inbox is 409 CONFLICT; the oldest message is never dropped.
* - `GET /api/sessions/:id/inbox[?wait=ms]` returns every pending message. Only the
* receiver's own read marks them seen. With `wait`, it parks while nothing is
* UNSEEN (a seen-but-unacked message does not end the wait, or a receiver holding
* one would spin).
* - `POST /api/sessions/:id/inbox/ack` removes messages by id, idempotently, and only
* for the receiver itself (403 otherwise).
* - `GET /api/agent-inbox/summary` reports `pending`, `unseen`, `oldestUnseenAt` and
* `parked` per session the caller can see. Counts only, never text, and kept out of
* `toState()` so a post does not fan out a `session:updated` to every browser.
*
* Nothing here writes to a pane.
*
* @module web/routes/inbox-routes
*/
import { FastifyInstance } from 'fastify';
import { ApiErrorCode, createErrorResponse } from '../../types.js';
import { InboxAckSchema, InboxPostSchema, InboxReadQuerySchema } from '../schemas.js';
import {
abortOnClientHangUp,
canAccessOwned,
findSessionOrFail,
getAuthUser,
ownerFor,
parseBody,
resolveParentSessionId,
waitCapacityResponse,
} from '../route-helpers.js';
import { agentInbox, MAX_INBOX_BYTES, MAX_MESSAGE_BYTES, MAX_MESSAGES_PER_INBOX } from '../agent-inbox.js';
import { sessionWaits, WaitCapacityError, type InboxWaitResult } from '../session-wait-registry.js';
import { clampWaitMs } from '../../config/agent-wait.js';
import type { SessionPort } from '../ports/index.js';
/** Per-session counts the summary route reports. */
export interface InboxSessionSummary {
pending: number;
unseen: number;
oldestUnseenAt: number | null;
/** The receiver itself is parked on `GET …/inbox?wait=` right now. */
parked: boolean;
}
export function registerInboxRoutes(app: FastifyInstance, ctx: SessionPort): void {
/** The resolved caller is the receiving session itself. */
const callerIsReceiver = (req: Parameters<typeof resolveParentSessionId>[1], id: string, owner?: string) =>
resolveParentSessionId(ctx, req, undefined, owner) === id;
app.post('/api/sessions/:id/inbox', async (req) => {
const { id } = req.params as { id: string };
const session = findSessionOrFail(ctx, id, req);
const { text } = parseBody(InboxPostSchema, req.body, 'Invalid inbox message');
const from = resolveParentSessionId(ctx, req, undefined, session.owner) ?? null;
const result = agentInbox.post(id, from, text);
if (!result.ok) {
switch (result.reason) {
case 'empty':
return createErrorResponse(ApiErrorCode.INVALID_INPUT, 'text must not be empty');
case 'message-too-large':
return createErrorResponse(
ApiErrorCode.INVALID_INPUT,
`Message is larger than ${MAX_MESSAGE_BYTES} bytes (UTF-8). Write it to a file in the workspace and post the path.`
);
case 'inbox-full-count':
return createErrorResponse(
ApiErrorCode.CONFLICT,
`Inbox of ${id} is full (${MAX_MESSAGES_PER_INBOX} messages). Nothing was stored; the receiver has to ack before more can be posted.`
);
case 'inbox-full-bytes':
return createErrorResponse(
ApiErrorCode.CONFLICT,
`Inbox of ${id} is full (${MAX_INBOX_BYTES} bytes of pending text). Nothing was stored; the receiver has to ack before more can be posted.`
);
}
}
// After the store, so a parked reader that wakes finds the message.
sessionWaits.notifyInbox(id);
return {
success: true,
data: { sessionId: id, message: result.message, pending: result.pending, unseen: result.unseen },
};
});
app.get('/api/sessions/:id/inbox', async (req, reply) => {
const { id } = req.params as { id: string };
const session = findSessionOrFail(ctx, id, req);
const query = parseBody(InboxReadQuerySchema, req.query);
const receiver = callerIsReceiver(req, id, session.owner);
// A receiver loops on this URL with identical parameters; a cached 200 would turn
// the loop into a busy spin (same reason as GET …/wait).
reply.header('Cache-Control', 'no-store');
let wait: InboxWaitResult | undefined;
if (query.wait !== undefined) {
const timeoutMs = clampWaitMs(query.wait);
if (agentInbox.unseenCount(id) > 0) {
wait = {
posted: false,
timedOut: false,
immediate: true,
ended: false,
aborted: false,
waitedMs: 0,
timeoutMs,
};
} else {
const abort = abortOnClientHangUp(reply);
try {
wait = await sessionWaits.waitForInbox(id, {
timeoutMs,
owner: ownerFor(req),
abortSignal: abort.signal,
receiver,
});
} catch (err) {
if (err instanceof WaitCapacityError) return waitCapacityResponse(err);
throw err;
}
}
}
// Read AFTER the wait: this is what the caller gets, so it must be current. A wait
// that ended because the session was deleted reads an empty inbox.
const read = agentInbox.read(id, { receiver });
return { success: true, data: { sessionId: id, receiver, ...read, ...(wait ? { wait } : {}) } };
});
app.post('/api/sessions/:id/inbox/ack', async (req) => {
const { id } = req.params as { id: string };
const session = findSessionOrFail(ctx, id, req);
const { ids } = parseBody(InboxAckSchema, req.body);
if (!callerIsReceiver(req, id, session.owner)) {
// A no-op here would let a coordinator believe it cleared a worker's mail, and
// would hide a client that forgot the header. Refusing says both out loud.
return createErrorResponse(
ApiErrorCode.FORBIDDEN,
`Only ${id} itself can acknowledge its inbox (X-Codeman-Parent-Session must resolve to it). Reading as anyone else is a peek.`
);
}
const removed = agentInbox.ack(id, ids);
return {
success: true,
data: { sessionId: id, removed, pending: agentInbox.pendingCount(id), unseen: agentInbox.unseenCount(id) },
};
});
app.get('/api/agent-inbox/summary', async (req, reply) => {
reply.header('Cache-Control', 'no-store');
const user = getAuthUser(req);
const counts = agentInbox.summary();
const sessions: Record<string, InboxSessionSummary> = {};
for (const session of ctx.sessions.values()) {
if (!canAccessOwned(user, session.owner)) continue;
const c = counts.get(session.id);
const parked = sessionWaits.inboxWaiterCount(session.id, true) > 0;
if (!c && !parked) continue;
sessions[session.id] = {
pending: c?.pending ?? 0,
unseen: c?.unseen ?? 0,
oldestUnseenAt: c?.oldestUnseenAt ?? null,
parked,
};
}
return { success: true, data: { sessions } };
});
}
+1
View File
@@ -12,6 +12,7 @@ export { registerCronRoutes } from './cron-routes.js';
export { registerSystemRoutes } from './system-routes.js';
export { registerHookEventRoutes } from './hook-event-routes.js';
export { registerApprovalRoutes } from './approval-routes.js';
export { registerInboxRoutes } from './inbox-routes.js';
export { registerRebootRestoreRoutes } from './reboot-restore-routes.js';
export { registerReadMyMindRoutes } from './readmymind-routes.js';
export { registerGitStatusRoutes } from './git-status-routes.js';
+3 -46
View File
@@ -4,7 +4,7 @@
* auto-clear, auto-compact, image watcher, flicker filter, and logout.
*/
import { FastifyInstance, type FastifyReply, type FastifyRequest } from 'fastify';
import { FastifyInstance, type FastifyRequest } from 'fastify';
import { z } from 'zod';
import { join, dirname, extname, basename, resolve as resolvePath } from 'node:path';
import { homedir } from 'node:os';
@@ -115,6 +115,8 @@ import {
sessionCapacityMessage,
SETTINGS_PATH,
validatePathWithinBase,
waitCapacityResponse,
abortOnClientHangUp,
} from '../route-helpers.js';
import { buildAgentCaseMarker, writeAgentCaseMarker } from '../../agent-case-marker.js';
import { canUsernameRunPrivilegedCommands, resolveClaudeModeForUsername } from '../../user-store.js';
@@ -738,23 +740,6 @@ function parseWaitQuery<T>(schema: z.ZodType<T>, query: unknown, label: string):
});
}
/**
* Map a waiter-cap rejection to the code that tells the caller the truth.
*
* The two caps mean different things and warrant different recovery: `session` is
* genuinely about THIS session, while `owner` and `total` are process-wide budgets
* that say nothing about it. Reporting a global cap as `SESSION_BUSY` (409,
* documented as "Session is busy") sent an agent off to a different session to hit
* the identical error. `RATE_LIMITED` is the code whose whole meaning is "come back
* later", and clients and proxies already treat 429 that way.
*/
function waitCapacityResponse(err: WaitCapacityError): ApiResponse<never> {
const code = err.scope === 'session' ? ApiErrorCode.SESSION_BUSY : ApiErrorCode.RATE_LIMITED;
// The registry's message already names the scope and the limit; passing it through
// verbatim keeps the wording in one place.
return createErrorResponse(code, err.message);
}
/**
* The signal a session is ALREADY emitting, corrected for liveness.
*
@@ -931,34 +916,6 @@ export function _paneDeathWatcherCount(): number {
return paneDeathWatchers.size;
}
/**
* An `AbortController` that fires when the CLIENT goes away, and only then.
*
* Freeing an abandoned waiter matters because the documented pattern is a loop of
* short waits: `curl --max-time 30 ".../wait?timeout=600000"` abandons a live waiter
* every iteration until the cap is hit and an innocent session reports busy. Same for
* any proxy that cuts the connection.
*
* ⚠️ **It must listen on the RESPONSE, not the request.** `req.raw` emits `'close'`
* as soon as the request body has finished streaming, which on a POST is BEFORE the
* handler ever blocks — measured at +1ms with `aborted: false`, indistinguishable
* from a real hang-up at +0ms. Wiring the abort there cancels every send-and-wait
* instantly and silently kills the feature (it survives on GET only because a GET has
* no body to finish). `reply.raw` emits `'close'` both when the response completes
* and when the socket dies, and `writableFinished` is what tells those apart: true
* only if the response actually went out. The guard is load-bearing, not defensive.
*
* `app.inject()` never emits `'close'` at all, so this is only observable over real
* HTTP — which is why the regression test for it binds a port.
*/
function abortOnClientHangUp(reply: FastifyReply): AbortController {
const controller = new AbortController();
reply.raw.on('close', () => {
if (!reply.raw.writableFinished) controller.abort();
});
return controller;
}
/**
* Inject the agent skill into a case on create, surfacing only the REFUSALS.
*
+5
View File
@@ -64,6 +64,7 @@ import { AUTH_COOKIE_NAME } from '../middleware/auth.js';
import { QR_AUTH_FAILURE_MAX } from '../../config/tunnel-config.js';
import { AUTH_SESSION_TTL_MS } from '../../config/auth-config.js';
import { resolveTerminalHistoryConfig } from '../../config/terminal-history.js';
import { agentInboxPersistence } from '../agent-inbox-persistence.js';
/**
* Defaults for `POST /api/deepseek/install-profile`.
@@ -1129,6 +1130,10 @@ export function registerSystemRoutes(
'Workflow run watcher'
);
// Agent inbox snapshot (default OFF). From `merged` like the toggles above: a
// partial PUT that omits the key must not switch it off and delete the file.
agentInboxPersistence.setEnabled(merged.agentInboxPersistEnabled === true);
// Handle image watcher toggle dynamically
toggleService((merged.imageWatcherEnabled as boolean) ?? false, imageWatcher, 'Image watcher', () => {
// Re-watch all active sessions that have image watcher enabled