feat: replace session commands with a natural-language stop

Remove the /compact, /clear and /stop session commands. They were gated
to the main room or SESSION_COMMAND_ALLOWED_SENDERS, neither of which
exists in this deployment, so nobody could use them. The agent-runner
/compact passthrough goes with them.

Instead, a short human message whose whole intent is "stop" (그만, 멈춰,
중단해, 하지 마, 취소, stop, cancel, ...; see src/stop-intent.ts) stops the
room when it has something to stop: a running or queued run, an open
paired task, or unprocessed human messages before it. The message loop
then
- advances the room cursors past the stop message (memory + router_state)
- completes the open paired task as user_stopped, cancels its open turns
  and drops its execution lease
- closes stdin with a user-stop reason and kills the agent through the
  existing GroupQueue.closeStdin/killProcess
- replies "진행 중이던 작업을 중단했습니다." once
When nothing is running the message is handled as a normal message.

The user-stop close reason is treated like a human interruption, so the
killed paired turn releases its lease without counting a failure and
queues no follow-up, and the turn controller does not post the generic
failure text on top of the stop reply.

advanceLastAgentCursor no longer moves a cursor backwards, so a run that
finishes after the stop cannot rewind the cursor and re-dispatch the
stop message (the respawn seen when an agent was only killed).

Stale SESSION_COMMAND_* keys in .env are now ignored instead of failing
startup.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Codex
2026-10-01 19:26:10 +09:00
parent fe7c5a7b23
commit ce4547daa6
40 changed files with 949 additions and 1084 deletions

View File

@@ -5,14 +5,10 @@ import {
markWorkItemDelivered,
type WorkItem,
} from './db.js';
import {
isSessionCommandSenderAllowed,
SERVICE_SESSION_SCOPE,
} from './config.js';
import { SERVICE_SESSION_SCOPE } from './config.js';
import { resolveRuntimeAttachmentBaseDirs } from './attachment-base-dirs.js';
import { enqueueGenericFollowUpAfterDeliveryRetry as enqueueDeliveryRetryFollowUp } from './message-runtime-dispatch.js';
import { processOpenWorkItemDelivery } from './message-runtime-delivery.js';
import { handleQueuedRunGates } from './message-runtime-gating.js';
import {
runPendingPairedTurnIfNeeded,
runQueuedGroupTurn,
@@ -24,7 +20,6 @@ import {
shouldSkipBotOnlyCollaboration,
} from './message-runtime-rules.js';
import { resolveOwnerTaskForHumanMessage } from './paired-execution-context.js';
import { transitionPairedTaskStatus } from './paired-task-status.js';
import { hasReviewerLease } from './service-routing.js';
import {
getFixedRoleChannelName,
@@ -41,8 +36,8 @@ import {
RELOGIN_REQUIRED_MESSAGE,
} from './token-refresh.js';
import { findChannel, formatMessages } from './router.js';
import { stopRoomWorkIfRequested, type RoomStopResult } from './room-stop.js';
import { createScopedLogger, logger } from './logger.js';
import type { AgentOutput } from './agent-runner.js';
import type { GroupQueue, GroupRunContext } from './group-queue.js';
import type {
ExecuteTurnFn,
@@ -55,31 +50,16 @@ import type {
RegisteredGroup,
} from './types.js';
type RunAgentFn = (
group: RegisteredGroup,
prompt: string,
chatJid: string,
runId: string,
onOutput?: (output: AgentOutput) => Promise<void>,
) => Promise<'success' | 'error'>;
interface ProcessGroupMessagesDeps {
assistantName: string;
failureFinalText: string;
timezone: string;
triggerPattern: RegExp;
channels: Channel[];
queue: Pick<GroupQueue, 'enqueueMessageCheck' | 'closeStdin' | 'killProcess'>;
queue: Pick<GroupQueue, 'enqueueMessageCheck'>;
getRoomBindings: () => Record<string, RegisteredGroup>;
getLastAgentTimestamps: () => Record<string, string>;
saveState: () => void;
clearSession: (groupFolder: string, opts?: { allRoles?: boolean }) => void;
runAgent: RunAgentFn;
executeTurn: ExecuteTurnFn;
hasImplicitContinuationWindow: (
chatJid: string,
messages: NewMessage[],
) => boolean;
openContinuation: (chatJid: string) => void;
isDuplicateOfLastBotFinal: (chatJid: string, text: string) => boolean;
labelPairedSenders: (chatJid: string, messages: NewMessage[]) => NewMessage[];
@@ -307,9 +287,10 @@ async function processMissedMessages(
return true;
}
const gateOutcome = await runQueuedRunGates(args, runtime, missedMessages);
if (gateOutcome !== null) {
return gateOutcome;
const stopResult = await runStopRequestGate(args, runtime, missedMessages);
if (stopResult.stopped) {
if (stopResult.hasMessagesAfterStop) continue;
return true;
}
const reloginOutcome = await runReloginRequiredGate(
@@ -449,11 +430,7 @@ async function runReloginRequiredGate(
if (agentType !== 'claude-code') return null;
if (!isReloginRequired()) return null;
await deliverSessionCommandMessage(
args,
runtime.chatJid,
RELOGIN_REQUIRED_MESSAGE,
);
await deliverRoomNotice(args, runtime.chatJid, RELOGIN_REQUIRED_MESSAGE);
const lastMessage = missedMessages[missedMessages.length - 1];
if (lastMessage?.seq != null) {
@@ -470,75 +447,34 @@ async function runReloginRequiredGate(
return true;
}
async function runQueuedRunGates(
/**
* A stop request that reaches a queued run without having been handled by the
* message loop (e.g. it was pending across a restart) still stops the room's
* open paired task instead of being sent to the agent as a prompt.
*/
async function runStopRequestGate(
args: ProcessGroupMessagesDeps,
runtime: RuntimeContext,
missedMessages: NewMessage[],
): Promise<boolean | null> {
const gateResult = await handleQueuedRunGates({
): Promise<RoomStopResult> {
return stopRoomWorkIfRequested({
chatJid: runtime.chatJid,
group: runtime.group,
runId: runtime.runId,
missedMessages,
triggerPattern: args.triggerPattern,
timezone: args.timezone,
hasImplicitContinuationWindow: args.hasImplicitContinuationWindow,
sessionCommandDeps: {
sendMessage: (text) =>
deliverSessionCommandMessage(args, runtime.chatJid, text),
setTyping: (typing) =>
runtime.channel.setTyping?.(runtime.chatJid, typing) ??
Promise.resolve(),
runAgent: (prompt, onOutput) =>
args.runAgent(
runtime.group,
prompt,
runtime.chatJid,
runtime.runId,
onOutput,
),
closeStdin: () =>
args.queue.closeStdin(runtime.chatJid, {
reason: 'session-command',
}),
clearSession: (opts) => args.clearSession(runtime.group.folder, opts),
advanceCursor: (cursorOrTimestamp) => {
advanceLastAgentCursor(
args.getLastAgentTimestamps(),
args.saveState,
runtime.chatJid,
cursorOrTimestamp,
);
},
formatMessages,
isAdminSender: (msg) => isSessionCommandSenderAllowed(msg.sender),
canSenderInteract: () => true,
resetPairedTask: () => completePairedTaskAsStopped(runtime.chatJid),
killProcess: () => args.queue.killProcess(runtime.chatJid),
},
});
return gateResult.handled ? gateResult.success : null;
}
function completePairedTaskAsStopped(chatJid: string): void {
if (!hasReviewerLease(chatJid)) return;
const task = getLatestOpenPairedTaskForChat(chatJid);
if (!task) return;
const now = new Date().toISOString();
transitionPairedTaskStatus({
taskId: task.id,
currentStatus: task.status,
nextStatus: 'completed',
expectedUpdatedAt: task.updated_at,
updatedAt: now,
patch: {
completion_reason: 'stopped',
channel: runtime.channel,
messages: missedMessages,
assistantName: args.assistantName,
lastAgentTimestamps: args.getLastAgentTimestamps(),
saveState: args.saveState,
controls: {
// This run is the room's queued work; it has not started an agent yet.
hasQueuedWork: () => false,
stopRunningAgent: () => false,
sendReply: (chatJid, text) => deliverRoomNotice(args, chatJid, text),
},
});
}
async function deliverSessionCommandMessage(
export async function deliverRoomNotice(
deps: Pick<ProcessGroupMessagesDeps, 'channels' | 'getRoomBindings'>,
chatJid: string,
text: string,