Skip to content

🀯 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.

8.5 KB
Raw Blame
/**
 * Runtime Step Context Types
 *
 * Step Context is computed at the beginning of each Agent Runtime step
 * and injected into Context Engine and Tool Executors.
 *
 * Key principles:
 * 1. Computed by the caller (AgentRuntime), not by Context Engine or Executor
 * 2. Executors read from stepContext, return new state via result.state
 * 3. Replaces the deprecated pluginState passing pattern
 */

/** Status of a todo item */
export type StepContextTodoStatus = 'todo' | 'processing' | 'completed';

/**
 * Todo item structure
 * Duplicated here to avoid circular dependency with builtin-tool-lobe-agent
 */
export interface StepContextTodoItem {
  status: StepContextTodoStatus;
  text: string;
}

/**
 * Todo list structure in step context
 */
export interface StepContextTodos {
  items: StepContextTodoItem[];
  updatedAt: string;
}

/**
 * Activated skill info from activateSkill messages
 */
export interface StepActivatedSkill {
  description?: string;
  /**
   * DB skill id. Absent for filesystem (project/device) and builtin skill
   * activations, whose persisted state carries no id β€” consumers match by
   * `name` (the server exec paths resolve archives/project skills by name).
   */
  id?: string;
  name: string;
}

/**
 * Initial Page Editor context
 * Stored at operation initialization and remains constant
 */
export interface InitialPageEditorContext {
  /**
   * Initial markdown content of the page
   */
  markdown: string;
  /**
   * Document metadata
   */
  metadata: {
    charCount?: number;
    lineCount?: number;
    title: string;
  };
  /**
   * Initial XML structure (for reference)
   */
  xml: string;
}

/**
 * Active topic document context
 * Captured when a user leaves the topic page editor but continues the same
 * topic conversation from the regular chat surface.
 */
export interface RuntimeActiveTopicDocumentContext {
  /**
   * Agent-document row ID used by lobe-agent-documents read/patch/edit APIs.
   */
  agentDocumentId?: string;
  /**
   * Underlying documents.id used by topic page routes.
   */
  documentId: string;
  /**
   * Optional send-time document snapshot.
   *
   * This lets non-page surfaces, such as an agent-document floating panel,
   * provide the current document body without enabling PageAgent editor tools.
   */
  snapshot?: InitialPageEditorContext;
  /**
   * Human-readable title for model disambiguation.
   */
  title?: string | null;
}

/**
 * User-selected skill context for the current request
 * Captured from slash-menu skill action tags before send
 */
export interface RuntimeSelectedSkill {
  /**
   * Preloaded skill content (markdown instructions).
   * When present, injected directly into user message instead of
   * constructing fake activateSkill tool-call preload messages.
   */
  content?: string;
  /**
   * Skill identifier used by runtime/tooling
   */
  identifier: string;
  /**
   * Human-readable skill name shown in the input UI
   */
  name: string;
}

/**
 * User-selected tool context for the current request
 * Captured from slash-menu tool action tags before send
 */
export interface RuntimeSelectedTool {
  /**
   * Preloaded tool context (systemRole + API descriptions).
   * When present, injected directly into user message instead of relying on
   * LLM to discover/activate the tool at runtime β€” saves tokens.
   */
  content?: string;
  /**
   * Tool identifier used by runtime/tooling
   */
  identifier: string;
  /**
   * Human-readable tool name shown in the input UI
   */
  name: string;
}

/**
 * Runtime Step Context
 *
 * Contains dynamically computed state that changes between steps.
 * Computed from messages at the beginning of each step.
 *
 * @example
 * ```typescript
 * const stepContext = computeStepContext(state);
 * // Pass to Context Engine
 * messagesEngine.process({ messages, stepContext });
 * // Pass to Executor
 * executor.invoke(params, { stepContext, messageId, ... });
 * ```
 */
export interface RuntimeStepContext {
  /**
   * Activated skills accumulated from activateSkill messages
   * Skills once activated remain active for the rest of the conversation
   */
  activatedSkills?: StepActivatedSkill[];
  /**
   * Activated tool identifiers accumulated from lobe-activator messages
   * Tools once activated remain active for the rest of the conversation
   */
  activatedToolIds?: string[];
  /** Tools the current operation can load through the client activator. */
  discoverableToolIds?: string[];
  /**
   * Whether there are queued user messages waiting to be processed.
   * When true after tool completion, the agent should finish early
   * so the queued messages can be sent as a new operation.
   */
  hasQueuedMessages?: boolean;
  /**
   * Current todo list state
   * Computed from the latest lobe-agent tool message in the conversation
   */
  todos?: StepContextTodos;
}

/**
 * Agent mentioned by the user via @ in the input editor
 */
export interface RuntimeMentionedAgent {
  /** Agent ID */
  id: string;
  /** Agent display name */
  name: string;
}

/**
 * A slim tool manifest injected at runtime by callers (e.g. @mention β†’ callAgent).
 * Structurally compatible with LobeToolManifest from @lobechat/context-engine
 * without requiring a cross-package import.
 */
export interface InjectedToolManifest {
  api: Array<{
    description: string;
    name: string;
    parameters: Record<string, any>;
  }>;
  identifier: string;
  meta: { description?: string; title?: string };
  systemRole?: string;
  type?: 'builtin' | 'default' | 'markdown' | 'mcp' | 'standalone';
}

/**
 * Initial Context
 *
 * Contains state captured at operation initialization.
 * Remains constant throughout the operation lifecycle.
 */
export interface RuntimeInitialContext {
  /**
   * Active topic document carried from page route to regular chat route.
   * This lets the model continue document work without page-editor tools.
   */
  activeTopicDocument?: RuntimeActiveTopicDocumentContext;
  /**
   * Goal progress overview, built from the goal detail page the user is
   * currently viewing. Injected into the last user message so the LLM can
   * answer progress questions about the goal without extra tool calls.
   */
  goalOverview?: InitialGoalOverviewContext;
  /**
   * Ad-hoc tool manifests injected by callers for the current request.
   * Merged into the tool resolution output without passing through ToolsEngine.
   * Deduplication: manifests whose identifier already appears in enabledToolIds are skipped.
   */
  injectedManifests?: InjectedToolManifest[];
  /**
   * Agents explicitly @mentioned by the user in the input editor.
   * When present in a non-group conversation, the current agent acts as
   * supervisor and can delegate to the mentioned agents via callAgent.
   */
  mentionedAgents?: RuntimeMentionedAgent[];
  /**
   * Live project context (members, knowledge, open tasks) for a run inside a
   * project, rebuilt each turn so renames and membership changes never go stale.
   */
  projectContext?: InitialProjectContext;
  /**
   * Skills explicitly selected by the user for the current request
   * This is ephemeral runtime context and is not persisted to chat history
   */
  selectedSkills?: RuntimeSelectedSkill[];
  /**
   * Tools explicitly selected by the user for the current request
   * This constrains the available tools for the current runtime execution
   */
  selectedTools?: RuntimeSelectedTool[];
  /**
   * Task Manager page context, built from the tasks list/detail page the user
   * is currently viewing. Injected into the last user message so the LLM can
   * answer questions about the on-screen tasks without extra tool calls.
   */
  taskManager?: InitialTaskManagerContext;
}

export interface InitialProjectContext {
  /** Prebuilt prompt describing the project the run belongs to. */
  contextPrompt: string;
}

export interface InitialTaskManagerContext {
  /** Prebuilt prompt describing the tasks shown on the page. */
  contextPrompt: string;
}

export interface GoalOverviewTaskItem {
  /** 1-based attempt count so far, when known. */
  attempts?: number;
  /** 1-based Task number as shown in the UI (#1, #2 …). */
  seq?: number;
  status: string;
  title: string;
}

export interface GoalOverviewDecision {
  question: string;
}

/**
 * Structured snapshot of the goal the user is viewing. Producers (goal page /
 * server pipeline) pass the data; the context-engine injector owns turning it
 * into prompt text, so wording changes never touch the transports.
 */
export interface InitialGoalOverviewContext {
  findings: string[];
  goal: {
    requirement?: string | null;
    status: string;
    title: string;
  };
  pendingDecisions: GoalOverviewDecision[];
  tasks: GoalOverviewTaskItem[];
}