@xopcai/xopc 0.0.385 → 0.0.387

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 (360) hide show
  1. package/dist/browser-ext/dist/sidepanel.js +1 -1
  2. package/dist/browser-ext/manifest.json +1 -1
  3. package/dist/extensions/telegram/xopc.extension.json +1 -1
  4. package/dist/gateway/static/root/assets/{agent-avatar-dicebear-Cb9eaXxR.js → agent-avatar-dicebear-Bv8M5ygD.js} +1 -1
  5. package/dist/gateway/static/root/assets/{agent-defaults-settings-panel-DEV-xtgm.js → agent-defaults-settings-panel-UBy01-65.js} +1 -1
  6. package/dist/gateway/static/root/assets/{agent-plugin-dialog-DXKc3Luj.js → agent-plugin-dialog-Q9guA8kU.js} +1 -1
  7. package/dist/gateway/static/root/assets/{agents-DcNxwpJQ.js → agents-yfJFubD0.js} +3 -3
  8. package/dist/gateway/static/root/assets/{app-management-settings-panel-X5i0Tz7_.js → app-management-settings-panel-Cdyad8c1.js} +1 -1
  9. package/dist/gateway/static/root/assets/{appearance-settings-CmHHzquT.js → appearance-settings-DPPvnKH_.js} +1 -1
  10. package/dist/gateway/static/root/assets/{apps-page-ChFA4Zp0.js → apps-page-Bn_jwaeA.js} +1 -1
  11. package/dist/gateway/static/root/assets/{automations-page-BFqsIqOI.js → automations-page-CAB2sLJ5.js} +1 -1
  12. package/dist/gateway/static/root/assets/{automations-workspace-Blfak-fT.js → automations-workspace-CYRUhhH4.js} +1 -1
  13. package/dist/gateway/static/root/assets/{block-editor-CpOLG3Co.js → block-editor-B9DmMEa8.js} +1 -1
  14. package/dist/gateway/static/root/assets/{browser-automations-page-BSbTJ9j2.js → browser-automations-page-BHAWpZE2.js} +1 -1
  15. package/dist/gateway/static/root/assets/{browser-settings-page-BUlILJrB.js → browser-settings-page-BG_17NcQ.js} +2 -2
  16. package/dist/gateway/static/root/assets/{capabilities-2Do3eKMM.js → capabilities-BX1rCiVm.js} +1 -1
  17. package/dist/gateway/static/root/assets/{capabilities-XFwwUNU3.js → capabilities-CW389yo6.js} +1 -1
  18. package/dist/gateway/static/root/assets/{capabilities-page-CeRdkwRf.js → capabilities-page-BAnBYWlY.js} +2 -2
  19. package/dist/gateway/static/root/assets/{capabilities-settings-panel-S-cKsGja.js → capabilities-settings-panel-Ca-d6lXk.js} +3 -3
  20. package/dist/gateway/static/root/assets/{capability-header-actions-6w8pQhnn.js → capability-header-actions-B3TL8TcF.js} +1 -1
  21. package/dist/gateway/static/root/assets/{channels-DfNTGBmp.js → channels-BadpS-nq.js} +1 -1
  22. package/dist/gateway/static/root/assets/{chat-terminal-dock-DnoQHpDc.js → chat-terminal-dock-C_vntFpP.js} +1 -1
  23. package/dist/gateway/static/root/assets/{chunk-KS7C4IRE-BMYIfy9x.js → chunk-KS7C4IRE--EKdQGRF.js} +1 -1
  24. package/dist/gateway/static/root/assets/{computer-settings-page-7yliE7sG.js → computer-settings-page-B-5kxk70.js} +1 -1
  25. package/dist/gateway/static/root/assets/{connector-service-page-DOLAUFSW.js → connector-service-page-DTnfpLHL.js} +1 -1
  26. package/dist/gateway/static/root/assets/{connectors-page-DAsn97XG.js → connectors-page-CmJV7gqj.js} +1 -1
  27. package/dist/gateway/static/root/assets/constants-DeXt1mV-.js +1 -0
  28. package/dist/gateway/static/root/assets/{date-picker-DNDqr4Fk.js → date-picker-D5zYeC8q.js} +1 -1
  29. package/dist/gateway/static/root/assets/{dependency-picker-B5oG7RgE.js → dependency-picker-D72vT-tb.js} +1 -1
  30. package/dist/gateway/static/root/assets/{desktop-pet-K7kUCX1O.js → desktop-pet-DvoeVPf_.js} +1 -1
  31. package/dist/gateway/static/root/assets/{desktop-pet-settings-KgOAuqSh.js → desktop-pet-settings-Dfb392hs.js} +1 -1
  32. package/dist/gateway/static/root/assets/{device-pairing-wizard-DvqniZDm.js → device-pairing-wizard-B06Sqn5D.js} +1 -1
  33. package/dist/gateway/static/root/assets/{directory-picker-path-field-BmOguLDl.js → directory-picker-path-field-CA3H3bc-.js} +1 -1
  34. package/dist/gateway/static/root/assets/{extension-debug-page-DtHNy4TE.js → extension-debug-page-B0wTBCx4.js} +1 -1
  35. package/dist/gateway/static/root/assets/{extension-page-DSSuMQxp.js → extension-page-BeHiXhB1.js} +1 -1
  36. package/dist/gateway/static/root/assets/{extension-provider-nbgU7xBS.js → extension-provider-CJZ5EVpQ.js} +1 -1
  37. package/dist/gateway/static/root/assets/{extension-settings-page-DSd__mNd.js → extension-settings-page-Q88-LFCJ.js} +1 -1
  38. package/dist/gateway/static/root/assets/{fallback-models-D7bjbiwZ.js → fallback-models-BXoPCvzq.js} +1 -1
  39. package/dist/gateway/static/root/assets/{gateway-settings-hSXGWumL.js → gateway-settings-IICLMGDI.js} +1 -1
  40. package/dist/gateway/static/root/assets/{highlighted-body-KQOG7T2V-C7xJwE61.js → highlighted-body-KQOG7T2V-D336so8z.js} +1 -1
  41. package/dist/gateway/static/root/assets/home-page--MvqsFhQ.js +2 -0
  42. package/dist/gateway/static/root/assets/{imports-page-BufZPzGE.js → imports-page-muV1SduS.js} +1 -1
  43. package/dist/gateway/static/root/assets/index-D0qMv3jf.js +260 -0
  44. package/dist/gateway/static/root/assets/{keyboard-shortcuts-settings-B8pPP5RF.js → keyboard-shortcuts-settings-i1sDWcwl.js} +1 -1
  45. package/dist/gateway/static/root/assets/{local-app-workbench-page-zEtvE7pJ.js → local-app-workbench-page-DY9tXEO6.js} +1 -1
  46. package/dist/gateway/static/root/assets/{local-apps-page-Bli7e_eg.js → local-apps-page-BHD73STy.js} +1 -1
  47. package/dist/gateway/static/root/assets/local-session-drafts-Be4BGM4Z.js +1 -0
  48. package/dist/gateway/static/root/assets/{logs-page-BimZk3R4.js → logs-page-DsPpe8Ws.js} +1 -1
  49. package/dist/gateway/static/root/assets/{management-settings-5Y4COyU9.js → management-settings-Buwi2wQE.js} +1 -1
  50. package/dist/gateway/static/root/assets/{markdown-view-DHfQAvZQ.js → markdown-view-CBjl-XEc.js} +2 -2
  51. package/dist/gateway/static/root/assets/mermaid-MCJ5UELQ-D2mip-f9.js +1 -0
  52. package/dist/gateway/static/root/assets/{note-detail-panel-KLDPLVg7.js → note-detail-panel-D8n80Gbr.js} +3 -3
  53. package/dist/gateway/static/root/assets/{notes-api-nqN2wKYc.js → notes-api-BlGP533W.js} +1 -1
  54. package/dist/gateway/static/root/assets/{notes-page-DST0oPXD.js → notes-page-Btf-jSS_.js} +5 -5
  55. package/dist/gateway/static/root/assets/{page-context-capture-button-Bmed83-6.js → page-context-capture-button-97RL8Gc7.js} +1 -1
  56. package/dist/gateway/static/root/assets/{personal-page-BG4Ystrm.js → personal-page-B04L8Oz5.js} +1 -1
  57. package/dist/gateway/static/root/assets/product-open-page-9zEDvZa7.js +1 -0
  58. package/dist/gateway/static/root/assets/{product-preview-content-DjmupQSq.js → product-preview-content-DynBrIXq.js} +1 -1
  59. package/dist/gateway/static/root/assets/{project-detail-page-CzBmV0P6.js → project-detail-page-BM7MsoVA.js} +1 -1
  60. package/dist/gateway/static/root/assets/{projects-page-DByqe5Em.js → projects-page-pcyeEJnz.js} +1 -1
  61. package/dist/gateway/static/root/assets/{remote-access-hub-DTjj-odF.js → remote-access-hub-CphyTu22.js} +1 -1
  62. package/dist/gateway/static/root/assets/{runtime-tools-settings-panel-B_ptn3T8.js → runtime-tools-settings-panel-DPafoO0G.js} +1 -1
  63. package/dist/gateway/static/root/assets/{scenes-page-wkua4l5y.js → scenes-page-j97FrDRW.js} +2 -2
  64. package/dist/gateway/static/root/assets/{schema-form-VvOSM84Y.js → schema-form-CuJNwKHO.js} +1 -1
  65. package/dist/gateway/static/root/assets/{send-session-input-BCAF-Ikt.js → send-session-input-C293-Hbx.js} +1 -1
  66. package/dist/gateway/static/root/assets/session-manager-COd9RECl.js +16 -0
  67. package/dist/gateway/static/root/assets/{sessions-page-D06XwYAT.js → sessions-page-D8t_8fMl.js} +1 -1
  68. package/dist/gateway/static/root/assets/settings-advanced-gate-CDkitNHA.js +1 -0
  69. package/dist/gateway/static/root/assets/{settings-page-C-6BJdb1.js → settings-page-DS9DMYUe.js} +1 -1
  70. package/dist/gateway/static/root/assets/{setup-status-panel-L0JSG0K-.js → setup-status-panel-DRDvm9yZ.js} +1 -1
  71. package/dist/gateway/static/root/assets/{share-link-dialog-C47Xgzta.js → share-link-dialog-BKGI8Kr0.js} +1 -1
  72. package/dist/gateway/static/root/assets/{share-preview-page-nJ2FWAEP.js → share-preview-page-BF2WaO43.js} +1 -1
  73. package/dist/gateway/static/root/assets/{shares-settings-BbgAUM3v.js → shares-settings-DQTQZu6V.js} +1 -1
  74. package/dist/gateway/static/root/assets/{skill-api-BFU1tPyw.js → skill-api-DzVa7G-O.js} +1 -1
  75. package/dist/gateway/static/root/assets/{skills-page-DZw6el4o.js → skills-page-CfJIjRdS.js} +1 -1
  76. package/dist/gateway/static/root/assets/{system-settings-panel-DshSGWNg.js → system-settings-panel-Bzhqed-a.js} +1 -1
  77. package/dist/gateway/static/root/assets/task-detail-page-BYQFC0-U.js +2 -0
  78. package/dist/gateway/static/root/assets/task-expandable-content-C9ohICpw.js +1 -0
  79. package/dist/gateway/static/root/assets/{tasks-DJIeIk9C.js → tasks-PuIUgF9L.js} +1 -1
  80. package/dist/gateway/static/root/assets/{tunnel-api-DFDXwWnU.js → tunnel-api-DrgpZ81I.js} +1 -1
  81. package/dist/gateway/static/root/assets/{usage-page-2RJLg54s.js → usage-page-Drk8FWnj.js} +1 -1
  82. package/dist/gateway/static/root/assets/{use-composer-attachments-BFP3k6oC.js → use-composer-attachments-rgW7h4sD.js} +1 -1
  83. package/dist/gateway/static/root/assets/{use-file-preview-expanded-B1BiTQNS.js → use-file-preview-expanded-DSKIxfz9.js} +1 -1
  84. package/dist/gateway/static/root/assets/{user-model-page-y1gjGYPI.js → user-model-page-07t2-nFE.js} +2 -2
  85. package/dist/gateway/static/root/assets/{work-discovery-overlay-Ch-KfpCF.js → work-discovery-overlay-TQ5bjVot.js} +1 -1
  86. package/dist/gateway/static/root/assets/{workflow-run-setup-panel-CTu297Hc.js → workflow-run-setup-panel-C9HP2uGG.js} +1 -1
  87. package/dist/gateway/static/root/assets/{workflows-page-CRZXG_rm.js → workflows-page-DK01JRI1.js} +3 -3
  88. package/dist/gateway/static/root/assets/{workspace-api-Xr3wz8T3.js → workspace-api-JWHOFos6.js} +2 -2
  89. package/dist/gateway/static/root/assets/{xopc-cloud-account-card-hEfjVjnc.js → xopc-cloud-account-card-B-BhQdAf.js} +1 -1
  90. package/dist/gateway/static/root/index.html +16 -16
  91. package/dist/package.js +1 -1
  92. package/dist/packages/gateway-contract/src/index.js +4 -0
  93. package/dist/packages/gateway-contract/src/result-reference.js +25 -0
  94. package/dist/packages/gateway-contract/src/session-input-command.js +2 -1
  95. package/dist/packages/gateway-contract/src/task-research-result.js +90 -0
  96. package/dist/packages/gateway-contract/src/task-result-delivery.js +21 -0
  97. package/dist/packages/gateway-contract/src/tasks.js +7 -1
  98. package/dist/packages/gateway-contract/src/turn-outcome.js +4 -0
  99. package/dist/src/agent/agent-manager.js +3 -3
  100. package/dist/src/agent/background-review/run-background-review.js +1 -1
  101. package/dist/src/agent/child-agent-factory.d.ts +4 -1
  102. package/dist/src/agent/child-agent-factory.js +86 -12
  103. package/dist/src/agent/context/connection-objective-context.d.ts +1 -0
  104. package/dist/src/agent/context/connection-objective-context.js +33 -0
  105. package/dist/src/agent/data-acquisition/service.js +41 -6
  106. package/dist/src/agent/data-acquisition/types.d.ts +2 -0
  107. package/dist/src/agent/embedded/agent-profile-context.d.ts +7 -0
  108. package/dist/src/agent/embedded/agent-profile-context.js +92 -0
  109. package/dist/src/agent/embedded/run-for-session.js +5 -2
  110. package/dist/src/agent/embedded/run-turn.js +19 -6
  111. package/dist/src/agent/embedded/runs.d.ts +9 -2
  112. package/dist/src/agent/embedded/runs.js +30 -7
  113. package/dist/src/agent/embedded/session-runner.js +5 -2
  114. package/dist/src/agent/embedded/types.d.ts +4 -0
  115. package/dist/src/agent/embedded/xopc-tools-bridge.js +13 -2
  116. package/dist/src/agent/external-tools/cliProvider.js +1 -1
  117. package/dist/src/agent/external-tools/composio-provider.js +2 -2
  118. package/dist/src/agent/external-tools/endpoint-provider.js +2 -2
  119. package/dist/src/agent/external-tools/gateway-tools.js +8 -4
  120. package/dist/src/agent/inbound/attachment-pipeline.js +1 -1
  121. package/dist/src/agent/orchestration/agent-run-supervisor.js +2 -1
  122. package/dist/src/agent/orchestration/agent-turn-policy.js +5 -1
  123. package/dist/src/agent/orchestration/delegation-budget.d.ts +7 -1
  124. package/dist/src/agent/orchestration/delegation-budget.js +17 -9
  125. package/dist/src/agent/orchestration/research-checkpoint.d.ts +56 -0
  126. package/dist/src/agent/orchestration/research-checkpoint.js +64 -0
  127. package/dist/src/agent/orchestration/run-agent-turn-with-timeout.d.ts +3 -1
  128. package/dist/src/agent/orchestration/run-agent-turn-with-timeout.js +15 -2
  129. package/dist/src/agent/orchestration/run-termination.d.ts +12 -0
  130. package/dist/src/agent/orchestration/run-termination.js +24 -0
  131. package/dist/src/agent/orchestration/turn-recovery.d.ts +4 -1
  132. package/dist/src/agent/orchestration/turn-recovery.js +19 -3
  133. package/dist/src/agent/prompt/sections/agent-identity.js +12 -7
  134. package/dist/src/agent/prompt/sections/messaging-runtime.js +1 -1
  135. package/dist/src/agent/prompt/sections/project-context.js +1 -1
  136. package/dist/src/agent/prompt/sections/response-language.d.ts +1 -1
  137. package/dist/src/agent/prompt/sections/response-language.js +6 -2
  138. package/dist/src/agent/prompt/subagent-context.js +1 -1
  139. package/dist/src/agent/prompt/system-prompt.js +4 -6
  140. package/dist/src/agent/service/direct-turn-helpers.d.ts +2 -0
  141. package/dist/src/agent/service/direct-turn-helpers.js +4 -0
  142. package/dist/src/agent/service/process-direct-one-shot.js +4 -1
  143. package/dist/src/agent/service/process-direct-streaming.js +3 -2
  144. package/dist/src/agent/service.js +2 -2
  145. package/dist/src/agent/skills/index.js +1 -1
  146. package/dist/src/agent/skills/managed-store.js +1 -1
  147. package/dist/src/agent/skills/skill-manage-ops.js +1 -1
  148. package/dist/src/agent/source-context/index.js +1 -1
  149. package/dist/src/agent/source-context/result-context.d.ts +2 -0
  150. package/dist/src/agent/source-context/result-context.js +32 -0
  151. package/dist/src/agent/source-context/types.d.ts +2 -2
  152. package/dist/src/agent/source-context/types.js +1 -1
  153. package/dist/src/agent/tasks/task-judge-service.js +3 -1
  154. package/dist/src/agent/tools/apply-patch.js +1 -1
  155. package/dist/src/agent/tools/delegate-tool.js +216 -121
  156. package/dist/src/agent/tools/delegation-policy.js +13 -1
  157. package/dist/src/agent/tools/exec-command.js +47 -2
  158. package/dist/src/agent/tools/factory.js +19 -10
  159. package/dist/src/agent/tools/index.d.ts +1 -0
  160. package/dist/src/agent/tools/index.js +2 -1
  161. package/dist/src/agent/tools/language-diagnostics.js +1 -1
  162. package/dist/src/agent/tools/personal-performance.d.ts +2 -0
  163. package/dist/src/agent/tools/personal-performance.js +82 -0
  164. package/dist/src/agent/tools/personal-read-tool.js +1 -1
  165. package/dist/src/agent/tools/personal-request-tool.js +9 -14
  166. package/dist/src/agent/tools/personal-result-tool.d.ts +2 -0
  167. package/dist/src/agent/tools/personal-result-tool.js +106 -0
  168. package/dist/src/agent/tools/personal-task-tool.d.ts +12 -3
  169. package/dist/src/agent/tools/personal-task-tool.js +115 -10
  170. package/dist/src/agent/tools/publish-artifacts.js +1 -1
  171. package/dist/src/agent/tools/research-checkpoint-tool.d.ts +3 -0
  172. package/dist/src/agent/tools/research-checkpoint-tool.js +28 -0
  173. package/dist/src/agent/tools/review-workspace.js +21 -2
  174. package/dist/src/agent/tools/search/cache.d.ts +20 -0
  175. package/dist/src/agent/tools/search/cache.js +19 -0
  176. package/dist/src/agent/tools/search/errors.d.ts +19 -0
  177. package/dist/src/agent/tools/search/errors.js +69 -0
  178. package/dist/src/agent/tools/search/providers/bing-api.js +2 -1
  179. package/dist/src/agent/tools/search/providers/bing-html.js +2 -1
  180. package/dist/src/agent/tools/search/providers/brave.js +2 -1
  181. package/dist/src/agent/tools/search/providers/duckduckgo-html.js +2 -1
  182. package/dist/src/agent/tools/search/providers/searxng.js +2 -1
  183. package/dist/src/agent/tools/search/providers/tavily.js +2 -1
  184. package/dist/src/agent/tools/search/providers/xopc-cloud.d.ts +1 -0
  185. package/dist/src/agent/tools/search/providers/xopc-cloud.js +7 -2
  186. package/dist/src/agent/tools/search/registry.d.ts +21 -5
  187. package/dist/src/agent/tools/search/registry.js +252 -25
  188. package/dist/src/agent/tools/search/types.d.ts +25 -0
  189. package/dist/src/agent/tools/send-media.js +1 -1
  190. package/dist/src/agent/tools/task-collaboration-tool.d.ts +9 -1
  191. package/dist/src/agent/tools/task-collaboration-tool.js +121 -2
  192. package/dist/src/agent/tools/task-evidence.d.ts +3 -0
  193. package/dist/src/agent/tools/task-evidence.js +71 -0
  194. package/dist/src/agent/tools/task-result-tool.d.ts +2 -0
  195. package/dist/src/agent/tools/task-result-tool.js +93 -0
  196. package/dist/src/agent/tools/tool-media.js +1 -1
  197. package/dist/src/agent/tools/web.d.ts +16 -2
  198. package/dist/src/agent/tools/web.js +74 -29
  199. package/dist/src/agent/tools/xopc-use-tool.js +27 -6
  200. package/dist/src/agent/workspace-runtime/registry.js +1 -1
  201. package/dist/src/agent-catalog/capabilities.js +2 -2
  202. package/dist/src/automations/capabilities/drafts.js +1 -1
  203. package/dist/src/automations/capabilities/write.d.ts +4 -4
  204. package/dist/src/automations/domain/validation.d.ts +8 -8
  205. package/dist/src/automations/draft/automation-draft-validator.d.ts +2 -2
  206. package/dist/src/automations/service/action-executor.js +1 -1
  207. package/dist/src/bootstrap/application-state.js +1 -1
  208. package/dist/src/browser/automations/schema.d.ts +2 -2
  209. package/dist/src/browser/automations/service.d.ts +2 -2
  210. package/dist/src/capabilities/runtime/dispatcher.js +1 -1
  211. package/dist/src/capabilities/runtime/product.js +1 -1
  212. package/dist/src/chat-commands/agent-edit.js +1 -1
  213. package/dist/src/cli/commands/agent.js +1 -1
  214. package/dist/src/cli/commands/agents.js +1 -1
  215. package/dist/src/cli/commands/doctor/checks/database-schema.js +1 -1
  216. package/dist/src/cli/commands/models.js +1 -1
  217. package/dist/src/cli/commands/onboard/model.js +1 -1
  218. package/dist/src/cli/utils/init-workspace-core.js +1 -1
  219. package/dist/src/config/agent-profile.js +2 -2
  220. package/dist/src/config/index.js +2 -2
  221. package/dist/src/config/loader.js +1 -1
  222. package/dist/src/config/models-json.js +1 -1
  223. package/dist/src/config/schema.d.ts +1 -0
  224. package/dist/src/config/schema.js +5 -2
  225. package/dist/src/connectors/connection-recovery-service.d.ts +3 -1
  226. package/dist/src/connectors/connection-recovery-service.js +67 -6
  227. package/dist/src/discussions/action-tasks.d.ts +2 -2
  228. package/dist/src/extensions/agent-plugins/validation.js +1 -1
  229. package/dist/src/gateway/agent-builtin-tools.d.ts +1 -1
  230. package/dist/src/gateway/agents-admin.js +2 -2
  231. package/dist/src/gateway/hono/lib/config-payload.js +1 -1
  232. package/dist/src/gateway/hono/routes/agent-stream.js +1 -1
  233. package/dist/src/gateway/hono/routes/config-patch/misc.js +2 -2
  234. package/dist/src/gateway/hono/routes/connectors.js +1 -1
  235. package/dist/src/gateway/hono/routes/context-sources.js +1 -1
  236. package/dist/src/gateway/hono/routes/notes.js +2 -2
  237. package/dist/src/gateway/hono/routes/projects.js +3 -3
  238. package/dist/src/gateway/hono/routes/session-input-handler.d.ts +18 -2
  239. package/dist/src/gateway/hono/routes/session-input-handler.js +2 -2
  240. package/dist/src/gateway/hono/routes/tasks.js +2 -2
  241. package/dist/src/gateway/image-generation-setup.js +1 -1
  242. package/dist/src/gateway/lock.js +1 -1
  243. package/dist/src/gateway/media-access.js +1 -1
  244. package/dist/src/gateway/service/agent-runner.d.ts +2 -0
  245. package/dist/src/gateway/service/agent-runner.js +30 -17
  246. package/dist/src/gateway/service/run-gateway-agent.js +32 -2
  247. package/dist/src/gateway/service/session-input-coordinator.d.ts +10 -1
  248. package/dist/src/gateway/service/session-input-coordinator.js +214 -27
  249. package/dist/src/gateway/service.d.ts +1 -0
  250. package/dist/src/gateway/service.js +49 -16
  251. package/dist/src/gateway/session-context-summary.js +1 -1
  252. package/dist/src/gateway/xopc-cloud-capability-setup.js +1 -1
  253. package/dist/src/home-intelligence/host.js +2 -2
  254. package/dist/src/local-apps/service.js +1 -1
  255. package/dist/src/media/session-references.js +1 -1
  256. package/dist/src/personal-agent/communication.js +1 -0
  257. package/dist/src/personal-agent/performance.d.ts +83 -0
  258. package/dist/src/personal-agent/performance.js +65 -0
  259. package/dist/src/personal-agent/policy.d.ts +1 -1
  260. package/dist/src/personal-agent/policy.js +1 -0
  261. package/dist/src/personal-agent/proactivity/service.js +1 -1
  262. package/dist/src/personal-agent/prompt-context.js +3 -1
  263. package/dist/src/personal-agent/prompts.js +10 -4
  264. package/dist/src/personal-agent/reply-composer.d.ts +1 -0
  265. package/dist/src/personal-agent/reply-composer.js +149 -20
  266. package/dist/src/personal-agent/reply-style.d.ts +1 -1
  267. package/dist/src/personal-agent/reply-style.js +1 -0
  268. package/dist/src/personal-agent/repository.d.ts +1 -1
  269. package/dist/src/personal-agent/repository.js +1 -1
  270. package/dist/src/personal-agent/request-delivery.js +3 -1
  271. package/dist/src/personal-agent/request-repository.d.ts +2 -0
  272. package/dist/src/personal-agent/request-service.d.ts +4 -0
  273. package/dist/src/personal-agent/request-service.js +91 -20
  274. package/dist/src/personal-agent/result-extraction.d.ts +42 -0
  275. package/dist/src/personal-agent/result-extraction.js +209 -0
  276. package/dist/src/personal-agent/result-file-links.d.ts +3 -0
  277. package/dist/src/personal-agent/result-file-links.js +21 -0
  278. package/dist/src/personal-agent/result-read-continuations.d.ts +13 -0
  279. package/dist/src/personal-agent/result-read-continuations.js +78 -0
  280. package/dist/src/personal-agent/result-reader.d.ts +43 -0
  281. package/dist/src/personal-agent/result-reader.js +461 -0
  282. package/dist/src/personal-agent/service.js +2 -2
  283. package/dist/src/personal-agent/task-cancel.js +85 -35
  284. package/dist/src/providers/model-catalog-persistence.js +1 -1
  285. package/dist/src/routing/resolve-route.js +1 -1
  286. package/dist/src/routing/resolve-tui-session-key.js +1 -1
  287. package/dist/src/scenes/taskFollowUp/service.d.ts +15 -5
  288. package/dist/src/session/client-history.d.ts +1 -1
  289. package/dist/src/session/client-history.js +1 -1
  290. package/dist/src/session/session-context-for-llm.js +4 -2
  291. package/dist/src/session/store.d.ts +3 -1
  292. package/dist/src/session/store.js +13 -3
  293. package/dist/src/share/hosted-session-share.js +1 -1
  294. package/dist/src/storage/sqlite/connection-wait-repository.d.ts +5 -2
  295. package/dist/src/storage/sqlite/connection-wait-repository.js +42 -17
  296. package/dist/src/storage/sqlite/index.d.ts +1 -0
  297. package/dist/src/storage/sqlite/index.js +3 -1
  298. package/dist/src/storage/sqlite/migrations/250_research_checkpoints.sql +15 -0
  299. package/dist/src/storage/sqlite/migrations/251_personal_result_reads.sql +40 -0
  300. package/dist/src/storage/sqlite/migrations/252_task_work_revisions.sql +15 -0
  301. package/dist/src/storage/sqlite/migrations/runner.d.ts +1 -1
  302. package/dist/src/storage/sqlite/migrations/runner.js +3 -3
  303. package/dist/src/storage/sqlite/research-checkpoint-repository.d.ts +24 -0
  304. package/dist/src/storage/sqlite/research-checkpoint-repository.js +91 -0
  305. package/dist/src/storage/sqlite/schema.js +1 -1
  306. package/dist/src/storage/sqlite/session-creation-repository.js +3 -2
  307. package/dist/src/storage/sqlite/session-input-repository.d.ts +16 -0
  308. package/dist/src/storage/sqlite/session-input-repository.js +41 -7
  309. package/dist/src/tasks/capabilities/management.d.ts +2 -2
  310. package/dist/src/tasks/capabilities/read.js +2 -2
  311. package/dist/src/tasks/capabilities/relations.d.ts +7 -7
  312. package/dist/src/tasks/capabilities/write.d.ts +2 -2
  313. package/dist/src/tasks/capabilities/write.js +1 -1
  314. package/dist/src/tasks/index.js +1 -1
  315. package/dist/src/tasks/task-allocation-service.d.ts +2 -0
  316. package/dist/src/tasks/task-allocation-service.js +100 -8
  317. package/dist/src/tasks/task-application-service.d.ts +18 -0
  318. package/dist/src/tasks/task-application-service.js +133 -2
  319. package/dist/src/tasks/task-context-assembler.js +13 -5
  320. package/dist/src/tasks/task-continuation.d.ts +1 -0
  321. package/dist/src/tasks/task-continuation.js +1 -0
  322. package/dist/src/tasks/task-contract-definition.d.ts +3 -0
  323. package/dist/src/tasks/task-contract-planner.d.ts +1 -0
  324. package/dist/src/tasks/task-contract-planner.js +61 -20
  325. package/dist/src/tasks/task-conversation-repository.js +1 -1
  326. package/dist/src/tasks/task-evidence-ranges.d.ts +7 -0
  327. package/dist/src/tasks/task-evidence-ranges.js +20 -0
  328. package/dist/src/tasks/task-execution-capabilities.d.ts +26 -0
  329. package/dist/src/tasks/task-execution-capabilities.js +117 -0
  330. package/dist/src/tasks/task-handoff-service.js +1 -1
  331. package/dist/src/tasks/task-handoff.d.ts +56 -0
  332. package/dist/src/tasks/task-handoff.js +510 -0
  333. package/dist/src/tasks/task-model-call.d.ts +7 -0
  334. package/dist/src/tasks/task-model-call.js +35 -0
  335. package/dist/src/tasks/task-read-model-projector.d.ts +6 -0
  336. package/dist/src/tasks/task-read-model-projector.js +12 -1
  337. package/dist/src/tasks/task-research-repair.d.ts +19 -0
  338. package/dist/src/tasks/task-research-repair.js +79 -0
  339. package/dist/src/tasks/task-research-result.d.ts +99 -0
  340. package/dist/src/tasks/task-research-result.js +478 -0
  341. package/dist/src/tasks/task-result-delivery-repository.js +37 -3
  342. package/dist/src/tasks/task-result-delivery-service.js +38 -10
  343. package/dist/src/tasks/task-run-coordinator.js +71 -15
  344. package/dist/src/tasks/task-run-dispatcher.d.ts +1 -0
  345. package/dist/src/tasks/task-run-dispatcher.js +3 -1
  346. package/dist/src/tasks/task-run-repository.d.ts +5 -0
  347. package/dist/src/tasks/task-run-repository.js +88 -1
  348. package/dist/src/tui/backends/embedded-backend.js +2 -2
  349. package/dist/src/voice/realtime/persona-context.js +1 -1
  350. package/package.json +12 -6
  351. package/dist/gateway/static/root/assets/constants-Dy8Gw0sF.js +0 -1
  352. package/dist/gateway/static/root/assets/home-page-DJNmlMfH.js +0 -2
  353. package/dist/gateway/static/root/assets/index-K8SXDtxr.js +0 -260
  354. package/dist/gateway/static/root/assets/local-session-drafts-D_tYFy7d.js +0 -1
  355. package/dist/gateway/static/root/assets/mermaid-MCJ5UELQ-DBRj4-1-.js +0 -1
  356. package/dist/gateway/static/root/assets/product-open-page-CXkYP9xE.js +0 -1
  357. package/dist/gateway/static/root/assets/session-manager-_yy4bxhT.js +0 -16
  358. package/dist/gateway/static/root/assets/settings-advanced-gate-DoAHy1wj.js +0 -1
  359. package/dist/gateway/static/root/assets/task-detail-page-CfZhq4XZ.js +0 -2
  360. package/dist/gateway/static/root/assets/task-expandable-content-CF6Bj-Qa.js +0 -1
@@ -15,10 +15,14 @@ import { extractAssistantText, getAssistantMessageErrorReason, stripCodeFences }
15
15
  import { resolveTaskLocale } from "./task-language.js";
16
16
  import { TaskAllocationRepository } from "./task-allocation-repository.js";
17
17
  import { TaskCollaborationRepository } from "./task-collaboration-repository.js";
18
+ import { defineTaskContract } from "./task-contract-definition.js";
19
+ import { supersededTaskInstructionIds } from "./task-research-result.js";
20
+ import { getTaskHandoff, resolveTaskHandoffReferences } from "./task-handoff.js";
18
21
  import { TaskApplicationService } from "./task-application-service.js";
19
- import { assessSpecialist } from "../agent-matching/service.js";
20
- import { AgentSelectionRepository, selectionRequestHash } from "../agent-matching/selection-repository.js";
21
22
  import { personalCapabilities } from "../personal-agent/capability-service.js";
23
+ import { assessTaskExecutor, captureExecutionRequirements, taskExecutionRequirements } from "./task-execution-capabilities.js";
24
+ import { ModelTaskContractPlanner } from "./task-contract-planner.js";
25
+ import { AgentSelectionRepository, selectionRequestHash } from "../agent-matching/selection-repository.js";
22
26
  import { z } from "zod";
23
27
  //#region src/tasks/task-allocation-service.ts
24
28
  init_src();
@@ -67,6 +71,15 @@ async function decideTaskAllocation(input) {
67
71
  body: input.task.body,
68
72
  contract: input.task.contract
69
73
  })}`,
74
+ `Host-captured handoff: ${JSON.stringify((({ originalRequest, sources, completeness }) => ({
75
+ originalRequest,
76
+ sources: sources.map(({ text: _text, ...source }) => source),
77
+ completeness
78
+ }))(getTaskHandoff(input.task.id) ?? {
79
+ originalRequest: void 0,
80
+ sources: [],
81
+ completeness: void 0
82
+ }))}`,
70
83
  `Task collaboration: ${JSON.stringify(new TaskCollaborationRepository().recent(input.task.id, void 0, 10))}`,
71
84
  `Candidates: ${JSON.stringify(input.candidates)}`
72
85
  ].filter(Boolean).join("\n\n");
@@ -119,7 +132,7 @@ var TaskAllocationDispatcher = class {
119
132
  const row = this.#allocations.claim();
120
133
  if (!row) return;
121
134
  const controller = new AbortController();
122
- const timer = setTimeout(() => controller.abort(/* @__PURE__ */ new Error("Task allocation timed out")), 2e4);
135
+ const timer = setTimeout(() => controller.abort(/* @__PURE__ */ new Error("Task allocation timed out")), 4e4);
123
136
  this.#controllers.add(controller);
124
137
  try {
125
138
  await this.allocate(row, controller.signal);
@@ -133,7 +146,7 @@ var TaskAllocationDispatcher = class {
133
146
  }
134
147
  async allocate(row, signal) {
135
148
  const tasks = new TaskRepository();
136
- const task = tasks.require(row.task_id);
149
+ let task = tasks.require(row.task_id);
137
150
  const zh = resolveTaskLocale(task) === "zh";
138
151
  if (task.version !== row.task_version) {
139
152
  runSqliteWriteTransaction((db) => {
@@ -142,7 +155,76 @@ var TaskAllocationDispatcher = class {
142
155
  return;
143
156
  }
144
157
  const requirements = normalizeSpecialistRequirements(JSON.parse(row.requirements_json));
145
- if ((task.body?.length ?? 0) > 12e3) requirements.requiredTools = [...new Set([...requirements.requiredTools ?? [], "xopc_use"])].sort();
158
+ let inferred = [];
159
+ let handoff;
160
+ try {
161
+ handoff = await resolveTaskHandoffReferences(task.id, this.deps.context(row.origin_conversation_id).getConfig?.());
162
+ } catch (error) {
163
+ this.finishFailure(row, error instanceof Error ? error.message : String(error), "source_reference_unavailable");
164
+ return;
165
+ }
166
+ const superseded = supersededTaskInstructionIds(task.id);
167
+ const activeDirections = new TaskCollaborationRepository().coordination(task.id).filter((entry) => ["main_agent", "user"].includes(entry.authorKind) && ["answer", "instruction"].includes(entry.kind) && !superseded.has(entry.id));
168
+ const taskContext = [
169
+ task.body,
170
+ activeDirections.length ? `Applicable ordered owner directions: ${JSON.stringify(activeDirections.map(({ id, sequence, body }) => ({
171
+ id,
172
+ sequence,
173
+ body
174
+ })))}` : "",
175
+ handoff?.originalRequest ? `Host-captured original user request:\n${handoff.originalRequest}` : "",
176
+ handoff ? `Selected input manifest: ${JSON.stringify(handoff.sources.map(({ text: _text, ...source }) => source))}\nCompleteness: ${JSON.stringify(handoff.completeness)}` : ""
177
+ ].filter(Boolean).join("\n\n");
178
+ if (taskContext.length > 96e3) {
179
+ this.finishFailure(row, zh ? "任务交接超过当前完整规划预算,请拆分任务或缩小引用范围。" : "Handoff exceeds the complete planning budget; split the task or narrow its inputs.", "handoff_budget_exceeded");
180
+ return;
181
+ }
182
+ const fallback = defineTaskContract(task.contract?.objective ?? task.title, task.locale);
183
+ if (task.contract && (this.deps.planner || !this.deps.decide) && !requirements.connector) {
184
+ const planned = await (this.deps.planner ?? new ModelTaskContractPlanner()).plan({
185
+ objective: task.contract.objective,
186
+ taskContext,
187
+ locale: task.locale,
188
+ signal
189
+ });
190
+ if (planned.capabilityPlanning === "unavailable") {
191
+ this.finishFailure(row, zh ? "后台未能完成任务能力清单,请重试分配;尚未启动执行。" : "Background capability planning is unavailable; retry allocation. Execution has not started.", "capability_planning_unavailable");
192
+ return;
193
+ }
194
+ inferred = planned.requiredCapabilities ?? [];
195
+ if (signal.aborted || this.#stopped) throw new Error("Task contract planning interrupted");
196
+ if ((JSON.stringify(task.contract.acceptanceCriteria) === JSON.stringify(fallback.acceptanceCriteria) || Boolean(getSqliteDatabase().prepare("SELECT 1 FROM task_work_revisions WHERE task_id = ? AND contract_version = ?").get(task.id, task.latestContractVersion))) && JSON.stringify(planned.acceptanceCriteria) !== JSON.stringify(fallback.acceptanceCriteria)) {
197
+ const updated = runSqliteWriteTransaction((db) => {
198
+ if (!this.#allocations.owns(row) || tasks.require(task.id).version !== task.version) return void 0;
199
+ const result = new TaskApplicationService().execute({
200
+ taskId: task.id,
201
+ expectedVersion: task.version,
202
+ idempotencyKey: `allocation:${row.id}:criteria`,
203
+ actor: {
204
+ kind: "system",
205
+ id: "task-router"
206
+ },
207
+ command: {
208
+ type: "revise_contract",
209
+ contract: {
210
+ ...task.contract,
211
+ acceptanceCriteria: planned.acceptanceCriteria,
212
+ constraints: [...new Set([...task.contract.constraints, ...planned.constraints])],
213
+ expectedOutputs: Boolean(db.prepare("SELECT 1 FROM task_work_revisions WHERE task_id = ? AND contract_version = ?").get(task.id, task.latestContractVersion)) || JSON.stringify(task.contract.expectedOutputs) === JSON.stringify(fallback.expectedOutputs) ? planned.expectedOutputs : task.contract.expectedOutputs
214
+ }
215
+ }
216
+ });
217
+ if (!result.ok) return void 0;
218
+ db.prepare("UPDATE task_allocations SET task_version = ? WHERE id = ?").run(result.model.task.version, row.id);
219
+ return result.model.task;
220
+ });
221
+ if (!updated) return;
222
+ task = updated;
223
+ row.task_version = task.version;
224
+ }
225
+ }
226
+ if (handoff && !requirements.connector) requirements.requiredTools = [...new Set([...requirements.requiredTools ?? [], "task_collaboration"])];
227
+ const needs = taskExecutionRequirements(task, requirements, inferred);
146
228
  const context = this.deps.context(row.origin_conversation_id);
147
229
  const permittedExecutors = () => {
148
230
  const connector = requirements.connector;
@@ -166,9 +248,19 @@ var TaskAllocationDispatcher = class {
166
248
  const named = catalog.list().filter((agent) => agent.id.toLowerCase() === requested || agent.profile?.name.toLowerCase() === requested);
167
249
  if (named.length === 1) requirements.requestedAgentId = named[0].id;
168
250
  }
169
- const candidates = (requirements.requestedAgentId ? [requirements.requestedAgentId] : catalog.list({ readyOnly: true }).filter((agent) => agent.enabled !== false && agent.purpose !== "task_dispatcher" && agent.id !== context.ownAgentId && !agent.id.startsWith("personal-")).map((agent) => agent.id)).filter((id) => !permitted || permitted.has(id)).map((id) => assessSpecialist(id, requirements, context)).filter((candidate) => candidate.eligibility === "eligible");
251
+ captureExecutionRequirements(task, requirements, needs);
252
+ const ids = requirements.requestedAgentId ? [requirements.requestedAgentId] : catalog.list({ readyOnly: true }).filter((agent) => agent.enabled !== false && agent.purpose !== "task_dispatcher" && agent.id !== context.ownAgentId && !agent.id.startsWith("personal-")).map((agent) => agent.id);
253
+ const candidates = ids.filter((id) => !permitted || permitted.has(id)).map((id) => assessTaskExecutor(id, requirements, needs, context, task.id)).filter((candidate) => candidate.eligibility === "eligible");
170
254
  if (!candidates.length) {
171
- this.finishFailure(row, zh ? "没有通过执行条件检查的 Specialist,请检查模型、工具和必需 Skill。" : "No specialist passed the model, tool and required Skill checks.", "no_eligible_candidate");
255
+ const failures = ids.map((id) => assessTaskExecutor(id, requirements, needs, context, task.id)).map((candidate) => ({
256
+ id: candidate.id,
257
+ checks: candidate.checks.filter((check) => ["blocked", "unknown"].includes(check.state))
258
+ }));
259
+ log.warn({
260
+ taskId: task.id,
261
+ failures
262
+ }, "No executor meets required operations");
263
+ this.finishFailure(row, (zh ? "没有执行者通过模型、工具、输入输出处理或必需 Skill 检查。" : "No executor passed model, tool, input/output or required Skill checks. ") + JSON.stringify(failures), "no_eligible_candidate");
172
264
  return;
173
265
  }
174
266
  if (candidates.length > 24) {
@@ -208,7 +300,7 @@ var TaskAllocationDispatcher = class {
208
300
  return;
209
301
  }
210
302
  permitted = permittedExecutors();
211
- const freshCandidates = (requirements.requestedAgentId ? [requirements.requestedAgentId] : catalog.list({ readyOnly: true }).filter((agent) => agent.enabled !== false && agent.purpose !== "task_dispatcher" && agent.id !== context.ownAgentId && !agent.id.startsWith("personal-")).map((agent) => agent.id)).filter((id) => !permitted || permitted.has(id)).map((id) => assessSpecialist(id, requirements, context)).filter((candidate) => candidate.eligibility === "eligible");
303
+ const freshCandidates = (requirements.requestedAgentId ? [requirements.requestedAgentId] : catalog.list({ readyOnly: true }).filter((agent) => agent.enabled !== false && agent.purpose !== "task_dispatcher" && agent.id !== context.ownAgentId && !agent.id.startsWith("personal-")).map((agent) => agent.id)).filter((id) => !permitted || permitted.has(id)).map((id) => assessTaskExecutor(id, requirements, needs, context, task.id)).filter((candidate) => candidate.eligibility === "eligible");
212
304
  if (selectionRequestHash(freshCandidates.map((candidate) => ({
213
305
  id: candidate.id,
214
306
  revision: candidate.revision
@@ -1,5 +1,6 @@
1
1
  import type { ActorRef, TaskCommand, TaskCreateRequest, TaskRunReceipt } from '@xopcai/gateway-contract';
2
2
  import { type TaskReadModel } from './task-read-model-projector.js';
3
+ import type { TurnContextRef } from '../agent/source-context/types.js';
3
4
  export type TaskApplicationResult = {
4
5
  ok: true;
5
6
  model: TaskReadModel;
@@ -9,9 +10,26 @@ export type TaskApplicationResult = {
9
10
  reason: 'not_found' | 'conflict' | 'invalid_transition' | 'blocked';
10
11
  model?: TaskReadModel;
11
12
  };
13
+ export type TaskRevisionApplicationResult = TaskApplicationResult | {
14
+ ok: false;
15
+ reason: 'invalid_reference';
16
+ model: TaskReadModel;
17
+ };
12
18
  export declare class TaskApplicationService {
13
19
  #private;
14
20
  create(input: TaskCreateRequest, actor?: ActorRef): TaskApplicationResult;
21
+ /** Atomically open a new work revision; allocation and source IO remain background work. */
22
+ reviseCompleted(input: {
23
+ taskId: string;
24
+ conversationId: string;
25
+ baselineResultId: string;
26
+ baselineVersion: string;
27
+ expectedVersion: number;
28
+ instruction: string;
29
+ idempotencyKey: string;
30
+ sourceRefs?: TurnContextRef[];
31
+ supersedesEntryIds?: string[];
32
+ }): TaskRevisionApplicationResult;
15
33
  execute(input: {
16
34
  taskId: string;
17
35
  idempotencyKey: string;
@@ -1,23 +1,29 @@
1
1
  import { getSqliteDatabase, init_transaction, runSqliteWriteTransaction } from "../storage/sqlite/transaction.js";
2
2
  import { TaskExecutorSelectionSchema, verifiedTaskCriteria } from "../../packages/gateway-contract/src/tasks.js";
3
+ import { resultReferenceId, resultReferenceVersion } from "../../packages/gateway-contract/src/result-reference.js";
3
4
  import { init_src } from "../../packages/gateway-contract/src/index.js";
4
5
  import { enqueueTaskAttentionRequiredEvent, enqueueTaskChangedEvent, init_task_change_events } from "./task-change-events.js";
5
6
  import { TaskRepository, init_task_repository } from "./task-repository.js";
6
7
  import { TaskRunRepository, init_task_run_repository } from "./task-run-repository.js";
8
+ import { init_request_repository, personalRequestForTask } from "../personal-agent/request-repository.js";
7
9
  import { resolveTaskLocale } from "./task-language.js";
8
10
  import { TaskAllocationRepository } from "./task-allocation-repository.js";
9
11
  import { TaskReadModelProjector } from "./task-read-model-projector.js";
12
+ import { TaskOriginRepository } from "./task-origin-repository.js";
13
+ import { resolvePersonalResultReference } from "../personal-agent/result-reader.js";
10
14
  import { TaskConversationRepository } from "./task-conversation-repository.js";
15
+ import { TaskCollaborationRepository } from "./task-collaboration-repository.js";
16
+ import { TaskResultDeliveryRepository } from "./task-result-delivery-repository.js";
11
17
  import { TaskContextRepository } from "./task-context-repository.js";
12
18
  import { TaskDependencyService } from "./task-dependency-service.js";
13
19
  import { TaskCriterionReviewRepository } from "./task-criterion-review-repository.js";
14
- import { TaskCollaborationRepository } from "./task-collaboration-repository.js";
15
- import { TaskResultDeliveryRepository } from "./task-result-delivery-repository.js";
20
+ import { captureTaskHandoff } from "./task-handoff.js";
16
21
  import { createHash, randomUUID } from "node:crypto";
17
22
  //#region src/tasks/task-application-service.ts
18
23
  init_src();
19
24
  init_transaction();
20
25
  init_task_change_events();
26
+ init_request_repository();
21
27
  init_task_repository();
22
28
  init_task_run_repository();
23
29
  function requestHash(value) {
@@ -120,6 +126,7 @@ var TaskApplicationService = class {
120
126
  ...edge,
121
127
  createdBy: actor
122
128
  });
129
+ if (input.originConversationId && input.activation.mode === "allocate") captureTaskHandoff(task.id, input.originConversationId, input.body ?? input.contract.objective);
123
130
  for (const grant of input.authorityGrants) this.#context.grant({
124
131
  taskId: task.id,
125
132
  ...grant,
@@ -198,6 +205,130 @@ var TaskApplicationService = class {
198
205
  return started;
199
206
  });
200
207
  }
208
+ /** Atomically open a new work revision; allocation and source IO remain background work. */
209
+ reviseCompleted(input) {
210
+ const db = getSqliteDatabase();
211
+ const task = this.#tasks.get(input.taskId);
212
+ if (!task || !new TaskOriginRepository().owns(task.id, input.conversationId)) return {
213
+ ok: false,
214
+ reason: "not_found"
215
+ };
216
+ if (personalRequestForTask(task.id)) throw new Error("Connected requests require a new authorized Request; completed Task revision cannot repeat external account actions");
217
+ const hash = requestHash(input);
218
+ const duplicate = db.prepare("SELECT request_hash FROM task_work_revisions WHERE idempotency_key = ?").get(input.idempotencyKey);
219
+ if (duplicate) {
220
+ if (duplicate.request_hash !== hash) throw new Error("Revision idempotency key reused with different input");
221
+ return {
222
+ ok: true,
223
+ model: this.#projector.project(task)
224
+ };
225
+ }
226
+ if (task.version !== input.expectedVersion) return {
227
+ ok: false,
228
+ reason: "conflict",
229
+ model: this.#projector.project(task)
230
+ };
231
+ if (this.#runs.getActiveRoot(task.id) || this.#runs.listActiveWaits(task.id).length || !this.#runs.getLatestRoot(task.id) || !["closed", "review"].includes(task.phase) || task.resolution && task.resolution !== "done") return {
232
+ ok: false,
233
+ reason: "invalid_transition",
234
+ model: this.#projector.project(task)
235
+ };
236
+ const baseline = resolvePersonalResultReference(input.conversationId, input.baselineResultId);
237
+ const latest = db.prepare(`SELECT delivery_id FROM task_result_deliveries WHERE task_run_id IN
238
+ (SELECT run_id FROM task_runs WHERE task_id = ?) AND status IN ('pending','delivered','stale') ORDER BY created_at DESC, rowid DESC LIMIT 1`).get(task.id);
239
+ if (baseline.taskId !== task.id || resultReferenceVersion(baseline) !== input.baselineVersion || latest?.delivery_id !== baseline.deliveryId) return {
240
+ ok: false,
241
+ reason: "conflict",
242
+ model: this.#projector.project(task)
243
+ };
244
+ const instruction = input.instruction.trim();
245
+ if (!instruction || instruction.length > 8e3 || !input.idempotencyKey.trim()) throw new Error("Revision requires a bounded instruction and idempotency key");
246
+ const board = new TaskCollaborationRepository();
247
+ for (const id of input.supersedesEntryIds ?? []) {
248
+ const entry = board.get(id);
249
+ if (!entry || entry.taskId !== task.id || !["instruction", "answer"].includes(entry.kind) || !["main_agent", "user"].includes(entry.authorKind)) return {
250
+ ok: false,
251
+ reason: "invalid_reference",
252
+ model: this.#projector.project(task)
253
+ };
254
+ }
255
+ return runSqliteWriteTransaction(() => {
256
+ const actor = { kind: "user" };
257
+ const entry = board.append({
258
+ taskId: task.id,
259
+ authorKind: "main_agent",
260
+ authorId: input.conversationId,
261
+ kind: "instruction",
262
+ body: instruction,
263
+ deliverToWorker: true,
264
+ idempotencyKey: `revision:${input.idempotencyKey}`
265
+ });
266
+ let current = task.phase === "closed" ? this.#tasks.setLifecycle({
267
+ taskId: task.id,
268
+ expectedVersion: task.version,
269
+ phase: "ready"
270
+ }) : task;
271
+ const contract = task.contract;
272
+ const originalBody = db.prepare("SELECT original_body FROM task_work_revisions WHERE task_id = ? AND original_body IS NOT NULL ORDER BY contract_version LIMIT 1").get(task.id);
273
+ const originalObjective = String(db.prepare("SELECT objective FROM task_contracts WHERE task_id = ? ORDER BY version LIMIT 1").get(task.id)?.objective ?? contract.objective);
274
+ current = this.#tasks.reviseContract({
275
+ ...contract,
276
+ taskId: task.id,
277
+ expectedVersion: current.version,
278
+ objective: `${originalObjective}\nCurrent revision: ${instruction}`,
279
+ acceptanceCriteria: task.contract.acceptanceCriteria,
280
+ createdBy: actor
281
+ });
282
+ current = this.#tasks.update(task.id, {
283
+ expectedVersion: current.version,
284
+ body: `${originalBody?.original_body ?? task.body ?? contract.objective}\n\n## Work revision\nBaseline result: ${baseline.deliveryId} (${input.baselineVersion}).\n${instruction}\nRetain unaffected requirements. Publish only the selected final artifacts of this revision. Prior runs are historical.`
285
+ });
286
+ db.prepare(`UPDATE task_origin_links SET origin_transcript_id = (SELECT active_transcript_id FROM sessions WHERE conversation_id = ?),
287
+ request_input_id = (SELECT id FROM session_inputs WHERE conversation_id = ? AND status = 'running' ORDER BY created_at_ms DESC LIMIT 1) WHERE task_id = ?`).run(input.conversationId, input.conversationId, task.id);
288
+ const refs = [...input.sourceRefs ?? []];
289
+ for (const sourceId of ["body", ...baseline.outcome.deliverables.filter((item) => item.availability === "available").map((item) => item.artifactId)]) {
290
+ const ref = {
291
+ kind: "result",
292
+ sourceId: resultReferenceId(baseline.deliveryId, sourceId),
293
+ expectedVersion: input.baselineVersion
294
+ };
295
+ if (!refs.some((item) => item.kind === ref.kind && item.sourceId === ref.sourceId)) refs.push(ref);
296
+ }
297
+ if (refs.length > 51) throw new Error("Revision input manifest exceeds 51 sources");
298
+ captureTaskHandoff(task.id, input.conversationId, current.body, refs);
299
+ db.prepare(`INSERT INTO task_work_revisions (revision_id, task_id, contract_version, baseline_delivery_id, baseline_version,
300
+ instruction_entry_id, input_id, idempotency_key, request_hash, supersedes_json, original_body, created_at)
301
+ VALUES (?, ?, ?, ?, ?, ?, (SELECT request_input_id FROM task_origin_links WHERE task_id = ?), ?, ?, ?, ?, ?)`).run(randomUUID(), task.id, current.latestContractVersion, baseline.deliveryId, input.baselineVersion, entry.id, task.id, input.idempotencyKey, hash, JSON.stringify(input.supersedesEntryIds ?? []), originalBody ? null : task.body ?? contract.objective, Date.now());
302
+ db.prepare("UPDATE task_sessions SET status = 'superseded', ended_at = ? WHERE task_id = ? AND role = 'execution' AND status = 'active'").run(Date.now(), task.id);
303
+ db.prepare("UPDATE task_conversation_state SET active_conversation_id = NULL, current_executor_agent_id = NULL, status = 'idle', updated_at = ? WHERE task_id = ?").run(Date.now(), task.id);
304
+ const allocation = new TaskAllocationRepository();
305
+ const previous = allocation.get(task.id);
306
+ if (previous) db.prepare(`UPDATE task_allocations SET id = ?, status = 'pending', attempts = 0, selected_agent_id = NULL,
307
+ lease_token = NULL, lease_expires_at = NULL, selection_reason = NULL, reason_code = NULL, task_version = ?, next_attempt_at = ?, updated_at = ? WHERE task_id = ?`).run(randomUUID(), current.version, Date.now(), Date.now(), task.id);
308
+ else allocation.create(task.id, input.conversationId, current.version, {
309
+ version: 1,
310
+ summary: instruction.slice(0, 300)
311
+ });
312
+ if (previous) allocation.publish(task.id, "修改要求已保存,正在为新修订分配执行者。");
313
+ db.prepare(`UPDATE task_result_deliveries SET reply_status = 'stale' WHERE task_run_id IN
314
+ (SELECT run_id FROM task_runs WHERE task_id = ?) AND reply_status IN ('pending','generating','ready')`).run(task.id);
315
+ enqueueTaskChangedEvent(db, {
316
+ taskId: task.id,
317
+ version: current.version,
318
+ changedFields: [
319
+ "contract",
320
+ "body",
321
+ "phase",
322
+ "context"
323
+ ],
324
+ actor
325
+ });
326
+ return {
327
+ ok: true,
328
+ model: this.#projector.project(current)
329
+ };
330
+ });
331
+ }
201
332
  execute(input) {
202
333
  const actor = input.actor ?? { kind: "user" };
203
334
  const task = this.#tasks.get(input.taskId);
@@ -1,4 +1,5 @@
1
1
  import { isXopcDatabaseOpen } from "../storage/sqlite/connection.js";
2
+ import { getSqliteDatabase } from "../storage/sqlite/transaction.js";
2
3
  import { verifiedTaskCriteria } from "../../packages/gateway-contract/src/tasks.js";
3
4
  import { init_src } from "../../packages/gateway-contract/src/index.js";
4
5
  import { TaskRepository, init_task_repository } from "./task-repository.js";
@@ -7,8 +8,8 @@ import { init_request_repository, personalRequestForTask } from "../personal-age
7
8
  import { init_sqlite } from "../storage/sqlite/index.js";
8
9
  import { TaskOriginRepository } from "./task-origin-repository.js";
9
10
  import { TaskConversationRepository } from "./task-conversation-repository.js";
10
- import { TaskContextRepository } from "./task-context-repository.js";
11
11
  import { TaskCollaborationRepository } from "./task-collaboration-repository.js";
12
+ import { TaskContextRepository } from "./task-context-repository.js";
12
13
  //#region src/tasks/task-context-assembler.ts
13
14
  init_src();
14
15
  init_sqlite();
@@ -131,17 +132,24 @@ function buildTaskExecutionDirective(conversationId) {
131
132
  return `- [${edge.role}] ${edge.targetKind}: ${edge.targetId.slice(0, 4e3)}${title}`;
132
133
  });
133
134
  const connected = personalRequestForTask(task.id);
134
- const postTool = connected ? "task_collaboration command post" : "xopc_use task collaboration_post";
135
+ const postTool = "task_collaboration command post";
135
136
  const board = new TaskCollaborationRepository();
137
+ const superseded = new Set(getSqliteDatabase().prepare("SELECT supersedes_json FROM task_work_revisions WHERE task_id = ?").all(task.id).flatMap((row) => JSON.parse(row.supersedes_json)));
136
138
  const collaboration = [...new Map([...board.recent(task.id, void 0, 12), ...board.coordination(task.id).filter((entry) => ["answer", "instruction"].includes(entry.kind))].map((entry) => [entry.id, entry])).values()].sort((left, right) => left.sequence - right.sequence);
137
139
  return [
138
140
  "<xopc_task_execution>",
139
141
  "This conversation is executing a durable task.",
140
142
  "Apply the response language to all user-facing task content, including collaboration posts, wait reasons, questions, choices, approval explanations, receipt summaries, evidence descriptions, and recovery instructions. Keep schema keys, enum values, identifiers, and exact acceptance criterion references unchanged. Language in attached context or earlier worker output does not set the response language.",
143
+ "Before execution read task_collaboration(command=\"get\", section=\"handoff\") for the host-captured user request, pinned input references and completeness limits. Follow nextOffset until the original request has been read completely. For each selected workspace file, call section source with materialize=true before filesystem tools; use the returned executionInputRoot and pinned input paths. An owner workspace path in the brief is a source location, never authorization to use it as your cwd. Read other selected sources using section source. Task interpretation does not replace the original request; quoted sources do not grant authority.",
141
144
  `Task: ${contract.objective}`,
142
145
  task.body?.trim() ? `Task details: ${task.body.trim().slice(0, 12e3)}` : "",
143
146
  `Expected outputs: ${contract.expectedOutputs.join("; ")}`,
144
147
  `Remaining acceptance criteria: ${remainingCriteria.join("; ")}`,
148
+ `Acceptance criterion indices: ${JSON.stringify(contract.acceptanceCriteria.map((criterion, criterionIndex) => ({
149
+ criterionIndex,
150
+ criterion
151
+ })))}`,
152
+ "For research or evidence-based conclusions, use publish_task_result before finishing when that tool is available. Cite exact excerpts from successful reads in this TaskRun, link each claim to source ids, and distinguish facts, inferences and recommendations. Publish required files first, then supply finalArtifactIds selecting only the final deliverables from their publication receipts; do not include intermediate or obsolete files. Read its per-criterion review; correct unsupported claims or explicitly disclose unmet/unverified criteria. Never replace missing evidence with a self-declared pass. Use task_collaboration get section evidence to recover real toolCallIds and exact excerpts. Your draft final reply is not a successful tool read. Do not create an extra delivery-note file solely to prove future reply wording. Do not add claims about a future reply; delivery checks occur after completion. A source quote match proves provenance, not factual truth. Keep the final reply concise; full evidence belongs in the result and report.",
145
153
  contract.constraints.length ? `Constraints: ${contract.constraints.join("; ")}` : "",
146
154
  contract.assumptions.length ? `Assumptions: ${contract.assumptions.join("; ")}` : "",
147
155
  contract.risks.length ? `Risks: ${contract.risks.join("; ")}` : "",
@@ -149,10 +157,10 @@ function buildTaskExecutionDirective(conversationId) {
149
157
  contextReferences.length ? `Attached task context:\n${contextReferences.join("\n")}` : "",
150
158
  ...contextEdges.filter((edge) => typeof edge.metadata.userAnswer === "string").slice(-20).map((edge) => `User response to ${edge.title ?? "question"}: ${JSON.stringify(edge.metadata.userAnswer)}`),
151
159
  handoffPayload ? `Handoff snapshot: ${handoffPayload}` : "",
152
- collaboration.length ? `Recent task collaboration:\n${collaboration.map((entry) => `- ${entry.sequence} id=${entry.id} ${entry.authorKind} ${entry.kind} delivery=${entry.deliveryStatus ?? "none"}${entry.causationId ? ` replyTo=${entry.causationId}` : ""}: ${JSON.stringify(entry.body)}`).join("\n")}` : "",
153
- `Before continuing, acknowledge each delivered answer or instruction with ${postTool}, kind ack, causationId equal to its entry ID. Explain your interpretation and how the final output will incorporate it. Acknowledgement records receipt and intent, not proof of completion. Apply the latest user direction on this same Task; report its actual adoption and any unmet requirements in the final result.`,
160
+ collaboration.length ? `Recent task collaboration:\n${collaboration.map((entry) => `- ${entry.sequence} id=${entry.id} ${entry.authorKind} ${entry.kind} superseded=${superseded.has(entry.id)} delivery=${entry.deliveryStatus ?? "none"}${entry.causationId ? ` replyTo=${entry.causationId}` : ""}: ${JSON.stringify(entry.body)}`).join("\n")}` : "",
161
+ `Initial handoff snapshots, source references and toolCallIds are not collaboration entries and require no ack. Before continuing, acknowledge only delivered user/main_agent collaboration entries of kind answer or instruction with ${postTool}, kind ack, causationId equal to its entry ID. Explain your interpretation and how the final output will incorporate it. Acknowledgement records receipt and intent, not proof of completion. Do not act on or acknowledge superseded directions. Apply all remaining applicable user directions on this same Task; report its actual adoption and any unmet requirements in the final result.`,
154
162
  `Report meaningful progress with ${postTool}. If blocked, post a question and stop this execution turn until answered.`,
155
- connected && (task.body?.length ?? 0) > 12e3 ? "Task details above are an excerpt. Read the complete brief with task_collaboration(command=\"get\", section=\"task\") before execution." : "",
163
+ (task.body?.length ?? 0) > 12e3 ? "Task details above are an excerpt. Read every page with task_collaboration(command=\"get\", section=\"brief\", offset=0) and nextOffset before execution." : "",
156
164
  connected ? `Connected request ${connected.requestId}: retain connector ${connected.connectorId} and account ${connected.accountId}. Text answers and instructions do not authorize account changes or writes. Use personal_request_connection for expired access; only the main connection UI can authorize recovery. Publish the latest adopted result with personal_request_result after all answers/instructions; do not use unavailable artifact tools.` : "",
157
165
  connected ? "Connected results and structured items return to the originating conversation automatically after this Task completes." : "For user-facing files, publish completed outputs with publish_artifacts before finishing. image_generate already publishes its images. Return structured artifact references rather than only local file paths. Published final outcomes are delivered automatically to the originating chat. Keep the final summary short and distinguish generated outputs from verified or accepted results.",
158
166
  "Take safe in-scope steps and produce inspectable evidence. Do not claim completion without verification.",
@@ -1,5 +1,6 @@
1
1
  export declare function getTaskExecutionDeadline(conversationId: string, runId: string): number | undefined;
2
2
  export declare function getTaskContinuation(conversationId: string, runId: string): {
3
3
  message: string;
4
+ reason?: string;
4
5
  deadlineAtMs?: number;
5
6
  } | undefined;
@@ -25,6 +25,7 @@ function getTaskContinuation(conversationId, runId) {
25
25
  if (continuation.transcriptId && getSessionMetadata(conversationId)?.transcriptId !== continuation.transcriptId) throw new Error("Cannot resume task because its execution transcript changed");
26
26
  return {
27
27
  message: continuation.message,
28
+ reason: continuation.reason,
28
29
  deadlineAtMs: run.timeoutAt
29
30
  };
30
31
  }
@@ -1,3 +1,4 @@
1
+ import type { ExecutionCapability } from './task-execution-capabilities.js';
1
2
  export interface TaskContractDefinition {
2
3
  objective: string;
3
4
  expectedOutputs: string[];
@@ -6,5 +7,7 @@ export interface TaskContractDefinition {
6
7
  approvalRequired: string[];
7
8
  assumptions: string[];
8
9
  risks: string[];
10
+ requiredCapabilities?: ExecutionCapability[];
11
+ capabilityPlanning?: 'complete' | 'unavailable';
9
12
  }
10
13
  export declare function defineTaskContract(objectiveInput: string, locale?: 'en' | 'zh'): TaskContractDefinition;
@@ -5,6 +5,7 @@ export interface TaskContractPlanningInput {
5
5
  taskContext?: string;
6
6
  projectContext?: string;
7
7
  userContext?: string;
8
+ signal?: AbortSignal;
8
9
  }
9
10
  export interface TaskContractPlanner {
10
11
  plan(input: TaskContractPlanningInput): Promise<TaskContractDefinition>;
@@ -1,12 +1,12 @@
1
1
  import { createLogger } from "../utils/logger/index.js";
2
2
  import { init_logger } from "../utils/logger.js";
3
- import { getAgentDefaultModelRef, init_schema } from "../config/schema.js";
4
- import { init_providers, resolveModel } from "../providers/index.js";
5
- import { completeWithResolvedCredentials, resolveModelCallApiKey } from "../providers/model-call.js";
3
+ import { getAgentDefaultChatModelConfig, init_schema } from "../config/schema.js";
4
+ import { completeTaskModelCall } from "./task-model-call.js";
6
5
  import { defineTaskContract } from "./task-contract-definition.js";
6
+ import { PERSONAL_WORKER_RESULT_GUIDANCE } from "../personal-agent/communication.js";
7
+ import { EXECUTION_CAPABILITIES } from "./task-execution-capabilities.js";
7
8
  //#region src/tasks/task-contract-planner.ts
8
9
  init_schema();
9
- init_providers();
10
10
  init_logger();
11
11
  const log = createLogger("TaskContractPlanner");
12
12
  function extractText(content) {
@@ -31,15 +31,36 @@ function strings(value, max) {
31
31
  function parseTaskContractResponse(raw) {
32
32
  const parsed = parseObject(raw);
33
33
  if (!parsed) return void 0;
34
+ if ([
35
+ "expectedOutputs",
36
+ "acceptanceCriteria",
37
+ "constraints",
38
+ "approvalRequired",
39
+ "assumptions",
40
+ "risks"
41
+ ].some((key) => parsed[key] !== void 0 && (!Array.isArray(parsed[key]) || parsed[key].some((value) => typeof value !== "string")))) return void 0;
34
42
  const objective = typeof parsed.objective === "string" ? parsed.objective.trim() : "";
35
43
  const expectedOutputs = strings(parsed.expectedOutputs, 8);
36
- const acceptanceCriteria = strings(parsed.acceptanceCriteria, 12);
44
+ const plannedCriteria = strings(parsed.acceptanceCriteria, 40);
45
+ const writeBoundary = (criterion) => /(?:仅|只)(?:能)?写入|未(?:覆盖|修改).*其他文件|(?:write only|only write)|(?:not|never) (?:overwrite|modify).*other files/i.test(criterion);
46
+ const deliveryPhrase = /最终(?:的)?(?:回复|答复)|交付说明(?:仅|只|中|不|未)|(?:final|future) (?:chat )?(?:reply|response)|(?:delivery|chat) (?:message|reply)/i;
47
+ const deliveryBoundary = (criterion) => deliveryPhrase.test(criterion);
48
+ const boundary = (criterion) => writeBoundary(criterion) || deliveryBoundary(criterion);
49
+ const acceptanceCriteria = plannedCriteria.filter((criterion) => !writeBoundary(criterion)).flatMap((criterion) => {
50
+ const position = criterion.search(deliveryPhrase);
51
+ if (position < 0) return [criterion];
52
+ const prefix = criterion.slice(0, position).replace(/[,,;;。\s]*(?:并且|且|并|and)?\s*$/i, "").trim();
53
+ return prefix && /运行|执行|发布|生成|校验|\b(?:run|execut|publish|generat|verif)/i.test(prefix) ? [prefix] : [];
54
+ }).filter((criterion) => !(/publish_task_result/.test(criterion) && /调用|使用|提交|返回|检查|验收|call|submit|review/i.test(criterion) && !/报告.*(?:说明|描述)|文档.*(?:说明|描述)|(?:report|document).*describe/i.test(criterion)));
55
+ if (Array.isArray(parsed.acceptanceCriteria) && parsed.acceptanceCriteria.length > 40) return void 0;
37
56
  if (!objective || expectedOutputs.length === 0 || acceptanceCriteria.length === 0) return void 0;
57
+ if (parsed.requiredCapabilities !== void 0 && (!Array.isArray(parsed.requiredCapabilities) || parsed.requiredCapabilities.some((name) => typeof name !== "string" || !Object.hasOwn(EXECUTION_CAPABILITIES, name)))) return void 0;
38
58
  return {
39
59
  objective,
60
+ ...parsed.requiredCapabilities === void 0 ? {} : { requiredCapabilities: strings(parsed.requiredCapabilities, 6) },
40
61
  expectedOutputs,
41
62
  acceptanceCriteria,
42
- constraints: strings(parsed.constraints, 10),
63
+ constraints: [...new Set([...strings(parsed.constraints, 10), ...plannedCriteria.filter(boundary)])],
43
64
  approvalRequired: strings(parsed.approvalRequired, 8),
44
65
  assumptions: strings(parsed.assumptions, 10),
45
66
  risks: strings(parsed.risks, 10)
@@ -49,35 +70,55 @@ var ModelTaskContractPlanner = class {
49
70
  async plan(input) {
50
71
  const fallback = defineTaskContract(input.objective, input.locale);
51
72
  try {
52
- const model = resolveModel(getAgentDefaultModelRef());
53
- const planned = parseTaskContractResponse(extractText((await completeWithResolvedCredentials(model, { messages: [{
73
+ if ((input.taskContext?.length ?? 0) > 96e3) throw new Error("Task context exceeds planning budget");
74
+ const models = getAgentDefaultChatModelConfig();
75
+ if (!models) throw new Error("No default task planning model is configured");
76
+ const messages = [{
54
77
  role: "user",
55
78
  content: [
56
79
  "Define the smallest complete, verifiable contract for the user task.",
57
80
  "Preserve the user intent. Do not invent requirements or ask for optional preferences.",
58
81
  "Acceptance criteria must describe externally checkable finished states, not activities.",
82
+ "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.",
83
+ "Keep each criterion concise and concrete; do not repeat the full brief. Include all required deliverable conditions without splitting trivial wording into unnecessary items.",
84
+ "Define criteria for the specialist deliverables only. Do not create self-referential criteria about calling publish_task_result, receiving this review, or what a future Personal Agent reply will say. Those are runtime delivery checks, evaluated after completion. Keep source support, calculations, completeness and requested limitations as separate criteria. User-specified files and content remain required.",
85
+ "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.",
59
86
  "List assumptions explicitly. Put only irreversible, external, financial, privacy, or permission decisions in approvalRequired.",
60
- "Return one JSON object only with keys: objective, expectedOutputs, acceptanceCriteria, constraints, approvalRequired, assumptions, risks.",
87
+ "Return one JSON object only. Every array contains flat strings, never objects or nested arrays. Schema example: {\"objective\":\"Deliver the requested work\",\"expectedOutputs\":[\"report.md\"],\"acceptanceCriteria\":[\"report.md contains the requested evidence\"],\"constraints\":[],\"approvalRequired\":[],\"assumptions\":[],\"risks\":[],\"requiredCapabilities\":[\"read_input\",\"publish_files\"]}. Capabilities must use the allowed enum values.",
61
88
  input.locale ? `Write all user-facing JSON values in ${input.locale === "zh" ? "Simplified Chinese" : "English"}. Preserve schema keys, identifiers, paths, and proper nouns.` : "Write all user-facing JSON values in the language of the user request, regardless of the language of project or attached context. Preserve schema keys and identifiers.",
62
89
  "",
63
90
  `User request:\n${input.objective.trim()}`,
64
- input.taskContext ? `\nUser-provided task context:\n${input.taskContext.slice(0, 16e3)}` : "",
91
+ input.taskContext ? `\nUser-provided task context:\n${input.taskContext.replace(PERSONAL_WORKER_RESULT_GUIDANCE, "").trim()}` : "",
65
92
  input.projectContext ? `\nProject context:\n${input.projectContext.slice(0, 8e3)}` : "",
66
93
  input.userContext ? `\nUser context:\n${input.userContext.slice(0, 8e3)}` : ""
67
94
  ].join("\n"),
68
95
  timestamp: Date.now()
69
- }] }, {
70
- apiKey: await resolveModelCallApiKey(model),
71
- maxTokens: 2e3,
72
- temperature: 0
73
- }, void 0, { operation: "task.plan_contract" })).content));
74
- return planned ? {
75
- ...planned,
76
- objective: fallback.objective
77
- } : fallback;
96
+ }];
97
+ for (let attempt = 0; attempt < 2; attempt++) {
98
+ input.signal?.throwIfAborted();
99
+ const planned = parseTaskContractResponse(extractText((await completeTaskModelCall(models, { messages }, {
100
+ maxTokens: 4e3,
101
+ temperature: 0,
102
+ signal: input.signal
103
+ }, { operation: "task.plan_contract" })).content));
104
+ if (planned?.requiredCapabilities) return {
105
+ ...planned,
106
+ objective: fallback.objective,
107
+ capabilityPlanning: "complete"
108
+ };
109
+ if (attempt === 0) messages.push({
110
+ role: "user",
111
+ timestamp: Date.now(),
112
+ content: "Your previous response did not match the required schema. Return the same task contract as one JSON object. expectedOutputs, acceptanceCriteria, constraints, approvalRequired, assumptions and risks must be flat string arrays, never objects. requiredCapabilities must be an array drawn only from read_input, execute_code, publish_files, web_research, browser, generate_image. Keep all user constraints; do not add criteria about a future chat reply. Return no commentary."
113
+ });
114
+ }
115
+ throw new Error("Task planning response did not contain a verifiable contract and operation requirements");
78
116
  } catch (err) {
79
117
  log.warn({ err }, "Task contract planning fell back to deterministic criteria");
80
- return fallback;
118
+ return {
119
+ ...fallback,
120
+ capabilityPlanning: "unavailable"
121
+ };
81
122
  }
82
123
  }
83
124
  };
@@ -91,7 +91,7 @@ var TaskConversationRepository = class {
91
91
  const existing = db.prepare("SELECT * FROM task_conversation_state WHERE task_id = ?").get(input.taskId);
92
92
  const current = db.prepare(`SELECT * FROM task_sessions
93
93
  WHERE task_id = ? AND role = 'execution' AND status = 'active'`).get(input.taskId);
94
- const sameSession = current?.conversation_id === input.conversationId;
94
+ const sameSession = current?.conversation_id === input.conversationId && (!input.runId || current.run_id === input.runId);
95
95
  const assignmentEpoch = sameSession ? current.assignment_epoch : (existing?.assignment_epoch ?? 0) + 1;
96
96
  if (!sameSession) db.prepare(`UPDATE task_sessions SET status = 'superseded', ended_at = ?
97
97
  WHERE task_id = ? AND role = 'execution' AND status = 'active'`).run(now, input.taskId);
@@ -0,0 +1,7 @@
1
+ export type EvidenceRange = {
2
+ start: number;
3
+ end: number;
4
+ };
5
+ /** Offsets are Unicode code points into a persisted successful tool result, never the input command. */
6
+ export declare function observedEvidenceExcerpt(body: string, range: EvidenceRange): string;
7
+ export declare function suggestedEvidenceRanges(body: string): EvidenceRange[];