* docs: thread-bound subagents plan * docs: add exact thread-bound subagent implementation touchpoints * Docs: prioritize auto thread-bound subagent flow * Docs: add ACP harness thread-binding extensions * Discord: add thread-bound session routing and auto-bind spawn flow * Subagents: add focus commands and ACP/session binding lifecycle hooks * Tests: cover thread bindings, focus commands, and ACP unbind hooks * Docs: add plugin-hook appendix for thread-bound subagents * Plugins: add subagent lifecycle hook events * Core: emit subagent lifecycle hooks and decouple Discord bindings * Discord: handle subagent bind lifecycle via plugin hooks * Subagents: unify completion finalizer and split registry modules * Add subagent lifecycle events module * Hooks: fix subagent ended context key * Discord: share thread bindings across ESM and Jiti * Subagents: add persistent sessions_spawn mode for thread-bound sessions * Subagents: clarify thread intro and persistent completion copy * test(subagents): stabilize sessions_spawn lifecycle cleanup assertions * Discord: add thread-bound session TTL with auto-unfocus * Subagents: fail session spawns when thread bind fails * Subagents: cover thread session failure cleanup paths * Session: add thread binding TTL config and /session ttl controls * Tests: align discord reaction expectations * Agent: persist sessionFile for keyed subagent sessions * Discord: normalize imports after conflict resolution * Sessions: centralize sessionFile resolve/persist helper * Discord: harden thread-bound subagent session routing * Rebase: resolve upstream/main conflicts * Subagents: move thread binding into hooks and split bindings modules * Docs: add channel-agnostic subagent routing hook plan * Agents: decouple subagent routing from Discord * Discord: refactor thread-bound subagent flows * Subagents: prevent duplicate end hooks and orphaned failed sessions * Refactor: split subagent command and provider phases * Subagents: honor hook delivery target overrides * Discord: add thread binding kill switches and refresh plan doc * Discord: fix thread bind channel resolution * Routing: centralize account id normalization * Discord: clean up thread bindings on startup failures * Discord: add startup cleanup regression tests * Docs: add long-term thread-bound subagent architecture * Docs: split session binding plan and dedupe thread-bound doc * Subagents: add channel-agnostic session binding routing * Subagents: stabilize announce completion routing tests * Subagents: cover multi-bound completion routing * Subagents: suppress lifecycle hooks on failed thread bind * tests: fix discord provider mock typing regressions * docs/protocol: sync slash command aliases and delete param models * fix: add changelog entry for Discord thread-bound subagents (#21805) (thanks @onutc) --------- Co-authored-by: Shadow <hi@shadowing.dev>
184 lines
6.4 KiB
TypeScript
184 lines
6.4 KiB
TypeScript
import fs from "node:fs/promises";
|
|
import { logVerbose } from "../../globals.js";
|
|
import { createInternalHookEvent, triggerInternalHook } from "../../hooks/internal-hooks.js";
|
|
import { getGlobalHookRunner } from "../../plugins/hook-runner-global.js";
|
|
import { resolveSendPolicy } from "../../sessions/send-policy.js";
|
|
import { shouldHandleTextCommands } from "../commands-registry.js";
|
|
import { handleAllowlistCommand } from "./commands-allowlist.js";
|
|
import { handleApproveCommand } from "./commands-approve.js";
|
|
import { handleBashCommand } from "./commands-bash.js";
|
|
import { handleCompactCommand } from "./commands-compact.js";
|
|
import { handleConfigCommand, handleDebugCommand } from "./commands-config.js";
|
|
import {
|
|
handleCommandsListCommand,
|
|
handleContextCommand,
|
|
handleExportSessionCommand,
|
|
handleHelpCommand,
|
|
handleStatusCommand,
|
|
handleWhoamiCommand,
|
|
} from "./commands-info.js";
|
|
import { handleModelsCommand } from "./commands-models.js";
|
|
import { handlePluginCommand } from "./commands-plugin.js";
|
|
import {
|
|
handleAbortTrigger,
|
|
handleActivationCommand,
|
|
handleRestartCommand,
|
|
handleSessionCommand,
|
|
handleSendPolicyCommand,
|
|
handleStopCommand,
|
|
handleUsageCommand,
|
|
} from "./commands-session.js";
|
|
import { handleSubagentsCommand } from "./commands-subagents.js";
|
|
import { handleTtsCommands } from "./commands-tts.js";
|
|
import type {
|
|
CommandHandler,
|
|
CommandHandlerResult,
|
|
HandleCommandsParams,
|
|
} from "./commands-types.js";
|
|
import { routeReply } from "./route-reply.js";
|
|
|
|
let HANDLERS: CommandHandler[] | null = null;
|
|
|
|
export async function handleCommands(params: HandleCommandsParams): Promise<CommandHandlerResult> {
|
|
if (HANDLERS === null) {
|
|
HANDLERS = [
|
|
// Plugin commands are processed first, before built-in commands
|
|
handlePluginCommand,
|
|
handleBashCommand,
|
|
handleActivationCommand,
|
|
handleSendPolicyCommand,
|
|
handleUsageCommand,
|
|
handleSessionCommand,
|
|
handleRestartCommand,
|
|
handleTtsCommands,
|
|
handleHelpCommand,
|
|
handleCommandsListCommand,
|
|
handleStatusCommand,
|
|
handleAllowlistCommand,
|
|
handleApproveCommand,
|
|
handleContextCommand,
|
|
handleExportSessionCommand,
|
|
handleWhoamiCommand,
|
|
handleSubagentsCommand,
|
|
handleConfigCommand,
|
|
handleDebugCommand,
|
|
handleModelsCommand,
|
|
handleStopCommand,
|
|
handleCompactCommand,
|
|
handleAbortTrigger,
|
|
];
|
|
}
|
|
const resetMatch = params.command.commandBodyNormalized.match(/^\/(new|reset)(?:\s|$)/);
|
|
const resetRequested = Boolean(resetMatch);
|
|
if (resetRequested && !params.command.isAuthorizedSender) {
|
|
logVerbose(
|
|
`Ignoring /reset from unauthorized sender: ${params.command.senderId || "<unknown>"}`,
|
|
);
|
|
return { shouldContinue: false };
|
|
}
|
|
|
|
// Trigger internal hook for reset/new commands
|
|
if (resetRequested && params.command.isAuthorizedSender) {
|
|
const commandAction = resetMatch?.[1] ?? "new";
|
|
const hookEvent = createInternalHookEvent("command", commandAction, params.sessionKey ?? "", {
|
|
sessionEntry: params.sessionEntry,
|
|
previousSessionEntry: params.previousSessionEntry,
|
|
commandSource: params.command.surface,
|
|
senderId: params.command.senderId,
|
|
cfg: params.cfg, // Pass config for LLM slug generation
|
|
});
|
|
await triggerInternalHook(hookEvent);
|
|
|
|
// Send hook messages immediately if present
|
|
if (hookEvent.messages.length > 0) {
|
|
// Use OriginatingChannel/To if available, otherwise fall back to command channel/from
|
|
// oxlint-disable-next-line typescript/no-explicit-any
|
|
const channel = params.ctx.OriginatingChannel || (params.command.channel as any);
|
|
// For replies, use 'from' (the sender) not 'to' (which might be the bot itself)
|
|
const to = params.ctx.OriginatingTo || params.command.from || params.command.to;
|
|
|
|
if (channel && to) {
|
|
const hookReply = { text: hookEvent.messages.join("\n\n") };
|
|
await routeReply({
|
|
payload: hookReply,
|
|
channel: channel,
|
|
to: to,
|
|
sessionKey: params.sessionKey,
|
|
accountId: params.ctx.AccountId,
|
|
threadId: params.ctx.MessageThreadId,
|
|
cfg: params.cfg,
|
|
});
|
|
}
|
|
}
|
|
|
|
// Fire before_reset plugin hook — extract memories before session history is lost
|
|
const hookRunner = getGlobalHookRunner();
|
|
if (hookRunner?.hasHooks("before_reset")) {
|
|
const prevEntry = params.previousSessionEntry;
|
|
const sessionFile = prevEntry?.sessionFile;
|
|
// Fire-and-forget: read old session messages and run hook
|
|
void (async () => {
|
|
try {
|
|
const messages: unknown[] = [];
|
|
if (sessionFile) {
|
|
const content = await fs.readFile(sessionFile, "utf-8");
|
|
for (const line of content.split("\n")) {
|
|
if (!line.trim()) {
|
|
continue;
|
|
}
|
|
try {
|
|
const entry = JSON.parse(line);
|
|
if (entry.type === "message" && entry.message) {
|
|
messages.push(entry.message);
|
|
}
|
|
} catch {
|
|
// skip malformed lines
|
|
}
|
|
}
|
|
} else {
|
|
logVerbose("before_reset: no session file available, firing hook with empty messages");
|
|
}
|
|
await hookRunner.runBeforeReset(
|
|
{ sessionFile, messages, reason: commandAction },
|
|
{
|
|
agentId: params.sessionKey?.split(":")[0] ?? "main",
|
|
sessionKey: params.sessionKey,
|
|
sessionId: prevEntry?.sessionId,
|
|
workspaceDir: params.workspaceDir,
|
|
},
|
|
);
|
|
} catch (err: unknown) {
|
|
logVerbose(`before_reset hook failed: ${String(err)}`);
|
|
}
|
|
})();
|
|
}
|
|
}
|
|
|
|
const allowTextCommands = shouldHandleTextCommands({
|
|
cfg: params.cfg,
|
|
surface: params.command.surface,
|
|
commandSource: params.ctx.CommandSource,
|
|
});
|
|
|
|
for (const handler of HANDLERS) {
|
|
const result = await handler(params, allowTextCommands);
|
|
if (result) {
|
|
return result;
|
|
}
|
|
}
|
|
|
|
const sendPolicy = resolveSendPolicy({
|
|
cfg: params.cfg,
|
|
entry: params.sessionEntry,
|
|
sessionKey: params.sessionKey,
|
|
channel: params.sessionEntry?.channel ?? params.command.channel,
|
|
chatType: params.sessionEntry?.chatType,
|
|
});
|
|
if (sendPolicy === "deny") {
|
|
logVerbose(`Send blocked by policy for session ${params.sessionKey ?? "unknown"}`);
|
|
return { shouldContinue: false };
|
|
}
|
|
|
|
return { shouldContinue: true };
|
|
}
|