feat: manually mirror opencoze's code from bytedance

Change-Id: I09a73aadda978ad9511264a756b2ce51f5761adf
This commit is contained in:
fanlv
2025-07-20 17:36:12 +08:00
commit 890153324f
14811 changed files with 1923430 additions and 0 deletions

View File

@@ -0,0 +1,40 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { type PluginRegistryEntry } from '@coze-common/chat-area';
import { type PluginBizContext } from './types/biz-context';
import { BizPlugin } from './plugin';
export const getDebugCommonPluginRegistry = (props: PluginBizContext) => {
// eslint-disable-next-line @typescript-eslint/naming-convention -- 插件命名大写开头符合预期
const BizPluginRegistry: PluginRegistryEntry<PluginBizContext> = {
/**
* 贯穿插件生命周期、组件的上下文
*/
createPluginBizContext() {
return {
...props,
};
},
/**
* 插件本体
*/
Plugin: BizPlugin,
};
return BizPluginRegistry;
};

View File

@@ -0,0 +1,47 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {
PluginMode,
PluginName,
WriteableChatAreaPlugin,
createWriteableLifeCycleServices,
} from '@coze-common/chat-area';
import { type PluginBizContext } from './types/biz-context';
import { bizLifeCycleServiceGenerator } from './services/life-cycle';
export class BizPlugin extends WriteableChatAreaPlugin<PluginBizContext> {
/**
* 插件类型
* PluginMode.Readonly = 只读模式
* PluginMode.Writeable = 可写模式
*/
public pluginMode = PluginMode.Writeable;
/**
* 插件名称
* 请点 PluginName 里面去定义
*/
public pluginName = PluginName.DebugCommon;
/**
* 生命周期服务
*/
public lifeCycleServices = createWriteableLifeCycleServices(
this,
bizLifeCycleServiceGenerator,
);
}

View File

@@ -0,0 +1,23 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { type WriteableAppLifeCycleServiceGenerator } from '@coze-common/chat-area';
import { type PluginBizContext } from '../../types/biz-context';
export const appLifeCycleServiceGenerator: WriteableAppLifeCycleServiceGenerator<
PluginBizContext
> = plugin => ({});

View File

@@ -0,0 +1,76 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { useMultiAgentStore } from '@coze-studio/bot-detail-store/multi-agent';
import { useBotInfoStore } from '@coze-studio/bot-detail-store/bot-info';
import {
getBotState,
type WriteableCommandLifeCycleServiceGenerator,
} from '@coze-common/chat-area';
import {
BotMode,
MultiAgentSessionType,
} from '@coze-arch/bot-api/developer_api';
import { type PluginBizContext } from '../../types/biz-context';
export const commandLifeCycleServiceGenerator: WriteableCommandLifeCycleServiceGenerator<
PluginBizContext
> = _ => ({
onAfterClearHistory() {
const {
chatModeConfig,
updatedCurrentAgentIdWithConnectStart,
resetHostAgent,
} = useMultiAgentStore.getState();
const { mode } = useBotInfoStore.getState();
if (mode === BotMode.MultiMode) {
updatedCurrentAgentIdWithConnectStart();
if (chatModeConfig.type === MultiAgentSessionType.Host) {
resetHostAgent();
}
}
},
onAfterStopResponding(ctx) {
const { brokenFlattenMessageGroup: brokenMessages } = ctx;
const { mode } = useBotInfoStore.getState();
const { chatModeConfig, setMultiAgent } = useMultiAgentStore.getState();
if (
mode !== BotMode.MultiMode ||
chatModeConfig.type !== MultiAgentSessionType.Host
) {
return;
}
const hostAgentId = chatModeConfig.currentHostId;
const targetMessage = brokenMessages
?.filter(msg => msg.role === 'assistant' && msg.type === 'answer')
.at(-1);
if (!targetMessage) {
setMultiAgent({ currentAgentID: hostAgentId });
return;
}
const parsedBotState = getBotState(targetMessage.extra_info.bot_state);
if (!parsedBotState?.awaiting) {
setMultiAgent({ currentAgentID: hostAgentId });
return;
}
setMultiAgent({ currentAgentID: parsedBotState.awaiting });
},
});

View File

@@ -0,0 +1,32 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { type WriteableLifeCycleServiceGenerator } from '@coze-common/chat-area';
import { type PluginBizContext } from '../../types/biz-context';
import { renderLifeCycleServiceGenerator } from './render';
import { messageLifeCycleServiceGenerator } from './message';
import { commandLifeCycleServiceGenerator } from './command';
import { appLifeCycleServiceGenerator } from './app';
export const bizLifeCycleServiceGenerator: WriteableLifeCycleServiceGenerator<
PluginBizContext
> = plugin => ({
appLifeCycleService: appLifeCycleServiceGenerator(plugin),
messageLifeCycleService: messageLifeCycleServiceGenerator(plugin),
commandLifeCycleService: commandLifeCycleServiceGenerator(plugin),
renderLifeCycleService: renderLifeCycleServiceGenerator(plugin),
});

View File

@@ -0,0 +1,119 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { useMultiAgentStore } from '@coze-studio/bot-detail-store/multi-agent';
import { useManuallySwitchAgentStore } from '@coze-studio/bot-detail-store';
import {
CODE_JINJA_FORMAT_ERROR,
type WriteableMessageLifeCycleServiceGenerator,
parseErrorInfoFromErrorMessage,
ChatBusinessErrorCode,
getBotState,
} from '@coze-common/chat-area';
import { I18n } from '@coze-arch/i18n';
import { Toast } from '@coze-arch/coze-design';
import { messageReportEvent } from '@coze-arch/bot-utils';
import { CustomError } from '@coze-arch/bot-error';
import {
handleBotStateBeforeSendMessage,
isCreateTaskMessage,
reportReceiveEvent,
sendTeaEventOnBeforeSendMessage,
} from '../../utils';
import { type PluginBizContext } from '../../types/biz-context';
export const messageLifeCycleServiceGenerator: WriteableMessageLifeCycleServiceGenerator<
PluginBizContext
> = plugin => ({
onMessagePullingSuccess() {
messageReportEvent.messageReceiveSuggestsEvent.success();
},
onSendMessageError(ctx) {
const { error: inputError } = ctx;
if (
(inputError as { ext?: { code?: number } }).ext?.code ===
CODE_JINJA_FORMAT_ERROR
) {
Toast.warning(I18n.t('jinja_invalid'));
}
const error =
inputError instanceof Error
? inputError
: new CustomError('normal_error', 'unknow');
const reason = error.message;
messageReportEvent.executeDraftBotEvent.error({ error, reason });
},
onAfterSendMessage() {
messageReportEvent.executeDraftBotEvent.success();
messageReportEvent.receiveMessageEvent.start();
},
onBeforeSendMessage(ctx) {
const { botId, scene } = plugin.pluginBizContext;
messageReportEvent.executeDraftBotEvent.start();
sendTeaEventOnBeforeSendMessage({
message: ctx.message,
from: ctx.from,
botId,
});
const result = handleBotStateBeforeSendMessage(ctx, scene);
return {
...ctx,
...result,
};
},
onBeforeProcessReceiveMessage(ctx) {
const { message } = ctx;
const { pluginBizContext } = plugin;
const {
methods: { refreshTaskList },
} = pluginBizContext;
reportReceiveEvent(message);
// 如果是创建定时任务的消息的话,需要刷新任务列表
if (isCreateTaskMessage(message)) {
refreshTaskList();
}
const botState = getBotState(message.extra_info.bot_state);
const agentId = botState?.agent_id;
if (agentId) {
useManuallySwitchAgentStore.getState().clearAgentId();
useMultiAgentStore.getState().setMultiAgent({ currentAgentID: agentId });
}
return ctx;
},
onMessagePullingError(ctx) {
const errorInfo = parseErrorInfoFromErrorMessage(ctx.error?.message);
if (!errorInfo) {
return;
}
if (errorInfo.code === ChatBusinessErrorCode.SuggestError) {
messageReportEvent.messageReceiveSuggestsEvent.error({
error: ctx.error,
reason: errorInfo.msg,
});
return;
}
messageReportEvent.receiveMessageEvent.error();
},
});

View File

@@ -0,0 +1,23 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { type WriteableRenderLifeCycleServiceGenerator } from '@coze-common/chat-area';
import { type PluginBizContext } from '../../types/biz-context';
export const renderLifeCycleServiceGenerator: WriteableRenderLifeCycleServiceGenerator<
PluginBizContext
> = plugin => ({});

View File

@@ -0,0 +1,25 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { type Scene } from '@coze-common/chat-area';
export interface PluginBizContext {
botId: string;
scene: Scene;
methods: {
refreshTaskList: () => void;
};
}

View File

@@ -0,0 +1,204 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { cloneDeep, merge } from 'lodash-es';
import { usePageRuntimeStore } from '@coze-studio/bot-detail-store/page-runtime';
import { useMultiAgentStore } from '@coze-studio/bot-detail-store/multi-agent';
import {
useBotInfoStore,
type BotInfoStore,
} from '@coze-studio/bot-detail-store/bot-info';
import { useManuallySwitchAgentStore } from '@coze-studio/bot-detail-store';
import {
type OnBeforeSendMessageContext,
Scene,
ContentType,
type Message,
getBotState,
type MessageExtraInfoBotState,
} from '@coze-common/chat-area';
import { messageReportEvent, safeJSONParse } from '@coze-arch/bot-utils';
import {
EVENT_NAMES,
type ParamsTypeDefine,
sendTeaEvent,
} from '@coze-arch/bot-tea';
import { useSpaceStore } from '@coze-arch/bot-studio-store';
import { BotMode } from '@coze-arch/bot-api/developer_api';
import { TrafficScene } from '@coze-arch/bot-api/debugger_api';
export enum MockTrafficEnabled {
DISABLE = 0,
ENABLE = 1,
}
export function getMockSetReqOptions(baseBotInfo: BotInfoStore) {
return {
headers: {
'rpc-persist-mock-traffic-scene':
baseBotInfo.mode === BotMode.MultiMode
? TrafficScene.CozeMultiAgentDebug
: TrafficScene.CozeSingleAgentDebug,
'rpc-persist-mock-traffic-caller-id': baseBotInfo.botId,
'rpc-persist-mock-space-id': baseBotInfo?.space_id,
'rpc-persist-mock-traffic-enable': MockTrafficEnabled.ENABLE,
},
};
}
export const sendTeaEventOnBeforeSendMessage = (params: {
message: Message<ContentType>;
from: string;
botId: string;
}) => {
const { message, from, botId } = params;
const { isSelf } = usePageRuntimeStore.getState();
const teaParam: Omit<
ParamsTypeDefine[EVENT_NAMES.click_send_message],
'from'
> = {
is_user_owned: isSelf ? 'true' : 'false',
message_id: message.extra_info.local_message_id,
bot_id: botId,
};
// 原本逻辑就只在这三个场景 sendTea
if (from === 'inputAndSend') {
sendTeaEvent(EVENT_NAMES.click_send_message, {
from: 'type',
...teaParam,
});
}
if (from === 'regenerate') {
sendTeaEvent(EVENT_NAMES.click_send_message, {
from: 'regenerate',
...teaParam,
});
}
if (from === 'suggestion') {
sendTeaEvent(EVENT_NAMES.click_send_message, {
from: 'welcome_message_suggestion',
...teaParam,
});
}
};
export const handleBotStateBeforeSendMessage = (
params: OnBeforeSendMessageContext,
scene: Scene,
) => {
const { message, options } = params;
const { mode } = useBotInfoStore.getState();
if (scene !== Scene.Playground && mode !== BotMode.MultiMode) {
return;
}
const clonedOptions: typeof options = cloneDeep(options ?? {});
if (scene === Scene.Playground) {
merge(clonedOptions, {
extendFiled: {
space_id: useSpaceStore.getState().getSpaceId(),
},
});
}
if (mode === BotMode.MultiMode) {
updateAgentBeforeSendMessage(params);
const botState = getBotStateBeforeSendMessage();
merge(clonedOptions, {
extendFiled: {
extra: { bot_state: JSON.stringify(botState) },
},
});
}
const baseBotInfo = useBotInfoStore.getState();
merge(clonedOptions, getMockSetReqOptions(baseBotInfo));
return {
message,
options: clonedOptions,
};
};
export const isCreateTaskMessage = (message: Message<ContentType>) => {
if (
typeof message === 'object' &&
message.type === 'tool_response' &&
message.content_type === ContentType.Text
) {
const messageContentObject = safeJSONParse(message.content);
if (
typeof messageContentObject === 'object' &&
messageContentObject.response_for_model === 'Task created successfully'
) {
return true;
}
}
return false;
};
export const reportReceiveEvent = (message: Message<ContentType>) => {
if (message.type === 'follow_up') {
messageReportEvent.messageReceiveSuggestsEvent.receiveSuggest();
return;
}
messageReportEvent.receiveMessageEvent.receiveMessage(message);
if (message.type === 'answer' && message.is_finish) {
messageReportEvent.receiveMessageEvent.finish(message);
messageReportEvent.receiveMessageEvent.start();
}
};
export const updateAgentBeforeSendMessage: (
param: OnBeforeSendMessageContext,
) => void = ({ message, options }) => {
if (!(options?.isRegenMessage && message.role === 'user')) {
return;
}
const {
currentAgentID,
updatedCurrentAgentIdWithConnectStart,
setMultiAgent,
} = useMultiAgentStore.getState();
const regeneratedMessageBotState = getBotState(message.extra_info.bot_state);
// regenerate 消息时 把 currentAgentId 设置为对应 userMessage 的 agentId
const fixedAgentId =
currentAgentID === useManuallySwitchAgentStore.getState().agentId
? currentAgentID
: regeneratedMessageBotState?.agent_id;
if (fixedAgentId) {
setMultiAgent({ currentAgentID: fixedAgentId });
} else {
updatedCurrentAgentIdWithConnectStart();
}
};
export const getBotStateBeforeSendMessage: () => MessageExtraInfoBotState =
() => {
const { botId } = useBotInfoStore.getState();
const { currentAgentID } = useMultiAgentStore.getState();
const botState: MessageExtraInfoBotState = {
agent_id: currentAgentID,
bot_id: botId,
};
return botState;
};