π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
import debug from 'debug';
import { BaseVirtualLastUserContentProvider } from '../base/BaseVirtualLastUserContentProvider';
import type { PipelineContext, ProcessorOptions } from '../types';
import type { OnboardingContextInjectorConfig } from './OnboardingContextInjector';
const log = debug('context-engine:provider:OnboardingActionHintInjector');
const buildDiscoveryTurnReminder = (
discoveryUserMessageCount: number | undefined,
remainingDiscoveryExchanges: number | undefined,
): string | null => {
if (discoveryUserMessageCount === undefined || remainingDiscoveryExchanges === undefined) {
return null;
}
const recommendedTarget = discoveryUserMessageCount + remainingDiscoveryExchanges;
if (remainingDiscoveryExchanges > 0) {
return [
'SYSTEM REMINDER: Current Discovery turn status:',
`- User discovery exchanges observed: ${discoveryUserMessageCount}.`,
`- Recommended target before Summary: ${recommendedTarget}.`,
`- Continue Discovery for about ${remainingDiscoveryExchanges} more user exchange(s). Ask one focused question about what the user does for work β their profession or main occupation β persist it to the persona, and do not explore other topics.`,
].join('\n');
}
return [
'SYSTEM REMINDER: Current Discovery turn status:',
`- User discovery exchanges observed: ${discoveryUserMessageCount}.`,
'- Recommended Discovery target has been reached.',
"- Once the user's profession is recorded in the persona, transition to Summary instead of asking more questions.",
].join('\n');
};
/**
* Onboarding Action Hint Injector
* Injects a standalone virtual user message AFTER the last user message with phase-specific
* tool call directives. This is a separate message (not appended to the user's message)
* so the model treats it as a distinct instruction rather than part of the user's input.
*/
export class OnboardingActionHintInjector extends BaseVirtualLastUserContentProvider {
readonly name = 'OnboardingActionHintInjector';
constructor(
private config: OnboardingContextInjectorConfig,
options: ProcessorOptions = {},
) {
super(options);
}
protected shouldSkip(_context: PipelineContext): boolean {
if (!this.config.enabled || !this.config.onboardingContext?.phaseGuidance) {
log('Disabled or no phaseGuidance configured, skipping');
return true;
}
return false;
}
protected buildContent(context: PipelineContext): string | null {
const ctx = this.config.onboardingContext;
if (!ctx) return null;
const hints: string[] = [];
const phase = ctx.phaseGuidance;
// Detect prior showAgentMarketplace calls. NOTE: this provider runs in pipeline phase 4.5
// (virtual tail guidance) BEFORE ToolCallProcessor converts the DB-shape `tools` array
// into OpenAI-shape `tool_calls`. So at injection time, assistant messages still carry
// `tools: [{ identifier, apiName, ... }]`, not `tool_calls`. Match on apiName here, with
// a `tool_calls` fallback in case ordering changes.
const isMarketplaceShowCall = (msg: any): boolean => {
if (msg?.role !== 'assistant') return false;
if (
Array.isArray(msg.tools) &&
msg.tools.some((t: any) => t?.apiName === 'showAgentMarketplace')
) {
return true;
}
if (Array.isArray(msg.tool_calls)) {
return msg.tool_calls.some(
(tc: any) =>
typeof tc?.function?.name === 'string' &&
tc.function.name.includes('showAgentMarketplace'),
);
}
return false;
};
const marketplaceAlreadyOpened = context.messages.some((msg) => isMarketplaceShowCall(msg));
if (phase.includes('Discovery')) {
const reminder = buildDiscoveryTurnReminder(
ctx.discoveryUserMessageCount,
ctx.remainingDiscoveryExchanges,
);
if (reminder) hints.push(reminder);
}
// Detect empty documents and nudge tool calls (empty docs use writeDocument; non-empty use updateDocument)
if (!ctx.soulContent) {
hints.push(
'SOUL.md is empty β call writeDocument(type="soul") to write the initial agent identity once the user gives you a name and emoji.',
);
}
if (!ctx.personaContent) {
hints.push(
'User Persona is empty β call writeDocument(type="persona") to seed the initial persona once you have learned something about the user.',
);
}
// Phase-specific persistence reminders
if (phase.includes('Agent Identity')) {
hints.push(
'When the user says "call you X", "your name is X", "ε«δ½ X", "δ½ ε« X", or equivalent phrasing, X is agentName. When the user says "use Y as the avatar", "倴εη¨ Y", or equivalent phrasing, Y is agentEmoji. Save those assistant identity fields before discussing the user profile.',
);
if (ctx.userInfo?.displayName || ctx.userInfo?.fullName || ctx.userInfo?.username) {
const userInfoHints = [
ctx.userInfo.displayName,
ctx.userInfo.fullName,
ctx.userInfo.username,
]
.filter(Boolean)
.map((value) => JSON.stringify(value).replaceAll('<', '\\u003c'));
hints.push(
`User account identity hints (${userInfoHints.join(', ')}) describe the user, not the assistant. Do NOT copy them into agentName unless the user explicitly asks to name the assistant that value.`,
);
}
hints.push(
'When the user settles on a name and emoji: call saveUserQuestion with agentName and agentEmoji only, then persist SOUL.md. Do NOT include fullName in the same saveUserQuestion call unless the user explicitly says that value is their own name. If SOUL.md is already non-empty, call updateDocument(type="soul") with the hunk mode that matches your edit β `insertAt`/`replaceLines`/`deleteLines` when you can read the line numbers from <current_soul_document>, or `replace` for a textual tweak. If empty, use writeDocument(type="soul") for the initial write.',
);
} else if (phase.includes('User Identity')) {
if (ctx.userInfo?.displayName) {
const displayName = JSON.stringify(ctx.userInfo.displayName).replaceAll('<', '\\u003c');
hints.push(
`Initial account user_info suggests displayName ${displayName}. Treat it as unconfirmed: ask whether you may use that name, then call saveUserQuestion with fullName only after the user confirms it or gives a correction.`,
);
}
hints.push(
'THIS TURN, as soon as the user tells you their name, call saveUserQuestion with fullName β do NOT wait until you also know their role. Persist the name immediately.',
);
hints.push(
'Seed the persona document the moment you have ANY useful fact about the user (just a name, just a role, or both). If empty, call writeDocument(type="persona") with a short initial draft containing whatever you know so far (even one line). If already non-empty, call updateDocument(type="persona") with `insertAt` at the end of the right section (use `line = totalLines + 1` to append) or `replace` for a textual tweak. Do NOT defer persistence until more facts arrive.',
);
} else if (phase.includes('Discovery')) {
hints.push(
'When the user tells you their profession, record it with updateDocument(type="persona"). Preferred shape: `{ mode: "insertAt", line: <line shown in <current_user_persona>>, content: "- new fact" }`. Use writeDocument(type="persona") only if the document is still empty. Do NOT call saveUserQuestion with interests or customInterests β interest collection has been removed from onboarding.',
);
hints.push(
'EARLY EXIT: A true early-exit signal is the user explicitly wanting to END onboarding (e.g., "I\'m tired", "I have to go", "let\'s chat next time", "no time right now", "let\'s stop for now", "let\'s wrap it up", "that\'s enough"; recognize equivalent phrasing in any language). Short affirmations like "ok" / "sure" / "alright" / "yes" / "got it" are NOT early-exit signals β they confirm what you just said and you should continue the current phase normally. When you see a real exit signal: stop asking questions, persist any unsaved fields best-effort (call saveUserQuestion with whatever you have), persist the persona via updateDocument (or writeDocument if it is still empty) β do NOT retry on failure β send a short warm farewell (1β2 sentences), then call `finishOnboarding`. Do NOT call `showAgentMarketplace` on early exit β that handoff is for normal completion only.',
);
} else if (phase.includes('Summary')) {
if (!marketplaceAlreadyOpened) {
hints.push(
'Present a summary, then THIS TURN call `showAgentMarketplace` exactly once with `{ requestId, categoryHints, prompt }` β pick 1β3 MarketplaceCategory slugs from what you learned in discovery. The picker is the required handoff that lets the user choose recommended assistants; do NOT skip it on normal completion. After the showAgentMarketplace tool result comes back, **STOP this turn** β no more tool calls and no closing text yet. The picker resolves directly via the tool result UI (the user will pick / skip in place); when it resolves, the runtime will start a NEW assistant turn whose tool result describes what was picked. The closing + `finishOnboarding` belong to that next turn. EXCEPTION: if the user has just signaled true early exit (e.g., "I have to go", "let\'s chat next time", "I\'m tired"; equivalents in any language) in this same turn, skip the marketplace entirely. Instead: persist any unsaved fields (best-effort), send a brief warm farewell, then call `finishOnboarding`. The marketplace handoff is mandatory for normal completion only β never on early exit.',
);
} else {
hints.push(
'You have ALREADY opened the marketplace picker this conversation, and the user has just resolved it through the picker UI β the latest tool result describes what was picked (look for `installedAgentIds` / `selectedTemplateIds`, or a `skipped`/`cancelled` status). Do NOT call `showAgentMarketplace` again, do NOT claim you just opened the list, and do NOT wait for another user message. THIS TURN: (1) briefly acknowledge the picks (or the skip/cancel) in 1β2 sentences; (2) call `updateDocument(type="persona")` with `insertAt` mode to record the picks (categories/use cases) so future sessions remember; (3) call `finishOnboarding`. If the tool result indicates skip/cancel, skip step 2 and just close + `finishOnboarding`.',
);
}
}
hints.push(
'PERSISTENCE RULE: Call the persistence tools (saveUserQuestion, writeDocument, updateDocument) to save information as you collect it β simply acknowledging in conversation is NOT enough. For document writes: use writeDocument only for the first write when the document is empty; for every subsequent edit use updateDocument with the appropriate hunk mode (`insertAt` / `replaceLines` / `deleteLines` for line-based edits, `replace` / `delete` for byte-exact textual edits). The injected <current_*_document> view shows each line prefixed with its 1-based number and `β` β use those numbers for line-based hunks.',
);
hints.push(
'TURN ORDER: A message that contains a tool call does NOT yield the turn to the user β the agent loop continues after the tool result. So never put a user-facing question in the same message as a tool call. When you need to both persist something and ask the user a question, use two messages: first emit the tool call(s) with no question text (a brief acknowledgement or no text is fine), then β after the tool results return β ask your question in a separate message with NO tool call. Bundling a question with a tool call strands the question and forces a confused "waiting for your reply" filler.',
);
hints.push(
'CONFIRMATION vs EARLY EXIT: Short replies like "ok" / "sure" / "alright" / "yes" / "got it" (and equivalents in any language) are CONFIRMATIONS, not early-exit signals. Continue the current phase normally β in Summary that means calling `showAgentMarketplace` next, NOT `finishOnboarding` directly.',
);
if (
phase.includes('Agent Identity') ||
phase.includes('User Identity') ||
phase.includes('Discovery')
) {
hints.push(
'EARLY EXIT REMINDER: A true early-exit signal means the user explicitly wants the onboarding to END β examples: "I\'m tired", "I have to go", "let\'s chat next time", "no time right now", "let\'s stop for now", "let\'s wrap it up", "that\'s enough"; recognize equivalent phrasing in any language. When you see one (and only then), persist any unsaved fields, persist SOUL.md and the user persona via updateDocument (or writeDocument if either is still empty) β best-effort; do NOT retry on failure β send a brief warm farewell, then call `finishOnboarding`. Do NOT call `showAgentMarketplace` on early exit β that handoff is for normal completion only.',
);
}
return `<next_actions>\n${hints.join('\n')}\n</next_actions>`;
}
/**
* Override: always create a standalone virtual user message instead of appending
* to the last user message. This keeps the action hints visually and semantically
* separate from the user's actual input.
*/
protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
if (this.shouldSkip(context)) {
return this.markAsExecuted(context);
}
const content = this.buildContent(context);
if (!content) {
return this.markAsExecuted(context);
}
const clonedContext = this.cloneContext(context);
clonedContext.messages.push(this.createVirtualLastUserMessage(content));
return this.markAsExecuted(clonedContext);
}
}