@@ -11,8 +11,10 @@
1111 import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
1212 import { homedir } from "node:os";
1313 import { join } from "node:path";
14+import { isDeepStrictEqual } from "node:util";
1415 import type {
1516 KnownProvider,
17+ Message,
1618 Model,
1719 OAuthCredentials,
1820 ThinkingLevel,
@@ -29,11 +31,13 @@ import {
2931 initPlugins,
3032 type LoadedPlugin,
3133 loadPluginConfig,
34+ type PluginEntry,
3235 } from "./plugins.ts";
3336 import {
3437 type AgentsMdFile,
3538 buildSystemPrompt,
3639 discoverAgentsMd,
40+ resolveAgentsScanRoot,
3741 } from "./prompt.ts";
3842 import {
3943 computeStats,
@@ -106,6 +110,14 @@ function saveOAuthCredentials(creds: Record<string, OAuthCredentials>): void {
106110 writeFileSync(AUTH_PATH, JSON.stringify(creds, null, 2), "utf-8");
107111 }
108112
113+/** Return whether refreshed OAuth credentials differ from the persisted value. */
114+export function didOAuthCredentialsChange(
115+ current: OAuthCredentials | undefined,
116+ next: OAuthCredentials,
117+): boolean {
118+ return !isDeepStrictEqual(current, next);
119+}
120+
109121 // ---------------------------------------------------------------------------
110122 // Provider discovery
111123 // ---------------------------------------------------------------------------
@@ -148,7 +160,12 @@ async function discoverProviders(): Promise<DiscoveryResult> {
148160 if (result) {
149161 providers.set(oauthProvider.id, result.apiKey);
150162 // Update credentials if they were refreshed
151- if (result.newCredentials !== oauthCredentials[oauthProvider.id]) {
163+ if (
164+ didOAuthCredentialsChange(
165+ oauthCredentials[oauthProvider.id],
166+ result.newCredentials,
167+ )
168+ ) {
152169 oauthCredentials[oauthProvider.id] = result.newCredentials;
153170 credsModified = true;
154171 }
@@ -286,6 +303,88 @@ function getSkillScanPaths(cwd: string, gitRoot: string | null): string[] {
286303 ];
287304 }
288305
306+/** Load AGENTS.md files, skills, plugins, git state, and the merged theme. */
307+export async function loadPromptContext(
308+ messages: readonly Message[],
309+ opts?: {
310+ cwd?: string;
311+ pluginEntries?: PluginEntry[];
312+ pluginConfigPath?: string;
313+ },
314+): Promise<{
315+ cwd: string;
316+ canonicalCwd: string;
317+ git: GitState | null;
318+ agentsMd: AgentsMdFile[];
319+ skills: Skill[];
320+ plugins: LoadedPlugin[];
321+ theme: Theme;
322+}> {
323+ const cwd = opts?.cwd ?? process.cwd();
324+ const canonicalCwd = canonicalizePath(cwd);
325+ const git = await getGitState(cwd);
326+ const gitRoot = git?.root ?? null;
327+ const home = homedir();
328+ const scanRoot = resolveAgentsScanRoot(
329+ cwd,
330+ gitRoot,
331+ home,
332+ process.env.MC_AGENTS_ROOT,
333+ );
334+ const agentsMd = discoverAgentsMd(cwd, scanRoot, join(home, ".agents"));
335+ const skills = discoverSkills(getSkillScanPaths(canonicalCwd, gitRoot));
336+ const pluginEntries =
337+ opts?.pluginEntries ??
338+ loadPluginConfig(opts?.pluginConfigPath ?? PLUGIN_CONFIG_PATH);
339+ const context: AgentContext = {
340+ cwd,
341+ messages,
342+ dataDir: DATA_DIR,
343+ };
344+ const plugins = await initPlugins(pluginEntries, context, (entry, err) => {
345+ console.error(`Plugin "${entry.name}" failed to init: ${err.message}`);
346+ });
347+ const themeOverrides = plugins
348+ .map((plugin) => plugin.result.theme)
349+ .filter((theme): theme is Partial<Theme> => theme != null);
350+
351+ return {
352+ cwd,
353+ canonicalCwd,
354+ git,
355+ agentsMd,
356+ skills,
357+ plugins,
358+ theme: mergeThemes(DEFAULT_THEME, ...themeOverrides),
359+ };
360+}
361+
362+/** Refresh the current prompt/session context at a reload boundary like `/new`. */
363+export async function reloadPromptContext(
364+ state: AppState,
365+ runtime?: {
366+ loadPromptContext?: typeof loadPromptContext;
367+ destroyPlugins?: typeof destroyPlugins;
368+ },
369+): Promise<void> {
370+ const loadContext = runtime?.loadPromptContext ?? loadPromptContext;
371+ const destroyLoadedPlugins = runtime?.destroyPlugins ?? destroyPlugins;
372+ const previousPlugins = state.plugins;
373+ const context = await loadContext(filterModelMessages(state.messages));
374+
375+ state.cwd = context.cwd;
376+ state.canonicalCwd = context.canonicalCwd;
377+ state.git = context.git;
378+ state.agentsMd = context.agentsMd;
379+ state.skills = context.skills;
380+ state.plugins = context.plugins;
381+ state.theme = context.theme;
382+
383+ await destroyLoadedPlugins(previousPlugins, (entry, err) => {
384+ console.error(`Plugin "${entry.name}" failed to destroy: ${err.message}`);
385+ });
386+}
387+
289388 // ---------------------------------------------------------------------------
290389 // App state
291390 // ---------------------------------------------------------------------------
@@ -345,7 +444,6 @@ export interface AppState {
345444 /** Initialize and return the full app state. */
346445 export async function init(): Promise<AppState> {
347446 const cwd = process.cwd();
348- const canonicalCwd = canonicalizePath(cwd);
349447
350448 // Ensure data directory exists
351449 mkdirSync(DATA_DIR, { recursive: true });
@@ -362,41 +460,15 @@ export async function init(): Promise<AppState> {
362460 );
363461 const model = selectModel(availableModels, startup.modelId);
364462
365- // Gather git state
366- const git = await getGitState(cwd);
367- const gitRoot = git?.root ?? null;
368-
369- // Discover context
370- const home = homedir();
371- const scanRoot = gitRoot ?? home;
372- const agentsMd = discoverAgentsMd(cwd, scanRoot, join(home, ".agents"));
373- const skills = discoverSkills(getSkillScanPaths(canonicalCwd, gitRoot));
374-
375- // Load plugins
376- const pluginEntries = loadPluginConfig(PLUGIN_CONFIG_PATH);
377-
378463 // Open database. Sessions are created lazily on the first user message.
379464 const db = openDatabase(DB_PATH);
380465 const effort = startup.effort;
381466 const messages: ReturnType<typeof loadMessages> = [];
382467 const stats = computeStats(messages);
383-
384- // Init plugins
385- const context: AgentContext = {
468+ const promptContext = await loadPromptContext(filterModelMessages(messages), {
386469 cwd,
387- messages: filterModelMessages(messages),
388- dataDir: DATA_DIR,
389- };
390- const plugins = await initPlugins(pluginEntries, context, (entry, err) => {
391- console.error(`Plugin "${entry.name}" failed to init: ${err.message}`);
392470 });
393471
394- // Build theme from defaults + plugin overrides
395- const themeOverrides = plugins
396- .map((p) => p.result.theme)
397- .filter((t): t is Partial<Theme> => t != null);
398- const theme = mergeThemes(DEFAULT_THEME, ...themeOverrides);
399-
400472 return {
401473 db,
402474 session: null,
@@ -404,17 +476,17 @@ export async function init(): Promise<AppState> {
404476 effort,
405477 messages,
406478 stats,
407- agentsMd,
408- skills,
409- plugins,
410- theme,
411- git,
479+ agentsMd: promptContext.agentsMd,
480+ skills: promptContext.skills,
481+ plugins: promptContext.plugins,
482+ theme: promptContext.theme,
483+ git: promptContext.git,
412484 providers,
413485 oauthCredentials,
414486 settings,
415487 settingsPath: SETTINGS_PATH,
416- cwd,
417- canonicalCwd,
488+ cwd: promptContext.cwd,
489+ canonicalCwd: promptContext.canonicalCwd,
418490 running: false,
419491 abortController: null,
420492 activeTurnPromise: null,