@xopcai/xopc 0.0.268 → 0.0.270

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 (240) hide show
  1. package/dist/browser-ext/manifest.json +1 -1
  2. package/dist/extensions/telegram/xopc.extension.json +1 -1
  3. package/dist/gateway/static/root/assets/{activity-store-Bhyy6ENz.js → activity-store-D_0FmdRj.js} +1 -1
  4. package/dist/gateway/static/root/assets/{agent-avatar-dicebear-B9WObxjr.js → agent-avatar-dicebear-IZvEXak_.js} +1 -1
  5. package/dist/gateway/static/root/assets/agent-defaults-settings-panel-CE3ygr3l.js +1 -0
  6. package/dist/gateway/static/root/assets/{agents-BJuTIRPD.js → agents-DzG2qw-c.js} +1 -1
  7. package/dist/gateway/static/root/assets/{api-B2y7ZjZk.js → api-O3TTQ4qN.js} +1 -1
  8. package/dist/gateway/static/root/assets/{app-management-settings-panel-Bbn9mDfL.js → app-management-settings-panel-Cqqsbzri.js} +1 -1
  9. package/dist/gateway/static/root/assets/{appearance-settings-Deo5EsIc.js → appearance-settings-DaJyf32s.js} +1 -1
  10. package/dist/gateway/static/root/assets/{apps-page-Cz4d7ErX.js → apps-page-B4lX6yoT.js} +1 -1
  11. package/dist/gateway/static/root/assets/{archive-plugin-CxJTU8MU.js → archive-plugin-kDPnDTJI.js} +1 -1
  12. package/dist/gateway/static/root/assets/{attachment-load-C71Cukgp.js → attachment-load-CJ3VceKS.js} +1 -1
  13. package/dist/gateway/static/root/assets/{automations-page-_J7UZ55Q.js → automations-page-JwMtU8XB.js} +1 -1
  14. package/dist/gateway/static/root/assets/automations-workspace-BiNBewg0.js +6 -0
  15. package/dist/gateway/static/root/assets/{binary-plugins-CX8fC8Zt.js → binary-plugins-DzyZXLBX.js} +1 -1
  16. package/dist/gateway/static/root/assets/{block-editor-Ci9fjoQL.js → block-editor-kTt3gYIJ.js} +3 -3
  17. package/dist/gateway/static/root/assets/{browser-automation-inputs-s5I78Iko.js → browser-automation-inputs-BKohPYR4.js} +1 -1
  18. package/dist/gateway/static/root/assets/{browser-automations-page-rDSx0ozx.js → browser-automations-page-ktQfFPk-.js} +1 -1
  19. package/dist/gateway/static/root/assets/{browser-settings-page-B9RA6x4x.js → browser-settings-page-Dgdt5uVL.js} +3 -3
  20. package/dist/gateway/static/root/assets/capabilities-settings-panel-BpDW-R9f.js +7 -0
  21. package/dist/gateway/static/root/assets/{channels-settings-CEhVLJNa.js → channels-settings-DU4EQnR0.js} +1 -1
  22. package/dist/gateway/static/root/assets/{channels-status-swr-_OsWr_vS.js → channels-status-swr-DrqzYmDr.js} +1 -1
  23. package/dist/gateway/static/root/assets/{chat-terminal-dock-DMSl8KxS.js → chat-terminal-dock-CIFGGLGa.js} +2 -2
  24. package/dist/gateway/static/root/assets/connectors-page-CfJqy284.js +2 -0
  25. package/dist/gateway/static/root/assets/{cron-expression-BByq6Uh8.js → cron-expression-BNwbnrEb.js} +1 -1
  26. package/dist/gateway/static/root/assets/{date-picker-m6JZCUEW.js → date-picker-DKyirU4K.js} +1 -1
  27. package/dist/gateway/static/root/assets/{dependency-picker-CwCAjbaJ.js → dependency-picker-D3vNIjRI.js} +1 -1
  28. package/dist/gateway/static/root/assets/{desktop-pet-DSmeEREd.js → desktop-pet-fQwRb_3p.js} +1 -1
  29. package/dist/gateway/static/root/assets/{desktop-pet-settings-MfKceMoe.js → desktop-pet-settings-DfOJ-GvT.js} +1 -1
  30. package/dist/gateway/static/root/assets/{extension-debug-page-CwvWy26h.js → extension-debug-page-Cn53jB5-.js} +1 -1
  31. package/dist/gateway/static/root/assets/{extension-page-DLrbVBHM.js → extension-page-IDpLCxpC.js} +1 -1
  32. package/dist/gateway/static/root/assets/{extension-settings-page-BI6C4PM-.js → extension-settings-page-B1dds2bP.js} +1 -1
  33. package/dist/gateway/static/root/assets/{gateway-config-swr-OObCK8jM.js → gateway-config-swr-B7dcmP7Q.js} +1 -1
  34. package/dist/gateway/static/root/assets/gateway-settings-pp9jN0wl.js +1 -0
  35. package/dist/gateway/static/root/assets/{gateway-startup-retry-D_TxKN_A.js → gateway-startup-retry-JGhGMhVZ.js} +1 -1
  36. package/dist/gateway/static/root/assets/{heartbeat-settings-CUl832Tb.js → heartbeat-settings-B8_zTyev.js} +1 -1
  37. package/dist/gateway/static/root/assets/home-page-g1KdAdLb.js +1 -0
  38. package/dist/gateway/static/root/assets/{image-generation-api-fPU9yGsw.js → image-generation-api-BJLX7Qrh.js} +1 -1
  39. package/dist/gateway/static/root/assets/index-1zRt56Zt.css +2 -0
  40. package/dist/gateway/static/root/assets/{index-wKE8Q2FX.js → index-OMnem2nr.js} +47 -47
  41. package/dist/gateway/static/root/assets/{keyboard-shortcuts-settings-r4DCS19O.js → keyboard-shortcuts-settings-CBvMTFFx.js} +1 -1
  42. package/dist/gateway/static/root/assets/{local-app-workbench-page-qwLuir8A.js → local-app-workbench-page-bj75v2ZE.js} +2 -2
  43. package/dist/gateway/static/root/assets/{local-apps-page-DkfCRLUh.js → local-apps-page-APCMNDvU.js} +1 -1
  44. package/dist/gateway/static/root/assets/{locale-store-DFQX9kTl.js → locale-store-BThkG0W5.js} +1 -1
  45. package/dist/gateway/static/root/assets/logs-page-BX7n39zV.js +2 -0
  46. package/dist/gateway/static/root/assets/{management-settings-Cfx4ATTa.js → management-settings-CM62j8ZX.js} +1 -1
  47. package/dist/gateway/static/root/assets/{markdown-view-D-5jHRWg.js → markdown-view-BwjpJVPs.js} +1 -1
  48. package/dist/gateway/static/root/assets/{media-plugins-DOLjWd3y.js → media-plugins-C10byeaa.js} +1 -1
  49. package/dist/gateway/static/root/assets/{messages-Dj8QuS6e.js → messages-D0V_bgRP.js} +2 -2
  50. package/dist/gateway/static/root/assets/{mobile-pairing-wizard-BGW9joAb.js → mobile-pairing-wizard-BCWfwVx3.js} +1 -1
  51. package/dist/gateway/static/root/assets/note-detail-panel-koOqb0gX.js +5 -0
  52. package/dist/gateway/static/root/assets/notes-page-BH54rY3B.js +8 -0
  53. package/dist/gateway/static/root/assets/{page-tabs-_SGXMT2O.js → page-tabs-qQ36zncF.js} +1 -1
  54. package/dist/gateway/static/root/assets/{preview-open-alternatives-lVetfCWk.js → preview-open-alternatives-BiAJvvCo.js} +1 -1
  55. package/dist/gateway/static/root/assets/proactive-card-CcNBqHoH.js +1 -0
  56. package/dist/gateway/static/root/assets/proactive-page-C3K61jve.js +1 -0
  57. package/dist/gateway/static/root/assets/{product-open-page-CIGLPFm7.js → product-open-page-CunnDP4w.js} +1 -1
  58. package/dist/gateway/static/root/assets/project-detail-page-SL2g8MZY.js +1 -0
  59. package/dist/gateway/static/root/assets/projects-page-BtxazT5J.js +1 -0
  60. package/dist/gateway/static/root/assets/{registry-api-CsZLatKo.js → registry-api-0JSegbNl.js} +1 -1
  61. package/dist/gateway/static/root/assets/remote-access-hub-BSb7b67A.js +1 -0
  62. package/dist/gateway/static/root/assets/{runtime-tools-settings-panel-BDqVrUEj.js → runtime-tools-settings-panel-bu_mwBTr.js} +1 -1
  63. package/dist/gateway/static/root/assets/{schema-form-8RQgFJJO.js → schema-form-BE0sgZyz.js} +1 -1
  64. package/dist/gateway/static/root/assets/sessions-page-ljcS2KVz.js +1 -0
  65. package/dist/gateway/static/root/assets/settings-advanced-gate-CR9Y9LQm.js +1 -0
  66. package/dist/gateway/static/root/assets/{settings-form-section-j4UjGM-f.js → settings-form-section-CBo517lV.js} +1 -1
  67. package/dist/gateway/static/root/assets/{settings-page-lMi50B_s.js → settings-page-DBPimx93.js} +1 -1
  68. package/dist/gateway/static/root/assets/{setup-status-panel-Dx4Fy3rU.js → setup-status-panel-J3AnooPW.js} +1 -1
  69. package/dist/gateway/static/root/assets/{share-preview-page-aSyKRH5y.js → share-preview-page-DdV75VTe.js} +1 -1
  70. package/dist/gateway/static/root/assets/shares-settings-AAm4Iwcp.js +1 -0
  71. package/dist/gateway/static/root/assets/skill-reload-api-pRCjP5sm.js +1 -0
  72. package/dist/gateway/static/root/assets/{skills-page-C2_CAvxW.js → skills-page-Cn_-nvRo.js} +1 -1
  73. package/dist/gateway/static/root/assets/{skills-page.utils-B00e4Q30.js → skills-page.utils-CfVAc_lu.js} +1 -1
  74. package/dist/gateway/static/root/assets/{system-settings-panel-CulAkrsV.js → system-settings-panel-B-pzalp-.js} +1 -1
  75. package/dist/gateway/static/root/assets/task-detail-page-CmrLy3PO.js +1 -0
  76. package/dist/gateway/static/root/assets/{theme-store-zRT6vaZc.js → theme-store-1wryLgBQ.js} +1 -1
  77. package/dist/gateway/static/root/assets/{tunnel-api-C01xgCWR.js → tunnel-api-Cgpnm2fL.js} +1 -1
  78. package/dist/gateway/static/root/assets/{use-autosave-DfSJ3c2p.js → use-autosave-N_lm4FdD.js} +1 -1
  79. package/dist/gateway/static/root/assets/user-model-page-u3QLDX6L.js +2 -0
  80. package/dist/gateway/static/root/assets/{voice-api-key-field-9v-miN8o.js → voice-api-key-field-DMsyVfri.js} +1 -1
  81. package/dist/gateway/static/root/assets/{voice-config-api-DpJEu2RQ.js → voice-config-api-QWVmiAp3.js} +1 -1
  82. package/dist/gateway/static/root/assets/{work-discovery-overlay-CREYgh-1.js → work-discovery-overlay-BC0vAxp1.js} +1 -1
  83. package/dist/gateway/static/root/assets/workflow-run-setup-panel-Cz9jQIlP.js +3 -0
  84. package/dist/gateway/static/root/assets/workflows-page-DA6OOK6X.js +6 -0
  85. package/dist/gateway/static/root/index.html +10 -10
  86. package/dist/gateway/static/root/notification-sw.js +15 -0
  87. package/dist/package.js +1 -1
  88. package/dist/packages/gateway-contract/src/notifications.js +15 -1
  89. package/dist/packages/gateway-contract/src/proactive.js +120 -0
  90. package/dist/packages/realtime-protocol/src/voice.js +2 -1
  91. package/dist/src/agent/tool-manuals/xopc-use.d.ts +1 -1
  92. package/dist/src/agent/tool-manuals/xopc-use.js +19 -1
  93. package/dist/src/agent/tools/factory.js +1 -0
  94. package/dist/src/agent/tools/xopc-use-tool.d.ts +3 -2
  95. package/dist/src/agent/tools/xopc-use-tool.js +48 -4
  96. package/dist/src/agent/workflow/subagent-runner.d.ts +1 -0
  97. package/dist/src/agent/workflow/subagent-runner.js +2 -2
  98. package/dist/src/browser/automations/schema.d.ts +1 -1
  99. package/dist/src/browser/automations/service.d.ts +1 -1
  100. package/dist/src/cli/bin.js +2 -2
  101. package/dist/src/cli/commands/agent.js +2 -2
  102. package/dist/src/cli/commands/auth.js +1 -1
  103. package/dist/src/cli/commands/doctor/checks/database-schema.js +1 -1
  104. package/dist/src/cli/commands/extension-dev.js +1 -1
  105. package/dist/src/cli/commands/extension-marketplace.js +1 -1
  106. package/dist/src/cli/commands/extension.js +1 -1
  107. package/dist/src/cli/commands/gateway/lifecycle.js +1 -1
  108. package/dist/src/cli/commands/gateway-ssh-tunnel.js +1 -1
  109. package/dist/src/cli/commands/models.js +2 -2
  110. package/dist/src/cli/commands/onboard.js +1 -1
  111. package/dist/src/cli/commands/platform.js +1 -1
  112. package/dist/src/cli/commands/profile.js +1 -1
  113. package/dist/src/cli/commands/tunnel.js +1 -1
  114. package/dist/src/cli/commands/update.js +1 -1
  115. package/dist/src/cli/extension-cli-register.js +1 -1
  116. package/dist/src/config/index.js +1 -1
  117. package/dist/src/connectors/connected-source-normalizers.js +3 -0
  118. package/dist/src/gateway/hono/routes/index.js +0 -2
  119. package/dist/src/gateway/hono/routes/lazy-bundles.js +12 -0
  120. package/dist/src/gateway/hono/routes/proactive-control.d.ts +3 -0
  121. package/dist/src/gateway/hono/routes/proactive-control.js +168 -0
  122. package/dist/src/gateway/hono/routes/proactive.d.ts +1 -1
  123. package/dist/src/gateway/hono/routes/proactive.js +12 -5
  124. package/dist/src/gateway/hono/routes/voice.js +1 -1
  125. package/dist/src/gateway/run-loop.js +1 -1
  126. package/dist/src/gateway/security/gateway-scopes.js +5 -0
  127. package/dist/src/gateway/server.js +1 -1
  128. package/dist/src/gateway/service.d.ts +0 -1
  129. package/dist/src/gateway/service.js +21 -23
  130. package/dist/src/notifications/planner.js +4 -3
  131. package/dist/src/notifications/proactive-channel.d.ts +8 -0
  132. package/dist/src/notifications/proactive-channel.js +57 -0
  133. package/dist/src/notifications/proactive-policy.d.ts +3 -0
  134. package/dist/src/notifications/proactive-policy.js +32 -0
  135. package/dist/src/notifications/service.d.ts +78 -0
  136. package/dist/src/notifications/service.js +71 -13
  137. package/dist/src/notifications/store.d.ts +2 -0
  138. package/dist/src/notifications/store.js +8 -1
  139. package/dist/src/notifications/web-push.d.ts +19 -0
  140. package/dist/src/notifications/web-push.js +182 -0
  141. package/dist/src/proactive/actions/service.js +12 -2
  142. package/dist/src/proactive/execution/agent-executor.d.ts +5 -0
  143. package/dist/src/proactive/execution/agent-executor.js +21 -0
  144. package/dist/src/proactive/execution/authorization.d.ts +5 -0
  145. package/dist/src/proactive/execution/authorization.js +61 -0
  146. package/dist/src/proactive/execution/context.d.ts +4 -0
  147. package/dist/src/proactive/execution/context.js +51 -14
  148. package/dist/src/proactive/execution/insight.d.ts +7 -0
  149. package/dist/src/proactive/execution/insight.js +36 -3
  150. package/dist/src/proactive/execution/repository.d.ts +2 -0
  151. package/dist/src/proactive/execution/repository.js +53 -9
  152. package/dist/src/proactive/execution/types.d.ts +7 -0
  153. package/dist/src/proactive/execution/worker.js +43 -7
  154. package/dist/src/proactive/experience.d.ts +69 -0
  155. package/dist/src/proactive/experience.js +90 -0
  156. package/dist/src/proactive/follow-ups.d.ts +123 -0
  157. package/dist/src/proactive/follow-ups.js +169 -0
  158. package/dist/src/proactive/inbox/cards.d.ts +21 -0
  159. package/dist/src/proactive/inbox/cards.js +266 -0
  160. package/dist/src/proactive/inbox/delivery.d.ts +6 -0
  161. package/dist/src/proactive/inbox/delivery.js +54 -0
  162. package/dist/src/proactive/inbox/digest.d.ts +8 -0
  163. package/dist/src/proactive/inbox/digest.js +112 -0
  164. package/dist/src/proactive/inbox/lifecycle.d.ts +4 -0
  165. package/dist/src/proactive/inbox/lifecycle.js +61 -0
  166. package/dist/src/proactive/inbox/notification-policy.d.ts +1 -0
  167. package/dist/src/proactive/inbox/notification-policy.js +22 -0
  168. package/dist/src/proactive/inbox/repository.d.ts +1 -0
  169. package/dist/src/proactive/inbox/repository.js +75 -12
  170. package/dist/src/proactive/inbox/types.d.ts +11 -1
  171. package/dist/src/proactive/inbox/worker.js +9 -3
  172. package/dist/src/proactive/index.js +2 -2
  173. package/dist/src/proactive/mail-thread.d.ts +13 -0
  174. package/dist/src/proactive/mail-thread.js +54 -0
  175. package/dist/src/proactive/maintenance.js +7 -0
  176. package/dist/src/proactive/metrics.d.ts +10 -0
  177. package/dist/src/proactive/metrics.js +27 -0
  178. package/dist/src/proactive/policy/presence.d.ts +2 -0
  179. package/dist/src/proactive/policy/presence.js +27 -0
  180. package/dist/src/proactive/policy/service.d.ts +51 -0
  181. package/dist/src/proactive/policy/service.js +120 -0
  182. package/dist/src/proactive/routing/matcher.js +3 -2
  183. package/dist/src/proactive/scenarios/control.d.ts +87 -0
  184. package/dist/src/proactive/scenarios/control.js +108 -0
  185. package/dist/src/proactive/scenarios/preview.d.ts +13 -0
  186. package/dist/src/proactive/scenarios/preview.js +81 -0
  187. package/dist/src/proactive/scenarios/prompt-composer.js +4 -2
  188. package/dist/src/proactive/scenarios/repository.js +5 -1
  189. package/dist/src/proactive/service.js +1 -1
  190. package/dist/src/proactive/temporal/schedule.d.ts +3 -0
  191. package/dist/src/proactive/temporal/schedule.js +67 -0
  192. package/dist/src/proactive/temporal/worker.d.ts +1 -0
  193. package/dist/src/proactive/temporal/worker.js +24 -6
  194. package/dist/src/storage/sqlite/migrations/159_proactive_controls.sql +68 -0
  195. package/dist/src/storage/sqlite/migrations/160_proactive_web_push.sql +27 -0
  196. package/dist/src/storage/sqlite/migrations/161_proactive_delivery_and_lifecycle.sql +51 -0
  197. package/dist/src/storage/sqlite/migrations/162_proactive_product.sql +7 -0
  198. package/dist/src/storage/sqlite/migrations/163_proactive_follow_ups.sql +29 -0
  199. package/dist/src/storage/sqlite/migrations/runner.d.ts +1 -1
  200. package/dist/src/storage/sqlite/migrations/runner.js +3 -3
  201. package/dist/src/storage/sqlite/migrations/runner.ts +1 -1
  202. package/dist/src/storage/sqlite/schema.js +1 -1
  203. package/dist/src/tasks/home-query-service.js +1 -1
  204. package/dist/src/tasks/index.js +4 -4
  205. package/dist/src/voice/dashscope/streaming-stt-session.js +1 -0
  206. package/dist/src/voice/dashscope/streaming-tts-stream.d.ts +1 -0
  207. package/dist/src/voice/dashscope/streaming-tts-stream.js +8 -0
  208. package/dist/src/voice/realtime/agentBroker.js +1 -1
  209. package/dist/src/voice/realtime/agentEngine.js +1 -1
  210. package/dist/src/voice/realtime/pcm-output-gain.d.ts +2 -0
  211. package/dist/src/voice/realtime/pcm-output-gain.js +16 -0
  212. package/dist/src/voice/realtime/runtime.d.ts +2 -1
  213. package/dist/src/voice/realtime/runtime.js +25 -7
  214. package/dist/src/workflows/domain/run.d.ts +1 -0
  215. package/dist/src/workflows/index.js +2 -2
  216. package/dist/src/workflows/service/workflow-run-service.d.ts +3 -0
  217. package/dist/src/workflows/service/workflow-run-service.js +27 -6
  218. package/dist/src/workflows/service/workflow-run-service.types.d.ts +1 -0
  219. package/package.json +7 -5
  220. package/dist/gateway/static/root/assets/agent-defaults-settings-panel-J1YFNG26.js +0 -1
  221. package/dist/gateway/static/root/assets/automations-workspace-Bn8nwUOL.js +0 -6
  222. package/dist/gateway/static/root/assets/capabilities-settings-panel-C1GUih8m.js +0 -7
  223. package/dist/gateway/static/root/assets/connectors-page-IQAQDSmO.js +0 -2
  224. package/dist/gateway/static/root/assets/gateway-settings-B3H7Vfbh.js +0 -1
  225. package/dist/gateway/static/root/assets/home-page-CT4JL2jm.js +0 -1
  226. package/dist/gateway/static/root/assets/index-CRJrO4GI.css +0 -2
  227. package/dist/gateway/static/root/assets/logs-page-DrNaaPWc.js +0 -2
  228. package/dist/gateway/static/root/assets/note-detail-panel-Dbj5OvXE.js +0 -5
  229. package/dist/gateway/static/root/assets/notes-page-5hRB3WXc.js +0 -8
  230. package/dist/gateway/static/root/assets/project-detail-page-CblWLA8k.js +0 -1
  231. package/dist/gateway/static/root/assets/projects-page-CGk-kzqs.js +0 -1
  232. package/dist/gateway/static/root/assets/remote-access-hub-Du8PweyU.js +0 -1
  233. package/dist/gateway/static/root/assets/sessions-page-BFm94dJC.js +0 -1
  234. package/dist/gateway/static/root/assets/settings-advanced-gate-C0H-cToA.js +0 -1
  235. package/dist/gateway/static/root/assets/shares-settings-CqF9s0pl.js +0 -1
  236. package/dist/gateway/static/root/assets/skill-reload-api-BBL_ZUSC.js +0 -1
  237. package/dist/gateway/static/root/assets/task-detail-page-D1FmRFIn.js +0 -1
  238. package/dist/gateway/static/root/assets/user-model-page-BGC_5baJ.js +0 -2
  239. package/dist/gateway/static/root/assets/workflow-run-setup-panel-BfCWdw8F.js +0 -3
  240. package/dist/gateway/static/root/assets/workflows-page-CvmKQkD0.js +0 -6
@@ -1,3 +1,5 @@
1
+ import { type ProactiveChannelSender } from './proactive-channel.js';
2
+ import { type NotificationPlan } from './planner.js';
1
3
  export declare class NotificationService {
2
4
  private readonly options;
3
5
  private timer;
@@ -6,10 +8,86 @@ export declare class NotificationService {
6
8
  constructor(options: {
7
9
  publish: (type: string, payload: unknown) => void;
8
10
  fetch?: typeof fetch;
11
+ sendChannel?: ProactiveChannelSender;
9
12
  });
10
13
  start(): void;
11
14
  stop(): void;
12
15
  handleGatewayEvent(type: string, payload: unknown): void;
16
+ /** Throws on persistence failure so durable producers can retry the handoff. */
17
+ persistGatewayEvent(type: string, payload: unknown): {
18
+ schemaVersion: 1;
19
+ id: string;
20
+ type: "work_discovery.failed" | "chat.completed" | "chat.failed" | "task.needs_input" | "task.blocked" | "task.failed" | "task.completed" | "automation.completed" | "automation.failed" | "proactive.insight" | "work_discovery.review_ready";
21
+ priority: "normal" | "high";
22
+ title: {
23
+ en: string;
24
+ zh: string;
25
+ };
26
+ payload: Record<string, unknown>;
27
+ createdAt: number;
28
+ target?: {
29
+ kind: "chat";
30
+ sessionKey: string;
31
+ } | {
32
+ kind: "task";
33
+ taskId: string;
34
+ } | {
35
+ kind: "automation_run";
36
+ automationId: string;
37
+ runId: string;
38
+ } | {
39
+ kind: "proactive_digest";
40
+ digestId: string;
41
+ } | {
42
+ kind: "insight";
43
+ inboxItemId: string;
44
+ } | {
45
+ kind: "work_discovery";
46
+ runId: string;
47
+ sessionKey: string;
48
+ };
49
+ body?: {
50
+ en: string;
51
+ zh: string;
52
+ };
53
+ };
54
+ persistPlan(plan: NotificationPlan): {
55
+ schemaVersion: 1;
56
+ id: string;
57
+ type: "work_discovery.failed" | "chat.completed" | "chat.failed" | "task.needs_input" | "task.blocked" | "task.failed" | "task.completed" | "automation.completed" | "automation.failed" | "proactive.insight" | "work_discovery.review_ready";
58
+ priority: "normal" | "high";
59
+ title: {
60
+ en: string;
61
+ zh: string;
62
+ };
63
+ payload: Record<string, unknown>;
64
+ createdAt: number;
65
+ target?: {
66
+ kind: "chat";
67
+ sessionKey: string;
68
+ } | {
69
+ kind: "task";
70
+ taskId: string;
71
+ } | {
72
+ kind: "automation_run";
73
+ automationId: string;
74
+ runId: string;
75
+ } | {
76
+ kind: "proactive_digest";
77
+ digestId: string;
78
+ } | {
79
+ kind: "insight";
80
+ inboxItemId: string;
81
+ } | {
82
+ kind: "work_discovery";
83
+ runId: string;
84
+ sessionKey: string;
85
+ };
86
+ body?: {
87
+ en: string;
88
+ zh: string;
89
+ };
90
+ };
13
91
  drain(): Promise<void>;
14
92
  private deliverPending;
15
93
  private send;
@@ -1,9 +1,15 @@
1
1
  import { createLogger } from "../utils/logger/index.js";
2
2
  import { init_logger } from "../utils/logger.js";
3
+ import { getSqliteDatabase, runSqliteWriteTransaction } from "../storage/sqlite/transaction.js";
3
4
  import { localizeNotification } from "../../packages/gateway-contract/src/notifications.js";
4
- import { disableNotificationDeviceForPushToken, listDeliverableNotificationDevices } from "./device-store.js";
5
+ import { proactivePreferences } from "../proactive/policy/service.js";
6
+ import { flushDueDigests } from "../proactive/inbox/digest.js";
5
7
  import { notificationPlanFromGatewayEvent } from "./planner.js";
6
- import { createNotificationEvent, expireUndeliverableNotificationDeliveries, listDueNotificationDeliveries, markNotificationDeliveryAccepted, markNotificationDeliveryDead, markNotificationDeliveryDelivered, pruneNotificationEvents, rescheduleNotificationDelivery } from "./store.js";
8
+ import { proactiveNotificationWorkspace, recheckNotificationDelivery } from "./proactive-policy.js";
9
+ import { createNotificationEvent, deferNotificationDelivery, expireUndeliverableNotificationDeliveries, listDueNotificationDeliveries, markNotificationDeliveryAccepted, markNotificationDeliveryDead, markNotificationDeliveryDelivered, pruneNotificationEvents, rescheduleNotificationDelivery } from "./store.js";
10
+ import { drainChannelNotifications, enqueueChannelNotification } from "./proactive-channel.js";
11
+ import { drainBrowserPush, enqueueBrowserPush } from "./web-push.js";
12
+ import { disableNotificationDeviceForPushToken, listDeliverableNotificationDevices } from "./device-store.js";
7
13
  //#region src/notifications/service.ts
8
14
  init_logger();
9
15
  const log = createLogger("Notifications");
@@ -58,15 +64,9 @@ var NotificationService = class {
58
64
  }
59
65
  handleGatewayEvent(type, payload) {
60
66
  try {
61
- const plan = notificationPlanFromGatewayEvent(type, payload);
62
- if (!plan) return;
63
- const devices = listDeliverableNotificationDevices().filter((device) => preferenceAllows(plan.notification.type, device.preferences));
64
- const result = createNotificationEvent({
65
- ...plan,
66
- deviceIds: devices.map((device) => device.id)
67
- });
68
- if (!result.created) return;
69
- this.options.publish("notification.created", result.notification);
67
+ const notification = this.persistGatewayEvent(type, payload);
68
+ if (!notification) return;
69
+ this.options.publish("notification.created", notification);
70
70
  this.drain();
71
71
  } catch (err) {
72
72
  log.error({
@@ -75,6 +75,50 @@ var NotificationService = class {
75
75
  }, "Notification event persistence failed");
76
76
  }
77
77
  }
78
+ /** Throws on persistence failure so durable producers can retry the handoff. */
79
+ persistGatewayEvent(type, payload) {
80
+ const plan = notificationPlanFromGatewayEvent(type, payload);
81
+ if (!plan) return null;
82
+ return this.persistPlan(plan);
83
+ }
84
+ persistPlan(plan) {
85
+ let devices = listDeliverableNotificationDevices().filter((device) => preferenceAllows(plan.notification.type, device.preferences));
86
+ const workspace = proactiveNotificationWorkspace(plan.notification);
87
+ let browserIds;
88
+ let selectedChannel = "all";
89
+ if (workspace) {
90
+ const preferences = proactivePreferences(workspace);
91
+ const browsers = getSqliteDatabase().prepare("SELECT id FROM proactive_web_push_subscriptions WHERE workspace_id = ? ORDER BY created_at DESC, id").all(workspace);
92
+ selectedChannel = preferences.preferredChannel === "auto" ? browsers.length ? "browser" : devices.length ? "mobile" : "browser" : preferences.preferredChannel;
93
+ if (!["all", "mobile"].includes(selectedChannel)) devices = [];
94
+ else if (preferences.preferredChannel === "auto") devices = devices.slice(0, 1);
95
+ browserIds = ["all", "browser"].includes(selectedChannel) ? browsers.map((row) => row.id) : [];
96
+ if (preferences.preferredChannel === "auto") browserIds = browserIds.slice(0, 1);
97
+ plan = {
98
+ ...plan,
99
+ notification: {
100
+ ...plan.notification,
101
+ payload: {
102
+ ...plan.notification.payload,
103
+ deliveryChannel: selectedChannel,
104
+ deliveryMode: preferences.preferredChannel
105
+ }
106
+ }
107
+ };
108
+ }
109
+ const result = runSqliteWriteTransaction(() => {
110
+ const created = createNotificationEvent({
111
+ ...plan,
112
+ deviceIds: devices.map((device) => device.id)
113
+ });
114
+ if (created.created) {
115
+ enqueueBrowserPush(created.notification, browserIds);
116
+ if (workspace && selectedChannel === "telegram") enqueueChannelNotification(created.notification, workspace);
117
+ }
118
+ return created;
119
+ });
120
+ return result.created ? result.notification : null;
121
+ }
78
122
  async drain() {
79
123
  if (this.draining) return;
80
124
  this.draining = true;
@@ -85,8 +129,11 @@ var NotificationService = class {
85
129
  pruneNotificationEvents(now - 720 * 60 * 60 * 1e3);
86
130
  this.lastMaintenanceAt = now;
87
131
  }
132
+ for (const notification of flushDueDigests((plan) => this.persistPlan(plan))) this.options.publish("notification.created", notification);
88
133
  await this.deliverPending();
89
134
  await this.checkReceipts();
135
+ await drainBrowserPush();
136
+ if (this.options.sendChannel) await drainChannelNotifications(this.options.sendChannel);
90
137
  } catch (err) {
91
138
  log.warn({ err }, "Notification delivery pass failed");
92
139
  } finally {
@@ -98,6 +145,17 @@ var NotificationService = class {
98
145
  await Promise.all(deliveries.map((delivery) => this.send(delivery)));
99
146
  }
100
147
  async send(delivery) {
148
+ if (delivery.event.type === "proactive.insight") {
149
+ const policy = recheckNotificationDelivery(delivery.event, "mobile");
150
+ if (policy === "cancel") {
151
+ markNotificationDeliveryDead(delivery.event.id, delivery.deviceId, "Proactive policy changed");
152
+ return;
153
+ }
154
+ if (policy instanceof Date) {
155
+ deferNotificationDelivery(delivery.event.id, delivery.deviceId, policy.getTime());
156
+ return;
157
+ }
158
+ }
101
159
  const fetchImpl = this.options.fetch ?? fetch;
102
160
  const localized = localizeNotification(delivery.event, delivery.locale);
103
161
  try {
@@ -110,8 +168,8 @@ var NotificationService = class {
110
168
  signal: AbortSignal.timeout(1e4),
111
169
  body: JSON.stringify({
112
170
  to: delivery.pushToken,
113
- title: localized.localizedTitle,
114
- body: localized.localizedBody,
171
+ title: delivery.event.type === "proactive.insight" ? delivery.locale.startsWith("zh") ? "有一项工作需要查看" : "A work update is ready" : localized.localizedTitle,
172
+ body: delivery.event.type === "proactive.insight" ? delivery.locale.startsWith("zh") ? "打开 xopc 查看详情。" : "Open xopc to review it." : localized.localizedBody,
115
173
  sound: delivery.event.priority === "high" ? "default" : void 0,
116
174
  priority: delivery.event.priority,
117
175
  data: {
@@ -51,3 +51,5 @@ export declare function notificationDeliveryMetrics(): {
51
51
  };
52
52
  export declare function expireUndeliverableNotificationDeliveries(now?: number): number;
53
53
  export declare function pruneNotificationEvents(before: number): number;
54
+ export declare function deferNotificationDelivery(eventId: string, deviceId: string, nextAttemptAt: number): void;
55
+ export declare function getNotificationEvent(id: string): ProductNotification | null;
@@ -180,5 +180,12 @@ function pruneNotificationEvents(before) {
180
180
  AND d.status IN ('pending', 'accepted')
181
181
  )`).run(before).changes));
182
182
  }
183
+ function deferNotificationDelivery(eventId, deviceId, nextAttemptAt) {
184
+ getSqliteDatabase().prepare("UPDATE notification_deliveries SET next_attempt_at = ?, last_error = 'Proactive quiet hours' WHERE event_id = ? AND device_id = ? AND status = 'pending'").run(nextAttemptAt, eventId, deviceId);
185
+ }
186
+ function getNotificationEvent(id) {
187
+ const row = getSqliteDatabase().prepare("SELECT * FROM notification_events WHERE event_id = ?").get(id);
188
+ return row ? eventFromRow(row) : null;
189
+ }
183
190
  //#endregion
184
- export { acknowledgeNotification, createNotificationEvent, expireUndeliverableNotificationDeliveries, listDueNotificationDeliveries, listNotificationEvents, markNotificationDeliveryAccepted, markNotificationDeliveryDead, markNotificationDeliveryDelivered, notificationDeliveryMetrics, pruneNotificationEvents, rescheduleNotificationDelivery };
191
+ export { acknowledgeNotification, createNotificationEvent, deferNotificationDelivery, expireUndeliverableNotificationDeliveries, getNotificationEvent, listDueNotificationDeliveries, listNotificationEvents, markNotificationDeliveryAccepted, markNotificationDeliveryDead, markNotificationDeliveryDelivered, notificationDeliveryMetrics, pruneNotificationEvents, rescheduleNotificationDelivery };
@@ -0,0 +1,19 @@
1
+ import { type ProductNotification } from '@xopcai/gateway-contract';
2
+ import webPush from 'web-push';
3
+ export declare function allowedPushEndpoint(value: string): boolean;
4
+ export declare function prepareBrowserPush(): {
5
+ publicKey: string;
6
+ };
7
+ export declare function registerBrowserPush(workspaceId: string, value: unknown): {
8
+ id: string;
9
+ };
10
+ export declare function unregisterBrowserPush(workspaceId: string, id: string): void;
11
+ export declare function enqueueBrowserPush(notification: ProductNotification, selectedIds?: string[]): void;
12
+ export declare function drainBrowserPush(send?: typeof webPush.sendNotification): Promise<void>;
13
+ /** A user-triggered probe to this browser only; provider acceptance is not user delivery. */
14
+ export declare function testBrowserPush(workspaceId: string, subscriptionId: string, send?: typeof webPush.sendNotification): Promise<{
15
+ id: `${string}-${string}-${string}-${string}-${string}`;
16
+ status: string;
17
+ }>;
18
+ export declare function acknowledgeBrowserProbe(workspaceId: string, id: string): void;
19
+ export declare function listBrowserProbes(workspaceId: string): Record<string, import("node:sqlite").SQLOutputValue>[];
@@ -0,0 +1,182 @@
1
+ import { getSqliteDatabase, runSqliteWriteTransaction } from "../storage/sqlite/transaction.js";
2
+ import { ProductNotificationSchema, notificationTargetRoute } from "../../packages/gateway-contract/src/notifications.js";
3
+ import { proactiveNotificationWorkspace, recheckNotificationDelivery } from "./proactive-policy.js";
4
+ import { createHash, randomUUID } from "node:crypto";
5
+ import { z } from "zod";
6
+ import webPush from "web-push";
7
+ //#region src/notifications/web-push.ts
8
+ function allowedPushEndpoint(value) {
9
+ try {
10
+ const url = new URL(value);
11
+ const host = url.hostname;
12
+ return url.protocol === "https:" && !url.username && !url.password && (!url.port || url.port === "443") && (host === "fcm.googleapis.com" || host === "updates.push.services.mozilla.com" || host.endsWith(".push.services.mozilla.com") || host === "web.push.apple.com" || host.endsWith(".notify.windows.com"));
13
+ } catch {
14
+ return false;
15
+ }
16
+ }
17
+ const BrowserPushSchema = z.object({
18
+ subscription: z.object({
19
+ endpoint: z.string().max(4096).refine(allowedPushEndpoint, "Unsupported push service"),
20
+ expirationTime: z.number().nullable().optional(),
21
+ keys: z.object({
22
+ auth: z.string().regex(/^[A-Za-z0-9_-]{22}$/),
23
+ p256dh: z.string().regex(/^[A-Za-z0-9_-]{87}$/)
24
+ }).strict()
25
+ }).strict(),
26
+ language: z.enum(["en", "zh"]).default("en")
27
+ }).strict();
28
+ function prepareBrowserPush() {
29
+ return runSqliteWriteTransaction((db) => {
30
+ let keys = db.prepare("SELECT public_key, private_key FROM proactive_web_push_keys WHERE id = 1").get();
31
+ if (!keys) {
32
+ const generated = webPush.generateVAPIDKeys();
33
+ db.prepare("INSERT INTO proactive_web_push_keys(id, public_key, private_key) VALUES (1, ?, ?)").run(generated.publicKey, generated.privateKey);
34
+ keys = {
35
+ public_key: generated.publicKey,
36
+ private_key: generated.privateKey
37
+ };
38
+ }
39
+ return { publicKey: keys.public_key };
40
+ });
41
+ }
42
+ function registerBrowserPush(workspaceId, value) {
43
+ const input = BrowserPushSchema.parse(value);
44
+ return runSqliteWriteTransaction((db) => {
45
+ const existing = db.prepare("SELECT id, workspace_id FROM proactive_web_push_subscriptions WHERE endpoint = ?").get(input.subscription.endpoint);
46
+ if (existing && existing.workspace_id !== workspaceId) throw new Error("Push subscription belongs to another workspace");
47
+ const id = existing?.id ?? randomUUID();
48
+ db.prepare(`INSERT INTO proactive_web_push_subscriptions(id, workspace_id, endpoint, subscription_json, language, created_at) VALUES (?, ?, ?, ?, ?, ?)
49
+ ON CONFLICT(endpoint) DO UPDATE SET subscription_json = excluded.subscription_json, language = excluded.language`).run(id, workspaceId, input.subscription.endpoint, JSON.stringify(input.subscription), input.language, (/* @__PURE__ */ new Date()).toISOString());
50
+ return { id };
51
+ });
52
+ }
53
+ function unregisterBrowserPush(workspaceId, id) {
54
+ getSqliteDatabase().prepare("DELETE FROM proactive_web_push_subscriptions WHERE workspace_id = ? AND id = ?").run(workspaceId, id);
55
+ }
56
+ function enqueueBrowserPush(notification, selectedIds) {
57
+ const workspace = proactiveNotificationWorkspace(notification);
58
+ if (!workspace) return;
59
+ const targetId = notification.target.kind === "insight" ? notification.target.inboxItemId : "";
60
+ const subscriptions = getSqliteDatabase().prepare("SELECT id FROM proactive_web_push_subscriptions WHERE workspace_id = ?").all(workspace);
61
+ for (const subscription of subscriptions) {
62
+ if (selectedIds && !selectedIds.includes(subscription.id)) continue;
63
+ getSqliteDatabase().prepare(`INSERT OR IGNORE INTO proactive_web_push_deliveries(notification_id, subscription_id, inbox_item_id, notification_revision, next_attempt_at) VALUES (?, ?, ?, ?, ?)`).run(notification.id, subscription.id, targetId, typeof notification.payload.notificationRevision === "number" ? notification.payload.notificationRevision : 1, Date.now());
64
+ }
65
+ }
66
+ async function drainBrowserPush(send = webPush.sendNotification) {
67
+ const db = getSqliteDatabase();
68
+ const keys = db.prepare("SELECT public_key, private_key FROM proactive_web_push_keys WHERE id = 1").get();
69
+ if (!keys) return;
70
+ const claim = runSqliteWriteTransaction((tx) => {
71
+ tx.prepare("UPDATE proactive_web_push_deliveries SET status = 'failed', last_error = 'Delivery lease exhausted' WHERE status = 'sending' AND lease_until <= ? AND attempt >= 5").run(Date.now());
72
+ const row = tx.prepare(`SELECT d.*, s.subscription_json, s.language FROM proactive_web_push_deliveries d
73
+ JOIN proactive_web_push_subscriptions s ON s.id = d.subscription_id
74
+ WHERE (d.status = 'pending' AND d.next_attempt_at <= ?) OR (d.status = 'sending' AND d.lease_until <= ?)
75
+ ORDER BY d.next_attempt_at LIMIT 1`).get(Date.now(), Date.now());
76
+ if (!row) return null;
77
+ tx.prepare("UPDATE proactive_web_push_deliveries SET status = 'sending', attempt = attempt + 1, lease_until = ? WHERE notification_id = ? AND subscription_id = ?").run(Date.now() + 6e4, row.notification_id, row.subscription_id);
78
+ return {
79
+ ...row,
80
+ attempt: row.attempt + 1
81
+ };
82
+ });
83
+ if (!claim) return;
84
+ const finish = (status, nextAt, error = null) => db.prepare(`UPDATE proactive_web_push_deliveries SET status = ?, next_attempt_at = ?, last_error = ?, lease_until = NULL
85
+ WHERE notification_id = ? AND subscription_id = ? AND attempt = ? AND status = 'sending'`).run(status, nextAt, error, claim.notification_id, claim.subscription_id, claim.attempt);
86
+ try {
87
+ const row = db.prepare("SELECT * FROM notification_events WHERE event_id = ?").get(claim.notification_id);
88
+ const notification = ProductNotificationSchema.parse({
89
+ schemaVersion: 1,
90
+ id: row.event_id,
91
+ type: row.event_type,
92
+ target: JSON.parse(String(row.target_json)),
93
+ priority: row.priority,
94
+ title: {
95
+ en: row.title_en,
96
+ zh: row.title_zh
97
+ },
98
+ payload: JSON.parse(String(row.payload_json)),
99
+ createdAt: row.created_at
100
+ });
101
+ const policy = recheckNotificationDelivery(notification, "browser");
102
+ if (policy === "cancel") {
103
+ finish("failed", Date.now(), "Policy changed or card expired");
104
+ return;
105
+ }
106
+ if (policy instanceof Date) {
107
+ finish("pending", policy.getTime());
108
+ db.prepare("UPDATE proactive_web_push_deliveries SET attempt = attempt - 1 WHERE notification_id = ? AND subscription_id = ? AND attempt = ?").run(claim.notification_id, claim.subscription_id, claim.attempt);
109
+ return;
110
+ }
111
+ const subscription = JSON.parse(claim.subscription_json);
112
+ if (!allowedPushEndpoint(subscription.endpoint)) throw new Error("Unsupported push service");
113
+ await send(subscription, JSON.stringify({
114
+ id: claim.notification_id,
115
+ title: claim.language === "zh" ? "有一项工作需要查看" : "A work update is ready",
116
+ body: claim.language === "zh" ? "打开 xopc 查看详情。" : "Open xopc to review it.",
117
+ route: notificationTargetRoute(notification.target, "web")
118
+ }), {
119
+ vapidDetails: {
120
+ subject: "https://xopc.ai",
121
+ publicKey: keys.public_key,
122
+ privateKey: keys.private_key
123
+ },
124
+ TTL: 3600,
125
+ timeout: 1e4,
126
+ topic: createHash("sha256").update(claim.inbox_item_id || claim.notification_id).digest("base64url").slice(0, 32)
127
+ });
128
+ finish("sent", Date.now());
129
+ } catch (error) {
130
+ const status = error.statusCode;
131
+ if (status === 404 || status === 410) {
132
+ db.prepare("DELETE FROM proactive_web_push_subscriptions WHERE id = ?").run(claim.subscription_id);
133
+ return;
134
+ }
135
+ finish(claim.attempt >= 5 ? "failed" : "pending", Date.now() + Math.min(36e5, 3e4 * 2 ** claim.attempt), status ? `Push service HTTP ${status}` : "Push delivery failed");
136
+ }
137
+ }
138
+ /** A user-triggered probe to this browser only; provider acceptance is not user delivery. */
139
+ async function testBrowserPush(workspaceId, subscriptionId, send = webPush.sendNotification) {
140
+ const id = randomUUID();
141
+ const claimed = runSqliteWriteTransaction((db) => {
142
+ const row = db.prepare("SELECT subscription_json FROM proactive_web_push_subscriptions WHERE id = ? AND workspace_id = ?").get(subscriptionId, workspaceId);
143
+ if (!row) throw new Error("Browser subscription not found");
144
+ if (db.prepare("SELECT 1 FROM proactive_push_probes WHERE workspace_id = ? AND created_at > ?").get(workspaceId, Date.now() - 6e4)) throw new Error("Wait one minute before another push test");
145
+ db.prepare("INSERT INTO proactive_push_probes(id, workspace_id, subscription_id, status, created_at) VALUES (?, ?, ?, ?, ?)").run(id, workspaceId, subscriptionId, "sending", Date.now());
146
+ return JSON.parse(row.subscription_json);
147
+ });
148
+ const keys = getSqliteDatabase().prepare("SELECT public_key, private_key FROM proactive_web_push_keys WHERE id = 1").get();
149
+ try {
150
+ if (!allowedPushEndpoint(claimed.endpoint)) throw new Error("Unsupported push service");
151
+ await send(claimed, JSON.stringify({
152
+ id,
153
+ title: "xopc 推送测试 / Push test",
154
+ body: "点击此通知确认打开 / Tap to confirm opening",
155
+ route: `/assistant-work?probe=${encodeURIComponent(id)}`
156
+ }), {
157
+ vapidDetails: {
158
+ subject: "https://xopc.ai",
159
+ publicKey: keys.public_key,
160
+ privateKey: keys.private_key
161
+ },
162
+ TTL: 300,
163
+ timeout: 1e4
164
+ });
165
+ getSqliteDatabase().prepare("UPDATE proactive_push_probes SET status = CASE WHEN opened_at IS NULL THEN 'accepted' ELSE 'opened' END WHERE id = ?").run(id);
166
+ return {
167
+ id,
168
+ status: "accepted"
169
+ };
170
+ } catch {
171
+ getSqliteDatabase().prepare("UPDATE proactive_push_probes SET status = 'failed', error = 'Push service did not accept the test' WHERE id = ?").run(id);
172
+ throw new Error("Push test failed; verify browser subscription and network connectivity");
173
+ }
174
+ }
175
+ function acknowledgeBrowserProbe(workspaceId, id) {
176
+ getSqliteDatabase().prepare("UPDATE proactive_push_probes SET status = 'opened', opened_at = ? WHERE id = ? AND workspace_id = ?").run(Date.now(), id, workspaceId);
177
+ }
178
+ function listBrowserProbes(workspaceId) {
179
+ return getSqliteDatabase().prepare("SELECT id, status, created_at AS createdAt, opened_at AS openedAt, error FROM proactive_push_probes WHERE workspace_id = ? ORDER BY created_at DESC LIMIT 10").all(workspaceId);
180
+ }
181
+ //#endregion
182
+ export { acknowledgeBrowserProbe, allowedPushEndpoint, drainBrowserPush, enqueueBrowserPush, listBrowserProbes, prepareBrowserPush, registerBrowserPush, testBrowserPush, unregisterBrowserPush };
@@ -1,4 +1,7 @@
1
1
  import { getSqliteDatabase, runSqliteWriteTransaction } from "../../storage/sqlite/transaction.js";
2
+ import { insightSourcesAuthorized, insightSourcesChanged } from "../execution/authorization.js";
3
+ import { effectiveProactivePolicy } from "../policy/service.js";
4
+ import { insightCorrelation } from "../inbox/lifecycle.js";
2
5
  import { TaskApplicationService } from "../../tasks/task-application-service.js";
3
6
  //#region src/proactive/actions/service.ts
4
7
  function projectIdFromAggregationKey(value) {
@@ -8,9 +11,15 @@ function projectIdFromAggregationKey(value) {
8
11
  function executeClaimedAction(row, now = /* @__PURE__ */ new Date()) {
9
12
  const action = JSON.parse(row.proposed_action_json);
10
13
  try {
14
+ if (getSqliteDatabase().prepare("SELECT 1 FROM proactive_inbox_items WHERE insight_id = ? AND withdrawn_at IS NOT NULL").get(row.insight_id)) throw new Error("Card was withdrawn");
15
+ if (!insightSourcesAuthorized(row.insight_id)) throw new Error("Source permission is no longer available");
16
+ if (insightSourcesChanged(row.insight_id)) throw new Error("Source changed; review updated work before acting");
17
+ if (!effectiveProactivePolicy(row.subscription_id).enabled) throw new Error("Proactive subscription paused");
18
+ const permission = getSqliteDatabase().prepare(`SELECT mode, allowed_actions_json FROM project_monitoring_policies WHERE project_id = ?`).get(projectIdFromAggregationKey(row.aggregation_key));
19
+ if (!getSqliteDatabase().prepare(`SELECT 1 FROM proactive_decisions d JOIN proactive_inbox_items i USING(inbox_item_id) WHERE i.insight_id = ? AND d.choice = 'approve'`).get(row.insight_id) && !(permission?.mode === "auto_low_risk" && JSON.parse(permission.allowed_actions_json).includes(action.id))) throw new Error("Action permission is no longer available");
11
20
  if (action.id !== "create_project_task") throw new Error(`Unsupported proactive action: ${action.id}`);
12
21
  const result = new TaskApplicationService().create({
13
- idempotencyKey: `proactive:${row.insight_id}:${action.id}`,
22
+ idempotencyKey: `proactive:${insightCorrelation(row.insight_id)}:${action.id}`,
14
23
  title: action.input.title,
15
24
  projectId: projectIdFromAggregationKey(row.aggregation_key),
16
25
  priority: "normal",
@@ -40,6 +49,7 @@ function executeClaimedAction(row, now = /* @__PURE__ */ new Date()) {
40
49
  getSqliteDatabase().prepare(`UPDATE proactive_insights
41
50
  SET action_status = 'completed', action_result_json = ?, action_error = NULL, action_updated_at = ?
42
51
  WHERE insight_id = ? AND action_status = 'executing'`).run(JSON.stringify({ taskId: result.model.task.id }), now.toISOString(), row.insight_id);
52
+ getSqliteDatabase().prepare("UPDATE proactive_inbox_items SET status = 'read', resolution = NULL, updated_at = ? WHERE insight_id = ?").run(now.toISOString(), row.insight_id);
43
53
  } catch (error) {
44
54
  getSqliteDatabase().prepare(`UPDATE proactive_insights
45
55
  SET action_status = 'failed', action_error = ?, action_updated_at = ?
@@ -53,7 +63,7 @@ function executePendingProactiveActions(now = /* @__PURE__ */ new Date()) {
53
63
  let executed = 0;
54
64
  while (true) {
55
65
  const row = runSqliteWriteTransaction((db) => {
56
- const candidate = db.prepare(`SELECT x.insight_id, b.aggregation_key, x.proposed_action_json
66
+ const candidate = db.prepare(`SELECT x.insight_id, x.subscription_id, b.aggregation_key, x.proposed_action_json
57
67
  FROM proactive_insights x
58
68
  JOIN proactive_runs r ON r.run_id = x.run_id
59
69
  JOIN proactive_signal_batches b ON b.batch_id = r.batch_id
@@ -12,5 +12,10 @@ export declare class ReadonlyProactiveAgentExecutor implements ProactiveAgentExe
12
12
  }): Promise<{
13
13
  text: string;
14
14
  modelRef: string;
15
+ usage: {
16
+ inputTokens: number;
17
+ outputTokens: number;
18
+ estimatedCostUsd?: number;
19
+ };
15
20
  }>;
16
21
  }
@@ -56,6 +56,7 @@ var ReadonlyProactiveAgentExecutor = class {
56
56
  this.config = config;
57
57
  }
58
58
  async execute(input) {
59
+ input.signal?.throwIfAborted();
59
60
  const model = resolveModel(getDefaultModelSync(this.config()));
60
61
  let toolCalls = 0;
61
62
  const agent = new Agent({
@@ -91,8 +92,28 @@ var ReadonlyProactiveAgentExecutor = class {
91
92
  const text = assistantText(agent.state.messages);
92
93
  if (!text) throw new Error("Proactive agent returned empty output");
93
94
  if (toolCalls === 0) throw new Error("Proactive agent did not inspect authorized evidence");
95
+ const usage = {
96
+ inputTokens: 0,
97
+ outputTokens: 0,
98
+ estimatedCostUsd: 0
99
+ };
100
+ for (const message of agent.state.messages) {
101
+ if (message.role !== "assistant") continue;
102
+ const reported = message.usage;
103
+ if (reported) {
104
+ usage.inputTokens += reported.input ?? 0;
105
+ usage.outputTokens += reported.output ?? 0;
106
+ usage.estimatedCostUsd += reported.cost?.total ?? 0;
107
+ }
108
+ }
109
+ const priced = Object.values(model.cost).some((value) => value > 0);
94
110
  return {
95
111
  text,
112
+ usage: {
113
+ inputTokens: usage.inputTokens,
114
+ outputTokens: usage.outputTokens,
115
+ ...priced ? { estimatedCostUsd: usage.estimatedCostUsd } : {}
116
+ },
96
117
  modelRef: `${model.provider}/${model.id}`
97
118
  };
98
119
  } finally {
@@ -0,0 +1,5 @@
1
+ /** Recheck connector consent for stored cards and actions, not just model input. */
2
+ export declare function insightSourcesAuthorized(insightId: string): boolean;
3
+ /** Compare versions, not generated prose, before showing or executing prepared work. */
4
+ export declare function insightSourcesChanged(insightId: string): boolean;
5
+ export declare function authorizedConnectedSource(itemId: string, workspaceId: string, scenarioKey: string, agentId?: string | null): import("../../knowledge/types.js").KnowledgeSourceItem;
@@ -0,0 +1,61 @@
1
+ import { getSqliteDatabase } from "../../storage/sqlite/transaction.js";
2
+ import { getKnowledgeSourceItem } from "../../storage/sqlite/knowledge-repository.js";
3
+ import { getConnectorSyncPolicyForConnection } from "../../storage/sqlite/connector-sync-policy-repository.js";
4
+ import { readMailThread } from "../mail-thread.js";
5
+ //#region src/proactive/execution/authorization.ts
6
+ /** Recheck connector consent for stored cards and actions, not just model input. */
7
+ function insightSourcesAuthorized(insightId) {
8
+ const snapshot = getSqliteDatabase().prepare(`SELECT s.workspace_id, x.scenario_key, c.evidence_ids_json
9
+ FROM proactive_insights x JOIN proactive_scenario_subscriptions s USING(subscription_id)
10
+ JOIN proactive_runs r USING(run_id) LEFT JOIN proactive_context_snapshots c ON c.snapshot_id = r.context_snapshot_id
11
+ WHERE x.insight_id = ?`).get(insightId);
12
+ if (snapshot?.evidence_ids_json) {
13
+ if (JSON.parse(snapshot.evidence_ids_json).some((id) => id.startsWith("source-item:") && !authorizedConnectedSource(id.slice(12), snapshot.workspace_id, snapshot.scenario_key))) return false;
14
+ }
15
+ return getSqliteDatabase().prepare(`SELECT e.subject_id, e.workspace_id, x.scenario_key
16
+ FROM proactive_insights x JOIN proactive_runs r USING(run_id)
17
+ JOIN proactive_batch_events be ON be.batch_id = r.batch_id JOIN proactive_events e USING(event_id)
18
+ WHERE x.insight_id = ? AND e.type LIKE 'connected_source.%'`).all(insightId).every((row) => Boolean(authorizedConnectedSource(row.subject_id, row.workspace_id, row.scenario_key)));
19
+ }
20
+ /** Compare versions, not generated prose, before showing or executing prepared work. */
21
+ function insightSourcesChanged(insightId) {
22
+ const db = getSqliteDatabase();
23
+ const row = db.prepare(`SELECT c.content_json FROM proactive_insights x JOIN proactive_runs r USING(run_id)
24
+ JOIN proactive_context_snapshots c ON c.snapshot_id = r.context_snapshot_id WHERE x.insight_id = ?`).get(insightId);
25
+ if (!row) return false;
26
+ const snapshot = JSON.parse(row.content_json);
27
+ if (snapshot.follow_up?.followUpId) {
28
+ const follow = db.prepare("SELECT source_item_id, revision, status, due_at FROM proactive_follow_ups WHERE id = ?").get(snapshot.follow_up.followUpId);
29
+ if (!follow || follow.status !== "watching" || follow.revision !== snapshot.follow_up.revision || Date.parse(follow.due_at) <= Date.now() !== snapshot.follow_up.deadlinePassed || readMailThread(follow.source_item_id)?.fingerprint !== snapshot.follow_up.fingerprint) return true;
30
+ }
31
+ for (const source of [...snapshot.connected_source?.items ?? [], ...snapshot.follow_up?.items ?? []]) {
32
+ const current = getKnowledgeSourceItem(source.sourceItemId);
33
+ if (!current || current.deletedAt || current.contentHash !== source.contentHash || current.occurredAt !== source.occurredAt) return true;
34
+ }
35
+ const project = snapshot.project_state?.project;
36
+ if (project) {
37
+ const current = db.prepare("SELECT updated_at FROM projects WHERE project_id = ?").get(project.project_id);
38
+ if (!current || current.updated_at !== project.updated_at) return true;
39
+ }
40
+ for (const task of [...snapshot.project_state?.activeTasks ?? [], ...snapshot.meeting_workspace?.activeTasks ?? []]) {
41
+ const current = db.prepare("SELECT updated_at FROM tasks WHERE task_id = ?").get(task.task_id);
42
+ if (!current || current.updated_at !== task.updated_at) return true;
43
+ }
44
+ for (const note of snapshot.meeting_workspace?.recentNotes ?? []) {
45
+ const current = db.prepare("SELECT updated_at FROM notes WHERE note_id = ?").get(note.note_id);
46
+ if (!current || current.updated_at !== note.updated_at) return true;
47
+ }
48
+ return false;
49
+ }
50
+ function authorizedConnectedSource(itemId, workspaceId, scenarioKey, agentId) {
51
+ const item = getKnowledgeSourceItem(itemId);
52
+ if (!item || item.deletedAt || item.metadata.workspaceId !== workspaceId || item.sensitivity === "secret" || item.sensitivity === "regulated") return null;
53
+ if (agentId && item.metadata.agentId && item.metadata.agentId !== agentId) return null;
54
+ const connectionId = item.metadata.connectionId;
55
+ if (typeof connectionId !== "string") return null;
56
+ if (!getSqliteDatabase().prepare("SELECT 1 FROM connector_connections WHERE id = ? AND status = 'active'").get(connectionId)) return null;
57
+ const policy = getConnectorSyncPolicyForConnection(connectionId);
58
+ return policy?.scanEnabled && policy.proactiveEnabled && (!policy.allowedScenarioKeys.length || policy.allowedScenarioKeys.includes(scenarioKey)) ? item : null;
59
+ }
60
+ //#endregion
61
+ export { authorizedConnectedSource, insightSourcesAuthorized, insightSourcesChanged };
@@ -33,6 +33,10 @@ export declare class DiscussionContextProvider implements ContextProvider {
33
33
  readonly id = "discussion";
34
34
  collect(input: ContextInput): Promise<ResolvedContext>;
35
35
  }
36
+ export declare class MailFollowUpContextProvider implements ContextProvider {
37
+ readonly id = "follow_up";
38
+ collect(input: ContextInput): Promise<ResolvedContext>;
39
+ }
36
40
  export declare class ContextProviderRegistry {
37
41
  private readonly providers;
38
42
  constructor(providers?: ContextProvider[]);