diff --git a/.claude/skills/customize/SKILL.md b/.claude/skills/customize/SKILL.md index cc7668e..f1b50c0 100644 --- a/.claude/skills/customize/SKILL.md +++ b/.claude/skills/customize/SKILL.md @@ -17,8 +17,8 @@ description: Customize Discord-only EJClaw behavior, routing, integrations, prom ## 자주 보는 수정 지점 - `src/channels/discord.ts` - 디스코드 메시지 파싱, 멘션 규칙, 첨부파일 처리, 음성 전사 -- `src/index.ts` - 오케스트레이션, 세션 명령, 라우팅, 상태 갱신 -- `src/session-commands.ts` - `/compact`, `/clear` 같은 세션 명령 +- `src/index.ts` - 오케스트레이션, 라우팅, 상태 갱신 +- `src/stop-intent.ts`, `src/room-stop.ts` - "그만"/"stop" 같은 자연어 작업 중단 - `src/db.ts` - 등록 그룹, 세션, 스케줄, 마이그레이션 - `src/config.ts` - 서비스 식별값, 디렉터리, 타임아웃, 기능 플래그 - `src/agent-runner.ts` - 에이전트 실행과 환경 변수 전달 @@ -32,7 +32,7 @@ description: Customize Discord-only EJClaw behavior, routing, integrations, prom ### 동작을 바꾸고 싶을 때 - 응답 조건, 멘션 처리, 첨부파일 처리: `src/channels/discord.ts` -- 세션 명령, 상태머신, 런루프: `src/index.ts`, `src/session-commands.ts` +- 작업 중단, 상태머신, 런루프: `src/index.ts`, `src/message-runtime-dispatch.ts`, `src/room-stop.ts` - 페르소나/응답 스타일: `groups/global/CLAUDE.md` ### 도구나 MCP를 붙일 때 @@ -43,8 +43,7 @@ description: Customize Discord-only EJClaw behavior, routing, integrations, prom ### 새 명령을 만들 때 -- 먼저 슬래시 명령인지, 자연어 규칙인지 구분합니다. -- 슬래시/예약 명령이면 `src/session-commands.ts`와 `src/index.ts` 경로를 봅니다. +- 슬래시 세션 명령은 없습니다. 런타임이 직접 처리해야 하는 짧은 자연어 명령이면 `src/room-stop.ts`처럼 메시지 루프(`src/message-runtime-dispatch.ts`)에서 가로챕니다. - 자연어 지시만으로 충분하면 프롬프트 문서만 수정합니다. ### 등록/배포 흐름을 바꿀 때 diff --git a/.claude/skills/debug/SKILL.md b/.claude/skills/debug/SKILL.md index e3992eb..643c16f 100644 --- a/.claude/skills/debug/SKILL.md +++ b/.claude/skills/debug/SKILL.md @@ -81,7 +81,7 @@ bun -e "import {Database} from 'bun:sqlite'; const db=new Database('store/messag - `chat_jid`는 `dc:` 형식이어야 합니다. tribunal 방인데 `work_dir`가 비어 있으면 첫 턴에 자동 복구됩니다. - `folder`는 `discord_main` 또는 `discord_` 형태를 유지합니다. -- 세션 명령 문제면 `src/session-commands.ts`와 `src/index.ts` 호출부를 같이 봅니다. +- 작업 중단("그만", "stop")이 안 먹으면 로그의 `Stopped room work on user request`와 `src/stop-intent.ts` 판정 규칙을 같이 봅니다. ## 원칙 diff --git a/.claude/skills/setup/SKILL.md b/.claude/skills/setup/SKILL.md index d197e55..38d9df3 100644 --- a/.claude/skills/setup/SKILL.md +++ b/.claude/skills/setup/SKILL.md @@ -78,7 +78,6 @@ USAGE_DASHBOARD=true # 고급 설정 MAX_CONCURRENT_AGENTS=5 -SESSION_COMMAND_ALLOWED_SENDERS=... # 세션 명령 허용 유저 ID (쉼표 구분) ``` ## 4. 러너 빌드 diff --git a/.env.example b/.env.example index a8a6cca..12a3d14 100644 --- a/.env.example +++ b/.env.example @@ -70,4 +70,3 @@ STATUS_CHANNEL_ID= # Discord channel ID for live status updat # --- Advanced --- # MAX_CONCURRENT_AGENTS=5 # Max parallel agent processes -# SESSION_COMMAND_ALLOWED_SENDERS= # Comma-separated Discord user IDs for session commands diff --git a/CHANGELOG.md b/CHANGELOG.md index 029b519..b997308 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,10 @@ ## [Unreleased] +### Added + +- 자연어 작업 중단: 작업이 실행 중이거나 대기 중인 방에 "그만", "멈춰", "중단해", "취소", "stop" 같은 중단 의도만 담긴 짧은 메시지를 보내면 실행 중인 에이전트를 종료하고, 열린 paired task를 `user_stopped`로 닫고(남은 turn 취소·lease 해제), 중단 메시지까지 처리된 것으로 넘긴 뒤 "진행 중이던 작업을 중단했습니다."라고 답함. 다른 지시가 섞인 메시지는 중단으로 보지 않음 + ### Changed - 기본 Claude 모델을 Claude Opus 5.5(`claude-opus-5-5`)로 상향. Opus 5.5는 Claude Code CLI 2.1.280 이상이 필요해 `@anthropic-ai/claude-agent-sdk`를 0.3.153 → 0.3.286(번들 CLI 2.1.286)으로 올림 (8b68885) @@ -17,10 +21,12 @@ - 쓰이지 않던 export·고아 모듈(`src/dashboard.ts`, `src/dashboard-status-content.ts`, `src/restart-context-cli.ts`)과 `DELTA_HANDOFF_*` 설정 - macOS launchd·nohup(WSL) 설치 경로와 `launchd/`, 쓰이지 않던 `repo-tokens/` GitHub Action. 서비스 설치는 Linux systemd만 지원 - 루트에서 import하지 않던 `yaml`, `zod`, `@modelcontextprotocol/sdk` 의존성 (agent-runner는 자체 의존성 유지) +- `/compact`·`/clear`·`/stop` 세션 명령(main 방·관리자 전용이라 실제로 쓰이지 않음)과 `SESSION_COMMAND_ALLOWED_SENDERS` 설정, agent-runner의 `/compact` 처리. `.env`에 남아 있는 `SESSION_COMMAND_*` 값은 더 이상 시작을 막지 않고 무시됨 - 기본 비활성이던 주기적 Codex warm-up 루프와 `CODEX_WARMUP_ENABLED`/`CODEX_WARMUP_INTERVAL_MS`. 고정 슬롯 usage primer는 그대로 동작 ### Fixed +- 메시지 처리 커서가 뒤로 감기지 않도록 함. 더 새로운 메시지를 이미 처리한 뒤 끝난 이전 실행이 커서를 되돌려 같은 메시지가 다시 실행되던 경로를 막음 - Codex 계정이 1개일 때 두 방이 동시에 Codex를 쓰면 두 번째 실행이 "Codex rotation pool unavailable"로 즉시 실패하고 리뷰가 조용히 생략되던 문제 수정. 잠금이 다른 실행에 잡혀 있으면 최대 15분 기다림 (30ba510) - 이미 턴 소유권을 잃은 실행의 5초 진행 표시 타이머가 멈추지 않아, 실제로 작업 중인 방의 진행 메시지가 멈춘 것처럼 보이던 문제 수정 (69ae334) - `work_dir`가 비어 있는 tribunal 방에서 실행 컨텍스트가 만들어지지 않아 작업 리비전이 얼고 10분 안의 후속 메시지가 버려지던 문제 수정. 자동 복구 경로가 동작하도록 함 (c7a8a43) diff --git a/README.md b/README.md index 54ea3c2..a7c699f 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,7 @@ EJClaw는 Discord 위에서 동작하는 Tribunal 멀티에이전트 개발 보 - Claude 장애 시 Codex로 넘기는 global failover - Claude OAuth 멀티 토큰 로테이션 - `assign_room` 기반 명시적 room assignment +- 자연어 중단: 작업 중인 방에 "그만", "멈춰", "중단해", "취소", "stop" 같은 짧은 메시지만 보내면 실행 중인 에이전트를 끝내고 열린 paired task를 닫음 - Bun + SQLite 기반 빠른 런타임 ## 운영 적용 사항 @@ -67,6 +68,15 @@ GitHub `main` 베이스 위에 운영 중 검증된 변경을 현재 코드 구 → 왕복이 누적되면 arbiter 자동 요청 가능 ``` +### 작업 중단 + +방에서 에이전트가 실행 중이거나, 대기 중인 메시지·열린 paired task가 있을 때 사람이 중단 의도만 담긴 짧은 메시지를 보내면 그 방의 작업을 멈춥니다. + +- 인식하는 표현: `그만`, `그만해(줘)`, `그만하자`, `멈춰(줘)`, `중단(해)`, `중지`, `하지 마`, `취소(해)`, `스톱`, `stop`, `cancel` 등. 앞뒤 봇 멘션과 끝의 `. ! ~ ㅠ ㅜ`는 무시하고, "작업 중단해줘", "제발 그만"처럼 짧은 수식어는 허용합니다. +- "그거 하지 말고 이거 해줘", "중단하지 말고 계속해", "로그인 취소 기능 만들어줘"처럼 다른 지시가 섞인 메시지는 중단으로 보지 않습니다. 애매하면 일반 메시지로 처리합니다. +- 중단 시: 실행 중인 owner/reviewer/arbiter 프로세스를 종료하고, 열린 paired task를 `completion_reason = 'user_stopped'`로 닫고(남은 turn 취소, 실행 lease 해제), 중단 메시지까지의 메시지를 처리된 것으로 넘긴 뒤 "진행 중이던 작업을 중단했습니다."라고 한 번 답합니다. +- 멈출 것이 없으면 그 메시지는 평소처럼 에이전트에게 전달됩니다. + ## 방 설정 모델 현재 room 설정의 기준은 다음과 같습니다. diff --git a/docs/configuration.md b/docs/configuration.md index 049c19e..a0a20ca 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -95,7 +95,6 @@ GROQ_API_KEY= ```bash ASSISTANT_NAME=claude STATUS_CHANNEL_ID= -SESSION_COMMAND_ALLOWED_SENDERS= MAX_CONCURRENT_AGENTS=5 ``` @@ -113,7 +112,8 @@ EJCLAW_ATTACHMENT_ALLOWED_DIRS=~/Pictures/Screenshots,~/Downloads/ejclaw-images - `ASSISTANT_NAME`은 owner trigger 기본 이름을 만듭니다 - paired room에서도 사용자 진입점은 owner가 기준입니다 -- status dashboard와 session command는 선택 설정입니다 +- status dashboard는 선택 설정입니다 +- `/compact`·`/clear`·`/stop` 세션 명령과 `SESSION_COMMAND_ALLOWED_SENDERS`는 제거됐습니다. 남아 있는 값은 무시됩니다. 작업 중단은 방에 "그만"·"멈춰"·"stop" 같은 짧은 메시지를 보내면 됩니다(README "작업 중단" 참고) ## 디버깅 경로 diff --git a/runners/agent-runner/src/index.ts b/runners/agent-runner/src/index.ts index 5fc1f3b..be8f9b2 100644 --- a/runners/agent-runner/src/index.ts +++ b/runners/agent-runner/src/index.ts @@ -40,7 +40,6 @@ import { writeOutput, } from './output-protocol.js'; import { buildClaudeSdkEnv } from './sdk-env.js'; -import { runSessionCommand } from './session-command.js'; import { runClaudeQuery } from './claude-query-runner.js'; import type { RunnerInput } from './runner-input.js'; @@ -124,9 +123,6 @@ async function main(): Promise { /* ignore */ } - // Effective working directory (WORK_DIR overrides GROUP_DIR) - const mainEffectiveCwd = WORK_DIR || GROUP_DIR; - // Build initial prompt (drain any pending IPC messages too) let prompt = runnerInput.prompt; if (runnerInput.isScheduledTask) { @@ -137,35 +133,7 @@ async function main(): Promise { log(`Draining ${pending.length} pending IPC messages into initial prompt`); prompt += '\n' + pending.join('\n'); } - // --- Slash command handling --- - // Check BEFORE prepending room role header so /compact isn't masked. - const KNOWN_SESSION_COMMANDS = new Set(['/compact']); - const isSessionSlashCommand = KNOWN_SESSION_COMMANDS.has( - runnerInput.prompt.trim(), - ); - - if (!isSessionSlashCommand) { - prompt = prependRoomRoleHeader(prompt, runnerInput.roomRoleContext); - } - const trimmedPrompt = prompt.trim(); - - if (isSessionSlashCommand) { - log(`Handling session command: ${trimmedPrompt}`); - await runSessionCommand({ - prompt: trimmedPrompt, - sessionId, - cwd: mainEffectiveCwd, - sdkEnv: guardedSdkEnv, - abortController: agentAbortController, - assistantName: runnerInput.assistantName, - groupDir: GROUP_DIR, - groupFolder: GROUP_FOLDER, - hostTasksDir: HOST_TASKS_DIR, - log, - }); - return; - } - // --- End slash command handling --- + prompt = prependRoomRoleHeader(prompt, runnerInput.roomRoleContext); try { log(`Starting query (session: ${sessionId || 'new'})...`); diff --git a/runners/agent-runner/src/session-command.ts b/runners/agent-runner/src/session-command.ts deleted file mode 100644 index 5fb02fa..0000000 --- a/runners/agent-runner/src/session-command.ts +++ /dev/null @@ -1,151 +0,0 @@ -import { query } from '@anthropic-ai/claude-agent-sdk'; - -import { compactBoundaryFromMessage } from './compaction-boundary.js'; -import { getClaudeCliPath } from './claude-cli.js'; -import { createPreCompactHook } from './runner-hooks.js'; -import { - buildCompactionOutput, - type RunnerCompaction, - writeOutput, -} from './output-protocol.js'; - -export interface RunSessionCommandArgs { - prompt: string; - sessionId?: string; - cwd: string; - sdkEnv: Record; - abortController: AbortController; - assistantName?: string; - groupDir: string; - groupFolder: string; - hostTasksDir: string; - log: (message: string) => void; -} - -export async function runSessionCommand({ - prompt, - sessionId, - cwd, - sdkEnv, - abortController, - assistantName, - groupDir, - groupFolder, - hostTasksDir, - log, -}: RunSessionCommandArgs): Promise { - let slashSessionId: string | undefined; - let compactBoundarySeen = false; - let slashCompaction: RunnerCompaction | undefined; - let hadError = false; - let resultEmitted = false; - - try { - for await (const message of query({ - prompt, - options: { - pathToClaudeCodeExecutable: getClaudeCliPath(log), - cwd, - resume: sessionId, - systemPrompt: undefined, - allowedTools: [], - env: sdkEnv, - permissionMode: 'bypassPermissions' as const, - allowDangerouslySkipPermissions: true, - settingSources: ['project', 'user'] as const, - abortController, - hooks: { - PreCompact: [ - { - hooks: [ - createPreCompactHook({ - assistantName, - groupDir, - groupFolder, - hostTasksDir, - log, - writeOutput, - }), - ], - }, - ], - }, - }, - })) { - const msgType = - message.type === 'system' - ? `system/${(message as { subtype?: string }).subtype}` - : message.type; - log(`[slash-cmd] type=${msgType}`); - - if (message.type === 'system' && message.subtype === 'init') { - slashSessionId = message.session_id; - log(`Session after slash command: ${slashSessionId}`); - } - - const observedCompaction = compactBoundaryFromMessage(message, log); - if (observedCompaction) { - compactBoundarySeen = true; - slashCompaction = observedCompaction; - } - - if (message.type === 'result') { - const resultSubtype = (message as { subtype?: string }).subtype; - const textResult = - 'result' in message ? (message as { result?: string }).result : null; - - if (resultSubtype?.startsWith('error')) { - hadError = true; - writeOutput({ - status: 'error', - result: null, - error: textResult || 'Session command failed.', - newSessionId: slashSessionId, - ...buildCompactionOutput(slashCompaction), - }); - } else { - writeOutput({ - status: 'success', - result: textResult || 'Conversation compacted.', - newSessionId: slashSessionId, - ...buildCompactionOutput(slashCompaction), - }); - } - resultEmitted = true; - } - } - } catch (err) { - hadError = true; - const errorMsg = err instanceof Error ? err.message : String(err); - log(`Slash command error: ${errorMsg}`); - writeOutput({ status: 'error', result: null, error: errorMsg }); - } - - log( - `Slash command done. compactBoundarySeen=${compactBoundarySeen}, hadError=${hadError}`, - ); - - if (!hadError && !compactBoundarySeen) { - log( - 'WARNING: compact_boundary was not observed. Compaction may not have completed.', - ); - } - - if (!resultEmitted && !hadError) { - writeOutput({ - status: 'success', - result: compactBoundarySeen - ? 'Conversation compacted.' - : 'Compaction requested but compact_boundary was not observed.', - newSessionId: slashSessionId, - ...buildCompactionOutput(slashCompaction), - }); - } else if (!hadError) { - writeOutput({ - status: 'success', - result: null, - newSessionId: slashSessionId, - ...buildCompactionOutput(slashCompaction), - }); - } -} diff --git a/src/bot-message-filter.test.ts b/src/bot-message-filter.test.ts index 529c689..34eb497 100644 --- a/src/bot-message-filter.test.ts +++ b/src/bot-message-filter.test.ts @@ -108,7 +108,7 @@ describe('filterProcessableMessages', () => { expect(result).toHaveLength(2); }); - it('filters session command control bot messages in paired rooms', () => { + it('filters the stop confirmation bot message in paired rooms', () => { const isOwn = (m: NewMessage) => m.is_bot_message === true && m.sender === OWN_BOT_ID; const result = filterProcessableMessages( @@ -118,8 +118,7 @@ describe('filterProcessableMessages', () => { id: 'control-1', sender: 'other-bot-456', sender_name: 'OtherBot', - content: - 'Current session cleared. The next message will start a new conversation.', + content: '진행 중이던 작업을 중단했습니다.', is_bot_message: true, }), makeMsg({ diff --git a/src/bot-message-filter.ts b/src/bot-message-filter.ts index bb717c4..3439914 100644 --- a/src/bot-message-filter.ts +++ b/src/bot-message-filter.ts @@ -1,4 +1,4 @@ -import { isSessionCommandControlMessage } from './session-commands.js'; +import { USER_STOP_REPLY } from './stop-intent.js'; import { NewMessage } from './types.js'; const PAIRED_EXECUTION_CONTROL_MESSAGE_PATTERN = @@ -8,6 +8,10 @@ function isPairedExecutionControlMessage(content: string): boolean { return PAIRED_EXECUTION_CONTROL_MESSAGE_PATTERN.test(content.trim()); } +function isUserStopReply(content: string): boolean { + return content.trim() === USER_STOP_REPLY; +} + /** * Filter messages before processing. * - Normal rooms: drop all bot messages. @@ -23,7 +27,7 @@ export function filterProcessableMessages( (message) => !( message.is_bot_message && - (isSessionCommandControlMessage(message.content) || + (isUserStopReply(message.content) || isPairedExecutionControlMessage(message.content)) ), ); diff --git a/src/config.test.ts b/src/config.test.ts index 001f70b..29dd5ad 100644 --- a/src/config.test.ts +++ b/src/config.test.ts @@ -41,6 +41,7 @@ describe('config/env loading', () => { delete process.env.CODEX_WARMUP_FAILURE_COOLDOWN_MS; delete process.env.CODEX_WARMUP_MAX_CONSECUTIVE_FAILURES; delete process.env.SESSION_COMMAND_USER_IDS; + delete process.env.SESSION_COMMAND_ALLOWED_SENDERS; vi.resetModules(); }); @@ -168,13 +169,12 @@ describe('config/env loading', () => { ); }); - it('fails fast when SESSION_COMMAND_USER_IDS is configured', async () => { + it('ignores stale session command keys left in the environment', async () => { process.env.SESSION_COMMAND_USER_IDS = 'alice,bob'; + process.env.SESSION_COMMAND_ALLOWED_SENDERS = 'alice'; const { loadConfig } = await import('./config/load-config.js'); - expect(() => loadConfig()).toThrow( - /Legacy env aliases are no longer supported; remove or rename \(SESSION_COMMAND_USER_IDS\) to the canonical keys/, - ); + expect(() => loadConfig()).not.toThrow(); }); }); diff --git a/src/config.ts b/src/config.ts index 2c0ad46..b052967 100644 --- a/src/config.ts +++ b/src/config.ts @@ -142,9 +142,3 @@ export const CODEX_WARMUP_CONFIG = CONFIG.codexWarmup; // Timezone for scheduled tasks (cron expressions, etc.) // Uses system timezone by default export const TIMEZONE = CONFIG.status.timezone; - -const SESSION_COMMAND_ALLOWED_SENDERS = CONFIG.sessionCommands.allowedSenders; - -export function isSessionCommandSenderAllowed(sender: string): boolean { - return SESSION_COMMAND_ALLOWED_SENDERS.has(sender); -} diff --git a/src/config/load-config.ts b/src/config/load-config.ts index 27a2352..7d206c5 100644 --- a/src/config/load-config.ts +++ b/src/config/load-config.ts @@ -12,10 +12,6 @@ const CANONICAL_DISCORD_CHANNEL_TOKEN_KEYS = new Set([ 'DISCORD_ARBITER_BOT_TOKEN', ]); -const CANONICAL_SESSION_COMMAND_KEYS = new Set([ - 'SESSION_COMMAND_ALLOWED_SENDERS', -]); - function readText(key: string): string | undefined { return getEnv(key); } @@ -90,9 +86,6 @@ function assertNoLegacyEnvAliasesConfigured(): void { if (key.startsWith('DISCORD_') && key.endsWith('_BOT_TOKEN')) { return !CANONICAL_DISCORD_CHANNEL_TOKEN_KEYS.has(key); } - if (key.startsWith('SESSION_COMMAND_')) { - return !CANONICAL_SESSION_COMMAND_KEYS.has(key); - } return false; }); @@ -101,7 +94,7 @@ function assertNoLegacyEnvAliasesConfigured(): void { } throw new Error( - `Legacy env aliases are no longer supported; remove or rename (${configuredAliases.join(', ')}) to the canonical keys DISCORD_OWNER_BOT_TOKEN, DISCORD_REVIEWER_BOT_TOKEN, DISCORD_ARBITER_BOT_TOKEN, SESSION_COMMAND_ALLOWED_SENDERS`, + `Legacy env aliases are no longer supported; remove or rename (${configuredAliases.join(', ')}) to the canonical keys DISCORD_OWNER_BOT_TOKEN, DISCORD_REVIEWER_BOT_TOKEN, DISCORD_ARBITER_BOT_TOKEN`, ); } @@ -270,13 +263,5 @@ export function loadConfig(): AppConfig { 1, ), }, - sessionCommands: { - allowedSenders: new Set( - (readText('SESSION_COMMAND_ALLOWED_SENDERS') ?? '') - .split(',') - .map((value) => value.trim()) - .filter(Boolean), - ), - }, }; } diff --git a/src/config/schema.ts b/src/config/schema.ts index e6b1bae..02d4692 100644 --- a/src/config/schema.ts +++ b/src/config/schema.ts @@ -88,7 +88,4 @@ export interface AppConfig { failureCooldownMs: number; maxConsecutiveFailures: number; }; - sessionCommands: { - allowedSenders: Set; - }; } diff --git a/src/db.ts b/src/db.ts index a2bbeb5..ebb7afe 100644 --- a/src/db.ts +++ b/src/db.ts @@ -105,6 +105,7 @@ export { refreshPairedTaskExecutionLease, recoverInterruptedPairedTurnAttemptsForService, releasePairedTaskExecutionLease, + releasePairedTaskExecutionLeasesForTask, reservePairedTurnReservation, setChannelOwnerLease, updatePairedTask, diff --git a/src/db/paired-state.ts b/src/db/paired-state.ts index 197c38b..5b97601 100644 --- a/src/db/paired-state.ts +++ b/src/db/paired-state.ts @@ -823,6 +823,16 @@ export function releasePairedTaskExecutionLeaseInDatabase( .run(args.taskId, CURRENT_SERVICE_ID, args.runId); } +/** Drop every execution lease held on a task, regardless of the claiming run. */ +export function releasePairedTaskExecutionLeasesForTaskInDatabase( + database: Database, + taskId: string, +): number { + return database + .prepare('DELETE FROM paired_task_execution_leases WHERE task_id = ?') + .run(taskId).changes; +} + export function refreshPairedTaskExecutionLeaseInDatabase( database: Database, args: { diff --git a/src/db/runtime-paired.ts b/src/db/runtime-paired.ts index 82a58e3..2e0de67 100644 --- a/src/db/runtime-paired.ts +++ b/src/db/runtime-paired.ts @@ -35,6 +35,7 @@ import { listPairedWorkspacesForTaskFromDatabase, refreshPairedTaskExecutionLeaseInDatabase, releasePairedTaskExecutionLeaseInDatabase, + releasePairedTaskExecutionLeasesForTaskInDatabase, reservePairedTurnReservationInDatabase, updatePairedTaskIfUnchangedInDatabase, updatePairedTaskInDatabase, @@ -172,6 +173,15 @@ export function releasePairedTaskExecutionLease(args: { releasePairedTaskExecutionLeaseInDatabase(requireDatabase(), args); } +export function releasePairedTaskExecutionLeasesForTask( + taskId: string, +): number { + return releasePairedTaskExecutionLeasesForTaskInDatabase( + requireDatabase(), + taskId, + ); +} + export function refreshPairedTaskExecutionLease(args: { taskId: string; runId: string; diff --git a/src/group-queue.ts b/src/group-queue.ts index e6933ee..ae364c6 100644 --- a/src/group-queue.ts +++ b/src/group-queue.ts @@ -511,7 +511,7 @@ export class GroupQueue { runId: state.currentRunId, processName: state.processName, }, - 'Killing agent process via /stop command', + 'Killing agent process on user stop request', ); try { // SIGTERM allows the runner to call AbortController.abort() for graceful cleanup. diff --git a/src/index.ts b/src/index.ts index 024516c..1d82ce9 100644 --- a/src/index.ts +++ b/src/index.ts @@ -10,7 +10,6 @@ import { STATUS_CHANNEL_ID, STATUS_UPDATE_INTERVAL, TIMEZONE, - TRIGGER_PATTERN, USAGE_UPDATE_INTERVAL, } from './config.js'; import './channels/index.js'; @@ -125,7 +124,6 @@ const runtime = createMessageRuntime({ idleTimeout: IDLE_TIMEOUT, pollInterval: POLL_INTERVAL, timezone: TIMEZONE, - triggerPattern: TRIGGER_PATTERN, channels, queue, getRoomBindings: runtimeState.getRoomBindings, diff --git a/src/message-close-reasons.ts b/src/message-close-reasons.ts index 2c8f18a..9ffad8b 100644 --- a/src/message-close-reasons.ts +++ b/src/message-close-reasons.ts @@ -1,7 +1,23 @@ export const HUMAN_MESSAGE_DETECTED_CLOSE_REASON = 'human-message-detected'; +export const USER_STOP_CLOSE_REASON = 'user-stop'; +/** + * True when a human interrupted the run, either with a new message or with an + * explicit stop request. Interrupted runs release their paired lease without + * counting a failure and do not queue follow-ups. + */ export function isHumanMessageCloseReason( reason: string | null | undefined, ): boolean { - return reason === HUMAN_MESSAGE_DETECTED_CLOSE_REASON; + return ( + reason === HUMAN_MESSAGE_DETECTED_CLOSE_REASON || + reason === USER_STOP_CLOSE_REASON + ); +} + +/** True when the run was killed because a human asked the room to stop. */ +export function isUserStopCloseReason( + reason: string | null | undefined, +): boolean { + return reason === USER_STOP_CLOSE_REASON; } diff --git a/src/message-runtime-dispatch.test.ts b/src/message-runtime-dispatch.test.ts index cbafe0b..7f5cd3e 100644 --- a/src/message-runtime-dispatch.test.ts +++ b/src/message-runtime-dispatch.test.ts @@ -70,7 +70,6 @@ function defaultArgs( channel, assistantName: '오너', failureFinalText: 'FAILED', - triggerPattern: /^\/clear\b/, hasImplicitContinuationWindow: vi.fn(() => false), lastAgentTimestamps: {}, saveState: vi.fn(), @@ -81,6 +80,11 @@ function defaultArgs( sendQueuedMessage: vi.fn(() => true), closeStdin: vi.fn(), isRunningMessageTurn: vi.fn(() => true), + roomStopControls: { + hasQueuedWork: vi.fn(() => true), + stopRunningAgent: vi.fn(() => true), + sendReply: vi.fn(async () => {}), + }, labelPairedSenders: vi.fn((_jid, messages) => messages), formatMessages: vi.fn((messages: NewMessage[]) => messages.map((item) => item.content).join('\n'), diff --git a/src/message-runtime-dispatch.ts b/src/message-runtime-dispatch.ts index 1d370ae..c7c1ccc 100644 --- a/src/message-runtime-dispatch.ts +++ b/src/message-runtime-dispatch.ts @@ -14,11 +14,7 @@ import { shouldSkipBotOnlyCollaboration, } from './message-runtime-rules.js'; import { enqueuePairedFollowUpAfterEvent } from './message-runtime-follow-up.js'; -import { - extractSessionCommand, - isSessionCommandAllowed, -} from './session-commands.js'; -import { isSessionCommandSenderAllowed } from './config.js'; +import { stopRoomWorkIfRequested, type RoomStopControls } from './room-stop.js'; import { hasReviewerLease } from './service-routing.js'; import type { ExecuteTurnFn } from './message-runtime-types.js'; import type { ScheduledPairedFollowUpIntentKind } from './paired-follow-up-scheduler.js'; @@ -224,7 +220,6 @@ export async function processLoopGroupMessages(args: { channel: Channel; assistantName: string; failureFinalText: string; - triggerPattern: RegExp; hasImplicitContinuationWindow: ( chatJid: string, messages: NewMessage[], @@ -242,11 +237,11 @@ export async function processLoopGroupMessages(args: { sendQueuedMessage: (chatJid: string, text: string) => boolean; closeStdin: (reason: string) => void; isRunningMessageTurn: (chatJid: string) => boolean; + roomStopControls: RoomStopControls; labelPairedSenders: (chatJid: string, messages: NewMessage[]) => NewMessage[]; formatMessages: (messages: NewMessage[], timezone: string) => string; }): Promise { const { chatJid, group, groupMessages, channel } = args; - const isMainGroup = group.isMain === true; const processableGroupMessages = getProcessableMessages( chatJid, groupMessages, @@ -284,21 +279,20 @@ export async function processLoopGroupMessages(args: { return; } - const loopCmdMsg = groupMessages.find( - (msg) => extractSessionCommand(msg.content, args.triggerPattern) !== null, - ); - - if (loopCmdMsg) { - if ( - isSessionCommandAllowed( - isMainGroup, - loopCmdMsg.is_from_me === true, - isSessionCommandSenderAllowed(loopCmdMsg.sender), - ) - ) { - args.closeStdin('session-command-detected'); + const stopResult = await stopRoomWorkIfRequested({ + chatJid, + group, + channel, + messages: processableGroupMessages, + assistantName: args.assistantName, + lastAgentTimestamps: args.lastAgentTimestamps, + saveState: args.saveState, + controls: args.roomStopControls, + }); + if (stopResult.stopped) { + if (stopResult.hasMessagesAfterStop) { + args.enqueueMessageCheck(); } - args.enqueueMessageCheck(); return; } diff --git a/src/message-runtime-gating.test.ts b/src/message-runtime-gating.test.ts deleted file mode 100644 index af2cbe8..0000000 --- a/src/message-runtime-gating.test.ts +++ /dev/null @@ -1,61 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest'; -import type { RegisteredGroup } from './types.js'; - -const { handleSessionCommandMock } = vi.hoisted(() => ({ - handleSessionCommandMock: vi.fn(), -})); - -vi.mock('./session-commands.js', () => ({ - handleSessionCommand: handleSessionCommandMock, -})); - -import { handleQueuedRunGates } from './message-runtime-gating.js'; - -function makeArgs(overrides: { - chatJid?: string; - sendMessage?: () => Promise; -}) { - return { - chatJid: overrides.chatJid ?? 'room-1', - group: { - folder: 'room-folder', - name: 'room', - isMain: false, - trigger: '코덱스', - added_at: new Date().toISOString(), - } satisfies RegisteredGroup, - runId: 'run-1', - missedMessages: [], - triggerPattern: /^코덱스/, - timezone: 'Asia/Seoul', - hasImplicitContinuationWindow: () => false, - sessionCommandDeps: { - sendMessage: overrides.sendMessage ?? (async () => {}), - } as never, - }; -} - -describe('message-runtime-gating', () => { - beforeEach(() => { - handleSessionCommandMock.mockReset(); - }); - - it('returns session-command results directly when a command is handled', async () => { - handleSessionCommandMock.mockResolvedValue({ - handled: true, - success: false, - }); - - const result = await handleQueuedRunGates(makeArgs({})); - - expect(result).toEqual({ handled: true, success: false }); - }); - - it('falls through when no session command matched', async () => { - handleSessionCommandMock.mockResolvedValue({ handled: false }); - - const result = await handleQueuedRunGates(makeArgs({})); - - expect(result).toEqual({ handled: false }); - }); -}); diff --git a/src/message-runtime-gating.ts b/src/message-runtime-gating.ts deleted file mode 100644 index 2a0c1c9..0000000 --- a/src/message-runtime-gating.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { - handleSessionCommand, - type SessionCommandDeps, -} from './session-commands.js'; -import type { NewMessage, RegisteredGroup } from './types.js'; - -export async function handleQueuedRunGates(args: { - chatJid: string; - group: RegisteredGroup; - runId: string; - missedMessages: NewMessage[]; - triggerPattern: RegExp; - timezone: string; - hasImplicitContinuationWindow: ( - chatJid: string, - messages: NewMessage[], - ) => boolean; - sessionCommandDeps: SessionCommandDeps; -}): Promise<{ handled: true; success: boolean } | { handled: false }> { - const cmdResult = await handleSessionCommand({ - missedMessages: args.missedMessages, - isMainGroup: args.group.isMain === true, - groupName: args.group.name, - runId: args.runId, - triggerPattern: args.triggerPattern, - timezone: args.timezone, - deps: args.sessionCommandDeps, - }); - if (cmdResult.handled) { - return cmdResult; - } - - return { handled: false }; -} diff --git a/src/message-runtime-group-processing.ts b/src/message-runtime-group-processing.ts index 2e80c79..fd1bc15 100644 --- a/src/message-runtime-group-processing.ts +++ b/src/message-runtime-group-processing.ts @@ -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, -) => Promise<'success' | 'error'>; - interface ProcessGroupMessagesDeps { assistantName: string; failureFinalText: string; timezone: string; - triggerPattern: RegExp; channels: Channel[]; - queue: Pick; + queue: Pick; getRoomBindings: () => Record; getLastAgentTimestamps: () => Record; 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 { - const gateResult = await handleQueuedRunGates({ +): Promise { + 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, chatJid: string, text: string, diff --git a/src/message-runtime-loop.ts b/src/message-runtime-loop.ts index 31fd03e..37cd4c0 100644 --- a/src/message-runtime-loop.ts +++ b/src/message-runtime-loop.ts @@ -13,13 +13,13 @@ import { import { SERVICE_SESSION_SCOPE } from './config.js'; import type { schedulePairedFollowUpWithMessageCheck } from './message-runtime-follow-up.js'; import type { ExecuteTurnFn } from './message-runtime-types.js'; +import type { RoomStopControls } from './room-stop.js'; import { findChannel, formatMessages } from './router.js'; import type { Channel, NewMessage, RegisteredGroup } from './types.js'; export async function processMessageLoopTick(args: { assistantName: string; failureFinalText: string; - triggerPattern: RegExp; timezone: string; channels: Channel[]; getRoomBindings: () => Record; @@ -41,6 +41,7 @@ export async function processMessageLoopTick(args: { sendQueuedMessage: (chatJid: string, text: string) => boolean; closeStdin: (chatJid: string, reason: string) => void; isRunningMessageTurn: (chatJid: string) => boolean; + roomStopControls: RoomStopControls; labelPairedSenders: (chatJid: string, messages: NewMessage[]) => NewMessage[]; }): Promise { args.enqueuePendingHandoffs(); @@ -87,7 +88,6 @@ export async function processMessageLoopTick(args: { channel, assistantName: args.assistantName, failureFinalText: args.failureFinalText, - triggerPattern: args.triggerPattern, hasImplicitContinuationWindow: args.hasImplicitContinuationWindow, lastAgentTimestamps: args.lastAgentTimestamps, saveState: args.saveState, @@ -107,6 +107,7 @@ export async function processMessageLoopTick(args: { sendQueuedMessage: args.sendQueuedMessage, closeStdin: (reason) => args.closeStdin(chatJid, reason), isRunningMessageTurn: args.isRunningMessageTurn, + roomStopControls: args.roomStopControls, labelPairedSenders: args.labelPairedSenders, formatMessages, }); diff --git a/src/message-runtime-progress-entry.test.ts b/src/message-runtime-progress-entry.test.ts index 73c77eb..66f0876 100644 --- a/src/message-runtime-progress-entry.test.ts +++ b/src/message-runtime-progress-entry.test.ts @@ -99,7 +99,6 @@ describe('message-runtime progress entry path', () => { idleTimeout: 1_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [ownerChannel, reviewerChannel], queue: { enqueueMessageCheck: vi.fn(), diff --git a/src/message-runtime-rules.ts b/src/message-runtime-rules.ts index 9f62be1..e25855c 100644 --- a/src/message-runtime-rules.ts +++ b/src/message-runtime-rules.ts @@ -62,14 +62,18 @@ export function advanceLastAgentCursor( cursorKey?: string, ): void { const key = cursorKey ?? chatJid; - if (typeof cursorOrTimestamp === 'number') { - lastAgentTimestamps[key] = String(cursorOrTimestamp); - } else { - lastAgentTimestamps[key] = normalizeStoredSeqCursor( - cursorOrTimestamp, - chatJid, - ); + const next = + typeof cursorOrTimestamp === 'number' + ? String(cursorOrTimestamp) + : normalizeStoredSeqCursor(cursorOrTimestamp, chatJid); + // Cursors only move forward. A run that finishes after a newer message was + // already consumed (e.g. a user stop request) must not rewind the cursor and + // re-dispatch that message. + const current = lastAgentTimestamps[key]; + if (current !== undefined && Number(next) < Number(current)) { + return; } + lastAgentTimestamps[key] = next; saveState(); } diff --git a/src/message-runtime.test.ts b/src/message-runtime.test.ts index 298b7f9..b610aa0 100644 --- a/src/message-runtime.test.ts +++ b/src/message-runtime.test.ts @@ -39,7 +39,6 @@ vi.mock('./config.js', () => ({ normalizeServiceId: vi.fn((serviceId: string) => serviceId), isClaudeService: vi.fn(() => true), isReviewService: vi.fn(() => false), - isSessionCommandSenderAllowed: vi.fn(() => false), TIMEZONE: 'Asia/Seoul', })); @@ -270,13 +269,6 @@ vi.mock('./sender-allowlist.js', () => ({ loadSenderAllowlist: vi.fn(() => ({})), })); -vi.mock('./session-commands.js', () => ({ - extractSessionCommand: vi.fn(() => null), - handleSessionCommand: vi.fn(async () => ({ handled: false })), - isSessionCommandAllowed: vi.fn(() => true), - isSessionCommandControlMessage: vi.fn(() => false), -})); - import * as agentRunner from './agent-runner.js'; import * as db from './db.js'; import { resolveGroupIpcPath } from './group-folder.js'; @@ -359,7 +351,6 @@ describe('createMessageRuntime', () => { idleTimeout: 1_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [channel], queue: { enqueueMessageCheck: vi.fn(), @@ -429,7 +420,6 @@ describe('createMessageRuntime', () => { idleTimeout: 1_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [channel], queue: { enqueueMessageCheck: vi.fn(), @@ -507,7 +497,6 @@ describe('createMessageRuntime', () => { idleTimeout: 1_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [channel], queue: { registerProcess: vi.fn(), @@ -559,7 +548,6 @@ describe('createMessageRuntime', () => { idleTimeout: 1_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [channel], queue: { registerProcess: vi.fn(), @@ -627,7 +615,6 @@ describe('createMessageRuntime', () => { idleTimeout: 1_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [channel], queue: { registerProcess: vi.fn(), @@ -753,7 +740,6 @@ describe('createMessageRuntime', () => { idleTimeout: 1_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [channel], queue: { registerProcess: vi.fn(), @@ -865,7 +851,6 @@ describe('createMessageRuntime', () => { idleTimeout: 1_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [channel], queue: { registerProcess: vi.fn(), @@ -949,7 +934,6 @@ describe('createMessageRuntime', () => { idleTimeout: 1_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [channel], queue: { registerProcess: vi.fn(), @@ -1039,7 +1023,6 @@ describe('createMessageRuntime', () => { idleTimeout: 1_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [ownerChannel], queue: { registerProcess: vi.fn(), @@ -1122,7 +1105,6 @@ describe('createMessageRuntime', () => { idleTimeout: 1_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [ownerChannel, reviewerChannel], queue: { registerProcess: vi.fn(), @@ -1216,7 +1198,6 @@ describe('createMessageRuntime', () => { idleTimeout: 1_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [ownerChannel, reviewerChannel], queue: { registerProcess: vi.fn(), @@ -1337,7 +1318,6 @@ describe('createMessageRuntime', () => { idleTimeout: 1_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [ownerChannel, reviewerChannel], queue: { registerProcess: vi.fn(), @@ -1430,7 +1410,6 @@ describe('createMessageRuntime', () => { idleTimeout: 1_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [ownerChannel, reviewerChannel], queue: { registerProcess: vi.fn(), @@ -1526,7 +1505,6 @@ describe('createMessageRuntime', () => { idleTimeout: 1_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [ownerChannel, reviewerChannel], queue: { registerProcess: vi.fn(), @@ -1603,7 +1581,6 @@ describe('createMessageRuntime', () => { idleTimeout: 1_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [channel], queue: { registerProcess: vi.fn(), @@ -1723,7 +1700,6 @@ describe('createMessageRuntime', () => { idleTimeout: 1_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [channel], queue: { registerProcess: vi.fn(), @@ -1830,7 +1806,6 @@ describe('createMessageRuntime', () => { idleTimeout: 1_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [channel], queue: { registerProcess: vi.fn(), @@ -2203,7 +2178,6 @@ describe('createMessageRuntime', () => { idleTimeout: 1_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [ownerChannel, reviewerChannel], queue: { registerProcess: vi.fn(), @@ -2322,7 +2296,6 @@ describe('createMessageRuntime', () => { idleTimeout: 1_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [ownerChannel, reviewerChannel], queue: { registerProcess: vi.fn(), @@ -2431,7 +2404,6 @@ describe('createMessageRuntime', () => { idleTimeout: 1_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [ownerChannel, reviewerChannel], queue: { registerProcess: vi.fn(), @@ -2559,7 +2531,6 @@ describe('createMessageRuntime', () => { idleTimeout: 1_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [ownerChannel, reviewerChannel], queue: { registerProcess: vi.fn(), @@ -2659,7 +2630,6 @@ describe('createMessageRuntime', () => { idleTimeout: 1_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [ownerChannel, reviewerChannel], queue: { registerProcess: vi.fn(), @@ -2755,7 +2725,6 @@ describe('createMessageRuntime', () => { idleTimeout: 1_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [ownerChannel, reviewerChannel], queue: { registerProcess: vi.fn(), @@ -2848,7 +2817,6 @@ describe('createMessageRuntime', () => { idleTimeout: 1_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [ownerChannel, reviewerChannel], queue: { registerProcess: vi.fn(), @@ -2943,7 +2911,6 @@ describe('createMessageRuntime', () => { idleTimeout: 1_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [ownerChannel, reviewerChannel, arbiterChannel], queue: { registerProcess: vi.fn(), @@ -3056,7 +3023,6 @@ describe('createMessageRuntime', () => { idleTimeout: 1_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [ownerChannel, reviewerChannel, arbiterChannel], queue: { registerProcess: vi.fn(), @@ -3172,7 +3138,6 @@ describe('createMessageRuntime', () => { idleTimeout: 1_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [ownerChannel, reviewerChannel], queue: { registerProcess: vi.fn(), @@ -3264,7 +3229,6 @@ describe('createMessageRuntime', () => { idleTimeout: 1_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [ownerChannel, reviewerChannel], queue: { registerProcess: vi.fn(), @@ -3353,7 +3317,6 @@ describe('createMessageRuntime', () => { idleTimeout: 1_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [ownerChannel, reviewerChannel], queue: { registerProcess: vi.fn(), @@ -3417,7 +3380,6 @@ describe('createMessageRuntime', () => { idleTimeout: 1_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [ownerChannel], queue: { enqueueMessageCheck: vi.fn(), @@ -3491,7 +3453,6 @@ describe('createMessageRuntime', () => { idleTimeout: 1_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [ownerChannel], queue: { registerProcess: vi.fn(), @@ -3561,7 +3522,6 @@ describe('createMessageRuntime', () => { idleTimeout: 1_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [ownerChannel], queue: { registerProcess: vi.fn(), @@ -3679,7 +3639,6 @@ describe('createMessageRuntime', () => { idleTimeout: 1_000, pollInterval: 1_000, timezone: 'Asia/Seoul', - triggerPattern: /^@Andy\b/i, channels: [ownerChannel, reviewerChannel], queue: { enqueueMessageCheck: vi.fn(), @@ -3795,7 +3754,6 @@ describe('createMessageRuntime', () => { idleTimeout: 1_000, pollInterval: 1_000, timezone: 'Asia/Seoul', - triggerPattern: /^@Andy\b/i, channels: [ownerChannel, arbiterChannel], queue: { registerProcess: vi.fn(), @@ -3873,7 +3831,6 @@ describe('createMessageRuntime', () => { idleTimeout: 60_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [channel], queue: { registerProcess: vi.fn(), @@ -3957,7 +3914,6 @@ describe('createMessageRuntime', () => { idleTimeout: 1_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [channel], queue: { registerProcess: vi.fn(), @@ -4049,7 +4005,6 @@ describe('createMessageRuntime', () => { idleTimeout: 1_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [channel], queue: { registerProcess: vi.fn(), @@ -4140,7 +4095,6 @@ describe('createMessageRuntime', () => { idleTimeout: 1_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [channel], queue: { registerProcess: vi.fn(), @@ -4241,7 +4195,6 @@ describe('createMessageRuntime', () => { idleTimeout: 1_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [channel], queue: { registerProcess: vi.fn(), @@ -4322,7 +4275,6 @@ describe('createMessageRuntime', () => { idleTimeout: 1_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [channel], queue: { registerProcess: vi.fn(), @@ -4424,7 +4376,6 @@ describe('createMessageRuntime', () => { idleTimeout: 20_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [channel], queue: { registerProcess: vi.fn(), @@ -4541,7 +4492,6 @@ describe('createMessageRuntime', () => { idleTimeout: 1_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [channel], queue: { registerProcess: vi.fn(), @@ -4647,7 +4597,6 @@ describe('createMessageRuntime', () => { idleTimeout: 1_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [channel], queue: { registerProcess: vi.fn(), @@ -4725,7 +4674,6 @@ describe('createMessageRuntime', () => { idleTimeout: 1_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [channel], queue: { registerProcess: vi.fn(), @@ -4786,7 +4734,6 @@ describe('createMessageRuntime', () => { idleTimeout: 1_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [channel], queue: { registerProcess: vi.fn(), @@ -4874,7 +4821,6 @@ describe('createMessageRuntime', () => { idleTimeout: 1_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [channel], queue: { registerProcess: vi.fn(), @@ -4949,7 +4895,6 @@ describe('createMessageRuntime', () => { idleTimeout: 1_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [channel], queue: { registerProcess: vi.fn(), @@ -5055,7 +5000,6 @@ describe('createMessageRuntime', () => { idleTimeout: 1_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [channel], queue: { registerProcess: vi.fn(), @@ -5181,7 +5125,6 @@ describe('createMessageRuntime', () => { idleTimeout: 1_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [channel], queue: { registerProcess: vi.fn(), @@ -5297,7 +5240,6 @@ describe('createMessageRuntime', () => { idleTimeout: 1_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [channel], queue: { registerProcess: vi.fn(), @@ -5378,7 +5320,6 @@ describe('createMessageRuntime', () => { idleTimeout: 60_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [channel], queue: { registerProcess: vi.fn(), @@ -5454,7 +5395,6 @@ describe('createMessageRuntime', () => { idleTimeout: 1_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [channel], queue: { registerProcess: vi.fn(), @@ -5537,7 +5477,6 @@ describe('createMessageRuntime', () => { idleTimeout: 1_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [channel], queue: { registerProcess: vi.fn(), @@ -5610,7 +5549,6 @@ describe('createMessageRuntime', () => { idleTimeout: 1_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [channel], queue: { registerProcess: vi.fn(), @@ -5668,7 +5606,6 @@ describe('createMessageRuntime', () => { idleTimeout: 1_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [makeChannel(chatJid)], queue: { registerProcess: vi.fn(), @@ -5728,7 +5665,6 @@ describe('createMessageRuntime', () => { idleTimeout: 1_000, pollInterval: 1_000, timezone: 'UTC', - triggerPattern: /^@Andy\b/i, channels: [makeChannel(chatJid)], queue: { registerProcess: vi.fn(), diff --git a/src/message-runtime.ts b/src/message-runtime.ts index 9a5e868..7633407 100644 --- a/src/message-runtime.ts +++ b/src/message-runtime.ts @@ -18,7 +18,12 @@ import { } from './message-runtime-turns.js'; import { handleMessageRuntimeAfterDeliverySuccess } from './message-runtime-after-delivery.js'; import { deliverMessageRuntimeFinalText } from './message-runtime-final-delivery.js'; -import { createProcessGroupMessages } from './message-runtime-group-processing.js'; +import { + createProcessGroupMessages, + deliverRoomNotice, +} from './message-runtime-group-processing.js'; +import { USER_STOP_CLOSE_REASON } from './message-close-reasons.js'; +import type { RoomStopControls } from './room-stop.js'; export { isDuplicateOfLastBotFinal }; @@ -27,7 +32,6 @@ export interface MessageRuntimeDeps { idleTimeout: number; pollInterval: number; timezone: string; - triggerPattern: RegExp; channels: Channel[]; queue: GroupQueue; getRoomBindings: () => Record; @@ -66,6 +70,26 @@ function createStartMessageLoop(args: { }; } +function createRoomStopControls( + deps: Pick, +): RoomStopControls { + return { + hasQueuedWork: (chatJid) => + (deps.queue.getStatuses([chatJid])[0]?.status ?? 'inactive') !== + 'inactive', + stopRunningAgent: (chatJid) => { + deps.queue.closeStdin(chatJid, { reason: USER_STOP_CLOSE_REASON }); + return deps.queue.killProcess(chatJid); + }, + sendReply: (chatJid, text) => + deliverRoomNotice( + { channels: deps.channels, getRoomBindings: deps.getRoomBindings }, + chatJid, + text, + ), + }; +} + export function createMessageRuntime(deps: MessageRuntimeDeps): { processGroupMessages: ( chatJid: string, @@ -181,28 +205,25 @@ export function createMessageRuntime(deps: MessageRuntimeDeps): { assistantName: deps.assistantName, failureFinalText: FAILURE_FINAL_TEXT, timezone: deps.timezone, - triggerPattern: deps.triggerPattern, channels: deps.channels, queue: deps.queue, getRoomBindings: deps.getRoomBindings, getLastAgentTimestamps: deps.getLastAgentTimestamps, saveState: deps.saveState, - clearSession: deps.clearSession, - runAgent, executeTurn, - hasImplicitContinuationWindow: continuationTracker.has, openContinuation: continuationTracker.open, isDuplicateOfLastBotFinal: checkDuplicateOfLastBotFinal, labelPairedSenders: labelPairedRuntimeSenders, }); + const roomStopControls = createRoomStopControls(deps); + const startMessageLoop = createStartMessageLoop({ pollInterval: deps.pollInterval, processTick: async () => { await processMessageLoopTick({ assistantName: deps.assistantName, failureFinalText: FAILURE_FINAL_TEXT, - triggerPattern: deps.triggerPattern, timezone: deps.timezone, channels: deps.channels, getRoomBindings: deps.getRoomBindings, @@ -222,6 +243,7 @@ export function createMessageRuntime(deps: MessageRuntimeDeps): { }), isRunningMessageTurn: (chatJid) => deps.queue.getStatuses([chatJid])[0]?.runPhase === 'running_messages', + roomStopControls, labelPairedSenders: labelPairedRuntimeSenders, }); }, diff --git a/src/message-turn-controller.test.ts b/src/message-turn-controller.test.ts index 362fccf..8bc7270 100644 --- a/src/message-turn-controller.test.ts +++ b/src/message-turn-controller.test.ts @@ -992,4 +992,28 @@ describe('MessageTurnController human interruptions', () => { expect(channel.sendAndTrack).toHaveBeenCalledTimes(1); expect(deliverFinalText).not.toHaveBeenCalled(); }); + + it('does not publish a failure final when the user stopped the run', async () => { + const channel = { ...makeChannel(), name: 'discord' } satisfies Channel; + const deliverFinalText = vi.fn().mockResolvedValue(true); + const controller = new MessageTurnController({ + chatJid: 'dc:test-room', + group: makeGroup(), + runId: 'run-user-stopped', + channel, + idleTimeout: 1_000, + failureFinalText: '실패', + isClaudeCodeAgent: true, + clearSession: vi.fn(), + requestClose: vi.fn(), + deliverFinalText, + deliveryRole: 'owner', + getCloseReason: () => 'user-stop', + }); + + await controller.start(); + await controller.finish('error'); + + expect(deliverFinalText).not.toHaveBeenCalled(); + }); }); diff --git a/src/message-turn-controller.ts b/src/message-turn-controller.ts index c043aa2..46d8488 100644 --- a/src/message-turn-controller.ts +++ b/src/message-turn-controller.ts @@ -10,7 +10,10 @@ import { shouldResetSessionOnAgentFailure } from './session-recovery.js'; import { TASK_STATUS_MESSAGE_PREFIX } from './task-watch-status.js'; import { formatElapsedKorean } from './utils.js'; import type { PairedTurnIdentity } from './paired-turn-identity.js'; -import { isHumanMessageCloseReason } from './message-close-reasons.js'; +import { + isHumanMessageCloseReason, + isUserStopCloseReason, +} from './message-close-reasons.js'; import { normalizeAgentOutputPhase, toVisiblePhase, @@ -872,6 +875,12 @@ export class MessageTurnController { if (this.terminalObserved()) { return; } + if (isUserStopCloseReason(this.options.getCloseReason?.() ?? null)) { + // The user asked the room to stop and already got a stop reply; the + // killed run must not add a "failed" message on top of it. + this.log.info('Skipped failure final because the user stopped the run'); + return; + } await this.publishTerminalText( appendErrorDetailToFailureText( this.options.failureFinalText, diff --git a/src/room-stop.test.ts b/src/room-stop.test.ts new file mode 100644 index 0000000..4ca0b85 --- /dev/null +++ b/src/room-stop.test.ts @@ -0,0 +1,328 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +vi.mock('./service-routing.js', () => ({ + hasReviewerLease: vi.fn(() => false), + resolveLeaseServiceId: vi.fn(() => null), +})); + +import { + _initTestDatabase, + claimPairedTurnReservation, + createPairedTask, + getMessagesSinceSeq, + getPairedTaskById, + getPairedTurnsForTask, + reservePairedTurnReservation, + storeChatMetadata, + storeMessage, +} from './db.js'; +import { requireDatabase } from './db/runtime-database.js'; +import { processLoopGroupMessages } from './message-runtime-dispatch.js'; +import { advanceLastAgentCursor } from './message-runtime-rules.js'; +import { hasReviewerLease } from './service-routing.js'; +import { USER_STOP_REPLY } from './stop-intent.js'; +import type { + Channel, + NewMessage, + PairedTask, + RegisteredGroup, +} from './types.js'; + +const chatJid = 'dc:stop-room'; +const assistantName = '오너'; + +const group: RegisteredGroup = { + name: 'Stop Room', + folder: 'stop-room', + trigger: '@오너', + added_at: '2026-10-01T00:00:00.000Z', + requiresTrigger: false, +}; + +const channel: Channel = { + name: 'discord', + connect: vi.fn(), + sendMessage: vi.fn(), + isConnected: vi.fn(() => true), + ownsJid: vi.fn(() => true), + disconnect: vi.fn(), +}; + +let messageCounter = 0; + +function postHumanMessage(content: string): NewMessage { + messageCounter += 1; + storeMessage({ + id: `msg-${messageCounter}`, + chat_jid: chatJid, + sender: 'user-1', + sender_name: 'User', + content, + timestamp: new Date( + Date.UTC(2026, 9, 1, 0, 0, messageCounter), + ).toISOString(), + is_from_me: false, + is_bot_message: false, + }); + const stored = getMessagesSinceSeq(chatJid, '0', assistantName).find( + (message) => message.id === `msg-${messageCounter}`, + ); + if (!stored) throw new Error('stored message not found'); + return stored; +} + +function makeTask(overrides: Partial = {}): PairedTask { + return { + id: 'stop-task', + chat_jid: chatJid, + group_folder: group.folder, + owner_service_id: 'claude', + reviewer_service_id: 'codex-review', + owner_agent_type: 'claude-code', + reviewer_agent_type: 'codex', + arbiter_agent_type: null, + title: null, + source_ref: 'HEAD', + plan_notes: null, + review_requested_at: null, + round_trip_count: 1, + owner_failure_count: 0, + owner_step_done_streak: 0, + finalize_step_done_count: 0, + task_done_then_user_reopen_count: 0, + empty_step_done_streak: 0, + status: 'in_review', + arbiter_verdict: null, + arbiter_requested_at: null, + completion_reason: null, + created_at: '2026-10-01T00:00:00.000Z', + updated_at: '2026-10-01T00:05:00.000Z', + ...overrides, + }; +} + +function makeControls(hasQueuedWork: boolean) { + return { + hasQueuedWork: vi.fn(() => hasQueuedWork), + stopRunningAgent: vi.fn(() => hasQueuedWork), + sendReply: vi.fn(async () => {}), + }; +} + +function makeArgs(args: { + groupMessages: NewMessage[]; + lastAgentTimestamps: Record; + controls: ReturnType; +}) { + return { + chatJid, + group, + groupMessages: args.groupMessages, + channel, + assistantName, + failureFinalText: 'FAILED', + hasImplicitContinuationWindow: vi.fn(() => false), + lastAgentTimestamps: args.lastAgentTimestamps, + saveState: vi.fn(), + timezone: 'Asia/Seoul', + executeTurn: vi.fn(), + schedulePairedFollowUp: vi.fn(() => true), + enqueueMessageCheck: vi.fn(), + sendQueuedMessage: vi.fn(() => true), + closeStdin: vi.fn(), + isRunningMessageTurn: vi.fn(() => args.controls.hasQueuedWork()), + roomStopControls: args.controls, + labelPairedSenders: vi.fn( + (_jid: string, messages: NewMessage[]) => messages, + ), + formatMessages: vi.fn((messages: NewMessage[]) => + messages.map((item) => item.content).join('\n'), + ), + } satisfies Parameters[0]; +} + +describe('natural-language stop in the message loop', () => { + beforeEach(() => { + _initTestDatabase(); + vi.clearAllMocks(); + vi.mocked(hasReviewerLease).mockReturnValue(false); + storeChatMetadata(chatJid, '2026-10-01T00:00:00.000Z', 'Stop Room'); + }); + + it('kills the running agent, consumes the messages and replies once', async () => { + const request = postHumanMessage('README 정리해줘'); + const stop = postHumanMessage('그만해'); + const controls = makeControls(true); + const lastAgentTimestamps: Record = { + [chatJid]: String(request.seq! - 1), + }; + const args = makeArgs({ + groupMessages: [stop], + lastAgentTimestamps, + controls, + }); + + await processLoopGroupMessages(args); + + expect(controls.stopRunningAgent).toHaveBeenCalledWith(chatJid); + expect(controls.sendReply).toHaveBeenCalledTimes(1); + expect(controls.sendReply).toHaveBeenCalledWith(chatJid, USER_STOP_REPLY); + expect(lastAgentTimestamps[chatJid]).toBe(String(stop.seq)); + expect(args.saveState).toHaveBeenCalled(); + // The stop message must not start or interrupt into a new turn. + expect(args.enqueueMessageCheck).not.toHaveBeenCalled(); + expect(args.closeStdin).not.toHaveBeenCalled(); + expect(args.sendQueuedMessage).not.toHaveBeenCalled(); + + // A run that finishes later with an older end seq cannot rewind the cursor. + advanceLastAgentCursor( + lastAgentTimestamps, + args.saveState, + chatJid, + request.seq!, + ); + expect(lastAgentTimestamps[chatJid]).toBe(String(stop.seq)); + }); + + it('treats a stop phrase as a normal message when nothing is running or pending', async () => { + const stop = postHumanMessage('그만'); + const controls = makeControls(false); + const lastAgentTimestamps: Record = { + [chatJid]: String(stop.seq! - 1), + }; + const args = makeArgs({ + groupMessages: [stop], + lastAgentTimestamps, + controls, + }); + + await processLoopGroupMessages(args); + + expect(controls.stopRunningAgent).not.toHaveBeenCalled(); + expect(controls.sendReply).not.toHaveBeenCalled(); + expect(lastAgentTimestamps[chatJid]).toBe(String(stop.seq! - 1)); + expect(args.enqueueMessageCheck).toHaveBeenCalledTimes(1); + }); + + it('drops unprocessed requests that are still waiting before the stop', async () => { + const request = postHumanMessage('배포 스크립트 고쳐줘'); + const stop = postHumanMessage('멈춰!'); + const controls = makeControls(false); + const lastAgentTimestamps: Record = { + [chatJid]: String(request.seq! - 1), + }; + const args = makeArgs({ + groupMessages: [request, stop], + lastAgentTimestamps, + controls, + }); + + await processLoopGroupMessages(args); + + expect(controls.sendReply).toHaveBeenCalledWith(chatJid, USER_STOP_REPLY); + expect(lastAgentTimestamps[chatJid]).toBe(String(stop.seq)); + expect(args.enqueueMessageCheck).not.toHaveBeenCalled(); + }); + + it('still processes a new instruction sent after the stop', async () => { + const stop = postHumanMessage('중단'); + const next = postHumanMessage('대신 테스트만 돌려줘'); + const controls = makeControls(true); + const lastAgentTimestamps: Record = { + [chatJid]: String(stop.seq! - 1), + }; + const args = makeArgs({ + groupMessages: [stop, next], + lastAgentTimestamps, + controls, + }); + + await processLoopGroupMessages(args); + + expect(controls.stopRunningAgent).toHaveBeenCalledTimes(1); + expect(lastAgentTimestamps[chatJid]).toBe(String(stop.seq)); + expect(args.enqueueMessageCheck).toHaveBeenCalledTimes(1); + }); + + it('does not stop on messages that carry another instruction', async () => { + const message = postHumanMessage('그거 하지 말고 이거 해줘'); + const controls = makeControls(true); + const lastAgentTimestamps: Record = { + [chatJid]: String(message.seq! - 1), + }; + const args = makeArgs({ + groupMessages: [message], + lastAgentTimestamps, + controls, + }); + + await processLoopGroupMessages(args); + + expect(controls.stopRunningAgent).not.toHaveBeenCalled(); + expect(controls.sendReply).not.toHaveBeenCalled(); + expect(args.closeStdin).toHaveBeenCalledWith('human-message-detected'); + expect(args.enqueueMessageCheck).toHaveBeenCalledTimes(1); + }); + + it('closes the open paired task, cancels its turn and releases the lease', async () => { + vi.mocked(hasReviewerLease).mockReturnValue(true); + const task = makeTask(); + createPairedTask(task); + expect( + reservePairedTurnReservation({ + chatJid, + taskId: task.id, + taskStatus: task.status, + roundTripCount: task.round_trip_count, + taskUpdatedAt: task.updated_at, + intentKind: 'reviewer-turn', + runId: 'run-reviewer', + }), + ).toBe(true); + expect( + claimPairedTurnReservation({ + chatJid, + taskId: task.id, + taskStatus: task.status, + roundTripCount: task.round_trip_count, + taskUpdatedAt: task.updated_at, + intentKind: 'reviewer-turn', + runId: 'run-reviewer', + }), + ).toBe(true); + + const stop = postHumanMessage('<@123456789> 작업 중단해줘'); + const controls = makeControls(false); + const reviewerKey = `${chatJid}:reviewer`; + const lastAgentTimestamps: Record = { + [chatJid]: String(stop.seq! - 1), + [reviewerKey]: String(stop.seq! - 1), + }; + const args = makeArgs({ + groupMessages: [stop], + lastAgentTimestamps, + controls, + }); + + await processLoopGroupMessages(args); + + expect(getPairedTaskById(task.id)).toMatchObject({ + status: 'completed', + completion_reason: 'user_stopped', + }); + expect(getPairedTurnsForTask(task.id)).toEqual([ + expect.objectContaining({ state: 'cancelled' }), + ]); + const leaseCount = requireDatabase() + .prepare( + 'SELECT COUNT(*) AS count FROM paired_task_execution_leases WHERE task_id = ?', + ) + .get(task.id) as { count: number }; + expect(leaseCount.count).toBe(0); + expect(lastAgentTimestamps[chatJid]).toBe(String(stop.seq)); + expect(lastAgentTimestamps[reviewerKey]).toBe(String(stop.seq)); + expect(controls.stopRunningAgent).toHaveBeenCalledWith(chatJid); + expect(controls.sendReply).toHaveBeenCalledWith(chatJid, USER_STOP_REPLY); + expect(args.enqueueMessageCheck).not.toHaveBeenCalled(); + }); +}); diff --git a/src/room-stop.ts b/src/room-stop.ts new file mode 100644 index 0000000..c832002 --- /dev/null +++ b/src/room-stop.ts @@ -0,0 +1,234 @@ +import { + cancelPairedTurn, + getLatestOpenPairedTaskForChat, + getMessagesSinceSeq, + getPairedTaskById, + getPairedTurnsForTask, + releasePairedTaskExecutionLeasesForTask, +} from './db.js'; +import { logger } from './logger.js'; +import { + advanceLastAgentCursor, + getProcessableMessages, + isExternalHumanMessage, + resolveCursorKeyForRole, +} from './message-runtime-rules.js'; +import { transitionPairedTaskStatus } from './paired-task-status.js'; +import { buildPairedTurnIdentity } from './paired-turn-identity.js'; +import { hasReviewerLease } from './service-routing.js'; +import { isStopIntent, USER_STOP_REPLY } from './stop-intent.js'; +import type { + Channel, + NewMessage, + PairedTask, + RegisteredGroup, +} from './types.js'; + +export const USER_STOP_COMPLETION_REASON = 'user_stopped'; + +const OPEN_TURN_STATES = new Set(['queued', 'running', 'delegated']); + +export interface RoomStopControls { + /** True when the group queue has a run in progress or work waiting. */ + hasQueuedWork: (chatJid: string) => boolean; + /** Close stdin with the stop reason and kill the room's running agent. */ + stopRunningAgent: (chatJid: string) => boolean; + sendReply: (chatJid: string, text: string) => Promise; +} + +export type RoomStopResult = + | { stopped: false } + | { stopped: true; hasMessagesAfterStop: boolean }; + +/** The latest human message in the batch whose whole intent is "stop". */ +export function findStopRequest(messages: NewMessage[]): NewMessage | null { + for (let index = messages.length - 1; index >= 0; index -= 1) { + const message = messages[index]; + if ( + message.seq != null && + isExternalHumanMessage(message) && + isStopIntent(message.content) + ) { + return message; + } + } + return null; +} + +function hasPendingHumanMessageBefore(args: { + chatJid: string; + channel: Channel; + assistantName: string; + lastAgentTimestamps: Record; + stopSeq: number; +}): boolean { + const raw = getMessagesSinceSeq( + args.chatJid, + args.lastAgentTimestamps[args.chatJid] || '0', + args.assistantName, + ); + return getProcessableMessages(args.chatJid, raw, args.channel).some( + (message) => + message.seq != null && + message.seq < args.stopSeq && + isExternalHumanMessage(message), + ); +} + +function advanceRoomCursorsPast(args: { + chatJid: string; + stopSeq: number; + lastAgentTimestamps: Record; + saveState: () => void; +}): void { + const keys = new Set([args.chatJid]); + for (const role of ['reviewer', 'arbiter'] as const) { + const key = resolveCursorKeyForRole(args.chatJid, role); + if (args.lastAgentTimestamps[key] !== undefined) keys.add(key); + } + for (const key of keys) { + advanceLastAgentCursor( + args.lastAgentTimestamps, + args.saveState, + args.chatJid, + args.stopSeq, + key, + ); + } +} + +function completeTaskAsStopped(task: PairedTask): boolean { + let current: PairedTask | undefined = task; + for (let attempt = 0; attempt < 3; attempt += 1) { + if (!current || current.status === 'completed') return false; + const transitioned = transitionPairedTaskStatus({ + taskId: current.id, + currentStatus: current.status, + nextStatus: 'completed', + expectedUpdatedAt: current.updated_at, + updatedAt: new Date().toISOString(), + patch: { completion_reason: USER_STOP_COMPLETION_REASON }, + }); + if (transitioned) return true; + current = getPairedTaskById(task.id); + } + return false; +} + +function cancelOpenTurns(taskId: string): number { + let cancelled = 0; + for (const turn of getPairedTurnsForTask(taskId)) { + if (!OPEN_TURN_STATES.has(turn.state)) continue; + try { + cancelPairedTurn({ + turnIdentity: buildPairedTurnIdentity({ + taskId: turn.task_id, + taskUpdatedAt: turn.task_updated_at, + intentKind: turn.intent_kind, + role: turn.role, + turnId: turn.turn_id, + }), + error: 'Stopped by user request.', + }); + cancelled += 1; + } catch (err) { + logger.warn( + { taskId, turnId: turn.turn_id, err }, + 'Failed to cancel paired turn while stopping room work', + ); + } + } + return cancelled; +} + +function closePairedTaskForStop(task: PairedTask): { + completed: boolean; + cancelledTurns: number; + releasedLeases: number; +} { + const completed = completeTaskAsStopped(task); + const cancelledTurns = cancelOpenTurns(task.id); + const releasedLeases = releasePairedTaskExecutionLeasesForTask(task.id); + return { completed, cancelledTurns, releasedLeases }; +} + +/** + * Handle a natural-language stop request ("그만", "멈춰", "stop", ...). + * + * Acts only when the room has something to stop: a running or queued run, an + * open paired task, or unprocessed human messages before the stop message. + * Otherwise the message is left alone and handled as a normal message. + */ +export async function stopRoomWorkIfRequested(args: { + chatJid: string; + group: RegisteredGroup; + channel: Channel; + messages: NewMessage[]; + assistantName: string; + lastAgentTimestamps: Record; + saveState: () => void; + controls: RoomStopControls; +}): Promise { + const { chatJid, controls } = args; + const stopMessage = findStopRequest(args.messages); + if (!stopMessage || stopMessage.seq == null) return { stopped: false }; + const stopSeq = stopMessage.seq; + + const openTask = hasReviewerLease(chatJid) + ? (getLatestOpenPairedTaskForChat(chatJid) ?? null) + : null; + const hasQueuedWork = controls.hasQueuedWork(chatJid); + const hasPendingMessages = + !hasQueuedWork && + !openTask && + hasPendingHumanMessageBefore({ + chatJid, + channel: args.channel, + assistantName: args.assistantName, + lastAgentTimestamps: args.lastAgentTimestamps, + stopSeq, + }); + if (!hasQueuedWork && !openTask && !hasPendingMessages) { + return { stopped: false }; + } + + // Consume everything up to and including the stop message first, so no + // run that finishes or retries afterwards can re-dispatch it. + advanceRoomCursorsPast({ + chatJid, + stopSeq, + lastAgentTimestamps: args.lastAgentTimestamps, + saveState: args.saveState, + }); + const closedTask = openTask ? closePairedTaskForStop(openTask) : null; + const killedProcess = controls.stopRunningAgent(chatJid); + + logger.info( + { + chatJid, + group: args.group.name, + groupFolder: args.group.folder, + stopSeq, + killedProcess, + hadQueuedWork: hasQueuedWork, + hadPendingMessages: hasPendingMessages, + pairedTaskId: openTask?.id ?? null, + pairedTaskStatus: openTask?.status ?? null, + ...(closedTask ?? {}), + }, + 'Stopped room work on user request', + ); + + try { + await controls.sendReply(chatJid, USER_STOP_REPLY); + } catch (err) { + logger.warn({ chatJid, err }, 'Failed to send stop confirmation'); + } + + return { + stopped: true, + hasMessagesAfterStop: args.messages.some( + (message) => message.seq != null && message.seq > stopSeq, + ), + }; +} diff --git a/src/session-commands.test.ts b/src/session-commands.test.ts deleted file mode 100644 index 1f57c1b..0000000 --- a/src/session-commands.test.ts +++ /dev/null @@ -1,324 +0,0 @@ -import { describe, it, expect, vi } from 'vitest'; -import { - extractSessionCommand, - handleSessionCommand, - isSessionCommandControlMessage, - isSessionCommandAllowed, -} from './session-commands.js'; -import type { NewMessage } from './types.js'; -import type { SessionCommandDeps } from './session-commands.js'; - -describe('extractSessionCommand', () => { - const trigger = /^@Andy\b/i; - - it('detects bare /compact', () => { - expect(extractSessionCommand('/compact', trigger)).toBe('/compact'); - }); - - it('does not treat bot-name prefixes as commands anymore', () => { - expect(extractSessionCommand('@Andy /compact', trigger)).toBeNull(); - }); - - it('detects bare /clear', () => { - expect(extractSessionCommand('/clear', trigger)).toBe('/clear'); - }); - - it('rejects /compact with extra text', () => { - expect(extractSessionCommand('/compact now please', trigger)).toBeNull(); - }); - - it('rejects partial matches', () => { - expect(extractSessionCommand('/compaction', trigger)).toBeNull(); - }); - - it('rejects regular messages', () => { - expect( - extractSessionCommand('please compact the conversation', trigger), - ).toBeNull(); - }); - - it('handles whitespace', () => { - expect(extractSessionCommand(' /compact ', trigger)).toBe('/compact'); - }); - - it('is case-sensitive for the command', () => { - expect(extractSessionCommand('/Compact', trigger)).toBeNull(); - }); -}); - -describe('isSessionCommandAllowed', () => { - it('allows main group regardless of sender', () => { - expect(isSessionCommandAllowed(true, false, false)).toBe(true); - }); - - it('allows trusted/admin sender (is_from_me) in non-main group', () => { - expect(isSessionCommandAllowed(false, true, false)).toBe(true); - }); - - it('allows configured admin sender in non-main group', () => { - expect(isSessionCommandAllowed(false, false, true)).toBe(true); - }); - - it('denies untrusted sender in non-main group', () => { - expect(isSessionCommandAllowed(false, false, false)).toBe(false); - }); - - it('allows trusted sender in main group', () => { - expect(isSessionCommandAllowed(true, true, false)).toBe(true); - }); -}); - -describe('isSessionCommandControlMessage', () => { - it('matches clear confirmation output', () => { - expect( - isSessionCommandControlMessage( - 'Current session cleared. The next message will start a new conversation.', - ), - ).toBe(true); - }); - - it('matches admin denial output', () => { - expect( - isSessionCommandControlMessage('Session commands require admin access.'), - ).toBe(true); - }); - - it('does not match regular bot conversation', () => { - expect( - isSessionCommandControlMessage( - '좋네요. 필요해지면 바로 말씀드리겠습니다.', - ), - ).toBe(false); - }); -}); - -function makeMsg( - content: string, - overrides: Partial = {}, -): NewMessage { - return { - id: 'msg-1', - chat_jid: 'group@test', - sender: 'user@test', - sender_name: 'User', - content, - timestamp: '100', - ...overrides, - }; -} - -function makeDeps( - overrides: Partial = {}, -): SessionCommandDeps { - return { - sendMessage: vi.fn().mockResolvedValue(undefined), - setTyping: vi.fn().mockResolvedValue(undefined), - runAgent: vi.fn().mockResolvedValue('success'), - closeStdin: vi.fn(), - clearSession: vi.fn(), - advanceCursor: vi.fn(), - formatMessages: vi.fn().mockReturnValue(''), - isAdminSender: vi.fn().mockReturnValue(false), - canSenderInteract: vi.fn().mockReturnValue(true), - killProcess: vi.fn().mockReturnValue(false), - ...overrides, - }; -} - -const trigger = /^@Andy\b/i; - -describe('handleSessionCommand', () => { - it('returns handled:false when no session command found', async () => { - const deps = makeDeps(); - const result = await handleSessionCommand({ - missedMessages: [makeMsg('hello')], - isMainGroup: true, - groupName: 'test', - triggerPattern: trigger, - timezone: 'UTC', - deps, - }); - expect(result.handled).toBe(false); - }); - - it('handles authorized /compact in main group', async () => { - const deps = makeDeps(); - const result = await handleSessionCommand({ - missedMessages: [makeMsg('/compact')], - isMainGroup: true, - groupName: 'test', - triggerPattern: trigger, - timezone: 'UTC', - deps, - }); - expect(result).toEqual({ handled: true, success: true }); - expect(deps.runAgent).toHaveBeenCalledWith( - '/compact', - expect.any(Function), - ); - expect(deps.advanceCursor).toHaveBeenCalledWith('100'); - }); - - it('handles authorized /clear without invoking the agent', async () => { - const deps = makeDeps(); - const result = await handleSessionCommand({ - missedMessages: [makeMsg('/clear')], - isMainGroup: true, - groupName: 'test', - triggerPattern: trigger, - timezone: 'UTC', - deps, - }); - expect(result).toEqual({ handled: true, success: true }); - expect(deps.closeStdin).toHaveBeenCalledTimes(1); - expect(deps.clearSession).toHaveBeenCalledTimes(1); - expect(deps.advanceCursor).toHaveBeenCalledWith('100'); - expect(deps.runAgent).not.toHaveBeenCalled(); - expect(deps.sendMessage).toHaveBeenCalledWith( - 'Current session cleared. The next message will start a new conversation.', - ); - }); - - it('sends denial to interactable sender in non-main group', async () => { - const deps = makeDeps(); - const result = await handleSessionCommand({ - missedMessages: [makeMsg('/compact', { is_from_me: false })], - isMainGroup: false, - groupName: 'test', - triggerPattern: trigger, - timezone: 'UTC', - deps, - }); - expect(result).toEqual({ handled: true, success: true }); - expect(deps.sendMessage).toHaveBeenCalledWith( - 'Session commands require admin access.', - ); - expect(deps.runAgent).not.toHaveBeenCalled(); - expect(deps.advanceCursor).toHaveBeenCalledWith('100'); - }); - - it('silently consumes denied command when sender cannot interact', async () => { - const deps = makeDeps({ - canSenderInteract: vi.fn().mockReturnValue(false), - }); - const result = await handleSessionCommand({ - missedMessages: [makeMsg('/compact', { is_from_me: false })], - isMainGroup: false, - groupName: 'test', - triggerPattern: trigger, - timezone: 'UTC', - deps, - }); - expect(result).toEqual({ handled: true, success: true }); - expect(deps.sendMessage).not.toHaveBeenCalled(); - expect(deps.advanceCursor).toHaveBeenCalledWith('100'); - }); - - it('processes pre-compact messages before /compact', async () => { - const deps = makeDeps(); - const msgs = [ - makeMsg('summarize this', { timestamp: '99' }), - makeMsg('/compact', { timestamp: '100' }), - ]; - const result = await handleSessionCommand({ - missedMessages: msgs, - isMainGroup: true, - groupName: 'test', - triggerPattern: trigger, - timezone: 'UTC', - deps, - }); - expect(result).toEqual({ handled: true, success: true }); - expect(deps.formatMessages).toHaveBeenCalledWith([msgs[0]], 'UTC'); - // Two runAgent calls: pre-compact + /compact - expect(deps.runAgent).toHaveBeenCalledTimes(2); - expect(deps.runAgent).toHaveBeenCalledWith( - '', - expect.any(Function), - ); - expect(deps.runAgent).toHaveBeenCalledWith( - '/compact', - expect.any(Function), - ); - }); - - it('allows is_from_me sender in non-main group', async () => { - const deps = makeDeps(); - const result = await handleSessionCommand({ - missedMessages: [makeMsg('/compact', { is_from_me: true })], - isMainGroup: false, - groupName: 'test', - triggerPattern: trigger, - timezone: 'UTC', - deps, - }); - expect(result).toEqual({ handled: true, success: true }); - expect(deps.runAgent).toHaveBeenCalledWith( - '/compact', - expect.any(Function), - ); - }); - - it('allows configured admin sender in non-main group', async () => { - const deps = makeDeps({ - isAdminSender: vi.fn().mockReturnValue(true), - }); - const result = await handleSessionCommand({ - missedMessages: [ - makeMsg('/clear', { is_from_me: false, sender: 'discord-user-1' }), - ], - isMainGroup: false, - groupName: 'test', - triggerPattern: trigger, - timezone: 'UTC', - deps, - }); - expect(result).toEqual({ handled: true, success: true }); - expect(deps.clearSession).toHaveBeenCalledTimes(1); - expect(deps.sendMessage).toHaveBeenCalledWith( - 'Current session cleared. The next message will start a new conversation.', - ); - }); - - it('reports failure when command-stage runAgent returns error without streamed status', async () => { - // runAgent resolves 'error' but callback never gets status: 'error' - const deps = makeDeps({ - runAgent: vi.fn().mockImplementation(async (prompt, onOutput) => { - await onOutput({ status: 'success', result: null }); - return 'error'; - }), - }); - const result = await handleSessionCommand({ - missedMessages: [makeMsg('/compact')], - isMainGroup: true, - groupName: 'test', - triggerPattern: trigger, - timezone: 'UTC', - deps, - }); - expect(result).toEqual({ handled: true, success: true }); - expect(deps.sendMessage).toHaveBeenCalledWith( - expect.stringContaining('failed'), - ); - }); - - it('returns success:false on pre-compact failure with no output', async () => { - const deps = makeDeps({ runAgent: vi.fn().mockResolvedValue('error') }); - const msgs = [ - makeMsg('summarize this', { timestamp: '99' }), - makeMsg('/compact', { timestamp: '100' }), - ]; - const result = await handleSessionCommand({ - missedMessages: msgs, - isMainGroup: true, - groupName: 'test', - triggerPattern: trigger, - timezone: 'UTC', - deps, - }); - expect(result).toEqual({ handled: true, success: false }); - expect(deps.sendMessage).toHaveBeenCalledWith( - expect.stringContaining('Failed to process'), - ); - }); -}); diff --git a/src/session-commands.ts b/src/session-commands.ts deleted file mode 100644 index 3bbd0b9..0000000 --- a/src/session-commands.ts +++ /dev/null @@ -1,228 +0,0 @@ -import { getAgentOutputText } from './agent-output.js'; -import type { NewMessage } from './types.js'; -import { logger } from './logger.js'; -import { sanitizeForOutbound } from './router.js'; -import type { StructuredAgentOutput } from './types.js'; - -const SESSION_COMMAND_CONTROL_PATTERNS = [ - /^Current session cleared\. The next message will start a new conversation\.$/, - /^Session commands require admin access\.$/, - /^Failed to process messages before \/compact\. Try again\.$/, - /^\/compact failed\. The session is unchanged\.$/, - /^Conversation compacted\.$/, -]; - -function normalizeSessionCommandText( - content: string, - _triggerPattern: RegExp, -): string { - return content.trim(); -} - -/** - * Extract a session slash command from a message. - * Returns the slash command (e.g., '/compact') or null if not a session command. - */ -export function extractSessionCommand( - content: string, - triggerPattern: RegExp, -): string | null { - const text = normalizeSessionCommandText(content, triggerPattern); - if (text === '/compact') return '/compact'; - if (text === '/clear') return '/clear'; - if (text === '/stop') return '/stop'; - return null; -} - -/** - * Check if a session command sender is authorized. - * Allowed: main group (any sender), or trusted/admin sender in any group. - */ -export function isSessionCommandAllowed( - isMainGroup: boolean, - isFromMe: boolean, - isAdminSender: boolean = false, -): boolean { - return isMainGroup || isFromMe || isAdminSender; -} - -export function isSessionCommandControlMessage(content: string): boolean { - const trimmed = content.trim(); - return SESSION_COMMAND_CONTROL_PATTERNS.some((pattern) => - pattern.test(trimmed), - ); -} - -/** Minimal agent result interface — matches the subset of AgentOutput used here. */ -export interface AgentResult { - status: 'success' | 'error'; - result?: string | object | null; - output?: StructuredAgentOutput; -} - -/** Dependencies injected by the orchestrator. */ -export interface SessionCommandDeps { - sendMessage: (text: string) => Promise; - setTyping: (typing: boolean) => Promise; - runAgent: ( - prompt: string, - onOutput: (result: AgentResult) => Promise, - ) => Promise<'success' | 'error'>; - closeStdin: () => void; - clearSession: (opts?: { allRoles?: boolean }) => void; - advanceCursor: (timestamp: string) => void; - formatMessages: (msgs: NewMessage[], timezone: string) => string; - isAdminSender: (msg: NewMessage) => boolean; - /** Whether the denied sender would normally be allowed to interact (for denial messages). */ - canSenderInteract: (msg: NewMessage) => boolean; - /** Reset/complete the active paired task so ping-pong stops. */ - resetPairedTask?: () => void; - /** Kill the currently running agent process for this group. Returns true if a process was killed. */ - killProcess: () => boolean; -} - -function agentResultToText(result: AgentResult): string { - const raw = getAgentOutputText({ - result: result.result ?? null, - output: result.output, - }); - return raw ? sanitizeForOutbound(raw) : ''; -} - -/** - * Handle session command interception in processGroupMessages. - * Scans messages for a session command, handles auth + execution. - * Returns { handled: true, success } if a command was found; { handled: false } otherwise. - * success=false means the caller should retry (cursor was not advanced). - */ -export async function handleSessionCommand(opts: { - missedMessages: NewMessage[]; - isMainGroup: boolean; - groupName: string; - runId?: string; - triggerPattern: RegExp; - timezone: string; - deps: SessionCommandDeps; -}): Promise<{ handled: false } | { handled: true; success: boolean }> { - const { - missedMessages, - isMainGroup, - groupName, - runId, - triggerPattern, - timezone, - deps, - } = opts; - - const cmdMsg = missedMessages.find( - (m) => extractSessionCommand(m.content, triggerPattern) !== null, - ); - const command = cmdMsg - ? extractSessionCommand(cmdMsg.content, triggerPattern) - : null; - if (!command || !cmdMsg) return { handled: false }; - - if ( - !isSessionCommandAllowed( - isMainGroup, - cmdMsg.is_from_me === true, - deps.isAdminSender(cmdMsg), - ) - ) { - // DENIED: send denial if the sender would normally be allowed to interact, - // then silently consume the command by advancing the cursor past it. - // Trade-off: other messages in the same batch are also consumed (cursor is - // a high-water mark). Acceptable for this narrow edge case. - if (deps.canSenderInteract(cmdMsg)) { - await deps.sendMessage('Session commands require admin access.'); - } - deps.advanceCursor(cmdMsg.timestamp); - return { handled: true, success: true }; - } - - // AUTHORIZED: process pre-compact messages first, then run the command - logger.info({ group: groupName, runId, command }, 'Session command'); - - if (command === '/clear') { - deps.closeStdin(); - deps.clearSession({ allRoles: true }); - deps.resetPairedTask?.(); - deps.advanceCursor(cmdMsg.timestamp); - await deps.sendMessage( - 'Current session cleared. The next message will start a new conversation.', - ); - return { handled: true, success: true }; - } - - if (command === '/stop') { - const killed = deps.killProcess(); - deps.resetPairedTask?.(); - deps.advanceCursor(cmdMsg.timestamp); - await deps.sendMessage( - killed ? 'Agent stopped.' : 'No agent is currently running in this room.', - ); - return { handled: true, success: true }; - } - - const cmdIndex = missedMessages.indexOf(cmdMsg); - const preCompactMsgs = missedMessages.slice(0, cmdIndex); - - // Send pre-compact messages to the agent so they're in the session context. - if (preCompactMsgs.length > 0) { - const prePrompt = deps.formatMessages(preCompactMsgs, timezone); - let hadPreError = false; - let preOutputSent = false; - - const preResult = await deps.runAgent(prePrompt, async (result) => { - if (result.status === 'error') hadPreError = true; - const text = agentResultToText(result); - if (text) { - await deps.sendMessage(text); - preOutputSent = true; - } - // Close stdin on session-update marker — emitted after query completes, - // so all results (including multi-result runs) are already written. - if (result.status === 'success' && result.result === null) { - deps.closeStdin(); - } - }); - - if (preResult === 'error' || hadPreError) { - logger.warn( - { group: groupName, runId }, - 'Pre-compact processing failed, aborting session command', - ); - await deps.sendMessage( - `Failed to process messages before ${command}. Try again.`, - ); - if (preOutputSent) { - // Output was already sent — don't retry or it will duplicate. - // Advance cursor past pre-compact messages, leave command pending. - deps.advanceCursor(preCompactMsgs[preCompactMsgs.length - 1].timestamp); - return { handled: true, success: true }; - } - return { handled: true, success: false }; - } - } - - // Forward the literal slash command as the prompt (no XML formatting) - await deps.setTyping(true); - - let hadCmdError = false; - const cmdOutput = await deps.runAgent(command, async (result) => { - if (result.status === 'error') hadCmdError = true; - const text = agentResultToText(result); - if (text) await deps.sendMessage(text); - }); - - // Advance cursor to the command — messages AFTER it remain pending for next poll. - deps.advanceCursor(cmdMsg.timestamp); - deps.resetPairedTask?.(); - await deps.setTyping(false); - - if (cmdOutput === 'error' || hadCmdError) { - await deps.sendMessage(`${command} failed. The session is unchanged.`); - } - - return { handled: true, success: true }; -} diff --git a/src/stop-intent.test.ts b/src/stop-intent.test.ts new file mode 100644 index 0000000..4ea988f --- /dev/null +++ b/src/stop-intent.test.ts @@ -0,0 +1,118 @@ +import { describe, expect, it } from 'vitest'; + +import { isStopIntent } from './stop-intent.js'; + +describe('isStopIntent', () => { + it.each([ + '그만', + '그만해', + '그만해줘', + '그만해 줘', + '그만해주세요', + '그만하자', + '그만해요', + '그만 좀 해', + '그만둬', + '멈춰', + '멈춰줘', + '멈춰 주세요', + '멈추자', + '중단', + '중단해', + '중단해줘', + '중지', + '중지해 주세요', + '하지마', + '하지 마', + '하지마세요', + '하지 말아줘', + '취소', + '취소해', + '스톱', + '스탑', + '작업 중단', + '작업 중단해줘', + '하던 거 그만해', + '다 멈춰', + '전부 취소해', + '제발 그만', + '아 그만해', + '그만 제발', + '잠깐 멈춰', + ])('treats the Korean stop phrase %j as a stop request', (text) => { + expect(isStopIntent(text)).toBe(true); + }); + + it.each([ + 'stop', + 'Stop', + 'STOP', + 'stop it', + 'stop now', + 'please stop', + 'Stop please', + 'cancel', + 'cancel that', + 'abort', + 'halt', + 'ok stop', + ])('treats the English stop phrase %j as a stop request', (text) => { + expect(isStopIntent(text)).toBe(true); + }); + + it.each([ + '그만!', + '그만해.', + '멈춰!!', + '그만해~', + '그만해ㅠㅠ', + '중단해ㅜ', + 'stop!', + 'stop...', + ' 그만해 ', + '<@123456789> 그만해', + '<@!123456789> 멈춰', + '그만해 <@123456789>', + '@오너 그만', + ])('ignores mentions and trailing punctuation around %j', (text) => { + expect(isStopIntent(text)).toBe(true); + }); + + it.each([ + '그거 하지 말고 이거 해줘', + '중단하지 말고 계속해', + '로그인 취소 기능 만들어줘', + '주문 취소 API 만들어줘', + '그만하고 테스트 돌려줘', + '멈춰 있는 서버 다시 켜줘', + '그만할까?', + '그만?', + '취소 버튼이 안 눌려', + '그거 하지마', + '그만해 그리고 이거 봐줘', + '아 그만해 진짜 이거 왜 안돼', + '빌드 중단된 이유 알려줘', + '그만해ㅋㅋ', + '', + ' ', + '그\n만', + '그만\n이거 해줘', + '<@123> 그만 <@456> 이거 해', + ])('does not treat the Korean message %j as a stop request', (text) => { + expect(isStopIntent(text)).toBe(false); + }); + + it.each([ + "don't stop", + 'stop the build and deploy', + 'cancel the login feature', + 'how do I stop the server?', + 'stop?', + 'please stop using tabs', + 'cancellation flow', + 'stopwatch', + 'unstoppable', + ])('does not treat the English message %j as a stop request', (text) => { + expect(isStopIntent(text)).toBe(false); + }); +}); diff --git a/src/stop-intent.ts b/src/stop-intent.ts new file mode 100644 index 0000000..c875063 --- /dev/null +++ b/src/stop-intent.ts @@ -0,0 +1,69 @@ +/** + * Conservative classifier for "stop what you are doing" chat messages. + * + * A message counts as a stop request only when, after removing bot mentions at + * the start or end and trailing punctuation, the whole message is a stop + * phrase (optionally wrapped in a filler word such as "아", "제발", "작업"). + * Anything that carries another instruction ("그거 하지 말고 이거 해줘", + * "중단하지 말고 계속해", "로그인 취소 기능 만들어줘") is not a stop request. + * When unsure, the answer is "not a stop request". + */ + +/** Reply posted after a stop request actually stopped something. */ +export const USER_STOP_REPLY = '진행 중이던 작업을 중단했습니다.'; + +const MAX_STOP_MESSAGE_LENGTH = 40; + +const EDGE_MENTIONS_PATTERN = /^(?:<@[!&]?\d+>\s*)+|(?:\s*<@[!&]?\d+>)+$/g; +const ANY_MENTION_PATTERN = /<@[!&]?\d+>/; +const LEADING_NAME_MENTION_PATTERN = /^@\S+\s+/; +// "?" is deliberately not stripped: "그만할까?" / "stop?" are questions. +const TRAILING_NOISE_PATTERN = /[\s.!~…ㅠㅜ;,]+$/u; + +// Words that may surround the stop phrase without changing its meaning. +// Matched against the Korean text with all whitespace removed. +const KOREAN_PREFIX = + '(?:아|야|어|앗|헐|제발|진짜|일단|잠깐만?|그냥|이제|지금|다|전부|모두|작업을?|진행을?|하던거|하던것|하던작업)'; +const KOREAN_SUFFIX = '(?:제발|좀|진짜)'; + +const KOREAN_STOP_CORE = [ + // 그만 / 그만해 / 그만 좀 해 / 그만해줘 / 그만하자 / 그만둬 ... + '그만좀?(?:요|해|해요|해라|하자|하세요|해줘|해줘요|해주세요|해주라|해줄래|둬|둬요|둬라|두자|두세요)?', + // 중단 / 중지 / 취소 (+ 해, 해줘, 하자, 시켜 ...) + '(?:중단|중지|취소)(?:요|해|해요|해라|하자|하세요|해줘|해줘요|해주세요|해주라|시켜|시켜줘|시켜주세요)?', + // 멈춰 / 멈춰줘 / 멈추자 / 멈춤 + '멈(?:춰|춰요|춰라|춰줘|춰줘요|춰주세요|추자|추세요|춤)', + // 하지마 / 하지 마 / 하지마세요 / 하지 말아줘 + '하지(?:마|마요|마라|마세요|말아줘|말아줘요|말아주세요)', + '스톱|스탑', +].join('|'); + +const KOREAN_STOP_PATTERN = new RegExp( + `^${KOREAN_PREFIX}{0,2}(?:${KOREAN_STOP_CORE})${KOREAN_SUFFIX}?$`, + 'u', +); + +const ENGLISH_STOP_PATTERN = + /^(?:(?:please|pls|ok|okay|hey|just|oh)\s+)*(?:stop|cancel|abort|halt)(?:\s+(?:it|that|this|now|please|pls|everything|all|working))*$/; + +/** + * Strip edge mentions and trailing punctuation, lowercase, and collapse + * whitespace. Returns null when the message cannot be a bare stop request + * (multi-line, or it mentions someone in the middle). + */ +function normalizeStopCandidate(content: string): string | null { + let text = content.trim(); + if (text.includes('\n')) return null; + text = text.replace(EDGE_MENTIONS_PATTERN, '').trim(); + if (ANY_MENTION_PATTERN.test(text)) return null; + text = text.replace(LEADING_NAME_MENTION_PATTERN, ''); + text = text.replace(TRAILING_NOISE_PATTERN, ''); + return text.toLowerCase().replace(/\s+/g, ' '); +} + +export function isStopIntent(content: string): boolean { + const text = normalizeStopCandidate(content); + if (!text || text.length > MAX_STOP_MESSAGE_LENGTH) return false; + if (ENGLISH_STOP_PATTERN.test(text)) return true; + return KOREAN_STOP_PATTERN.test(text.replace(/\s+/g, '')); +} diff --git a/test/vitest-env.ts b/test/vitest-env.ts index 5fc1b8f..408433d 100644 --- a/test/vitest-env.ts +++ b/test/vitest-env.ts @@ -4,20 +4,10 @@ const CANONICAL_DISCORD_KEYS = new Set([ 'DISCORD_ARBITER_BOT_TOKEN', ]); -const CANONICAL_SESSION_COMMAND_KEYS = new Set([ - 'SESSION_COMMAND_ALLOWED_SENDERS', -]); - for (const key of Object.keys(process.env)) { if (key.startsWith('DISCORD_') && key.endsWith('_BOT_TOKEN')) { if (!CANONICAL_DISCORD_KEYS.has(key)) { delete process.env[key]; } - continue; - } - if (key.startsWith('SESSION_COMMAND_')) { - if (!CANONICAL_SESSION_COMMAND_KEYS.has(key)) { - delete process.env[key]; - } } }