🤯 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
✨ feat(creds): collect credentials through a secure form (#20469)
Neko7a0c250bd47f
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.tsindex cf809396d40..5b9435a6e53 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts@@ -1431,7 +1431,7 @@ describe('AgentRuntimeService', () => {};it('drops the snapshot in the state it persists after the run saves a credential', async () => {- const persistedState = await runStepWithToolCall('saveCreds');+ const persistedState = await runStepWithToolCall('requestCredsInput');expect(persistedState.operationCredentials).toBeUndefined();});diff --git a/apps/server/src/services/agentRuntime/__tests__/agentInterventionNotification.test.ts b/apps/server/src/services/agentRuntime/__tests__/agentInterventionNotification.test.tsindex b5323f55bae..5603cd945e7 100644--- a/apps/server/src/services/agentRuntime/__tests__/agentInterventionNotification.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/agentInterventionNotification.test.ts@@ -233,6 +233,34 @@ describe('buildRuntimeInterventionNotification', () => {expect(result?.systemActionEligibility).toBe('review_only');});+ it('lets only the card resolve the secure credential form', async () => {+ const credsForm = {+ apiName: 'requestCredsInput',+ arguments: '{"key":"openai","name":"OpenAI","type":"kv-env","fieldNames":["OPENAI_API_KEY"]}',+ id: 'call-creds',+ identifier: 'lobe-creds',+ type: 'builtin' as const,+ };+ const result = await buildRuntimeInterventionNotification({+ operationId: 'operation-1',+ state: buildState({+ pendingToolMessageIds: { 'call-creds': 'tool-creds' },+ pendingToolsCalling: [credsForm],+ toolManifestMap: {+ 'lobe-creds': { api: [{ name: 'requestCredsInput' }], identifier: 'lobe-creds' },+ },+ }),+ userId: 'user-1',+ });++ expect(result?.items[0]).toMatchObject({+ allowedActions: ['approve_tool', 'reject_continue', 'stop'],+ interactionKind: 'tool_approval',+ surface: 'form',+ });+ expect(result?.systemActionEligibility).toBe('review_only');+ });+it('emits an exact old-batch supersession for a partially resolved re-park', async () => {const result = await buildRuntimeInterventionNotification({operationId: 'operation-2',diff --git a/apps/server/src/services/agentRuntime/agentInterventionNotification.ts b/apps/server/src/services/agentRuntime/agentInterventionNotification.tsindex 5cab53bd428..fd592eed914 100644--- a/apps/server/src/services/agentRuntime/agentInterventionNotification.ts+++ b/apps/server/src/services/agentRuntime/agentInterventionNotification.ts@@ -155,6 +155,13 @@ const actionsFor = (];}+ if (interactionKind === 'tool_approval') {+ // A form resolved by approval (the secure credential form): the card+ // approves after its own write, so there are no arguments to edit and no+ // allow-list entry to remember.+ return ['approve_tool', 'reject_continue', 'stop'];+ }+if (interactionKind === 'question') {// Standard runtime AskUser has Submit / Skip semantics. Cancel is a// provider/custom terminal action and has no runtime handler here.diff --git a/apps/server/src/services/agentRuntime/credentialFacts.test.ts b/apps/server/src/services/agentRuntime/credentialFacts.test.tsindex b542080427c..21ef41aa10b 100644--- a/apps/server/src/services/agentRuntime/credentialFacts.test.ts+++ b/apps/server/src/services/agentRuntime/credentialFacts.test.ts@@ -18,7 +18,7 @@ describe('stepChangedCredentials', () => {expect(stepChangedCredentials({ payload: { message: 'hi' }, phase: 'user_input' })).toBe(false);});- it.each(['saveCreds', 'initiateOAuthConnect', 'connectComposioService'])(+ it.each(['requestCredsInput', 'initiateOAuthConnect', 'connectComposioService'])('is true after %s',(apiName) => {expect(stepChangedCredentials(singleCall('lobe-creds', apiName))).toBe(true);@@ -30,7 +30,9 @@ describe('stepChangedCredentials', () => {});it('is false for another tool that happens to share an api name', () => {- expect(stepChangedCredentials(singleCall('lobe-web-browsing', 'saveCreds'))).toBe(false);+ expect(stepChangedCredentials(singleCall('lobe-web-browsing', 'requestCredsInput'))).toBe(+ false,+ );});it.each(['lobe-agent', 'lobe-group-management'])(@@ -45,7 +47,7 @@ describe('stepChangedCredentials', () => {stepChangedCredentials(batch([{ apiName: 'injectCredsToSandbox', identifier: 'lobe-creds' },- { apiName: 'saveCreds', identifier: 'lobe-creds' },+ { apiName: 'requestCredsInput', identifier: 'lobe-creds' },]),),).toBe(true);diff --git a/apps/server/src/services/agentRuntime/credentialFacts.ts b/apps/server/src/services/agentRuntime/credentialFacts.tsindex 70bdb0a3eb2..47436d2ec3c 100644--- a/apps/server/src/services/agentRuntime/credentialFacts.ts+++ b/apps/server/src/services/agentRuntime/credentialFacts.ts@@ -10,7 +10,7 @@ import { LobeAgentIdentifier } from '@lobechat/builtin-tool-lobe-agent';const MUTATING_API_NAMES = new Set<string>([CredsApiName.connectComposioService,CredsApiName.initiateOAuthConnect,- CredsApiName.saveCreds,+ CredsApiName.requestCredsInput,]);/**diff --git a/apps/server/src/services/toolExecution/serverRuntimes/creds.ts b/apps/server/src/services/toolExecution/serverRuntimes/creds.tsindex 6010cc16c99..1095c629c12 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/creds.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/creds.ts@@ -171,22 +171,6 @@ export class ServerCredsService implements ICredsService {return result as any;}-- async saveKVCred(params: {- description?: string;- key: string;- name: string;- type: 'kv-env' | 'kv-header';- values: Record<string, string>;- }): Promise<{ id: number }> {- log('saveKVCred: key=%s, name=%s, type=%s', params.key, params.name, params.type);-- const result = await this.credsAccessor().createKV(params);-- log('saveKVCred success: id=%d', result.id);-- return result;- }}/**diff --git a/locales/en-US/tool.json b/locales/en-US/tool.jsonindex 5f7e4c74eb0..d1514ad3984 100644--- a/locales/en-US/tool.json+++ b/locales/en-US/tool.json@@ -85,6 +85,19 @@"connector.deleteAgentConfirmContent": "This connector belongs to the agent “{{agent}}”. Deleting it will also remove this tool from that agent.","connector.manageOnlyCreator": "Only the creator or a workspace owner can manage this connector","connector.thisAgent": "this agent",+ "credsInput.approveFailed": "The credential was saved, but the conversation couldn't continue. Please try again.",+ "credsInput.notice.lookupFailed": "Couldn't check whether this credential already exists, so it can't be saved safely right now. Skip, or try again later.",+ "credsInput.notice.noPermission": "Only workspace admins can save workspace credentials. Skip this request, or ask an admin to add the credential in the workspace settings.",+ "credsInput.notice.overwrite": "A credential with key “{{key}}” already exists. Saving will replace its values.",+ "credsInput.notice.personal": "Saved encrypted to your personal credentials. The values go directly to storage and are never shown to the AI.",+ "credsInput.notice.typeMismatch": "A credential with key “{{key}}” already exists with a different type ({{type}}) and can't be replaced from here. Skip, and ask for it under a different key.",+ "credsInput.notice.workspace": "Saved encrypted to this workspace's credentials. The values go directly to storage and are never shown to the AI.",+ "credsInput.placeholder": "Enter {{field}}",+ "credsInput.saveFailed": "Couldn't save the credential. Please try again.",+ "credsInput.skip": "Skip",+ "credsInput.submit": "Save",+ "credsInput.submitting": "Saving…",+ "credsInput.update": "Update","dalle.autoGenerate": "Auto Generate","dalle.downloading": "The image links generated by DALL·E3 are only valid for 1 hour, caching the images locally...","dalle.generate": "Generate",diff --git a/locales/zh-CN/tool.json b/locales/zh-CN/tool.jsonindex ef92d48905c..4c733bd181b 100644--- a/locales/zh-CN/tool.json+++ b/locales/zh-CN/tool.json@@ -85,6 +85,19 @@"connector.deleteAgentConfirmContent": "该连接器归属于助理「{{agent}}」。删除它会同时把这个工具从该助理中移除。","connector.manageOnlyCreator": "仅创建者或工作区 Owner 可以管理此连接器","connector.thisAgent": "该助理",+ "credsInput.approveFailed": "凭据已保存,但对话没能继续。请重试。",+ "credsInput.notice.lookupFailed": "无法确认这个凭据是否已存在,暂时不能安全保存。你可以跳过,或稍后再试。",+ "credsInput.notice.noPermission": "只有工作区管理员可以保存工作区凭据。你可以跳过,或请管理员在工作区设置中添加这个凭据。",+ "credsInput.notice.overwrite": "已存在 key 为「{{key}}」的凭证,保存后将替换其中的值。",+ "credsInput.notice.personal": "将加密保存到你的个人凭证。输入的值直接写入存储,AI 无法看到。",+ "credsInput.notice.typeMismatch": "已存在 key 为「{{key}}」的凭据,但类型不同({{type}}),不能在这里替换。请跳过,并改用其他 key。",+ "credsInput.notice.workspace": "将加密保存到当前工作区的凭证。输入的值直接写入存储,AI 无法看到。",+ "credsInput.placeholder": "输入 {{field}}",+ "credsInput.saveFailed": "凭证保存失败,请重试。",+ "credsInput.skip": "跳过",+ "credsInput.submit": "保存",+ "credsInput.submitting": "保存中…",+ "credsInput.update": "更新","dalle.autoGenerate": "自动生成","dalle.downloading": "DALL·E3 生成的图片链接仅在 1 小时内有效,正在本地缓存图片...","dalle.generate": "生成",diff --git a/packages/builtin-tool-activator/src/systemRole.ts b/packages/builtin-tool-activator/src/systemRole.tsindex ada746958f4..2f439e043ab 100644--- a/packages/builtin-tool-activator/src/systemRole.ts+++ b/packages/builtin-tool-activator/src/systemRole.ts@@ -89,7 +89,7 @@ export const systemPrompt = `You have access to a Tools Activator that allows yo→ use \`connectComposioService\` after activating \`lobe-creds\`. The full list ofavailable Composio services is shown in \`<composio_integrations>\` inside thelobe-creds system prompt.- - For API keys/tokens → guide user to save with \`saveCreds\`+ - For API keys/tokens → use \`requestCredsInput\` so the user enters them in a secure form5. For sandbox code that needs credentials → use \`injectCredsToSandbox\` to inject them as environment variables**Important:**diff --git a/packages/builtin-tool-creds/package.json b/packages/builtin-tool-creds/package.jsonindex 40b113b086e..5d8fb2914bc 100644--- a/packages/builtin-tool-creds/package.json+++ b/packages/builtin-tool-creds/package.json@@ -10,8 +10,14 @@"./executor": "./src/executor/index.ts"},"main": "./src/index.ts",- "dependencies": {},+ "dependencies": {+ "@lobechat/shared-tool-ui": "workspace:*"+ },"devDependencies": {"@lobechat/types": "workspace:*"+ },+ "peerDependencies": {+ "@lobehub/ui": "^5",+ "react": "^19"}}diff --git a/packages/builtin-tool-creds/src/ExecutionRuntime/index.ts b/packages/builtin-tool-creds/src/ExecutionRuntime/index.tsindex dbbdef3415d..2900e52224c 100644--- a/packages/builtin-tool-creds/src/ExecutionRuntime/index.ts+++ b/packages/builtin-tool-creds/src/ExecutionRuntime/index.ts@@ -5,11 +5,12 @@ import {} from '@lobechat/const';import type { BuiltinServerRuntimeOutput } from '@lobechat/types';+import { buildRequestCredsInputResult } from '../requestCredsInput';import type {ConnectComposioServiceParams,InitiateOAuthConnectParams,InjectCredsToSandboxParams,- SaveCredsParams,+ RequestCredsInputParams,} from '../types';import { LOBEHUB_OAUTH_PROVIDER_LIST } from '../types';@@ -59,17 +60,6 @@ export interface ICredsService {listCreds: () => Promise<{data?: Array<{ id: number; key: string }>;}>;-- /**- * Save KV credential- */- saveKVCred: (params: {- description?: string;- key: string;- name: string;- type: 'kv-env' | 'kv-header';- values: Record<string, string>;- }) => Promise<{ id: number }>;}/**@@ -278,46 +268,20 @@ export class CredsExecutionRuntime {}/**- * Save new credentials+ * Runs after the user approves the secure form. The form already wrote the+ * values to the credential store, so this only confirms the key exists and+ * reports it — the values never pass through the agent run.*/- async saveCreds(args: SaveCredsParams): Promise<BuiltinServerRuntimeOutput> {+ async requestCredsInput(args: RequestCredsInputParams): Promise<BuiltinServerRuntimeOutput> {try {- // Only support kv-env and kv-header types in server runtime- // File upload requires frontend interaction- if (args.type !== 'kv-env' && args.type !== 'kv-header') {- return {- content: `Credential type "${args.type}" is not supported in background execution. Only kv-env and kv-header types are supported.`,- error: {- message: `Unsupported credential type: ${args.type}`,- type: 'UnsupportedCredentialType',- },- success: false,- };- }-- await this.credsService.saveKVCred({- description: args.description,- key: args.key,- name: args.name,- type: args.type,- values: args.values,- });-- return {- content: `Credential "${args.name}" saved successfully with key "${args.key}"`,- state: {- key: args.key,- message: `Credential "${args.name}" saved successfully`,- success: true,- },- success: true,- };+ const { data } = await this.credsService.listCreds();+ return buildRequestCredsInputResult(args, !!data?.some((cred) => cred.key === args.key));} catch (error) {return {- content: `Failed to save credential: ${error instanceof Error ? error.message : 'Unknown error'}`,+ content: `Failed to check credential "${args.key}": ${error instanceof Error ? error.message : 'Unknown error'}`,error: {- message: error instanceof Error ? error.message : 'Failed to save credential',- type: 'SaveCredentialFailed',+ message: error instanceof Error ? error.message : 'Failed to check credential',+ type: 'CheckCredentialFailed',},success: false,};diff --git a/packages/builtin-tool-creds/src/client/Intervention/RequestCredsInput/index.tsx b/packages/builtin-tool-creds/src/client/Intervention/RequestCredsInput/index.tsxnew file mode 100644index 00000000000..cde60d0a722--- /dev/null+++ b/packages/builtin-tool-creds/src/client/Intervention/RequestCredsInput/index.tsx@@ -0,0 +1,178 @@+'use client';++import { SecretInputView } from '@lobechat/shared-tool-ui/secret-input';+import type { BuiltinInterventionProps } from '@lobechat/types';+import { Flexbox } from '@lobehub/ui';+import { Tag, Text } from '@lobehub/ui/base-ui';+import { memo, useCallback, useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';+import { usePermission } from '@/hooks/usePermission';+import { useClientDataSWR } from '@/libs/swr';+import { lambdaClient } from '@/libs/trpc/client';++import type { RequestCredsInputParams } from '../../../types';+import {+ canSaveCredsInput,+ createCredsInputSubmit,+ type CredsWriteClient,+ findWritableCred,+ isCredTypeMismatch,+ saveCredsInput,+} from './saveCredsInput';++/**+ * Same scope the server runtime uses (`credsAccessor`): inside a workspace the+ * agent's credentials are the workspace organization's, otherwise the user's.+ * `workspaceCreds` mirrors `market.creds` but is registered in the cloud+ * namespace, so it is cast at the boundary like the workspace settings page.+ */+const useScopedCredsClient = () => {+ const workspaceId = useActiveWorkspaceId();+ return useMemo(+ () => ({+ client: (workspaceId+ ? lambdaClient.workspaceCreds+ : lambdaClient.market.creds) as unknown as CredsWriteClient,+ isWorkspace: !!workspaceId,+ }),+ [workspaceId],+ );+};++/**+ * Secure form for `lobe-creds/requestCredsInput`.+ *+ * The plaintext goes from the form straight to the credential store. Only then+ * does the card approve the tool call, with no payload: the host maps submit+ * to the ordinary approve action, and the tool itself just confirms the key+ * exists. Skipping rejects the call so the agent can continue without it.+ */+const RequestCredsInputIntervention = memo<BuiltinInterventionProps<RequestCredsInputParams>>(+ ({ actionsPortalTarget, args, disabled, interactionMode, onInteractionAction }) => {+ const { t } = useTranslation('tool');+ const { client, isWorkspace } = useScopedCredsClient();+ const { allowed: canManageWorkspaceCreds } = usePermission('manage_provider_key');+ const canSave = canSaveCredsInput({ canManageWorkspaceCreds, isWorkspace });+ const [error, setError] = useState<string>();++ const fieldNames = useMemo(+ () => (Array.isArray(args?.fieldNames) ? args.fieldNames.filter(Boolean) : []),+ [args?.fieldNames],+ );+ const name = args?.name || args?.key;+ const isInteractive = interactionMode === 'custom';++ // Only metadata (id / key / owner / type) — list responses never carry values.+ const {+ data: existing,+ error: lookupError,+ isLoading: lookingUp,+ } = useClientDataSWR(+ isInteractive && canSave && args?.key+ ? ['requestCredsInput:existing', args.key, isWorkspace]+ : null,+ () => findWritableCred(client, args.key, isWorkspace),+ );++ // One instance per card, so a retry after a failed approval does not write+ // the secret again. Errors are shown as fixed copy, never the raw message.+ const submit = useMemo(+ () =>+ createCredsInputSubmit({+ approve: async () => {+ await onInteractionAction?.({ payload: {}, type: 'submit' });+ },+ onError: (stage) =>+ setError(t(stage === 'save' ? 'credsInput.saveFailed' : 'credsInput.approveFailed')),+ save: (values) => saveCredsInput(client, args, isWorkspace, values),+ }),+ [args, client, isWorkspace, onInteractionAction, t],+ );++ const handleSubmit = useCallback(+ async (values: Record<string, string>) => {+ setError(undefined);+ await submit(values);+ },+ [submit],+ );++ const typeMismatch = isCredTypeMismatch(existing, args?.type);++ // Submitting before the existing-key lookup settles would overwrite a+ // credential without the Update label or the overwrite warning.+ let blockedReason: string | undefined;+ if (!canSave) blockedReason = t('credsInput.notice.noPermission');+ else if (lookupError) blockedReason = t('credsInput.notice.lookupFailed');+ else if (typeMismatch)+ blockedReason = t('credsInput.notice.typeMismatch', { key: args.key, type: existing?.type });++ const handleCancel = useCallback(() => {+ let reason = 'The user chose not to enter this credential.';+ if (!canSave)+ reason =+ 'The user cannot save workspace credentials: only workspace admins can. A workspace admin needs to add this credential in the workspace settings.';+ else if (typeMismatch)+ reason = `A credential with key "${args.key}" already exists with a different type (${existing?.type}). Request it again under a different key.`;+ void onInteractionAction?.({ reason, type: 'skip' });+ }, [args?.key, canSave, existing?.type, onInteractionAction, typeMismatch]);++ const header = (+ <Flexbox gap={4}>+ <Flexbox horizontal align={'center'} gap={8}>+ <Text strong>{name}</Text>+ <Tag>{args?.key}</Tag>+ </Flexbox>+ {args?.description && <Text type={'secondary'}>{args.description}</Text>}+ </Flexbox>+ );++ if (!isInteractive) {+ return (+ <Flexbox gap={8}>+ {header}+ <Text fontSize={12} type={'secondary'}>+ {fieldNames.join(', ')}+ </Text>+ </Flexbox>+ );+ }++ return (+ <SecretInputView+ actionsPortalTarget={actionsPortalTarget}+ blockedReason={blockedReason}+ disabled={disabled || lookingUp}+ error={error}+ fields={fieldNames}+ labels={{+ cancel: t('credsInput.skip'),+ placeholder: (field) => t('credsInput.placeholder', { field }),+ submit: t(existing ? 'credsInput.update' : 'credsInput.submit'),+ submitting: t('credsInput.submitting'),+ }}+ notice={+ <Flexbox gap={8}>+ {header}+ <Text fontSize={12} type={'secondary'}>+ {t(isWorkspace ? 'credsInput.notice.workspace' : 'credsInput.notice.personal')}+ </Text>+ {existing && !typeMismatch && (+ <Text fontSize={12} type={'warning'}>+ {t('credsInput.notice.overwrite', { key: args.key })}+ </Text>+ )}+ </Flexbox>+ }+ onCancel={handleCancel}+ onSubmit={handleSubmit}+ />+ );+ },+);++RequestCredsInputIntervention.displayName = 'RequestCredsInputIntervention';++export default RequestCredsInputIntervention;diff --git a/packages/builtin-tool-creds/src/client/Intervention/RequestCredsInput/saveCredsInput.test.ts b/packages/builtin-tool-creds/src/client/Intervention/RequestCredsInput/saveCredsInput.test.tsnew file mode 100644index 00000000000..a41d257bb4c--- /dev/null+++ b/packages/builtin-tool-creds/src/client/Intervention/RequestCredsInput/saveCredsInput.test.ts@@ -0,0 +1,177 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import {+ canSaveCredsInput,+ createCredsInputSubmit,+ type CredsWriteClient,+ CredTypeMismatchError,+ isCredTypeMismatch,+ saveCredsInput,+} from './saveCredsInput';++const values = { OPENAI_API_KEY: 'sk-test-secret-value' };++const args = {+ fieldNames: ['OPENAI_API_KEY'],+ key: 'openai',+ name: 'OpenAI API Key',+ type: 'kv-env' as const,+};++const createClient = (+ rows: Array<{ id: number; key: string; ownerType?: string; type?: string }>,+) => ({+ createKV: { mutate: vi.fn().mockResolvedValue({ id: 1 }) },+ list: { query: vi.fn().mockResolvedValue({ data: rows }) },+ update: { mutate: vi.fn().mockResolvedValue({}) },+});++describe('saveCredsInput', () => {+ let client: ReturnType<typeof createClient>;++ beforeEach(() => {+ client = createClient([]);+ });++ it('creates a credential when the key is new', async () => {+ await saveCredsInput(client as CredsWriteClient, args, false, values);++ expect(client.createKV.mutate).toHaveBeenCalledWith({+ description: undefined,+ key: 'openai',+ name: 'OpenAI API Key',+ type: 'kv-env',+ values,+ });+ expect(client.update.mutate).not.toHaveBeenCalled();+ });++ it('overwrites the credential that already uses the key', async () => {+ client = createClient([{ id: 7, key: 'openai' }]);++ await saveCredsInput(client as CredsWriteClient, args, false, values);++ expect(client.update.mutate).toHaveBeenCalledWith({+ description: undefined,+ id: 7,+ name: 'OpenAI API Key',+ values,+ });+ expect(client.createKV.mutate).not.toHaveBeenCalled();+ });++ it('never overwrites a member’s shared credential from the workspace scope', async () => {+ client = createClient([{ id: 9, key: 'openai', ownerType: 'user' }]);++ await saveCredsInput(client as CredsWriteClient, args, true, values);++ expect(client.update.mutate).not.toHaveBeenCalled();+ expect(client.createKV.mutate).toHaveBeenCalledTimes(1);+ });++ it('overwrites the workspace’s own credential with the key', async () => {+ client = createClient([{ id: 3, key: 'openai', ownerType: 'organization' }]);++ await saveCredsInput(client as CredsWriteClient, args, true, values);++ expect(client.update.mutate).toHaveBeenCalledWith(expect.objectContaining({ id: 3 }));+ });++ it('propagates store failures so the form stays open', async () => {+ client.createKV.mutate.mockRejectedValue(new Error('Failed to create KV credential'));++ await expect(saveCredsInput(client as CredsWriteClient, args, false, values)).rejects.toThrow();+ });+});++describe('canSaveCredsInput', () => {+ it('always allows personal credentials', () => {+ expect(canSaveCredsInput({ canManageWorkspaceCreds: false, isWorkspace: false })).toBe(true);+ });++ it('requires the credential-management permission inside a workspace', () => {+ expect(canSaveCredsInput({ canManageWorkspaceCreds: true, isWorkspace: true })).toBe(true);+ expect(canSaveCredsInput({ canManageWorkspaceCreds: false, isWorkspace: true })).toBe(false);+ });+});++describe('createCredsInputSubmit', () => {+ it('saves, then approves', async () => {+ const save = vi.fn().mockResolvedValue(undefined);+ const approve = vi.fn().mockResolvedValue(undefined);+ const onError = vi.fn();++ await createCredsInputSubmit({ approve, onError, save })(values);++ expect(save).toHaveBeenCalledWith(values);+ expect(approve).toHaveBeenCalledTimes(1);+ expect(onError).not.toHaveBeenCalled();+ });++ it('does not approve when the save fails', async () => {+ const save = vi.fn().mockRejectedValue(new Error('store unavailable'));+ const approve = vi.fn();+ const onError = vi.fn();++ await expect(createCredsInputSubmit({ approve, onError, save })(values)).rejects.toThrow();++ expect(onError).toHaveBeenCalledWith('save');+ expect(approve).not.toHaveBeenCalled();+ });++ it('reports a failed approval and retries it without writing the secret again', async () => {+ const save = vi.fn().mockResolvedValue(undefined);+ const approve = vi+ .fn()+ .mockRejectedValueOnce(new Error('resume failed'))+ .mockResolvedValueOnce(undefined);+ const onError = vi.fn();+ const submit = createCredsInputSubmit({ approve, onError, save });++ await expect(submit(values)).rejects.toThrow();+ expect(onError).toHaveBeenCalledWith('approve');++ await submit(values);++ expect(save).toHaveBeenCalledTimes(1);+ expect(approve).toHaveBeenCalledTimes(2);+ });++ it('writes edited values before retrying a failed approval', async () => {+ const save = vi.fn().mockResolvedValue(undefined);+ const approve = vi+ .fn()+ .mockRejectedValueOnce(new Error('resume failed'))+ .mockResolvedValueOnce(undefined);+ const submit = createCredsInputSubmit({ approve, onError: vi.fn(), save });++ await expect(submit(values)).rejects.toThrow();++ const edited = { OPENAI_API_KEY: 'sk-test-edited-value' };+ await submit(edited);++ expect(save).toHaveBeenCalledTimes(2);+ expect(save).toHaveBeenLastCalledWith(edited);+ expect(approve).toHaveBeenCalledTimes(2);+ });+});++describe('credential type mismatch', () => {+ it('detects an existing credential of another type', () => {+ expect(isCredTypeMismatch(undefined, 'kv-env')).toBe(false);+ expect(isCredTypeMismatch({ type: 'kv-env' }, 'kv-env')).toBe(false);+ expect(isCredTypeMismatch({ type: 'kv-header' }, 'kv-env')).toBe(true);+ expect(isCredTypeMismatch({ type: 'oauth' }, 'kv-env')).toBe(true);+ });++ it('refuses to overwrite a credential of another type', async () => {+ const client = createClient([{ id: 7, key: 'openai', type: 'kv-header' }]);++ await expect(+ saveCredsInput(client as CredsWriteClient, args, false, values),+ ).rejects.toBeInstanceOf(CredTypeMismatchError);++ expect(client.update.mutate).not.toHaveBeenCalled();+ expect(client.createKV.mutate).not.toHaveBeenCalled();+ });+});diff --git a/packages/builtin-tool-creds/src/client/Intervention/RequestCredsInput/saveCredsInput.ts b/packages/builtin-tool-creds/src/client/Intervention/RequestCredsInput/saveCredsInput.tsnew file mode 100644index 00000000000..3a855008719--- /dev/null+++ b/packages/builtin-tool-creds/src/client/Intervention/RequestCredsInput/saveCredsInput.ts@@ -0,0 +1,155 @@+import type { RequestCredsInputParams } from '../../../types';++/**+ * The slice of the `market.creds` / `workspaceCreds` tRPC clients the secure+ * form writes through. Structural so the logic stays testable without the app.+ */+export interface CredsWriteClient {+ createKV: {+ mutate: (input: {+ description?: string;+ key: string;+ name: string;+ type: 'kv-env' | 'kv-header';+ values: Record<string, string>;+ }) => Promise<unknown>;+ };+ list: {+ query: () => Promise<{+ data?: Array<{ id: number; key: string; ownerType?: string; type?: string }>;+ }>;+ };+ update: {+ mutate: (input: {+ description?: string;+ id: number;+ name?: string;+ values?: Record<string, string>;+ }) => Promise<unknown>;+ };+}++/**+ * Whether the user can save into the scope the agent reads. Personal+ * credentials are always the user's own; workspace credentials need the+ * workspace's credential-management permission, so a member without it gets+ * an explanation instead of a form whose every save would be refused.+ * Falling back to personal credentials would not help: inside a workspace the+ * agent only reads the workspace's credentials.+ */+export const canSaveCredsInput = ({+ canManageWorkspaceCreds,+ isWorkspace,+}: {+ canManageWorkspaceCreds: boolean;+ isWorkspace: boolean;+}) => !isWorkspace || canManageWorkspaceCreds;++/**+ * Finds a credential the scoped API can overwrite. A workspace list also holds+ * members' shared personal credentials, which only their owners can write.+ */+export const findWritableCred = async (+ client: CredsWriteClient,+ key: string,+ isWorkspace: boolean,+) => {+ const { data } = await client.list.query();+ return data?.find((cred) => cred.key === key && (!isWorkspace || cred.ownerType !== 'user'));+};++/**+ * An existing credential can only be updated in place when it has the+ * requested type: the update API changes values but not the type, so values of+ * one type written into a credential of another would be injected wrongly.+ */+export const isCredTypeMismatch = (+ existing: { type?: string } | undefined,+ requestedType: RequestCredsInputParams['type'],+) => !!existing && existing.type !== undefined && existing.type !== requestedType;++export class CredTypeMismatchError extends Error {+ constructor() {+ super('A credential with this key already exists with a different type');+ this.name = 'CredTypeMismatchError';+ }+}++/**+ * Writes the form's values to the credential store: updates the credential+ * with the same key when the scope can write it, creates one otherwise.+ * Re-reads the list instead of trusting what the card showed, since the key+ * may have been created elsewhere in the meantime, and refuses to update a+ * credential of another type.+ */+export const saveCredsInput = async (+ client: CredsWriteClient,+ args: RequestCredsInputParams,+ isWorkspace: boolean,+ values: Record<string, string>,+) => {+ const writable = await findWritableCred(client, args.key, isWorkspace);+ if (isCredTypeMismatch(writable, args.type)) throw new CredTypeMismatchError();++ if (writable) {+ await client.update.mutate({+ description: args.description,+ id: writable.id,+ name: args.name,+ values,+ });+ } else {+ await client.createKV.mutate({+ description: args.description,+ key: args.key,+ name: args.name || args.key,+ type: args.type,+ values,+ });+ }+};++export type CredsInputSubmitStage = 'approve' | 'save';++const sameValues = (a: Record<string, string>, b: Record<string, string>) =>+ Object.keys(a).length === Object.keys(b).length &&+ Object.entries(a).every(([key, value]) => b[key] === value);++/**+ * Submit handler for the secure form: write the values, then approve the+ * call. The two steps fail independently. When the write succeeded but the+ * approval did not, a retry with the same values only approves again; if the+ * user edited a field in between, the new values are written first, so the+ * approved credential is always what the form shows. `onError` gets the failed+ * stage so the card can say which one to retry.+ */+export const createCredsInputSubmit = ({+ approve,+ onError,+ save,+}: {+ approve: () => Promise<void>;+ onError: (stage: CredsInputSubmitStage) => void;+ save: (values: Record<string, string>) => Promise<void>;+}) => {+ let savedValues: Record<string, string> | undefined;++ return async (values: Record<string, string>) => {+ if (!savedValues || !sameValues(values, savedValues)) {+ try {+ await save(values);+ } catch (error) {+ onError('save');+ throw error;+ }+ savedValues = { ...values };+ }++ try {+ await approve();+ } catch (error) {+ onError('approve');+ throw error;+ }+ };+};diff --git a/packages/builtin-tool-creds/src/client/Intervention/index.ts b/packages/builtin-tool-creds/src/client/Intervention/index.tsnew file mode 100644index 00000000000..2e7640114cd--- /dev/null+++ b/packages/builtin-tool-creds/src/client/Intervention/index.ts@@ -0,0 +1,8 @@+import type { BuiltinIntervention } from '@lobechat/types';++import { CredsApiName } from '../../types';+import RequestCredsInputIntervention from './RequestCredsInput';++export const CredsInterventions: Record<string, BuiltinIntervention> = {+ [CredsApiName.requestCredsInput]: RequestCredsInputIntervention as BuiltinIntervention,+};diff --git a/packages/builtin-tool-creds/src/client/index.ts b/packages/builtin-tool-creds/src/client/index.tsindex 0b8004d23df..a23801e1839 100644--- a/packages/builtin-tool-creds/src/client/index.ts+++ b/packages/builtin-tool-creds/src/client/index.ts@@ -1,4 +1,4 @@-// Client-side components for Creds tool-// Placeholder for future Render/Streaming components--export {};+export { CredsIdentifier, CredsManifest } from '../manifest';+export * from '../types';+export { CredsInterventions } from './Intervention';+export { default as RequestCredsInputIntervention } from './Intervention/RequestCredsInput';diff --git a/packages/builtin-tool-creds/src/executor/index.ts b/packages/builtin-tool-creds/src/executor/index.tsindex a393d6db25d..a5100499cb6 100644--- a/packages/builtin-tool-creds/src/executor/index.ts+++ b/packages/builtin-tool-creds/src/executor/index.ts@@ -11,11 +11,12 @@ import { useUserStore } from '@/store/user';import { userProfileSelectors } from '@/store/user/slices/auth/selectors';import { CredsIdentifier } from '../manifest';+import { buildRequestCredsInputResult } from '../requestCredsInput';import type {ConnectComposioServiceParams,InitiateOAuthConnectParams,InjectCredsToSandboxParams,- SaveCredsParams,+ RequestCredsInputParams,} from '../types';import { CredsApiName, LOBEHUB_OAUTH_PROVIDER_LIST } from '../types';@@ -385,67 +386,26 @@ class CredsExecutor extends BaseExecutor<typeof CredsApiName> {};/**- * Save new credentials+ * Runs after the user approves the secure form, which already wrote the+ * values to the credential store. Only confirms the key exists.*/- saveCreds = async (- params: SaveCredsParams,+ requestCredsInput = async (+ params: RequestCredsInputParams,_ctx?: BuiltinToolContext,): Promise<BuiltinToolResult> => {try {- // Normalize params: AI may send `displayName` instead of `name`,- // or `value` (env-style string) instead of `values` (Record)- const raw = params as any;- const name: string = params.name || raw.displayName || params.key;-- let values: Record<string, string> = params.values;- if (!values && typeof raw.value === 'string') {- values = {};- for (const line of (raw.value as string).split('\n')) {- const idx = line.indexOf('=');- if (idx > 0) {- values[line.slice(0, idx).trim()] = line.slice(idx + 1).trim();- }- }- }-- if (!values || Object.keys(values).length === 0) {- return {- content:- 'Failed to save credential: values must be a non-empty object of key-value pairs (e.g., { "API_KEY": "sk-xxx" }).',- error: {- message: 'values is empty or missing. Provide key-value pairs, not a raw string.',- type: 'InvalidParams',- },- success: false,- };- }-- log('[CredsExecutor] saveCreds - key:', params.key, 'name:', name);-- await lambdaClient.market.creds.createKV.mutate({- description: params.description,- key: params.key,- name,- type: params.type as 'kv-env' | 'kv-header',- values,- });-- return {- content: `Credential "${name}" saved successfully with key "${params.key}"`,- state: {- key: params.key,- message: `Credential "${name}" saved successfully`,- success: true,- },- success: true,- };+ const { data } = await lambdaClient.market.creds.listForContext.query();+ return buildRequestCredsInputResult(+ params,+ data.some((cred) => cred.key === params.key),+ );} catch (error) {- log('[CredsExecutor] saveCreds - error:', error);+ log('[CredsExecutor] requestCredsInput - error:', error);return {- content: `Failed to save credential: ${error instanceof Error ? error.message : 'Unknown error'}`,+ content: `Failed to check credential "${params.key}": ${error instanceof Error ? error.message : 'Unknown error'}`,error: {- message: error instanceof Error ? error.message : 'Failed to save credential',- type: 'SaveCredentialFailed',+ message: error instanceof Error ? error.message : 'Failed to check credential',+ type: 'CheckCredentialFailed',},success: false,};diff --git a/packages/builtin-tool-creds/src/index.ts b/packages/builtin-tool-creds/src/index.tsindex 00c4fef2df9..ff189b50909 100644--- a/packages/builtin-tool-creds/src/index.ts+++ b/packages/builtin-tool-creds/src/index.ts@@ -24,6 +24,6 @@ export {type InitiateOAuthConnectParams,type InjectCredsToSandboxParams,type InjectCredsToSandboxState,- type SaveCredsParams,- type SaveCredsState,+ type RequestCredsInputParams,+ type RequestCredsInputState,} from './types';diff --git a/packages/builtin-tool-creds/src/manifest.ts b/packages/builtin-tool-creds/src/manifest.tsindex afb8594e889..b64c9cc50b9 100644--- a/packages/builtin-tool-creds/src/manifest.ts+++ b/packages/builtin-tool-creds/src/manifest.ts@@ -63,8 +63,9 @@ export const CredsManifest: BuiltinToolManifest = {},{description:- 'Save a new credential securely. Use this when the user wants to store sensitive information like API keys, tokens, or secrets. The credential will be encrypted and stored securely.',- name: CredsApiName.saveCreds,+ 'Ask the user to enter a credential in a secure form, then store it encrypted. You only name the credential and its fields; the user types the values into the form, which saves them directly. The values never appear in this conversation, so never ask the user to paste a secret into the chat. Reusing an existing key lets the user update that credential.',+ humanIntervention: 'always',+ name: CredsApiName.requestCredsInput,parameters: {additionalProperties: false,properties: {@@ -72,6 +73,18 @@ export const CredsManifest: BuiltinToolManifest = {description: 'Optional description explaining what this credential is used for',type: 'string',},+ fieldNames: {+ description:+ 'Names of the values the user should fill in. For kv-env, the environment variable names (e.g., ["OPENAI_API_KEY"]); for kv-header, the header names (e.g., ["Authorization"]).',+ items: {+ pattern: '^[A-Za-z_][A-Za-z0-9_-]*$',+ type: 'string',+ },+ maxItems: 10,+ minItems: 1,+ type: 'array',+ uniqueItems: true,+ },key: {description:'Unique identifier key for the credential (e.g., "openai", "github-token"). Use lowercase with hyphens.',@@ -87,16 +100,8 @@ export const CredsManifest: BuiltinToolManifest = {enum: ['kv-env', 'kv-header'],type: 'string',},- values: {- additionalProperties: {- type: 'string',- },- description:- 'Key-value pairs of the credential. For kv-env, the key should be the environment variable name (e.g., {"OPENAI_API_KEY": "sk-..."})',- type: 'object',- },},- required: ['key', 'name', 'type', 'values'],+ required: ['key', 'name', 'type', 'fieldNames'],type: 'object',} satisfies JSONSchema7,},diff --git a/packages/builtin-tool-creds/src/requestCredsInput.test.ts b/packages/builtin-tool-creds/src/requestCredsInput.test.tsnew file mode 100644index 00000000000..93fc27464a8--- /dev/null+++ b/packages/builtin-tool-creds/src/requestCredsInput.test.ts@@ -0,0 +1,64 @@+import { describe, expect, it, vi } from 'vitest';++import { CredsExecutionRuntime, type ICredsService } from './ExecutionRuntime';+import { CredsManifest } from './manifest';+import { buildRequestCredsInputResult } from './requestCredsInput';+import { CredsApiName } from './types';++const args = {+ fieldNames: ['OPENAI_API_KEY'],+ key: 'openai',+ name: 'OpenAI API Key',+ type: 'kv-env' as const,+};++describe('requestCredsInput', () => {+ it('declares only non-secret parameters and always pauses for the user', () => {+ const api = CredsManifest.api.find((item) => item.name === CredsApiName.requestCredsInput);++ expect(api?.humanIntervention).toBe('always');+ expect(api?.parameters).toMatchObject({ additionalProperties: false });+ expect(Object.keys((api?.parameters as { properties: object }).properties).sort()).toEqual([+ 'description',+ 'fieldNames',+ 'key',+ 'name',+ 'type',+ ]);+ });++ it('no longer offers an API that takes credential values as arguments', () => {+ expect(CredsManifest.api.map((item) => item.name)).not.toContain('saveCreds');+ for (const api of CredsManifest.api) {+ expect(+ Object.keys((api.parameters as { properties?: object }).properties ?? {}),+ ).not.toContain('values');+ }+ });++ it('reports a saved credential by key only', () => {+ const result = buildRequestCredsInputResult(args, true);++ expect(result.success).toBe(true);+ expect(result.state).toEqual({ key: 'openai' });+ expect(result.content).toContain('"openai"');+ });++ it('fails without asking for the secret when the form was not completed', () => {+ const result = buildRequestCredsInputResult(args, false);++ expect(result.success).toBe(false);+ expect(result.error?.type).toBe('CredentialNotFound');+ expect(result.content).toContain('Do not ask for the secret in the chat');+ });++ it('checks the scoped credential list after approval', async () => {+ const listCreds = vi.fn().mockResolvedValue({ data: [{ id: 1, key: 'openai' }] });+ const runtime = new CredsExecutionRuntime({ listCreds } as unknown as ICredsService);++ const result = await runtime.requestCredsInput(args);++ expect(listCreds).toHaveBeenCalledTimes(1);+ expect(result.success).toBe(true);+ });+});diff --git a/packages/builtin-tool-creds/src/requestCredsInput.ts b/packages/builtin-tool-creds/src/requestCredsInput.tsnew file mode 100644index 00000000000..de62affa89c--- /dev/null+++ b/packages/builtin-tool-creds/src/requestCredsInput.ts@@ -0,0 +1,35 @@+import type { BuiltinServerRuntimeOutput } from '@lobechat/types';++import type { RequestCredsInputParams, RequestCredsInputState } from './types';++/**+ * Tool result of an approved `requestCredsInput` call.+ *+ * The secure form writes the values to the credential store before it+ * approves the call, so by the time the tool runs the only thing left to report+ * is whether the key now exists. Built from the request arguments and that+ * lookup alone, the result cannot carry a secret.+ */+export const buildRequestCredsInputResult = (+ args: Pick<RequestCredsInputParams, 'key' | 'name'>,+ found: boolean,+): BuiltinServerRuntimeOutput => {+ if (!found) {+ return {+ content: `No credential with key "${args.key}" was found, so the user did not complete the secure form. Do not ask for the secret in the chat. Call requestCredsInput again only if the user asks to.`,+ error: {+ message: `Credential not found: ${args.key}`,+ type: 'CredentialNotFound',+ },+ success: false,+ };+ }++ const state: RequestCredsInputState = { key: args.key };++ return {+ content: `Credential "${args.name || args.key}" is saved under key "${args.key}". The user entered its values in a secure form; they are encrypted and not visible to you. Refer to the credential by its key.`,+ state,+ success: true,+ };+};diff --git a/packages/builtin-tool-creds/src/systemRole.ts b/packages/builtin-tool-creds/src/systemRole.tsindex 656517b688c..01873466608 100644--- a/packages/builtin-tool-creds/src/systemRole.ts+++ b/packages/builtin-tool-creds/src/systemRole.ts@@ -20,7 +20,7 @@ Cloud sandbox reachable for credential injection: {{creds_sandbox_reachable}}<core_responsibilities>1. **Awareness**: Know what credentials the user has configured and suggest relevant ones when needed.-2. **Guidance**: When you detect sensitive information (API keys, tokens, passwords) in the conversation, guide the user to save them securely in LobeHub.+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.</core_responsibilities>@@ -28,11 +28,12 @@ Cloud sandbox reachable for credential injection: {{creds_sandbox_reachable}}<tooling>- **initiateOAuthConnect**: Start OAuth authorization flow for third-party services. Returns an authorization URL for the user to click.- **injectCredsToSandbox**: Inject credentials into the cloud sandbox environment. Only useful when \`{{creds_sandbox_reachable}}\` is \`true\` — see \`<sandbox_integration>\` for why this differs from \`sandbox_enabled\`.-- **saveCreds**: Save new credentials securely. Use when user wants to store sensitive information.- - Parameters: \`key\` (unique identifier, lowercase with hyphens), \`name\` (display name), \`type\` ("kv-env" or "kv-header"), \`values\` (object of key-value pairs, NOT a string), \`description\` (optional)- - Example: \`saveCreds({ key: "openai", name: "OpenAI API Key", type: "kv-env", values: { "OPENAI_API_KEY": "sk-xxx" } })\`- - For multiple env vars: \`saveCreds({ key: "my-config", name: "My Config", type: "kv-env", values: { "APP_URL": "http://localhost:3000", "DB_URL": "postgres://..." } })\`- - IMPORTANT: \`values\` must be a JSON object (Record<string, string>), NOT a raw string. Each environment variable should be a separate key-value pair in the object.+- **requestCredsInput**: Ask the user to enter a credential in a secure form. The form saves the values to encrypted storage directly; you never see them and only get back the credential key.+ - Parameters: \`key\` (unique identifier, lowercase with hyphens), \`name\` (display name), \`type\` ("kv-env" or "kv-header"), \`fieldNames\` (names of the values to fill in), \`description\` (optional)+ - Example: \`requestCredsInput({ key: "openai", name: "OpenAI API Key", type: "kv-env", fieldNames: ["OPENAI_API_KEY"] })\`+ - For multiple env vars: \`requestCredsInput({ key: "my-config", name: "My Config", type: "kv-env", fieldNames: ["APP_URL", "DB_URL"] })\`+ - Reuse the key of an existing credential to let the user update its values.+ - If the user skips the form, do not ask again in the same turn; continue without the credential or explain what is blocked.</tooling><oauth_providers>@@ -48,25 +49,19 @@ When a user mentions they want to use one of these services, use \`initiateOAuth<security_guidelines>- **Never display credential values** in your responses. Refer to credentials by their key or name only.-- **Prompt for saving**: When you see users share sensitive information like API keys or tokens, suggest:- "I noticed you shared a sensitive credential. Would you like me to save it securely in LobeHub? This way you can reuse it without sharing it again."-- **Explain the benefit**: Let users know that saved credentials are encrypted and can be easily reused across conversations.+- **Never collect secrets through the chat.** Do not ask the user to type or paste API keys, tokens, passwords, or other secrets into a message, and never put a secret value into any tool argument. Use \`requestCredsInput\` instead.+- **If the user already pasted a secret** into the conversation: do not repeat it and do not try to save it from the message. Tell the user it is now part of the conversation history, recommend rotating it, and offer \`requestCredsInput\` to store the new value securely.</security_guidelines>-<credential_saving_triggers>-Proactively suggest saving credentials when you detect:-- API keys (e.g., "sk-...", "api_...", patterns like "OPENAI_API_KEY=...")-- Access tokens or bearer tokens+<credential_collection_triggers>+Offer \`requestCredsInput\` when a task needs a secret that is not in the available credentials list, for example:+- API keys or access tokens for a third-party API- Secret keys or private keys- Database connection strings with passwords- OAuth client secrets-- Any explicitly labeled secrets or passwords-When suggesting to save, always:-1. Explain that the credential will be encrypted and stored securely-2. Ask the user for a meaningful name and optional description-3. Use the \`saveCreds\` tool to store it with \`values\` as a JSON object (e.g., \`{ "API_KEY": "sk-xxx" }\`), NOT a raw string-</credential_saving_triggers>+Before calling it, briefly tell the user what the credential is for. The form itself tells the user that the values are encrypted and never shown to you.+</credential_collection_triggers><sandbox_integration>**Only applies when the cloud sandbox is reachable this run (current value: {{creds_sandbox_reachable}}).**@@ -117,6 +112,6 @@ When \`{{creds_sandbox_reachable}}\` is \`false\`, this run is routed to a devic<response_expectations>- When credentials are relevant, mention which ones are available and how they can be used.- When accessing credentials, briefly explain why access is needed.-- When guiding users to save credentials, be helpful but not pushy.+- When asking users for credentials, be helpful but not pushy.- Keep credential-related discussions concise and security-focused.</response_expectations>`;diff --git a/packages/builtin-tool-creds/src/types.ts b/packages/builtin-tool-creds/src/types.tsindex 4345b276538..d929e94b11e 100644--- a/packages/builtin-tool-creds/src/types.ts+++ b/packages/builtin-tool-creds/src/types.ts@@ -20,10 +20,10 @@ export const CredsApiName = {injectCredsToSandbox: 'injectCredsToSandbox',/**- * Save a new credential- * Use when user wants to store sensitive info securely+ * Ask the user to enter a credential's values in a secure form.+ * The values go straight to the credential store and never reach the model.*/- saveCreds: 'saveCreds',+ requestCredsInput: 'requestCredsInput',} as const;export type CredsApiNameType = (typeof CredsApiName)[keyof typeof CredsApiName];@@ -90,11 +90,16 @@ export interface InjectCredsToSandboxState {success: boolean;}-export interface SaveCredsParams {+export interface RequestCredsInputParams {/*** Optional description for the credential*/description?: string;+ /**+ * Names of the values the user fills in, e.g. environment variable names+ * (`OPENAI_API_KEY`) for kv-env or header names for kv-header+ */+ fieldNames: string[];/*** Unique key for the credential (used for reference)*/@@ -106,26 +111,15 @@ export interface SaveCredsParams {/*** The type of credential*/- type: CredType;- /**- * Key-value pairs of the credential (for kv-env and kv-header types)- */- values: Record<string, string>;+ type: 'kv-env' | 'kv-header';}-export interface SaveCredsState {- /**- * The created credential key- */- key?: string;- /**- * Error message if save failed- */- message?: string;- /**- * Whether save was successful- */- success: boolean;+/**+ * Plugin state of an approved `requestCredsInput` call. Carries the key only:+ * the values went from the form to the credential store directly.+ */+export interface RequestCredsInputState {+ key: string;}// ==================== Composio Service Types ====================diff --git a/packages/builtin-tools/src/register.ts b/packages/builtin-tools/src/register.tsindex 06930ea6a1e..0545f4e304e 100644--- a/packages/builtin-tools/src/register.ts+++ b/packages/builtin-tools/src/register.ts@@ -43,6 +43,7 @@ import {CloudSandboxRenders,CloudSandboxStreamings,} from '@lobechat/builtin-tool-cloud-sandbox/client';+import { CredsIdentifier, CredsInterventions } from '@lobechat/builtin-tool-creds/client';import {GoalInspectors,GoalInterventions,@@ -391,6 +392,7 @@ export const registerBuiltinToolSurfaces = (): void => {ClaudeCodeInterventions[ClaudeCodeApiName.AskUserQuestion],},[QODER_IDENTIFIER]: ClaudeCodeInterventions as Record<string, BuiltinIntervention>,+ [CredsIdentifier]: CredsInterventions as Record<string, BuiltinIntervention>,[CloudSandboxManifest.identifier]: CloudSandboxInterventions as Record<string,BuiltinInterventiondiff --git a/packages/locales/src/default/tool.ts b/packages/locales/src/default/tool.tsindex 3d73f34a090..07292f0591f 100644--- a/packages/locales/src/default/tool.ts+++ b/packages/locales/src/default/tool.ts@@ -94,6 +94,26 @@ export default {'This connector belongs to the agent “{{agent}}”. Deleting it will also remove this tool from that agent.','connector.manageOnlyCreator': 'Only the creator or a workspace owner can manage this connector','connector.thisAgent': 'this agent',+ 'credsInput.approveFailed':+ "The credential was saved, but the conversation couldn't continue. Please try again.",+ 'credsInput.notice.lookupFailed':+ "Couldn't check whether this credential already exists, so it can't be saved safely right now. Skip, or try again later.",+ 'credsInput.notice.noPermission':+ 'Only workspace admins can save workspace credentials. Skip this request, or ask an admin to add the credential in the workspace settings.',+ 'credsInput.notice.overwrite':+ 'A credential with key “{{key}}” already exists. Saving will replace its values.',+ 'credsInput.notice.personal':+ 'Saved encrypted to your personal credentials. The values go directly to storage and are never shown to the AI.',+ 'credsInput.notice.typeMismatch':+ "A credential with key “{{key}}” already exists with a different type ({{type}}) and can't be replaced from here. Skip, and ask for it under a different key.",+ 'credsInput.notice.workspace':+ "Saved encrypted to this workspace's credentials. The values go directly to storage and are never shown to the AI.",+ 'credsInput.placeholder': 'Enter {{field}}',+ 'credsInput.saveFailed': "Couldn't save the credential. Please try again.",+ 'credsInput.skip': 'Skip',+ 'credsInput.submit': 'Save',+ 'credsInput.submitting': 'Saving…',+ 'credsInput.update': 'Update','dalle.autoGenerate': 'Auto Generate','dalle.downloading':'The image links generated by DALL·E3 are only valid for 1 hour, caching the images locally...',diff --git a/packages/shared-tool-ui/package.json b/packages/shared-tool-ui/package.jsonindex 70975787318..4a319005606 100644--- a/packages/shared-tool-ui/package.json+++ b/packages/shared-tool-ui/package.json@@ -12,6 +12,7 @@"./inspectors/linear-labels": "./src/Inspector/Linear/labels.ts","./pending-hotkeys": "./src/pendingHotkeys.ts","./renders": "./src/Render/index.ts",+ "./secret-input": "./src/SecretInput/index.ts","./styles": "./src/styles.ts"},"dependencies": {diff --git a/packages/shared-tool-ui/src/SecretInput/SecretInputView.tsx b/packages/shared-tool-ui/src/SecretInput/SecretInputView.tsxnew file mode 100644index 00000000000..a1219c2a95e--- /dev/null+++ b/packages/shared-tool-ui/src/SecretInput/SecretInputView.tsx@@ -0,0 +1,123 @@+'use client';++import { Flexbox, Icon } from '@lobehub/ui';+import { Button, InputPassword, Text } from '@lobehub/ui/base-ui';+import { cssVar } from 'antd-style';+import { CircleAlert } from 'lucide-react';+import { memo, type ReactNode } from 'react';+import { createPortal } from 'react-dom';++import type { SecretInputLabels } from './types';+import { useSecretInputForm } from './useSecretInputForm';++export interface SecretInputViewProps {+ /**+ * When present, the submit / cancel footer is portaled here so it stays+ * pinned below scrollable content (same contract as `AskUserQuestionView`).+ */+ actionsPortalTarget?: HTMLElement | null;+ /**+ * Why the user cannot enter the secret here, e.g. a missing permission.+ * Replaces the fields and disables submit; cancel stays available.+ */+ blockedReason?: ReactNode;+ disabled?: boolean;+ /** Short, human-readable failure message; never the sink's raw error. */+ error?: string;+ /** Field names to collect, e.g. environment variable names. */+ fields: string[];+ labels: SecretInputLabels;+ /** Context shown above the fields, e.g. where the secret will be stored. */+ notice?: ReactNode;+ onCancel: () => void;+ /**+ * Receives the plaintext values. The caller must hand them straight to its+ * sink (a credential store, a device vault) and report only a non-secret+ * reference onwards — never put them in tool arguments, results, plugin+ * state, stores or logs. A rejection keeps the values so the user can retry.+ */+ onSubmit: (values: Record<string, string>) => Promise<void>;+}++/**+ * Password-style form for secrets that must not enter the agent context. See+ * {@link useSecretInputForm} for how long the values are kept.+ */+const SecretInputView = memo<SecretInputViewProps>(+ ({+ actionsPortalTarget,+ blockedReason,+ disabled,+ error,+ fields,+ labels,+ notice,+ onCancel,+ onSubmit,+ }) => {+ const { complete, formKey, handleChange, handleSubmit, submitting } = useSecretInputForm({+ fields,+ onSubmit,+ });++ const inert = disabled || submitting;+ const canSubmit = !inert && !blockedReason && complete;++ const actions = (+ <Flexbox horizontal gap={8} justify={'flex-end'}>+ <Button disabled={inert} onClick={onCancel}>+ {labels.cancel}+ </Button>+ <Button disabled={!canSubmit} loading={submitting} type={'primary'} onClick={handleSubmit}>+ {submitting ? labels.submitting : labels.submit}+ </Button>+ </Flexbox>+ );++ return (+ <Flexbox gap={12}>+ {notice}+ {blockedReason ? (+ <Text fontSize={12} type={'warning'}>+ {blockedReason}+ </Text>+ ) : (+ <Flexbox gap={8} key={formKey}>+ {fields.map((field) => (+ <Flexbox gap={4} key={field}>+ <Text fontSize={12} type={'secondary'}>+ {field}+ </Text>+ <InputPassword+ data-1p-ignore+ autoComplete={'off'}+ data-lpignore={'true'}+ disabled={inert}+ placeholder={labels.placeholder(field)}+ spellCheck={false}+ onChange={(event) => handleChange(field, event.target.value)}+ onPressEnter={() => {+ if (canSubmit) void handleSubmit();+ }}+ />+ </Flexbox>+ ))}+ </Flexbox>+ )}+ {error && (+ <Flexbox horizontal align={'center'} gap={6} role={'alert'}>+ <Icon color={cssVar.colorError} icon={CircleAlert} size={14} />+ <Text fontSize={12} type={'danger'}>+ {error}+ </Text>+ </Flexbox>+ )}+ {actionsPortalTarget ? createPortal(actions, actionsPortalTarget) : actions}+ </Flexbox>+ );+ },+);++SecretInputView.displayName = 'SecretInputView';++export default SecretInputView;diff --git a/packages/shared-tool-ui/src/SecretInput/index.ts b/packages/shared-tool-ui/src/SecretInput/index.tsnew file mode 100644index 00000000000..723c6abb33a--- /dev/null+++ b/packages/shared-tool-ui/src/SecretInput/index.ts@@ -0,0 +1,3 @@+export { default as SecretInputView, type SecretInputViewProps } from './SecretInputView';+export type { SecretInputLabels } from './types';+export { useSecretInputForm, type UseSecretInputFormParams } from './useSecretInputForm';diff --git a/packages/shared-tool-ui/src/SecretInput/types.ts b/packages/shared-tool-ui/src/SecretInput/types.tsnew file mode 100644index 00000000000..e25bcf568b3--- /dev/null+++ b/packages/shared-tool-ui/src/SecretInput/types.ts@@ -0,0 +1,8 @@+export interface SecretInputLabels {+ cancel: string;+ /** Placeholder for each field; receives the field name. */+ placeholder: (field: string) => string;+ submit: string;+ /** Shown on the submit button while the sink write is in flight. */+ submitting: string;+}diff --git a/packages/shared-tool-ui/src/SecretInput/useSecretInputForm.test.ts b/packages/shared-tool-ui/src/SecretInput/useSecretInputForm.test.tsnew file mode 100644index 00000000000..902d120c6a5--- /dev/null+++ b/packages/shared-tool-ui/src/SecretInput/useSecretInputForm.test.ts@@ -0,0 +1,65 @@+/**+ * @vitest-environment happy-dom+ */+import { act, renderHook } from '@testing-library/react';+import { describe, expect, it, vi } from 'vitest';++import { useSecretInputForm } from './useSecretInputForm';++const fields = ['OPENAI_API_KEY'];++describe('useSecretInputForm', () => {+ it('completes only when every field has a value', () => {+ const { result } = renderHook(() =>+ useSecretInputForm({ fields: ['A', 'B'], onSubmit: vi.fn() }),+ );++ act(() => result.current.handleChange('A', 'a'));+ expect(result.current.complete).toBe(false);++ act(() => result.current.handleChange('B', 'b'));+ expect(result.current.complete).toBe(true);++ act(() => result.current.handleChange('B', ''));+ expect(result.current.complete).toBe(false);+ });++ it('keeps the values after a failed submit so the user can retry', async () => {+ const onSubmit = vi+ .fn()+ .mockRejectedValueOnce(new Error('store unavailable'))+ .mockResolvedValueOnce(undefined);+ const { result } = renderHook(() => useSecretInputForm({ fields, onSubmit }));++ act(() => result.current.handleChange('OPENAI_API_KEY', 'sk-one-time'));+ const formKey = result.current.formKey;++ await act(() => result.current.handleSubmit());++ // The inputs are not remounted and the retry needs no re-entry.+ expect(result.current.formKey).toBe(formKey);+ expect(result.current.complete).toBe(true);++ await act(() => result.current.handleSubmit());++ expect(onSubmit).toHaveBeenNthCalledWith(2, { OPENAI_API_KEY: 'sk-one-time' });+ });++ it('drops the values after a successful submit', async () => {+ const onSubmit = vi.fn().mockResolvedValue(undefined);+ const { result } = renderHook(() => useSecretInputForm({ fields, onSubmit }));++ act(() => result.current.handleChange('OPENAI_API_KEY', 'sk-saved'));+ const formKey = result.current.formKey;++ await act(() => result.current.handleSubmit());++ expect(onSubmit).toHaveBeenCalledWith({ OPENAI_API_KEY: 'sk-saved' });+ expect(result.current.formKey).not.toBe(formKey);+ expect(result.current.complete).toBe(false);++ await act(() => result.current.handleSubmit());++ expect(onSubmit).toHaveBeenLastCalledWith({ OPENAI_API_KEY: undefined });+ });+});diff --git a/packages/shared-tool-ui/src/SecretInput/useSecretInputForm.ts b/packages/shared-tool-ui/src/SecretInput/useSecretInputForm.tsnew file mode 100644index 00000000000..1bb99f5b27c--- /dev/null+++ b/packages/shared-tool-ui/src/SecretInput/useSecretInputForm.ts@@ -0,0 +1,64 @@+import { useCallback, useEffect, useRef, useState } from 'react';++export interface UseSecretInputFormParams {+ fields: string[];+ /**+ * Receives the plaintext values. A rejection keeps them so the user can+ * retry without re-entering a secret the provider may not show again.+ */+ onSubmit: (values: Record<string, string>) => Promise<void>;+}++/**+ * Value lifecycle of a secret form.+ *+ * Values live in a ref, not React state or any store, so they never reach+ * devtools state snapshots, draft persistence or re-render props. They are+ * dropped after a successful submit or on unmount; a failed submit keeps them+ * for the retry. Only which fields are filled is kept in state.+ */+export const useSecretInputForm = ({ fields, onSubmit }: UseSecretInputFormParams) => {+ const valuesRef = useRef<Record<string, string>>({});+ const [filled, setFilled] = useState<Set<string>>(() => new Set());+ const [submitting, setSubmitting] = useState(false);+ // Bumping the key remounts the uncontrolled inputs, clearing their DOM values.+ const [formKey, setFormKey] = useState(0);++ useEffect(+ () => () => {+ valuesRef.current = {};+ },+ [],+ );++ const handleChange = useCallback((field: string, value: string) => {+ valuesRef.current[field] = value;+ setFilled((prev) => {+ const hasValue = value.length > 0;+ if (prev.has(field) === hasValue) return prev;+ const next = new Set(prev);+ if (hasValue) next.add(field);+ else next.delete(field);+ return next;+ });+ }, []);++ const handleSubmit = useCallback(async () => {+ const values = Object.fromEntries(fields.map((field) => [field, valuesRef.current[field]]));+ setSubmitting(true);+ try {+ await onSubmit(values);+ valuesRef.current = {};+ setFilled(new Set());+ setFormKey((key) => key + 1);+ } catch {+ // The caller surfaces the failure; the values stay for the retry.+ } finally {+ setSubmitting(false);+ }+ }, [fields, onSubmit]);++ const complete = fields.length > 0 && fields.every((field) => filled.has(field));++ return { complete, formKey, handleChange, handleSubmit, submitting };+};diff --git a/packages/types/src/tool/intervention.test.ts b/packages/types/src/tool/intervention.test.tsindex d25fc812114..b4008452c77 100644--- a/packages/types/src/tool/intervention.test.ts+++ b/packages/types/src/tool/intervention.test.ts@@ -13,4 +13,15 @@ describe('classifyToolInterventionPresentation', () => {surface: 'form',});});++ it('keeps the secure credential form an approval that only its card can resolve', () => {+ expect(classifyToolInterventionPresentation('lobe-creds', 'requestCredsInput')).toEqual({+ interactionKind: 'tool_approval',+ surface: 'form',+ });+ expect(classifyToolInterventionPresentation('lobe-creds', 'injectCredsToSandbox')).toEqual({+ interactionKind: 'tool_approval',+ surface: 'binary',+ });+ });});diff --git a/packages/types/src/tool/intervention.ts b/packages/types/src/tool/intervention.tsindex ceef9ab1cd3..5f7c84f249b 100644--- a/packages/types/src/tool/intervention.ts+++ b/packages/types/src/tool/intervention.ts@@ -192,6 +192,14 @@ export const classifyToolInterventionPresentation = (return { interactionKind: 'custom', surface: 'form' };}+ // The secure credential form writes the secret itself and then resolves the+ // call as an ordinary approval, so it keeps tool-approval semantics. It is+ // still a form: approving it anywhere but the card (Approve all, a push or+ // notification action) would skip the form and never store the secret.+ if (identifier === 'lobe-creds' && apiName === 'requestCredsInput') {+ return { interactionKind: 'tool_approval', surface: 'form' };+ }+// Claude Code / Cursor ACP / Devin ACP / Droid ACP / Qoder expose provider-specific intervention// forms (permission, plan, bespoke prompts). They are intentionally kept// non-binary even when a newly added API name is not yet known to Web.diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/customInteractionHandlers.test.ts b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/customInteractionHandlers.test.tsindex 8cdd9812cfb..644970f74a6 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/customInteractionHandlers.test.ts+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/customInteractionHandlers.test.ts@@ -1,3 +1,4 @@+import { CredsApiName, CredsIdentifier } from '@lobechat/builtin-tool-creds';import { LobeAgentApiName, LobeAgentIdentifier } from '@lobechat/builtin-tool-lobe-agent';import {UserInteractionApiName,@@ -12,9 +13,11 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { installMarketplaceAgents } from '@/services/installMarketplaceAgents';import {+ isApprovalBackedInteraction,isCustomInteractionIdentifier,prepareCustomInteractionSubmit,recordCustomInteractionResolution,+ toApprovalDecision,} from './customInteractionHandlers';vi.mock('@/services/installMarketplaceAgents', () => ({@@ -142,4 +145,36 @@ describe('customInteractionHandlers', () => {},});});++ describe('approval-backed forms (lobe-creds requestCredsInput)', () => {+ it('renders as a custom form', () => {+ expect(isApprovalBackedInteraction(CredsIdentifier, CredsApiName.requestCredsInput)).toBe(+ true,+ );+ expect(isCustomInteractionIdentifier(CredsIdentifier, CredsApiName.requestCredsInput)).toBe(+ true,+ );+ expect(isApprovalBackedInteraction(CredsIdentifier, CredsApiName.injectCredsToSandbox)).toBe(+ false,+ );+ });++ it('turns submit into a plain approval that drops the payload', () => {+ const decision = toApprovalDecision({+ payload: { OPENAI_API_KEY: 'sk-test-secret-value' },+ type: 'submit',+ });++ expect(decision).toEqual({ type: 'approve' });+ expect(JSON.stringify(decision)).not.toContain('sk-test-secret-value');+ });++ it('turns skip and cancel into reject-and-continue', () => {+ expect(toApprovalDecision({ reason: 'not now', type: 'skip' })).toEqual({+ reason: 'not now',+ type: 'reject',+ });+ expect(toApprovalDecision({ type: 'cancel' })).toEqual({ reason: undefined, type: 'reject' });+ });+ });});diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/customInteractionHandlers.ts b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/customInteractionHandlers.tsindex 6151c45650e..4083b7dda62 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/customInteractionHandlers.ts+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/customInteractionHandlers.ts@@ -1,4 +1,5 @@import { ClaudeCodeIdentifier } from '@lobechat/builtin-tool-claude-code';+import { CredsApiName, CredsIdentifier } from '@lobechat/builtin-tool-creds';import { LobeAgentApiName, LobeAgentIdentifier } from '@lobechat/builtin-tool-lobe-agent';import {UserInteractionApiName,@@ -177,6 +178,31 @@ const HETERO_CUSTOM_INTERACTION_IDENTIFIERS = new Set<string>([export const isHeteroInteractionIdentifier = (identifier: string) =>HETERO_CUSTOM_INTERACTION_IDENTIFIERS.has(identifier);+/**+ * Custom forms whose submit is an ordinary tool approval: the card performs+ * its side effect itself (e.g. writing a secret to the credential store) and+ * then lets the tool run, so the run never carries the form's input. The host+ * drops the submit payload and approves; skip becomes reject-and-continue.+ */+export const isApprovalBackedInteraction = (identifier: string, apiName?: string) =>+ identifier === CredsIdentifier && apiName === CredsApiName.requestCredsInput;++type InteractionAction =+ | { payload: Record<string, unknown>; type: 'submit' }+ | { payload?: Record<string, unknown>; reason?: string; type: 'skip' }+ | { payload?: Record<string, unknown>; type: 'cancel' };++/**+ * Maps an approval-backed form's action to the tool decision. The result has+ * no room for the payload, so nothing the form submits can reach the run.+ */+export const toApprovalDecision = (+ action: InteractionAction,+): { type: 'approve' } | { reason?: string; type: 'reject' } =>+ action.type === 'submit'+ ? { type: 'approve' }+ : { reason: action.type === 'skip' ? action.reason : undefined, type: 'reject' };+/*** lobe-agent reuses the user-interaction `askUserQuestion` card. Unlike the* standalone tool (whose whole identifier is a custom interaction), lobe-agent@@ -187,6 +213,7 @@ export const isCustomInteractionIdentifier = (identifier: string, apiName?: striidentifier === UserInteractionIdentifier ||isLobeAgentAskUserQuestion(identifier, apiName) ||isHeteroInteractionIdentifier(identifier) ||+ isApprovalBackedInteraction(identifier, apiName) ||Boolean(findCustomInteractionSubmitHandler(identifier, apiName));export const prepareCustomInteractionSubmit = async (diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/index.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/index.tsxindex 89b331fda8b..4fd9e3dac77 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/index.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/index.tsx@@ -15,10 +15,12 @@ import Arguments from '../Arguments';import ApprovalActions from './ApprovalActions';import {isAgentMarketplaceCall,+ isApprovalBackedInteraction,isCustomInteractionIdentifier,isHeteroInteractionIdentifier,prepareCustomInteractionSubmit,recordCustomInteractionResolution,+ toApprovalDecision,} from './customInteractionHandlers';import Fallback from './Fallback';import KeyValueEditor from './KeyValueEditor';@@ -132,6 +134,8 @@ const Intervention = memo<InterventionProps>(// writes and topic-status flip fall back to the global `activeTopicId` and// land on whichever topic the user is currently viewing.const submitHeteroIntervention = useConversationStore((s) => s.submitHeteroIntervention);+ const approveToolCall = useConversationStore((s) => s.approveToolCall);+ const rejectAndContinueToolCall = useConversationStore((s) => s.rejectAndContinueToolCall);const executeInteractionAction = useCallback(async (@@ -145,6 +149,14 @@ const Intervention = memo<InterventionProps>(await submitHeteroIntervention(id, action.type, action.payload);return;}+ // These forms already applied their input (e.g. a secret) outside the+ // run, so only the decision goes on; the payload is dropped.+ if (isApprovalBackedInteraction(identifier, apiName)) {+ const decision = toApprovalDecision(action);+ if (decision.type === 'approve') await approveToolCall(id, assistantGroupId ?? '');+ else await rejectAndContinueToolCall(id, decision.reason);+ return;+ }switch (action.type) {case 'submit': {if (usesDurableServerClaim && isAgentMarketplaceCall(identifier, apiName)) {@@ -218,12 +230,15 @@ const Intervention = memo<InterventionProps>(},[apiName,+ approveToolCall,+ assistantGroupId,canUseResource,cancelToolInteraction,id,identifier,interventionResolving,parsedArgs,+ rejectAndContinueToolCall,skipToolInteraction,submitHeteroIntervention,submitToolInteraction,diff --git a/src/features/Conversation/store/slices/data/pendingInterventions.test.ts b/src/features/Conversation/store/slices/data/pendingInterventions.test.tsindex 73cfd03b04a..24439539ea3 100644--- a/src/features/Conversation/store/slices/data/pendingInterventions.test.ts+++ b/src/features/Conversation/store/slices/data/pendingInterventions.test.ts@@ -193,6 +193,15 @@ describe('canApproveInterventionBatch', () => {expect(canApproveInterventionBatch(members as any)).toBe(false);});+ it('never bulk-approves the secure credential form, which must save before approving', () => {+ expect(+ canApproveInterventionBatch([+ pending('lobe-creds', 'requestCredsInput', 1),+ pending('filesystem', 'writeFile', 2),+ ]),+ ).toBe(false);+ });+it('does not render a bulk action for a single binary card', () => {expect(canApproveInterventionBatch([pending('filesystem', 'writeFile', 1)])).toBe(false);});