Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
docs: translate comments from Chinese to English (#15)
Jiayuan3a435aac8a8b
diff --git a/src/agent/cli.ts b/src/agent/cli.tsindex 07c4e69a33..32de4bc3bd 100644--- a/src/agent/cli.ts+++ b/src/agent/cli.ts@@ -112,7 +112,7 @@ async function main() {sessionId: opts.session,});- // 如果是新创建的 session,提示用户 sessionId+ // If it's a newly created session, notify user of sessionIdif (!opts.session) {console.error(`[session: ${agent.sessionId}]`);}diff --git a/src/agent/context-window/guard.ts b/src/agent/context-window/guard.tsindex 20fdd4f258..1fdfddfe6d 100644--- a/src/agent/context-window/guard.ts+++ b/src/agent/context-window/guard.ts@@ -1,22 +1,22 @@/**- * Context Window Guard - 上下文窗口验证+ * Context Window Guard - Context Window Validation*- * 在 agent 运行前验证 context window 是否足够,防止 token 溢出+ * Validates context window sufficiency before agent runs to prevent token overflow*/import type { ContextWindowInfo, ContextWindowGuardResult, ContextWindowSource } from "./types.js";-/** 硬性最小 token 数,低于此值将阻止运行 */+/** Hard minimum token count, below which execution will be blocked */export const CONTEXT_WINDOW_HARD_MIN_TOKENS = 16_000;-/** 警告阈值,低于此值会发出警告 */+/** Warning threshold, below which a warning will be issued */export const CONTEXT_WINDOW_WARN_BELOW_TOKENS = 32_000;-/** 默认 context window(当无法获取时) */+/** Default context window (when unable to obtain) */export const DEFAULT_CONTEXT_TOKENS = 200_000;/**- * 标准化为正整数+ * Normalize to positive integer*/function normalizePositiveInt(value: unknown): number | null {if (typeof value !== "number" || !Number.isFinite(value)) return null;@@ -25,31 +25,31 @@ function normalizePositiveInt(value: unknown): number | null {}/**- * 解析 context window 信息+ * Resolve context window information*- * 优先级:model > config > default+ * Priority: model > config > default*/export function resolveContextWindowInfo(params: {- /** Model 的 contextWindow 属性 */+ /** Model's contextWindow property */modelContextWindow?: number | undefined;- /** 配置中指定的 context tokens */+ /** Context tokens specified in config */configContextTokens?: number | undefined;- /** 默认值 */+ /** Default value */defaultTokens?: number | undefined;}): ContextWindowInfo {- // 1. 尝试从 model 获取+ // 1. Try getting from modelconst fromModel = normalizePositiveInt(params.modelContextWindow);if (fromModel) {return { tokens: fromModel, source: "model" };}- // 2. 尝试从配置获取+ // 2. Try getting from configconst fromConfig = normalizePositiveInt(params.configContextTokens);if (fromConfig) {return { tokens: fromConfig, source: "config" };}- // 3. 使用默认值+ // 3. Use default valuereturn {tokens: Math.floor(params.defaultTokens ?? DEFAULT_CONTEXT_TOKENS),source: "default",@@ -57,9 +57,9 @@ export function resolveContextWindowInfo(params: {}/**- * 评估 context window guard+ * Evaluate context window guard*- * 返回是否需要警告或阻止运行+ * Returns whether warning or blocking is needed*/export function evaluateContextWindowGuard(params: {info: ContextWindowInfo;@@ -85,9 +85,9 @@ export function evaluateContextWindowGuard(params: {}/**- * 完整的 context window guard 流程+ * Complete context window guard workflow*- * 解析 + 评估一步完成+ * Resolution + evaluation in one step*/export function checkContextWindow(params: {modelContextWindow?: number | undefined;diff --git a/src/agent/context-window/summarization.ts b/src/agent/context-window/summarization.tsindex e6808e51ea..dbb69f85e1 100644--- a/src/agent/context-window/summarization.ts+++ b/src/agent/context-window/summarization.ts@@ -1,7 +1,7 @@/**- * 摘要式 Compaction+ * Summary-based Compaction*- * 使用 LLM 生成历史消息的摘要,而不是简单截断+ * Uses LLM to generate summaries of historical messages instead of simple truncation*/import type { AgentMessage } from "@mariozechner/pi-agent-core";@@ -9,41 +9,41 @@ import { generateSummary, estimateTokens } from "@mariozechner/pi-coding-agent";import type { Model } from "@mariozechner/pi-ai";import { estimateMessagesTokens } from "./token-estimation.js";-/** 摘要 Compaction 结果 */+/** Summary compaction result */export type SummaryCompactionResult = {- /** 保留的消息(包含摘要消息) */+ /** Kept messages (including summary message) */kept: AgentMessage[];- /** 移除的消息数量 */+ /** Number of removed messages */removedCount: number;- /** 移除的 token 数 */+ /** Tokens removed */tokensRemoved: number;- /** 保留的 token 数 */+ /** Tokens kept */tokensKept: number;- /** 生成的摘要 */+ /** Generated summary */summary: string;- /** compaction 原因 */+ /** Compaction reason */reason: "summary";};-/** 摘要 Compaction 参数 */+/** Summary compaction parameters */export type SummaryCompactionParams = {- /** 消息列表 */+ /** Message list */messages: AgentMessage[];- /** LLM Model(用于生成摘要) */+ /** LLM Model (for generating summary) */model: Model<any>;/** API Key */apiKey: string;- /** 可用 token 数 */+ /** Available tokens */availableTokens: number;- /** 目标利用率 (0-1),默认 0.5 */+ /** Target utilization ratio (0-1), defaults to 0.5 */targetRatio?: number | undefined;- /** 最少保留消息数,默认 10 */+ /** Minimum messages to keep, defaults to 10 */minKeepMessages?: number | undefined;- /** 预留给摘要生成的 token 数,默认 2048 */+ /** Tokens reserved for summary generation, defaults to 2048 */reserveTokens?: number | undefined;- /** 自定义摘要指令 */+ /** Custom summary instructions */customInstructions?: string | undefined;- /** 之前的摘要(用于增量更新) */+ /** Previous summary (for incremental update) */previousSummary?: string | undefined;/** AbortSignal */signal?: AbortSignal | undefined;@@ -59,7 +59,7 @@ const DEFAULT_SUMMARY_INSTRUCTIONS = `Summarize the conversation history conciseKeep the summary concise but complete. Use bullet points for clarity.`;/**- * 将消息分割为需要摘要的部分和保留的部分+ * Split messages into parts to summarize and parts to keep*/export function splitMessagesForSummary(messages: AgentMessage[],@@ -73,18 +73,18 @@ export function splitMessagesForSummary(const minKeep = options?.minKeepMessages ?? 10;if (messages.length <= minKeep) {- return null; // 消息太少,不需要压缩+ return null; // Too few messages, no compression needed}const totalTokens = estimateMessagesTokens(messages);const targetTokens = Math.floor(availableTokens * targetRatio);- // 如果当前已经在目标内,不需要压缩+ // If already within target, no compression neededif (totalTokens <= targetTokens) {return null;}- // 从后往前保留消息+ // Keep messages from back to frontconst toKeep: AgentMessage[] = [];let keptTokens = 0;@@ -92,19 +92,19 @@ export function splitMessagesForSummary(const msg = messages[i]!;const msgTokens = estimateTokens(msg);- // 检查是否可以添加这条消息+ // Check if this message can be addedif (keptTokens + msgTokens <= targetTokens || toKeep.length < minKeep) {toKeep.unshift(msg);keptTokens += msgTokens;}- // 如果已经达到最小保留数且超过目标,停止+ // If minimum keep count reached and exceeds target, stopif (toKeep.length >= minKeep && keptTokens >= targetTokens) {break;}}- // 需要摘要的消息+ // Messages to summarizeconst toSummarize = messages.slice(0, messages.length - toKeep.length);if (toSummarize.length === 0) {@@ -115,7 +115,7 @@ export function splitMessagesForSummary(}/**- * 创建摘要消息+ * Create summary message*/function createSummaryMessage(summary: string, previousSummary?: string): AgentMessage {const content = previousSummary@@ -130,9 +130,9 @@ function createSummaryMessage(summary: string, previousSummary?: string): AgentM}/**- * 执行摘要式 Compaction+ * Execute summary-based compaction*- * 使用 LLM 生成历史消息的摘要,然后将摘要和最近的消息组合+ * Uses LLM to generate summary of historical messages, then combines summary with recent messages*/export async function compactMessagesWithSummary(params: SummaryCompactionParams,@@ -162,7 +162,7 @@ export async function compactMessagesWithSummary(const { toSummarize, toKeep } = split;- // 生成摘要+ // Generate summaryconst instructions = customInstructions || DEFAULT_SUMMARY_INSTRUCTIONS;const summary = await generateSummary(toSummarize,@@ -174,10 +174,10 @@ export async function compactMessagesWithSummary(previousSummary,);- // 创建摘要消息+ // Create summary messageconst summaryMessage = createSummaryMessage(summary, previousSummary);- // 组合结果+ // Combine resultsconst kept = [summaryMessage, ...toKeep];const tokensRemoved = estimateMessagesTokens(toSummarize);@@ -194,9 +194,9 @@ export async function compactMessagesWithSummary(}/**- * 分块生成摘要(用于超大历史)+ * Generate summary in chunks (for very large history)*- * 当历史太大时,分块生成摘要然后合并+ * When history is too large, generate summaries by chunks then merge*/export async function compactMessagesWithChunkedSummary(params: SummaryCompactionParams & {@@ -217,7 +217,7 @@ export async function compactMessagesWithChunkedSummary(maxChunkTokens = 50000,} = params;- // 分割消息+ // Split messagesconst split = splitMessagesForSummary(messages, availableTokens, {targetRatio,minKeepMessages,@@ -229,13 +229,13 @@ export async function compactMessagesWithChunkedSummary(const { toSummarize, toKeep } = split;- // 如果需要摘要的消息不多,直接摘要+ // If messages to summarize are not many, summarize directlyconst toSummarizeTokens = estimateMessagesTokens(toSummarize);if (toSummarizeTokens <= maxChunkTokens) {return compactMessagesWithSummary(params);}- // 分块处理+ // Process in chunksconst chunks: AgentMessage[][] = [];let currentChunk: AgentMessage[] = [];let currentTokens = 0;@@ -257,7 +257,7 @@ export async function compactMessagesWithChunkedSummary(chunks.push(currentChunk);}- // 为每个块生成摘要+ // Generate summary for each chunkconst instructions = customInstructions || DEFAULT_SUMMARY_INSTRUCTIONS;const chunkSummaries: string[] = [];@@ -276,13 +276,13 @@ export async function compactMessagesWithChunkedSummary(runningContext = chunkSummary;}- // 最终摘要就是最后一个块的摘要(已经包含了之前的上下文)+ // Final summary is the last chunk's summary (already includes previous context)const finalSummary = chunkSummaries[chunkSummaries.length - 1] ?? "";- // 创建摘要消息+ // Create summary messageconst summaryMessage = createSummaryMessage(finalSummary);- // 组合结果+ // Combine resultsconst kept = [summaryMessage, ...toKeep];const tokensRemoved = estimateMessagesTokens(toSummarize);diff --git a/src/agent/context-window/token-estimation.ts b/src/agent/context-window/token-estimation.tsindex e0a6701883..7899b05003 100644--- a/src/agent/context-window/token-estimation.ts+++ b/src/agent/context-window/token-estimation.ts@@ -1,45 +1,45 @@/**- * Token 估算工具+ * Token estimation tool*- * 提供消息和系统提示词的 token 计数功能+ * Provides token counting functionality for messages and system prompts*/import type { AgentMessage } from "@mariozechner/pi-agent-core";import { estimateTokens } from "@mariozechner/pi-coding-agent";import type { TokenEstimation, TokenAwareCompactionResult } from "./types.js";-/** 安全边界系数,用于补偿估算不准确 */+/** Safety margin coefficient to compensate for estimation inaccuracy */export const ESTIMATION_SAFETY_MARGIN = 1.2; // 20% buffer-/** 触发 compaction 的利用率阈值 */+/** Utilization threshold for triggering compaction */export const COMPACTION_TRIGGER_RATIO = 0.8; // 80%-/** Compaction 目标利用率 */+/** Compaction target utilization ratio */export const COMPACTION_TARGET_RATIO = 0.5; // 50%-/** 最小保留消息数 */+/** Minimum messages to keep */export const MIN_KEEP_MESSAGES = 10;/**- * 估算消息数组的总 token 数+ * Estimate total tokens for message array*/export function estimateMessagesTokens(messages: AgentMessage[]): number {return messages.reduce((sum, message) => sum + estimateTokens(message), 0);}/**- * 估算系统提示词的 token 数+ * Estimate tokens for system prompt*/export function estimateSystemPromptTokens(systemPrompt: string | undefined): number {if (!systemPrompt) return 0;- // 简单估算:约 4 字符 = 1 token(适用于英文/代码混合文本)- // 中文约 2 字符 = 1 token- // 取平均值 3+ // Simple estimation: ~4 chars = 1 token (for English/code mixed text)+ // Chinese ~2 chars = 1 token+ // Average value of 3return Math.ceil(systemPrompt.length / 3);}/**- * 计算完整的 token 使用情况+ * Calculate complete token usage*/export function estimateTokenUsage(params: {messages: AgentMessage[];@@ -49,15 +49,15 @@ export function estimateTokenUsage(params: {}): TokenEstimation {const messageTokens = estimateMessagesTokens(params.messages);const systemPromptTokens = estimateSystemPromptTokens(params.systemPrompt);- const reserve = params.reserveTokens ?? 1024; // 预留给响应生成+ const reserve = params.reserveTokens ?? 1024; // Reserved for response generation- // 可用 token = 总窗口 - 系统提示 - 预留+ // Available tokens = total window - system prompt - reserveconst availableTokens = Math.max(0,params.contextWindowTokens - systemPromptTokens - reserve,);- // 计算利用率(带安全边界)+ // Calculate utilization ratio (with safety margin)const safeMessageTokens = messageTokens * ESTIMATION_SAFETY_MARGIN;const utilizationRatio = availableTokens > 0 ? safeMessageTokens / availableTokens : 1;@@ -70,16 +70,16 @@ export function estimateTokenUsage(params: {}/**- * 判断是否需要 compaction+ * Determine if compaction is needed*/export function shouldCompact(estimation: TokenEstimation): boolean {return estimation.utilizationRatio >= COMPACTION_TRIGGER_RATIO;}/**- * Token 感知的消息压缩+ * Token-aware message compression*- * 策略:从最旧的消息开始移除,直到达到目标利用率+ * Strategy: Remove from oldest messages until reaching target utilization ratio*/export function compactMessagesTokenAware(messages: AgentMessage[],@@ -93,39 +93,39 @@ export function compactMessagesTokenAware(const minKeep = options?.minKeepMessages ?? MIN_KEEP_MESSAGES;if (messages.length <= minKeep) {- return null; // 消息太少,不压缩+ return null; // Too few messages, no compression}const currentTokens = estimateMessagesTokens(messages);const targetTokens = Math.floor(availableTokens * targetRatio);- // 如果当前已经在目标内,不需要压缩+ // If already within target, no compression neededif (currentTokens <= targetTokens) {return null;}- // 从后往前保留消息,直到达到目标 token 数+ // Keep messages from back to front until reaching target token countconst kept: AgentMessage[] = [];let keptTokens = 0;- // 反向遍历,保留最新的消息+ // Reverse iteration, keep newest messagesfor (let i = messages.length - 1; i >= 0; i--) {const msg = messages[i]!;const msgTokens = estimateTokens(msg);- // 检查是否可以添加这条消息+ // Check if this message can be addedif (keptTokens + msgTokens <= targetTokens || kept.length < minKeep) {kept.unshift(msg);keptTokens += msgTokens;}- // 如果已经达到最小保留数且超过目标,停止+ // If minimum keep count reached and exceeds target, stopif (kept.length >= minKeep && keptTokens >= targetTokens) {break;}}- // 如果保留的消息数量不变,说明没有压缩+ // If kept message count unchanged, no compression occurredif (kept.length >= messages.length) {return null;}@@ -142,9 +142,9 @@ export function compactMessagesTokenAware(}/**- * 检查单条消息是否过大+ * Check if single message is oversized*- * 如果单条消息超过 context window 的一定比例,可能需要特殊处理+ * If a single message exceeds a certain ratio of context window, special handling may be needed*/export function isMessageOversized(message: AgentMessage,diff --git a/src/agent/context-window/types.ts b/src/agent/context-window/types.tsindex 11cbb8eeea..c53dbbf1cc 100644--- a/src/agent/context-window/types.ts+++ b/src/agent/context-window/types.ts@@ -1,48 +1,48 @@/**- * Context Window Guard - 类型定义+ * Context Window Guard - Type Definitions*- * 用于管理和验证 LLM 上下文窗口限制+ * Used to manage and validate LLM context window limits*/-/** Context window 信息来源 */+/** Context window information source */export type ContextWindowSource = "model" | "config" | "default";-/** Context window 信息 */+/** Context window information */export type ContextWindowInfo = {- /** Token 数量 */+ /** Token count */tokens: number;- /** 来源 */+ /** Source */source: ContextWindowSource;};-/** Context window guard 验证结果 */+/** Context window guard validation result */export type ContextWindowGuardResult = ContextWindowInfo & {- /** 是否需要警告(窗口较小) */+ /** Whether warning is needed (window is small) */shouldWarn: boolean;- /** 是否应该阻止运行(窗口太小) */+ /** Whether execution should be blocked (window is too small) */shouldBlock: boolean;};-/** Token 估算结果 */+/** Token estimation result */export type TokenEstimation = {- /** 消息总 token 数 */+ /** Total message tokens */messageTokens: number;- /** 系统提示词 token 数 */+ /** System prompt tokens */systemPromptTokens: number;- /** 可用 token 数 */+ /** Available tokens */availableTokens: number;- /** 使用率 (0-1) */+ /** Utilization ratio (0-1) */utilizationRatio: number;};-/** Compaction 结果(带 token 信息) */+/** Compaction result (with token information) */export type TokenAwareCompactionResult = {- /** 保留的消息 */+ /** Kept messages */kept: import("@mariozechner/pi-agent-core").AgentMessage[];- /** 移除的消息数量 */+ /** Number of removed messages */removedCount: number;- /** 移除的 token 数 */+ /** Tokens removed */tokensRemoved: number;- /** 保留的 token 数 */+ /** Tokens kept */tokensKept: number;};diff --git a/src/agent/profile/types.ts b/src/agent/profile/types.tsindex fbbc4f827f..d6bc0c37a2 100644--- a/src/agent/profile/types.ts+++ b/src/agent/profile/types.ts@@ -1,8 +1,8 @@/**- * Agent Profile 类型定义+ * Agent Profile Type Definitions*/-/** Profile 文件名常量 */+/** Profile filename constants */export const PROFILE_FILES = {soul: "soul.md",identity: "identity.md",@@ -11,34 +11,34 @@ export const PROFILE_FILES = {bootstrap: "bootstrap.md",} as const;-/** Agent Profile 配置 */+/** Agent Profile configuration */export interface AgentProfile {/** Profile ID */id: string;- /** 人格约束 - 定义 agent 的行为边界和风格 */+ /** Personality constraints - defines agent's behavior boundaries and style */soul?: string | undefined;- /** 身份信息 - agent 的名称和自我认知 */+ /** Identity information - agent's name and self-awareness */identity?: string | undefined;- /** 自定义工具描述 - 额外的工具使用说明 */+ /** Custom tool descriptions - additional tool usage instructions */tools?: string | undefined;- /** 持久记忆 - 长期知识库 */+ /** Persistent memory - long-term knowledge base */memory?: string | undefined;- /** 初始上下文 - 每次对话的引导信息 */+ /** Initial context - guidance information for each conversation */bootstrap?: string | undefined;}-/** Profile Manager 选项 */+/** Profile Manager options */export interface ProfileManagerOptions {/** Profile ID */profileId: string;- /** 基础目录,默认 ~/.super-multica/agent-profiles */+ /** Base directory, defaults to ~/.super-multica/agent-profiles */baseDir?: string | undefined;}-/** 创建 Profile 的选项 */+/** Create Profile options */export interface CreateProfileOptions {- /** 基础目录 */+ /** Base directory */baseDir?: string | undefined;- /** 是否使用默认模板初始化 */+ /** Whether to initialize with default templates */useTemplates?: boolean | undefined;}diff --git a/src/agent/runner.ts b/src/agent/runner.tsindex da7da22401..95427a0d78 100644--- a/src/agent/runner.ts+++ b/src/agent/runner.ts@@ -12,7 +12,7 @@ import {} from "./context-window/index.js";/**- * 根据 provider 获取 API Key+ * Get API Key based on provider*/function resolveApiKey(provider: string): string | undefined {const providerEnvMap: Record<string, string> = {@@ -33,7 +33,7 @@ function resolveApiKey(provider: string): string | undefined {return process.env[envVar];}- // 尝试通用格式: PROVIDER_API_KEY+ // Try generic format: PROVIDER_API_KEYconst normalizedProvider = provider.toUpperCase().replace(/-/g, "_");return process.env[`${normalizedProvider}_API_KEY`];}@@ -45,7 +45,7 @@ export class Agent {private readonly profile?: ProfileManager;private readonly contextWindowGuard: ContextWindowGuardResult;- /** 当前会话 ID */+ /** Current session ID */readonly sessionId: string;constructor(options: AgentOptions = {}) {diff --git a/src/agent/session/compaction.ts b/src/agent/session/compaction.tsindex 636c36c057..935abe1b66 100644--- a/src/agent/session/compaction.ts+++ b/src/agent/session/compaction.ts@@ -14,16 +14,16 @@ import {export type CompactionResult = {kept: AgentMessage[];removedCount: number;- /** Token 感知模式下的额外信息 */+ /** Additional information in token-aware mode */tokensRemoved?: number | undefined;tokensKept?: number | undefined;- /** 摘要模式下生成的摘要 */+ /** Summary generated in summary mode */summary?: string | undefined;reason: "count" | "tokens" | "summary";};/**- * 基于消息数量的简单压缩(旧逻辑,保持向后兼容)+ * Simple compression based on message count (legacy logic, maintains backward compatibility)*/export function compactMessagesByCount(messages: AgentMessage[],@@ -40,7 +40,7 @@ export function compactMessagesByCount(}/**- * 基于 token 的智能压缩+ * Token-based intelligent compression*/export function compactMessagesByTokens(messages: AgentMessage[],@@ -62,13 +62,13 @@ export function compactMessagesByTokens(};}-/** 同步压缩选项(count/tokens 模式) */+/** Synchronous compaction options (count/tokens modes) */export type SyncCompactionOptions = {mode: "count" | "tokens";- // count 模式参数+ // count mode parametersmaxMessages?: number | undefined;keepLast?: number | undefined;- // tokens 模式参数+ // tokens mode parameterscontextWindowTokens?: number | undefined;systemPrompt?: string | undefined;reserveTokens?: number | undefined;@@ -76,19 +76,19 @@ export type SyncCompactionOptions = {minKeepMessages?: number | undefined;};-/** 摘要压缩选项(summary 模式) */+/** Summary compaction options (summary mode) */export type SummaryCompactionOptions = {mode: "summary";- // 必需参数+ // Required parametersmodel: Model<any>;apiKey: string;- // tokens 模式参数(复用)+ // tokens mode parameters (reused)contextWindowTokens?: number | undefined;systemPrompt?: string | undefined;reserveTokens?: number | undefined;targetRatio?: number | undefined;minKeepMessages?: number | undefined;- // summary 特有参数+ // summary-specific parameterscustomInstructions?: string | undefined;previousSummary?: string | undefined;signal?: AbortSignal | undefined;@@ -98,9 +98,9 @@ export type SummaryCompactionOptions = {export type CompactionOptions = SyncCompactionOptions | SummaryCompactionOptions;/**- * 统一的压缩入口(同步版本,用于 count/tokens 模式)+ * Unified compaction entry point (synchronous version, for count/tokens modes)*- * 根据模式选择压缩策略+ * Selects compaction strategy based on mode*/export function compactMessages(messages: AgentMessage[],@@ -114,7 +114,7 @@ export function compactMessages();}- // Token 模式+ // Token modeconst contextWindowTokens = options.contextWindowTokens ?? 200_000;const estimation = estimateTokenUsage({messages,@@ -135,9 +135,9 @@ export function compactMessages(}/**- * 摘要式压缩(异步版本)+ * Summary-based compaction (asynchronous version)*- * 使用 LLM 生成历史消息的摘要+ * Uses LLM to generate summary of historical messages*/export async function compactMessagesAsync(messages: AgentMessage[],@@ -151,12 +151,12 @@ export async function compactMessagesAsync(reserveTokens: options.reserveTokens,});- // 检查是否需要压缩+ // Check if compaction is neededif (!shouldCompactTokens(estimation)) {return null;}- // 使用分块摘要处理超大历史+ // Use chunked summary to handle very large historyconst result = await compactMessagesWithChunkedSummary({messages,model: options.model,diff --git a/src/agent/session/session-manager.ts b/src/agent/session/session-manager.tsindex 17f13fcd2e..c635c58e4e 100644--- a/src/agent/session/session-manager.ts+++ b/src/agent/session/session-manager.ts@@ -8,32 +8,32 @@ export type SessionManagerOptions = {sessionId: string;baseDir?: string | undefined;- // Compaction 模式配置- /** Compaction 模式: "count" 使用消息计数, "tokens" 使用 token 感知, "summary" 使用 LLM 摘要 */+ // Compaction mode configuration+ /** Compaction mode: "count" uses message count, "tokens" uses token awareness, "summary" uses LLM summary */compactionMode?: "count" | "tokens" | "summary" | undefined;- // Count 模式参数+ // Count mode parametersmaxMessages?: number | undefined;keepLast?: number | undefined;- // Token 模式参数- /** Context window token 数 */+ // Token mode parameters+ /** Context window token count */contextWindowTokens?: number | undefined;- /** 系统提示词(用于计算可用 token) */+ /** System prompt (used to calculate available tokens) */systemPrompt?: string | undefined;- /** 预留给响应的 token 数 */+ /** Tokens reserved for responses */reserveTokens?: number | undefined;- /** Compaction 目标利用率 (0-1) */+ /** Compaction target utilization ratio (0-1) */targetRatio?: number | undefined;- /** 最小保留消息数 */+ /** Minimum messages to keep */minKeepMessages?: number | undefined;- // Summary 模式参数- /** LLM Model(用于生成摘要) */+ // Summary mode parameters+ /** LLM Model (for generating summary) */model?: Model<any> | undefined;/** API Key */apiKey?: string | undefined;- /** 自定义摘要指令 */+ /** Custom summary instructions */customInstructions?: string | undefined;};@@ -41,16 +41,16 @@ export class SessionManager {private readonly sessionId: string;private readonly baseDir: string | undefined;private readonly compactionMode: "count" | "tokens" | "summary";- // Count 模式+ // Count modeprivate readonly maxMessages: number;private readonly keepLast: number;- // Token 模式+ // Token modeprivate readonly contextWindowTokens: number;private systemPrompt: string | undefined;private readonly reserveTokens: number;private readonly targetRatio: number;private readonly minKeepMessages: number;- // Summary 模式+ // Summary modeprivate model: Model<any> | undefined;private apiKey: string | undefined;private readonly customInstructions: string | undefined;@@ -63,21 +63,21 @@ export class SessionManager {this.sessionId = options.sessionId;this.baseDir = options.baseDir;- // Compaction 模式+ // Compaction modethis.compactionMode = options.compactionMode ?? "count";- // Count 模式参数+ // Count mode parametersthis.maxMessages = options.maxMessages ?? 80;this.keepLast = options.keepLast ?? 60;- // Token 模式参数+ // Token mode parametersthis.contextWindowTokens = options.contextWindowTokens ?? 200_000;this.systemPrompt = options.systemPrompt;this.reserveTokens = options.reserveTokens ?? 1024;this.targetRatio = options.targetRatio ?? 0.5;this.minKeepMessages = options.minKeepMessages ?? 10;- // Summary 模式参数+ // Summary mode parametersthis.model = options.model;this.apiKey = options.apiKey;this.customInstructions = options.customInstructions;@@ -86,35 +86,35 @@ export class SessionManager {}/**- * 更新系统提示词(用于 token 模式计算)+ * Update system prompt (for token mode calculation)*/setSystemPrompt(systemPrompt: string | undefined) {this.systemPrompt = systemPrompt;}/**- * 获取当前 context window token 数+ * Get current context window token count*/getContextWindowTokens(): number {return this.contextWindowTokens;}/**- * 设置 LLM Model(用于 summary 模式)+ * Set LLM Model (for summary mode)*/setModel(model: Model<any> | undefined) {this.model = model;}/**- * 设置 API Key(用于 summary 模式)+ * Set API Key (for summary mode)*/setApiKey(apiKey: string | undefined) {this.apiKey = apiKey;}/**- * 获取当前 compaction 模式+ * Get current compaction mode*/getCompactionMode(): "count" | "tokens" | "summary" {return this.compactionMode;@@ -171,9 +171,9 @@ export class SessionManager {let result;if (this.compactionMode === "summary") {- // Summary 模式需要 model 和 apiKey+ // Summary mode requires model and apiKeyif (!this.model || !this.apiKey) {- // 降级到 tokens 模式+ // Downgrade to tokens moderesult = compactMessages(messages, {mode: "tokens",contextWindowTokens: this.contextWindowTokens,@@ -196,7 +196,7 @@ export class SessionManager {previousSummary: this.previousSummary,});- // 保存摘要用于下次增量更新+ // Save summary for next incremental updateif (result?.summary) {this.previousSummary = result.summary;}@@ -204,10 +204,10 @@ export class SessionManager {} else {result = compactMessages(messages, {mode: this.compactionMode,- // Count 模式参数+ // Count mode parametersmaxMessages: this.maxMessages,keepLast: this.keepLast,- // Token 模式参数+ // Token mode parameterscontextWindowTokens: this.contextWindowTokens,systemPrompt: this.systemPrompt,reserveTokens: this.reserveTokens,@@ -230,7 +230,7 @@ export class SessionManager {removed: result.removedCount,kept: result.kept.length,timestamp: Date.now(),- // Token/Summary 模式下的额外信息+ // Additional information in Token/Summary modetokensRemoved: result.tokensRemoved,tokensKept: result.tokensKept,summary: result.summary,diff --git a/src/agent/tools/exec.ts b/src/agent/tools/exec.tsindex fbbb1a808d..222141f1c4 100644--- a/src/agent/tools/exec.ts+++ b/src/agent/tools/exec.ts@@ -71,12 +71,12 @@ export function createExecTool(defaultCwd?: string): AgentTool<typeof ExecSchemachild.on("error", (err) => {if (timeout) clearTimeout(timeout);spawnError = err;- // 不 reject,让 close 事件处理+ // Don't reject, let close event handle});child.on("close", (code) => {if (timeout) clearTimeout(timeout);- // 如果有 spawn 错误,返回错误信息+ // If there's a spawn error, return error messageif (spawnError) {resolve({content: [{ type: "text", text: `Error: ${spawnError.message}` }],diff --git a/src/agent/types.ts b/src/agent/types.tsindex fc7ad9bdd4..fb99426b48 100644--- a/src/agent/types.ts+++ b/src/agent/types.ts@@ -11,38 +11,38 @@ export type AgentLogger = {};export type AgentOptions = {- /** Agent Profile ID - 加载预定义的身份、人格、记忆等配置 */+ /** Agent Profile ID - loads predefined identity, personality, memory and other configurations */profileId?: string | undefined;- /** Profile 基础目录,默认 ~/.super-multica/agent-profiles */+ /** Profile base directory, defaults to ~/.super-multica/agent-profiles */profileBaseDir?: string | undefined;provider?: string | undefined;model?: string | undefined;- /** System prompt,如果设置了 profileId 会自动从 profile 构建 */+ /** System prompt, if profileId is set will auto-construct from profile */systemPrompt?: string | undefined;thinkingLevel?: ThinkingLevel | undefined;- /** 命令执行目录 */+ /** Command execution directory */cwd?: string | undefined;sessionId?: string | undefined;logger?: AgentLogger | undefined;- // === Context Window Guard 配置 ===- /** 手动指定 context window token 数(覆盖 model 的值) */+ // === Context Window Guard Configuration ===+ /** Manually specify context window token count (overrides model value) */contextWindowTokens?: number | undefined;- /** 预留给响应生成的 token 数,默认 1024 */+ /** Tokens reserved for response generation, defaults to 1024 */reserveTokens?: number | undefined;/**- * Compaction 模式:- * - "count": 使用旧的消息计数- * - "tokens": 使用 token 感知(默认)- * - "summary": 使用 LLM 生成摘要+ * Compaction mode:+ * - "count": uses legacy message count+ * - "tokens": uses token awareness (default)+ * - "summary": uses LLM to generate summary*/compactionMode?: "count" | "tokens" | "summary" | undefined;- /** Compaction 目标利用率 (0-1),默认 0.5 */+ /** Compaction target utilization ratio (0-1), defaults to 0.5 */compactionTargetRatio?: number | undefined;- /** 最小保留消息数,默认 10 */+ /** Minimum messages to keep, defaults to 10 */minKeepMessages?: number | undefined;- // === Summary Compaction 配置 ===- /** 自定义摘要生成指令 */+ // === Summary Compaction Configuration ===+ /** Custom summary generation instructions */summaryInstructions?: string | undefined;};diff --git a/src/gateway/app.controller.ts b/src/gateway/app.controller.tsindex 8920f18400..d80cb10952 100644--- a/src/gateway/app.controller.ts+++ b/src/gateway/app.controller.ts@@ -22,7 +22,7 @@ export class AppController {@Post("broadcast")broadcast(@Body() body: { text: string }): { success: boolean } {- // 通过 HTTP 接口广播消息给所有 WebSocket 客户端+ // Broadcast messages to all WebSocket clients via HTTP interfacethis.eventsGateway.server.emit("message", {from: "server",text: body.text,diff --git a/src/gateway/events.gateway.ts b/src/gateway/events.gateway.tsindex 3c7ab4cad6..917446e87c 100644--- a/src/gateway/events.gateway.ts+++ b/src/gateway/events.gateway.ts@@ -29,9 +29,9 @@ import {cors: {origin: "*",},- // 心跳检测配置- pingInterval: 25000, // 每 25 秒发送 PING- pingTimeout: 20000, // 20 秒内需响应,否则断开+ // Heartbeat detection configuration+ pingInterval: 25000, // Send PING every 25 seconds+ pingTimeout: 20000, // Must respond within 20 seconds, otherwise disconnect})export class EventsGatewayimplements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect@@ -44,9 +44,9 @@ export class EventsGateway@WebSocketServer()server!: Server;- // deviceId -> socketId 映射+ // deviceId -> socketId mappingprivate deviceToSocket = new Map<string, string>();- // socketId -> deviceInfo 映射+ // socketId -> deviceInfo mappingprivate socketToDevice = new Map<string, DeviceInfo>();afterInit(_server: Server): void {@@ -72,7 +72,7 @@ export class EventsGatewayreturn;}- // 检查 deviceId 是否已被其他 socket 使用+ // Check if deviceId is already in use by another socketconst existingSocketId = this.deviceToSocket.get(deviceId);if (existingSocketId && existingSocketId !== client.id) {this.logger.warn(@@ -88,7 +88,7 @@ export class EventsGatewayreturn;}- // 注册设备+ // Register deviceconst deviceInfo: DeviceInfo = { deviceId, deviceType };this.deviceToSocket.set(deviceId, client.id);this.socketToDevice.set(client.id, deviceInfo);@@ -127,7 +127,7 @@ export class EventsGatewayconst senderDevice = this.socketToDevice.get(client.id);- // 检查发送者是否已注册+ // Check if sender is registeredif (!senderDevice) {const error: SendErrorResponse = {messageId: message.id,@@ -138,7 +138,7 @@ export class EventsGatewayreturn;}- // 检查消息 from 是否匹配+ // Check if message 'from' matchesif (message.from !== senderDevice.deviceId) {const error: SendErrorResponse = {messageId: message.id,@@ -149,7 +149,7 @@ export class EventsGatewayreturn;}- // 查找目标设备+ // Find target deviceconst targetSocketId = this.deviceToSocket.get(message.to);if (!targetSocketId) {const error: SendErrorResponse = {@@ -161,7 +161,7 @@ export class EventsGatewayreturn;}- // 转发消息+ // Forward messagethis.logger.debug({ messageId: message.id, from: message.from, to: message.to, action: message.action },"Routing message"@@ -178,17 +178,17 @@ export class EventsGatewayreturn { event: GatewayEvents.PONG, data: "Hello from Gateway!" };}- /** 获取所有在线设备(供 HTTP API 使用) */+ /** Get all online devices (for HTTP API use) */getOnlineDevices(): DeviceInfo[] {return Array.from(this.socketToDevice.values());}- /** 获取指定类型的在线设备 */+ /** Get online devices of specified type */getOnlineDevicesByType(type: "client" | "agent"): DeviceInfo[] {return this.getOnlineDevices().filter((d) => d.deviceType === type);}- /** 向指定设备发送消息(供 HTTP API 使用) */+ /** Send message to specified device (for HTTP API use) */sendToDevice(deviceId: string, event: string, data: unknown): boolean {const socketId = this.deviceToSocket.get(deviceId);if (!socketId) return false;diff --git a/src/hub/agent.ts b/src/hub/agent.tsindex f2cda83902..d25b83c554 100644--- a/src/hub/agent.ts+++ b/src/hub/agent.ts@@ -4,8 +4,8 @@ import { Channel } from "./channel.js";import type { Message } from "./types.js";/**- * Agent — 使用 pi-agent-core 进行真实推理。- * write() 触发一次模型运行,read() 输出流式结果。+ * Agent — uses pi-agent-core for real inference.+ * write() triggers a model run, read() outputs streaming results.*/export class Agent {readonly id: string;@@ -29,7 +29,7 @@ export class Agent {return this._closed;}- /** 写入消息到 agent(非阻塞,串行排队) */+ /** Write message to agent (non-blocking, serialized queue) */write(content: string): void {if (this._closed) {throw new Error("Agent is closed");@@ -51,12 +51,12 @@ export class Agent {});}- /** 持续读取消息流 */+ /** Continuously read message stream */read(): AsyncIterable<Message> {return this.channel;}- /** 关闭 agent,停止所有读取 */+ /** Close agent, stop all reads */close(): void {if (this._closed) return;this._closed = true;diff --git a/src/hub/channel.ts b/src/hub/channel.tsindex 266b2ba41d..5073c3cdcb 100644--- a/src/hub/channel.ts+++ b/src/hub/channel.ts@@ -1,6 +1,6 @@/**- * Go channel 风格的异步可迭代队列。- * 支持多 writer、单 reader,close 后结束迭代。+ * Go channel style async iterable queue.+ * Supports multiple writers, single reader, iteration ends after close.*/export class Channel<T> implements AsyncIterable<T> {private buffer: T[] = [];@@ -18,7 +18,7 @@ export class Channel<T> implements AsyncIterable<T> {return this.buffer.length;}- /** 发送值到 channel。channel 已关闭时返回 false。 */+ /** Send value to channel. Returns false when channel is closed. */send(value: T): boolean {if (this.closed) return false;@@ -32,7 +32,7 @@ export class Channel<T> implements AsyncIterable<T> {return true;}- /** 关闭 channel,唤醒所有等待中的 reader。 */+ /** Close channel, wake up all waiting readers. */close(): void {if (this.closed) return;this.closed = true;diff --git a/src/hub/hub.ts b/src/hub/hub.tsindex f34c593557..2d39b6f6bc 100644--- a/src/hub/hub.ts+++ b/src/hub/hub.ts@@ -12,7 +12,7 @@ export class Hub {readonly path: string;readonly deviceId: string;- /** 当前 Gateway 连接状态 */+ /** Current Gateway connection state */get connectionState(): ConnectionState {return this.client.state;}@@ -68,7 +68,7 @@ export class Hub {this.client.connect();}- /** 创建新 Agent,或用已有 ID 重建 */+ /** Create new Agent, or rebuild with existing ID */createAgent(id?: string): Agent {if (id) {const existing = this.agents.get(id);@@ -80,14 +80,14 @@ export class Hub {const agent = new Agent(id);this.agents.set(agent.id, agent);- // 内部消费 agent 产出的消息+ // Internally consume messages produced by agentvoid this.consumeAgent(agent);console.log(`Agent created: ${agent.id}`);return agent;}- /** 内部读取 agent 的输出并通过 Gateway 发送 */+ /** Internally read agent output and send via Gateway */private async consumeAgent(agent: Agent): Promise<void> {for await (const msg of agent.read()) {console.log(`[${agent.id}] ${msg.content}`);diff --git a/src/hub/types.ts b/src/hub/types.tsindex 780f660be8..8c73d8e38a 100644--- a/src/hub/types.ts+++ b/src/hub/types.ts@@ -4,8 +4,8 @@ export interface Message {}export interface HubOptions {- /** 远端 Gateway WebSocket 地址,如 "http://localhost:3000" */+ /** Remote Gateway WebSocket address, e.g. "http://localhost:3000" */url: string;- /** WebSocket 路径,默认 "/ws" */+ /** WebSocket path, defaults to "/ws" */path?: string | undefined;}diff --git a/src/shared/gateway-sdk/actions/hello.ts b/src/shared/gateway-sdk/actions/hello.tsindex 56b7950f76..36e56ba81e 100644--- a/src/shared/gateway-sdk/actions/hello.ts+++ b/src/shared/gateway-sdk/actions/hello.ts@@ -1,14 +1,14 @@-/** Hello Action - 测试用的问候消息 */+/** Hello Action - test greeting message */export const HelloAction = "hello" as const;export const HelloResponseAction = "hello_response" as const;-/** Hello 请求 payload */+/** Hello request payload */export interface HelloPayload {greeting: string;}-/** Hello 响应 payload */+/** Hello response payload */export interface HelloResponsePayload {reply: string;}diff --git a/src/shared/gateway-sdk/types.ts b/src/shared/gateway-sdk/types.tsindex 352e4060e7..9911c64ebc 100644--- a/src/shared/gateway-sdk/types.ts+++ b/src/shared/gateway-sdk/types.ts@@ -1,53 +1,53 @@-/** WebSocket 事件名称 */+/** WebSocket event names */export const GatewayEvents = {- // 系统事件+ // System eventsPING: "ping",PONG: "pong",REGISTERED: "registered",- // 消息路由+ // Message routingSEND: "send",RECEIVE: "receive",SEND_ERROR: "send_error",} as const;-// ============ 设备相关 ============+// ============ Device Related ============-/** 设备类型 */+/** Device type */export type DeviceType = "client" | "agent";-/** 设备信息 */+/** Device information */export interface DeviceInfo {deviceId: string;deviceType: DeviceType;}-/** 注册响应 */+/** Registration response */export interface RegisteredResponse {success: boolean;deviceId: string;error?: string;}-// ============ 消息路由 ============+// ============ Message Routing ============-/** 路由消息 */+/** Routed message */export interface RoutedMessage<T = unknown> {- /** 消息唯一ID (UUID v7,包含时间戳) */+ /** Unique message ID (UUID v7, contains timestamp) */id: string;- /** 用户ID(登录后填充) */+ /** User ID (populated after login) */uid: string | null;- /** 发送者 deviceId */+ /** Sender deviceId */from: string;- /** 接收者 deviceId */+ /** Recipient deviceId */to: string;- /** 动作类型 */+ /** Action type */action: string;- /** 消息内容 */+ /** Message payload */payload: T;}-/** 发送失败响应 */+/** Send failure response */export interface SendErrorResponse {messageId: string;error: string;@@ -56,43 +56,43 @@ export interface SendErrorResponse {// ============ Ping/Pong ============-/** Ping 请求 */+/** Ping request */export interface PingPayload {[key: string]: unknown;}-/** Ping 响应 */+/** Ping response */export interface PongResponse {event: string;data: string;}-// ============ 客户端配置 ============+// ============ Client Configuration ============-/** 连接配置 */+/** Connection configuration */export interface GatewayClientOptions {- /** 服务器地址,如 http://localhost:3000 */+ /** Server address, e.g. http://localhost:3000 */url: string;- /** WebSocket 路径,默认 /ws */+ /** WebSocket path, defaults to /ws */path?: string | undefined;- /** 设备ID */+ /** Device ID */deviceId: string;- /** 设备类型 */+ /** Device type */deviceType: DeviceType;- /** 自动重连,默认 true */+ /** Auto reconnect, defaults to true */autoReconnect?: boolean | undefined;- /** 重连延迟(毫秒),默认 1000 */+ /** Reconnect delay (milliseconds), defaults to 1000 */reconnectDelay?: number | undefined;}-/** 连接状态 */+/** Connection state */export type ConnectionState =| "disconnected"| "connecting"| "connected"| "registered";-/** 事件回调类型 */+/** Event callback types */export interface GatewayClientCallbacks {onConnect?: (socketId: string) => void;onDisconnect?: (reason: string) => void;