π€― 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
π fix: refresh content baseline from DB on every ingest call (#14603)
LiJiancfe618fb50ba
diff --git a/src/server/services/aiAgent/index.ts b/src/server/services/aiAgent/index.tsindex 0aadc014504..60f968987b0 100644--- a/src/server/services/aiAgent/index.ts+++ b/src/server/services/aiAgent/index.ts@@ -684,23 +684,23 @@ export class AiAgentService {const topic = await this.topicModel.findById(topicId);const topicRepos: string[] = topic?.metadata?.repos ?? [];- // Resolve GitHub OAuth token so the sandbox can clone private repos.+ // Resolve GitHub OAuth token for the sandbox. Always attempt so CC can use+ // git / gh CLI even when no repos are pre-selected. Falls back to the+ // standard 'github' key (LobeHub OAuth connector default); agent config can+ // override via GITHUB_CRED_KEY.let githubToken: string | undefined;- if (topicRepos.length > 0) {- const githubCredKey = agentConfig.agencyConfig?.heterogeneousProvider?.env?.GITHUB_CRED_KEY;- if (githubCredKey) {- try {- const list = await this.marketService.market.creds.list();- const cred = list.data?.find((c: { key: string }) => c.key === githubCredKey);- if (cred) {- const full = await this.marketService.market.creds.get(cred.id, { decrypt: true });- const vals = (full as any).plaintext ?? (full as any).values ?? {};- githubToken = vals.access_token ?? vals.token;- }- } catch (err) {- log('execAgent: failed to resolve GitHub token for repo clone: %O', err);- }+ const githubCredKey =+ agentConfig.agencyConfig?.heterogeneousProvider?.env?.GITHUB_CRED_KEY ?? 'github';+ try {+ const list = await this.marketService.market.creds.list();+ const cred = list.data?.find((c: { key: string }) => c.key === githubCredKey);+ if (cred) {+ const full = await this.marketService.market.creds.get(cred.id, { decrypt: true });+ const vals = (full as any).plaintext ?? (full as any).values ?? {};+ githubToken = vals.access_token ?? vals.token;}+ } catch (err) {+ log('execAgent: failed to resolve GitHub token: %O', err);}// Build cloud-specific system context (repo list + workspace info + optional agent-level static context).diff --git a/src/server/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts b/src/server/services/heterogeneousAgent/HeterogeneousPersistenceHandler.tsindex 0582530b2b2..47a41d7d4ad 100644--- a/src/server/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts+++ b/src/server/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts@@ -239,6 +239,50 @@ export class HeterogeneousPersistenceHandler {}): Promise<void> {const state = await this.loadOrCreateState(params.operationId, params.topicId);+ // Refresh content/reasoning baseline from DB before processing this batch.+ //+ // Root cause of truncation: Vercel serverless routes consecutive batches to+ // different Lambda instances. A warm replica's in-memory `accumulatedContent`+ // reflects only the batches IT processed β it has no visibility into batches+ // handled by other replicas. When that warm replica later processes a+ // tools_calling event, `persistMainToolBatch` writes the stale short content+ // alongside the new tools, overwriting the correct (longer) DB value.+ //+ // Fix: re-read the current assistant message from DB at the start of every+ // ingest call. Since `flushBatchContent` always writes at the end of each+ // batch, DB is authoritative. Reading here gives us the freshest flushed+ // content as the new baseline, so any text accumulated in this batch extends+ // the correct full string rather than a stale partial.+ //+ // Cost: one extra `findById` round-trip per warm ingest call (cold calls+ // already read the message in `loadOrCreateState` β the second read is+ // redundant but harmless and keeps the logic uniform).+ const refreshed = await this.deps.messageModel.findById(state.currentAssistantMessageId);+ const dbContent = (refreshed?.content ?? '') as string;+ const dbReasoning = (refreshed?.reasoning as { content?: string } | null)?.content ?? '';++ // Adopt DB value only when it is LONGER than what this instance holds in memory.+ // This correctly handles two competing cases without introducing a dirty flag:+ //+ // 1. Multi-replica stale (the problem this refresh was added to fix):+ // Another replica flushed more content to DB than this warm instance+ // has in memory β dbContent is longer β adopt it so new text in this+ // batch extends the correct full string rather than a stale partial.+ //+ // 2. flushBatchContent retry on the same warm instance (P1 concern):+ // Events were already processed and marked in processedKeys, but the+ // end-of-batch flush threw a transient DB error. DB still holds the+ // shorter pre-batch value; in-memory already has the correct result.+ // Unconditionally overwriting with the DB value would wipe those+ // chunks permanently (processedKeys prevents replay). Taking the+ // longer in-memory value keeps them safe.+ if (dbContent.length > state.accumulatedContent.length) {+ state.accumulatedContent = dbContent;+ }+ if (dbReasoning.length > state.accumulatedReasoning.length) {+ state.accumulatedReasoning = dbReasoning;+ }+for (const event of params.events) {const key = eventKey(event);if (state.processedKeys.has(key)) {diff --git a/src/server/services/heterogeneousAgent/cloudHeteroContext.ts b/src/server/services/heterogeneousAgent/cloudHeteroContext.tsindex b88bf7196f4..c3b0f757de3 100644--- a/src/server/services/heterogeneousAgent/cloudHeteroContext.ts+++ b/src/server/services/heterogeneousAgent/cloudHeteroContext.ts@@ -38,12 +38,18 @@ export function buildCloudHeteroContext(params: {workspaceLines.push('','## GitHub Authentication',- 'A GitHub OAuth token is available as the `GITHUB_TOKEN` environment variable.',- 'Use it for:',- '- Authenticated git operations (`git clone`, `git push`, `git pull`, etc.)',- '- GitHub CLI: `gh` commands work out of the box',- '- GitHub API calls: pass it as `Authorization: Bearer $GITHUB_TOKEN`',- '- Accessing private repositories',+ 'GitHub credentials are pre-injected into this sandbox:',+ '',+ '- `GITHUB_TOKEN` env var is set β git and `gh` CLI pick it up automatically',+ '- `gh` CLI is pre-authenticated β all `gh` commands work out of the box',+ '- `~/.creds/env` contains `GITHUB_ACCESS_TOKEN` (same format as `injectCredsToSandbox`)',+ ' β source it in sub-shells or scripts that need an explicit token:',+ ' ```bash',+ ' source ~/.creds/env',+ ' echo $GITHUB_ACCESS_TOKEN | gh auth login --hostname github.com --with-token',+ ' ```',+ '',+ 'You can use `git push`, `git pull`, `gh pr create`, `gh issue list`, GitHub API calls, etc. directly.',);}diff --git a/src/server/services/heterogeneousAgent/sandboxRunner.ts b/src/server/services/heterogeneousAgent/sandboxRunner.tsindex b9d7b585546..340a40baa64 100644--- a/src/server/services/heterogeneousAgent/sandboxRunner.ts+++ b/src/server/services/heterogeneousAgent/sandboxRunner.ts@@ -38,6 +38,32 @@ function repoToLocalDir(repo: string): string {return raw.replaceAll(/[^\w.-]/g, '');}+/**+ * Write GitHub credentials into the sandbox in the same format produced by+ * `injectCredsToSandbox(["github"])` so CC can source them from sub-shells:+ *+ * source ~/.creds/env # exports GITHUB_ACCESS_TOKEN+ * echo $GITHUB_ACCESS_TOKEN | gh auth login --hostname github.com --with-token+ *+ * Also authenticates the `gh` CLI upfront so all `gh` commands work out of+ * the box without CC having to call inject first.+ *+ * Returns null when no token is available.+ */+function buildCredsSetupScript(githubToken?: string): string | null {+ if (!githubToken) return null;+ const tokenJson = JSON.stringify(githubToken);+ return [+ 'mkdir -p ~/.creds',+ // Write GITHUB_ACCESS_TOKEN matching the injectCredsToSandbox oauth naming scheme+ `printf 'GITHUB_ACCESS_TOKEN=%s\\n' ${tokenJson} > ~/.creds/env`,+ // Pre-authenticate gh CLI so CC can use it immediately (gh also picks up+ // GITHUB_TOKEN from env, but explicit login ensures ~/.config/gh/hosts.yml+ // is populated for cases where env is reset in a sub-shell)+ `echo ${tokenJson} | gh auth login --hostname github.com --with-token 2>/dev/null || true`,+ ].join(' && \\\n');+}+/*** Build an idempotent setup script that clones each repo if not already present.* Uses `[ -d <dir> ] || git clone ...` so re-runs on the same sandbox are no-ops.@@ -145,8 +171,12 @@ export async function spawnHeteroSandbox(params: SandboxRunParams): Promise<void...(githubToken ? [`GITHUB_TOKEN=${JSON.stringify(githubToken)}`] : []),].join(' ');const mainCommand = `echo ${base64Payload} | base64 -d | ${envVars} ${args.join(' ')}`;- const setupScript = buildRepoSetupScript(repos ?? [], githubToken);- const shellCommand = setupScript ? `${setupScript} && \\\n${mainCommand}` : mainCommand;+ // Creds first (writes ~/.creds/env + authenticates gh CLI), then repo clone.+ const credsScript = buildCredsSetupScript(githubToken);+ const repoScript = buildRepoSetupScript(repos ?? [], githubToken);+ const setupParts = [credsScript, repoScript].filter(Boolean);+ const shellCommand =+ setupParts.length > 0 ? `${setupParts.join(' && \\\n')} && \\\n${mainCommand}` : mainCommand;log('spawnHeteroSandbox: userId=%s op=%s type=%s topic=%s',