bots.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930
  1. import { zcodeProtocolTraceSchema, type ZCodeProtocolTrace } from "./zcode-protocol/trace.js";
  2. import { channelContentPartsSchema, type ChannelContentPart } from "./channel-mention.js";
  3. /* oxlint-disable eslint(max-lines) -- Bot 共享合约集中维护 provider、状态和 schema,保持类型与校验就近。 */
  4. import { z } from "zod";
  5. import { modelSelectionSchema, type ModelSelection } from "./model-selection.js";
  6. import { conversationQuotesSchema } from "./conversationSelection.js";
  7. import { ZCODE_AGENT_PROVIDER, ZCODE_AGENT_PROVIDER_LABEL } from "./zcode-agent-policy.js";
  8. import type {
  9. ZCodeConfigOption,
  10. ZCodeElicitationRequest,
  11. ZCodeElicitationQuestion,
  12. ZCodePermissionRequest,
  13. ZCodePromptAttachment,
  14. ZCodeProvider,
  15. ZCodeStreamEvent,
  16. ZCodeTaskMeta,
  17. ZCodeTaskRuntimeStatus,
  18. } from "./zcode-task-types-core.js";
  19. import {
  20. zcodeInteractionRequestOriginSchema,
  21. zcodePermissionResponseSchema,
  22. type ZCodeInteractionRequestOrigin,
  23. type ZCodePermissionResponse,
  24. } from "./zcode-protocol-legacy-types.js";
  25. import type { Locale } from "./protocol.js";
  26. export const botProviders = [
  27. "telegram",
  28. "webhook",
  29. "feishu",
  30. "lark",
  31. "weixin",
  32. "discord",
  33. "wecom",
  34. ] as const;
  35. export type BotProvider = (typeof botProviders)[number];
  36. export type FeishuBotProvider = Extract<BotProvider, "feishu" | "lark">;
  37. /**
  38. * 定时任务完成后的 Bot 回推目标。只保留未来仍稳定的会话地址;当前消息 id/context token
  39. * 属于一次入站交互,不能持久化后复用。该字段由 Host 注入,模型工具参数不直接暴露。
  40. */
  41. export const zcodeAutomationBotDeliveryTargetSchema = z
  42. .object({
  43. provider: z.enum(["feishu", "lark", "weixin"]),
  44. botId: z.string().trim().min(1),
  45. providerUserId: z.string().trim().min(1),
  46. chatType: z.enum(["private", "group"]),
  47. threadId: z.string().min(1).optional(),
  48. rootMessageId: z.string().min(1).optional(),
  49. })
  50. .strict();
  51. export type ZCodeAutomationBotDeliveryTarget = z.infer<
  52. typeof zcodeAutomationBotDeliveryTargetSchema
  53. >;
  54. export function isFeishuBotProvider(provider: BotProvider): provider is FeishuBotProvider {
  55. return provider === "feishu" || provider === "lark";
  56. }
  57. export type BotContextMode = "draft" | "task";
  58. export type BotReplyGranularity =
  59. | "assistant_changes"
  60. | "assistant_toolcalls_changes"
  61. | "summary_changes"
  62. | "streaming_card";
  63. export const BOT_REPLY_GRANULARITIES = [
  64. "assistant_changes",
  65. "assistant_toolcalls_changes",
  66. "summary_changes",
  67. "streaming_card",
  68. ] as const satisfies readonly BotReplyGranularity[];
  69. export const ALL_BOT_WORKSPACES = "*";
  70. export const BOT_BIND_CODE_TTL_MS = 30_000;
  71. export interface BotWorkspaceRef {
  72. id: string;
  73. label: string;
  74. workspacePath: string;
  75. workspaceIdentity?: string;
  76. }
  77. export interface BotAllowedCommands {
  78. status: boolean;
  79. new: boolean;
  80. workspace: boolean;
  81. model: boolean;
  82. mode?: boolean;
  83. thoughtLevel: boolean;
  84. sandboxMode?: boolean;
  85. approvalPolicy?: boolean;
  86. reply: boolean;
  87. }
  88. export type BotCommandPolicy = BotAllowedCommands;
  89. export interface BotCurrentOptions {
  90. modelSelection?: ModelSelection;
  91. mode?: string;
  92. sandboxMode?: string;
  93. approvalPolicy?: string;
  94. }
  95. export type BotReplyMode = BotReplyGranularity;
  96. export interface BotConfig {
  97. id: string;
  98. name: string;
  99. provider: BotProvider;
  100. enabled: boolean;
  101. credentialRef?: string;
  102. webhookSecretRef?: string;
  103. webhookUrl?: string;
  104. webhookAuthHeaderName?: string;
  105. feishuAppId?: string;
  106. providerUserId?: string;
  107. displayName?: string;
  108. allowedWorkspaces: string[];
  109. allowedCommands: BotAllowedCommands;
  110. currentOptions: BotCurrentOptions;
  111. replyMode: BotReplyMode;
  112. }
  113. export interface BotPendingPermissionOption {
  114. requestId: string;
  115. optionId: string;
  116. command: "approve" | "deny";
  117. label: string;
  118. response: ZCodePermissionResponse;
  119. handledAt?: number;
  120. }
  121. export interface BotPendingElicitation {
  122. taskId: string;
  123. requestId: string;
  124. runId: string;
  125. origin?: ZCodeInteractionRequestOrigin;
  126. actorKey?: string;
  127. currentQuestionIndex: number;
  128. questions: ZCodeElicitationQuestion[];
  129. answers: Record<string, string[]>;
  130. renderContext?: {
  131. kind: "plan_approval";
  132. plan: string;
  133. };
  134. expandedCustomAnswerQuestionIndexes?: number[];
  135. handledAt?: number;
  136. }
  137. export interface BotStructuredElicitationResponse {
  138. requestId: string;
  139. action: "accept" | "decline" | "cancel";
  140. content?: Record<string, unknown>;
  141. }
  142. export interface BotOutboundElicitationRequest {
  143. requestId: string;
  144. taskId: string;
  145. runId: string;
  146. currentQuestionIndex: number;
  147. questions: ZCodeElicitationQuestion[];
  148. answers?: Record<string, string[]>;
  149. status?: "pending" | "completed" | "cancelled";
  150. expandedCustomAnswerQuestionIndexes?: number[];
  151. schema?: unknown;
  152. }
  153. export interface BotDraftOptions {
  154. provider: ZCodeProvider;
  155. modelSelection?: ModelSelection;
  156. mode?: string;
  157. }
  158. export interface BotsConfigFile {
  159. version: 3;
  160. bots: BotConfig[];
  161. }
  162. export interface BotState {
  163. botId: string;
  164. group?: BotGroupSession;
  165. workspacePath: string;
  166. workspaceIdentity?: string;
  167. workspaceId?: string;
  168. mode: BotContextMode;
  169. activeTaskId: string | null;
  170. draftOptions?: BotDraftOptions;
  171. pendingPermissionOptions?: BotPendingPermissionOption[];
  172. pendingElicitation?: BotPendingElicitation;
  173. telegramOffset?: number;
  174. weixinGetUpdatesBuf?: string;
  175. weixinActivatedAt?: number;
  176. /** 单聊绑定代际,阻止换绑后迟到事件恢复旧关联。 */
  177. privateBindingId?: string;
  178. /** iLink 登录返回机器人身份,单聊接收人来自已授权入站消息。 */
  179. privateRecipientId?: string;
  180. updatedAt: number;
  181. }
  182. export type BotContextState = BotState;
  183. export const botGroupDeliverySchema = z
  184. .object({
  185. /** 名字解析前的请求指纹;重复调用只读原回执,不因目录变化改发给其他人。 */
  186. channelReplyRequestHash: z
  187. .string()
  188. .regex(/^[a-f0-9]{64}$/u)
  189. .optional(),
  190. appId: z.string().optional(),
  191. trace: zcodeProtocolTraceSchema.optional(),
  192. authorizationId: z.string().optional(),
  193. id: z.string().min(1),
  194. taskId: z.string().min(1),
  195. sourceCommandId: z.string().min(1).optional(),
  196. text: z.string(),
  197. replyToMessageId: z.string().optional(),
  198. mentionedUserIds: z.array(z.string().min(1)).max(200).optional(),
  199. contentParts: channelContentPartsSchema.optional(),
  200. providerMessageId: z.string().optional(),
  201. threadId: z.string().min(1).optional(),
  202. rootMessageId: z.string().optional(),
  203. status: z.enum(["pending", "sent", "failed", "unknown", "invalidated"]),
  204. lastError: z.string().optional(),
  205. updatedAt: z.number(),
  206. })
  207. .strict();
  208. export type BotGroupDelivery = z.infer<typeof botGroupDeliverySchema>;
  209. export const botGroupCardSchema = z
  210. .object({
  211. chatId: z.string().min(1),
  212. threadId: z.string().min(1).optional(),
  213. conversationThreadId: z.string().min(1).nullable().optional(),
  214. taskId: z.string().nullable(),
  215. authorizationId: z.string().min(1),
  216. })
  217. .strict();
  218. export type BotGroupCard = z.infer<typeof botGroupCardSchema>;
  219. export const botTopicMessageSchema = z
  220. .object({
  221. id: z.string().min(1),
  222. chatId: z.string().min(1),
  223. threadId: z.string().min(1),
  224. senderId: z.string(),
  225. senderName: z.string().optional(),
  226. parentId: z.string().optional(),
  227. attachments: z.array(z.object({ name: z.string(), kind: z.string() }).strict()).optional(),
  228. senderType: z.enum(["user", "app"]),
  229. text: z.string(),
  230. createdAt: z.number(),
  231. kind: z.string(),
  232. controlCard: z.boolean().optional(),
  233. deleted: z.boolean().optional(),
  234. })
  235. .strict();
  236. export type BotTopicMessage = z.infer<typeof botTopicMessageSchema>;
  237. export interface BotTopicHistoryRequest {
  238. chatId: string;
  239. threadId: string;
  240. rootMessageId: string;
  241. messageId: string;
  242. checkpoint?: string;
  243. }
  244. export const botTopicContextSchema = z
  245. .object({
  246. messages: z.array(botTopicMessageSchema).max(201),
  247. checkpoint: z.string().min(1),
  248. hasGap: z.boolean(),
  249. })
  250. .strict();
  251. export type BotTopicHistoryBatch = z.infer<typeof botTopicContextSchema>;
  252. export const botIdentitySchema = z
  253. .object({ name: z.string().min(1), openId: z.string().min(1).optional() })
  254. .strict();
  255. export const botBackgroundHistorySchema = z
  256. .object({ revision: z.string().min(1), checkpoint: z.string().min(1).optional() })
  257. .strict();
  258. export const botAutoReplyGuardSchema = z
  259. .object({
  260. consecutive: z.number().int().min(0).max(5),
  261. messageIds: z.array(z.string().min(1)),
  262. })
  263. .strict();
  264. export interface BotGroupSession {
  265. preparation?: BotTopicPreparation[];
  266. chatId: string;
  267. chatMode?: "group" | "topic";
  268. threadId?: string;
  269. rootMessageId?: string;
  270. topicTitle?: string;
  271. topicUrl?: string;
  272. /** 仅群默认记录拥有此配置;话题按群授权检查读取。 */
  273. historyEnabled?: boolean;
  274. /** 仅成功接收首次输入后接入;leave 后保留任务但停止普通消息触发。 */
  275. topicActive?: boolean;
  276. topicAliases?: Record<string, { taskId: string; rootMessageId: string }>;
  277. name: string;
  278. ownerId: string;
  279. enabled: boolean;
  280. taskIds: string[];
  281. taskWorkspaces?: Record<string, { workspacePath: string; workspaceIdentity?: string }>;
  282. currentOptions: BotCurrentOptions;
  283. initiatorId?: string;
  284. authorizationId?: string;
  285. deliveries?: Record<string, BotGroupDelivery>;
  286. autoReplyGuard?: z.infer<typeof botAutoReplyGuardSchema>;
  287. backgroundHistory?: z.infer<typeof botBackgroundHistorySchema>;
  288. inputs?: Record<
  289. string,
  290. {
  291. taskId: string;
  292. source: BotGroupInputSource;
  293. admission?: "pending" | "accepted" | "rejected";
  294. progress?: BotGroupInputProgress;
  295. }
  296. >;
  297. }
  298. export const botGroupInputStatusSchema = z.enum([
  299. "waiting",
  300. "working",
  301. "done",
  302. "failed",
  303. "stopped",
  304. "cancelled",
  305. "discarded",
  306. ]);
  307. export type BotGroupInputStatus = z.infer<typeof botGroupInputStatusSchema>;
  308. export const botTopicPreparationSchema = z
  309. .object({
  310. contentParts: channelContentPartsSchema.optional(),
  311. messageId: z.string().min(1),
  312. senderName: z.string(),
  313. text: z.string(),
  314. status: z.enum(["preparing", "waitingStop", "failed"]),
  315. error: z.string().optional(),
  316. })
  317. .strict();
  318. export type BotTopicPreparation = z.infer<typeof botTopicPreparationSchema>;
  319. export const botGroupInputProgressSchema = z
  320. .object({
  321. status: botGroupInputStatusSchema,
  322. interruptionReason: z.literal("newMessage").optional(),
  323. cardMessageId: z.string().min(1).optional(),
  324. cardStatus: botGroupInputStatusSchema.optional(),
  325. })
  326. .strict();
  327. export type BotGroupInputProgress = z.infer<typeof botGroupInputProgressSchema>;
  328. /** CLI 只接收轻量材料索引;原文留在 Host 归档及文本附件。 */
  329. export const botTopicHistorySourceSchema = z
  330. .object({
  331. checkpoint: z.string().min(1).max(256),
  332. hasGap: z.boolean(),
  333. messageCount: z.number().int().min(0).max(201),
  334. resourceMessages: z
  335. .array(
  336. z
  337. .object({
  338. messageId: z.string().min(1).max(256),
  339. count: z.number().int().min(1).max(1000),
  340. })
  341. .strict(),
  342. )
  343. .max(201),
  344. })
  345. .strict();
  346. export const botTopicInputMessageSchema = z
  347. .object({
  348. contentParts: channelContentPartsSchema.optional(),
  349. messageId: z.string().min(1),
  350. senderId: z.string().min(1),
  351. senderName: z.string(),
  352. mentionedBot: z.boolean().optional(),
  353. text: z.string(),
  354. conversationQuotes: conversationQuotesSchema.optional(),
  355. attachmentIndexes: z.array(z.number().int().nonnegative()),
  356. })
  357. .strict();
  358. /** 可信 Host 注入的输入来源;身份展示不能反向授予执行权限。 */
  359. export const botGroupInputSourceSchema = z
  360. .object({
  361. botIdentity: botIdentitySchema.optional(),
  362. appId: z.string().min(1).optional(),
  363. contentParts: channelContentPartsSchema.optional(),
  364. authorizationId: z.string().min(1).optional(),
  365. botId: z.string().min(1),
  366. provider: z.enum(["feishu", "lark"]),
  367. chatId: z.string().min(1),
  368. threadId: z.string().min(1).optional(),
  369. rootMessageId: z.string().optional(),
  370. senderId: z.string().min(1),
  371. senderName: z.string(),
  372. mentionedBot: z.boolean().optional(),
  373. messageId: z.string().min(1),
  374. messages: z.array(botTopicInputMessageSchema).min(1).max(200).optional(),
  375. topicContext: botTopicContextSchema.optional(),
  376. topicHistory: botTopicHistorySourceSchema.optional(),
  377. })
  378. .strict()
  379. .superRefine((source, ctx) => {
  380. if (
  381. source.messages &&
  382. (!source.threadId ||
  383. source.messages.at(-1)?.messageId !== source.messageId ||
  384. new Set(source.messages.map((message) => message.messageId)).size !==
  385. source.messages.length)
  386. ) {
  387. ctx.addIssue({
  388. code: "custom",
  389. path: ["messages"],
  390. message: "Topic batch boundary mismatch",
  391. });
  392. }
  393. if (
  394. source.topicHistory &&
  395. (!source.threadId || source.topicHistory.checkpoint !== source.messageId)
  396. ) {
  397. ctx.addIssue({
  398. code: "custom",
  399. path: ["topicHistory"],
  400. message: "Topic history scope mismatch",
  401. });
  402. }
  403. if (
  404. source.topicContext &&
  405. (!source.threadId ||
  406. source.topicContext.checkpoint !== source.messageId ||
  407. source.topicContext.messages.some(
  408. (m) => m.chatId !== source.chatId || m.threadId !== source.threadId,
  409. ))
  410. )
  411. ctx.addIssue({
  412. code: "custom",
  413. path: ["topicContext"],
  414. message: "Topic context scope mismatch",
  415. });
  416. });
  417. export type BotGroupInputSource = z.infer<typeof botGroupInputSourceSchema>;
  418. export interface BotsStateFile {
  419. version: 3;
  420. bots: Record<string, BotState>;
  421. }
  422. export interface BotRuntimeInfo {
  423. /** 最近一次消息投递错误;独立于长连接状态,成功投递后清除。 */
  424. deliveryError?: string;
  425. /** 当前进程保留的失败单聊回复;显式重试可能重复此前已收到的内容。 */
  426. deliveryRetryId?: string;
  427. botId: string;
  428. provider: BotProvider;
  429. status: "disabled" | "idle" | "polling" | "connected" | "error";
  430. messageId?: string;
  431. message?: string;
  432. lastUpdateAt?: number;
  433. offset?: number;
  434. }
  435. export interface BotActor {
  436. /** 本次可信输入是否明确提及机器人;用于话题回复提醒。 */
  437. mentionedBot?: boolean;
  438. provider: BotProvider;
  439. botId: string;
  440. providerUserId: string;
  441. displayName?: string;
  442. chatType: "private" | "group";
  443. chatId?: string;
  444. threadId?: string;
  445. /** 仅服务根据已保存的结果关联设置;null 表示原群默认任务。 */
  446. conversationThreadId?: string | null;
  447. rootMessageId?: string;
  448. topicTitle?: string;
  449. topicUrl?: string;
  450. providerMessageId?: string;
  451. providerContextToken?: string;
  452. }
  453. export type BotInboundAttachmentKind = "image" | "audio" | "video" | "file";
  454. export interface BotInboundAttachment {
  455. id: string;
  456. kind: BotInboundAttachmentKind;
  457. filename: string;
  458. mimeType: string;
  459. sizeBytes?: number;
  460. providerFileId?: string;
  461. downloadUrl?: string;
  462. dataBase64?: string;
  463. localPath?: string;
  464. providerMetadata?: Record<string, string>;
  465. }
  466. export type BotCommand =
  467. | { type: "group.history"; enabled?: boolean }
  468. | { type: "queue.cancel"; commandId: string }
  469. | { type: "group.enable" }
  470. | { type: "group.disable" }
  471. | { type: "bind"; code: string }
  472. | { type: "help" }
  473. | { type: "status" }
  474. | { type: "new" }
  475. | { type: "reconnect" }
  476. | { type: "workspace.list" }
  477. | { type: "workspace.set"; value: string }
  478. | { type: "model.list" }
  479. | { type: "model.provider.set"; value: string }
  480. | { type: "model.set"; value: string }
  481. | { type: "mode.list" }
  482. | { type: "mode.set"; value: string }
  483. | { type: "thoughtLevel.list" }
  484. | { type: "thoughtLevel.set"; value: string }
  485. | { type: "task.list" }
  486. | { type: "task.set"; value: string }
  487. | { type: "reply.list" }
  488. | { type: "reply.set"; value: string }
  489. | { type: "stop" }
  490. | { type: "topic.leave" }
  491. | { type: "permission.respond"; value: string }
  492. | { type: "elicitation.respond"; value: string }
  493. | { type: "elicitation.submit" }
  494. | { type: "approve"; requestId: string; optionId: string }
  495. | { type: "deny"; requestId: string }
  496. | { type: "unknown"; name: string; raw: string }
  497. | { type: "selection.cancel" }
  498. | { type: "message"; text: string };
  499. export interface SelectionPrompt {
  500. id: string;
  501. token?: string;
  502. title: string;
  503. currentId?: string;
  504. cancelLabel?: string;
  505. showCancel?: boolean;
  506. action:
  507. | "queue.cancel"
  508. | "workspace.set"
  509. | "model.provider.set"
  510. | "model.set"
  511. | "mode.set"
  512. | "thoughtLevel.set"
  513. | "task.set"
  514. | "reply.set"
  515. | "permission.respond"
  516. | "elicitation.respond";
  517. options: Array<{
  518. id: string;
  519. label: string;
  520. description?: string;
  521. }>;
  522. }
  523. export interface BotInboundMessage {
  524. /** 仅供命令/纯唤醒识别;原文 text 和 contentParts 保持完整。 */
  525. commandText?: string;
  526. /** Provider 核验的当前机器人身份,不从正文推断。 */
  527. botOpenId?: string;
  528. /** Provider 校验的发送者类型;机器人正文不具有控制命令权限。 */
  529. senderType?: "user" | "app";
  530. contentParts?: ChannelContentPart[];
  531. /** 由 Provider 根据真实 mention 身份设置;不是正文解析结果。 */
  532. mentionedBot?: boolean;
  533. /** 原生根消息经 Provider 核验确为当前机器人发送。 */
  534. topicRootIsCurrentBot?: boolean;
  535. /** 可信 Provider 校验后的明确引用,不参与控制命令解析。 */
  536. referencedMessage?: import("./conversationSelection.js").ConversationSelectionText & {
  537. messageId: string;
  538. };
  539. groupCard?: BotGroupCard;
  540. groupCardAction?: boolean;
  541. botId: string;
  542. actor: BotActor;
  543. text: string;
  544. attachments?: BotInboundAttachment[];
  545. elicitationResponse?: BotStructuredElicitationResponse;
  546. receivedAt?: number;
  547. }
  548. export interface BotOutboundMessage {
  549. trace?: ZCodeProtocolTrace;
  550. contentParts?: ChannelContentPart[];
  551. groupCard?: BotGroupCard;
  552. threadId?: string;
  553. conversationThreadId?: string | null;
  554. rootMessageId?: string;
  555. botId: string;
  556. provider: BotProvider;
  557. providerUserId: string;
  558. text: string;
  559. locale?: Locale;
  560. selection?: SelectionPrompt;
  561. elicitation?: BotOutboundElicitationRequest;
  562. providerContextToken?: string;
  563. /** 无权限/过期回调只能提示操作者,不能覆盖群共享卡片。 */
  564. callbackToastOnly?: boolean;
  565. /** 管理员待办独立通知,不允许用拒绝提示覆盖共享卡片。 */
  566. administratorAttention?: boolean;
  567. replyToMessageId?: string;
  568. /** 可信输入决定的提醒对象;只作展示,不授予群操作权限。 */
  569. mentionedUserIds?: string[];
  570. deliveryId?: string;
  571. /** 任务回推需在实际发送前重新验证群当前关联。控制命令回复不携带。 */
  572. groupTaskId?: string;
  573. /** 可信任务事件中的输入命令,用于将投递状态定位到对应回复。 */
  574. groupSourceCommandId?: string;
  575. }
  576. export interface BotTaskSummary {
  577. taskId: string;
  578. title: string;
  579. status: ZCodeTaskRuntimeStatus | "persisted-completed" | "persisted-error" | "unknown";
  580. workspacePath: string;
  581. workspaceIdentity?: string;
  582. provider?: ZCodeProvider;
  583. model?: string;
  584. }
  585. export const BOT_TASK_BROADCAST_CHANNEL = "bots:task";
  586. export const BOT_TASK_STREAM_BROADCAST_CHANNEL = "bots:task-stream";
  587. export type BotTaskBroadcastEvent =
  588. | "created"
  589. | "prompt_sent"
  590. | "resumed"
  591. | "streaming"
  592. | "permission_request"
  593. | "permission_resolved"
  594. | "elicitation_request"
  595. | "elicitation_resolved"
  596. | "updated"
  597. | "completed"
  598. | "error";
  599. export interface BotTaskBroadcastPayload {
  600. workspacePath: string;
  601. workspaceIdentity?: string;
  602. taskId: string;
  603. event: BotTaskBroadcastEvent;
  604. updatedAt: number;
  605. task?: ZCodeTaskMeta;
  606. provider?: ZCodeProvider;
  607. configOptions?: ZCodeConfigOption[];
  608. prompt?: {
  609. content: string;
  610. attachments?: ZCodePromptAttachment[];
  611. messageId: string;
  612. sentAt: number;
  613. };
  614. permissionRequest?: ZCodePermissionRequest;
  615. elicitationRequest?: ZCodeElicitationRequest;
  616. requestId?: string;
  617. error?: string;
  618. }
  619. export interface BotTaskStreamBroadcastPayload {
  620. workspacePath: string;
  621. workspaceIdentity?: string;
  622. taskId: string;
  623. event: ZCodeStreamEvent;
  624. updatedAt: number;
  625. }
  626. export interface BotServiceStatus {
  627. botsCount: number;
  628. enabledBotsCount: number;
  629. contextsCount: number;
  630. botRuntime: BotRuntimeInfo[];
  631. }
  632. export interface BotProviderCallbackResult {
  633. ok: boolean;
  634. replies: BotOutboundMessage[];
  635. responseBody?: unknown;
  636. status?: number;
  637. }
  638. export const botAllowedCommandsSchema = z
  639. .object({
  640. status: z.boolean(),
  641. new: z.boolean(),
  642. workspace: z.boolean(),
  643. model: z.boolean(),
  644. mode: z.boolean().optional(),
  645. thoughtLevel: z.boolean(),
  646. sandboxMode: z.boolean().optional(),
  647. approvalPolicy: z.boolean().optional(),
  648. // 兼容旧 bot-config.json;/cli 命令已移除,新配置不会再写入这个字段。
  649. cli: z.boolean().optional(),
  650. reply: z.boolean(),
  651. })
  652. .strict();
  653. export const botCommandPolicySchema = botAllowedCommandsSchema;
  654. // 修复原因:第三方 CLI provider 已移除,ZCodeProvider 只剩 glm,但旧 bot 配置与状态文件里可能仍存有
  655. // 已移除 provider 的历史值。改成严格 literal 会让整份文件 parse 失败、Bot 全部不可用;
  656. // 因此解析时继续接受这些历史值,并统一归一到当前唯一的 agent provider。
  657. const legacyBotAgentProviderSchema = z
  658. .enum(["codex", "claude", "opencode", "gemini", "glm"])
  659. .transform((): typeof ZCODE_AGENT_PROVIDER => ZCODE_AGENT_PROVIDER);
  660. export const botCurrentOptionsSchema = z
  661. .object({
  662. modelSelection: modelSelectionSchema.optional(),
  663. mode: z.string().min(1).optional(),
  664. sandboxMode: z.string().min(1).optional(),
  665. approvalPolicy: z.string().min(1).optional(),
  666. // 兼容旧 bot-config.json;CLI provider 现在统一由 ZCode Protocol 侧配置决定。
  667. cli: legacyBotAgentProviderSchema.optional(),
  668. })
  669. .strict();
  670. export const botDraftOptionsSchema = z
  671. .object({
  672. provider: legacyBotAgentProviderSchema,
  673. modelSelection: modelSelectionSchema.optional(),
  674. mode: z.string().min(1).optional(),
  675. })
  676. .strict();
  677. const botElicitationOptionSchema = z
  678. .object({
  679. value: z.string(),
  680. label: z.string(),
  681. description: z.string().optional(),
  682. })
  683. .strict();
  684. const botElicitationQuestionSchema = z
  685. .object({
  686. question: z.string(),
  687. header: z.string(),
  688. options: z.array(botElicitationOptionSchema),
  689. multiSelect: z.boolean().optional(),
  690. })
  691. .strict();
  692. const botPendingElicitationSchema = z
  693. .object({
  694. taskId: z.string().min(1),
  695. requestId: z.string().min(1),
  696. runId: z.string().min(1),
  697. origin: zcodeInteractionRequestOriginSchema.optional(),
  698. actorKey: z.string().min(1).optional(),
  699. currentQuestionIndex: z.number().int().min(0),
  700. questions: z.array(botElicitationQuestionSchema),
  701. answers: z.record(z.string(), z.array(z.string())),
  702. renderContext: z
  703. .object({
  704. kind: z.literal("plan_approval"),
  705. plan: z.string().min(1),
  706. })
  707. .strict()
  708. .optional(),
  709. expandedCustomAnswerQuestionIndexes: z.array(z.number().int().min(0)).optional(),
  710. handledAt: z.number().optional(),
  711. })
  712. .strict();
  713. export const botConfigSchema = z
  714. .object({
  715. id: z.string().min(1),
  716. name: z.string(),
  717. provider: z.enum(botProviders),
  718. enabled: z.boolean(),
  719. credentialRef: z.string().min(1).optional(),
  720. webhookSecretRef: z.string().min(1).optional(),
  721. webhookUrl: z.string().url().optional(),
  722. webhookAuthHeaderName: z.string().min(1).optional(),
  723. feishuAppId: z.string().min(1).optional(),
  724. providerUserId: z.string().min(1).optional(),
  725. displayName: z.string().optional(),
  726. allowedWorkspaces: z.array(z.string().min(1)),
  727. allowedCommands: botAllowedCommandsSchema,
  728. currentOptions: botCurrentOptionsSchema,
  729. replyMode: z.enum([
  730. "assistant_changes",
  731. "assistant_toolcalls_changes",
  732. "summary_changes",
  733. "streaming_card",
  734. ]),
  735. })
  736. .strict();
  737. export const botsConfigFileSchema = z
  738. .object({
  739. version: z.literal(3),
  740. bots: z.array(botConfigSchema),
  741. })
  742. .strict();
  743. export const botsStateFileSchema = z
  744. .object({
  745. version: z.literal(3),
  746. bots: z.record(
  747. z.string(),
  748. z.object({
  749. botId: z.string().min(1),
  750. group: z
  751. .object({
  752. chatId: z.string().trim().min(1),
  753. chatMode: z.enum(["group", "topic"]).optional(),
  754. threadId: z.string().trim().min(1).optional(),
  755. rootMessageId: z.string().min(1).optional(),
  756. topicTitle: z.string().optional(),
  757. topicUrl: z.string().url().optional(),
  758. historyEnabled: z.boolean().optional(),
  759. topicActive: z.boolean().optional(),
  760. preparation: z.array(botTopicPreparationSchema).optional(),
  761. topicAliases: z
  762. .record(
  763. z.string(),
  764. z.object({ taskId: z.string().min(1), rootMessageId: z.string().min(1) }).strict(),
  765. )
  766. .optional(),
  767. name: z.string(),
  768. ownerId: z.string().min(1),
  769. enabled: z.boolean(),
  770. taskIds: z.array(z.string().min(1)),
  771. taskWorkspaces: z
  772. .record(
  773. z.string(),
  774. z
  775. .object({
  776. workspacePath: z.string().min(1),
  777. workspaceIdentity: z.string().optional(),
  778. })
  779. .strict(),
  780. )
  781. .optional(),
  782. currentOptions: botCurrentOptionsSchema,
  783. initiatorId: z.string().optional(),
  784. authorizationId: z.string().optional(),
  785. deliveries: z.record(z.string(), botGroupDeliverySchema).optional(),
  786. autoReplyGuard: botAutoReplyGuardSchema.optional(),
  787. backgroundHistory: botBackgroundHistorySchema.optional(),
  788. inputs: z
  789. .record(
  790. z.string(),
  791. z
  792. .object({
  793. taskId: z.string().min(1),
  794. source: botGroupInputSourceSchema,
  795. admission: z.enum(["pending", "accepted", "rejected"]).optional(),
  796. progress: botGroupInputProgressSchema.optional(),
  797. })
  798. .strict(),
  799. )
  800. .optional(),
  801. })
  802. .strict()
  803. .optional(),
  804. workspacePath: z.string().min(1),
  805. workspaceIdentity: z.string().min(1).optional(),
  806. workspaceId: z.string().min(1).optional(),
  807. mode: z.enum(["draft", "task"]),
  808. activeTaskId: z.string().min(1).nullable(),
  809. draftOptions: botDraftOptionsSchema.optional(),
  810. pendingPermissionOptions: z
  811. .array(
  812. z.object({
  813. requestId: z.string().min(1),
  814. optionId: z.string().min(1),
  815. command: z.enum(["approve", "deny"]),
  816. label: z.string().min(1),
  817. response: zcodePermissionResponseSchema,
  818. handledAt: z.number().optional(),
  819. }),
  820. )
  821. .optional(),
  822. pendingElicitation: botPendingElicitationSchema.optional(),
  823. telegramOffset: z.number().optional(),
  824. weixinGetUpdatesBuf: z.string().optional(),
  825. weixinActivatedAt: z.number().optional(),
  826. privateBindingId: z.string().min(1).optional(),
  827. privateRecipientId: z.string().min(1).optional(),
  828. updatedAt: z.number(),
  829. }),
  830. ),
  831. })
  832. .strict();
  833. export const DEFAULT_BOT_COMMANDS: BotAllowedCommands = {
  834. status: true,
  835. new: true,
  836. workspace: true,
  837. model: true,
  838. mode: true,
  839. thoughtLevel: true,
  840. reply: true,
  841. };
  842. export const DEFAULT_BOT_REPLY_GRANULARITY: BotReplyGranularity = "assistant_changes";
  843. export function getSupportedBotReplyGranularities(
  844. provider: BotProvider,
  845. ): readonly BotReplyGranularity[] {
  846. return isFeishuBotProvider(provider)
  847. ? (["streaming_card"] as const)
  848. : BOT_REPLY_GRANULARITIES.filter(
  849. // Bugfix: streaming card 依赖 Feishu/Lark Card JSON 2.0,其他 channel 无法渲染或更新该消息形态。
  850. (granularity) => granularity !== "streaming_card",
  851. );
  852. }
  853. export function normalizeBotReplyGranularity(
  854. provider: BotProvider,
  855. replyMode: BotReplyGranularity | undefined,
  856. ): BotReplyGranularity {
  857. const supported = getSupportedBotReplyGranularities(provider);
  858. const candidate = replyMode ?? DEFAULT_BOT_REPLY_GRANULARITY;
  859. return supported.includes(candidate) ? candidate : supported[0]!;
  860. }
  861. export const BOT_ZCODE_PROVIDER_OPTIONS: Array<{
  862. id: ZCodeProvider;
  863. label: string;
  864. }> = [{ id: ZCODE_AGENT_PROVIDER, label: ZCODE_AGENT_PROVIDER_LABEL }];