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.

♻️ refactor(creds): defer credential workflows until tool activation (#23464)

AmAzing-c0df2aef4ae9
diff --git a/apps/server/src/modules/AgentRuntime/adapters/__tests__/serverCallLlmTooling.test.ts b/apps/server/src/modules/AgentRuntime/adapters/__tests__/serverCallLlmTooling.test.ts
index fa465f408d5..1d43c2f9245 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/__tests__/serverCallLlmTooling.test.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/__tests__/serverCallLlmTooling.test.ts
@@ -1,4 +1,6 @@
import { type AgentState, normalizeAgentState } from '@lobechat/agent-runtime';
+import { LobeActivatorManifest } from '@lobechat/builtin-tool-activator';
+import { CredsIdentifier, CredsManifest } from '@lobechat/builtin-tool-creds';
import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';
import { describe, expect, it } from 'vitest';
@@ -30,6 +32,44 @@ const searchTool = {
} as unknown as NonNullable<AgentState['tools']>[number];
describe('resolveServerCallLlmTooling', () => {
+ it('offers credential discovery before activation and the credential workflow afterwards', () => {
+ const ctx = { operationId: 'op-1', stepIndex: 0 };
+ const state = buildState({
+ operationToolSet: {
+ enabledToolIds: [LobeActivatorManifest.identifier],
+ manifestMap: {
+ [LobeActivatorManifest.identifier]: LobeActivatorManifest,
+ [CredsIdentifier]: CredsManifest,
+ },
+ sourceMap: {},
+ tools: [],
+ },
+ });
+ const before = resolveServerCallLlmTooling(ctx, state);
+ const discovery = before.toolDiscoveryConfig?.availableTools.find(
+ (tool) => tool.identifier === CredsIdentifier,
+ );
+ expect(discovery?.description).toContain('API keys');
+ expect(before.resolved.promptManifestMap).not.toHaveProperty(CredsIdentifier);
+
+ const after = resolveServerCallLlmTooling(
+ { ...ctx, stepIndex: 1 },
+ {
+ ...state,
+ activatedStepTools: [
+ { activatedAtStep: 0, id: CredsIdentifier, manifest: CredsManifest, source: 'discovery' },
+ ],
+ },
+ );
+ for (const { name } of CredsManifest.api) {
+ expect(
+ before.resolved.promptManifestMap[LobeActivatorManifest.identifier].systemRole,
+ ).not.toContain(name);
+ expect(discovery?.description).not.toContain(name);
+ expect(after.resolved.promptManifestMap[CredsIdentifier].systemRole).toContain(name);
+ }
+ });
+
it.each([false, true])(
'limits tools after mid-run device selection to the operation pool (allowed=%s)',
(allowed) => {
diff --git a/apps/server/src/services/aiAgent/shareGate/README.md b/apps/server/src/services/aiAgent/shareGate/README.md
index 8c891d411e9..536e6b742cc 100644
--- a/apps/server/src/services/aiAgent/shareGate/README.md
+++ b/apps/server/src/services/aiAgent/shareGate/README.md
@@ -146,9 +146,9 @@ absence of a known exploit.
historical activations as already enabled (`shareGate/toolSet.ts:166`). A
kept activator gets the share-visitor `systemRole`
(`getSystemPromptForShareVisitor`), which omits the default prompt's push
- to activate `lobe-skill-store` / `lobe-creds` first (both stay denied
- above) and keeps its `activateSkill` lines only when `lobe-skills` itself
- survived the gate.
+ to activate `lobe-skill-store` first and keeps its `activateSkill` lines
+ only when `lobe-skills` itself survived the gate. Credential discovery
+ lives in the `lobe-creds` manifest, which the gate excludes.
1. What it can see. `<available_tools>` is the operation's `manifestMap`
minus enabled tools (`apps/server/src/modules/AgentRuntime/executorHelpers.ts:644`), and
diff --git a/packages/builtin-tool-activator/src/systemRole.ts b/packages/builtin-tool-activator/src/systemRole.ts
index 4067d0191ab..b0132279468 100644
--- a/packages/builtin-tool-activator/src/systemRole.ts
+++ b/packages/builtin-tool-activator/src/systemRole.ts
@@ -34,57 +34,9 @@ const skillStoreDiscovery = `<skill_store_discovery>
For marketplace skill searches, skill install requests (including SKILL.md, GitHub or LobeHub skill URLs), or a specialized task that needs a capability missing from the available tools and skills, use the Skill Store. If lobe-skill-store is in <available_tools>, activate it before browsing or trying a CLI. If already active, call it directly.
</skill_store_discovery>`;
-const credentialsManagement = `<credentials_management>
-**CRITICAL: Activate \`lobe-creds\` when ANY of the following conditions are met:**
-
-**Trigger conditions (MUST activate lobe-creds immediately):**
-- User needs to authenticate with a third-party service (OAuth, API keys, tokens)
-- User mentions: "API key", "access token", "credentials", "authenticate", "login to service"
-- Task requires environment variables (e.g., \`OPENAI_API_KEY\`, \`GITHUB_TOKEN\`)
-- User wants to store or manage sensitive information securely
-- Sandbox code execution requires credentials/secrets to be injected
-- User asks to connect to services like GitHub, Linear, Microsoft, Notion, Twitter, etc.
-- User wants to use, open, connect, or interact with a third-party integration service
- (e.g., Notion, Slack, Google Drive, Gmail, Airtable, Jira, Figma, HubSpot,
- Salesforce, Dropbox, ClickUp, Confluence, Supabase, WhatsApp, YouTube,
- Zendesk, Cal.com, OneDrive, Outlook Mail, Google Sheets, Google Docs)
-- User says things like "help me use Notion", "connect my Slack", "open Google Drive",
- "I want to use Jira", "set up Airtable" β€” these are third-party OAuth services
-
-**Decision flow:**
-1. **If ANY trigger condition above is met** β†’ Immediately activate \`lobe-creds\`
-2. Check if the required credential already exists using the credentials list in context
-3. If credential exists and the sandbox is reachable β†’ use \`injectCredsToSandbox\` (see \`<credential_usage_by_runtime>\` below)
-4. If credential doesn't exist:
- - For LobeHub OAuth services (GitHub, Linear, Microsoft, Notion, Twitter) β†’ use \`initiateOAuthConnect\`
- - For Composio-managed services (Slack, Google Drive, Airtable, Jira, etc.)
- β†’ use \`connectComposioService\` after activating \`lobe-creds\`. The full list of
- available Composio services is shown in \`<composio_integrations>\` inside the
- lobe-creds system prompt.
- - For API keys/tokens β†’ use \`requestCredsInput\` so the user enters them in a secure form
-5. For sandbox code that needs credentials β†’ use \`injectCredsToSandbox\` to inject them as environment variables
-
-**Important:**
-- Never ask users to paste API keys directly in chat β€” always use \`lobe-creds\` to store them securely
-
-<credential_usage_by_runtime>
-**Cloud sandbox reachable for credential injection: {{creds_sandbox_reachable}}.** This is about whether \`runCommand\`/\`execScript\` will actually execute in the cloud sandbox this run β€” not whether the dedicated Cloud Sandbox tool happens to be present, which can be \`true\` at the same time a device is also routed (auto mode).
-
-When \`{{creds_sandbox_reachable}}\` is \`true\`:
-- Use \`injectCredsToSandbox\` before running code that needs credentials. Injected credentials become automatically available as environment variables in every \`runCommand\`/\`execScript\` call β€” you do NOT need to \`source\` any file yourself. See the \`lobe-creds\` system prompt's \`<sandbox_integration>\` section for the full contract.
-
-When \`{{creds_sandbox_reachable}}\` is \`false\` (this run is routed to a device):
-- Do NOT call \`injectCredsToSandbox\` β€” it only writes into the cloud sandbox, and nothing in this run executes there.
-- There is currently no tool exposed to read a saved credential's plaintext value for inline use on a device-routed run. Tell the user this credential can't be used in this run rather than inventing a workaround.
-</credential_usage_by_runtime>
-</credentials_management>`;
-
-const bestPracticesCreds = `- **CREDS-FIRST: Any need for authentication, API keys, OAuth, tokens, or env variables β†’ activate \`lobe-creds\` FIRST to manage credentials securely.**
-`;
-
-const bestPractices = ({ withCreds }: { withCreds: boolean }) => `<best_practices>
+const bestPractices = `<best_practices>
- **IMPORTANT: Plan ahead and activate all needed tools upfront in a single call.** Before responding to the user, analyze their request and determine ALL tools you will need, then activate them together. Do NOT activate tools incrementally during a multi-step task.
-${withCreds ? bestPracticesCreds : ''}- Check the \`<available_tools>\` list before activating tools
+- Check the \`<available_tools>\` list before activating tools
- Only activate tools that are relevant to the user's current request
- After activation, use the tools' APIs directly β€” no need to call activateTools again for the same tools
</best_practices>`;
@@ -97,16 +49,12 @@ ${toolSelectionGuidelines({ withSkills: true })}
${skillStoreDiscovery}
-${credentialsManagement}
-
-${bestPractices({ withCreds: true })}
+${bestPractices}
`;
/**
- * Variant for Agent Share visitor runs. `lobe-skill-store` and `lobe-creds`
- * are never available to a visitor, so the sections that send the model to
- * activate them first would divert requests (skills, auth, GitHub/Notion…)
- * toward an impossible prerequisite instead of the granted tools. The
+ * Agent Share visitors cannot use the Skill Store. Keep discovery scoped to
+ * the granted tools and omit the marketplace instructions. The
* `activateSkill` lines are kept only when the share grants skills, since
* `lobe-skills` is otherwise absent from the visitor's tool set.
*/
@@ -116,5 +64,5 @@ ${howItWorks({ withSkills })}
${toolSelectionGuidelines({ withSkills })}
-${bestPractices({ withCreds: false })}
+${bestPractices}
`;
diff --git a/packages/builtin-tool-creds/src/manifest.ts b/packages/builtin-tool-creds/src/manifest.ts
index abcdc55b984..23ec51eca17 100644
--- a/packages/builtin-tool-creds/src/manifest.ts
+++ b/packages/builtin-tool-creds/src/manifest.ts
@@ -109,7 +109,7 @@ export const CredsManifest: BuiltinToolManifest = {
meta: {
avatar: 'πŸ”',
description:
- 'Manage user credentials for authentication, environment variable injection, and API verification. Use this tool when tasks require API keys, OAuth tokens, or secrets - such as calling third-party APIs, authenticating with external services, or injecting credentials into sandbox environments.',
+ 'Activate first to connect a third-party account, manage API keys or tokens, or run code that needs secrets. Collect secrets securely through this tool. Never ask users to paste them into chat.',
title: 'Credentials',
},
systemRole: systemPrompt,
diff --git a/packages/builtin-tool-creds/src/systemRole.ts b/packages/builtin-tool-creds/src/systemRole.ts
index e408cce6059..469cfcd99d1 100644
--- a/packages/builtin-tool-creds/src/systemRole.ts
+++ b/packages/builtin-tool-creds/src/systemRole.ts
@@ -19,7 +19,7 @@ Cloud sandbox reachable for credential injection: {{creds_sandbox_reachable}}
</credential_types>
<core_responsibilities>
-1. **Awareness**: Know what credentials the user has configured and suggest relevant ones when needed.
+1. **Check existing credentials**: Check the available credentials and connected integrations before requesting a new credential or starting an OAuth connection.
2. **Secure collection**: When a task needs a secret the user has not saved yet, use \`requestCredsInput\` so the user types it into a secure form. Never ask the user to paste a secret into the chat.
3. **Runtime Integration**: When the cloud sandbox is reachable (\`{{creds_sandbox_reachable}}\`), use \`injectCredsToSandbox\` to inject credentials into the sandbox environment before running code that needs them.
4. **Ownership disclosure**: In a workspace, some listed credentials are tagged \`[shared by <name>]\` (a teammate's own credential they chose to share) or \`[workspace credential]\` (owned by the workspace itself). Never present a shared credential as if it belongs to the workspace or to you β€” when it's relevant, tell the user whose credential is actually being used.
@@ -44,7 +44,7 @@ LobeHub provides built-in OAuth integrations for the following services:
- **notion**: Notion workspace and knowledge management. Connect to create pages, search content, update databases, and organize workspace knowledge.
- **twitter**: X (Twitter) social media. Connect to post tweets, manage timeline, engage with audience.
-When a user mentions they want to use one of these services, use \`initiateOAuthConnect\` to provide them with an authorization link. After they authorize, the credential will be automatically saved and available for use.
+When the user needs one of these services and its credential is missing, use \`initiateOAuthConnect\` to provide an authorization link. After authorization, the credential is saved for use.
</oauth_providers>
<security_guidelines>