@xopcai/xopc 0.0.484 → 0.0.486

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (206) hide show
  1. package/dist/browser-ext/manifest.json +1 -1
  2. package/dist/extensions/telegram/src/inbound-processor.js +4 -6
  3. package/dist/extensions/telegram/xopc.extension.json +1 -1
  4. package/dist/extensions/weixin/src/messaging/process-message.js +2 -1
  5. package/dist/gateway/server/chunks.bin +1166 -1121
  6. package/dist/gateway/server/chunks.json +1 -1
  7. package/dist/gateway/static/root/assets/agent-run-error-parser-DsXmcKt-.js +1 -0
  8. package/dist/gateway/static/root/assets/{api-CGs641OT.js → api-CGrHK9ij.js} +1 -1
  9. package/dist/gateway/static/root/assets/{apps-page-CH9wENBj.js → apps-page-6xeWvMpF.js} +1 -1
  10. package/dist/gateway/static/root/assets/{automations-page-B1Ri4sh8.js → automations-page-BLFBqaPX.js} +1 -1
  11. package/dist/gateway/static/root/assets/{automations-workspace-CNSza6ir.js → automations-workspace-DiO3Iyuj.js} +2 -2
  12. package/dist/gateway/static/root/assets/{capabilities-abgigXV1.js → capabilities-CW-vdkz6.js} +1 -1
  13. package/dist/gateway/static/root/assets/{capabilities-BaKHutgZ.js → capabilities-DZrjA95P.js} +1 -1
  14. package/dist/gateway/static/root/assets/capabilities-page-DQrfkrBA.js +2 -0
  15. package/dist/gateway/static/root/assets/{capabilities-settings-panel-BOwbZn9X.js → capabilities-settings-panel-DIT2dvtc.js} +1 -1
  16. package/dist/gateway/static/root/assets/{channels-DlnXbcOj.js → channels-Dcr5dgqw.js} +1 -1
  17. package/dist/gateway/static/root/assets/{chat-page-LOR5JxDh.js → chat-page-DWZCzxY7.js} +31 -31
  18. package/dist/gateway/static/root/assets/{chat-terminal-dock-DE8j-K9d.js → chat-terminal-dock-DCUuwiTt.js} +1 -1
  19. package/dist/gateway/static/root/assets/command-palette-api-UrqPvWR1.js +1 -0
  20. package/dist/gateway/static/root/assets/composer-payload-handoff-a0quQ25p.js +1 -0
  21. package/dist/gateway/static/root/assets/connected-providers-grid-BJKEp0SE.js +1 -0
  22. package/dist/gateway/static/root/assets/{connectors-page-BJm1jjct.js → connectors-page-BteRI1XM.js} +1 -1
  23. package/dist/gateway/static/root/assets/{extension-debug-page-D3X7SlzG.js → extension-debug-page-4jJ1uVQJ.js} +1 -1
  24. package/dist/gateway/static/root/assets/{extension-iframe-host-CIAq7PSn.js → extension-iframe-host-CJV5JETm.js} +1 -1
  25. package/dist/gateway/static/root/assets/{extension-message-router-B2wbucV7.js → extension-message-router-B4I-Y6qs.js} +1 -1
  26. package/dist/gateway/static/root/assets/{extension-page-qwY7r1_p.js → extension-page-lc7a84nG.js} +1 -1
  27. package/dist/gateway/static/root/assets/{extension-provider-DFcRbTHI.js → extension-provider-D8_mIBI0.js} +1 -1
  28. package/dist/gateway/static/root/assets/{extension-settings-page-Cpnh9lcZ.js → extension-settings-page-Uw2lfWRh.js} +1 -1
  29. package/dist/gateway/static/root/assets/{home-page-BusNFHe-.js → home-page-mSRCU81k.js} +4 -4
  30. package/dist/gateway/static/root/assets/{home-task-actions-C8Fi6GBq.js → home-task-actions-_ZAc57Y7.js} +1 -1
  31. package/dist/gateway/static/root/assets/{index-DE6GguFZ.js → index-CJAEAcZV.js} +7 -7
  32. package/dist/gateway/static/root/assets/{local-app-workbench-page-B9uSL1Mi.js → local-app-workbench-page-C3Lqi8E1.js} +1 -1
  33. package/dist/gateway/static/root/assets/{note-detail-panel-DXzfoiyk.js → note-detail-panel-uc-5k3a2.js} +3 -3
  34. package/dist/gateway/static/root/assets/{notes-page-BNTgiHSk.js → notes-page-RPfvHnl6.js} +1 -1
  35. package/dist/gateway/static/root/assets/{page-context-capture-button-BXSBeGms.js → page-context-capture-button-CVHz9b6c.js} +1 -1
  36. package/dist/gateway/static/root/assets/{personal-page-D7zTHQ0K.js → personal-page-Dt1d3tQT.js} +1 -1
  37. package/dist/gateway/static/root/assets/{personal-profile-settings-TcI0Zfwr.js → personal-profile-settings-XiT1MgTK.js} +1 -1
  38. package/dist/gateway/static/root/assets/{personal-settings-panel-BJ46T7ZO.js → personal-settings-panel-bcw04REt.js} +1 -1
  39. package/dist/gateway/static/root/assets/{preview-runtime-C1U57WSM.js → preview-runtime-FtWOW5i4.js} +1 -1
  40. package/dist/gateway/static/root/assets/{product-automation-feedback-GA_YPLkr.js → product-automation-feedback-DdFoCDzG.js} +1 -1
  41. package/dist/gateway/static/root/assets/product-preview-content-B3mzl6-f.js +1 -0
  42. package/dist/gateway/static/root/assets/product-preview-modal-5kTp_7Qk.js +2 -0
  43. package/dist/gateway/static/root/assets/project-detail-page-DGPfKx5M.js +7 -0
  44. package/dist/gateway/static/root/assets/{projects-page-BHQxQGTd.js → projects-page-C-9x23LR.js} +1 -1
  45. package/dist/gateway/static/root/assets/route-preload-CzorjVc9.js +2 -0
  46. package/dist/gateway/static/root/assets/routine-panel-n4IstC8Y.js +2 -0
  47. package/dist/gateway/static/root/assets/session-manager-C2MCS4C5.js +28 -0
  48. package/dist/gateway/static/root/assets/{settings-page-BOzzOS6k.js → settings-page-DsM_f07M.js} +1 -1
  49. package/dist/gateway/static/root/assets/{share-preview-page-Di5_ukH8.js → share-preview-page-C32Mq-BY.js} +1 -1
  50. package/dist/gateway/static/root/assets/{shares-settings-CirGM67m.js → shares-settings-BDGbs8wz.js} +1 -1
  51. package/dist/gateway/static/root/assets/{skills-page-gGU0LZ5e.js → skills-page-kL8E5zgi.js} +1 -1
  52. package/dist/gateway/static/root/assets/space-page-DwyuUvI3.js +2 -0
  53. package/dist/gateway/static/root/assets/task-copy-CtcqCQ78.js +1 -0
  54. package/dist/gateway/static/root/assets/task-detail-page-DdCpNW8K.js +3 -0
  55. package/dist/gateway/static/root/assets/{task-header-title-Cdgp2rCs.js → task-header-title-CLt_lmjb.js} +1 -1
  56. package/dist/gateway/static/root/assets/task-result-presentation-CgvcqEMD.js +1 -0
  57. package/dist/gateway/static/root/assets/task-run-issue-notice-8FX876PP.js +1 -0
  58. package/dist/gateway/static/root/assets/tasks-CvOAtEHv.js +1 -0
  59. package/dist/gateway/static/root/assets/turn-outcome-Dtw6OgwL.js +1 -0
  60. package/dist/gateway/static/root/assets/{use-composer-attachments-DJsIzJ1c.js → use-composer-attachments-BEuyorVm.js} +1 -1
  61. package/dist/gateway/static/root/assets/{use-file-preview-expanded-BFF2vXm5.js → use-file-preview-expanded-Cehu0745.js} +1 -1
  62. package/dist/gateway/static/root/assets/use-personal-work-B25WRGHj.js +1 -0
  63. package/dist/gateway/static/root/assets/{use-realtime-voice-9OvLwHzk.js → use-realtime-voice-CV3GIt_T.js} +1 -1
  64. package/dist/gateway/static/root/assets/{use-workspace-tree-LCIT1H-D.js → use-workspace-tree-C0C861cb.js} +1 -1
  65. package/dist/gateway/static/root/assets/{voice-settings-j8o-hGTm.js → voice-settings-JpPo3BvX.js} +1 -1
  66. package/dist/gateway/static/root/assets/workspace-api-CQOuWbVv.js +2 -0
  67. package/dist/gateway/static/root/assets/{workspace-file-preview-dialog-DwVWTehC.js → workspace-file-preview-dialog-CmMueTmW.js} +1 -1
  68. package/dist/gateway/static/root/index.html +30 -28
  69. package/dist/package.js +1 -1
  70. package/dist/packages/gateway-contract/src/index.js +3 -1
  71. package/dist/packages/gateway-contract/src/notifications.js +1 -8
  72. package/dist/packages/gateway-contract/src/task-display.js +9 -2
  73. package/dist/packages/gateway-contract/src/task-lifecycle.js +1 -0
  74. package/dist/packages/gateway-contract/src/task-research-result.js +2 -1
  75. package/dist/packages/gateway-contract/src/tasks.js +6 -1
  76. package/dist/packages/gateway-contract/src/user-message-text.js +64 -0
  77. package/dist/src/agent/embedded/run-for-session.js +27 -28
  78. package/dist/src/agent/embedded/session-runner.js +14 -1
  79. package/dist/src/agent/fallback/candidates.d.ts +1 -0
  80. package/dist/src/agent/fallback/candidates.js +1 -1
  81. package/dist/src/agent/image/generation/provider-registry.js +3 -1
  82. package/dist/src/agent/mcp/connection-drafts.d.ts +3 -1
  83. package/dist/src/agent/mcp/connection-drafts.js +24 -11
  84. package/dist/src/agent/mcp/connection-setup.js +13 -10
  85. package/dist/src/agent/mcp/native-mcp.js +1 -0
  86. package/dist/src/agent/mcp/network-policy.d.ts +6 -0
  87. package/dist/src/agent/mcp/network-policy.js +49 -0
  88. package/dist/src/agent/mcp/transport.js +14 -7
  89. package/dist/src/agent/messaging/message-router.js +2 -2
  90. package/dist/src/agent/models/manager.d.ts +1 -1
  91. package/dist/src/agent/models/manager.js +2 -1
  92. package/dist/src/agent/models/turn-candidates.d.ts +16 -0
  93. package/dist/src/agent/models/turn-candidates.js +55 -0
  94. package/dist/src/agent/service/direct-turn-helpers.js +9 -24
  95. package/dist/src/agent/service.d.ts +1 -0
  96. package/dist/src/agent/service.js +12 -0
  97. package/dist/src/agent/skills/installer.js +2 -2
  98. package/dist/src/auth/credentials.js +3 -1
  99. package/dist/src/auth/oauth/index.d.ts +0 -1
  100. package/dist/src/auth/oauth/index.js +1 -4
  101. package/dist/src/auth/oauth/registry.js +0 -4
  102. package/dist/src/auth/oauth/xopc-cloud.js +1 -1
  103. package/dist/src/chat-commands/command-parse.d.ts +1 -0
  104. package/dist/src/chat-commands/command-parse.js +8 -10
  105. package/dist/src/chat-commands/registry.d.ts +5 -0
  106. package/dist/src/chat-commands/registry.js +8 -0
  107. package/dist/src/cli/command-manifest.js +1 -1
  108. package/dist/src/cli/commands/auth.js +4 -2
  109. package/dist/src/cli/commands/models.js +12 -10
  110. package/dist/src/config/models-json.js +1 -2
  111. package/dist/src/config/schema.d.ts +54 -4
  112. package/dist/src/config/schema.js +3 -1
  113. package/dist/src/gateway/agent-reactions/reaction.d.ts +1 -2
  114. package/dist/src/gateway/agent-reactions/reaction.js +10 -21
  115. package/dist/src/gateway/custom-image-providers.js +4 -1
  116. package/dist/src/gateway/hono/oauth.js +3 -0
  117. package/dist/src/gateway/hono/routes/device-push.js +55 -15
  118. package/dist/src/gateway/hono/routes/mobile-capability-panels.d.ts +67 -0
  119. package/dist/src/gateway/hono/routes/mobile-capability-panels.js +16 -131
  120. package/dist/src/gateway/hono/routes/mobile-mcp-setup.d.ts +9 -0
  121. package/dist/src/gateway/hono/routes/mobile-mcp-setup.js +949 -0
  122. package/dist/src/gateway/hono/routes/notifications.js +12 -1
  123. package/dist/src/gateway/hono/routes/session-command-handler.js +1 -4
  124. package/dist/src/gateway/hono/routes/session-input-handler.js +1 -4
  125. package/dist/src/gateway/hono/routes/sessions.js +1 -13
  126. package/dist/src/gateway/next-turn-suggestions/generator.js +16 -2
  127. package/dist/src/gateway/next-turn-suggestions/service.d.ts +2 -1
  128. package/dist/src/gateway/next-turn-suggestions/service.js +17 -5
  129. package/dist/src/gateway/next-turn-suggestions/snapshot.d.ts +11 -0
  130. package/dist/src/gateway/next-turn-suggestions/snapshot.js +31 -2
  131. package/dist/src/gateway/security/gateway-scopes.js +1 -0
  132. package/dist/src/gateway/service/config-coordinator.d.ts +14 -1
  133. package/dist/src/gateway/service/run-gateway-agent.js +2 -13
  134. package/dist/src/gateway/service.js +80 -60
  135. package/dist/src/local-apps/capabilities/projections.d.ts +5 -5
  136. package/dist/src/media/generation-changes.d.ts +4 -0
  137. package/dist/src/media/generation-changes.js +37 -0
  138. package/dist/src/music-generation/repository.js +12 -6
  139. package/dist/src/notifications/device-store.d.ts +3 -0
  140. package/dist/src/notifications/device-store.js +14 -1
  141. package/dist/src/notifications/platform-push.d.ts +17 -0
  142. package/dist/src/notifications/platform-push.js +58 -0
  143. package/dist/src/notifications/service.d.ts +2 -2
  144. package/dist/src/notifications/service.js +26 -12
  145. package/dist/src/notifications/store.d.ts +1 -1
  146. package/dist/src/notifications/store.js +3 -2
  147. package/dist/src/providers/env-keys.js +0 -1
  148. package/dist/src/providers/index.js +1 -7
  149. package/dist/src/providers/model-catalog-sync-service.js +3 -1
  150. package/dist/src/providers/model-registry.js +6 -2
  151. package/dist/src/providers/presentation.js +1 -2
  152. package/dist/src/providers/provider-policy.js +2 -1
  153. package/dist/src/session/client-history.js +3 -3
  154. package/dist/src/session/reset-triggers.js +1 -1
  155. package/dist/src/session/user-message-display.js +3 -2
  156. package/dist/src/storage/sqlite/agent-reaction-repository.d.ts +2 -4
  157. package/dist/src/storage/sqlite/agent-reaction-repository.js +18 -13
  158. package/dist/src/storage/sqlite/device-access-repository.js +2 -1
  159. package/dist/src/tasks/capabilities/write.d.ts +2 -0
  160. package/dist/src/tasks/home-query-service.js +2 -1
  161. package/dist/src/tasks/task-contract-planner.js +1 -0
  162. package/dist/src/tasks/task-conversation-summary.d.ts +1 -1
  163. package/dist/src/tasks/task-delivery-checks.d.ts +12 -0
  164. package/dist/src/tasks/task-delivery-checks.js +91 -0
  165. package/dist/src/tasks/task-final-reply.d.ts +3 -1
  166. package/dist/src/tasks/task-final-reply.js +17 -4
  167. package/dist/src/tasks/task-model-call.js +4 -2
  168. package/dist/src/tasks/task-origin-repository.d.ts +1 -1
  169. package/dist/src/tasks/task-read-model-projector.js +24 -7
  170. package/dist/src/tasks/task-research-result.js +12 -27
  171. package/dist/src/tasks/task-result-delivery-repository.js +3 -2
  172. package/dist/src/tasks/task-retry-service.js +2 -1
  173. package/dist/src/tasks/task-run-coordinator.js +14 -4
  174. package/dist/src/tasks/task-run-dispatcher.d.ts +1 -0
  175. package/dist/src/tasks/task-run-dispatcher.js +78 -48
  176. package/dist/src/tasks/task-run-repository.js +1 -1
  177. package/dist/src/tui/tui-commands.d.ts +2 -1
  178. package/dist/src/tui/tui-commands.js +3 -3
  179. package/dist/src/tui/tui-submit.d.ts +1 -1
  180. package/dist/src/tui/tui-submit.js +2 -4
  181. package/dist/src/video-generation/drafts.js +2 -0
  182. package/dist/src/video-generation/repository.js +13 -6
  183. package/package.json +1 -1
  184. package/dist/gateway/static/root/assets/capabilities-page-EENl65YY.js +0 -2
  185. package/dist/gateway/static/root/assets/command-palette-api-YP0zV_Ol.js +0 -1
  186. package/dist/gateway/static/root/assets/composer-payload-handoff-ClWsunJ2.js +0 -1
  187. package/dist/gateway/static/root/assets/connected-providers-grid-BgW-ioIt.js +0 -1
  188. package/dist/gateway/static/root/assets/product-preview-content-BOq3gtSJ.js +0 -1
  189. package/dist/gateway/static/root/assets/product-preview-modal-DIh_CsXp.js +0 -2
  190. package/dist/gateway/static/root/assets/project-detail-page-Dgs8ImMC.js +0 -7
  191. package/dist/gateway/static/root/assets/route-preload-7WVrzJca.js +0 -2
  192. package/dist/gateway/static/root/assets/routine-panel-Bfbiz0IN.js +0 -2
  193. package/dist/gateway/static/root/assets/session-manager-DUWeBdeG.js +0 -28
  194. package/dist/gateway/static/root/assets/space-page-CKVuhV2i.js +0 -2
  195. package/dist/gateway/static/root/assets/task-detail-page-DEpYIaok.js +0 -3
  196. package/dist/gateway/static/root/assets/task-run-issue-notice-CGrUMy0s.js +0 -1
  197. package/dist/gateway/static/root/assets/tasks-CwyNaa-j.js +0 -1
  198. package/dist/gateway/static/root/assets/turn-outcome-BSbEJx8h.js +0 -1
  199. package/dist/gateway/static/root/assets/use-personal-work-Dd2jRUpz.js +0 -1
  200. package/dist/gateway/static/root/assets/workspace-api-BuNWyNvA.js +0 -2
  201. package/dist/src/auth/oauth/google-antigravity.d.ts +0 -4
  202. package/dist/src/auth/oauth/google-antigravity.js +0 -9
  203. package/dist/src/auth/oauth/google-oauth/google-antigravity.d.ts +0 -25
  204. package/dist/src/auth/oauth/google-oauth/google-antigravity.js +0 -309
  205. package/dist/src/notifications/harmony-push.d.ts +0 -27
  206. package/dist/src/notifications/harmony-push.js +0 -96
@@ -91,6 +91,7 @@ var ModelTaskContractPlanner = class {
91
91
  "Acceptance criteria must describe externally checkable finished states, not activities.",
92
92
  "Write boundaries and prohibitions on unrelated actions belong in constraints, not criteria requiring proof that no unobserved action ever occurred. Criteria may check the actual delivered output paths and unchanged supplied input bytes. Never remove an explicit scope restriction.",
93
93
  "Keep each criterion concise and concrete. For simple work use the fewest checks that cover all explicit deliverables and material constraints. Prefer observable checks such as the required file, format, fields or count. Treat optional analysis, extra conclusions and aesthetic improvements as optional unless the user requires them. Do not invent work to make the contract more elaborate.",
94
+ "Keep delivery format and character limits in their own criteria, separate from factual accuracy, publication dates and source requirements. For explicit chat format and limits, use concrete wording such as \"The final reply must be plain text\" or \"The final reply must be at most 500 characters\". For explicitly requested HTML structure, describe the required file name or page elements separately from what those elements must substantively say.",
94
95
  "Define criteria for the deliverables requested by the user. When the requested answer is a chat reply, list it explicitly in expectedOutputs and preserve its concrete requirements, including language and any length limits the user actually set. Treat general brevity or “keep it short” as a presentation preference. Do not turn it into a word or character quota or an acceptance check. Keep source support, calculations, completeness and requested limitations as separate criteria. Do not create self-referential criteria about calling publish_task_result, receiving this review or wording a routine delivery acknowledgement.",
95
96
  "requiredCapabilities is a minimal subset of read_input, execute_code, publish_files, web_research, browser, generate_image. Include only operations necessary for the requested inputs/outputs; this list selects registered tools and grants no permissions. Do not require browser when ordinary web fetch suffices. Preserve explicit executor/Skill and scope constraints.",
96
97
  "List assumptions explicitly. Put only irreversible, external, financial, privacy, or permission decisions in approvalRequired.",
@@ -59,7 +59,7 @@ export declare function taskConversationSummary(taskId: string, conversationId:
59
59
  questionId: unknown;
60
60
  }[];
61
61
  attention: {
62
- kind: "allocation_blocked" | "allocation_failed" | "input_required" | "approval_required" | "dependency_blocked" | "run_failed" | "run_decision_required" | "verification_failed" | "overdue" | "stale";
62
+ kind: "allocation_blocked" | "allocation_failed" | "input_required" | "approval_required" | "dependency_blocked" | "run_failed" | "run_decision_required" | "verification_failed" | "verification_unverified" | "overdue" | "stale";
63
63
  summary: string;
64
64
  }[];
65
65
  workerProgress: {
@@ -0,0 +1,12 @@
1
+ import type { TaskResearchResult } from '@xopcai/gateway-contract';
2
+ type PublishedFile = {
3
+ title: string;
4
+ content?: string;
5
+ };
6
+ export declare function checkTaskDelivery(result: TaskResearchResult, input: {
7
+ files: PublishedFile[];
8
+ publishedFileCount: number;
9
+ chatReplyOnly: boolean;
10
+ zh: boolean;
11
+ }): TaskResearchResult;
12
+ export {};
@@ -0,0 +1,91 @@
1
+ import { finalReplyCharacterLimit, isReplyLengthCriterion } from "./task-final-reply.js";
2
+ import { parseHTML } from "linkedom";
3
+ import MarkdownIt from "markdown-it";
4
+ //#region src/tasks/task-delivery-checks.ts
5
+ const markdown = new MarkdownIt({ html: true });
6
+ const plainChat = /^(?:(?:最终)?(?:回复|答复)为纯文本(?:聊天内容)?|(?:use |deliver )(?:a )?plain[- ]text chat (?:reply|response)|(?:the )?(?:final )?(?:chat )?(?:reply|response) (?:is|must be) plain[- ]text)(?:[,,]\s*(?:未生成任何文件|不生成(?:任何)?文件|without (?:any )?(?:files|attachments)))?$/iu;
7
+ const noMarkdown = /^(?:(?:最终)?(?:回复|答复)(?:使用纯文本[,,]\s*)?(?:不使用|不得使用|无)\s*Markdown|(?:the )?(?:final )?(?:chat )?(?:reply|response) (?:uses? no|must not use) Markdown)$/iu;
8
+ const htmlFilename = /^(?:(?:HTML\s*)?文件名(?:为|是|:|:)\s*|(?:the )?(?:HTML )?(?:file ?name is|file is named)\s+)`?([^\s`/\\]+\.html?)`?$/iu;
9
+ const singleHtml = /^(?:(?:交付|发布)(?:一个|一份)?单文件\s*HTML(?:\s*(?:文件|网页))?|(?:deliver|publish) (?:a )?single HTML (?:file|document))$/iu;
10
+ const htmlHeadingAndFooter = /^(?:HTML\s*(?:页面)?(?:包含|含有)(?:可见)?标题(?:和|与|及)页脚|(?:the )?HTML (?:page )?(?:has|contains) (?:a )?(?:heading|title) and (?:a )?footer)$/iu;
11
+ const inlineCss = /^(?:CSS\s*(?:全部)?(?:内联|内嵌)|CSS\s*(?:必须|须)(?:内联|内嵌)|(?:all )?CSS (?:is|must be) (?:inline|embedded))$/iu;
12
+ function checkTaskDelivery(result, input) {
13
+ const { finalText } = result;
14
+ const { files, zh } = input;
15
+ const length = finalText === void 0 ? void 0 : Array.from(finalText).length;
16
+ const htmlFiles = files.filter((file) => /\.html?$/iu.test(file.title));
17
+ const knowsFinalFiles = result.finalArtifactIds !== void 0 || files.length > 0;
18
+ const htmlContent = htmlFiles.length === 1 ? htmlFiles[0].content : void 0;
19
+ let document;
20
+ const checked = (check, passed, zhNote, enNote) => ({
21
+ ...check,
22
+ status: passed ? "passed" : "failed",
23
+ claimIds: [],
24
+ method: "tool_verified",
25
+ note: zh ? zhNote : enNote
26
+ });
27
+ const unverified = (check, zhNote, enNote) => ({
28
+ ...check,
29
+ status: "unverified",
30
+ claimIds: [],
31
+ note: zh ? zhNote : enNote
32
+ });
33
+ const checks = result.checks.map((check) => {
34
+ const criterion = check.criterion.trim().replace(/[.。]$/u, "");
35
+ const limit = finalReplyCharacterLimit(check.criterion, input.chatReplyOnly);
36
+ if (finalText === void 0 && (limit !== void 0 || plainChat.test(criterion) || noMarkdown.test(criterion))) return unverified(check, "尚未提交供核验的最终回复。", "No final reply was submitted for verification.");
37
+ if (limit !== void 0 && length !== void 0) {
38
+ if (length > limit || isReplyLengthCriterion(criterion, input.chatReplyOnly)) return checked(check, length <= limit, `最终回复共 ${length} 个字符,上限为 ${limit}。`, `The final reply contains ${length} characters. The limit is ${limit}.`);
39
+ }
40
+ if (finalText !== void 0 && plainChat.test(criterion)) {
41
+ const excludesFiles = /未生成|不生成|without /iu.test(criterion);
42
+ const passed = !((input.chatReplyOnly || excludesFiles) && files.length > 0 || /未生成|不生成/u.test(criterion) && input.publishedFileCount > 0) && !markdown.parse(finalText, {}).some((token) => [
43
+ "html_block",
44
+ "fence",
45
+ "code_block"
46
+ ].includes(token.type) || token.children?.some((child) => ["html_inline", "image"].includes(child.type)));
47
+ return checked(check, passed, passed ? "最终交付为纯文本聊天回复。" : "最终交付含文件、图片、HTML 或代码块。", passed ? "The final delivery is a plain-text chat reply." : "The delivery contains files, images, HTML, or code blocks.");
48
+ }
49
+ if (finalText !== void 0 && noMarkdown.test(criterion)) {
50
+ const passed = markdown.parse(finalText, {}).every((token) => [
51
+ "paragraph_open",
52
+ "paragraph_close",
53
+ "inline"
54
+ ].includes(token.type) && (token.children ?? []).every((child) => ["text", "softbreak"].includes(child.type)));
55
+ return checked(check, passed, passed ? "最终回复为无 Markdown 格式的文本。" : "最终回复含 Markdown 排版或 HTML。", passed ? "The final reply is text without Markdown formatting." : "The final reply contains Markdown formatting or HTML.");
56
+ }
57
+ const filename = htmlFilename.exec(criterion)?.[1];
58
+ if (filename && knowsFinalFiles) {
59
+ const file = htmlFiles.find((item) => item.title === filename);
60
+ return checked(check, Boolean(file), file ? `最终交付包含文件 ${filename}。` : `最终交付中缺少 ${filename}。`, file ? `The final delivery lists the file ${filename}.` : `The final publication does not include ${filename}.`);
61
+ }
62
+ const single = singleHtml.test(criterion);
63
+ const css = inlineCss.test(criterion);
64
+ if (single || css || htmlHeadingAndFooter.test(criterion)) {
65
+ if (knowsFinalFiles && (htmlFiles.length === 0 || single && files.length !== 1)) return checked(check, false, "最终交付未包含要求的 HTML 文件。", "The final delivery does not contain the required HTML file.");
66
+ if (htmlContent === void 0) return unverified(check, "尚未读取最终 HTML 正文。", "The final HTML could not be read.");
67
+ document ??= parseHTML(htmlContent).document;
68
+ let passed;
69
+ let label;
70
+ if (single) {
71
+ passed = Boolean(document.querySelector("html > body"));
72
+ label = zh ? "单文件 HTML 结构" : "single-file HTML structure";
73
+ } else if (css) {
74
+ const style = [...document.querySelectorAll("style")].map((element) => element.textContent ?? "").join("\n");
75
+ passed = Boolean(style.trim() || document.querySelector("[style]")) && !document.querySelector("link[rel~=\"stylesheet\" i]") && !/@import\b/iu.test(style.replace(/\/\*[\s\S]*?\*\//gu, ""));
76
+ label = zh ? "内联样式" : "inline CSS";
77
+ } else {
78
+ passed = Boolean(document.querySelector("body h1")?.textContent?.trim() && document.querySelector("body footer")?.textContent?.trim());
79
+ label = zh ? "页面标题和页脚" : "page heading and footer";
80
+ }
81
+ return checked(check, passed, `最终 HTML 的${label}${passed ? "符合" : "不符合"}要求。`, `The published HTML ${passed ? "meets" : "does not meet"} the requirement for ${label}.`);
82
+ }
83
+ return check;
84
+ });
85
+ return {
86
+ ...result,
87
+ checks
88
+ };
89
+ }
90
+ //#endregion
91
+ export { checkTaskDelivery };
@@ -1,2 +1,4 @@
1
1
  export declare function isChatReplyOutput(output: string): boolean;
2
- export declare function finalReplyCharacterLimit(criterion: string): number | undefined;
2
+ export declare function finalReplyCharacterLimit(criterion: string, chatReplyOnly?: boolean): number | undefined;
3
+ export declare function isChatOnlyDelivery(outputs: string[]): boolean;
4
+ export declare function isReplyLengthCriterion(criterion: string, chatReplyOnly: boolean): boolean;
@@ -1,11 +1,24 @@
1
1
  //#region src/tasks/task-final-reply.ts
2
2
  function isChatReplyOutput(output) {
3
- return /(?:对话|聊天)(?:内|中|里|正文|回复|答复)|中文(?:回复|答复)|\b(?:chat|in-chat) (?:reply|response|answer)\b|\b(?:reply|response|answer) in (?:this )?chat\b/iu.test(output);
3
+ return /^(?:chat|in_chat)_(?:reply|response|answer)$/iu.test(output.trim()) || /(?:对话|聊天)(?:内|中|里|正文|回复|答复)|中文(?:回复|答复)|\b(?:chat|in-chat) (?:reply|response|answer)\b|\b(?:reply|response|answer) in (?:this )?chat\b/iu.test(output);
4
4
  }
5
- function finalReplyCharacterLimit(criterion) {
6
- if (!/(?:回复|答复|\b(?:reply|response)\b)/iu.test(criterion)) return void 0;
5
+ function finalReplyCharacterLimit(criterion, chatReplyOnly = false) {
6
+ if (!/(?:回复|答复|\b(?:reply|response)\b)/iu.test(criterion) && !(chatReplyOnly && isReplyLengthCriterion(criterion, true))) return void 0;
7
7
  const limit = criterion.match(/(?:不超过|最多|至多|限于)\s*([1-9]\d*)\s*(?:个\s*)?(?:字符|汉字|字)(?!段|节|体|样)/u)?.[1] ?? criterion.match(/([1-9]\d*)\s*(?:个\s*)?(?:字符|汉字|字)\s*(?:以内|以下)/u)?.[1] ?? criterion.match(/(?:at most|no more than|up to|maximum(?: of)?|limit of)\s+([1-9]\d*)\s+characters?\b/iu)?.[1];
8
8
  return limit === void 0 ? void 0 : Number(limit);
9
9
  }
10
+ function isChatOnlyDelivery(outputs) {
11
+ return outputs.length === 1 && isChatReplyOutput(outputs[0]);
12
+ }
13
+ function isReplyLengthCriterion(criterion, chatReplyOnly) {
14
+ const text = criterion.trim().replace(/[.。]$/u, "");
15
+ const subject = /^(?:(?:最终)?(?:对话|聊天)?(?:回复|答复)(?:正文|长度|字数|篇幅)?|(?:总)?篇幅|总字数|全文)\s*/u;
16
+ if (subject.test(text)) {
17
+ const match = subject.exec(text);
18
+ if (!chatReplyOnly && !/(?:回复|答复)/u.test(match[0])) return false;
19
+ return /^(?:(?:不超过|最多|至多|限于)\s*[1-9]\d*\s*(?:个\s*)?(?:字符|汉字|字)|(?:控制在|限在)?\s*[1-9]\d*\s*(?:个\s*)?(?:字符|汉字|字)\s*(?:以内|以下))$/u.test(text.slice(match[0].length));
20
+ }
21
+ return /^(?:the )?(?:final )?(?:chat )?(?:reply|response) (?:must be |is |contains? )?(?:at most|no more than|up to|maximum(?: of)?|limit of)\s+[1-9]\d*\s+characters?$/iu.test(text);
22
+ }
10
23
  //#endregion
11
- export { finalReplyCharacterLimit, isChatReplyOutput };
24
+ export { finalReplyCharacterLimit, isChatOnlyDelivery, isChatReplyOutput, isReplyLengthCriterion };
@@ -20,13 +20,15 @@ async function completeTaskModelCall(models, context, options, usage) {
20
20
  return response;
21
21
  } catch (error) {
22
22
  options.signal?.throwIfAborted();
23
- if (index === chain.length - 1 || !isTransientProviderErrorMessage(error instanceof Error ? error.message : String(error))) throw error;
23
+ const message = error instanceof Error ? error.message : String(error);
24
+ const missingCredential = /^No API key for provider:/i.test(message) && chain[index + 1] !== chain[index];
25
+ if (index === chain.length - 1 || !missingCredential && !isTransientProviderErrorMessage(message)) throw error;
24
26
  log.warn({
25
27
  modelRef: chain[index],
26
28
  nextModelRef: chain[index + 1],
27
29
  operation: usage.operation,
28
30
  conversationId: usage.conversationId
29
- }, "Task model request failed transiently; trying configured recovery model");
31
+ }, missingCredential ? "Task model credentials are missing; trying configured fallback model" : "Task model request failed transiently; trying configured recovery model");
30
32
  }
31
33
  }
32
34
  throw new Error("No task model is configured");
@@ -50,7 +50,7 @@ export declare class TaskOriginRepository {
50
50
  };
51
51
  };
52
52
  attention: {
53
- kind: "allocation_blocked" | "allocation_failed" | "input_required" | "approval_required" | "dependency_blocked" | "run_failed" | "run_decision_required" | "verification_failed" | "overdue" | "stale";
53
+ kind: "allocation_blocked" | "allocation_failed" | "input_required" | "approval_required" | "dependency_blocked" | "run_failed" | "run_decision_required" | "verification_failed" | "verification_unverified" | "overdue" | "stale";
54
54
  summary: string;
55
55
  sourceId?: string;
56
56
  };
@@ -1,4 +1,6 @@
1
1
  import { getSqliteDatabase, init_transaction } from "../storage/sqlite/transaction.js";
2
+ import { taskRunResultKind } from "../../packages/gateway-contract/src/tasks.js";
3
+ import { init_src } from "../../packages/gateway-contract/src/index.js";
2
4
  import { TaskRepository, init_task_repository } from "./task-repository.js";
3
5
  import { init_task_instruction_sequence, taskInstructionSequence } from "./task-instruction-sequence.js";
4
6
  import { TaskRunRepository, init_task_run_repository } from "./task-run-repository.js";
@@ -8,6 +10,7 @@ import { TaskAllocationRepository } from "./task-allocation-repository.js";
8
10
  import { TaskCriterionReviewRepository } from "./task-criterion-review-repository.js";
9
11
  import { isReadOnlyRetryDecision, isReadOnlyTaskRetry } from "./task-retry-policy.js";
10
12
  //#region src/tasks/task-read-model-projector.ts
13
+ init_src();
11
14
  init_transaction();
12
15
  init_request_repository();
13
16
  init_task_repository();
@@ -54,13 +57,26 @@ var TaskReadModelProjector = class {
54
57
  sourceId: wait.id
55
58
  });
56
59
  }
57
- if (!attention.some((item) => item.kind === "run_decision_required") && latestRun?.status === "failed" && latestRun.contractVersion === task.latestContractVersion) {
60
+ if (latestRun && latestRun.contractVersion === task.latestContractVersion && (latestRun.status === "failed" || latestRun.status === "succeeded" && task.phase === "review")) {
58
61
  const receipt = this.#runs.getReceipt(latestRun.id);
59
- attention.push({
60
- kind: receipt?.verification.status === "failed" ? "verification_failed" : "run_failed",
61
- summary: latestRun.terminalMessage ?? receipt?.summary ?? (resolveTaskLocale(task) === "zh" ? "最近一次执行失败" : "The latest run failed"),
62
- sourceId: latestRun.id
63
- });
62
+ const zh = resolveTaskLocale(task) === "zh";
63
+ const resultKind = receipt ? taskRunResultKind(receipt) : "execution_failed";
64
+ if (resultKind === "execution_failed") {
65
+ const label = zh ? "执行失败" : "Execution failed";
66
+ const detail = receipt?.failure?.phase === "preflight" ? receipt.failure.recoveryAction : latestRun.terminalMessage ?? receipt?.summary;
67
+ attention.push({
68
+ kind: "run_failed",
69
+ summary: detail && !detail.trimStart().startsWith("{") ? `${label} · ${detail}` : label,
70
+ sourceId: latestRun.id
71
+ });
72
+ } else if (resultKind === "verification_failed" || resultKind === "verification_unverified") {
73
+ const summary = resultKind === "verification_failed" ? zh ? "验收未通过,查看未满足的验收项。" : "Acceptance failed. Review the unmet criteria." : zh ? "结果未验证,查看仍需核验的验收项。" : "Result unverified. Review the criteria that still need verification.";
74
+ attention.push({
75
+ kind: resultKind,
76
+ summary,
77
+ sourceId: latestRun.id
78
+ });
79
+ }
64
80
  }
65
81
  if (task.dueAt !== void 0 && task.phase !== "closed" && task.dueAt < now) attention.push({
66
82
  kind: "overdue",
@@ -130,6 +146,7 @@ var TaskReadModelProjector = class {
130
146
  waitId: pending.sourceId
131
147
  }
132
148
  };
149
+ const failure = attention.find((item) => item.kind === "run_failed" || item.kind === "verification_failed" || item.kind === "verification_unverified");
133
150
  const decision = attention.find((item) => item.kind === "run_decision_required");
134
151
  if (decision?.sourceId) {
135
152
  const connected = Boolean(personalRequestForTask(task.id));
@@ -151,7 +168,6 @@ var TaskReadModelProjector = class {
151
168
  };
152
169
  }
153
170
  if (state === "failed") {
154
- const failure = attention.find((item) => item.kind === "run_failed" || item.kind === "verification_failed");
155
171
  const canRetryExecutor = latestRun?.executorKind === "agent" && typeof latestRun.executorRef.agentId === "string";
156
172
  if (failure?.sourceId) return {
157
173
  status: "failed",
@@ -194,6 +210,7 @@ var TaskReadModelProjector = class {
194
210
  };
195
211
  return {
196
212
  status: "review",
213
+ reason: failure?.summary,
197
214
  primaryAction: acceptance.canSignOff ? {
198
215
  type: "signoff",
199
216
  resultId: acceptance.id
@@ -17,13 +17,14 @@ import { readMediaReference } from "../media/media-reference.js";
17
17
  import { TaskConversationRepository } from "./task-conversation-repository.js";
18
18
  import { TaskCollaborationRepository } from "./task-collaboration-repository.js";
19
19
  import { sanitizePersonalResultFileLinks } from "../personal-agent/result-file-links.js";
20
- import { finalReplyCharacterLimit } from "./task-final-reply.js";
20
+ import { isChatOnlyDelivery } from "./task-final-reply.js";
21
21
  import { TaskResultDeliveryRepository } from "./task-result-delivery-repository.js";
22
22
  import { defineTaskContract } from "./task-contract-definition.js";
23
23
  import { completeTaskModelCall } from "./task-model-call.js";
24
24
  import { personalRequestReviewSnapshot } from "../personal-agent/request-verification.js";
25
25
  import { observedEvidenceExcerpt, suggestedEvidenceRanges } from "./task-evidence-ranges.js";
26
26
  import { isTaskEvidenceTool } from "./task-evidence-tools.js";
27
+ import { checkTaskDelivery } from "./task-delivery-checks.js";
27
28
  import { createHash } from "node:crypto";
28
29
  import { z } from "zod";
29
30
  //#region src/tasks/task-research-result.ts
@@ -243,7 +244,7 @@ function applyResearchReview(result, raw, criteria) {
243
244
  });
244
245
  }
245
246
  const reviewResearchResult = async (input, signal) => {
246
- const models = resolveEffectiveAgentConfigForSession(input.conversationId).config.models.chat;
247
+ const { models } = resolveEffectiveAgentConfigForSession(input.conversationId).config;
247
248
  const { checks: _checks, review: _review, claims, instructionChecks, ...submitted } = input.result;
248
249
  const auditInput = {
249
250
  ...input,
@@ -275,7 +276,7 @@ const reviewResearchResult = async (input, signal) => {
275
276
  const replyGuidance = " If finalText is supplied, it is the exact chat text selected for delivery. Inspect it directly for language, structure, coverage, labels and links. Use hostObservations.finalTextCharacters for character limits. Compare its factual statements with the supported claims and sources. Cite supported claim IDs for the findings checked in the text. Do not infer reply content from the claim ledger or demand a file for a text-only reply. For connected-app deliveries, inspect the saved result instead. When neither is supplied, criteria requiring chat content remain unverified.";
276
277
  let correction = "";
277
278
  for (let attempt = 0; attempt < 2; attempt++) {
278
- const response = await completeTaskModelCall(models, {
279
+ const response = await completeTaskModelCall(models.background ?? models.chat, {
279
280
  systemPrompt: systemPrompt + replyGuidance,
280
281
  messages: [{
281
282
  role: "user",
@@ -415,6 +416,7 @@ async function submitTaskResearchResult(conversationId, toolCallId, raw, signal,
415
416
  const artifact = TurnOutcomeDeliverableSchema.safeParse(rawArtifact);
416
417
  if (artifact.success && artifact.data.availability === "available" && artifact.data.location === "artifact_store" && artifact.data.uri?.startsWith("media://outbound/")) published.set(artifact.data.artifactId, artifact.data);
417
418
  }
419
+ const publishedFileCount = published.size;
418
420
  if (published.size && submitted.finalArtifactIds === void 0) throw new Error(JSON.stringify({
419
421
  code: "final_artifact_selection_required",
420
422
  message: "Select finalArtifactIds from the successful publications; [] explicitly selects a text-only result. Intermediate files will not be delivered automatically.",
@@ -445,7 +447,7 @@ async function submitTaskResearchResult(conversationId, toolCallId, raw, signal,
445
447
  let contentBudget = 24e3;
446
448
  for (const artifact of published.values()) {
447
449
  let content;
448
- if (/\.(md|txt|csv|json|m?js|cjs|ts|py|sh)$/i.test(artifact.title)) try {
450
+ if (/\.(html?|md|txt|csv|json|m?js|cjs|ts|py|sh)$/i.test(artifact.title)) try {
449
451
  const { buffer } = await readMediaReference(artifact.uri, 24e3);
450
452
  if (buffer.length <= contentBudget) {
451
453
  content = buffer.toString("utf8");
@@ -490,29 +492,12 @@ async function submitTaskResearchResult(conversationId, toolCallId, raw, signal,
490
492
  clearTimeout(timer);
491
493
  signal?.removeEventListener("abort", abort);
492
494
  }
493
- if (!personalSnapshot) {
494
- const length = finalText ? Array.from(finalText).length : void 0;
495
- const zh = resolveTaskLocale(task) === "zh";
496
- result = {
497
- ...result,
498
- checks: result.checks.map((check) => {
499
- const limit = finalReplyCharacterLimit(check.criterion);
500
- if (limit === void 0 || length !== void 0 && length <= limit) return check;
501
- if (length === void 0) return {
502
- ...check,
503
- status: "unverified",
504
- claimIds: [],
505
- note: zh ? "尚未提交供核验的最终对话正文。" : "No final chat text was submitted for verification."
506
- };
507
- return {
508
- ...check,
509
- status: "failed",
510
- claimIds: [],
511
- note: zh ? `最终对话正文共 ${length} 个字符,超过 ${limit} 字上限。` : `Final chat text has ${length} characters, exceeding the ${limit}-character limit.`
512
- };
513
- })
514
- };
515
- }
495
+ if (!personalSnapshot) result = checkTaskDelivery(result, {
496
+ files: artifacts,
497
+ publishedFileCount,
498
+ chatReplyOnly: isChatOnlyDelivery(task.contract?.expectedOutputs ?? []),
499
+ zh: resolveTaskLocale(task) === "zh"
500
+ });
516
501
  if (JSON.stringify(criteria) === JSON.stringify(defineTaskContract(task.contract?.objective ?? task.title, task.locale).acceptanceCriteria)) result = {
517
502
  ...result,
518
503
  checks: result.checks.map((check) => ({
@@ -12,7 +12,7 @@ import { init_request_repository, personalRequestForTask } from "../personal-age
12
12
  import { TaskConversationRepository } from "./task-conversation-repository.js";
13
13
  import { TaskCollaborationRepository } from "./task-collaboration-repository.js";
14
14
  import { hasPersonalResultFileLinks, sanitizePersonalResultFileLinks } from "../personal-agent/result-file-links.js";
15
- import { finalReplyCharacterLimit } from "./task-final-reply.js";
15
+ import { finalReplyCharacterLimit, isChatOnlyDelivery } from "./task-final-reply.js";
16
16
  import { randomUUID } from "node:crypto";
17
17
  //#region src/tasks/task-result-delivery-repository.ts
18
18
  init_src();
@@ -125,7 +125,8 @@ var TaskResultDeliveryRepository = class {
125
125
  const unpublishedFile = Boolean(rawText && hasPersonalResultFileLinks(rawText) && !finalText && !deliverables.some((item) => item.availability === "available"));
126
126
  const candidate = finalText ?? (rawText ? sanitizePersonalResultFileLinks(rawText) : void 0);
127
127
  const replyLength = candidate ? Array.from(candidate).length : 0;
128
- const replyTooLong = task.contract?.acceptanceCriteria.some((criterion) => replyLength > (finalReplyCharacterLimit(criterion) ?? Infinity));
128
+ const chatOnly = isChatOnlyDelivery(task.contract?.expectedOutputs ?? []);
129
+ const replyTooLong = task.contract?.acceptanceCriteria.some((criterion) => replyLength > (finalReplyCharacterLimit(criterion, chatOnly) ?? Infinity));
129
130
  const text = replyTooLong ? void 0 : candidate || (unpublishedFile ? "The file has not been published for download." : void 0);
130
131
  if (!deliverables.length && (!text || status !== "succeeded" && !finalText)) return false;
131
132
  if (!deliverables.length && personalRequestForTask(run.taskId)) return false;
@@ -88,7 +88,8 @@ async function retryTask(input, deps) {
88
88
  if (input.expectedRunId && latest.id !== input.expectedRunId) return result("changed", latest);
89
89
  if (!task || latest.contractVersion !== task.latestContractVersion || latest.executorKind !== "agent" || typeof latest.executorRef.agentId !== "string") return result("not_retryable", latest);
90
90
  const readOnly = !request && (personal || taskWaits.length > 0) && isReadOnlyTaskRetry(task, latest);
91
- if (personal && !request && !readOnly) return result("not_retryable", latest, "read_scope_unverified");
91
+ const failedBeforeExecution = latest.startedAt === void 0 && (runs.getReceipt(latest.id)?.failure?.phase === "preflight" || latest.terminalCode === "dispatch_failed" && latest.terminalMessage === "Task executor differs from the active conversation");
92
+ if (personal && !request && !readOnly && !failedBeforeExecution) return result("not_retryable", latest, "read_scope_unverified");
92
93
  const decisionWaits = request || readOnly ? taskWaits.filter((wait) => wait.taskRunId === latest.id && isReadOnlyRetryDecision(wait.condition, Boolean(request))) : [];
93
94
  if (taskWaits.length !== decisionWaits.length || runs.getActiveRoot(task.id)) return result("blocked", latest, "other_wait");
94
95
  const readiness = request ? connectionReadiness(request) : "ready";
@@ -249,13 +249,22 @@ var TaskRunCoordinator = class TaskRunCoordinator {
249
249
  observedAt: Date.now(),
250
250
  verifies: currentResearch.checks.filter((check) => check.status === "passed" && check.claimIds.includes(claim.id)).map((check) => check.criterion)
251
251
  })) ?? [];
252
+ const deliveryEvidence = currentResearch?.checks.filter((check) => check.status === "passed" && check.method === "tool_verified").map((check) => ({
253
+ kind: "test",
254
+ title: `Delivery check ${check.criterionIndex + 1}`,
255
+ summary: check.note,
256
+ verifies: [check.criterion],
257
+ provenance: "tool",
258
+ strength: "verified",
259
+ observedAt: Date.now()
260
+ })) ?? [];
252
261
  const checks = structuralCheck?.checks ?? currentResearch?.checks.map((check) => ({
253
262
  criterion: check.criterion,
254
263
  status: check.status,
255
264
  checkId: taskCheckId(task.id, run.contractVersion, check.criterionIndex),
256
- evidenceTitles: check.claimIds.map((id) => `Research claim: ${id}`),
265
+ evidenceTitles: check.method === "tool_verified" && check.status === "passed" ? [`Delivery check ${check.criterionIndex + 1}`] : check.claimIds.map((id) => `Research claim: ${id}`),
257
266
  note: check.note,
258
- method: currentResearch.review === "model_reviewed" ? "model_reviewed" : "unverified"
267
+ method: check.method ?? (currentResearch.review === "model_reviewed" ? "model_reviewed" : "unverified")
259
268
  })) ?? (task.contract?.acceptanceCriteria ?? []).map((criterion) => ({
260
269
  criterion,
261
270
  status: "unverified",
@@ -287,10 +296,11 @@ var TaskRunCoordinator = class TaskRunCoordinator {
287
296
  evidence: [
288
297
  ...this.#evidence,
289
298
  ...researchEvidence,
299
+ ...deliveryEvidence,
290
300
  ...structuralCheck ? [structuralCheck.evidence] : []
291
301
  ],
292
302
  verification: {
293
- status: achieved ? "passed" : [...checks, ...instructionChecks].some((check) => check.status === "failed") ? "failed" : "unverified",
303
+ status: achieved ? "passed" : publications.missing.length > 0 || [...checks, ...instructionChecks].some((check) => check.status === "failed") ? "failed" : "unverified",
294
304
  checks: [...checks, ...instructionChecks]
295
305
  },
296
306
  remainingWork: repair ? repair.gaps : emptySuccess ? [task.contract?.objective ?? (zh ? "完成任务" : "Complete the task")] : achieved ? [] : status === "succeeded" ? currentResearch ? [...currentResearch.checks.filter((check) => check.status !== "passed").map((check) => check.criterion), ...currentResearch.claims.filter((claim) => claim.support !== "supported").map((claim) => claim.note ?? claim.statement)] : task.contract?.acceptanceCriteria ?? [] : [],
@@ -299,7 +309,7 @@ var TaskRunCoordinator = class TaskRunCoordinator {
299
309
  completionVerdict: achieved ? "achieved" : status === "succeeded" ? "partial" : "not_achieved",
300
310
  ...finalStatus === "failed" ? { failure: {
301
311
  code: acceptanceFailed ? "acceptance_incomplete" : unconfirmedEffects ? "tool_outcome_unconfirmed" : emptySuccess ? "empty_agent_run" : "agent_run_failed",
302
- phase: "execution",
312
+ phase: acceptanceFailed ? "verification" : "execution",
303
313
  recoveryAction: acceptanceFailed ? zh ? "自动补做后仍有未核验项;检查已记录的缺口后重试任务" : "Automatic repair left unverified requirements; inspect the recorded gaps and retry" : unconfirmedEffects ? zh ? "检查上次操作的实际影响后再恢复任务" : "Confirm the previous operation effects before resuming" : zh ? "使用其他可用助手或模型重试任务" : "Retry the task run with another available Agent or model"
304
314
  } } : {}
305
315
  }
@@ -6,6 +6,7 @@ export declare class TaskRunDispatcher {
6
6
  maxConcurrency?: number;
7
7
  ensureSession: (taskId: string, runId: string, agentId?: string) => Promise<string>;
8
8
  validateExecutor?: (taskId: string, agentId?: string) => void;
9
+ preflightModel?: (conversationId: string) => Promise<void>;
9
10
  runAgent: (runId: string, conversationId: string, message: string) => Promise<void>;
10
11
  });
11
12
  dispatch(): void;
@@ -8,6 +8,7 @@ import { RECOVERY_READ_TOOLS, findUnconfirmedToolEffect } from "../agent/orchest
8
8
  import { resolveTaskLocale } from "./task-language.js";
9
9
  import { TaskApplicationService } from "./task-application-service.js";
10
10
  import { runInIndependentAgentExecution } from "../agent/independent-execution.js";
11
+ import { TaskModelPreflightError } from "../agent/models/turn-candidates.js";
11
12
  //#region src/tasks/task-run-dispatcher.ts
12
13
  init_logger();
13
14
  init_task_repository();
@@ -102,44 +103,47 @@ var TaskRunDispatcher = class {
102
103
  if (!run) return;
103
104
  const task = this.#tasks.get(run.taskId);
104
105
  if (!task) continue;
106
+ const zh = resolveTaskLocale(task) === "zh";
107
+ const retireSuperseded = (expectedRunVersion) => {
108
+ const summary = zh ? "任务要求已更新,本次执行未启动。" : "Task requirements changed before execution.";
109
+ this.#application.completeRun({
110
+ runId: run.id,
111
+ expectedRunVersion,
112
+ terminalCode: "spec_superseded",
113
+ receipt: {
114
+ status: "cancelled",
115
+ summary,
116
+ changes: [],
117
+ evidence: [],
118
+ verification: {
119
+ status: "unverified",
120
+ checks: []
121
+ },
122
+ remainingWork: [],
123
+ needsUser: false
124
+ }
125
+ });
126
+ };
105
127
  try {
106
- if (!(run.status === "waiting" ? this.#runs.setStatus({
128
+ const executableRun = run.status === "waiting" ? this.#runs.setStatus({
107
129
  runId: run.id,
108
130
  expectedVersion: run.version,
109
131
  from: ["waiting"],
110
- to: "running",
132
+ to: run.startedAt === void 0 ? "queued" : "running",
111
133
  actor: {
112
134
  kind: "system",
113
135
  id: workerId
114
136
  }
115
- }) : run)) continue;
137
+ }) : run;
138
+ if (!executableRun) continue;
116
139
  const agentId = typeof run.executorRef.agentId === "string" ? run.executorRef.agentId : void 0;
117
140
  const conversationId = task.latestContractVersion === run.contractVersion ? await this.deps.ensureSession(task.id, run.id, agentId) : void 0;
118
141
  if (this.#stopped) return;
119
142
  if (!conversationId || this.#tasks.get(task.id)?.latestContractVersion !== run.contractVersion) {
120
- const summary = resolveTaskLocale(task) === "zh" ? "任务要求已更新,本次执行未启动。" : "Task requirements changed before execution.";
121
143
  const current = this.#runs.get(run.id);
122
- if (!current) continue;
123
- this.#application.completeRun({
124
- runId: current.id,
125
- expectedRunVersion: current.version,
126
- terminalCode: "spec_superseded",
127
- receipt: {
128
- status: "cancelled",
129
- summary,
130
- changes: [],
131
- evidence: [],
132
- verification: {
133
- status: "unverified",
134
- checks: []
135
- },
136
- remainingWork: [],
137
- needsUser: false
138
- }
139
- });
144
+ if (current?.leaseOwner === workerId) retireSuperseded(current.version);
140
145
  continue;
141
146
  }
142
- this.deps.validateExecutor?.(task.id, agentId);
143
147
  this.#activeRunIds.add(run.id);
144
148
  const heartbeat = setInterval(() => {
145
149
  if (!this.#runs.heartbeat({
@@ -154,6 +158,15 @@ var TaskRunDispatcher = class {
154
158
  heartbeat.unref?.();
155
159
  this.#heartbeats.add(heartbeat);
156
160
  try {
161
+ await this.deps.preflightModel?.(conversationId);
162
+ if (this.#stopped) return;
163
+ const current = this.#runs.get(run.id);
164
+ if (current?.version !== executableRun.version || current.leaseOwner !== workerId) continue;
165
+ if (this.#tasks.get(task.id)?.latestContractVersion !== run.contractVersion) {
166
+ retireSuperseded(current.version);
167
+ continue;
168
+ }
169
+ this.deps.validateExecutor?.(task.id, agentId);
157
170
  await this.deps.runAgent(run.id, conversationId, buildTaskRunMessage(task.contract?.objective ?? task.title, run.trigger, task.contract?.brief, task.id));
158
171
  } finally {
159
172
  clearInterval(heartbeat);
@@ -163,36 +176,53 @@ var TaskRunDispatcher = class {
163
176
  } catch (error) {
164
177
  if (this.#stopped) return;
165
178
  const current = this.#runs.get(run.id);
166
- if (current?.status === "waiting" && current.policySnapshot.continuation) continue;
167
- if (current && [
179
+ if (current?.status === "waiting" && current.policySnapshot.continuation && !(error instanceof TaskModelPreflightError)) continue;
180
+ if (current?.leaseOwner === workerId && [
168
181
  "queued",
169
182
  "running",
170
183
  "waiting",
171
184
  "verifying"
172
- ].includes(current.status)) this.#application.completeRun({
173
- runId: current.id,
174
- expectedRunVersion: current.version,
175
- terminalCode: "dispatch_failed",
176
- terminalMessage: error instanceof Error ? error.message : String(error),
177
- receipt: {
178
- status: "failed",
179
- summary: resolveTaskLocale(task) === "zh" ? "任务执行调度失败" : "TaskRun dispatch failed",
180
- changes: [],
181
- evidence: [],
182
- verification: {
183
- status: "unverified",
184
- checks: []
185
- },
186
- remainingWork: [task.contract?.objective ?? task.title],
187
- needsUser: false,
188
- completionVerdict: "not_achieved",
189
- failure: {
190
- code: "dispatch_failed",
191
- phase: "dispatch",
192
- recoveryAction: resolveTaskLocale(task) === "zh" ? "重试任务执行" : "Retry the task run"
193
- }
185
+ ].includes(current.status)) {
186
+ if (error instanceof TaskModelPreflightError && this.#tasks.get(task.id)?.latestContractVersion !== run.contractVersion) {
187
+ retireSuperseded(current.version);
188
+ continue;
194
189
  }
195
- });
190
+ const preflight = error instanceof TaskModelPreflightError ? error : void 0;
191
+ const code = preflight?.code ?? "dispatch_failed";
192
+ const diagnostic = error instanceof Error ? error.message : String(error);
193
+ const summary = preflight ? JSON.stringify({
194
+ kind: code,
195
+ code,
196
+ provider: preflight.provider,
197
+ modelRef: preflight.modelRef,
198
+ deepLink: "/settings/capabilities/models",
199
+ message: diagnostic
200
+ }) : zh ? "任务执行调度失败" : "TaskRun dispatch failed";
201
+ this.#application.completeRun({
202
+ runId: current.id,
203
+ expectedRunVersion: current.version,
204
+ terminalCode: code,
205
+ terminalMessage: preflight ? summary : diagnostic,
206
+ receipt: {
207
+ status: "failed",
208
+ summary,
209
+ changes: [],
210
+ evidence: [],
211
+ verification: {
212
+ status: "unverified",
213
+ checks: []
214
+ },
215
+ remainingWork: [task.contract?.objective ?? task.title],
216
+ needsUser: false,
217
+ completionVerdict: "not_achieved",
218
+ failure: {
219
+ code,
220
+ phase: preflight ? "preflight" : "dispatch",
221
+ recoveryAction: preflight ? zh ? "在模型设置中检查执行模型及凭证后重试" : "Check the execution model and its credentials in Model Settings, then retry" : zh ? "重试任务执行" : "Retry the task run"
222
+ }
223
+ }
224
+ });
225
+ }
196
226
  log.warn({
197
227
  err: error,
198
228
  runId: run.id
@@ -231,7 +231,7 @@ var init_task_run_repository = __esmMin((() => {
231
231
  const now = input.now ?? Date.now();
232
232
  return getSqliteDatabase().prepare(`UPDATE task_runs SET heartbeat_at = ?, lease_expires_at = ?
233
233
  WHERE run_id = ? AND lease_owner = ?
234
- AND status IN ('running', 'waiting', 'verifying')`).run(now, now + input.leaseMs, input.runId, input.owner).changes === 0 ? void 0 : this.get(input.runId);
234
+ AND status IN ('queued', 'running', 'waiting', 'verifying')`).run(now, now + input.leaseMs, input.runId, input.owner).changes === 0 ? void 0 : this.get(input.runId);
235
235
  }
236
236
  listExpiredLeasedRunning(now = Date.now(), limit = 50) {
237
237
  return getSqliteDatabase().prepare(`SELECT * FROM task_runs
@@ -101,4 +101,5 @@ export type CommandHandlerDeps = {
101
101
  recoverStream?: () => void | Promise<void>;
102
102
  retryLastMessage?: () => void | Promise<void>;
103
103
  };
104
- export declare function createTuiCommandHandler(deps: CommandHandlerDeps): (input: string) => void;
104
+ /** Returns false when the input has no TUI command handler. */
105
+ export declare function createTuiCommandHandler(deps: CommandHandlerDeps): (input: string) => false | void;