automation-port.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. import {
  2. AutomationCreateLimitError,
  3. hasRelativeDelayMinutes,
  4. isAutomationCreateLimitError,
  5. type AutomationPort,
  6. type CronAutomation,
  7. } from "@zcode/contracts";
  8. import {
  9. parseModelPickerValue,
  10. zcodeAutomationCheckTaskBindingResultSchema,
  11. zcodeAutomationCreateResultSchema,
  12. zcodeAutomationDeleteResultSchema,
  13. zcodeAutomationListResultSchema,
  14. zcodeAutomationUpdateResultSchema,
  15. zcodeProtocolMethods,
  16. type ZCodeAutomationProtocol,
  17. } from "@zcode/shared";
  18. import {
  19. ProtocolRequestError,
  20. type ZCodeProtocolAgentServerContext,
  21. type ZCodeProtocolSessionRecord,
  22. } from "./server-types.js";
  23. export const AUTOMATION_CREATE_FROM_AUTOMATION_RUN_ERROR =
  24. "Cannot create a scheduled task while running a scheduled task.";
  25. export const AUTOMATION_CREATE_IN_BOUND_SESSION_ERROR =
  26. "Cannot create a scheduled task inside a session that already belongs to a scheduled task. " +
  27. "Ask the user to start a new chat to create another scheduled task.";
  28. export const AUTOMATION_CREATE_BOUND_SESSION_CHECK_ERROR =
  29. "Cannot verify whether this session belongs to a scheduled task. Try again later.";
  30. export function createProtocolAutomationPort(
  31. context: ZCodeProtocolAgentServerContext,
  32. // 归属会话解析器:automation-port 是按 session 构造的,直接绑定「自己所服务的 session
  33. // record」。避免依赖 context.sessions 查找——V4/desktop 会话未必登记在该 legacy map 里,
  34. // 之前会导致 activeSession 命中失败、权限/思考等级丢失(模型有 createContext 兜底才幸存)。
  35. resolveOwnSession?: () => ZCodeProtocolSessionRecord | undefined,
  36. ): AutomationPort {
  37. return {
  38. async create(input, createContext) {
  39. // 优先用归属 session(本工具运行所在会话);退回按 createContext.sessionId 查 legacy map。
  40. const activeSession =
  41. resolveOwnSession?.() ??
  42. (createContext?.sessionId ? context.sessions.get(createContext.sessionId) : undefined);
  43. if (activeSession?.activeAutomationId?.trim()) {
  44. // 当前 turn 已经由 automationId 派发;继续 CronCreate 会形成递归定时任务链。
  45. // 这个判断发生在 automation-port 内,命中时不会调用 protocol automation/create。
  46. throw new Error(AUTOMATION_CREATE_FROM_AUTOMATION_RUN_ERROR);
  47. }
  48. // 桌面交互输入直连 CLI(绕过 host adapter 的 toolDenylist 注入),普通用户在
  49. // 一个已归属定时任务的会话里继续输入时,CronCreate 仍被注册且没有 per-turn 过滤,会绕过
  50. // 前面所有守卫再次创建定时任务。这里在创建入口按 targetTaskId 做与入口路径无关的兜底:
  51. // 只要当前会话已经是某个 automation 的绑定会话(= 定时任务会话),就拒绝再次创建;普通会话
  52. // 首次创建时还没有绑定,正常放行。归属判断必须走专用 EXISTS 协议,不能读取完整列表;否则
  53. // 任意历史任务的展示字段损坏都会让当前会话误报“无法验证”。
  54. const ownSessionId = createContext?.sessionId ?? activeSession?.app.sessionId;
  55. if (ownSessionId) {
  56. let bound: boolean;
  57. try {
  58. try {
  59. const result = await context.requestClient(
  60. zcodeProtocolMethods.automationCheckTaskBinding,
  61. { targetTaskId: ownSessionId },
  62. zcodeAutomationCheckTaskBindingResultSchema,
  63. );
  64. bound = result.bound;
  65. } catch (error) {
  66. if (!(error instanceof ProtocolRequestError && error.code === -32601)) {
  67. throw error;
  68. }
  69. // 协议版本仍为 1,新 CLI 连接升级前仍存活或远端的旧 Host 时,专用归属
  70. // 方法会返回 -32601。只有“方法不存在”能证明是能力差异,此时回退旧版列表筛选;
  71. // 数据库、传输和协议错误仍交给外层 fail-closed,不能误判为未绑定。
  72. const legacyResult = await context.requestClient(
  73. zcodeProtocolMethods.automationList,
  74. {},
  75. zcodeAutomationListResultSchema,
  76. );
  77. bound = legacyResult.automations.some(
  78. (automation) => automation.targetTaskId === ownSessionId,
  79. );
  80. }
  81. } catch (error) {
  82. context.logger?.warn("Failed to check bound automations before CronCreate", {
  83. errorMessage: error instanceof Error ? error.message : String(error),
  84. event: "automation.create.bound_session_check.failed",
  85. sessionId: ownSessionId,
  86. });
  87. // 会话归属查询是阻止递归 CronCreate 的授权边界;未知不能等同于未绑定,
  88. // 否则 host / 数据库短暂故障会重新开放创建能力。查询失败必须 fail-closed。
  89. throw new Error(AUTOMATION_CREATE_BOUND_SESSION_CHECK_ERROR);
  90. }
  91. if (bound) {
  92. throw new Error(AUTOMATION_CREATE_IN_BOUND_SESSION_ERROR);
  93. }
  94. }
  95. // CronCreate 的工具上下文只携带了部分配置,导致权限或思考等级在跨层时丢失。
  96. // 协议边界按 sessionId 读取活跃 runtime,确保保存的是用户触发工具当下看到的配置。
  97. // 定时任务只继承会话稳定 Selection:加速卡等单轮执行走 modelExecution
  98. // (selectionScope=execution),从不改写 Session Selection,因此这里读到的一定不是
  99. // turn-only 模型,不需要再区分持久/临时两套读取路径。
  100. const runtimeModelSelection =
  101. activeSession?.app.runtime.getSessionModelSelection() ??
  102. (() => {
  103. try {
  104. return createContext?.model ? parseModelPickerValue(createContext.model) : undefined;
  105. } catch {
  106. return undefined;
  107. }
  108. })();
  109. const runtimeMode = activeSession?.app.getMode();
  110. const hasIntervalCarrier = input.intervalUnit !== undefined && input.interval !== undefined;
  111. let result;
  112. try {
  113. result = await context.requestClient(
  114. zcodeProtocolMethods.automationCreate,
  115. {
  116. // 相对时间不由模型换算绝对时刻;兼容协议仍要求 cronExpr,服务层会用真实时钟覆盖占位值。
  117. // `!== null` 判定会把省略 delayMinutes 的普通 cron 调用误走相对分支,
  118. // 强制 recurring=false;相对任务的唯一口径是 hasRelativeDelayMinutes(显式数字)。
  119. cronExpr: input.cron ?? "* * * * *",
  120. ...(hasRelativeDelayMinutes(input) ? { relativeDelayMinutes: input.delayMinutes } : {}),
  121. prompt: input.prompt,
  122. title: input.title,
  123. recurring: hasRelativeDelayMinutes(input)
  124. ? false
  125. : hasIntervalCarrier
  126. ? true
  127. : (input.recurring ?? true),
  128. // workspace 仍由 protocol server 从当前 session 注入。
  129. ...(runtimeModelSelection ? { modelSelection: runtimeModelSelection } : {}),
  130. ...(runtimeMode ? { mode: runtimeMode === "auto" ? "build" : runtimeMode } : {}),
  131. ...(createContext?.sessionId ? { targetTaskId: createContext.sessionId } : {}),
  132. ...(activeSession?.activeBotDeliveryTarget
  133. ? { botDeliveryTarget: activeSession.activeBotDeliveryTarget }
  134. : {}),
  135. ...(hasIntervalCarrier
  136. ? {
  137. // 新建 carrier 不透传有限上限;create 协议没有 maxRuns=null 清除语义。
  138. intervalUnit: input.intervalUnit,
  139. interval: input.interval,
  140. }
  141. : input.maxRuns !== undefined
  142. ? { maxRuns: input.maxRuns }
  143. : {}),
  144. },
  145. zcodeAutomationCreateResultSchema,
  146. );
  147. } catch (error) {
  148. if (!isAutomationCreateLimitError(error)) throw error;
  149. // 协议错误过去以普通 Error 进入工具循环,模型会把错误里的删除建议当成
  150. // 可执行恢复步骤,继而反复 CronList/CronDelete/CronCreate。映射成稳定领域错误,
  151. // 让 core 能在不依赖 shared 实现的情况下关闭当前 turn 的工具恢复边界。
  152. throw new AutomationCreateLimitError(
  153. error instanceof Error ? error.message : String(error),
  154. error,
  155. );
  156. }
  157. const automation = toCronAutomation(result.automation);
  158. const title = automation.title.trim();
  159. if (activeSession && title.length > 0) {
  160. try {
  161. // 会话内 CronCreate 会在首轮回复中创建 automation,但首条消息触发的
  162. // session_title sidecar 可能迟到并根据助手解释生成标题,导致标题变成“我无法...”。
  163. // CronCreate 成功后把当前会话标题固定为 automation 标题,阻止 generated 标题覆盖。
  164. await activeSession.app.setCustomSessionTitle({
  165. title,
  166. traceContext: activeSession.traceContext,
  167. });
  168. } catch (error) {
  169. context.logger?.warn("Failed to freeze session title after CronCreate", {
  170. errorMessage: error instanceof Error ? error.message : String(error),
  171. event: "automation.session_title_freeze.failed",
  172. sessionId: createContext?.sessionId,
  173. });
  174. }
  175. }
  176. return automation;
  177. },
  178. async update(input) {
  179. const hasIntervalCarrier = input.intervalUnit !== undefined && input.interval !== undefined;
  180. const result = await context.requestClient(
  181. zcodeProtocolMethods.automationUpdate,
  182. {
  183. automationId: input.id,
  184. ...(input.title !== undefined ? { title: input.title } : {}),
  185. ...(input.cron !== undefined ? { cronExpr: input.cron } : {}),
  186. ...(input.prompt !== undefined ? { prompt: input.prompt } : {}),
  187. ...(hasIntervalCarrier
  188. ? {
  189. // 历史一次性任务只透传 carrier 会保留 recurring=false,首次派发后
  190. // 被 repository 标记 completed。carrier 必须在协议边界原子切换为无限循环。
  191. recurring: true,
  192. maxRuns: null,
  193. intervalUnit: input.intervalUnit,
  194. interval: input.interval,
  195. }
  196. : {
  197. ...(input.recurring !== undefined ? { recurring: input.recurring } : {}),
  198. ...(input.maxRuns !== undefined ? { maxRuns: input.maxRuns } : {}),
  199. }),
  200. },
  201. zcodeAutomationUpdateResultSchema,
  202. );
  203. return toCronAutomation(result.automation);
  204. },
  205. async list() {
  206. const result = await context.requestClient(
  207. zcodeProtocolMethods.automationList,
  208. {},
  209. zcodeAutomationListResultSchema,
  210. );
  211. return result.automations.map(toCronAutomation);
  212. },
  213. async delete(input) {
  214. const result = await context.requestClient(
  215. zcodeProtocolMethods.automationDelete,
  216. { automationId: input.id },
  217. zcodeAutomationDeleteResultSchema,
  218. );
  219. return result.deleted;
  220. },
  221. };
  222. }
  223. function normalizeCronAutomationMode(
  224. mode: ZCodeAutomationProtocol["mode"],
  225. ): CronAutomation["mode"] {
  226. switch (mode) {
  227. case undefined:
  228. return undefined;
  229. case "plan":
  230. case "edit":
  231. case "guarded":
  232. case "yolo":
  233. case "build":
  234. return mode;
  235. case "dontAsk":
  236. case "bypassPermissions":
  237. return "yolo";
  238. case "default":
  239. case "auto":
  240. case "acceptEdits":
  241. case "autoEdit":
  242. return "build";
  243. default: {
  244. const exhaustiveMode: never = mode;
  245. return exhaustiveMode;
  246. }
  247. }
  248. }
  249. function toCronAutomation(input: ZCodeAutomationProtocol): CronAutomation {
  250. return {
  251. automationId: input.automationId,
  252. title: input.title,
  253. cronExpr: input.cronExpr,
  254. prompt: input.prompt,
  255. enabled: input.enabled,
  256. lifecycleStatus: input.lifecycleStatus,
  257. nextRunAt: input.nextRunAt,
  258. lastRunAt: input.lastRunAt,
  259. runCount: input.runCount,
  260. recurring: input.recurring,
  261. maxRuns: input.maxRuns,
  262. modelSelection: input.modelSelection,
  263. // 显式按既有 session 权限语义降级,协议以后新增 mode 时由穷尽检查强制同步处理。
  264. mode: normalizeCronAutomationMode(input.mode),
  265. // 透传权威 scheduleRule;会话卡片必须读到本字段才能展示 cron 无法表达的真实间隔
  266. // (如每50小时、每40天),否则只能从兼容 cronExpr 推断出「每小时的第00分」等错误展示。
  267. scheduleRule: input.scheduleRule,
  268. };
  269. }