feat: Make /init an interactive flow conducted by the primary agent [LET-7891] (#1356)

This commit is contained in:
Devansh Jain
2026-03-11 16:59:25 -07:00
committed by GitHub
parent d9eaa74ad6
commit a5c407eade
10 changed files with 93 additions and 488 deletions

View File

@@ -224,11 +224,9 @@ import {
import { formatCompact } from "./helpers/format";
import { parsePatchOperations } from "./helpers/formatArgsDisplay";
import {
buildLegacyInitMessage,
buildMemoryInitRuntimePrompt,
buildInitMessage,
fireAutoInit,
gatherGitContext,
hasActiveInitSubagent,
} from "./helpers/initCommand";
import {
getReflectionSettings,
@@ -1711,27 +1709,12 @@ export default function App({
const [showExitStats, setShowExitStats] = useState(false);
const sharedReminderStateRef = useRef(createSharedReminderState());
// Per-agent init progression — survives agent/conversation switches unlike SharedReminderState.
const initProgressByAgentRef = useRef(
new Map<string, { shallowCompleted: boolean; deepFired: boolean }>(),
);
const systemPromptRecompileByConversationRef = useRef(
new Map<string, Promise<void>>(),
);
const queuedSystemPromptRecompileByConversationRef = useRef(
new Set<string>(),
);
const updateInitProgress = (
forAgentId: string,
update: Partial<{ shallowCompleted: boolean; deepFired: boolean }>,
) => {
const progress = initProgressByAgentRef.current.get(forAgentId) ?? {
shallowCompleted: false,
deepFired: false,
};
Object.assign(progress, update);
initProgressByAgentRef.current.set(forAgentId, progress);
};
// Track if we've set the conversation summary for this new conversation
// Initialized to true for resumed conversations (they already have context)
@@ -9261,7 +9244,6 @@ export default function App({
if (trimmed === "/init") {
const cmd = commandRunner.start(msg, "Gathering project context...");
// Check for pending approvals before either path
const approvalCheck = await checkPendingApprovalsForSlashCommand();
if (approvalCheck.blocked) {
cmd.fail(
@@ -9270,112 +9252,38 @@ export default function App({
return { submitted: false };
}
const gitContext = gatherGitContext();
// Interactive init: the primary agent conducts the flow,
// asks the user questions, and runs the initializing-memory skill.
autoInitPendingAgentIdsRef.current.delete(agentId);
setCommandRunning(true);
try {
cmd.finish(
"Building your memory palace... Start a new conversation with `letta --new` to work in parallel.",
true,
);
if (settingsManager.isMemfsEnabled(agentId)) {
// MemFS path: background subagent
if (hasActiveInitSubagent()) {
cmd.fail(
"Memory initialization is already running in the background.",
);
return { submitted: true };
}
const gitContext = gatherGitContext();
const memoryDir = settingsManager.isMemfsEnabled(agentId)
? getMemoryFilesystemRoot(agentId)
: undefined;
try {
const initPrompt = buildMemoryInitRuntimePrompt({
agentId,
workingDirectory: process.cwd(),
memoryDir: getMemoryFilesystemRoot(agentId),
gitContext,
depth: "deep",
});
const initMessage = buildInitMessage({
gitContext,
memoryDir,
});
const { spawnBackgroundSubagentTask } = await import(
"../tools/impl/Task"
);
spawnBackgroundSubagentTask({
subagentType: "init",
prompt: initPrompt,
description: "Initializing memory",
silentCompletion: true,
onComplete: async ({ success, error }) => {
const msg = await handleMemorySubagentCompletion(
{
agentId,
conversationId: conversationIdRef.current,
subagentType: "init",
initDepth: "deep",
success,
error,
},
{
recompileByConversation:
systemPromptRecompileByConversationRef.current,
recompileQueuedByConversation:
queuedSystemPromptRecompileByConversationRef.current,
updateInitProgress,
logRecompileFailure: (message) =>
debugWarn("memory", message),
},
);
appendTaskNotificationEvents([msg]);
},
});
// Clear pending auto-init only after spawn succeeded
autoInitPendingAgentIdsRef.current.delete(agentId);
cmd.finish(
"Learning about you and your codebase in the background. You'll be notified when ready.",
true,
);
// TODO: Remove this hack once commandRunner supports a
// "silent" finish that skips the reminder callback.
// Currently cmd.finish() always enqueues a command-IO
// reminder, which leaks the /init context into the
// primary agent's next turn and causes it to invoke the
// initializing-memory skill itself.
const reminders =
sharedReminderStateRef.current.pendingCommandIoReminders;
const idx = reminders.findIndex((r) => r.input === "/init");
if (idx !== -1) {
reminders.splice(idx, 1);
}
} catch (error) {
const errorDetails = formatErrorDetails(error, agentId);
cmd.fail(
`Failed to start memory initialization: ${errorDetails}`,
);
}
} else {
// Legacy path: primary agent processConversation
autoInitPendingAgentIdsRef.current.delete(agentId);
setCommandRunning(true);
try {
cmd.finish(
"Assimilating project context and defragmenting memories...",
true,
);
const initMessage = buildLegacyInitMessage({
gitContext,
memfsSection: "",
});
await processConversation([
{
type: "message",
role: "user",
content: buildTextParts(initMessage),
},
]);
} catch (error) {
const errorDetails = formatErrorDetails(error, agentId);
cmd.fail(`Failed: ${errorDetails}`);
} finally {
setCommandRunning(false);
}
await processConversation([
{
type: "message",
role: "user",
content: buildTextParts(initMessage),
},
]);
} catch (error) {
const errorDetails = formatErrorDetails(error, agentId);
cmd.fail(`Failed: ${errorDetails}`);
} finally {
setCommandRunning(false);
}
return { submitted: true };
}
@@ -9493,7 +9401,6 @@ export default function App({
agentId,
conversationId: conversationIdRef.current,
subagentType: "init",
initDepth: "shallow",
success,
error,
},
@@ -9502,7 +9409,6 @@ export default function App({
systemPromptRecompileByConversationRef.current,
recompileQueuedByConversation:
queuedSystemPromptRecompileByConversationRef.current,
updateInitProgress,
logRecompileFailure: (message) =>
debugWarn("memory", message),
},
@@ -9632,7 +9538,6 @@ ${SYSTEM_REMINDER_CLOSE}
systemPromptRecompileByConversationRef.current,
recompileQueuedByConversation:
queuedSystemPromptRecompileByConversationRef.current,
updateInitProgress,
logRecompileFailure: (message) =>
debugWarn("memory", message),
},
@@ -9655,72 +9560,10 @@ ${SYSTEM_REMINDER_CLOSE}
return false;
}
};
const maybeLaunchDeepInitSubagent = async () => {
if (!memfsEnabledForAgent) return false;
if (hasActiveInitSubagent()) return false;
try {
const gitContext = gatherGitContext();
const initPrompt = buildMemoryInitRuntimePrompt({
agentId,
workingDirectory: process.cwd(),
memoryDir: getMemoryFilesystemRoot(agentId),
gitContext,
depth: "deep",
});
const { spawnBackgroundSubagentTask } = await import(
"../tools/impl/Task"
);
spawnBackgroundSubagentTask({
subagentType: "init",
prompt: initPrompt,
description: "Deep memory initialization",
silentCompletion: true,
onComplete: async ({ success, error }) => {
const msg = await handleMemorySubagentCompletion(
{
agentId,
conversationId: conversationIdRef.current,
subagentType: "init",
initDepth: "deep",
success,
error,
},
{
recompileByConversation:
systemPromptRecompileByConversationRef.current,
recompileQueuedByConversation:
queuedSystemPromptRecompileByConversationRef.current,
updateInitProgress,
logRecompileFailure: (message) =>
debugWarn("memory", message),
},
);
appendTaskNotificationEvents([msg]);
},
});
debugLog("memory", "Auto-launched deep init subagent");
return true;
} catch (error) {
debugWarn(
"memory",
`Failed to auto-launch deep init subagent: ${
error instanceof Error ? error.message : String(error)
}`,
);
return false;
}
};
syncReminderStateFromContextTracker(
sharedReminderStateRef.current,
contextTrackerRef.current,
);
// Hydrate init progression from the per-agent map into the shared state
// so the deep-init provider sees the correct flags for the current agent.
const initProgress = initProgressByAgentRef.current.get(agentId);
sharedReminderStateRef.current.shallowInitCompleted =
initProgress?.shallowCompleted ?? false;
sharedReminderStateRef.current.deepInitFired =
initProgress?.deepFired ?? false;
const { getSkillSources } = await import("../agent/context");
const { parts: sharedReminderParts } = await buildSharedReminderParts({
mode: "interactive",
@@ -9736,7 +9579,6 @@ ${SYSTEM_REMINDER_CLOSE}
skillSources: getSkillSources(),
resolvePlanModeReminder: getPlanModeReminder,
maybeLaunchReflectionSubagent,
maybeLaunchDeepInitSubagent,
});
for (const part of sharedReminderParts) {
reminderParts.push(part);

View File

@@ -76,7 +76,7 @@ ${recentCommits}
}
}
// ── Depth instructions ────────────────────────────────────
// ── Shallow init (background subagent) ───────────────────
const SHALLOW_INSTRUCTIONS = `
Shallow init — fast project basics only (~5 tool calls max):
@@ -87,25 +87,13 @@ Shallow init — fast project basics only (~5 tool calls max):
- Skip: deep directory exploration, architecture mapping, config analysis, historical sessions, persona files, reflection/checkpoint phase
`.trim();
const DEEP_INSTRUCTIONS = `
Deep init — full exploration (follow the initializing-memory skill fully):
- Read all existing memory files first — do NOT recreate what already exists
- Then follow the full initializing-memory skill as your operating guide
- Expand and deepen existing shallow files, add new ones to reach 15-25 target
- If shallow init already ran, build on its output rather than starting over
`.trim();
// ── Prompt builders ────────────────────────────────────────
/** Prompt for the background init subagent (MemFS path). */
export function buildMemoryInitRuntimePrompt(args: {
/** Prompt for the background shallow-init subagent. */
export function buildShallowInitPrompt(args: {
agentId: string;
workingDirectory: string;
memoryDir: string;
gitContext: string;
depth?: "shallow" | "deep";
}): string {
const depth = args.depth ?? "deep";
return `
The user ran /init for the current project.
@@ -113,7 +101,7 @@ Runtime context:
- parent_agent_id: ${args.agentId}
- working_directory: ${args.workingDirectory}
- memory_dir: ${args.memoryDir}
- research_depth: ${depth}
- research_depth: shallow
Git/project context:
${args.gitContext}
@@ -121,7 +109,7 @@ ${args.gitContext}
Task:
Initialize or reorganize the parent agent's filesystem-backed memory for this project.
${depth === "shallow" ? SHALLOW_INSTRUCTIONS : DEEP_INSTRUCTIONS}
${SHALLOW_INSTRUCTIONS}
Instructions:
- Use the pre-loaded initializing-memory skill as your operating guide
@@ -148,12 +136,11 @@ export async function fireAutoInit(
if (!settingsManager.isMemfsEnabled(agentId)) return false;
const gitContext = gatherGitContext();
const initPrompt = buildMemoryInitRuntimePrompt({
const initPrompt = buildShallowInitPrompt({
agentId,
workingDirectory: process.cwd(),
memoryDir: getMemoryFilesystemRoot(agentId),
gitContext,
depth: "shallow",
});
const { spawnBackgroundSubagentTask } = await import("../../tools/impl/Task");
@@ -168,14 +155,20 @@ export async function fireAutoInit(
return true;
}
/** Message for the primary agent via processConversation (legacy non-MemFS path). */
export function buildLegacyInitMessage(args: {
// ── Interactive init (primary agent) ─────────────────────
/** Message for the primary agent via processConversation when user runs /init. */
export function buildInitMessage(args: {
gitContext: string;
memfsSection: string;
memoryDir?: string;
}): string {
const memfsSection = args.memoryDir
? `\n## Memory filesystem\n\nMemory filesystem is enabled. Memory directory: \`${args.memoryDir}\`\n`
: "";
return `${SYSTEM_REMINDER_OPEN}
The user has requested memory initialization via /init.
${args.memfsSection}
${memfsSection}
## 1. Invoke the initializing-memory skill
Use the \`Skill\` tool with \`skill: "initializing-memory"\` to load the comprehensive instructions for memory initialization.

View File

@@ -4,71 +4,41 @@ import {
} from "../../agent/modify";
export type MemorySubagentType = "init" | "reflection";
export type MemoryInitDepth = "shallow" | "deep";
export interface MemoryInitProgressUpdate {
shallowCompleted: boolean;
deepFired: boolean;
}
type RecompileAgentSystemPromptFn = (
conversationId: string,
options?: RecompileAgentSystemPromptOptions,
) => Promise<string>;
export type MemorySubagentCompletionArgs =
| {
agentId: string;
conversationId: string;
subagentType: "init";
initDepth: MemoryInitDepth;
success: boolean;
error?: string;
}
| {
agentId: string;
conversationId: string;
subagentType: "reflection";
initDepth?: never;
success: boolean;
error?: string;
};
export interface MemorySubagentCompletionArgs {
agentId: string;
conversationId: string;
subagentType: MemorySubagentType;
success: boolean;
error?: string;
}
export interface MemorySubagentCompletionDeps {
recompileByConversation: Map<string, Promise<void>>;
recompileQueuedByConversation: Set<string>;
updateInitProgress: (
agentId: string,
update: Partial<MemoryInitProgressUpdate>,
) => void;
logRecompileFailure?: (message: string) => void;
recompileAgentSystemPromptImpl?: RecompileAgentSystemPromptFn;
}
/**
* Finalize a memory-writing subagent by updating init progress, recompiling the
* parent agent's system prompt, and returning the user-facing completion text.
* Finalize a memory-writing subagent by recompiling the parent agent's
* system prompt and returning the user-facing completion text.
*/
export async function handleMemorySubagentCompletion(
args: MemorySubagentCompletionArgs,
deps: MemorySubagentCompletionDeps,
): Promise<string> {
const { agentId, conversationId, subagentType, initDepth, success, error } =
args;
const { agentId, conversationId, subagentType, success, error } = args;
const recompileAgentSystemPromptFn =
deps.recompileAgentSystemPromptImpl ?? recompileAgentSystemPrompt;
let recompileError: string | null = null;
if (success) {
if (subagentType === "init") {
deps.updateInitProgress(
agentId,
initDepth === "shallow"
? { shallowCompleted: true }
: { deepFired: true },
);
}
try {
let inFlight = deps.recompileByConversation.get(conversationId);
@@ -106,9 +76,7 @@ export async function handleMemorySubagentCompletion(
if (subagentType === "reflection") {
return `Tried to reflect, but got lost in the palace: ${normalizedError}`;
}
return initDepth === "deep"
? `Deep memory initialization failed: ${normalizedError}`
: `Memory initialization failed: ${normalizedError}`;
return `Memory initialization failed: ${normalizedError}`;
}
const baseMessage =