import type { Plugin } from '@opencode/plugin'; import type { ForgeKind } from './forge'; import { requestNoun } from './forges'; import { CONCURRENCY, mapLimit } from './limit'; import type { TitleLookups } from './lookups'; import { createKeyedQueue } from './keyed-queue'; import { statusOptions } from './options'; import { LINKED_NOTE_TOOL, restrictRequest, summarySystem, taggedInput, turnInput, UNAVAILABLE_TEXT, type SummaryRequest, } from './review-summary'; import { APPROVAL_STATUS_TOOL, APPROVAL_TOOLS, MARK_READY_TOOL, PREPARE_PREFIX, } from './review-preparation'; import { storedPreparation } from './review-automation-host'; import { createReviewClaims } from './review-claim'; import { linkedOwner, type DirectorySession } from './linked-session'; import { ForgeSessionRpc, implement } from './rpc'; import { setupStatus, type Status, type StatusDependencies } from './status-server'; import { summaryPrefix } from './summary-delivery'; import type { Snapshot } from './store'; import { applyTargetChange, includesRequest, MAX_TARGETS, parseTargetChange, targetOutput, targetRequest, targetsPrefix, type Target, } from './target'; import { extractIssueNumber, reconcileTitle } from './title'; // Stored per session. `prefix` is the title prefix this plugin last wrote, so // it can be replaced without touching text the user added. Before sessions // could have several targets, the state held a single `target`. type StoredState = { targets?: Target[]; prefix?: string }; type SessionState = { targets: Target[]; prefix?: string | null }; const TARGET_KEY = 'forgekeeper-session-target'; // How many forks back a session without targets looks for inherited ones. const MAX_FORK_DEPTH = 5; const GUIDANCE = [ 'When the user establishes or changes the primary issue, PR, or MR for this session, call set_session_target with its full URL before starting that work.', 'When the user asks you to work on several issues, PRs, or MRs together, call set_session_target with all of their full URLs in targets. If the user describes them instead of linking them, find them first, then set them before starting that work. When they are all PRs/MRs for one established issue, pass it as issue_url.', 'Reviewing, triaging, or addressing feedback on existing issues, PRs, or MRs makes them the primary targets. Call set_session_target with their full URLs before reading their discussions or changing them, including when a skill, search, or forge listing found them instead of the user linking them.', 'After you create a PR or MR for the current task (for example with gpsup, glab mr create, gh pr create, or a forge tool), call set_session_target with the new PR/MR URL. Pass the current issue as issue_url when the PR/MR was created for it. If the session has several targets that are still part of the task, use operation "add" so they are kept.', 'When the user drops some of several targets from the task, call set_session_target with operation "remove" and their URLs.', 'Background references, comparisons, and dependencies do not change the target. Follow-ups without a new primary target keep the current target.', 'Include issue_url only when its relationship to the target PRs/MRs is established. Never carry over the checked-out branch’s issue to another target.', 'Do not set targets for general questions or infer them from the checkout. When the user wants to clear all targets, call set_session_target with target "none".', `The current session target is in the entry "${TARGET_KEY}". The plugin updates it when it changes, so trust the latest value.`, ]; function describeTargets(targets: readonly Target[]): string { if (targets.length === 0) return 'none'; if (targets.length === 1) return JSON.stringify(targets[0]); return `${targets.length} targets: ${JSON.stringify(targets)}`; } function toolResult(targets: readonly Target[], missing: readonly string[]): string { let lines: string[]; switch (targets.length) { case 0: lines = ['Session target: none.']; break; case 1: lines = [`Session target: ${targets[0].url}`]; break; default: lines = [ `Session targets (${targets.length}):`, ...targets.map((target) => `- ${target.url}`), ]; break; } if (missing.length) lines.push(`Not session targets, so not removed: ${missing.join(', ')}`); return lines.join('\n'); } const DISABLED = { enabled: false, snapshot: { loading: false } }; // How long cleanup waits for running title updates. They can't write once // cleanup starts, so this only bounds how long their lookups are kept. const DRAIN_TIME = 5_000; async function drain(tasks: Promise[], limit: number) { let timer: ReturnType | undefined; await Promise.race([ Promise.allSettled(tasks), new Promise((resolve) => (timer = setTimeout(resolve, limit))), ]); clearTimeout(timer); } // RPC values must be JSON, which has no `undefined`, such as a cleared error. const json = (value: T): T => JSON.parse(JSON.stringify(value)); // Stores each root session's targets, keeps its title prefix current, serves // the targets to the CLI over RPC, and, given `status`, watches the PRs/MRs // of the sessions that CLIs show. export async function setupServer( ctx: Plugin.Context, lookups: TitleLookups, status?: StatusDependencies, ) { const pending = createKeyedQueue(); const instructing = createKeyedQueue(); const controller = new AbortController(); // Set when cleanup starts. No title update or target change starts after // it, and one that is running stops before it writes, so it can't // overwrite what the replacement instance stores. let closing = false; // The last targets read or written per session, for checks that can't wait // for storage, such as whether a PR/MR is still a target before notifying. const known = new Map(); // Counts each session's target writes. A read that overlapped a write may // return the old targets, so it doesn't update `known`. const revisions = new Map(); const revision = (sessionID: string) => revisions.get(sessionID) ?? 0; const bump = (sessionID: string) => revisions.set(sessionID, revision(sessionID) + 1); // The session each session was forked from, or null. Fork metadata never // changes, so one read per session is enough. const forkSources = new Map(); const forkSource = async (sessionID: string) => { if (forkSources.has(sessionID)) return forkSources.get(sessionID); try { const session = await ctx.session.get({ sessionID }); const source = session?.fork?.sessionID ?? null; forkSources.set(sessionID, source); return source; } catch { return null; } }; // A fork without a record of its own reads the nearest ancestor's record. // Its next update saves that state as its own, inside the keyed queue, so // nothing here can overwrite a concurrent target change. const storedState = async (sessionID: string): Promise => { let current = sessionID; for (let depth = 0; depth <= MAX_FORK_DEPTH; depth++) { const stored = (await ctx.storage.get(`sessions/${current}`)) as StoredState | undefined; if (stored) return stored; const source = await forkSource(current); if (!source) break; current = source; } return undefined; }; const readState = async (sessionID: string): Promise => { const stored = await storedState(sessionID); return { targets: Array.isArray(stored?.targets) ? stored.targets : [], prefix: stored ? (stored.prefix ?? null) : undefined, }; }; async function stateFor(sessionID: string): Promise { const started = revision(sessionID); const state = await readState(sessionID); if (revision(sessionID) === started) known.set(sessionID, state.targets); return state; } // Bumps the revision before and after the write, so neither a read that // started before it nor one that started while it ran updates `known`. const save = async (sessionID: string, state: SessionState) => { if (closing) throw new Error('The plugin is reloading. Try again.'); bump(sessionID); known.set(sessionID, state.targets); try { await ctx.storage.set(`sessions/${sessionID}`, { ...(state.targets.length ? { targets: state.targets } : {}), ...(state.prefix ? { prefix: state.prefix } : {}), }); } finally { bump(sessionID); } }; let watcher: Status | undefined; let directoryForgePromise: Promise | undefined; const directoryForge = () => (directoryForgePromise ??= status?.forges.detectForge?.(ctx.location.directory).catch(() => undefined) ?? Promise.resolve(undefined)); const requireWatcher = async () => { if (watcher) return watcher; const forge = await directoryForge(); throw new Error(`${requestNoun(forge)} status is disabled`); }; const rpc = await ctx.rpc.register( ForgeSessionRpc, implement({ monitoringStatus: async ({ sessionID }) => watcher ? json(await watcher.monitoringStatus(sessionID)) : { enabled: false, directory: ctx.location.directory, sessionID, discovered: false, leased: false, polling: false, paused: false, humanFeedback: false, automatedFeedback: false, status: { loading: false }, targets: [], }, target: async ({ sessionID }) => targetOutput((await stateFor(sessionID)).targets), watch: async ({ clientID, keys, visible }) => { const forge = await directoryForge(); return watcher ? { enabled: true, ...(forge ? { forge } : {}), statuses: json(watcher.service.watch(clientID, keys, visible)), } : { enabled: false, ...(forge ? { forge } : {}), statuses: {} }; }, release: async ({ clientID }) => { watcher?.service.release(clientID); return {}; }, refresh: async ({ key }) => { const forge = await directoryForge(); return watcher ? { enabled: true, ...(forge ? { forge } : {}), snapshot: json(await watcher.refresh(key)), } : { ...DISABLED, ...(forge ? { forge } : {}) }; }, feedback: async () => (watcher ? watcher.feedbackState() : { items: [], paused: false }), markFeedbackRead: async ({ ids }) => watcher ? watcher.decorateInbox(await watcher.inbox.markRead(ids)) : { items: [], paused: false }, acknowledgeFeedback: async ({ id }) => watcher ? watcher.decorateInbox(await watcher.inbox.acknowledge(id)) : { items: [], paused: false }, summarizeFeedback: async ({ id }) => (await requireWatcher()).summarize(id), actOnFeedback: async ({ id, retry }) => (await requireWatcher()).act(id, retry), pauseFeedback: async ({ paused }) => { if (!watcher) return { items: [], paused: false }; const state = await watcher.inbox.pause(paused); watcher.service.pauseFeedback(paused); if (!paused) watcher.retryPending(); await watcher.discovery.refresh(); return watcher.decorateInbox(state); }, cleanupCandidates: async ({ scanID }, context) => watcher ? json(await watcher.cleanupCandidates({ scanID, signal: context?.signal })) : { enabled: false, candidates: [], skippedErrors: 0 }, cleanupSessions: async ({ sessionIDs, scanID, allowClientArchive, finalizeArchived }) => json( await ( await requireWatcher() ).cleanupSessions(sessionIDs, { scanID, allowClientArchive, finalizeArchived, }), ), }), ); const settings = statusOptions(ctx.options); if (settings.problems.length) void rpc.events .emit('notice', { message: `Some Forgekeeper options were ignored: ${settings.problems.join('; ')}`, variant: 'error', }) .catch(() => {}); if (status && settings.enabled) { watcher = await setupStatus(ctx, settings, status, { state: stateFor, storedTargets: async (sessionID) => (await readState(sessionID)).targets, isTarget: (sessionID, url) => includesRequest(known.get(sessionID) ?? [], url), publish: (key: string, snapshot: Snapshot) => void rpc.events .emit('status', { directory: ctx.location.directory, key, snapshot: json(snapshot) }) .catch(() => {}), notice: (notice) => void rpc.events.emit('notice', json(notice)).catch(() => {}), forge: directoryForge, feedbackChanged: (directory = ctx.location.directory) => void rpc.events.emit('feedbackChanged', { directory }).catch(() => {}), sessionsCleanedUp: (sessionIDs, options) => void rpc.events .emit('sessionsCleanedUp', { sessionIDs, ...(options?.archive ? { archive: true } : {}), }) .catch(() => {}), cleanupProgress: (progress) => void rpc.events.emit('cleanupProgress', json(progress)).catch(() => {}), }); } async function update( sessionID: string, state?: SessionState, observedTitle = false, ): Promise { const session = await ctx.session.get({ sessionID }); if (session.parentID || !session.title || linkedOwner(session as DirectorySession)) return; const directory = session.location.directory; if (directory !== ctx.location.directory) return; state ??= await stateFor(sessionID); const prefix = targetsPrefix(state.targets); if (closing) return; if (prefix || state.prefix) { const title = reconcileTitle(session.title, prefix, state.prefix); if (title !== session.title) await ctx.session.update({ sessionID, title }); } else if (!session.fork && (!observedTitle || state.prefix === null)) return; await save(sessionID, { targets: state.targets, ...(prefix ? { prefix } : {}) }); } // Runs one update at a time per session, so a target change and a turn // ending at once can't interleave their reads and writes. function schedule(sessionID: string, action = () => update(sessionID)): Promise { if (closing) return Promise.reject(new Error('The plugin is reloading. Try again.')); return pending.run(sessionID, action); } // Infers the related issue of each PR/MR target from its source branch. // Targets the session already had were looked up when they were added. async function inferIssues(targets: Target[], previous: readonly Target[]) { const known = new Set( previous.filter((target) => !target.issueUrl).map((target) => target.url), ); await mapLimit(targets, CONCURRENCY, async (target) => { if (target.issueUrl || target.branchIssue || known.has(target.url)) return; const request = targetRequest(target); const branch = request ? await lookups.sourceBranch(request, ctx.location.directory) : undefined; const issue = branch ? extractIssueNumber(branch) : undefined; if (issue) target.branchIssue = issue; }); } async function changeTargets(sessionID: string, input: unknown) { const change = parseTargetChange(input); let result: { targets: Target[]; missing: string[] } = { targets: [], missing: [] }; await schedule(sessionID, async () => { const session = await ctx.session.get({ sessionID }); if (session.parentID || session.location.directory !== ctx.location.directory) { throw new Error('Session targets can only be set in the current root session.'); } if (linkedOwner(session as DirectorySession)) throw new Error( 'This session runs a Forgekeeper task for another session, which keeps the targets. Set targets there.', ); const state = await stateFor(sessionID); result = applyTargetChange(state.targets, change); await inferIssues(result.targets, state.targets); const next = { ...state, targets: result.targets }; await save(sessionID, next); watcher?.targetsChanged(sessionID, result.targets); await instruct(sessionID).catch(() => {}); await rpc.events.emit('targetChanged', { sessionID, ...targetOutput(result.targets) }); await update(sessionID, next); }); return toolResult(result.targets, result.missing); } const tools = await ctx.tool.transform((editor) => { editor.add({ name: 'set_session_target', options: { codemode: false }, description: 'Set the issues, PRs, or MRs this session works on, for its title and PR/MR status. Use target for one full URL, or "none" to clear all targets. Use targets for several full URLs. The default operation, "replace", sets exactly the given targets; "add" keeps the current targets, and "remove" drops the given ones. Call it after creating a PR/MR for the current task. Without issue_url, the related issue is inferred from the PR/MR source branch name. This only changes local session metadata.', input: { type: 'object', properties: { target: { type: 'string', description: 'Full GitHub/GitLab issue, PR, or MR URL, or "none" to clear all targets.', }, targets: { type: 'array', items: { type: 'string' }, minItems: 1, maxItems: MAX_TARGETS, description: 'Several full GitHub/GitLab issue, PR, or MR URLs, instead of target.', }, operation: { type: 'string', enum: ['replace', 'add', 'remove'], description: 'How the given targets change the current ones. Defaults to "replace".', }, issue_url: { type: 'string', description: 'Optional full URL of an established related issue for target, or for every PR/MR in targets. Omit when unknown.', }, }, additionalProperties: false, }, execute: async (input, { sessionID }) => ({ content: await changeTargets(sessionID, input) }), }); // Offered only in review summaries whose comments link to other notes; // the context hook removes it from every other request. if (watcher) { const summaries = watcher; editor.add({ name: LINKED_NOTE_TOOL, options: { codemode: false }, description: 'Read a note that the review comments being summarized link to. Works only during a Forgekeeper review summary, and only for the links its request lists as readable.', input: { type: 'object', properties: { url: { type: 'string', description: 'One of the readable links, exactly as listed.' }, }, required: ['url'], additionalProperties: false, }, execute: async (input, { sessionID }) => ({ content: await summaries.fetchLinked(sessionID, (input as { url?: unknown })?.url), }), }); editor.add({ name: APPROVAL_STATUS_TOOL, options: { codemode: false }, description: 'Read live status for the PR/MR bound to the active Forgekeeper review approval follow-up turn. Works only during an authorized approval follow-up.', input: { type: 'object', properties: {}, additionalProperties: false, }, execute: async (_input, context) => ({ content: await summaries.approvalStatus(context.sessionID, context.signal), }), }); editor.add({ name: MARK_READY_TOOL, options: { codemode: false }, description: 'Mark the verified draft PR/MR for the active Forgekeeper review approval follow-up as ready for review. Re-verifies authorization and approval before mutating. Works only during an authorized approval follow-up.', input: { type: 'object', properties: {}, additionalProperties: false, }, execute: async (_input, context) => ({ content: await summaries.markApprovalReady({ sessionID: context.sessionID, agent: context.agent, messageID: context.messageID, callID: context.id, signal: context.signal, }), }), }); } }); const commands = await ctx.command.transform((editor) => { editor.add({ name: 'forge-detach', description: 'Remove session targets by full URL, or omit URLs to clear all targets', execute: async ({ sessionID, prompt }) => { const urls = (prompt.text ?? '').trim().split(/\s+/).filter(Boolean); const message = await changeTargets( sessionID, urls.length ? { operation: 'remove', targets: urls } : { target: 'none' }, ); await rpc.events.emit('notice', { sessionID, variant: 'info', message }); }, }); }); async function writeInstructions(sessionID: string): Promise { if (closing) return; const state = await stateFor(sessionID); const value = `Current session target: ${describeTargets(state.targets)}.`; const entries = await ctx.session.instructions.entry.list({ sessionID }); if (entries.some((entry) => entry.key === TARGET_KEY && entry.value === value)) return; if (closing) return; await ctx.session.instructions.entry.put({ sessionID, key: TARGET_KEY, value }); } function instruct(sessionID: string): Promise { return instructing.run(sessionID, () => writeInstructions(sessionID)); } // Without monitoring, such as after `status` is turned off, a // Forgekeeper message queued earlier can still start a step. Its record // isn't read then: the step only says the review text is unavailable. // Sessions whose latest request was such a step, for the backstops. const orphaned = new Set(); // A tag counts unless the context shows a user prompt, which may quote one. async function orphanedStep(event: SummaryRequest): Promise { if (!taggedInput(event.messages)) { const records = await ctx.storage.scan({ prefix: summaryPrefix(event.sessionID) }); if (!records.entries.length) return false; } try { const input = turnInput(await ctx.session.context({ sessionID: event.sessionID })); // Without an input, such as after a compaction, the step may be one. return !input || input.type !== 'user'; } catch { return true; } } // A summary turn's request is replaced before anything else runs, and its // failures propagate, so the request never runs with the session's tools. // A failure in the guidance must not block the request, so it's skipped. await ctx.session.hook('context', async (event) => { if (!watcher) { const input = turnInput(await ctx.session.context({ sessionID: event.sessionID })); let preparing = input?.id.startsWith(PREPARE_PREFIX); if (!input) { const claims = status?.reviewClaims ?? createReviewClaims(); try { preparing = !!(await storedPreparation(ctx, claims, event.sessionID)); } finally { if (!status?.reviewClaims) claims.close(); } } if (preparing) throw new Error( 'Review preparation is disabled. Enable Forgekeeper status before resuming this task.', ); } let approvalTurnActive = false; if (watcher) { // A preparation turn that can't be confirmed, such as when the // session's context can't be read, still gets a summary's // restrictions when one applies; otherwise its request fails. let preparing = false; let failure: { error: unknown } | undefined; try { preparing = await watcher.prepareAutomation(event); } catch (error) { failure = { error }; } if (!preparing && (await watcher.prepareSummary(event))) return; if (failure) throw failure.error; if (preparing) approvalTurnActive = await watcher.approvalTurn(event.sessionID); } else if (await orphanedStep(event)) { orphaned.add(event.sessionID); restrictRequest(event, summarySystem(false), UNAVAILABLE_TEXT); return; } else orphaned.delete(event.sessionID); if (event.tools) { delete event.tools[LINKED_NOTE_TOOL]; if (!approvalTurnActive) { for (const name of APPROVAL_TOOLS) delete event.tools[name]; } } if (approvalTurnActive) return; const session = await ctx.session.get({ sessionID: event.sessionID }).catch(() => undefined); if (session && session.location.directory !== ctx.location.directory) return; if (!session || session.parentID || linkedOwner(session as DirectorySession)) { if (event.tools) { delete event.tools.set_session_target; if ((await sessionKind(session)) !== 'ordinary') delete event.tools.question; } return; } try { event.system.push({ type: 'text', text: GUIDANCE.join('\n') }); await instruct(event.sessionID); } catch { // The request goes ahead without the guidance. } }); // A compaction summarizes the stored transcript, where a linked session's // task is only a placeholder. A failure fails the compaction, so the // summary never stands in for a task it doesn't hold. await ctx.session.hook('compaction', async (event) => { await watcher?.prepareCompaction(event); }); // OpenCode reads instruction entries before a step's request reaches the // context hook, and announces later changes in another step. Writing the // entry when a prompt is admitted makes it part of the first step's // instructions. The context hook still writes it for sessions without one, // such as those that started with a synthetic message. await ctx.session.hook('prompt', async (event) => { try { if (await ownsSession(event.sessionID)) await instruct(event.sessionID); } catch { // The prompt is admitted anyway, and the context hook writes the entry. } }); async function sessionKind(session: Awaited> | undefined) { const seen = new Set(); while (session) { if (linkedOwner(session as DirectorySession)) return 'linked'; if (!session.parentID) return 'ordinary'; if (seen.has(session.parentID)) break; seen.add(session.parentID); session = await ctx.session.get({ sessionID: session.parentID }).catch(() => undefined); } return 'unknown'; } // Linked sessions get no target guidance: their owner keeps the targets. async function ownsSession(sessionID: string): Promise { const session = await ctx.session.get({ sessionID }); return ( !session.parentID && session.location.directory === ctx.location.directory && !linkedOwner(session as DirectorySession) ); } // Backstops for a summary turn whose request still reached tools, such as // after a hook ordering change. Each refuses the action outright. The // linked-note tool checks its own calls, and asks for no permissions. // They stay without monitoring too, for steps of messages queued earlier. const summarizing = async (sessionID: string) => watcher ? watcher.summarizing(sessionID) : orphaned.has(sessionID); await ctx.tool.hook('execute.before', async (event) => { if (watcher && event.tool === LINKED_NOTE_TOOL) return; if (await summarizing(event.sessionID)) throw new Error('Tools are disabled while Forgekeeper summarizes review feedback.'); if (watcher && (await watcher.approvalTurn(event.sessionID))) { if (!APPROVAL_TOOLS.has(event.tool)) throw new Error( 'Only Forgekeeper approval follow-up tools are allowed during a review approval turn.', ); } }); await ctx.permission.hook('evaluate', async (event) => { if (await summarizing(event.sessionID)) { event.effect = 'deny'; event.message = 'Forgekeeper review summaries run without tools.'; return; } if (watcher && (await watcher.approvalTurn(event.sessionID))) { if (event.action === MARK_READY_TOOL) { if (event.effect !== 'ask') return; } else { event.effect = 'deny'; event.message = 'Forgekeeper review approval follow-ups cannot run general tools or commands.'; return; } } if (event.effect !== 'ask') return; const session = await ctx.session.get({ sessionID: event.sessionID }).catch(() => undefined); if (session && session.location.directory !== ctx.location.directory) return; const kind = await sessionKind(session); if (kind !== 'ordinary') { event.effect = 'deny'; event.message = kind === 'unknown' ? 'Forgekeeper could not verify session ownership. Retry when the session is available.' : 'Forgekeeper linked sessions run in the background without interactive permission prompts. Use allowed tools or commands, or report what needs to be run so the owning session can handle it with the user.'; } }); void (async () => { for await (const event of ctx.event.subscribe({ types: [ 'session.created', 'session.renamed', 'session.moved', 'session.archived', 'session.unarchived', 'session.deleted', 'session.compaction.ended', 'session.execution.started', 'session.execution.succeeded', 'session.execution.failed', 'session.execution.interrupted', ], signal: controller.signal, })) { const { type } = event as { type: string }; const sessionID = (event.data as { sessionID?: string } | undefined)?.sessionID; if (sessionID) { if (type === 'session.created' || type === 'session.renamed') { void schedule(sessionID, () => update(sessionID, undefined, true)).catch(() => {}); } else if (type === 'session.execution.succeeded') { void schedule(sessionID).catch(() => {}); } } if (type === 'session.moved' && sessionID) watcher?.sessionMoved(sessionID); if (type === 'session.deleted' && sessionID) watcher?.sessionDeleted(sessionID); if (type === 'session.archived' && sessionID) watcher?.sessionArchived(sessionID); if ( sessionID && (type === 'session.archived' || type === 'session.unarchived' || type === 'session.deleted' || type === 'session.compaction.ended' || type === 'session.execution.started' || type === 'session.execution.interrupted') ) void watcher?.discovery.refresh(sessionID); if ( sessionID && (type === 'session.execution.succeeded' || type === 'session.execution.failed') ) watcher?.turnEnded(sessionID); // A shutdown doesn't end the turn: the resumed execution continues it. const reason = (event.data as { reason?: string } | undefined)?.reason; if ( sessionID && (type === 'session.execution.succeeded' || type === 'session.execution.failed' || type === 'session.execution.interrupted') && !(type === 'session.execution.interrupted' && reason === 'shutdown') ) watcher?.executionEnded( sessionID, type === 'session.execution.succeeded' ? 'succeeded' : 'failed', (event as { created?: number }).created ?? Date.now(), ); } })().catch(async (error) => { // Without events, titles and statuses stop following renames and turns until reload. if (controller.signal.aborted) return; const reason = error instanceof Error ? error.message : String(error); const forge = await directoryForge(); void rpc.events .emit('notice', { message: `Session title and ${requestNoun(forge)} status updates stopped: ${reason}`, variant: 'error', }) .catch(() => {}); }); // Stops new work, waits for running title updates and target changes, then // stops the status watchers. return async () => { closing = true; controller.abort(); await drain(pending.tasks(), DRAIN_TIME); await watcher?.dispose(); await commands?.dispose(); await tools.dispose(); await rpc.dispose(); }; }