@xopcai/xopc 0.0.99 → 0.0.100
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.
- package/dist/browser-ext/manifest.json +1 -1
- package/dist/extensions/telegram/src/account-manager.d.ts +3 -3
- package/dist/extensions/telegram/src/account-manager.js +8 -8
- package/dist/extensions/telegram/src/account-manager.js.map +1 -1
- package/dist/extensions/telegram/src/actions/message-actions.d.ts +4 -0
- package/dist/extensions/telegram/src/actions/message-actions.js +71 -0
- package/dist/extensions/telegram/src/actions/message-actions.js.map +1 -0
- package/dist/extensions/telegram/src/adapters/config-adapter.js +9 -1
- package/dist/extensions/telegram/src/adapters/config-adapter.js.map +1 -1
- package/dist/extensions/telegram/src/adapters/config-surface.js +1 -1
- package/dist/extensions/telegram/src/adapters/config-surface.js.map +1 -1
- package/dist/extensions/telegram/src/adapters/outbound-adapter.d.ts +2 -1
- package/dist/extensions/telegram/src/adapters/outbound-adapter.js +18 -4
- package/dist/extensions/telegram/src/adapters/outbound-adapter.js.map +1 -1
- package/dist/extensions/telegram/src/adapters/security-adapter.js +2 -1
- package/dist/extensions/telegram/src/adapters/security-adapter.js.map +1 -1
- package/dist/extensions/telegram/src/adapters/streaming-adapter.js +90 -6
- package/dist/extensions/telegram/src/adapters/streaming-adapter.js.map +1 -1
- package/dist/extensions/telegram/src/adapters/types.d.ts +9 -1
- package/dist/extensions/telegram/src/api-root.d.ts +4 -0
- package/dist/extensions/telegram/src/api-root.js +42 -0
- package/dist/extensions/telegram/src/api-root.js.map +1 -0
- package/dist/extensions/telegram/src/approval-delivery.d.ts +9 -0
- package/dist/extensions/telegram/src/approval-delivery.js +36 -0
- package/dist/extensions/telegram/src/approval-delivery.js.map +1 -0
- package/dist/extensions/telegram/src/approval-store.d.ts +25 -0
- package/dist/extensions/telegram/src/approval-store.js +61 -0
- package/dist/extensions/telegram/src/approval-store.js.map +1 -0
- package/dist/extensions/telegram/src/config-schema.d.ts +185 -35
- package/dist/extensions/telegram/src/config-schema.js +67 -45
- package/dist/extensions/telegram/src/config-schema.js.map +1 -1
- package/dist/extensions/telegram/src/conversation-id.d.ts +6 -0
- package/dist/extensions/telegram/src/conversation-id.js +18 -0
- package/dist/extensions/telegram/src/conversation-id.js.map +1 -0
- package/dist/extensions/telegram/src/doctor.d.ts +5 -0
- package/dist/extensions/telegram/src/doctor.js +80 -0
- package/dist/extensions/telegram/src/doctor.js.map +1 -0
- package/dist/extensions/telegram/src/exec-approval-handler.d.ts +7 -0
- package/dist/extensions/telegram/src/exec-approval-handler.js +36 -0
- package/dist/extensions/telegram/src/exec-approval-handler.js.map +1 -0
- package/dist/extensions/telegram/src/exec-approvals.d.ts +8 -0
- package/dist/extensions/telegram/src/exec-approvals.js +20 -0
- package/dist/extensions/telegram/src/exec-approvals.js.map +1 -0
- package/dist/extensions/telegram/src/focus-handler.d.ts +12 -0
- package/dist/extensions/telegram/src/focus-handler.js +55 -0
- package/dist/extensions/telegram/src/focus-handler.js.map +1 -0
- package/dist/extensions/telegram/src/group-config-resolver.d.ts +12 -0
- package/dist/extensions/telegram/src/group-config-resolver.js +17 -0
- package/dist/extensions/telegram/src/group-config-resolver.js.map +1 -0
- package/dist/extensions/telegram/src/inbound-coalescer.d.ts +15 -0
- package/dist/extensions/telegram/src/inbound-coalescer.js +107 -0
- package/dist/extensions/telegram/src/inbound-coalescer.js.map +1 -0
- package/dist/extensions/telegram/src/inbound-processor.d.ts +1 -0
- package/dist/extensions/telegram/src/inbound-processor.js +41 -4
- package/dist/extensions/telegram/src/inbound-processor.js.map +1 -1
- package/dist/extensions/telegram/src/network-errors.d.ts +2 -0
- package/dist/extensions/telegram/src/network-errors.js +23 -0
- package/dist/extensions/telegram/src/network-errors.js.map +1 -0
- package/dist/extensions/telegram/src/plugin.d.ts +11 -0
- package/dist/extensions/telegram/src/plugin.js +191 -57
- package/dist/extensions/telegram/src/plugin.js.map +1 -1
- package/dist/extensions/telegram/src/polling-session.d.ts +17 -0
- package/dist/extensions/telegram/src/polling-session.js +112 -0
- package/dist/extensions/telegram/src/polling-session.js.map +1 -0
- package/dist/extensions/telegram/src/proxy-fetch.d.ts +2 -0
- package/dist/extensions/telegram/src/proxy-fetch.js +14 -0
- package/dist/extensions/telegram/src/proxy-fetch.js.map +1 -0
- package/dist/extensions/telegram/src/reactions.d.ts +14 -0
- package/dist/extensions/telegram/src/reactions.js +48 -0
- package/dist/extensions/telegram/src/reactions.js.map +1 -0
- package/dist/extensions/telegram/src/reply-params.d.ts +15 -0
- package/dist/extensions/telegram/src/reply-params.js +28 -0
- package/dist/extensions/telegram/src/reply-params.js.map +1 -0
- package/dist/extensions/telegram/src/startup-errors.d.ts +3 -0
- package/dist/extensions/telegram/src/startup-errors.js +27 -0
- package/dist/extensions/telegram/src/startup-errors.js.map +1 -0
- package/dist/extensions/telegram/src/telegram-actions.d.ts +25 -0
- package/dist/extensions/telegram/src/telegram-actions.js +65 -0
- package/dist/extensions/telegram/src/telegram-actions.js.map +1 -0
- package/dist/extensions/telegram/src/thread-bindings.d.ts +15 -0
- package/dist/extensions/telegram/src/thread-bindings.js +22 -0
- package/dist/extensions/telegram/src/thread-bindings.js.map +1 -0
- package/dist/extensions/telegram/src/token-resolver.d.ts +8 -0
- package/dist/extensions/telegram/src/token-resolver.js +34 -0
- package/dist/extensions/telegram/src/token-resolver.js.map +1 -0
- package/dist/extensions/telegram/src/update-offset-store.d.ts +9 -0
- package/dist/extensions/telegram/src/update-offset-store.js +66 -0
- package/dist/extensions/telegram/src/update-offset-store.js.map +1 -0
- package/dist/extensions/telegram/xopc.extension.json +1 -1
- package/dist/gateway/static/root/assets/{agents-4KTK-Ku7.js → agents-C5jtBK-H.js} +1 -1
- package/dist/gateway/static/root/assets/{apps-page-DkgInY2w.js → apps-page-smJl-qf_.js} +1 -1
- package/dist/gateway/static/root/assets/channels-settings-CH6KgFK6.js +1 -0
- package/dist/gateway/static/root/assets/channels-status-swr-CV70xvY7.js +8 -0
- package/dist/gateway/static/root/assets/{cron-api-BRDli2Mm.js → cron-api-CgBO8B7I.js} +1 -1
- package/dist/gateway/static/root/assets/{cron-page-BzEr5Za8.js → cron-page-Be0cW1cR.js} +1 -1
- package/dist/gateway/static/root/assets/{dist-BsHh1vX0.js → dist-P8HRGUuh.js} +1 -1
- package/dist/gateway/static/root/assets/{extension-debug-page-TWt5q_ef.js → extension-debug-page-BowuycYu.js} +1 -1
- package/dist/gateway/static/root/assets/{extension-page-C3kV8ZvZ.js → extension-page-27-Zpv8O.js} +1 -1
- package/dist/gateway/static/root/assets/{extension-settings-page-Csy9LNC6.js → extension-settings-page-DDFa_rIq.js} +1 -1
- package/dist/gateway/static/root/assets/{fetch-BLLOP2CM.js → fetch-drJUxxKP.js} +1 -1
- package/dist/gateway/static/root/assets/{field-primitives-MXbM8HvY.js → field-primitives-BWLssxEb.js} +1 -1
- package/dist/gateway/static/root/assets/{heartbeat-config-api-CkoyqfRx.js → heartbeat-config-api-BVuYNYT_.js} +1 -1
- package/dist/gateway/static/root/assets/index-CRDAmr3W.js +4840 -0
- package/dist/gateway/static/root/assets/index-DjNDHzwG.css +1 -0
- package/dist/gateway/static/root/assets/{logs-page-B2vY41ph.js → logs-page-BDX8IrDQ.js} +1 -1
- package/dist/gateway/static/root/assets/{note-detail-page-B7qE5pkO.js → note-detail-page-BmQ9KeiA.js} +1 -1
- package/dist/gateway/static/root/assets/{note-time-NBBReVR4.js → note-time-14I9Sgqh.js} +1 -1
- package/dist/gateway/static/root/assets/{notes-page-CsWYaqYM.js → notes-page-BMfP0FFf.js} +1 -1
- package/dist/gateway/static/root/assets/{sessions-page-BPGY3SCT.js → sessions-page-C3scyChq.js} +1 -1
- package/dist/gateway/static/root/assets/{settings-advanced-gate-DtA451RM.js → settings-advanced-gate-2ODuCjHP.js} +1 -1
- package/dist/gateway/static/root/assets/{settings-form-section-DYR_SPlX.js → settings-form-section-DUoGKAiW.js} +1 -1
- package/dist/gateway/static/root/assets/{settings-page-BJUgZQzN.js → settings-page-CttAfOWV.js} +1 -1
- package/dist/gateway/static/root/assets/{share-preview-page-3u8VFmdo.js → share-preview-page-B77xqiiI.js} +1 -1
- package/dist/gateway/static/root/assets/{skills-page-DuyhcH4U.js → skills-page-B_bAZGzB.js} +1 -1
- package/dist/gateway/static/root/assets/{theme-store-e2q2yjs4.js → theme-store-BgCPrmxU.js} +1 -1
- package/dist/gateway/static/root/assets/url-q28QhI7l.js +3 -0
- package/dist/gateway/static/root/assets/{utils-B4Vw3fnc.js → utils-CCGejlcX.js} +1 -1
- package/dist/gateway/static/root/assets/{voice-api-key-field-BFY67Hhp.js → voice-api-key-field-DZzzihcY.js} +1 -1
- package/dist/gateway/static/root/assets/{workflow-page.utils-yUJ5jexd.js → workflow-page.utils-D5RMAmT4.js} +1 -1
- package/dist/gateway/static/root/assets/{workflows-page-DIMHCpNt.js → workflows-page-DEYpC6Bv.js} +1 -1
- package/dist/gateway/static/root/index.html +5 -5
- package/dist/package.js +1 -1
- package/dist/src/agent/agent-manager.d.ts +4 -0
- package/dist/src/agent/agent-manager.js +68 -4
- package/dist/src/agent/agent-manager.js.map +1 -1
- package/dist/src/agent/child-agent-factory.d.ts +1 -0
- package/dist/src/agent/child-agent-factory.js +13 -10
- package/dist/src/agent/child-agent-factory.js.map +1 -1
- package/dist/src/agent/embedded/run-for-session.d.ts +1 -0
- package/dist/src/agent/embedded/run-for-session.js +1 -0
- package/dist/src/agent/embedded/run-for-session.js.map +1 -1
- package/dist/src/agent/embedded/run-turn.js +1 -17
- package/dist/src/agent/embedded/run-turn.js.map +1 -1
- package/dist/src/agent/embedded/session-runner.js +3 -1
- package/dist/src/agent/embedded/session-runner.js.map +1 -1
- package/dist/src/agent/embedded/session-tool-result-guard.d.ts +1 -0
- package/dist/src/agent/embedded/session-tool-result-guard.js +1 -0
- package/dist/src/agent/embedded/session-tool-result-guard.js.map +1 -1
- package/dist/src/agent/inbound/attachment-pipeline.d.ts +37 -0
- package/dist/src/agent/inbound/attachment-pipeline.js +169 -0
- package/dist/src/agent/inbound/attachment-pipeline.js.map +1 -0
- package/dist/src/agent/inbound/turn-dispatcher.d.ts +3 -5
- package/dist/src/agent/inbound/turn-dispatcher.js +1 -2
- package/dist/src/agent/inbound/turn-dispatcher.js.map +1 -1
- package/dist/src/agent/memory/index.d.ts +2 -0
- package/dist/src/agent/memory/index.js +2 -1
- package/dist/src/agent/memory/memory-flush.d.ts +27 -0
- package/dist/src/agent/memory/memory-flush.js +124 -0
- package/dist/src/agent/memory/memory-flush.js.map +1 -0
- package/dist/src/agent/messaging/outbound-coordinator.js +2 -1
- package/dist/src/agent/messaging/outbound-coordinator.js.map +1 -1
- package/dist/src/agent/messaging/stream-manager.d.ts +2 -0
- package/dist/src/agent/messaging/stream-manager.js +3 -0
- package/dist/src/agent/messaging/stream-manager.js.map +1 -1
- package/dist/src/agent/orchestration/agent-orchestrator.d.ts +0 -4
- package/dist/src/agent/orchestration/agent-orchestrator.js +40 -107
- package/dist/src/agent/orchestration/agent-orchestrator.js.map +1 -1
- package/dist/src/agent/prompt/contribution.d.ts +9 -0
- package/dist/src/agent/prompt/contribution.js +1 -0
- package/dist/src/agent/prompt/safety.js +0 -10
- package/dist/src/agent/prompt/safety.js.map +1 -1
- package/dist/src/agent/prompt/sanitize-for-prompt.d.ts +6 -0
- package/dist/src/agent/prompt/sanitize-for-prompt.js +13 -0
- package/dist/src/agent/prompt/sanitize-for-prompt.js.map +1 -0
- package/dist/src/agent/prompt/sections/behavior.d.ts +5 -0
- package/dist/src/agent/prompt/sections/behavior.js +50 -0
- package/dist/src/agent/prompt/sections/behavior.js.map +1 -0
- package/dist/src/agent/prompt/sections/memory-skills.d.ts +9 -0
- package/dist/src/agent/prompt/sections/memory-skills.js +59 -0
- package/dist/src/agent/prompt/sections/memory-skills.js.map +1 -0
- package/dist/src/agent/prompt/sections/messaging-runtime.d.ts +16 -0
- package/dist/src/agent/prompt/sections/messaging-runtime.js +69 -0
- package/dist/src/agent/prompt/sections/messaging-runtime.js.map +1 -0
- package/dist/src/agent/prompt/sections/project-context.d.ts +16 -0
- package/dist/src/agent/prompt/sections/project-context.js +58 -0
- package/dist/src/agent/prompt/sections/project-context.js.map +1 -0
- package/dist/src/agent/prompt/sections/tooling.d.ts +5 -0
- package/dist/src/agent/prompt/sections/tooling.js +119 -0
- package/dist/src/agent/prompt/sections/tooling.js.map +1 -0
- package/dist/src/agent/prompt/sections/workspace-runtime.d.ts +11 -0
- package/dist/src/agent/prompt/sections/workspace-runtime.js +32 -0
- package/dist/src/agent/prompt/sections/workspace-runtime.js.map +1 -0
- package/dist/src/agent/prompt/service-prompt-builder.d.ts +13 -0
- package/dist/src/agent/prompt/service-prompt-builder.js +54 -13
- package/dist/src/agent/prompt/service-prompt-builder.js.map +1 -1
- package/dist/src/agent/prompt/subagent-context.d.ts +15 -0
- package/dist/src/agent/prompt/subagent-context.js +68 -0
- package/dist/src/agent/prompt/subagent-context.js.map +1 -0
- package/dist/src/agent/prompt/system-prompt-params.d.ts +53 -0
- package/dist/src/agent/prompt/system-prompt-params.js +74 -0
- package/dist/src/agent/prompt/system-prompt-params.js.map +1 -0
- package/dist/src/agent/prompt/system-prompt.d.ts +22 -11
- package/dist/src/agent/prompt/system-prompt.js +79 -193
- package/dist/src/agent/prompt/system-prompt.js.map +1 -1
- package/dist/src/agent/prompt/types.d.ts +3 -0
- package/dist/src/agent/service/build-direct-message-content.d.ts +5 -21
- package/dist/src/agent/service/build-direct-message-content.js +11 -64
- package/dist/src/agent/service/build-direct-message-content.js.map +1 -1
- package/dist/src/agent/service/direct-turn-helpers.d.ts +1 -1
- package/dist/src/agent/service/direct-turn-helpers.js +7 -0
- package/dist/src/agent/service/direct-turn-helpers.js.map +1 -1
- package/dist/src/agent/service/process-direct-one-shot.d.ts +3 -3
- package/dist/src/agent/service/process-direct-one-shot.js +22 -17
- package/dist/src/agent/service/process-direct-one-shot.js.map +1 -1
- package/dist/src/agent/service/process-direct-streaming.d.ts +6 -20
- package/dist/src/agent/service/process-direct-streaming.js +39 -40
- package/dist/src/agent/service/process-direct-streaming.js.map +1 -1
- package/dist/src/agent/service/webchat-tts.d.ts +4 -9
- package/dist/src/agent/service/webchat-tts.js +9 -20
- package/dist/src/agent/service/webchat-tts.js.map +1 -1
- package/dist/src/agent/service.d.ts +8 -19
- package/dist/src/agent/service.js +53 -11
- package/dist/src/agent/service.js.map +1 -1
- package/dist/src/agent/tools/factory.js +2 -0
- package/dist/src/agent/tools/factory.js.map +1 -1
- package/dist/src/agent/tools/index.d.ts +1 -0
- package/dist/src/agent/tools/index.js +2 -1
- package/dist/src/agent/tools/media-read-tool.d.ts +2 -0
- package/dist/src/agent/tools/media-read-tool.js +89 -0
- package/dist/src/agent/tools/media-read-tool.js.map +1 -0
- package/dist/src/channels/attachments/attachment-classifiers.d.ts +8 -0
- package/dist/src/channels/attachments/attachment-classifiers.js +11 -0
- package/dist/src/channels/attachments/attachment-classifiers.js.map +1 -0
- package/dist/src/channels/attachments/inbound-persist.d.ts +13 -34
- package/dist/src/channels/attachments/inbound-persist.js +34 -102
- package/dist/src/channels/attachments/inbound-persist.js.map +1 -1
- package/dist/src/channels/attachments/inbound-types.d.ts +13 -0
- package/dist/src/channels/attachments/inbound-types.js +30 -0
- package/dist/src/channels/attachments/inbound-types.js.map +1 -0
- package/dist/src/channels/attachments/outbound-tts-persist.d.ts +3 -12
- package/dist/src/channels/attachments/outbound-tts-persist.js +28 -48
- package/dist/src/channels/attachments/outbound-tts-persist.js.map +1 -1
- package/dist/src/channels/attachments/voice-stt-webchat.d.ts +3 -3
- package/dist/src/channels/attachments/voice-stt-webchat.js +8 -14
- package/dist/src/channels/attachments/voice-stt-webchat.js.map +1 -1
- package/dist/src/channels/channel-domain.d.ts +30 -2
- package/dist/src/channels/exec-approval-runtime.d.ts +29 -0
- package/dist/src/channels/exec-approval-runtime.js +30 -0
- package/dist/src/channels/exec-approval-runtime.js.map +1 -0
- package/dist/src/channels/index.js +1 -1
- package/dist/src/channels/plugin-types.d.ts +1 -0
- package/dist/src/channels/transport-types.d.ts +2 -2
- package/dist/src/cli/commands/channels.js +1 -1
- package/dist/src/cli/commands/doctor/checks/database-schema.d.ts +2 -0
- package/dist/src/cli/commands/doctor/checks/database-schema.js +62 -0
- package/dist/src/cli/commands/doctor/checks/database-schema.js.map +1 -0
- package/dist/src/cli/commands/doctor/flow.js +2 -0
- package/dist/src/cli/commands/doctor/flow.js.map +1 -1
- package/dist/src/cli/commands/init.js +2 -57
- package/dist/src/cli/commands/init.js.map +1 -1
- package/dist/src/cli/commands/onboard/channels/registry.js +1 -1
- package/dist/src/cli/commands/setup.js +6 -5
- package/dist/src/cli/commands/setup.js.map +1 -1
- package/dist/src/cli/utils/init-workspace-core.js +1 -2
- package/dist/src/cli/utils/init-workspace-core.js.map +1 -1
- package/dist/src/config/index.js +2 -2
- package/dist/src/config/paths.d.ts +0 -13
- package/dist/src/config/paths.js +1 -20
- package/dist/src/config/paths.js.map +1 -1
- package/dist/src/config/rules.js +1 -1
- package/dist/src/config/schema.d.ts +24 -0
- package/dist/src/config/schema.js +33 -2
- package/dist/src/config/schema.js.map +1 -1
- package/dist/src/cron/executor.js +2 -2
- package/dist/src/gateway/heartbeat/service.js +1 -1
- package/dist/src/gateway/hono/lib/config-payload.js +1 -1
- package/dist/src/gateway/hono/routes/config-patch/channels.js +3 -3
- package/dist/src/gateway/hono/routes/config-patch/channels.js.map +1 -1
- package/dist/src/gateway/hono/routes/lazy-bundles.js +8 -0
- package/dist/src/gateway/hono/routes/lazy-bundles.js.map +1 -1
- package/dist/src/gateway/hono/routes/media.d.ts +3 -0
- package/dist/src/gateway/hono/routes/media.js +50 -0
- package/dist/src/gateway/hono/routes/media.js.map +1 -0
- package/dist/src/gateway/hono/routes/sessions.js +6 -0
- package/dist/src/gateway/hono/routes/sessions.js.map +1 -1
- package/dist/src/gateway/hono/routes/workspace.js +1 -87
- package/dist/src/gateway/hono/routes/workspace.js.map +1 -1
- package/dist/src/gateway/service/sessions-api.js +3 -0
- package/dist/src/gateway/service/sessions-api.js.map +1 -1
- package/dist/src/heartbeat/index.js +1 -1
- package/dist/src/media/index.d.ts +5 -0
- package/dist/src/media/index.js +5 -0
- package/dist/src/media/media-reference.d.ts +23 -0
- package/dist/src/media/media-reference.js +34 -0
- package/dist/src/media/media-reference.js.map +1 -0
- package/dist/src/media/paths.d.ts +5 -0
- package/dist/src/media/paths.js +20 -0
- package/dist/src/media/paths.js.map +1 -0
- package/dist/src/media/session-references.d.ts +8 -0
- package/dist/src/media/session-references.js +45 -0
- package/dist/src/media/session-references.js.map +1 -0
- package/dist/src/media/store.d.ts +19 -0
- package/dist/src/media/store.js +131 -0
- package/dist/src/media/store.js.map +1 -0
- package/dist/src/media/types.d.ts +34 -0
- package/dist/src/media/types.js +1 -0
- package/dist/src/media/uri.d.ts +15 -0
- package/dist/src/media/uri.js +51 -0
- package/dist/src/media/uri.js.map +1 -0
- package/dist/src/session/session-title.js +6 -3
- package/dist/src/session/session-title.js.map +1 -1
- package/dist/src/session/store.js +1 -1
- package/dist/src/session/store.js.map +1 -1
- package/dist/src/session/types.d.ts +12 -7
- package/dist/src/session/types.js.map +1 -1
- package/dist/src/storage/sqlite/index.d.ts +4 -1
- package/dist/src/storage/sqlite/index.js +6 -2
- package/dist/src/storage/sqlite/migrations/002_add_flush_columns.sql +3 -0
- package/dist/src/storage/sqlite/migrations/discover.d.ts +4 -0
- package/dist/src/storage/sqlite/migrations/discover.js +38 -0
- package/dist/src/storage/sqlite/migrations/discover.js.map +1 -0
- package/dist/src/storage/sqlite/migrations/discover.ts +52 -0
- package/dist/src/storage/sqlite/migrations/errors.d.ts +11 -0
- package/dist/src/storage/sqlite/migrations/errors.js +27 -0
- package/dist/src/storage/sqlite/migrations/errors.js.map +1 -0
- package/dist/src/storage/sqlite/migrations/errors.ts +32 -0
- package/dist/src/storage/sqlite/migrations/runner.d.ts +22 -0
- package/dist/src/storage/sqlite/migrations/runner.js +97 -0
- package/dist/src/storage/sqlite/migrations/runner.js.map +1 -0
- package/dist/src/storage/sqlite/migrations/runner.ts +153 -0
- package/dist/src/storage/sqlite/migrations/types.d.ts +12 -0
- package/dist/src/storage/sqlite/migrations/types.js +1 -0
- package/dist/src/storage/sqlite/migrations/types.ts +13 -0
- package/dist/src/storage/sqlite/row-mappers.d.ts +4 -0
- package/dist/src/storage/sqlite/row-mappers.js +4 -0
- package/dist/src/storage/sqlite/row-mappers.js.map +1 -1
- package/dist/src/storage/sqlite/schema-version.d.ts +6 -0
- package/dist/src/storage/sqlite/schema-version.js +29 -0
- package/dist/src/storage/sqlite/schema-version.js.map +1 -0
- package/dist/src/storage/sqlite/schema.d.ts +5 -3
- package/dist/src/storage/sqlite/schema.js +24 -28
- package/dist/src/storage/sqlite/schema.js.map +1 -1
- package/dist/src/storage/sqlite/schema.sql +2 -0
- package/dist/src/storage/sqlite/session-metadata.js +1 -0
- package/dist/src/storage/sqlite/session-metadata.js.map +1 -1
- package/dist/src/storage/sqlite/session-repository.js +7 -3
- package/dist/src/storage/sqlite/session-repository.js.map +1 -1
- package/package.json +1 -1
- package/dist/gateway/static/root/assets/channels-settings-BxW1Xio4.js +0 -1
- package/dist/gateway/static/root/assets/channels-status-swr-Cxm6AvQO.js +0 -8
- package/dist/gateway/static/root/assets/index-BJDmBCSl.css +0 -1
- package/dist/gateway/static/root/assets/index-Cbg5TS5m.js +0 -4707
- package/dist/gateway/static/root/assets/url-DpFBIyN9.js +0 -3
- package/dist/src/cli/commands/onboard/workspace.d.ts +0 -14
- package/dist/src/cli/commands/onboard/workspace.js +0 -33
- package/dist/src/cli/commands/onboard/workspace.js.map +0 -1
- package/dist/src/cli/utils/workspace.d.ts +0 -35
- package/dist/src/cli/utils/workspace.js +0 -72
- package/dist/src/cli/utils/workspace.js.map +0 -1
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
import { readAgentMessageContent } from "../memory/agent-message-access.js";
|
|
2
|
+
import { readMediaReferenceBase64 } from "../../media/media-reference.js";
|
|
3
|
+
import { isImageInboundAttachment } from "../../channels/attachments/attachment-classifiers.js";
|
|
4
|
+
import "../../channels/attachments/inbound-persist.js";
|
|
5
|
+
import { expandAtFileMentionsInPlainText } from "../context/expand-at-file-mentions.js";
|
|
6
|
+
import { resolveImageHandlingStrategy } from "../image/vision-detection.js";
|
|
7
|
+
import { resolveInboundImageContentParts } from "../image/inbound-image-handling.js";
|
|
8
|
+
//#region src/agent/inbound/attachment-pipeline.ts
|
|
9
|
+
const VISION_INLINE_MAX_BYTES = 2 * 1024 * 1024;
|
|
10
|
+
function textBlocksFromContent(content) {
|
|
11
|
+
if (typeof content === "string") return content.trim() ? [content] : [];
|
|
12
|
+
if (!Array.isArray(content)) return [];
|
|
13
|
+
const out = [];
|
|
14
|
+
for (const block of content) if (block && typeof block === "object" && block.type === "text") {
|
|
15
|
+
const t = block.text;
|
|
16
|
+
if (typeof t === "string" && t.trim()) out.push(t);
|
|
17
|
+
}
|
|
18
|
+
return out;
|
|
19
|
+
}
|
|
20
|
+
function joinTextBlocks(parts) {
|
|
21
|
+
return parts.join("\n").trim();
|
|
22
|
+
}
|
|
23
|
+
function buildMediaPathFields(media) {
|
|
24
|
+
if (!media.length) return {};
|
|
25
|
+
return {
|
|
26
|
+
MediaPath: media[0].path,
|
|
27
|
+
MediaPaths: media.map((m) => m.path),
|
|
28
|
+
MediaTypes: media.map((m) => m.mimeType)
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
function assertUserContentHasNoInlineMedia(content) {
|
|
32
|
+
if (!Array.isArray(content)) return;
|
|
33
|
+
for (const block of content) {
|
|
34
|
+
if (!block || typeof block !== "object") continue;
|
|
35
|
+
if (block.type === "image") throw new Error("User transcript content must not contain image blocks");
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
function assertTranscriptUserMessage(message) {
|
|
39
|
+
if (message.role !== "user") return;
|
|
40
|
+
assertUserContentHasNoInlineMedia(message.content);
|
|
41
|
+
const media = message.media;
|
|
42
|
+
if (!media?.length) return;
|
|
43
|
+
for (const ref of media) {
|
|
44
|
+
if (!ref.uri?.trim()) throw new Error("User transcript media ref missing uri");
|
|
45
|
+
if ("data" in ref && typeof ref.data === "string") throw new Error("User transcript media ref must not include data");
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
async function readImageBase64FromRef(ref) {
|
|
49
|
+
const loaded = await readMediaReferenceBase64(ref.uri, VISION_INLINE_MAX_BYTES);
|
|
50
|
+
return {
|
|
51
|
+
data: loaded.data,
|
|
52
|
+
mimeType: ref.mimeType?.startsWith("image/") ? ref.mimeType : loaded.mimeType
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
function appendMediaAttachedLines(textParts, media) {
|
|
56
|
+
for (const ref of media) if (!isImageInboundAttachment(ref)) textParts.push([
|
|
57
|
+
`[media attached: ${ref.name} (${ref.mimeType}, ${ref.size} bytes)]`,
|
|
58
|
+
`xopc-media-uri:${ref.uri}`,
|
|
59
|
+
`xopc-media-path:${ref.path}`,
|
|
60
|
+
"Use the read_media tool with the xopc-media-uri value when you need to inspect this attachment."
|
|
61
|
+
].join("\n"));
|
|
62
|
+
}
|
|
63
|
+
async function expandUserText(text, sessionKey, agentManager) {
|
|
64
|
+
if (!text.trim()) return "";
|
|
65
|
+
let out = text;
|
|
66
|
+
if (/@file:/.test(out)) {
|
|
67
|
+
const wsKey = sessionKey || "agent:main:main";
|
|
68
|
+
const root = agentManager.getResolvedWorkspaceForSession(wsKey);
|
|
69
|
+
out = await expandAtFileMentionsInPlainText(out, root);
|
|
70
|
+
}
|
|
71
|
+
return out.trim();
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Build the transcript row for a user turn (text + media metadata only).
|
|
75
|
+
*/
|
|
76
|
+
async function buildTranscriptUserMessage(opts) {
|
|
77
|
+
const expandedText = await expandUserText(opts.text, opts.sessionKey, opts.agentManager);
|
|
78
|
+
const prepared = opts.prepared ?? [];
|
|
79
|
+
const imageRefs = prepared.filter(isImageInboundAttachment);
|
|
80
|
+
const textParts = [];
|
|
81
|
+
if (expandedText) textParts.push(expandedText);
|
|
82
|
+
const strategy = resolveImageHandlingStrategy(opts.modelRef);
|
|
83
|
+
if (strategy !== "native") appendMediaAttachedLines(textParts, prepared.filter((m) => !isImageInboundAttachment(m)));
|
|
84
|
+
if (imageRefs.length > 0 && strategy !== "native") {
|
|
85
|
+
const images = await Promise.all(imageRefs.map((ref) => readImageBase64FromRef(ref)));
|
|
86
|
+
const parts = await resolveInboundImageContentParts({
|
|
87
|
+
modelRef: opts.modelRef,
|
|
88
|
+
cfg: opts.config,
|
|
89
|
+
userTextForContext: expandedText,
|
|
90
|
+
images
|
|
91
|
+
});
|
|
92
|
+
for (const part of parts) if (part.type === "text" && part.text.trim()) textParts.push(part.text.trim());
|
|
93
|
+
}
|
|
94
|
+
if (textParts.length === 0 && prepared.length > 0) textParts.push("Please analyze the attachment(s) I sent.");
|
|
95
|
+
const message = {
|
|
96
|
+
role: "user",
|
|
97
|
+
content: joinTextBlocks(textParts),
|
|
98
|
+
timestamp: Date.now(),
|
|
99
|
+
...prepared.length > 0 ? {
|
|
100
|
+
media: prepared,
|
|
101
|
+
...buildMediaPathFields(prepared)
|
|
102
|
+
} : {}
|
|
103
|
+
};
|
|
104
|
+
assertTranscriptUserMessage(message);
|
|
105
|
+
return message;
|
|
106
|
+
}
|
|
107
|
+
/** Hydrate images from media store for the current LLM prompt. */
|
|
108
|
+
async function hydrateUserTurnForLlm(opts) {
|
|
109
|
+
const text = joinTextBlocks(textBlocksFromContent(readAgentMessageContent(opts.message)));
|
|
110
|
+
const media = opts.message.media ?? [];
|
|
111
|
+
const images = [];
|
|
112
|
+
if (resolveImageHandlingStrategy(opts.modelRef) === "native") for (const ref of media.filter(isImageInboundAttachment)) {
|
|
113
|
+
const loaded = await readImageBase64FromRef(ref);
|
|
114
|
+
images.push({
|
|
115
|
+
type: "image",
|
|
116
|
+
data: loaded.data,
|
|
117
|
+
mimeType: loaded.mimeType
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
return {
|
|
121
|
+
text,
|
|
122
|
+
images
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
const pendingTranscriptBySession = /* @__PURE__ */ new Map();
|
|
126
|
+
function messageTextForPendingCompare(message) {
|
|
127
|
+
return joinTextBlocks(textBlocksFromContent(readAgentMessageContent(message)));
|
|
128
|
+
}
|
|
129
|
+
function pendingMatchesMessage(pending, message) {
|
|
130
|
+
const pendingText = messageTextForPendingCompare(pending);
|
|
131
|
+
const actualText = messageTextForPendingCompare(message);
|
|
132
|
+
if (!pendingText) return true;
|
|
133
|
+
if (!actualText) return false;
|
|
134
|
+
return actualText.includes(pendingText) || pendingText.includes(actualText);
|
|
135
|
+
}
|
|
136
|
+
function setPendingTranscriptUserMessage(sessionKey, message) {
|
|
137
|
+
assertTranscriptUserMessage(message);
|
|
138
|
+
pendingTranscriptBySession.set(sessionKey, message);
|
|
139
|
+
}
|
|
140
|
+
function takePendingTranscriptUserMessage(sessionKey) {
|
|
141
|
+
const msg = pendingTranscriptBySession.get(sessionKey);
|
|
142
|
+
pendingTranscriptBySession.delete(sessionKey);
|
|
143
|
+
return msg;
|
|
144
|
+
}
|
|
145
|
+
function clearPendingTranscriptUserMessage(sessionKey, message) {
|
|
146
|
+
const existing = pendingTranscriptBySession.get(sessionKey);
|
|
147
|
+
if (!existing) return;
|
|
148
|
+
if (message && existing !== message) return;
|
|
149
|
+
pendingTranscriptBySession.delete(sessionKey);
|
|
150
|
+
}
|
|
151
|
+
function pendingTranscriptReferencesMediaUri(sessionKey, uri) {
|
|
152
|
+
return pendingTranscriptBySession.get(sessionKey)?.media?.some((ref) => ref.uri === uri.trim()) === true;
|
|
153
|
+
}
|
|
154
|
+
function transformUserMessageForPersistence(sessionKey, message) {
|
|
155
|
+
if (message.role !== "user") return message;
|
|
156
|
+
if (sessionKey) {
|
|
157
|
+
const pending = pendingTranscriptBySession.get(sessionKey);
|
|
158
|
+
if (pending && pendingMatchesMessage(pending, message)) {
|
|
159
|
+
pendingTranscriptBySession.delete(sessionKey);
|
|
160
|
+
return pending;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
assertTranscriptUserMessage(message);
|
|
164
|
+
return message;
|
|
165
|
+
}
|
|
166
|
+
//#endregion
|
|
167
|
+
export { assertTranscriptUserMessage, buildTranscriptUserMessage, clearPendingTranscriptUserMessage, hydrateUserTurnForLlm, pendingTranscriptReferencesMediaUri, setPendingTranscriptUserMessage, takePendingTranscriptUserMessage, transformUserMessageForPersistence };
|
|
168
|
+
|
|
169
|
+
//# sourceMappingURL=attachment-pipeline.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"attachment-pipeline.js","names":[],"sources":["../../../../src/agent/inbound/attachment-pipeline.ts"],"sourcesContent":["import type { AgentMessage } from '@earendil-works/pi-agent-core';\nimport type { ImageContent } from '@earendil-works/pi-ai';\n\nimport type { Config } from '../../config/schema.js';\nimport {\n isImageInboundAttachment,\n type MediaRef,\n} from '../../channels/attachments/inbound-persist.js';\nimport { readMediaReferenceBase64 } from '../../media/media-reference.js';\nimport { expandAtFileMentionsInPlainText } from '../context/expand-at-file-mentions.js';\nimport { readAgentMessageContent } from '../memory/agent-message-access.js';\nimport { resolveInboundImageContentParts } from '../image/inbound-image-handling.js';\nimport { resolveImageHandlingStrategy } from '../image/vision-detection.js';\nimport type { AgentInstanceGateway } from '../agent-instance-gateway.js';\n\nexport type TranscriptUserMessage = AgentMessage & {\n media?: MediaRef[];\n MediaPath?: string;\n MediaPaths?: string[];\n MediaTypes?: string[];\n};\n\nexport type LlmUserTurn = {\n text: string;\n images: ImageContent[];\n};\n\nconst VISION_INLINE_MAX_BYTES = 2 * 1024 * 1024;\n\nfunction textBlocksFromContent(content: unknown): string[] {\n if (typeof content === 'string') {\n return content.trim() ? [content] : [];\n }\n if (!Array.isArray(content)) {\n return [];\n }\n const out: string[] = [];\n for (const block of content) {\n if (block && typeof block === 'object' && (block as { type?: string }).type === 'text') {\n const t = (block as { text?: string }).text;\n if (typeof t === 'string' && t.trim()) {\n out.push(t);\n }\n }\n }\n return out;\n}\n\nfunction joinTextBlocks(parts: string[]): string {\n return parts.join('\\n').trim();\n}\n\nfunction buildMediaPathFields(media: MediaRef[]): Pick<TranscriptUserMessage, 'MediaPath' | 'MediaPaths' | 'MediaTypes'> {\n if (!media.length) return {};\n return {\n MediaPath: media[0]!.path,\n MediaPaths: media.map((m) => m.path),\n MediaTypes: media.map((m) => m.mimeType),\n };\n}\n\nfunction assertUserContentHasNoInlineMedia(content: unknown): void {\n if (!Array.isArray(content)) {\n return;\n }\n for (const block of content) {\n if (!block || typeof block !== 'object') {\n continue;\n }\n const type = (block as { type?: string }).type;\n if (type === 'image') {\n throw new Error('User transcript content must not contain image blocks');\n }\n }\n}\n\nexport function assertTranscriptUserMessage(message: AgentMessage): void {\n if ((message as { role?: string }).role !== 'user') {\n return;\n }\n assertUserContentHasNoInlineMedia((message as { content?: unknown }).content);\n const media = (message as TranscriptUserMessage).media;\n if (!media?.length) {\n return;\n }\n for (const ref of media) {\n if (!ref.uri?.trim()) {\n throw new Error('User transcript media ref missing uri');\n }\n if ('data' in ref && typeof (ref as { data?: unknown }).data === 'string') {\n throw new Error('User transcript media ref must not include data');\n }\n }\n}\n\nasync function readImageBase64FromRef(ref: MediaRef): Promise<{ data: string; mimeType: string }> {\n const loaded = await readMediaReferenceBase64(ref.uri, VISION_INLINE_MAX_BYTES);\n return {\n data: loaded.data,\n mimeType: ref.mimeType?.startsWith('image/') ? ref.mimeType : loaded.mimeType,\n };\n}\n\nfunction appendMediaAttachedLines(textParts: string[], media: MediaRef[]): void {\n for (const ref of media) {\n if (!isImageInboundAttachment(ref)) {\n textParts.push(\n [\n `[media attached: ${ref.name} (${ref.mimeType}, ${ref.size} bytes)]`,\n `xopc-media-uri:${ref.uri}`,\n `xopc-media-path:${ref.path}`,\n 'Use the read_media tool with the xopc-media-uri value when you need to inspect this attachment.',\n ].join('\\n'),\n );\n }\n }\n}\n\nasync function expandUserText(\n text: string,\n sessionKey: string,\n agentManager: AgentInstanceGateway,\n): Promise<string> {\n if (!text.trim()) {\n return '';\n }\n let out = text;\n if (/@file:/.test(out)) {\n const wsKey = sessionKey || 'agent:main:main';\n const root = agentManager.getResolvedWorkspaceForSession(wsKey);\n out = await expandAtFileMentionsInPlainText(out, root);\n }\n return out.trim();\n}\n\n/**\n * Build the transcript row for a user turn (text + media metadata only).\n */\nexport async function buildTranscriptUserMessage(opts: {\n text: string;\n prepared: MediaRef[] | undefined;\n sessionKey: string;\n modelRef: string;\n config: Config | undefined;\n agentManager: AgentInstanceGateway;\n}): Promise<TranscriptUserMessage> {\n const expandedText = await expandUserText(opts.text, opts.sessionKey, opts.agentManager);\n const prepared = opts.prepared ?? [];\n const imageRefs = prepared.filter(isImageInboundAttachment);\n\n const textParts: string[] = [];\n if (expandedText) {\n textParts.push(expandedText);\n }\n\n const strategy = resolveImageHandlingStrategy(opts.modelRef);\n\n if (strategy !== 'native') {\n appendMediaAttachedLines(textParts, prepared.filter((m) => !isImageInboundAttachment(m)));\n }\n\n if (imageRefs.length > 0 && strategy !== 'native') {\n const images = await Promise.all(imageRefs.map((ref) => readImageBase64FromRef(ref)));\n const parts = await resolveInboundImageContentParts({\n modelRef: opts.modelRef,\n cfg: opts.config,\n userTextForContext: expandedText,\n images,\n });\n for (const part of parts) {\n if (part.type === 'text' && part.text.trim()) {\n textParts.push(part.text.trim());\n }\n }\n }\n\n if (textParts.length === 0 && prepared.length > 0) {\n textParts.push('Please analyze the attachment(s) I sent.');\n }\n\n const content = joinTextBlocks(textParts);\n const message: TranscriptUserMessage = {\n role: 'user',\n content,\n timestamp: Date.now(),\n ...(prepared.length > 0 ? { media: prepared, ...buildMediaPathFields(prepared) } : {}),\n };\n assertTranscriptUserMessage(message);\n return message;\n}\n\n/** Hydrate images from media store for the current LLM prompt. */\nexport async function hydrateUserTurnForLlm(opts: {\n message: TranscriptUserMessage;\n modelRef: string;\n}): Promise<LlmUserTurn> {\n const text = joinTextBlocks(textBlocksFromContent(readAgentMessageContent(opts.message)));\n const media = opts.message.media ?? [];\n const images: ImageContent[] = [];\n\n if (resolveImageHandlingStrategy(opts.modelRef) === 'native') {\n for (const ref of media.filter(isImageInboundAttachment)) {\n const loaded = await readImageBase64FromRef(ref);\n images.push({ type: 'image', data: loaded.data, mimeType: loaded.mimeType });\n }\n }\n\n return { text, images };\n}\n\nconst pendingTranscriptBySession = new Map<string, TranscriptUserMessage>();\n\nfunction messageTextForPendingCompare(message: AgentMessage): string {\n return joinTextBlocks(textBlocksFromContent(readAgentMessageContent(message)));\n}\n\nfunction pendingMatchesMessage(pending: TranscriptUserMessage, message: AgentMessage): boolean {\n const pendingText = messageTextForPendingCompare(pending);\n const actualText = messageTextForPendingCompare(message);\n if (!pendingText) {\n return true;\n }\n if (!actualText) {\n return false;\n }\n return actualText.includes(pendingText) || pendingText.includes(actualText);\n}\n\nexport function setPendingTranscriptUserMessage(sessionKey: string, message: TranscriptUserMessage): void {\n assertTranscriptUserMessage(message);\n pendingTranscriptBySession.set(sessionKey, message);\n}\n\nexport function takePendingTranscriptUserMessage(sessionKey: string): TranscriptUserMessage | undefined {\n const msg = pendingTranscriptBySession.get(sessionKey);\n pendingTranscriptBySession.delete(sessionKey);\n return msg;\n}\n\nexport function clearPendingTranscriptUserMessage(sessionKey: string, message?: TranscriptUserMessage): void {\n const existing = pendingTranscriptBySession.get(sessionKey);\n if (!existing) {\n return;\n }\n if (message && existing !== message) {\n return;\n }\n pendingTranscriptBySession.delete(sessionKey);\n}\n\nexport function pendingTranscriptReferencesMediaUri(sessionKey: string, uri: string): boolean {\n const pending = pendingTranscriptBySession.get(sessionKey);\n return pending?.media?.some((ref) => ref.uri === uri.trim()) === true;\n}\n\nexport function transformUserMessageForPersistence(\n sessionKey: string | undefined,\n message: AgentMessage,\n): AgentMessage {\n if ((message as { role?: string }).role !== 'user') {\n return message;\n }\n if (sessionKey) {\n const pending = pendingTranscriptBySession.get(sessionKey);\n if (pending && pendingMatchesMessage(pending, message)) {\n pendingTranscriptBySession.delete(sessionKey);\n return pending;\n }\n }\n assertTranscriptUserMessage(message);\n return message;\n}\n"],"mappings":";;;;;;;;AA2BA,MAAM,0BAA0B,IAAI,OAAO;AAE3C,SAAS,sBAAsB,SAA4B;AACzD,KAAI,OAAO,YAAY,SACrB,QAAO,QAAQ,MAAM,GAAG,CAAC,QAAQ,GAAG,EAAE;AAExC,KAAI,CAAC,MAAM,QAAQ,QAAQ,CACzB,QAAO,EAAE;CAEX,MAAM,MAAgB,EAAE;AACxB,MAAK,MAAM,SAAS,QAClB,KAAI,SAAS,OAAO,UAAU,YAAa,MAA4B,SAAS,QAAQ;EACtF,MAAM,IAAK,MAA4B;AACvC,MAAI,OAAO,MAAM,YAAY,EAAE,MAAM,CACnC,KAAI,KAAK,EAAE;;AAIjB,QAAO;;AAGT,SAAS,eAAe,OAAyB;AAC/C,QAAO,MAAM,KAAK,KAAK,CAAC,MAAM;;AAGhC,SAAS,qBAAqB,OAA2F;AACvH,KAAI,CAAC,MAAM,OAAQ,QAAO,EAAE;AAC5B,QAAO;EACL,WAAW,MAAM,GAAI;EACrB,YAAY,MAAM,KAAK,MAAM,EAAE,KAAK;EACpC,YAAY,MAAM,KAAK,MAAM,EAAE,SAAS;EACzC;;AAGH,SAAS,kCAAkC,SAAwB;AACjE,KAAI,CAAC,MAAM,QAAQ,QAAQ,CACzB;AAEF,MAAK,MAAM,SAAS,SAAS;AAC3B,MAAI,CAAC,SAAS,OAAO,UAAU,SAC7B;AAGF,MADc,MAA4B,SAC7B,QACX,OAAM,IAAI,MAAM,wDAAwD;;;AAK9E,SAAgB,4BAA4B,SAA6B;AACvE,KAAK,QAA8B,SAAS,OAC1C;AAEF,mCAAmC,QAAkC,QAAQ;CAC7E,MAAM,QAAS,QAAkC;AACjD,KAAI,CAAC,OAAO,OACV;AAEF,MAAK,MAAM,OAAO,OAAO;AACvB,MAAI,CAAC,IAAI,KAAK,MAAM,CAClB,OAAM,IAAI,MAAM,wCAAwC;A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IAAI,YAAY,SAAS,WAAW;;AAG7E,SAAgB,gCAAgC,YAAoB,SAAsC;AACxG,6BAA4B,QAAQ;AACpC,4BAA2B,IAAI,YAAY,QAAQ;;AAGrD,SAAgB,iCAAiC,YAAuD;CACtG,MAAM,MAAM,2BAA2B,IAAI,WAAW;AACtD,4BAA2B,OAAO,WAAW;AAC7C,QAAO;;AAGT,SAAgB,kCAAkC,YAAoB,SAAuC;CAC3G,MAAM,WAAW,2BAA2B,IAAI,WAAW;AAC3D,KAAI,CAAC,SACH;AAEF,KAAI,WAAW,aAAa,QAC1B;AAEF,4BAA2B,OAAO,WAAW;;AAG/C,SAAgB,oCAAoC,YAAoB,KAAsB;AAE5F,QADgB,2BAA2B,IAAI,WACjC,EAAE,OAAO,MAAM,QAAQ,IAAI,QAAQ,IAAI,MAAM,CAAC,KAAK;;AAGnE,SAAgB,mCACd,YACA,SACc;AACd,KAAK,QAA8B,SAAS,OAC1C,QAAO;AAET,KAAI,YAAY;EACd,MAAM,UAAU,2BAA2B,IAAI,WAAW;AAC1D,MAAI,WAAW,sBAAsB,SAAS,QAAQ,EAAE;AACtD,8BAA2B,OAAO,WAAW;AAC7C,UAAO;;;AAGX,6BAA4B,QAAQ;AACpC,QAAO"}
|
|
@@ -22,8 +22,7 @@ import type { ModelManager } from '../models/index.js';
|
|
|
22
22
|
import type { SessionConfigStore } from '../../session/index.js';
|
|
23
23
|
import type { SessionStore } from '../../session/store.js';
|
|
24
24
|
import type { SessionContext, SessionHydrator, SessionStateBag } from '../session/index.js';
|
|
25
|
-
import type {
|
|
26
|
-
import { type DirectInboundAttachment } from '../service/build-direct-message-content.js';
|
|
25
|
+
import type { InboundAttachmentInput, MediaRef } from '../../channels/attachments/inbound-persist.js';
|
|
27
26
|
import { type ProcessDirectStreamingSseEvent } from '../service/process-direct-streaming.js';
|
|
28
27
|
export interface TurnDispatcherConfig {
|
|
29
28
|
log: ContextualLogger;
|
|
@@ -44,8 +43,7 @@ export interface TurnDispatcherConfig {
|
|
|
44
43
|
initSessionContext: (sessionKey: string, channel: string, chatId: string) => SessionContext;
|
|
45
44
|
/** Per-session config hydration: workspace, model, thinking. */
|
|
46
45
|
sessionHydrator: SessionHydrator;
|
|
47
|
-
|
|
48
|
-
prepareInboundAttachments: (sessionKey: string, attachments?: DirectInboundAttachment[]) => Promise<DirectInboundAttachment[] | undefined>;
|
|
46
|
+
prepareInboundAttachments: (sessionKey: string, attachments?: InboundAttachmentInput[]) => Promise<MediaRef[] | undefined>;
|
|
49
47
|
enqueueMaybeAutoTitleAfterPersist: (sessionKey: string) => void;
|
|
50
48
|
enqueueProvisionalSessionTitle?: (sessionKey: string, userText: string) => void;
|
|
51
49
|
endDirectRequestContext: () => void;
|
|
@@ -56,7 +54,7 @@ export interface TurnDispatcherConfig {
|
|
|
56
54
|
previousSessionId: string;
|
|
57
55
|
} | null>;
|
|
58
56
|
}
|
|
59
|
-
export type DirectAttachment =
|
|
57
|
+
export type DirectAttachment = InboundAttachmentInput;
|
|
60
58
|
export declare class TurnDispatcher {
|
|
61
59
|
private readonly cfg;
|
|
62
60
|
private readonly log;
|
|
@@ -78,10 +78,9 @@ var TurnDispatcher = class {
|
|
|
78
78
|
applyResolvedThinkingLevel: (sk, t) => c.sessionHydrator.thinking(sk, t),
|
|
79
79
|
getConfig: c.getConfig,
|
|
80
80
|
sessionConfigStore: c.sessionConfigStore,
|
|
81
|
-
attachmentRootsForSession: c.attachmentRootsForSession,
|
|
82
81
|
commandHandler: c.commandHandler,
|
|
83
82
|
prepareInboundAttachments: c.prepareInboundAttachments,
|
|
84
|
-
|
|
83
|
+
buildTranscriptUserMessage: async (text, prepared, sk) => buildDirectUserMessageContent({
|
|
85
84
|
content: text,
|
|
86
85
|
attachments: prepared,
|
|
87
86
|
sessionKey: sk,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"turn-dispatcher.js","names":[],"sources":["../../../../src/agent/inbound/turn-dispatcher.ts"],"sourcesContent":["/**\n * TurnDispatcher — single entry point for direct (non-bus) agent turns.\n *\n * Wraps the two existing direct-turn runners (one-shot and streaming) so the\n * parent `AgentService` no longer carries a pair of huge `createXxxDeps()`\n * factories. The public surface — `processDirect`, `processDirectStreaming`,\n * `steerWebchatSession`, `enqueueWebchatSseEvent`,\n * `notifyWebchatTranscriptAppend` — matches what `AgentService` exposed\n * previously, so callers (gateway, CLI) are unchanged.\n *\n * Like `OutboundCoordinator` and `InboundLoop`, this class accepts a wide\n * dependency bag in its constructor (the direct-turn pipeline touches almost\n * every other subsystem). The win is that AgentService becomes the only place\n * that wires those dependencies together; individual responsibilities now live\n * in their own classes and are unit-testable.\n */\n\nimport type { Config } from '../../config/schema.js';\nimport type { ContextualLogger } from '../../utils/logger/types.js';\n\nimport type { AgentManager } from '../agent-manager.js';\nimport type { CommandHandler } from '../messaging/command-handler.js';\nimport type { ModelManager } from '../models/index.js';\nimport type { SessionConfigStore } from '../../session/index.js';\nimport type { SessionStore } from '../../session/store.js';\nimport type {\n SessionContext,\n SessionHydrator,\n SessionStateBag,\n} from '../session/index.js';\nimport { queueEmbeddedSteer } from '../embedded/runs.js';\nimport type { InternalAttachmentRoots } from '../../channels/attachments/inbound-persist.js';\nimport {\n buildDirectUserMessageContent,\n type DirectInboundAttachment,\n} from '../service/build-direct-message-content.js';\nimport {\n runProcessDirectStreaming,\n type ProcessDirectStreamingDeps,\n type ProcessDirectStreamingSseEvent,\n} from '../service/process-direct-streaming.js';\nimport {\n runProcessDirect,\n type RunProcessDirectDeps,\n} from '../service/process-direct-one-shot.js';\nimport { maybeEmitWebchatTts } from '../service/webchat-tts.js';\n\nexport interface TurnDispatcherConfig {\n log: ContextualLogger;\n agentManager: AgentManager;\n sessionStore: SessionStore;\n modelManager: ModelManager;\n sessionConfigStore: SessionConfigStore;\n sessionState: SessionStateBag;\n commandHandler: CommandHandler;\n getConfig: () => Config | undefined;\n /** Strict accessor — required for direct-turn paths that must have a config. */\n requireConfig: () => Config;\n parseSessionKey: (sessionKey: string) => { channel: string; chatId: string };\n /** Establish per-session context (also creates the Agent + subscribes to events). */\n initSessionContext: (sessionKey: string, channel: string, chatId: string) => SessionContext;\n /** Per-session config hydration: workspace, model, thinking. */\n sessionHydrator: SessionHydrator;\n attachmentRootsForSession: (sessionKey: string) => InternalAttachmentRoots;\n prepareInboundAttachments: (\n sessionKey: string,\n attachments?: DirectInboundAttachment[],\n ) => Promise<DirectInboundAttachment[] | undefined>;\n enqueueMaybeAutoTitleAfterPersist: (sessionKey: string) => void;\n enqueueProvisionalSessionTitle?: (sessionKey: string, userText: string) => void;\n endDirectRequestContext: () => void;\n /** Gateway hook fired after assistant text lands on disk (UI refetch). */\n onSessionTranscriptUpdated?: (sessionKey: string) => void;\n resetSession: (sessionKey: string) => Promise<{ sessionId: string; previousSessionId: string } | null>;\n}\n\nexport type DirectAttachment = DirectInboundAttachment;\n\nexport class TurnDispatcher {\n private readonly cfg: TurnDispatcherConfig;\n private readonly log: ContextualLogger;\n\n constructor(cfg: TurnDispatcherConfig) {\n this.cfg = cfg;\n this.log = cfg.log;\n }\n\n /** One-shot direct turn (CLI / embedded TUI). */\n processDirect(\n content: string,\n sessionKey = 'agent:main:main',\n attachments?: DirectAttachment[],\n thinking?: string,\n ): Promise<string> {\n return runProcessDirect(this.buildOneShotDeps(), {\n content,\n sessionKey,\n attachments,\n thinking,\n });\n }\n\n /** Streaming direct turn (webchat SSE / CLI streaming). */\n async *processDirectStreaming(\n content: string,\n sessionKey = 'agent:main:main',\n attachments?: DirectAttachment[],\n thinking?: string,\n options?: { signal?: AbortSignal },\n ): AsyncGenerator<ProcessDirectStreamingSseEvent, void, unknown> {\n yield* runProcessDirectStreaming(this.buildStreamingDeps(), {\n content,\n sessionKey,\n attachments,\n thinking,\n signal: options?.signal,\n });\n }\n\n /** Push an out-of-band event into the live webchat stream for a session. */\n enqueueWebchatSseEvent(\n sessionKey: string,\n event: { type: string; [key: string]: unknown },\n ): void {\n const pub = this.cfg.sessionState.getWebchatPublisher(sessionKey);\n if (pub) {\n pub(event);\n }\n }\n\n /** Stream assistant text to live webchat session + notify transcript listeners. */\n notifyWebchatTranscriptAppend(sessionKey: string, assistantText: string): void {\n const trimmed = assistantText.trim();\n if (trimmed) {\n this.enqueueWebchatSseEvent(sessionKey, { type: 'token', content: trimmed });\n }\n this.cfg.onSessionTranscriptUpdated?.(sessionKey);\n }\n\n /**\n * Queue a steering user message into pi-agent's in-flight run (delivered\n * after current tool work, before the next LLM call). See `Agent.steer`\n * in `@earendil-works/pi-agent-core`.\n */\n async steerWebchatSession(sessionKey: string, text: string): Promise<boolean> {\n const trimmed = text.trim();\n if (!trimmed) return false;\n try {\n return await queueEmbeddedSteer(sessionKey, trimmed);\n } catch (err) {\n this.log.warn({ err, sessionKey }, 'steerWebchatSession failed');\n return false;\n }\n }\n\n private buildStreamingDeps(): ProcessDirectStreamingDeps {\n const c = this.cfg;\n return {\n log: this.log,\n parseSessionKey: c.parseSessionKey,\n initDirectStreamingSession: c.initSessionContext,\n registerWebchatSsePublisher: (sk, publisher) =>\n c.sessionState.registerWebchatPublisher(sk, publisher),\n unregisterWebchatSsePublisher: (sk) => c.sessionState.unregisterWebchatPublisher(sk),\n agentManager: c.agentManager,\n hydrateSessionWorkspaceFromStore: (sk) => c.sessionHydrator.workspace(sk),\n hydrateSessionModelFromStore: (sk) => c.sessionHydrator.model(sk),\n sessionStore: c.sessionStore,\n modelManager: c.modelManager,\n applyResolvedThinkingLevel: (sk, t) => c.sessionHydrator.thinking(sk, t),\n getConfig: c.getConfig,\n sessionConfigStore: c.sessionConfigStore,\n attachmentRootsForSession: c.attachmentRootsForSession,\n commandHandler: c.commandHandler,\n prepareInboundAttachments: c.prepareInboundAttachments,\n buildMessageContent: (text, prepared, sk) =>\n buildDirectUserMessageContent({\n content: text,\n attachments: prepared,\n sessionKey: sk,\n config: c.requireConfig(),\n agentManager: c.agentManager,\n modelManager: c.modelManager,\n }),\n recordPersistentGoalStreamOutcome: (sk, o) =>\n c.sessionState.recordPersistentGoalStreamOutcome(sk, o),\n enqueueProvisionalSessionTitle: (sk, userText) => {\n c.enqueueProvisionalSessionTitle?.(sk, userText);\n },\n onTurnComplete: (sk, text) => {\n if (text) {\n c.sessionState.setLastAssistantText(sk, text);\n }\n c.enqueueMaybeAutoTitleAfterPersist(sk);\n },\n reloadWebchatTranscript: (sk) => {\n c.onSessionTranscriptUpdated?.(sk);\n },\n maybeEmitWebchatTts: (sk, hadVoice) =>\n maybeEmitWebchatTts(\n {\n config: c.getConfig(),\n sessionStore: c.sessionStore,\n getLastAssistantPlainText: (sessionKey) =>\n c.sessionState.getLastAssistantText(sessionKey) ??\n c.agentManager.getLastAssistantContent(sessionKey) ??\n '',\n log: this.log,\n },\n sk,\n hadVoice,\n ),\n endDirectRequestContext: c.endDirectRequestContext,\n resetSession: c.resetSession,\n };\n }\n\n private buildOneShotDeps(): RunProcessDirectDeps {\n const c = this.cfg;\n const cfg = c.requireConfig();\n return {\n log: this.log,\n config: cfg,\n parseSessionKey: c.parseSessionKey,\n initSessionContext: (sk, channel, chatId) => {\n void c.initSessionContext(sk, channel, chatId);\n },\n hydrateSessionWorkspaceFromStore: (sk) => c.sessionHydrator.workspace(sk),\n hydrateSessionModelFromStore: (sk) => c.sessionHydrator.model(sk),\n agentManager: c.agentManager,\n sessionStore: c.sessionStore,\n modelManager: c.modelManager,\n applyResolvedThinkingLevel: (sk, t) => c.sessionHydrator.thinking(sk, t),\n prepareInboundAttachments: c.prepareInboundAttachments,\n commandHandler: c.commandHandler,\n onTurnComplete: (sk, text) => {\n if (text) {\n c.sessionState.setLastAssistantText(sk, text);\n }\n c.enqueueMaybeAutoTitleAfterPersist(sk);\n },\n endDirectRequestContext: c.endDirectRequestContext,\n resetSession: c.resetSession,\n };\n }\n}\n"],"mappings":";;;;;;AA8EA,IAAa,iBAAb,MAA4B;CAC1B;CACA;CAEA,YAAY,KAA2B;AACrC,OAAK,MAAM;AACX,OAAK,MAAM,IAAI;;;CAIjB,cACE,SACA,aAAa,mBACb,a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K;AAE/C,MAAE,kCAAkC,GAAG;;GAEzC,yBAAyB,EAAE;GAC3B,cAAc,EAAE;GACjB"}
|
|
1
|
+
{"version":3,"file":"turn-dispatcher.js","names":[],"sources":["../../../../src/agent/inbound/turn-dispatcher.ts"],"sourcesContent":["/**\n * TurnDispatcher — single entry point for direct (non-bus) agent turns.\n *\n * Wraps the two existing direct-turn runners (one-shot and streaming) so the\n * parent `AgentService` no longer carries a pair of huge `createXxxDeps()`\n * factories. The public surface — `processDirect`, `processDirectStreaming`,\n * `steerWebchatSession`, `enqueueWebchatSseEvent`,\n * `notifyWebchatTranscriptAppend` — matches what `AgentService` exposed\n * previously, so callers (gateway, CLI) are unchanged.\n *\n * Like `OutboundCoordinator` and `InboundLoop`, this class accepts a wide\n * dependency bag in its constructor (the direct-turn pipeline touches almost\n * every other subsystem). The win is that AgentService becomes the only place\n * that wires those dependencies together; individual responsibilities now live\n * in their own classes and are unit-testable.\n */\n\nimport type { Config } from '../../config/schema.js';\nimport type { ContextualLogger } from '../../utils/logger/types.js';\n\nimport type { AgentManager } from '../agent-manager.js';\nimport type { CommandHandler } from '../messaging/command-handler.js';\nimport type { ModelManager } from '../models/index.js';\nimport type { SessionConfigStore } from '../../session/index.js';\nimport type { SessionStore } from '../../session/store.js';\nimport type {\n SessionContext,\n SessionHydrator,\n SessionStateBag,\n} from '../session/index.js';\nimport { queueEmbeddedSteer } from '../embedded/runs.js';\nimport type {\n InboundAttachmentInput,\n MediaRef,\n} from '../../channels/attachments/inbound-persist.js';\nimport {\n buildDirectUserMessageContent,\n} from '../service/build-direct-message-content.js';\nimport {\n runProcessDirectStreaming,\n type ProcessDirectStreamingDeps,\n type ProcessDirectStreamingSseEvent,\n} from '../service/process-direct-streaming.js';\nimport {\n runProcessDirect,\n type RunProcessDirectDeps,\n} from '../service/process-direct-one-shot.js';\nimport { maybeEmitWebchatTts } from '../service/webchat-tts.js';\n\nexport interface TurnDispatcherConfig {\n log: ContextualLogger;\n agentManager: AgentManager;\n sessionStore: SessionStore;\n modelManager: ModelManager;\n sessionConfigStore: SessionConfigStore;\n sessionState: SessionStateBag;\n commandHandler: CommandHandler;\n getConfig: () => Config | undefined;\n /** Strict accessor — required for direct-turn paths that must have a config. */\n requireConfig: () => Config;\n parseSessionKey: (sessionKey: string) => { channel: string; chatId: string };\n /** Establish per-session context (also creates the Agent + subscribes to events). */\n initSessionContext: (sessionKey: string, channel: string, chatId: string) => SessionContext;\n /** Per-session config hydration: workspace, model, thinking. */\n sessionHydrator: SessionHydrator;\n prepareInboundAttachments: (\n sessionKey: string,\n attachments?: InboundAttachmentInput[],\n ) => Promise<MediaRef[] | undefined>;\n enqueueMaybeAutoTitleAfterPersist: (sessionKey: string) => void;\n enqueueProvisionalSessionTitle?: (sessionKey: string, userText: string) => void;\n endDirectRequestContext: () => void;\n /** Gateway hook fired after assistant text lands on disk (UI refetch). */\n onSessionTranscriptUpdated?: (sessionKey: string) => void;\n resetSession: (sessionKey: string) => Promise<{ sessionId: string; previousSessionId: string } | null>;\n}\n\nexport type DirectAttachment = InboundAttachmentInput;\n\nexport class TurnDispatcher {\n private readonly cfg: TurnDispatcherConfig;\n private readonly log: ContextualLogger;\n\n constructor(cfg: TurnDispatcherConfig) {\n this.cfg = cfg;\n this.log = cfg.log;\n }\n\n /** One-shot direct turn (CLI / embedded TUI). */\n processDirect(\n content: string,\n sessionKey = 'agent:main:main',\n attachments?: DirectAttachment[],\n thinking?: string,\n ): Promise<string> {\n return runProcessDirect(this.buildOneShotDeps(), {\n content,\n sessionKey,\n attachments,\n thinking,\n });\n }\n\n /** Streaming direct turn (webchat SSE / CLI streaming). */\n async *processDirectStreaming(\n content: string,\n sessionKey = 'agent:main:main',\n attachments?: DirectAttachment[],\n thinking?: string,\n options?: { signal?: AbortSignal },\n ): AsyncGenerator<ProcessDirectStreamingSseEvent, void, unknown> {\n yield* runProcessDirectStreaming(this.buildStreamingDeps(), {\n content,\n sessionKey,\n attachments,\n thinking,\n signal: options?.signal,\n });\n }\n\n /** Push an out-of-band event into the live webchat stream for a session. */\n enqueueWebchatSseEvent(\n sessionKey: string,\n event: { type: string; [key: string]: unknown },\n ): void {\n const pub = this.cfg.sessionState.getWebchatPublisher(sessionKey);\n if (pub) {\n pub(event);\n }\n }\n\n /** Stream assistant text to live webchat session + notify transcript listeners. */\n notifyWebchatTranscriptAppend(sessionKey: string, assistantText: string): void {\n const trimmed = assistantText.trim();\n if (trimmed) {\n this.enqueueWebchatSseEvent(sessionKey, { type: 'token', content: trimmed });\n }\n this.cfg.onSessionTranscriptUpdated?.(sessionKey);\n }\n\n /**\n * Queue a steering user message into pi-agent's in-flight run (delivered\n * after current tool work, before the next LLM call). See `Agent.steer`\n * in `@earendil-works/pi-agent-core`.\n */\n async steerWebchatSession(sessionKey: string, text: string): Promise<boolean> {\n const trimmed = text.trim();\n if (!trimmed) return false;\n try {\n return await queueEmbeddedSteer(sessionKey, trimmed);\n } catch (err) {\n this.log.warn({ err, sessionKey }, 'steerWebchatSession failed');\n return false;\n }\n }\n\n private buildStreamingDeps(): ProcessDirectStreamingDeps {\n const c = this.cfg;\n return {\n log: this.log,\n parseSessionKey: c.parseSessionKey,\n initDirectStreamingSession: c.initSessionContext,\n registerWebchatSsePublisher: (sk, publisher) =>\n c.sessionState.registerWebchatPublisher(sk, publisher),\n unregisterWebchatSsePublisher: (sk) => c.sessionState.unregisterWebchatPublisher(sk),\n agentManager: c.agentManager,\n hydrateSessionWorkspaceFromStore: (sk) => c.sessionHydrator.workspace(sk),\n hydrateSessionModelFromStore: (sk) => c.sessionHydrator.model(sk),\n sessionStore: c.sessionStore,\n modelManager: c.modelManager,\n applyResolvedThinkingLevel: (sk, t) => c.sessionHydrator.thinking(sk, t),\n getConfig: c.getConfig,\n sessionConfigStore: c.sessionConfigStore,\n commandHandler: c.commandHandler,\n prepareInboundAttachments: c.prepareInboundAttachments,\n buildTranscriptUserMessage: async (text, prepared, sk) =>\n buildDirectUserMessageContent({\n content: text,\n attachments: prepared,\n sessionKey: sk,\n config: c.requireConfig(),\n agentManager: c.agentManager,\n modelManager: c.modelManager,\n }),\n recordPersistentGoalStreamOutcome: (sk, o) =>\n c.sessionState.recordPersistentGoalStreamOutcome(sk, o),\n enqueueProvisionalSessionTitle: (sk, userText) => {\n c.enqueueProvisionalSessionTitle?.(sk, userText);\n },\n onTurnComplete: (sk, text) => {\n if (text) {\n c.sessionState.setLastAssistantText(sk, text);\n }\n c.enqueueMaybeAutoTitleAfterPersist(sk);\n },\n reloadWebchatTranscript: (sk) => {\n c.onSessionTranscriptUpdated?.(sk);\n },\n maybeEmitWebchatTts: (sk, hadVoice) =>\n maybeEmitWebchatTts(\n {\n config: c.getConfig(),\n sessionStore: c.sessionStore,\n getLastAssistantPlainText: (sessionKey) =>\n c.sessionState.getLastAssistantText(sessionKey) ??\n c.agentManager.getLastAssistantContent(sessionKey) ??\n '',\n log: this.log,\n },\n sk,\n hadVoice,\n ),\n endDirectRequestContext: c.endDirectRequestContext,\n resetSession: c.resetSession,\n };\n }\n\n private buildOneShotDeps(): RunProcessDirectDeps {\n const c = this.cfg;\n const cfg = c.requireConfig();\n return {\n log: this.log,\n config: cfg,\n parseSessionKey: c.parseSessionKey,\n initSessionContext: (sk, channel, chatId) => {\n void c.initSessionContext(sk, channel, chatId);\n },\n hydrateSessionWorkspaceFromStore: (sk) => c.sessionHydrator.workspace(sk),\n hydrateSessionModelFromStore: (sk) => c.sessionHydrator.model(sk),\n agentManager: c.agentManager,\n sessionStore: c.sessionStore,\n modelManager: c.modelManager,\n applyResolvedThinkingLevel: (sk, t) => c.sessionHydrator.thinking(sk, t),\n prepareInboundAttachments: c.prepareInboundAttachments,\n commandHandler: c.commandHandler,\n onTurnComplete: (sk, text) => {\n if (text) {\n c.sessionState.setLastAssistantText(sk, text);\n }\n c.enqueueMaybeAutoTitleAfterPersist(sk);\n },\n endDirectRequestContext: c.endDirectRequestContext,\n resetSession: c.resetSession,\n };\n }\n}\n"],"mappings":";;;;;;AA+EA,IAAa,iBAAb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;GAC7B,gBAAgB,EAAE;GAClB,iBAAiB,IAAI,SAAS;AAC5B,QAAI,KACF,GAAE,aAAa,qBAAqB,IAAI,KAAK;AAE/C,MAAE,kCAAkC,GAAG;;GAEzC,yBAAyB,EAAE;GAC3B,cAAc,EAAE;GACjB"}
|
|
@@ -11,3 +11,5 @@ export type { MemoryProvider, MemoryProviderInitOptions } from './provider.js';
|
|
|
11
11
|
export { StubMemoryProvider } from './stub-memory-provider.js';
|
|
12
12
|
export type { MemorySnapshot, MemoryStoreConfig } from './types.js';
|
|
13
13
|
export { extractAgentUserPlainText } from './user-message-text.js';
|
|
14
|
+
export { MemoryFlushService } from './memory-flush.js';
|
|
15
|
+
export type { MemoryFlushConfig, MemoryFlushOptions, MemoryFlushResult } from './memory-flush.js';
|
|
@@ -7,5 +7,6 @@ import { BuiltinMemoryProvider } from "./builtin-provider.js";
|
|
|
7
7
|
import { MemoryManager } from "./manager.js";
|
|
8
8
|
import { StubMemoryProvider } from "./stub-memory-provider.js";
|
|
9
9
|
import { createMemoryManagerFromConfig } from "./create-memory-manager.js";
|
|
10
|
+
import { MemoryFlushService } from "./memory-flush.js";
|
|
10
11
|
import { discoverMemoryPlugins } from "./plugin-discovery.js";
|
|
11
|
-
export { BuiltinMemoryProvider, BuiltinMemoryStore, MEMORY_ENTRY_DELIMITER, MemoryManager, StubMemoryProvider, buildMemoryContextBlock, createMemoryManagerFromConfig, discoverMemoryPlugins, extractAgentUserPlainText, injectPrefetchIntoUserMessage, isCuratedMemoryInPrompt, isMemorySubsystemEnabled, resolveBuiltinMemoryStoreConfig, sanitizeMemoryContextFenceEscapes, scanForThreats, shouldInjectMemoryPrefetchThisTurn, shouldRegisterCuratedMemoryTool };
|
|
12
|
+
export { BuiltinMemoryProvider, BuiltinMemoryStore, MEMORY_ENTRY_DELIMITER, MemoryFlushService, MemoryManager, StubMemoryProvider, buildMemoryContextBlock, createMemoryManagerFromConfig, discoverMemoryPlugins, extractAgentUserPlainText, injectPrefetchIntoUserMessage, isCuratedMemoryInPrompt, isMemorySubsystemEnabled, resolveBuiltinMemoryStoreConfig, sanitizeMemoryContextFenceEscapes, scanForThreats, shouldInjectMemoryPrefetchThisTurn, shouldRegisterCuratedMemoryTool };
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { CompactionResult } from './compaction.js';
|
|
2
|
+
export interface MemoryFlushConfig {
|
|
3
|
+
enabled: boolean;
|
|
4
|
+
threshold: number;
|
|
5
|
+
softThresholdTokens: number;
|
|
6
|
+
afterCompactions: number;
|
|
7
|
+
maxEntryChars: number;
|
|
8
|
+
includeToolHistory: boolean;
|
|
9
|
+
}
|
|
10
|
+
export interface MemoryFlushOptions {
|
|
11
|
+
workspaceDir: string;
|
|
12
|
+
sessionKey: string;
|
|
13
|
+
compactionResult: CompactionResult;
|
|
14
|
+
config: MemoryFlushConfig;
|
|
15
|
+
}
|
|
16
|
+
export interface MemoryFlushResult {
|
|
17
|
+
flushed: boolean;
|
|
18
|
+
entryPath: string;
|
|
19
|
+
entryLength: number;
|
|
20
|
+
reason?: string;
|
|
21
|
+
}
|
|
22
|
+
export declare class MemoryFlushService {
|
|
23
|
+
flush(options: MemoryFlushOptions): Promise<MemoryFlushResult>;
|
|
24
|
+
private buildEntry;
|
|
25
|
+
/** YYYY-MM-DD in local time (for daily `memory/YYYY-MM-DD.md` names). */
|
|
26
|
+
private isoDay;
|
|
27
|
+
}
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { createLogger } from "../../utils/logger/index.js";
|
|
2
|
+
import { init_logger } from "../../utils/logger.js";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { existsSync } from "node:fs";
|
|
5
|
+
import { appendFile, mkdir, readFile, writeFile } from "node:fs/promises";
|
|
6
|
+
//#region src/agent/memory/memory-flush.ts
|
|
7
|
+
init_logger();
|
|
8
|
+
const log = createLogger("MemoryFlush");
|
|
9
|
+
var MemoryFlushService = class {
|
|
10
|
+
async flush(options) {
|
|
11
|
+
const { workspaceDir, sessionKey, compactionResult, config } = options;
|
|
12
|
+
if (!config.enabled) return {
|
|
13
|
+
flushed: false,
|
|
14
|
+
entryPath: "",
|
|
15
|
+
entryLength: 0,
|
|
16
|
+
reason: "disabled"
|
|
17
|
+
};
|
|
18
|
+
const now = /* @__PURE__ */ new Date();
|
|
19
|
+
const day = this.isoDay(now);
|
|
20
|
+
const memoryDir = join(workspaceDir, "memory");
|
|
21
|
+
const filePath = join(memoryDir, `${day}.md`);
|
|
22
|
+
const entryPath = `memory/${day}.md`;
|
|
23
|
+
await mkdir(memoryDir, { recursive: true });
|
|
24
|
+
const entryText = this.buildEntry(sessionKey, compactionResult, now, config).text;
|
|
25
|
+
const entryLength = entryText.length;
|
|
26
|
+
if (entryLength > config.maxEntryChars) log.warn({
|
|
27
|
+
sessionKey,
|
|
28
|
+
entryLength,
|
|
29
|
+
maxEntryChars: config.maxEntryChars
|
|
30
|
+
}, "Flush entry exceeds maxEntryChars; truncating");
|
|
31
|
+
try {
|
|
32
|
+
if (!existsSync(filePath)) await writeFile(filePath, `# Daily Notes — ${day}\n\n` + entryText, "utf-8");
|
|
33
|
+
else {
|
|
34
|
+
const existing = await readFile(filePath, "utf-8");
|
|
35
|
+
if (existing.length > 5e4) log.warn({
|
|
36
|
+
sessionKey,
|
|
37
|
+
filePath,
|
|
38
|
+
size: existing.length
|
|
39
|
+
}, "Daily notes file is large; continuing append");
|
|
40
|
+
await appendFile(filePath, "\n" + entryText, "utf-8");
|
|
41
|
+
}
|
|
42
|
+
log.info({
|
|
43
|
+
sessionKey,
|
|
44
|
+
entryPath,
|
|
45
|
+
entryLength
|
|
46
|
+
}, "Memory flushed to daily notes");
|
|
47
|
+
return {
|
|
48
|
+
flushed: true,
|
|
49
|
+
entryPath,
|
|
50
|
+
entryLength
|
|
51
|
+
};
|
|
52
|
+
} catch (err) {
|
|
53
|
+
const em = err instanceof Error ? err.message : String(err);
|
|
54
|
+
log.error({
|
|
55
|
+
sessionKey,
|
|
56
|
+
err,
|
|
57
|
+
filePath
|
|
58
|
+
}, `Memory flush failed: ${em}`);
|
|
59
|
+
return {
|
|
60
|
+
flushed: false,
|
|
61
|
+
entryPath,
|
|
62
|
+
entryLength: 0,
|
|
63
|
+
reason: `write_error: ${em}`
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
buildEntry(sessionKey, result, now, config) {
|
|
68
|
+
const iso = now.toISOString();
|
|
69
|
+
const lines = [];
|
|
70
|
+
lines.push(`## Session Flush [${sessionKey}] ${iso}`);
|
|
71
|
+
lines.push("");
|
|
72
|
+
const summary = result.summary || "";
|
|
73
|
+
lines.push(`**Summary:** ${summary}`);
|
|
74
|
+
lines.push("");
|
|
75
|
+
const structured = result.structuredSummary;
|
|
76
|
+
if (structured) {
|
|
77
|
+
if (structured.userRequests && structured.userRequests.length > 0) {
|
|
78
|
+
lines.push("**User Requests:**");
|
|
79
|
+
for (const req of structured.userRequests) lines.push(`- ${req}`);
|
|
80
|
+
lines.push("");
|
|
81
|
+
}
|
|
82
|
+
if (structured.keyDecisions && structured.keyDecisions.length > 0) {
|
|
83
|
+
lines.push("**Key Decisions:**");
|
|
84
|
+
for (const decision of structured.keyDecisions) lines.push(`- ${decision}`);
|
|
85
|
+
lines.push("");
|
|
86
|
+
}
|
|
87
|
+
if (structured.filesModified && structured.filesModified.length > 0) {
|
|
88
|
+
lines.push("**Files Modified:**");
|
|
89
|
+
for (const file of structured.filesModified) lines.push(`- ${file}`);
|
|
90
|
+
lines.push("");
|
|
91
|
+
}
|
|
92
|
+
if (config.includeToolHistory && structured.toolCalls && structured.toolCalls.length > 0) {
|
|
93
|
+
lines.push("**Tool Calls:**");
|
|
94
|
+
for (const call of structured.toolCalls) {
|
|
95
|
+
const filePart = call.filePath ? ` (${call.filePath})` : "";
|
|
96
|
+
const status = call.success ? "success" : "failed";
|
|
97
|
+
lines.push(`- \`${call.toolName}\`${filePart} — ${status}`);
|
|
98
|
+
}
|
|
99
|
+
lines.push("");
|
|
100
|
+
}
|
|
101
|
+
} else if (summary) {
|
|
102
|
+
lines.push("**Summary (text only):**");
|
|
103
|
+
lines.push(summary);
|
|
104
|
+
lines.push("");
|
|
105
|
+
}
|
|
106
|
+
lines.push("---");
|
|
107
|
+
let text = lines.join("\n");
|
|
108
|
+
if (text.length > config.maxEntryChars) {
|
|
109
|
+
const headerEnd = text.indexOf("\n\n") + 2;
|
|
110
|
+
const header = text.slice(0, headerEnd);
|
|
111
|
+
const remainingBudget = config.maxEntryChars - header.length - 60;
|
|
112
|
+
text = header + text.slice(headerEnd).slice(0, Math.max(0, remainingBudget)) + "\n\n*(Entry truncated due to length limit)*\n---";
|
|
113
|
+
}
|
|
114
|
+
return { text };
|
|
115
|
+
}
|
|
116
|
+
/** YYYY-MM-DD in local time (for daily `memory/YYYY-MM-DD.md` names). */
|
|
117
|
+
isoDay(d) {
|
|
118
|
+
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
//#endregion
|
|
122
|
+
export { MemoryFlushService };
|
|
123
|
+
|
|
124
|
+
//# sourceMappingURL=memory-flush.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"memory-flush.js","names":[],"sources":["../../../../src/agent/memory/memory-flush.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { mkdir, readFile, writeFile, appendFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { createLogger } from '../../utils/logger.js';\nimport type { CompactionResult } from './compaction.js';\n\nconst log = createLogger('MemoryFlush');\n\nexport interface MemoryFlushConfig {\n enabled: boolean;\n threshold: number;\n softThresholdTokens: number;\n afterCompactions: number;\n maxEntryChars: number;\n includeToolHistory: boolean;\n}\n\nexport interface MemoryFlushOptions {\n workspaceDir: string;\n sessionKey: string;\n compactionResult: CompactionResult;\n config: MemoryFlushConfig;\n}\n\nexport interface MemoryFlushResult {\n flushed: boolean;\n entryPath: string;\n entryLength: number;\n reason?: string;\n}\n\nexport class MemoryFlushService {\n async flush(options: MemoryFlushOptions): Promise<MemoryFlushResult> {\n const { workspaceDir, sessionKey, compactionResult, config } = options;\n\n if (!config.enabled) {\n return { flushed: false, entryPath: '', entryLength: 0, reason: 'disabled' };\n }\n\n const now = new Date();\n const day = this.isoDay(now);\n const memoryDir = join(workspaceDir, 'memory');\n const filePath = join(memoryDir, `${day}.md`);\n const entryPath = `memory/${day}.md`;\n\n await mkdir(memoryDir, { recursive: true });\n\n const entry = this.buildEntry(sessionKey, compactionResult, now, config);\n const entryText = entry.text;\n const entryLength = entryText.length;\n\n if (entryLength > config.maxEntryChars) {\n log.warn({ sessionKey, entryLength, maxEntryChars: config.maxEntryChars }, 'Flush entry exceeds maxEntryChars; truncating');\n }\n\n try {\n const fileExists = existsSync(filePath);\n if (!fileExists) {\n const frontmatter = `# Daily Notes — ${day}\\n\\n`;\n await writeFile(filePath, frontmatter + entryText, 'utf-8');\n } else {\n const existing = await readFile(filePath, 'utf-8');\n // Warn if file is getting large (>50KB) but still append\n if (existing.length > 50_000) {\n log.warn({ sessionKey, filePath, size: existing.length }, 'Daily notes file is large; continuing append');\n }\n await appendFile(filePath, '\\n' + entryText, 'utf-8');\n }\n\n log.info({ sessionKey, entryPath, entryLength }, 'Memory flushed to daily notes');\n return { flushed: true, entryPath, entryLength };\n } catch (err) {\n const em = err instanceof Error ? err.message : String(err);\n log.error({ sessionKey, err, filePath }, `Memory flush failed: ${em}`);\n return { flushed: false, entryPath, entryLength: 0, reason: `write_error: ${em}` };\n }\n }\n\n private buildEntry(\n sessionKey: string,\n result: CompactionResult,\n now: Date,\n config: MemoryFlushConfig,\n ): { text: string } {\n const iso = now.toISOString();\n const lines: string[] = [];\n\n lines.push(`## Session Flush [${sessionKey}] ${iso}`);\n lines.push('');\n\n const summary = result.summary || '';\n lines.push(`**Summary:** ${summary}`);\n lines.push('');\n\n const structured = result.structuredSummary;\n if (structured) {\n if (structured.userRequests && structured.userRequests.length > 0) {\n lines.push('**User Requests:**');\n for (const req of structured.userRequests) {\n lines.push(`- ${req}`);\n }\n lines.push('');\n }\n\n if (structured.keyDecisions && structured.keyDecisions.length > 0) {\n lines.push('**Key Decisions:**');\n for (const decision of structured.keyDecisions) {\n lines.push(`- ${decision}`);\n }\n lines.push('');\n }\n\n if (structured.filesModified && structured.filesModified.length > 0) {\n lines.push('**Files Modified:**');\n for (const file of structured.filesModified) {\n lines.push(`- ${file}`);\n }\n lines.push('');\n }\n\n if (config.includeToolHistory && structured.toolCalls && structured.toolCalls.length > 0) {\n lines.push('**Tool Calls:**');\n for (const call of structured.toolCalls) {\n const filePart = call.filePath ? ` (${call.filePath})` : '';\n const status = call.success ? 'success' : 'failed';\n lines.push(`- \\`${call.toolName}\\`${filePart} — ${status}`);\n }\n lines.push('');\n }\n } else if (summary) {\n // Fallback when structuredSummary is absent\n lines.push('**Summary (text only):**');\n lines.push(summary);\n lines.push('');\n }\n\n lines.push('---');\n\n let text = lines.join('\\n');\n\n // Respect maxEntryChars by truncating from the end if needed\n if (text.length > config.maxEntryChars) {\n // Keep the header and a truncation notice\n const headerEnd = text.indexOf('\\n\\n') + 2;\n const header = text.slice(0, headerEnd);\n const remainingBudget = config.maxEntryChars - header.length - 60;\n const body = text.slice(headerEnd);\n const truncatedBody = body.slice(0, Math.max(0, remainingBudget));\n text = header + truncatedBody + '\\n\\n*(Entry truncated due to length limit)*\\n---';\n }\n\n return { text };\n }\n\n /** YYYY-MM-DD in local time (for daily `memory/YYYY-MM-DD.md` names). */\n private isoDay(d: Date): string {\n const y = d.getFullYear();\n const m = String(d.getMonth() + 1).padStart(2, '0');\n const day = String(d.getDate()).padStart(2, '0');\n return `${y}-${m}-${day}`;\n }\n}\n"],"mappings":";;;;;;aAGqD;AAGrD,MAAM,MAAM,aAAa,cAAc;AAyBvC,IAAa,qBAAb,MAAgC;CAC9B,MAAM,MAAM,SAAyD;EACnE,MAAM,EAAE,cAAc,YAAY,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GAAG,UAAU;GACvC,MAAM,kBAAkB,OAAO,gBAAgB,OAAO,SAAS;AAG/D,UAAO,SAFM,KAAK,MAAM,UACE,CAAC,MAAM,GAAG,KAAK,IAAI,GAAG,gBAAgB,CACnC,GAAG;;AAGlC,SAAO,EAAE,MAAM;;;CAIjB,OAAe,GAAiB;AAI9B,SAAO,GAHG,EAAE,aAGD,CAAC,GAFF,OAAO,EAAE,UAAU,GAAG,EAAE,CAAC,SAAS,GAAG,IAE/B,CAAC,GADL,OAAO,EAAE,SAAS,CAAC,CAAC,SAAS,GAAG,IACrB"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createLogger } from "../../utils/logger/index.js";
|
|
2
2
|
import { init_logger } from "../../utils/logger.js";
|
|
3
|
-
import { createTypingController } from "../lifecycle/typing.js";
|
|
4
3
|
import { shouldSilence } from "../../heartbeat/tokens.js";
|
|
4
|
+
import { createTypingController } from "../lifecycle/typing.js";
|
|
5
5
|
//#region src/agent/messaging/outbound-coordinator.ts
|
|
6
6
|
init_logger();
|
|
7
7
|
const log = createLogger("OutboundCoordinator");
|
|
@@ -84,6 +84,7 @@ var OutboundCoordinator = class {
|
|
|
84
84
|
metadata: {
|
|
85
85
|
accountId: msg.metadata?.accountId,
|
|
86
86
|
threadId: msg.metadata?.threadId,
|
|
87
|
+
inboundMessageId: msg.metadata?.messageId,
|
|
87
88
|
transcribedVoice: sessionContext.metadata?.transcribedVoice,
|
|
88
89
|
sessionWebhook: msg.metadata?.sessionWebhook,
|
|
89
90
|
conversationId: msg.metadata?.conversationId
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"outbound-coordinator.js","names":[],"sources":["../../../../src/agent/messaging/outbound-coordinator.ts"],"sourcesContent":["/**\n * OutboundCoordinator — owns the post-turn outbound pipeline.\n *\n * Concentrates the responsibilities that used to be scattered across\n * `AgentService`:\n * - typing-on / typing-off lifecycle for channels that surface \"is typing…\"\n * - final assistant response delivery (silence guard + hook + bus publish)\n * - cross-cutting `webchat_turn_complete` hook + `/goal` post-turn\n * - thin pass-through for extension `message_sending` / `message_sent` hooks\n *\n * The class is intentionally framework-agnostic: it pulls everything it needs\n * via the constructor config (no direct AgentService reference), so it is\n * unit-testable and lets the parent `AgentService` shrink to a coordinator.\n */\n\nimport type { MessageBus, InboundMessage } from '../../infra/bus/index.js';\nimport type { Config } from '../../config/schema.js';\nimport type { HookHandler } from '../lifecycle/hook-handler.js';\nimport type { SessionContext } from '../session/index.js';\nimport { createTypingController, type TypingController } from '../lifecycle/typing.js';\nimport { DEFAULT_ACK_MAX_CHARS, NO_REPLY, shouldSilence } from '../../heartbeat/tokens.js';\nimport { createLogger } from '../../utils/logger.js';\nimport type { StreamManager } from './stream-manager.js';\n\nconst log = createLogger('OutboundCoordinator');\n\nexport interface OutboundCoordinatorConfig {\n bus: MessageBus;\n hookHandler: HookHandler;\n streamManager: StreamManager;\n /** Reads the effective config snapshot (honours runtime overrides). */\n getConfig: () => Config | undefined;\n /** Resolves the last visible assistant text for a session (in-memory + agent fallback). */\n getLastAssistantPlainText: (sessionKey: string) => string;\n /**\n * Run the `/goal` post-turn verdict for a completed user turn. Owned by\n * `PersistentGoalService`; OutboundCoordinator only forwards.\n */\n runPersistentGoalPostTurn: (payload: SessionTurnCompletePayload) => Promise<void>;\n}\n\nexport interface SessionTurnCompletePayload {\n sessionKey: string;\n channel: string;\n chatId: string;\n inboundUserText: string;\n assistantPlainText: string;\n aborted: boolean;\n streamError?: string;\n skipPersistentGoalPostTurn?: boolean;\n outboundMetadata?: Record<string, unknown>;\n}\n\nexport class OutboundCoordinator {\n private readonly bus: MessageBus;\n private readonly hookHandler: HookHandler;\n private readonly streamManager: StreamManager;\n private readonly getConfig: () => Config | undefined;\n private readonly getLastAssistantPlainText: (sessionKey: string) => string;\n private readonly runPersistentGoalPostTurn: OutboundCoordinatorConfig['runPersistentGoalPostTurn'];\n\n constructor(config: OutboundCoordinatorConfig) {\n this.bus = config.bus;\n this.hookHandler = config.hookHandler;\n this.streamManager = config.streamManager;\n this.getConfig = config.getConfig;\n this.getLastAssistantPlainText = config.getLastAssistantPlainText;\n this.runPersistentGoalPostTurn = config.runPersistentGoalPostTurn;\n }\n\n /**\n * Build the typing indicator controller for an inbound message. Returns\n * `null` for the CLI channel (no typing UI). Caller is responsible for\n * `start()` and `stop()` (`stop()` should run AFTER the final outbound so\n * Telegram/Weixin see `typing_off` only once the message is delivered).\n */\n createTypingControllerForInbound(msg: InboundMessage): TypingController | null {\n if (msg.channel === 'cli') {\n return null;\n }\n const meta = msg.metadata as Record<string, unknown> | undefined;\n return createTypingController({\n intervalSeconds: 5,\n onStart: async () => {\n await this.bus.publishOutbound({\n channel: msg.channel,\n chat_id: msg.chat_id,\n content: '',\n type: 'typing_on',\n metadata: {\n accountId: meta?.accountId,\n threadId: meta?.threadId,\n sessionWebhook: meta?.sessionWebhook,\n conversationId: meta?.conversationId,\n },\n });\n },\n onStop: async () => {\n await this.bus.publishOutbound({\n channel: msg.channel,\n chat_id: msg.chat_id,\n content: '',\n type: 'typing_off',\n metadata: {\n accountId: meta?.accountId,\n threadId: meta?.threadId,\n sessionWebhook: meta?.sessionWebhook,\n conversationId: meta?.conversationId,\n },\n });\n },\n });\n }\n\n /**\n * Publish the assistant's visible text as the final bus message. Honours the\n * stream-manager \"channel already streamed the final text\" hint, the heartbeat\n * silence guard, and the extension `message_sending` hook.\n */\n async sendFinalResponse(msg: InboundMessage, sessionContext: SessionContext): Promise<void> {\n if (this.streamManager.consumeSkipFinalOutbound()) {\n return;\n }\n\n const finalContent = this.getLastAssistantPlainText(sessionContext.sessionKey);\n if (!finalContent?.trim()) {\n return;\n }\n\n const ackMax = this.getConfig()?.gateway?.heartbeat?.ackMaxChars ?? DEFAULT_ACK_MAX_CHARS;\n if (shouldSilence(finalContent, ackMax) || finalContent.trim() === NO_REPLY) {\n log.debug({ sessionKey: sessionContext.sessionKey }, 'Silent reply — skipping outbound');\n return;\n }\n\n const hookResult = await this.hookHandler.runMessageSending(\n sessionContext.chatId,\n finalContent,\n sessionContext.channel,\n );\n if (!hookResult.send) {\n return;\n }\n\n await this.bus.publishOutbound({\n channel: sessionContext.channel,\n chat_id: sessionContext.chatId,\n content: hookResult.content || finalContent,\n type: 'message',\n metadata: {\n accountId: msg.metadata?.accountId,\n threadId: msg.metadata?.threadId,\n transcribedVoice: sessionContext.metadata?.transcribedVoice,\n sessionWebhook: msg.metadata?.sessionWebhook,\n conversationId: msg.metadata?.conversationId,\n },\n });\n }\n\n /**\n * Post-turn hook + `/goal` checklist evaluation. Wired into both the bus-driven\n * inbound finally block and the webchat direct-stream finally. The goal verdict\n * itself lives in `PersistentGoalService`; we just trigger the extension hook\n * here and delegate the `/goal` work.\n */\n async emitSessionTurnComplete(payload: SessionTurnCompletePayload): Promise<void> {\n await this.hookHandler.triggerWithSessionKey(payload.sessionKey, 'webchat_turn_complete', {\n sessionKey: payload.sessionKey,\n channel: payload.channel,\n chatId: payload.chatId,\n inboundUserText: payload.inboundUserText,\n assistantPlainText: payload.assistantPlainText,\n aborted: payload.aborted,\n ...(payload.streamError !== undefined ? { streamError: payload.streamError } : {}),\n });\n\n await this.runPersistentGoalPostTurn(payload);\n }\n\n /** Extension hook pass-through (Gateway ChannelManager). */\n invokeOutboundMessageSending(\n to: string,\n content: string,\n channel: string,\n ): Promise<{ send: boolean; content?: string; reason?: string }> {\n return this.hookHandler.runMessageSending(to, content, channel);\n }\n\n /** Extension hook pass-through (Gateway ChannelManager). */\n invokeOutboundMessageSent(\n to: string,\n content: string,\n success: boolean,\n error: string | undefined,\n channel: string,\n ): Promise<void> {\n return this.hookHandler.runMessageSent(to, content, success, error, channel);\n }\n}\n"],"mappings":";;;;;aAqBqD;AAGrD,MAAM,MAAM,aAAa,sBAAsB;AA6B/C,IAAa,sBAAb,MAAiC;CAC/B;CACA;CACA;CACA;CACA;CACA;CAEA,YAAY,QAAmC;AAC7C,OAAK,MAAM,OAAO;AAClB,OAAK,cAAc,OAAO;AAC1B,OAAK,gB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AU,IAAI,UAAU;IACxB,kBAAkB,eAAe,UAAU;IAC3C,gBAAgB,IAAI,UAAU;IAC9B,gBAAgB,IAAI,UAAU;IAC/B;GACF,CAAC;;;;;;;;CASJ,MAAM,wBAAwB,SAAoD;AAChF,QAAM,KAAK,YAAY,sBAAsB,QAAQ,YAAY,yBAAyB;GACxF,YAAY,QAAQ;GACpB,SAAS,QAAQ;GACjB,QAAQ,QAAQ;GAChB,iBAAiB,QAAQ;GACzB,oBAAoB,QAAQ;GAC5B,SAAS,QAAQ;GACjB,GAAI,QAAQ,gBAAgB,KAAA,IAAY,EAAE,aAAa,QAAQ,aAAa,GAAG,EAAE;GAClF,CAAC;AAEF,QAAM,KAAK,0BAA0B,QAAQ;;;CAI/C,6BACE,IACA,SACA,SAC+D;AAC/D,SAAO,KAAK,YAAY,kBAAkB,IAAI,SAAS,QAAQ;;;CAIjE,0BACE,IACA,SACA,SACA,OACA,SACe;AACf,SAAO,KAAK,YAAY,eAAe,IAAI,SAAS,SAAS,OAAO,QAAQ"}
|
|
1
|
+
{"version":3,"file":"outbound-coordinator.js","names":[],"sources":["../../../../src/agent/messaging/outbound-coordinator.ts"],"sourcesContent":["/**\n * OutboundCoordinator — owns the post-turn outbound pipeline.\n *\n * Concentrates the responsibilities that used to be scattered across\n * `AgentService`:\n * - typing-on / typing-off lifecycle for channels that surface \"is typing…\"\n * - final assistant response delivery (silence guard + hook + bus publish)\n * - cross-cutting `webchat_turn_complete` hook + `/goal` post-turn\n * - thin pass-through for extension `message_sending` / `message_sent` hooks\n *\n * The class is intentionally framework-agnostic: it pulls everything it needs\n * via the constructor config (no direct AgentService reference), so it is\n * unit-testable and lets the parent `AgentService` shrink to a coordinator.\n */\n\nimport type { MessageBus, InboundMessage } from '../../infra/bus/index.js';\nimport type { Config } from '../../config/schema.js';\nimport type { HookHandler } from '../lifecycle/hook-handler.js';\nimport type { SessionContext } from '../session/index.js';\nimport { createTypingController, type TypingController } from '../lifecycle/typing.js';\nimport { DEFAULT_ACK_MAX_CHARS, NO_REPLY, shouldSilence } from '../../heartbeat/tokens.js';\nimport { createLogger } from '../../utils/logger.js';\nimport type { StreamManager } from './stream-manager.js';\n\nconst log = createLogger('OutboundCoordinator');\n\nexport interface OutboundCoordinatorConfig {\n bus: MessageBus;\n hookHandler: HookHandler;\n streamManager: StreamManager;\n /** Reads the effective config snapshot (honours runtime overrides). */\n getConfig: () => Config | undefined;\n /** Resolves the last visible assistant text for a session (in-memory + agent fallback). */\n getLastAssistantPlainText: (sessionKey: string) => string;\n /**\n * Run the `/goal` post-turn verdict for a completed user turn. Owned by\n * `PersistentGoalService`; OutboundCoordinator only forwards.\n */\n runPersistentGoalPostTurn: (payload: SessionTurnCompletePayload) => Promise<void>;\n}\n\nexport interface SessionTurnCompletePayload {\n sessionKey: string;\n channel: string;\n chatId: string;\n inboundUserText: string;\n assistantPlainText: string;\n aborted: boolean;\n streamError?: string;\n skipPersistentGoalPostTurn?: boolean;\n outboundMetadata?: Record<string, unknown>;\n}\n\nexport class OutboundCoordinator {\n private readonly bus: MessageBus;\n private readonly hookHandler: HookHandler;\n private readonly streamManager: StreamManager;\n private readonly getConfig: () => Config | undefined;\n private readonly getLastAssistantPlainText: (sessionKey: string) => string;\n private readonly runPersistentGoalPostTurn: OutboundCoordinatorConfig['runPersistentGoalPostTurn'];\n\n constructor(config: OutboundCoordinatorConfig) {\n this.bus = config.bus;\n this.hookHandler = config.hookHandler;\n this.streamManager = config.streamManager;\n this.getConfig = config.getConfig;\n this.getLastAssistantPlainText = config.getLastAssistantPlainText;\n this.runPersistentGoalPostTurn = config.runPersistentGoalPostTurn;\n }\n\n /**\n * Build the typing indicator controller for an inbound message. Returns\n * `null` for the CLI channel (no typing UI). Caller is responsible for\n * `start()` and `stop()` (`stop()` should run AFTER the final outbound so\n * Telegram/Weixin see `typing_off` only once the message is delivered).\n */\n createTypingControllerForInbound(msg: InboundMessage): TypingController | null {\n if (msg.channel === 'cli') {\n return null;\n }\n const meta = msg.metadata as Record<string, unknown> | undefined;\n return createTypingController({\n intervalSeconds: 5,\n onStart: async () => {\n await this.bus.publishOutbound({\n channel: msg.channel,\n chat_id: msg.chat_id,\n content: '',\n type: 'typing_on',\n metadata: {\n accountId: meta?.accountId,\n threadId: meta?.threadId,\n sessionWebhook: meta?.sessionWebhook,\n conversationId: meta?.conversationId,\n },\n });\n },\n onStop: async () => {\n await this.bus.publishOutbound({\n channel: msg.channel,\n chat_id: msg.chat_id,\n content: '',\n type: 'typing_off',\n metadata: {\n accountId: meta?.accountId,\n threadId: meta?.threadId,\n sessionWebhook: meta?.sessionWebhook,\n conversationId: meta?.conversationId,\n },\n });\n },\n });\n }\n\n /**\n * Publish the assistant's visible text as the final bus message. Honours the\n * stream-manager \"channel already streamed the final text\" hint, the heartbeat\n * silence guard, and the extension `message_sending` hook.\n */\n async sendFinalResponse(msg: InboundMessage, sessionContext: SessionContext): Promise<void> {\n if (this.streamManager.consumeSkipFinalOutbound()) {\n return;\n }\n\n const finalContent = this.getLastAssistantPlainText(sessionContext.sessionKey);\n if (!finalContent?.trim()) {\n return;\n }\n\n const ackMax = this.getConfig()?.gateway?.heartbeat?.ackMaxChars ?? DEFAULT_ACK_MAX_CHARS;\n if (shouldSilence(finalContent, ackMax) || finalContent.trim() === NO_REPLY) {\n log.debug({ sessionKey: sessionContext.sessionKey }, 'Silent reply — skipping outbound');\n return;\n }\n\n const hookResult = await this.hookHandler.runMessageSending(\n sessionContext.chatId,\n finalContent,\n sessionContext.channel,\n );\n if (!hookResult.send) {\n return;\n }\n\n await this.bus.publishOutbound({\n channel: sessionContext.channel,\n chat_id: sessionContext.chatId,\n content: hookResult.content || finalContent,\n type: 'message',\n metadata: {\n accountId: msg.metadata?.accountId,\n threadId: msg.metadata?.threadId,\n inboundMessageId: msg.metadata?.messageId,\n transcribedVoice: sessionContext.metadata?.transcribedVoice,\n sessionWebhook: msg.metadata?.sessionWebhook,\n conversationId: msg.metadata?.conversationId,\n },\n });\n }\n\n /**\n * Post-turn hook + `/goal` checklist evaluation. Wired into both the bus-driven\n * inbound finally block and the webchat direct-stream finally. The goal verdict\n * itself lives in `PersistentGoalService`; we just trigger the extension hook\n * here and delegate the `/goal` work.\n */\n async emitSessionTurnComplete(payload: SessionTurnCompletePayload): Promise<void> {\n await this.hookHandler.triggerWithSessionKey(payload.sessionKey, 'webchat_turn_complete', {\n sessionKey: payload.sessionKey,\n channel: payload.channel,\n chatId: payload.chatId,\n inboundUserText: payload.inboundUserText,\n assistantPlainText: payload.assistantPlainText,\n aborted: payload.aborted,\n ...(payload.streamError !== undefined ? { streamError: payload.streamError } : {}),\n });\n\n await this.runPersistentGoalPostTurn(payload);\n }\n\n /** Extension hook pass-through (Gateway ChannelManager). */\n invokeOutboundMessageSending(\n to: string,\n content: string,\n channel: string,\n ): Promise<{ send: boolean; content?: string; reason?: string }> {\n return this.hookHandler.runMessageSending(to, content, channel);\n }\n\n /** Extension hook pass-through (Gateway ChannelManager). */\n invokeOutboundMessageSent(\n to: string,\n content: string,\n success: boolean,\n error: string | undefined,\n channel: string,\n ): Promise<void> {\n return this.hookHandler.runMessageSent(to, content, success, error, channel);\n }\n}\n"],"mappings":";;;;;aAqBqD;AAGrD,MAAM,MAAM,aAAa,sBAAsB;AA6B/C,IAAa,sBAAb,MAAiC;CAC/B;CACA;CACA;CACA;CACA;CACA;CAEA,YAAY,QAAmC;AAC7C,OAAK,MAAM,OAAO;AAClB,OAAK,cAAc,OAAO;AAC1B,OAAK,gBAAgB,OAAO;AAC5B,OAAK,YAAY,OAAO;AACxB,OAAK,4BAA4B,OAAO;AACxC,OAAK,4BAA4B,OAAO;;;;;;;;CAS1C,iCAAiC,KAA8C;AAC7E,MAAI,IAAI,YAAY,MAClB,QAAO;EAET,MAAM,OAAO,IAAI;AACjB,SAAO,uBAAuB;GAC5B,iBAAiB;GACjB,SAAS,YAAY;AACnB,UAAM,KAAK,IAAI,gBAAgB;KAC7B,SAAS,IAAI;KACb,SAAS,IAAI;KACb,SAAS;KACT,MA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AoB,QAAQ;GAC5B,SAAS,QAAQ;GACjB,GAAI,QAAQ,gBAAgB,KAAA,IAAY,EAAE,aAAa,QAAQ,aAAa,GAAG,EAAE;GAClF,CAAC;AAEF,QAAM,KAAK,0BAA0B,QAAQ;;;CAI/C,6BACE,IACA,SACA,SAC+D;AAC/D,SAAO,KAAK,YAAY,kBAAkB,IAAI,SAAS,QAAQ;;;CAIjE,0BACE,IACA,SACA,SACA,OACA,SACe;AACf,SAAO,KAAK,YAAY,eAAe,IAAI,SAAS,SAAS,OAAO,QAAQ"}
|
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
import type { ProgressStage } from '../lifecycle/progress.js';
|
|
8
8
|
export interface StreamHandle {
|
|
9
9
|
update: (text: string) => void;
|
|
10
|
+
updateReasoning?: (text: string) => void;
|
|
10
11
|
updateProgress?: (text: string, stage: ProgressStage, detail?: string) => void;
|
|
11
12
|
setProgress?: (stage: ProgressStage, detail?: string) => void;
|
|
12
13
|
end: () => Promise<void>;
|
|
@@ -37,6 +38,7 @@ export declare class StreamManager {
|
|
|
37
38
|
* Update the stream with text content
|
|
38
39
|
*/
|
|
39
40
|
update(text: string): void;
|
|
41
|
+
updateReasoning(text: string): void;
|
|
40
42
|
/**
|
|
41
43
|
* End the stream and clear the handle
|
|
42
44
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stream-manager.js","names":[],"sources":["../../../../src/agent/messaging/stream-manager.ts"],"sourcesContent":["/**\n * Stream Manager - Manages stream handles for progress updates\n *\n * Handles creation and lifecycle of stream handles for sending progress updates\n * and streaming responses.\n */\n\nimport type { ProgressStage } from '../lifecycle/progress.js';\n\nexport interface StreamHandle {\n update: (text: string) => void;\n updateProgress?: (text: string, stage: ProgressStage, detail?: string) => void;\n setProgress?: (stage: ProgressStage, detail?: string) => void;\n end: () => Promise<void>;\n abort: () => Promise<void>;\n messageId: () => number | undefined;\n skipFinalOutbound?: () => boolean;\n}\n\nexport class StreamManager {\n private currentHandle: StreamHandle | null = null;\n private skipFinalOutboundPending = false;\n\n /**\n * Set the current stream handle\n */\n setHandle(handle: StreamHandle): void {\n this.currentHandle = handle;\n }\n\n /**\n * Get the current stream handle\n */\n getHandle(): StreamHandle | null {\n return this.currentHandle;\n }\n\n /**\n * Clear the current stream handle\n */\n clearHandle(): void {\n this.currentHandle = null;\n }\n\n /**\n * Check if a stream handle is currently active\n */\n hasActiveHandle(): boolean {\n return this.currentHandle !== null;\n }\n\n /**\n * Update the stream with text content\n */\n update(text: string): void {\n this.currentHandle?.update(text);\n }\n\n /**\n * End the stream and clear the handle\n */\n async end(): Promise<void> {\n if (this.currentHandle) {\n const handle = this.currentHandle;\n await handle.end();\n this.skipFinalOutboundPending = handle.skipFinalOutbound?.() ?? false;\n this.clearHandle();\n } else {\n this.skipFinalOutboundPending = false;\n }\n }\n\n /**\n * Abort the stream and clear the handle\n */\n async abort(): Promise<void> {\n if (this.currentHandle) {\n await this.currentHandle.abort();\n this.skipFinalOutboundPending = false;\n this.clearHandle();\n }\n }\n\n /**\n * Whether the channel already delivered the final assistant text (e.g. Telegram streaming).\n * Consumes the flag for one outbound decision.\n */\n consumeSkipFinalOutbound(): boolean {\n const v = this.skipFinalOutboundPending;\n this.skipFinalOutboundPending = false;\n return v;\n }\n\n /**\n * Get the current message ID from the stream handle\n */\n getMessageId(): number | undefined {\n return this.currentHandle?.messageId();\n }\n\n /**\n * Update progress via the stream handle\n */\n updateProgress(text: string, stage: ProgressStage, detail?: string): void {\n if (this.currentHandle?.updateProgress) {\n this.currentHandle.updateProgress(text, stage, detail);\n }\n }\n\n /**\n * Set progress stage via the stream handle\n */\n setProgress(stage: ProgressStage, detail?: string): void {\n if (this.currentHandle?.setProgress) {\n this.currentHandle.setProgress(stage, detail);\n }\n }\n}\n"],"mappings":";
|
|
1
|
+
{"version":3,"file":"stream-manager.js","names":[],"sources":["../../../../src/agent/messaging/stream-manager.ts"],"sourcesContent":["/**\n * Stream Manager - Manages stream handles for progress updates\n *\n * Handles creation and lifecycle of stream handles for sending progress updates\n * and streaming responses.\n */\n\nimport type { ProgressStage } from '../lifecycle/progress.js';\n\nexport interface StreamHandle {\n update: (text: string) => void;\n updateReasoning?: (text: string) => void;\n updateProgress?: (text: string, stage: ProgressStage, detail?: string) => void;\n setProgress?: (stage: ProgressStage, detail?: string) => void;\n end: () => Promise<void>;\n abort: () => Promise<void>;\n messageId: () => number | undefined;\n skipFinalOutbound?: () => boolean;\n}\n\nexport class StreamManager {\n private currentHandle: StreamHandle | null = null;\n private skipFinalOutboundPending = false;\n\n /**\n * Set the current stream handle\n */\n setHandle(handle: StreamHandle): void {\n this.currentHandle = handle;\n }\n\n /**\n * Get the current stream handle\n */\n getHandle(): StreamHandle | null {\n return this.currentHandle;\n }\n\n /**\n * Clear the current stream handle\n */\n clearHandle(): void {\n this.currentHandle = null;\n }\n\n /**\n * Check if a stream handle is currently active\n */\n hasActiveHandle(): boolean {\n return this.currentHandle !== null;\n }\n\n /**\n * Update the stream with text content\n */\n update(text: string): void {\n this.currentHandle?.update(text);\n }\n\n updateReasoning(text: string): void {\n this.currentHandle?.updateReasoning?.(text);\n }\n\n /**\n * End the stream and clear the handle\n */\n async end(): Promise<void> {\n if (this.currentHandle) {\n const handle = this.currentHandle;\n await handle.end();\n this.skipFinalOutboundPending = handle.skipFinalOutbound?.() ?? false;\n this.clearHandle();\n } else {\n this.skipFinalOutboundPending = false;\n }\n }\n\n /**\n * Abort the stream and clear the handle\n */\n async abort(): Promise<void> {\n if (this.currentHandle) {\n await this.currentHandle.abort();\n this.skipFinalOutboundPending = false;\n this.clearHandle();\n }\n }\n\n /**\n * Whether the channel already delivered the final assistant text (e.g. Telegram streaming).\n * Consumes the flag for one outbound decision.\n */\n consumeSkipFinalOutbound(): boolean {\n const v = this.skipFinalOutboundPending;\n this.skipFinalOutboundPending = false;\n return v;\n }\n\n /**\n * Get the current message ID from the stream handle\n */\n getMessageId(): number | undefined {\n return this.currentHandle?.messageId();\n }\n\n /**\n * Update progress via the stream handle\n */\n updateProgress(text: string, stage: ProgressStage, detail?: string): void {\n if (this.currentHandle?.updateProgress) {\n this.currentHandle.updateProgress(text, stage, detail);\n }\n }\n\n /**\n * Set progress stage via the stream handle\n */\n setProgress(stage: ProgressStage, detail?: string): void {\n if (this.currentHandle?.setProgress) {\n this.currentHandle.setProgress(stage, detail);\n }\n }\n}\n"],"mappings":";AAoBA,IAAa,gBAAb,MAA2B;CACzB,gBAA6C;CAC7C,2BAAmC;;;;CAKnC,UAAU,QAA4B;AACpC,OAAK,gBAAgB;;;;;CAMvB,YAAiC;AAC/B,SAAO,KAAK;;;;;CAMd,cAAoB;AAClB,OAAK,gBAAgB;;;;;CAMvB,kBAA2B;AACzB,SAAO,KAAK,kBAAkB;;;;;CAMhC,OAAO,MAAoB;AACzB,OAAK,eAAe,OAAO,KAAK;;CAGlC,gBAAgB,MAAoB;AAClC,OAAK,eAAe,kBAAkB,KAAK;;;;;CAM7C,MAAM,MAAqB;AACzB,MAAI,KAAK,eAAe;GACtB,MAAM,SAAS,KAAK;AACpB,SAAM,OAAO,KAAK;AAClB,QAAK,2BAA2B,OAAO,qBAAqB,IAAI;AAChE,QAAK,aAAa;QAElB,MAAK,2BAA2B;;;;;CAOpC,MAAM,QAAuB;AAC3B,MAAI,KAAK,eAAe;AACtB,SAAM,KAAK,cAAc,OAAO;AAChC,QAAK,2BAA2B;AAChC,QAAK,aAAa;;;;;;;CAQtB,2BAAoC;EAClC,MAAM,IAAI,KAAK;AACf,OAAK,2BAA2B;AAChC,SAAO;;;;;CAMT,eAAmC;AACjC,SAAO,KAAK,eAAe,WAAW;;;;;CAMxC,eAAe,MAAc,OAAsB,QAAuB;AACxE,MAAI,KAAK,eAAe,eACtB,MAAK,cAAc,eAAe,MAAM,OAAO,OAAO;;;;;CAO1D,YAAY,OAAsB,QAAuB;AACvD,MAAI,KAAK,eAAe,YACtB,MAAK,cAAc,YAAY,OAAO,OAAO"}
|
|
@@ -64,10 +64,6 @@ export declare class AgentOrchestrator {
|
|
|
64
64
|
* Process a message through the agent orchestration pipeline
|
|
65
65
|
*/
|
|
66
66
|
process(msg: InboundMessage, context: SessionContext): Promise<void>;
|
|
67
|
-
/**
|
|
68
|
-
* Build an agent message from an inbound message
|
|
69
|
-
*/
|
|
70
|
-
private buildUserMessage;
|
|
71
67
|
/**
|
|
72
68
|
* Get the current agent model ID
|
|
73
69
|
*/
|