rookery-agent 0.3.1 → 0.4.1
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/README.md +9 -3
- package/docs/updates.md +12 -0
- package/package.json +1 -2
- package/packages/cli/dist/commands/chat.d.ts.map +1 -1
- package/packages/cli/dist/commands/chat.js +37 -74
- package/packages/cli/dist/commands/chat.js.map +1 -1
- package/packages/cli/dist/commands/config.js +4 -4
- package/packages/cli/dist/commands/config.js.map +1 -1
- package/packages/cli/dist/commands/doctor.d.ts.map +1 -1
- package/packages/cli/dist/commands/doctor.js +113 -91
- package/packages/cli/dist/commands/doctor.js.map +1 -1
- package/packages/cli/dist/commands/memory.d.ts.map +1 -1
- package/packages/cli/dist/commands/memory.js +28 -31
- package/packages/cli/dist/commands/memory.js.map +1 -1
- package/packages/cli/dist/commands/org.d.ts.map +1 -1
- package/packages/cli/dist/commands/org.js +36 -103
- package/packages/cli/dist/commands/org.js.map +1 -1
- package/packages/cli/dist/commands/serve.d.ts.map +1 -1
- package/packages/cli/dist/commands/serve.js +8 -6
- package/packages/cli/dist/commands/serve.js.map +1 -1
- package/packages/cli/dist/commands/sessions.d.ts.map +1 -1
- package/packages/cli/dist/commands/sessions.js +18 -17
- package/packages/cli/dist/commands/sessions.js.map +1 -1
- package/packages/cli/dist/commands/shared.d.ts +26 -5
- package/packages/cli/dist/commands/shared.d.ts.map +1 -1
- package/packages/cli/dist/commands/shared.js +85 -63
- package/packages/cli/dist/commands/shared.js.map +1 -1
- package/packages/cli/dist/commands/slash.d.ts +51 -0
- package/packages/cli/dist/commands/slash.d.ts.map +1 -0
- package/packages/cli/dist/commands/slash.js +110 -0
- package/packages/cli/dist/commands/slash.js.map +1 -0
- package/packages/cli/dist/commands/tasks.d.ts.map +1 -1
- package/packages/cli/dist/commands/tasks.js +74 -115
- package/packages/cli/dist/commands/tasks.js.map +1 -1
- package/packages/cli/dist/commands/tools.d.ts.map +1 -1
- package/packages/cli/dist/commands/tools.js +51 -34
- package/packages/cli/dist/commands/tools.js.map +1 -1
- package/packages/cli/dist/index.js +42 -52
- package/packages/cli/dist/index.js.map +1 -1
- package/packages/cli/dist/repl.d.ts +1 -25
- package/packages/cli/dist/repl.d.ts.map +1 -1
- package/packages/cli/dist/repl.js +165 -726
- package/packages/cli/dist/repl.js.map +1 -1
- package/packages/cli/dist/replInput.d.ts +33 -0
- package/packages/cli/dist/replInput.d.ts.map +1 -0
- package/packages/cli/dist/replInput.js +97 -0
- package/packages/cli/dist/replInput.js.map +1 -0
- package/packages/cli/dist/replOutput.d.ts +11 -0
- package/packages/cli/dist/replOutput.d.ts.map +1 -0
- package/packages/cli/dist/replOutput.js +22 -0
- package/packages/cli/dist/replOutput.js.map +1 -0
- package/packages/cli/dist/replQuestions.d.ts +32 -0
- package/packages/cli/dist/replQuestions.d.ts.map +1 -0
- package/packages/cli/dist/replQuestions.js +122 -0
- package/packages/cli/dist/replQuestions.js.map +1 -0
- package/packages/cli/dist/replSlash.d.ts +24 -0
- package/packages/cli/dist/replSlash.d.ts.map +1 -0
- package/packages/cli/dist/replSlash.js +311 -0
- package/packages/cli/dist/replSlash.js.map +1 -0
- package/packages/cli/dist/replState.d.ts +56 -0
- package/packages/cli/dist/replState.d.ts.map +1 -0
- package/packages/cli/dist/replState.js +89 -0
- package/packages/cli/dist/replState.js.map +1 -0
- package/packages/cli/dist/tui/App.d.ts +7 -24
- package/packages/cli/dist/tui/App.d.ts.map +1 -1
- package/packages/cli/dist/tui/App.js +139 -513
- package/packages/cli/dist/tui/App.js.map +1 -1
- package/packages/cli/dist/tui/LiveRegion.d.ts +16 -0
- package/packages/cli/dist/tui/LiveRegion.d.ts.map +1 -0
- package/packages/cli/dist/tui/LiveRegion.js +37 -0
- package/packages/cli/dist/tui/LiveRegion.js.map +1 -0
- package/packages/cli/dist/tui/boot.d.ts +34 -0
- package/packages/cli/dist/tui/boot.d.ts.map +1 -0
- package/packages/cli/dist/tui/boot.js +133 -0
- package/packages/cli/dist/tui/boot.js.map +1 -0
- package/packages/cli/dist/tui/commands.d.ts +3 -4
- package/packages/cli/dist/tui/commands.d.ts.map +1 -1
- package/packages/cli/dist/tui/commands.js +339 -405
- package/packages/cli/dist/tui/commands.js.map +1 -1
- package/packages/cli/dist/tui/components/ActivityLine.d.ts +1 -1
- package/packages/cli/dist/tui/components/ActivityLine.d.ts.map +1 -1
- package/packages/cli/dist/tui/components/ActivityLine.js +2 -2
- package/packages/cli/dist/tui/components/ActivityLine.js.map +1 -1
- package/packages/cli/dist/tui/components/AssignmentsView.d.ts.map +1 -1
- package/packages/cli/dist/tui/components/AssignmentsView.js +34 -20
- package/packages/cli/dist/tui/components/AssignmentsView.js.map +1 -1
- package/packages/cli/dist/tui/components/Logo.d.ts +3 -19
- package/packages/cli/dist/tui/components/Logo.d.ts.map +1 -1
- package/packages/cli/dist/tui/components/Logo.js +13 -13
- package/packages/cli/dist/tui/components/Logo.js.map +1 -1
- package/packages/cli/dist/tui/components/Markdown.d.ts.map +1 -1
- package/packages/cli/dist/tui/components/Markdown.js +201 -146
- package/packages/cli/dist/tui/components/Markdown.js.map +1 -1
- package/packages/cli/dist/tui/components/QuestionView.d.ts +0 -2
- package/packages/cli/dist/tui/components/QuestionView.d.ts.map +1 -1
- package/packages/cli/dist/tui/components/QuestionView.js +21 -12
- package/packages/cli/dist/tui/components/QuestionView.js.map +1 -1
- package/packages/cli/dist/tui/components/Scrollback.d.ts.map +1 -1
- package/packages/cli/dist/tui/components/Scrollback.js +6 -3
- package/packages/cli/dist/tui/components/Scrollback.js.map +1 -1
- package/packages/cli/dist/tui/components/SlashPalette.d.ts.map +1 -1
- package/packages/cli/dist/tui/components/SlashPalette.js +14 -9
- package/packages/cli/dist/tui/components/SlashPalette.js.map +1 -1
- package/packages/cli/dist/tui/components/StatusLine.d.ts.map +1 -1
- package/packages/cli/dist/tui/components/StatusLine.js +45 -22
- package/packages/cli/dist/tui/components/StatusLine.js.map +1 -1
- package/packages/cli/dist/tui/components/ToolGroup.d.ts.map +1 -1
- package/packages/cli/dist/tui/components/ToolGroup.js +12 -7
- package/packages/cli/dist/tui/components/ToolGroup.js.map +1 -1
- package/packages/cli/dist/tui/components/WatchView.d.ts.map +1 -1
- package/packages/cli/dist/tui/components/WatchView.js +28 -17
- package/packages/cli/dist/tui/components/WatchView.js.map +1 -1
- package/packages/cli/dist/tui/highlight.d.ts +0 -2
- package/packages/cli/dist/tui/highlight.d.ts.map +1 -1
- package/packages/cli/dist/tui/highlight.js +8 -6
- package/packages/cli/dist/tui/highlight.js.map +1 -1
- package/packages/cli/dist/tui/history.d.ts +30 -4
- package/packages/cli/dist/tui/history.d.ts.map +1 -1
- package/packages/cli/dist/tui/history.js +100 -75
- package/packages/cli/dist/tui/history.js.map +1 -1
- package/packages/cli/dist/tui/hooks/coalescer.d.ts +18 -0
- package/packages/cli/dist/tui/hooks/coalescer.d.ts.map +1 -0
- package/packages/cli/dist/tui/hooks/coalescer.js +36 -0
- package/packages/cli/dist/tui/hooks/coalescer.js.map +1 -0
- package/packages/cli/dist/tui/hooks/useColumns.d.ts +2 -7
- package/packages/cli/dist/tui/hooks/useColumns.d.ts.map +1 -1
- package/packages/cli/dist/tui/hooks/useColumns.js +6 -11
- package/packages/cli/dist/tui/hooks/useColumns.js.map +1 -1
- package/packages/cli/dist/tui/hooks/useHistory.d.ts +7 -4
- package/packages/cli/dist/tui/hooks/useHistory.d.ts.map +1 -1
- package/packages/cli/dist/tui/hooks/useHistory.js +21 -18
- package/packages/cli/dist/tui/hooks/useHistory.js.map +1 -1
- package/packages/cli/dist/tui/hooks/usePrompt.d.ts +27 -0
- package/packages/cli/dist/tui/hooks/usePrompt.d.ts.map +1 -0
- package/packages/cli/dist/tui/hooks/usePrompt.js +169 -0
- package/packages/cli/dist/tui/hooks/usePrompt.js.map +1 -0
- package/packages/cli/dist/tui/hooks/useQuestion.d.ts +23 -0
- package/packages/cli/dist/tui/hooks/useQuestion.d.ts.map +1 -0
- package/packages/cli/dist/tui/hooks/useQuestion.js +43 -0
- package/packages/cli/dist/tui/hooks/useQuestion.js.map +1 -0
- package/packages/cli/dist/tui/hooks/useScrollback.d.ts +18 -0
- package/packages/cli/dist/tui/hooks/useScrollback.d.ts.map +1 -0
- package/packages/cli/dist/tui/hooks/useScrollback.js +29 -0
- package/packages/cli/dist/tui/hooks/useScrollback.js.map +1 -0
- package/packages/cli/dist/tui/hooks/useSession.d.ts +25 -0
- package/packages/cli/dist/tui/hooks/useSession.d.ts.map +1 -0
- package/packages/cli/dist/tui/hooks/useSession.js +36 -0
- package/packages/cli/dist/tui/hooks/useSession.js.map +1 -0
- package/packages/cli/dist/tui/hooks/useSlash.d.ts +0 -2
- package/packages/cli/dist/tui/hooks/useSlash.d.ts.map +1 -1
- package/packages/cli/dist/tui/hooks/useSlash.js +0 -1
- package/packages/cli/dist/tui/hooks/useSlash.js.map +1 -1
- package/packages/cli/dist/tui/hooks/useSpeech.d.ts +19 -0
- package/packages/cli/dist/tui/hooks/useSpeech.d.ts.map +1 -0
- package/packages/cli/dist/tui/hooks/useSpeech.js +33 -0
- package/packages/cli/dist/tui/hooks/useSpeech.js.map +1 -0
- package/packages/cli/dist/tui/hooks/useTicker.d.ts +13 -0
- package/packages/cli/dist/tui/hooks/useTicker.d.ts.map +1 -0
- package/packages/cli/dist/tui/hooks/useTicker.js +24 -0
- package/packages/cli/dist/tui/hooks/useTicker.js.map +1 -0
- package/packages/cli/dist/tui/hooks/useTurn.d.ts +4 -4
- package/packages/cli/dist/tui/hooks/useTurn.d.ts.map +1 -1
- package/packages/cli/dist/tui/hooks/useTurn.js +167 -289
- package/packages/cli/dist/tui/hooks/useTurn.js.map +1 -1
- package/packages/cli/dist/tui/hooks/useWatch.d.ts.map +1 -1
- package/packages/cli/dist/tui/hooks/useWatch.js +15 -48
- package/packages/cli/dist/tui/hooks/useWatch.js.map +1 -1
- package/packages/cli/dist/tui/inkTheme.d.ts.map +1 -1
- package/packages/cli/dist/tui/inkTheme.js +9 -11
- package/packages/cli/dist/tui/inkTheme.js.map +1 -1
- package/packages/cli/dist/tui/theme.d.ts +7 -13
- package/packages/cli/dist/tui/theme.d.ts.map +1 -1
- package/packages/cli/dist/tui/theme.js +18 -15
- package/packages/cli/dist/tui/theme.js.map +1 -1
- package/packages/cli/dist/tui/types.d.ts +10 -23
- package/packages/cli/dist/tui/types.d.ts.map +1 -1
- package/packages/cli/dist/tui/types.js +13 -31
- package/packages/cli/dist/tui/types.js.map +1 -1
- package/packages/cli/dist/ui/modelNames.d.ts.map +1 -1
- package/packages/cli/dist/ui/modelNames.js +45 -37
- package/packages/cli/dist/ui/modelNames.js.map +1 -1
- package/packages/cli/dist/ui/render.d.ts +32 -14
- package/packages/cli/dist/ui/render.d.ts.map +1 -1
- package/packages/cli/dist/ui/render.js +155 -98
- package/packages/cli/dist/ui/render.js.map +1 -1
- package/packages/cli/dist/ui/speech.d.ts +4 -7
- package/packages/cli/dist/ui/speech.d.ts.map +1 -1
- package/packages/cli/dist/ui/speech.js +37 -51
- package/packages/cli/dist/ui/speech.js.map +1 -1
- package/packages/cli/dist/ui/spinner.d.ts +1 -4
- package/packages/cli/dist/ui/spinner.d.ts.map +1 -1
- package/packages/cli/dist/ui/spinner.js +1 -12
- package/packages/cli/dist/ui/spinner.js.map +1 -1
- package/packages/cli/package.json +1 -1
- package/packages/core/dist/agents/persona.d.ts.map +1 -1
- package/packages/core/dist/agents/persona.js +27 -11
- package/packages/core/dist/agents/persona.js.map +1 -1
- package/packages/core/dist/assistant/board-watch.d.ts +72 -0
- package/packages/core/dist/assistant/board-watch.d.ts.map +1 -0
- package/packages/core/dist/assistant/board-watch.js +224 -0
- package/packages/core/dist/assistant/board-watch.js.map +1 -0
- package/packages/core/dist/assistant/chat-turn.d.ts +14 -0
- package/packages/core/dist/assistant/chat-turn.d.ts.map +1 -0
- package/packages/core/dist/assistant/chat-turn.js +159 -0
- package/packages/core/dist/assistant/chat-turn.js.map +1 -0
- package/packages/core/dist/assistant/dream-recorder.d.ts +74 -0
- package/packages/core/dist/assistant/dream-recorder.d.ts.map +1 -0
- package/packages/core/dist/assistant/dream-recorder.js +282 -0
- package/packages/core/dist/assistant/dream-recorder.js.map +1 -0
- package/packages/core/dist/assistant/headless-turn.d.ts +17 -0
- package/packages/core/dist/assistant/headless-turn.d.ts.map +1 -0
- package/packages/core/dist/assistant/headless-turn.js +330 -0
- package/packages/core/dist/assistant/headless-turn.js.map +1 -0
- package/packages/core/dist/assistant/journalled-turn.d.ts +39 -0
- package/packages/core/dist/assistant/journalled-turn.d.ts.map +1 -0
- package/packages/core/dist/assistant/journalled-turn.js +75 -0
- package/packages/core/dist/assistant/journalled-turn.js.map +1 -0
- package/packages/core/dist/assistant/memory-learning.d.ts +27 -0
- package/packages/core/dist/assistant/memory-learning.d.ts.map +1 -0
- package/packages/core/dist/assistant/memory-learning.js +82 -0
- package/packages/core/dist/assistant/memory-learning.js.map +1 -0
- package/packages/core/dist/assistant/promotion-notice.d.ts +14 -0
- package/packages/core/dist/assistant/promotion-notice.d.ts.map +1 -0
- package/packages/core/dist/assistant/promotion-notice.js +33 -0
- package/packages/core/dist/assistant/promotion-notice.js.map +1 -0
- package/packages/core/dist/assistant/scheduled-runs.d.ts +30 -0
- package/packages/core/dist/assistant/scheduled-runs.d.ts.map +1 -0
- package/packages/core/dist/assistant/scheduled-runs.js +184 -0
- package/packages/core/dist/assistant/scheduled-runs.js.map +1 -0
- package/packages/core/dist/assistant/sessions.d.ts +44 -0
- package/packages/core/dist/assistant/sessions.d.ts.map +1 -0
- package/packages/core/dist/assistant/sessions.js +75 -0
- package/packages/core/dist/assistant/sessions.js.map +1 -0
- package/packages/core/dist/assistant/terminal-turn.d.ts +18 -0
- package/packages/core/dist/assistant/terminal-turn.d.ts.map +1 -0
- package/packages/core/dist/assistant/terminal-turn.js +228 -0
- package/packages/core/dist/assistant/terminal-turn.js.map +1 -0
- package/packages/core/dist/assistant/terminals.d.ts +91 -0
- package/packages/core/dist/assistant/terminals.d.ts.map +1 -0
- package/packages/core/dist/assistant/terminals.js +266 -0
- package/packages/core/dist/assistant/terminals.js.map +1 -0
- package/packages/core/dist/assistant/turn-support.d.ts +109 -0
- package/packages/core/dist/assistant/turn-support.d.ts.map +1 -0
- package/packages/core/dist/assistant/turn-support.js +80 -0
- package/packages/core/dist/assistant/turn-support.js.map +1 -0
- package/packages/core/dist/assistant/turn-transcript.d.ts +44 -0
- package/packages/core/dist/assistant/turn-transcript.d.ts.map +1 -0
- package/packages/core/dist/assistant/turn-transcript.js +82 -0
- package/packages/core/dist/assistant/turn-transcript.js.map +1 -0
- package/packages/core/dist/assistant/types.d.ts +120 -0
- package/packages/core/dist/assistant/types.d.ts.map +1 -0
- package/packages/core/dist/assistant/types.js +2 -0
- package/packages/core/dist/assistant/types.js.map +1 -0
- package/packages/core/dist/computer/accessibility.d.ts.map +1 -1
- package/packages/core/dist/computer/accessibility.js +40 -35
- package/packages/core/dist/computer/accessibility.js.map +1 -1
- package/packages/core/dist/computer/mcp-server.js +426 -364
- package/packages/core/dist/computer/mcp-server.js.map +1 -1
- package/packages/core/dist/computer/powershell.d.ts.map +1 -1
- package/packages/core/dist/computer/powershell.js +25 -16
- package/packages/core/dist/computer/powershell.js.map +1 -1
- package/packages/core/dist/computer/screen-text.d.ts.map +1 -1
- package/packages/core/dist/computer/screen-text.js +54 -34
- package/packages/core/dist/computer/screen-text.js.map +1 -1
- package/packages/core/dist/computer/sketch.d.ts.map +1 -1
- package/packages/core/dist/computer/sketch.js +185 -128
- package/packages/core/dist/computer/sketch.js.map +1 -1
- package/packages/core/dist/computer/tools.d.ts +2 -0
- package/packages/core/dist/computer/tools.d.ts.map +1 -1
- package/packages/core/dist/computer/tools.js +31 -27
- package/packages/core/dist/computer/tools.js.map +1 -1
- package/packages/core/dist/computer/validation.d.ts +16 -16
- package/packages/core/dist/computer/validation.d.ts.map +1 -1
- package/packages/core/dist/computer/validation.js +28 -20
- package/packages/core/dist/computer/validation.js.map +1 -1
- package/packages/core/dist/config.d.ts +10 -1
- package/packages/core/dist/config.d.ts.map +1 -1
- package/packages/core/dist/config.js +81 -26
- package/packages/core/dist/config.js.map +1 -1
- package/packages/core/dist/cron/parse.d.ts.map +1 -1
- package/packages/core/dist/cron/parse.js +90 -77
- package/packages/core/dist/cron/parse.js.map +1 -1
- package/packages/core/dist/cron/scheduler.d.ts.map +1 -1
- package/packages/core/dist/cron/scheduler.js +99 -65
- package/packages/core/dist/cron/scheduler.js.map +1 -1
- package/packages/core/dist/cron/script.d.ts.map +1 -1
- package/packages/core/dist/cron/script.js +72 -42
- package/packages/core/dist/cron/script.js.map +1 -1
- package/packages/core/dist/external/claude-code.d.ts.map +1 -1
- package/packages/core/dist/external/claude-code.js +41 -28
- package/packages/core/dist/external/claude-code.js.map +1 -1
- package/packages/core/dist/external/discovery.d.ts.map +1 -1
- package/packages/core/dist/external/discovery.js +14 -11
- package/packages/core/dist/external/discovery.js.map +1 -1
- package/packages/core/dist/external/shared.d.ts +20 -0
- package/packages/core/dist/external/shared.d.ts.map +1 -1
- package/packages/core/dist/external/shared.js +97 -81
- package/packages/core/dist/external/shared.js.map +1 -1
- package/packages/core/dist/gateway/policy.d.ts.map +1 -1
- package/packages/core/dist/gateway/policy.js +5 -2
- package/packages/core/dist/gateway/policy.js.map +1 -1
- package/packages/core/dist/logger.d.ts.map +1 -1
- package/packages/core/dist/logger.js +11 -11
- package/packages/core/dist/logger.js.map +1 -1
- package/packages/core/dist/memory/db.d.ts.map +1 -1
- package/packages/core/dist/memory/db.js +175 -226
- package/packages/core/dist/memory/db.js.map +1 -1
- package/packages/core/dist/memory/dream/admission.d.ts +5 -0
- package/packages/core/dist/memory/dream/admission.d.ts.map +1 -1
- package/packages/core/dist/memory/dream/admission.js +8 -14
- package/packages/core/dist/memory/dream/admission.js.map +1 -1
- package/packages/core/dist/memory/dream/candidate.d.ts.map +1 -1
- package/packages/core/dist/memory/dream/candidate.js +119 -92
- package/packages/core/dist/memory/dream/candidate.js.map +1 -1
- package/packages/core/dist/memory/dream/evaluate.d.ts +13 -4
- package/packages/core/dist/memory/dream/evaluate.d.ts.map +1 -1
- package/packages/core/dist/memory/dream/evaluate.js +264 -288
- package/packages/core/dist/memory/dream/evaluate.js.map +1 -1
- package/packages/core/dist/memory/dream/frame.d.ts +6 -0
- package/packages/core/dist/memory/dream/frame.d.ts.map +1 -1
- package/packages/core/dist/memory/dream/frame.js +137 -91
- package/packages/core/dist/memory/dream/frame.js.map +1 -1
- package/packages/core/dist/memory/dream/label.d.ts.map +1 -1
- package/packages/core/dist/memory/dream/label.js +6 -9
- package/packages/core/dist/memory/dream/label.js.map +1 -1
- package/packages/core/dist/memory/dream/measure.d.ts +4 -0
- package/packages/core/dist/memory/dream/measure.d.ts.map +1 -1
- package/packages/core/dist/memory/dream/measure.js +13 -58
- package/packages/core/dist/memory/dream/measure.js.map +1 -1
- package/packages/core/dist/memory/dream/policy.d.ts.map +1 -1
- package/packages/core/dist/memory/dream/policy.js +4 -2
- package/packages/core/dist/memory/dream/policy.js.map +1 -1
- package/packages/core/dist/memory/dream/probe.d.ts +31 -4
- package/packages/core/dist/memory/dream/probe.d.ts.map +1 -1
- package/packages/core/dist/memory/dream/probe.js +290 -289
- package/packages/core/dist/memory/dream/probe.js.map +1 -1
- package/packages/core/dist/memory/dream/promote.d.ts.map +1 -1
- package/packages/core/dist/memory/dream/promote.js +10 -11
- package/packages/core/dist/memory/dream/promote.js.map +1 -1
- package/packages/core/dist/memory/dream/score.d.ts +9 -0
- package/packages/core/dist/memory/dream/score.d.ts.map +1 -1
- package/packages/core/dist/memory/dream/score.js +6 -7
- package/packages/core/dist/memory/dream/score.js.map +1 -1
- package/packages/core/dist/memory/dream/slots.d.ts.map +1 -1
- package/packages/core/dist/memory/dream/slots.js +0 -0
- package/packages/core/dist/memory/dream/slots.js.map +1 -1
- package/packages/core/dist/memory/dream/trajectory.d.ts.map +1 -1
- package/packages/core/dist/memory/dream/trajectory.js +76 -53
- package/packages/core/dist/memory/dream/trajectory.js.map +1 -1
- package/packages/core/dist/memory/dream/util.d.ts +44 -0
- package/packages/core/dist/memory/dream/util.d.ts.map +1 -0
- package/packages/core/dist/memory/dream/util.js +83 -0
- package/packages/core/dist/memory/dream/util.js.map +1 -0
- package/packages/core/dist/memory/extractor.d.ts.map +1 -1
- package/packages/core/dist/memory/extractor.js +67 -46
- package/packages/core/dist/memory/extractor.js.map +1 -1
- package/packages/core/dist/memory/gate.d.ts.map +1 -1
- package/packages/core/dist/memory/gate.js +55 -44
- package/packages/core/dist/memory/gate.js.map +1 -1
- package/packages/core/dist/memory/recall.d.ts +1 -1
- package/packages/core/dist/memory/recall.d.ts.map +1 -1
- package/packages/core/dist/memory/recall.js +55 -43
- package/packages/core/dist/memory/recall.js.map +1 -1
- package/packages/core/dist/memory/sleep-dream.d.ts +210 -0
- package/packages/core/dist/memory/sleep-dream.d.ts.map +1 -0
- package/packages/core/dist/memory/sleep-dream.js +1109 -0
- package/packages/core/dist/memory/sleep-dream.js.map +1 -0
- package/packages/core/dist/memory/sleep-frames.d.ts +40 -0
- package/packages/core/dist/memory/sleep-frames.d.ts.map +1 -0
- package/packages/core/dist/memory/sleep-frames.js +127 -0
- package/packages/core/dist/memory/sleep-frames.js.map +1 -0
- package/packages/core/dist/memory/sleep-limits.d.ts +18 -0
- package/packages/core/dist/memory/sleep-limits.d.ts.map +1 -0
- package/packages/core/dist/memory/sleep-limits.js +34 -0
- package/packages/core/dist/memory/sleep-limits.js.map +1 -0
- package/packages/core/dist/memory/sleep-model.d.ts +36 -0
- package/packages/core/dist/memory/sleep-model.d.ts.map +1 -0
- package/packages/core/dist/memory/sleep-model.js +80 -0
- package/packages/core/dist/memory/sleep-model.js.map +1 -0
- package/packages/core/dist/memory/sleep-policy.d.ts +19 -0
- package/packages/core/dist/memory/sleep-policy.d.ts.map +1 -0
- package/packages/core/dist/memory/sleep-policy.js +79 -0
- package/packages/core/dist/memory/sleep-policy.js.map +1 -0
- package/packages/core/dist/memory/sleep-prompts.d.ts +15 -0
- package/packages/core/dist/memory/sleep-prompts.d.ts.map +1 -0
- package/packages/core/dist/memory/sleep-prompts.js +212 -0
- package/packages/core/dist/memory/sleep-prompts.js.map +1 -0
- package/packages/core/dist/memory/sleep-report.d.ts +63 -0
- package/packages/core/dist/memory/sleep-report.d.ts.map +1 -0
- package/packages/core/dist/memory/sleep-report.js +97 -0
- package/packages/core/dist/memory/sleep-report.js.map +1 -0
- package/packages/core/dist/memory/sleep-verdicts.d.ts +77 -0
- package/packages/core/dist/memory/sleep-verdicts.d.ts.map +1 -0
- package/packages/core/dist/memory/sleep-verdicts.js +198 -0
- package/packages/core/dist/memory/sleep-verdicts.js.map +1 -0
- package/packages/core/dist/memory/sleep.d.ts +6 -61
- package/packages/core/dist/memory/sleep.d.ts.map +1 -1
- package/packages/core/dist/memory/sleep.js +1099 -2458
- package/packages/core/dist/memory/sleep.js.map +1 -1
- package/packages/core/dist/memory/store-rows.d.ts +43 -0
- package/packages/core/dist/memory/store-rows.d.ts.map +1 -0
- package/packages/core/dist/memory/store-rows.js +330 -0
- package/packages/core/dist/memory/store-rows.js.map +1 -0
- package/packages/core/dist/memory/store.d.ts +34 -20
- package/packages/core/dist/memory/store.d.ts.map +1 -1
- package/packages/core/dist/memory/store.js +634 -861
- package/packages/core/dist/memory/store.js.map +1 -1
- package/packages/core/dist/migration-cron.d.ts +2 -1
- package/packages/core/dist/migration-cron.d.ts.map +1 -1
- package/packages/core/dist/migration-cron.js +197 -154
- package/packages/core/dist/migration-cron.js.map +1 -1
- package/packages/core/dist/migration-scripts.d.ts +11 -3
- package/packages/core/dist/migration-scripts.d.ts.map +1 -1
- package/packages/core/dist/migration-scripts.js +81 -61
- package/packages/core/dist/migration-scripts.js.map +1 -1
- package/packages/core/dist/migration-shared.d.ts +9 -0
- package/packages/core/dist/migration-shared.d.ts.map +1 -0
- package/packages/core/dist/migration-shared.js +16 -0
- package/packages/core/dist/migration-shared.js.map +1 -0
- package/packages/core/dist/migration.d.ts.map +1 -1
- package/packages/core/dist/migration.js +150 -111
- package/packages/core/dist/migration.js.map +1 -1
- package/packages/core/dist/org/assignment-log.d.ts +28 -0
- package/packages/core/dist/org/assignment-log.d.ts.map +1 -0
- package/packages/core/dist/org/assignment-log.js +86 -0
- package/packages/core/dist/org/assignment-log.js.map +1 -0
- package/packages/core/dist/org/bridge.d.ts.map +1 -1
- package/packages/core/dist/org/bridge.js +32 -30
- package/packages/core/dist/org/bridge.js.map +1 -1
- package/packages/core/dist/org/controller.d.ts +18 -21
- package/packages/core/dist/org/controller.d.ts.map +1 -1
- package/packages/core/dist/org/controller.js +2042 -1848
- package/packages/core/dist/org/controller.js.map +1 -1
- package/packages/core/dist/org/json-reply.d.ts +6 -0
- package/packages/core/dist/org/json-reply.d.ts.map +1 -0
- package/packages/core/dist/org/json-reply.js +23 -0
- package/packages/core/dist/org/json-reply.js.map +1 -0
- package/packages/core/dist/org/mcp-bridge.js +34 -26
- package/packages/core/dist/org/mcp-bridge.js.map +1 -1
- package/packages/core/dist/org/planner.d.ts.map +1 -1
- package/packages/core/dist/org/planner.js +38 -42
- package/packages/core/dist/org/planner.js.map +1 -1
- package/packages/core/dist/org/project-mcp.d.ts.map +1 -1
- package/packages/core/dist/org/project-mcp.js +2 -5
- package/packages/core/dist/org/project-mcp.js.map +1 -1
- package/packages/core/dist/org/prompts.d.ts.map +1 -1
- package/packages/core/dist/org/prompts.js +176 -156
- package/packages/core/dist/org/prompts.js.map +1 -1
- package/packages/core/dist/org/questions.d.ts.map +1 -1
- package/packages/core/dist/org/questions.js +19 -14
- package/packages/core/dist/org/questions.js.map +1 -1
- package/packages/core/dist/org/review.d.ts.map +1 -1
- package/packages/core/dist/org/review.js +27 -43
- package/packages/core/dist/org/review.js.map +1 -1
- package/packages/core/dist/org/store.d.ts +19 -32
- package/packages/core/dist/org/store.d.ts.map +1 -1
- package/packages/core/dist/org/store.js +250 -206
- package/packages/core/dist/org/store.js.map +1 -1
- package/packages/core/dist/org/tool-args.d.ts +54 -0
- package/packages/core/dist/org/tool-args.d.ts.map +1 -0
- package/packages/core/dist/org/tool-args.js +104 -0
- package/packages/core/dist/org/tool-args.js.map +1 -0
- package/packages/core/dist/org/tools.d.ts.map +1 -1
- package/packages/core/dist/org/tools.js +238 -443
- package/packages/core/dist/org/tools.js.map +1 -1
- package/packages/core/dist/profile.d.ts.map +1 -1
- package/packages/core/dist/profile.js +114 -57
- package/packages/core/dist/profile.js.map +1 -1
- package/packages/core/dist/providers/catalogue.d.ts.map +1 -1
- package/packages/core/dist/providers/catalogue.js +89 -60
- package/packages/core/dist/providers/catalogue.js.map +1 -1
- package/packages/core/dist/providers/claude-code.d.ts.map +1 -1
- package/packages/core/dist/providers/claude-code.js +418 -357
- package/packages/core/dist/providers/claude-code.js.map +1 -1
- package/packages/core/dist/providers/claude-tui.d.ts +13 -9
- package/packages/core/dist/providers/claude-tui.d.ts.map +1 -1
- package/packages/core/dist/providers/claude-tui.js +568 -396
- package/packages/core/dist/providers/claude-tui.js.map +1 -1
- package/packages/core/dist/providers/codex-auth.d.ts +3 -0
- package/packages/core/dist/providers/codex-auth.d.ts.map +1 -1
- package/packages/core/dist/providers/codex-auth.js +9 -7
- package/packages/core/dist/providers/codex-auth.js.map +1 -1
- package/packages/core/dist/providers/codex-bridge.d.ts +24 -7
- package/packages/core/dist/providers/codex-bridge.d.ts.map +1 -1
- package/packages/core/dist/providers/codex-bridge.js +128 -168
- package/packages/core/dist/providers/codex-bridge.js.map +1 -1
- package/packages/core/dist/providers/codex-translate.d.ts.map +1 -1
- package/packages/core/dist/providers/codex-translate.js +195 -197
- package/packages/core/dist/providers/codex-translate.js.map +1 -1
- package/packages/core/dist/providers/loopback-server.d.ts +33 -0
- package/packages/core/dist/providers/loopback-server.d.ts.map +1 -0
- package/packages/core/dist/providers/loopback-server.js +104 -0
- package/packages/core/dist/providers/loopback-server.js.map +1 -0
- package/packages/core/dist/providers/model-gateway.d.ts +2 -4
- package/packages/core/dist/providers/model-gateway.d.ts.map +1 -1
- package/packages/core/dist/providers/model-gateway.js +39 -75
- package/packages/core/dist/providers/model-gateway.js.map +1 -1
- package/packages/core/dist/providers/process.d.ts.map +1 -1
- package/packages/core/dist/providers/process.js +32 -23
- package/packages/core/dist/providers/process.js.map +1 -1
- package/packages/core/dist/providers/provider-catalog.d.ts.map +1 -1
- package/packages/core/dist/providers/provider-catalog.js +21 -23
- package/packages/core/dist/providers/provider-catalog.js.map +1 -1
- package/packages/core/dist/providers/quota.d.ts.map +1 -1
- package/packages/core/dist/providers/quota.js +37 -37
- package/packages/core/dist/providers/quota.js.map +1 -1
- package/packages/core/dist/providers/registry.d.ts.map +1 -1
- package/packages/core/dist/providers/registry.js +3 -1
- package/packages/core/dist/providers/registry.js.map +1 -1
- package/packages/core/dist/providers/user-settings-guard.d.ts.map +1 -1
- package/packages/core/dist/providers/user-settings-guard.js +7 -2
- package/packages/core/dist/providers/user-settings-guard.js.map +1 -1
- package/packages/core/dist/runtime.d.ts +45 -158
- package/packages/core/dist/runtime.d.ts.map +1 -1
- package/packages/core/dist/runtime.js +184 -1701
- package/packages/core/dist/runtime.js.map +1 -1
- package/packages/core/dist/skills/import.d.ts.map +1 -1
- package/packages/core/dist/skills/import.js +52 -36
- package/packages/core/dist/skills/import.js.map +1 -1
- package/packages/core/dist/skills/shelf.d.ts +14 -0
- package/packages/core/dist/skills/shelf.d.ts.map +1 -1
- package/packages/core/dist/skills/shelf.js +2 -3
- package/packages/core/dist/skills/shelf.js.map +1 -1
- package/packages/core/dist/skills/store.d.ts +2 -0
- package/packages/core/dist/skills/store.d.ts.map +1 -1
- package/packages/core/dist/skills/store.js +17 -12
- package/packages/core/dist/skills/store.js.map +1 -1
- package/packages/core/dist/tools/catalog.d.ts +13 -0
- package/packages/core/dist/tools/catalog.d.ts.map +1 -1
- package/packages/core/dist/tools/catalog.js +20 -5
- package/packages/core/dist/tools/catalog.js.map +1 -1
- package/packages/core/dist/tools/hub.d.ts +4 -1
- package/packages/core/dist/tools/hub.d.ts.map +1 -1
- package/packages/core/dist/tools/hub.js +114 -83
- package/packages/core/dist/tools/hub.js.map +1 -1
- package/packages/core/dist/turns/journal.d.ts.map +1 -1
- package/packages/core/dist/turns/journal.js +12 -18
- package/packages/core/dist/turns/journal.js.map +1 -1
- package/packages/core/dist/types.d.ts +25 -3
- package/packages/core/dist/types.d.ts.map +1 -1
- package/packages/core/dist/types.js.map +1 -1
- package/packages/core/dist/util/blocks.d.ts.map +1 -1
- package/packages/core/dist/util/blocks.js +14 -22
- package/packages/core/dist/util/blocks.js.map +1 -1
- package/packages/core/dist/util/queue.d.ts +0 -2
- package/packages/core/dist/util/queue.d.ts.map +1 -1
- package/packages/core/dist/util/queue.js +0 -6
- package/packages/core/dist/util/queue.js.map +1 -1
- package/packages/core/package.json +1 -1
- package/packages/server/dist/auth.d.ts +27 -9
- package/packages/server/dist/auth.d.ts.map +1 -1
- package/packages/server/dist/auth.js +73 -15
- package/packages/server/dist/auth.js.map +1 -1
- package/packages/server/dist/env.d.ts.map +1 -1
- package/packages/server/dist/env.js +18 -15
- package/packages/server/dist/env.js.map +1 -1
- package/packages/server/dist/errors.d.ts +3 -0
- package/packages/server/dist/errors.d.ts.map +1 -0
- package/packages/server/dist/errors.js +5 -0
- package/packages/server/dist/errors.js.map +1 -0
- package/packages/server/dist/gateways/attachments.d.ts.map +1 -1
- package/packages/server/dist/gateways/attachments.js +38 -21
- package/packages/server/dist/gateways/attachments.js.map +1 -1
- package/packages/server/dist/gateways/markdown.d.ts.map +1 -1
- package/packages/server/dist/gateways/markdown.js +30 -12
- package/packages/server/dist/gateways/markdown.js.map +1 -1
- package/packages/server/dist/gateways/push.d.ts +6 -6
- package/packages/server/dist/gateways/push.d.ts.map +1 -1
- package/packages/server/dist/gateways/push.js +101 -74
- package/packages/server/dist/gateways/push.js.map +1 -1
- package/packages/server/dist/gateways/telegram-api.d.ts.map +1 -1
- package/packages/server/dist/gateways/telegram-api.js +61 -44
- package/packages/server/dist/gateways/telegram-api.js.map +1 -1
- package/packages/server/dist/gateways/telegram.d.ts +5 -0
- package/packages/server/dist/gateways/telegram.d.ts.map +1 -1
- package/packages/server/dist/gateways/telegram.js +985 -753
- package/packages/server/dist/gateways/telegram.js.map +1 -1
- package/packages/server/dist/gateways/threads.d.ts.map +1 -1
- package/packages/server/dist/gateways/threads.js +144 -130
- package/packages/server/dist/gateways/threads.js.map +1 -1
- package/packages/server/dist/listeners/imap.d.ts.map +1 -1
- package/packages/server/dist/listeners/imap.js +0 -0
- package/packages/server/dist/listeners/imap.js.map +1 -1
- package/packages/server/dist/listeners/registry.d.ts.map +1 -1
- package/packages/server/dist/listeners/registry.js +15 -15
- package/packages/server/dist/listeners/registry.js.map +1 -1
- package/packages/server/dist/main.js +3 -2
- package/packages/server/dist/main.js.map +1 -1
- package/packages/server/dist/routes/chat.d.ts.map +1 -1
- package/packages/server/dist/routes/chat.js +5 -8
- package/packages/server/dist/routes/chat.js.map +1 -1
- package/packages/server/dist/routes/config.d.ts +6 -0
- package/packages/server/dist/routes/config.d.ts.map +1 -1
- package/packages/server/dist/routes/config.js +34 -31
- package/packages/server/dist/routes/config.js.map +1 -1
- package/packages/server/dist/routes/cron.d.ts.map +1 -1
- package/packages/server/dist/routes/cron.js +33 -23
- package/packages/server/dist/routes/cron.js.map +1 -1
- package/packages/server/dist/routes/dream.d.ts +1 -1
- package/packages/server/dist/routes/dream.d.ts.map +1 -1
- package/packages/server/dist/routes/dream.js +16 -34
- package/packages/server/dist/routes/dream.js.map +1 -1
- package/packages/server/dist/routes/gateways.d.ts.map +1 -1
- package/packages/server/dist/routes/gateways.js +8 -13
- package/packages/server/dist/routes/gateways.js.map +1 -1
- package/packages/server/dist/routes/memories.d.ts.map +1 -1
- package/packages/server/dist/routes/memories.js +16 -29
- package/packages/server/dist/routes/memories.js.map +1 -1
- package/packages/server/dist/routes/night.d.ts +31 -0
- package/packages/server/dist/routes/night.d.ts.map +1 -0
- package/packages/server/dist/routes/night.js +28 -0
- package/packages/server/dist/routes/night.js.map +1 -0
- package/packages/server/dist/routes/org.d.ts.map +1 -1
- package/packages/server/dist/routes/org.js +125 -119
- package/packages/server/dist/routes/org.js.map +1 -1
- package/packages/server/dist/routes/profile.d.ts.map +1 -1
- package/packages/server/dist/routes/profile.js +5 -6
- package/packages/server/dist/routes/profile.js.map +1 -1
- package/packages/server/dist/routes/providers.d.ts.map +1 -1
- package/packages/server/dist/routes/providers.js +1 -3
- package/packages/server/dist/routes/providers.js.map +1 -1
- package/packages/server/dist/routes/query.d.ts +10 -0
- package/packages/server/dist/routes/query.d.ts.map +1 -0
- package/packages/server/dist/routes/query.js +17 -0
- package/packages/server/dist/routes/query.js.map +1 -0
- package/packages/server/dist/routes/questions.d.ts.map +1 -1
- package/packages/server/dist/routes/questions.js +5 -11
- package/packages/server/dist/routes/questions.js.map +1 -1
- package/packages/server/dist/routes/sessions.d.ts.map +1 -1
- package/packages/server/dist/routes/sessions.js +20 -28
- package/packages/server/dist/routes/sessions.js.map +1 -1
- package/packages/server/dist/routes/sleep.d.ts.map +1 -1
- package/packages/server/dist/routes/sleep.js +21 -36
- package/packages/server/dist/routes/sleep.js.map +1 -1
- package/packages/server/dist/routes/stats.d.ts.map +1 -1
- package/packages/server/dist/routes/stats.js +2 -7
- package/packages/server/dist/routes/stats.js.map +1 -1
- package/packages/server/dist/routes/terminals.d.ts.map +1 -1
- package/packages/server/dist/routes/terminals.js +19 -14
- package/packages/server/dist/routes/terminals.js.map +1 -1
- package/packages/server/dist/routes/tools.d.ts.map +1 -1
- package/packages/server/dist/routes/tools.js +9 -5
- package/packages/server/dist/routes/tools.js.map +1 -1
- package/packages/server/dist/routes/ws.d.ts.map +1 -1
- package/packages/server/dist/routes/ws.js +235 -207
- package/packages/server/dist/routes/ws.js.map +1 -1
- package/packages/server/dist/schemas.d.ts +30 -21
- package/packages/server/dist/schemas.d.ts.map +1 -1
- package/packages/server/dist/schemas.js +3 -2
- package/packages/server/dist/schemas.js.map +1 -1
- package/packages/server/dist/server.d.ts.map +1 -1
- package/packages/server/dist/server.js +257 -238
- package/packages/server/dist/server.js.map +1 -1
- package/packages/server/dist/services/stream.d.ts.map +1 -1
- package/packages/server/dist/services/stream.js +6 -4
- package/packages/server/dist/services/stream.js.map +1 -1
- package/packages/server/dist/services/stt.d.ts +1 -1
- package/packages/server/dist/services/stt.d.ts.map +1 -1
- package/packages/server/dist/services/stt.js +175 -124
- package/packages/server/dist/services/stt.js.map +1 -1
- package/packages/server/dist/services/tts.d.ts.map +1 -1
- package/packages/server/dist/services/tts.js +82 -54
- package/packages/server/dist/services/tts.js.map +1 -1
- package/packages/server/dist/services/turns.d.ts +8 -6
- package/packages/server/dist/services/turns.d.ts.map +1 -1
- package/packages/server/dist/services/turns.js +36 -32
- package/packages/server/dist/services/turns.js.map +1 -1
- package/packages/server/dist/services/updates.d.ts +1 -0
- package/packages/server/dist/services/updates.d.ts.map +1 -1
- package/packages/server/dist/services/updates.js +150 -91
- package/packages/server/dist/services/updates.js.map +1 -1
- package/packages/server/dist/services/voice-keys.d.ts.map +1 -1
- package/packages/server/dist/services/voice-keys.js +4 -2
- package/packages/server/dist/services/voice-keys.js.map +1 -1
- package/packages/server/dist/static.d.ts +1 -1
- package/packages/server/dist/static.d.ts.map +1 -1
- package/packages/server/dist/static.js +7 -7
- package/packages/server/dist/static.js.map +1 -1
- package/packages/server/package.json +1 -1
- package/packages/web/dist/assets/{abnfDiagram-O67JEVCF-D7YyFndQ.js → abnfDiagram-O67JEVCF-BmjzYusK.js} +1 -1
- package/packages/web/dist/assets/{arc-C_Zgk2dJ.js → arc-n9TPu3wY.js} +1 -1
- package/packages/web/dist/assets/{architectureDiagram-NJMV4G6O-eI0adu1B.js → architectureDiagram-NJMV4G6O-Cx9TKHMG.js} +1 -1
- package/packages/web/dist/assets/{blockDiagram-BEXU5L5S-WAoOFUA9.js → blockDiagram-BEXU5L5S-Cu2lqO0u.js} +1 -1
- package/packages/web/dist/assets/{c4Diagram-YGBWAQC7-DE8Zyhng.js → c4Diagram-YGBWAQC7-C0lage7M.js} +1 -1
- package/packages/web/dist/assets/channel-Cx64mAod.js +1 -0
- package/packages/web/dist/assets/{chunk-2Q5K7J3B-bnqLP2XD.js → chunk-2Q5K7J3B-D3aVQoie.js} +1 -1
- package/packages/web/dist/assets/{chunk-3FUC2YCW-Ck1_SVe0.js → chunk-3FUC2YCW-Cmrvpp5I.js} +2 -2
- package/packages/web/dist/assets/{chunk-5VM5RSS4-hDmC41gD.js → chunk-5VM5RSS4-Bk7nd1Or.js} +1 -1
- package/packages/web/dist/assets/{chunk-GTNCS2PH-PoWvfCrT.js → chunk-GTNCS2PH--_-V13S9.js} +1 -1
- package/packages/web/dist/assets/{chunk-GWA4HPMP-D3V0IG43.js → chunk-GWA4HPMP-B2iN_iAC.js} +1 -1
- package/packages/web/dist/assets/{chunk-JWPE2WC7-BryfpHM5.js → chunk-JWPE2WC7-BCQEdHBw.js} +1 -1
- package/packages/web/dist/assets/{chunk-NETBCI7D-8ic1iEdT.js → chunk-NETBCI7D-lKrFsR6g.js} +1 -1
- package/packages/web/dist/assets/{chunk-WEXAMYUT-nM8tmQT2.js → chunk-WEXAMYUT-Bl4c2a1n.js} +1 -1
- package/packages/web/dist/assets/{chunk-XXDRQBXY-Do28F482.js → chunk-XXDRQBXY-xvPIGObD.js} +1 -1
- package/packages/web/dist/assets/{classDiagram-v2-NBCMYWYE-Bop9oNNO.js → classDiagram-v2-NBCMYWYE-DjX85RUY.js} +1 -1
- package/packages/web/dist/assets/{cose-bilkent-JH36ORCC-a7f_bpnt.js → cose-bilkent-JH36ORCC-Dn5oYBNs.js} +1 -1
- package/packages/web/dist/assets/{cynefin-OW5HDTMX-DnArcis_.js → cynefin-OW5HDTMX-D1zN_crx.js} +1 -1
- package/packages/web/dist/assets/{cynefinDiagram-VND7K2PF-vEuTb1GD.js → cynefinDiagram-VND7K2PF-B-GwPS_J.js} +1 -1
- package/packages/web/dist/assets/{dagre-6A5THRUB-BgG4MynJ.js → dagre-6A5THRUB-C2wUvKaS.js} +1 -1
- package/packages/web/dist/assets/{diagram-22UHCM2B-DRCQpafv.js → diagram-22UHCM2B-DnZ3T6JG.js} +1 -1
- package/packages/web/dist/assets/{diagram-3UASUU5V-BKgmAXde.js → diagram-3UASUU5V-DR8pK0Yb.js} +1 -1
- package/packages/web/dist/assets/{diagram-ATOU4E4O-B6Hsy36X.js → diagram-ATOU4E4O-olswvjNy.js} +1 -1
- package/packages/web/dist/assets/{diagram-CDSNMT55-JflyfyoB.js → diagram-CDSNMT55-CkbrgFGH.js} +1 -1
- package/packages/web/dist/assets/{diagram-MLGK6HIB-Dd2QPJjT.js → diagram-MLGK6HIB-DiNLsh9k.js} +1 -1
- package/packages/web/dist/assets/{diagram-MPIPVDR6-DE5QU60x.js → diagram-MPIPVDR6-DY0eRCo8.js} +1 -1
- package/packages/web/dist/assets/{ebnfDiagram-ZINNZB2B-D7AQ741b.js → ebnfDiagram-ZINNZB2B-BwyYBste.js} +1 -1
- package/packages/web/dist/assets/{elk-276RUBZZ-CeewBVLF.js → elk-276RUBZZ-BOkb2Unt.js} +1 -1
- package/packages/web/dist/assets/{erDiagram-OPXOYQCR-mLLYkZ5c.js → erDiagram-OPXOYQCR-Bopm0hOe.js} +1 -1
- package/packages/web/dist/assets/{flowDiagram-KWPJA3E3-DtpSpsQN.js → flowDiagram-KWPJA3E3-CB8O7Rey.js} +1 -1
- package/packages/web/dist/assets/{ganttDiagram-FUAMR5RP-1_lh-3ky.js → ganttDiagram-FUAMR5RP-BMoBwxn3.js} +1 -1
- package/packages/web/dist/assets/{gitGraphDiagram-X574FWY7-DoPXZuT5.js → gitGraphDiagram-X574FWY7-r9EVynuW.js} +1 -1
- package/packages/web/dist/assets/index-BJFGaq8t.js +646 -0
- package/packages/web/dist/assets/index-BMYKZrup.css +32 -0
- package/packages/web/dist/assets/{infoDiagram-VRGFBTTK-DQpRGGiD.js → infoDiagram-VRGFBTTK-4NICTzD4.js} +1 -1
- package/packages/web/dist/assets/{ishikawaDiagram-OU5B5YK6-gH5C9Q2e.js → ishikawaDiagram-OU5B5YK6-qmYHkSam.js} +1 -1
- package/packages/web/dist/assets/{journeyDiagram-ZHPQQLJL-Bg-oeFjb.js → journeyDiagram-ZHPQQLJL-BSb6Qa2c.js} +1 -1
- package/packages/web/dist/assets/{kanban-definition-PNTS6WVX-BnpI4VH8.js → kanban-definition-PNTS6WVX-B0cwMsip.js} +1 -1
- package/packages/web/dist/assets/{mermaid.core-BwBKxlRA.js → mermaid.core-CTl4Qse1.js} +4 -4
- package/packages/web/dist/assets/{mindmap-definition-NLK3R4M7-NBnnxEoO.js → mindmap-definition-NLK3R4M7-tbJ4AKr2.js} +1 -1
- package/packages/web/dist/assets/{pegDiagram-GJSIUBJH-RrXXbIvO.js → pegDiagram-GJSIUBJH-BD50Xatx.js} +1 -1
- package/packages/web/dist/assets/{pieDiagram-5QR66LMP-B27q6Gso.js → pieDiagram-5QR66LMP-C52DU0dU.js} +1 -1
- package/packages/web/dist/assets/{quadrantDiagram-O4NWA36T-DGDsdur2.js → quadrantDiagram-O4NWA36T-Dmf0Relz.js} +1 -1
- package/packages/web/dist/assets/{railroadDiagram-XR7U4H2S-GdjkE3mI.js → railroadDiagram-XR7U4H2S-q1rW0LBx.js} +1 -1
- package/packages/web/dist/assets/{requirementDiagram-PLB6GJNP-DjK0GfgO.js → requirementDiagram-PLB6GJNP-ChTty00B.js} +1 -1
- package/packages/web/dist/assets/{sankeyDiagram-IPEJSGJF-BG_AIkwF.js → sankeyDiagram-IPEJSGJF-vRhUUtR0.js} +1 -1
- package/packages/web/dist/assets/scene-DUzELcJR.js +4620 -0
- package/packages/web/dist/assets/{sequenceDiagram-PO4LG4MO-CIQwUb4y.js → sequenceDiagram-PO4LG4MO-CJ37i6X7.js} +1 -1
- package/packages/web/dist/assets/{sizeCapture-INFHLROL-bpIoPxdJ.js → sizeCapture-INFHLROL-CUwB5IU5.js} +1 -1
- package/packages/web/dist/assets/{stateDiagram-v2-GCMORJYK-8hYXvPPv.js → stateDiagram-v2-GCMORJYK-CbmUCHZz.js} +1 -1
- package/packages/web/dist/assets/{swimlanes-2SLR337P-gfflUMF9.js → swimlanes-2SLR337P-BH1ix14-.js} +1 -1
- package/packages/web/dist/assets/swimlanesDiagram-TC7HE7FX-D1P54_6D.js +8 -0
- package/packages/web/dist/assets/{timeline-definition-EJHVYXUP-PHMNoGTZ.js → timeline-definition-EJHVYXUP-h73o8wo_.js} +1 -1
- package/packages/web/dist/assets/{usecaseDiagram-POWQR4AR-B2j5iteO.js → usecaseDiagram-POWQR4AR-BmrG9VWs.js} +1 -1
- package/packages/web/dist/assets/{vennDiagram-UO4OBE2U-BzxtZ-_2.js → vennDiagram-UO4OBE2U-Bax-03xB.js} +1 -1
- package/packages/web/dist/assets/{wardleyDiagram-VNRHLVJA-DL7YbMpY.js → wardleyDiagram-VNRHLVJA-A2y6258q.js} +1 -1
- package/packages/web/dist/assets/{xychartDiagram-PMCCYNJV-CisgP1cT.js → xychartDiagram-PMCCYNJV-BSiMaGgj.js} +1 -1
- package/packages/web/dist/index.html +2 -2
- package/packages/web/package.json +1 -1
- package/packages/web/dist/assets/channel-egZxcyUK.js +0 -1
- package/packages/web/dist/assets/index-Cw2Opmx7.js +0 -648
- package/packages/web/dist/assets/index-j0zBRCgT.css +0 -32
- package/packages/web/dist/assets/scene-D4LPicHk.js +0 -4620
- package/packages/web/dist/assets/swimlanesDiagram-TC7HE7FX-9wdzGXU-.js +0 -8
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { ASSISTANT_MEMORY_OWNER, classifyCallback, classifyUpdate, isAudible, missingGatewaySettings, nextGatewayAction, notificationReadCallbackData, notificationReadDoneCallbackData, providerQuota, questionCallbackData, questionDoneCallbackData, readCallbackData, splitMessage, } from '../../../core/dist/index.js';
|
|
2
|
-
import { localModelReady, transcribe
|
|
2
|
+
import { localModelReady, transcribe } from '../services/stt.js';
|
|
3
3
|
import { voiceKeys } from '../services/voice-keys.js';
|
|
4
4
|
import { humanDuration, humanSize, pruneInbox, saveAttachment } from './attachments.js';
|
|
5
5
|
import { toTelegramHtml } from './markdown.js';
|
|
@@ -113,7 +113,7 @@ export function questionClosedKeyboard(reason, chosen) {
|
|
|
113
113
|
*/
|
|
114
114
|
export function questionText(question) {
|
|
115
115
|
const lines = [
|
|
116
|
-
'❓ ' + oneLine(question.header,
|
|
116
|
+
'❓ ' + oneLine(question.header, QUESTION_HEADER_WIDTH),
|
|
117
117
|
'',
|
|
118
118
|
question.question.trim(),
|
|
119
119
|
'',
|
|
@@ -267,22 +267,44 @@ const ID_REPLY_INTERVAL_MS = 60 * 60 * 1000;
|
|
|
267
267
|
/** How much of a message ends up in the log. */
|
|
268
268
|
const AUDIT_TEXT = 120;
|
|
269
269
|
const REJECT_TEXT = 80;
|
|
270
|
+
/** Longest a question's header reads before it is cut. */
|
|
271
|
+
const QUESTION_HEADER_WIDTH = 80;
|
|
272
|
+
/** Longest an option label reads in the toast that confirms a tap. */
|
|
273
|
+
const TAP_TOAST_WIDTH = 60;
|
|
274
|
+
/** Widths at which one row of a list command is cut for a phone screen. */
|
|
275
|
+
const ROW_TITLE_WIDTH = 70;
|
|
276
|
+
const ROW_NAME_WIDTH = 50;
|
|
277
|
+
/** Largest file the Bot API lets a bot download, in megabytes. */
|
|
278
|
+
const BOT_API_DOWNLOAD_LIMIT_MB = 20;
|
|
279
|
+
const BYTES_PER_MB = 1024 * 1024;
|
|
280
|
+
/** Telegram deletes at most this many messages per call. */
|
|
281
|
+
const DELETE_BATCH = 100;
|
|
270
282
|
/**
|
|
271
|
-
*
|
|
272
|
-
*
|
|
273
|
-
*
|
|
274
|
-
* is applied piece by piece. `splitMessage` guarantees every piece carries
|
|
275
|
-
* balanced code fences, so each one converts on its own without the fence
|
|
276
|
-
* state of its neighbours.
|
|
283
|
+
* How long past its deadline a question's entry may linger before the next
|
|
284
|
+
* new question sweeps it. The closing event normally removes it first; this
|
|
285
|
+
* only bounds the map when that event never arrived.
|
|
277
286
|
*/
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
287
|
+
const EXPIRED_QUESTION_GRACE_MS = 60_000;
|
|
288
|
+
const MINUTE_MS = 60_000;
|
|
289
|
+
const MINUTES_PER_HOUR = 60;
|
|
290
|
+
const MINUTES_PER_DAY = 24 * MINUTES_PER_HOUR;
|
|
291
|
+
/** The guard's refusals that come before the allowlist has vouched for the sender. */
|
|
292
|
+
const STRANGER_REJECTIONS = ['not_a_message', 'bot_sender', 'not_allowed'];
|
|
293
|
+
const REASON_UNAUTHORIZED = 'Telegram rejected this bot token (401). Gateway stopped.';
|
|
294
|
+
const REASON_CONFLICT = 'Another process is polling the same bot (409). Gateway stopped.';
|
|
281
295
|
/** What Telegram accepts in one message, counted after escaping. */
|
|
282
296
|
const TELEGRAM_LIMIT = 4096;
|
|
297
|
+
/** Smallest budget a re-cut falls back to, and how often it is tried before that. */
|
|
298
|
+
const MIN_PIECE_BUDGET = 400;
|
|
299
|
+
const MAX_RECUT_ATTEMPTS = 4;
|
|
283
300
|
/**
|
|
284
301
|
* One message's worth of HTML at a time, each piece guaranteed to fit.
|
|
285
302
|
*
|
|
303
|
+
* The Markdown conversion itself lives in `markdown.ts`; what matters here
|
|
304
|
+
* is that it is applied piece by piece. `splitMessage` guarantees every
|
|
305
|
+
* piece carries balanced code fences, so each one converts on its own
|
|
306
|
+
* without the fence state of its neighbours.
|
|
307
|
+
*
|
|
286
308
|
* `splitMessage` counts the text as written, but what goes on the wire is
|
|
287
309
|
* escaped: a line of `&` grows fivefold, and a piece cut at exactly 4096
|
|
288
310
|
* characters then arrives at the API as 20 000 and is refused - which reads,
|
|
@@ -295,16 +317,16 @@ const TELEGRAM_LIMIT = 4096;
|
|
|
295
317
|
*/
|
|
296
318
|
export function htmlPieces(text) {
|
|
297
319
|
let budget = TELEGRAM_LIMIT;
|
|
298
|
-
for (let attempt = 0; attempt <
|
|
320
|
+
for (let attempt = 0; attempt < MAX_RECUT_ATTEMPTS; attempt += 1) {
|
|
299
321
|
const pieces = splitMessage(text, budget);
|
|
300
|
-
const html = pieces.map(
|
|
322
|
+
const html = pieces.map((piece) => toTelegramHtml(piece));
|
|
301
323
|
if (html.every((piece) => piece.length <= TELEGRAM_LIMIT))
|
|
302
324
|
return html;
|
|
303
325
|
// Re-cut against the worst growth actually seen, not a guess about it.
|
|
304
326
|
const growth = Math.max(...html.map((piece, index) => piece.length / Math.max(1, pieces[index]?.length ?? 1)));
|
|
305
|
-
budget = Math.max(
|
|
327
|
+
budget = Math.max(MIN_PIECE_BUDGET, Math.floor(TELEGRAM_LIMIT / growth));
|
|
306
328
|
}
|
|
307
|
-
return splitMessage(text,
|
|
329
|
+
return splitMessage(text, MIN_PIECE_BUDGET).map((piece) => toTelegramHtml(piece));
|
|
308
330
|
}
|
|
309
331
|
/**
|
|
310
332
|
* What a streamed message should say once the turn is over.
|
|
@@ -336,6 +358,10 @@ export function mergeFinalText(streamed, finalText) {
|
|
|
336
358
|
/** A sleep that neither keeps the process alive nor outlives a stop(). */
|
|
337
359
|
function delay(ms, signal) {
|
|
338
360
|
return new Promise((resolve) => {
|
|
361
|
+
if (signal.aborted) {
|
|
362
|
+
resolve();
|
|
363
|
+
return;
|
|
364
|
+
}
|
|
339
365
|
const timer = setTimeout(resolve, ms);
|
|
340
366
|
timer.unref?.();
|
|
341
367
|
signal.addEventListener('abort', () => {
|
|
@@ -360,8 +386,7 @@ function asRecord(value) {
|
|
|
360
386
|
}
|
|
361
387
|
/** The sender's username, straight out of the raw update, for the log only. */
|
|
362
388
|
function usernameOf(update) {
|
|
363
|
-
const
|
|
364
|
-
const from = message?.from;
|
|
389
|
+
const from = asRecord(asRecord(update.message)?.from);
|
|
365
390
|
return typeof from?.username === 'string' ? from.username : undefined;
|
|
366
391
|
}
|
|
367
392
|
/**
|
|
@@ -397,6 +422,309 @@ export async function answerTaskQuestion(context, asked, answer) {
|
|
|
397
422
|
return { ok: false, reason: errorText(error) };
|
|
398
423
|
}
|
|
399
424
|
}
|
|
425
|
+
/** How a file is named in the line the assistant is handed. */
|
|
426
|
+
const KIND_LABEL = {
|
|
427
|
+
photo: 'A photo',
|
|
428
|
+
voice: 'A voice message',
|
|
429
|
+
audio: 'An audio file',
|
|
430
|
+
video: 'A video',
|
|
431
|
+
video_note: 'A video note',
|
|
432
|
+
animation: 'An animation',
|
|
433
|
+
document: 'A document',
|
|
434
|
+
sticker: 'A sticker',
|
|
435
|
+
};
|
|
436
|
+
/**
|
|
437
|
+
* What an allowed sender is told when their own message was refused.
|
|
438
|
+
*
|
|
439
|
+
* Every reason in here is one the guard can only reach *after* the
|
|
440
|
+
* allowlist has said yes, in the sender's own private chat - so the
|
|
441
|
+
* silence that protects the bot from strangers buys nothing here, and
|
|
442
|
+
* costs the owner a message that seems to vanish. Everything else stays
|
|
443
|
+
* silent, `not_private` included: a word in a group chat is exactly what
|
|
444
|
+
* the guard refused to allow.
|
|
445
|
+
*/
|
|
446
|
+
const REJECTION_NOTE = {
|
|
447
|
+
forwarded: 'Forwarded messages are not accepted - they carry someone else\'s words. Send the text or the file yourself.',
|
|
448
|
+
media_off: 'Attachments are switched off for this gateway. You can turn them on in the gateway settings.',
|
|
449
|
+
unsupported_media: 'Animated and video stickers cannot be read.',
|
|
450
|
+
too_large: 'That file is larger than this gateway accepts.',
|
|
451
|
+
too_long: 'That message is too long. Shorten it, or send it as a file.',
|
|
452
|
+
no_content: 'There was nothing in that message I can work with.',
|
|
453
|
+
};
|
|
454
|
+
/** The chat a message was sent from is the sender's own private chat. */
|
|
455
|
+
function isOwnChat(verdict) {
|
|
456
|
+
return verdict.chatId !== undefined && verdict.chatId === verdict.userId;
|
|
457
|
+
}
|
|
458
|
+
/**
|
|
459
|
+
* Why a failure will not pass on its own, if it is one of the two that never
|
|
460
|
+
* do: a token Telegram does not know (401), and a second process polling the
|
|
461
|
+
* same bot (409). Anything else is weather.
|
|
462
|
+
*/
|
|
463
|
+
function hopelessReason(error) {
|
|
464
|
+
if (!(error instanceof TelegramApiError))
|
|
465
|
+
return undefined;
|
|
466
|
+
if (error.unauthorized)
|
|
467
|
+
return REASON_UNAUTHORIZED;
|
|
468
|
+
if (error.conflict)
|
|
469
|
+
return REASON_CONFLICT;
|
|
470
|
+
return undefined;
|
|
471
|
+
}
|
|
472
|
+
/** Ids from `top` downwards that go into one delete call, counting at most `CLEAR_SWEEP` back from `newest`. */
|
|
473
|
+
function sweepBatch(top, newest) {
|
|
474
|
+
const batch = [];
|
|
475
|
+
for (let id = top; id > 0 && id > top - DELETE_BATCH && newest - id < CLEAR_SWEEP; id -= 1)
|
|
476
|
+
batch.push(id);
|
|
477
|
+
return batch;
|
|
478
|
+
}
|
|
479
|
+
/** The notification the user is replying to, in the words the turn is told, unless this conversation already holds it. */
|
|
480
|
+
function quotedNotification(context, origin, fresh) {
|
|
481
|
+
if (!origin)
|
|
482
|
+
return undefined;
|
|
483
|
+
if (fresh)
|
|
484
|
+
return originContext(context, origin);
|
|
485
|
+
// A thread being continued already holds the notification in its history.
|
|
486
|
+
// A notice that never had a record is the exception: there is nothing to
|
|
487
|
+
// read back, so its own text is all the context there will ever be.
|
|
488
|
+
return origin.ref ? undefined : origin.snippet;
|
|
489
|
+
}
|
|
490
|
+
/**
|
|
491
|
+
* Whether a turn would end up listening locally, and so might have to wait
|
|
492
|
+
* for a model to be fetched. Read fresh: a key added on the voice page
|
|
493
|
+
* takes effect on the next voice note, not on the next restart.
|
|
494
|
+
*/
|
|
495
|
+
function listensLocally(context, config) {
|
|
496
|
+
if (config.transcribe === 'local')
|
|
497
|
+
return true;
|
|
498
|
+
if (config.transcribe !== 'auto')
|
|
499
|
+
return false;
|
|
500
|
+
const keys = voiceKeys(context.config.home);
|
|
501
|
+
return !keys.openai && !keys.elevenlabs;
|
|
502
|
+
}
|
|
503
|
+
/** The line a stored file becomes in the prompt: where it is, and what the assistant should do with it. */
|
|
504
|
+
function describeStoredFile(attachment, label, stored) {
|
|
505
|
+
const size = humanSize(stored.bytes);
|
|
506
|
+
switch (attachment.kind) {
|
|
507
|
+
case 'photo':
|
|
508
|
+
case 'sticker':
|
|
509
|
+
return `${label} (${size}) is at ${stored.path}. Open it with your file-reading tool before you answer; you can see images.`;
|
|
510
|
+
case 'video':
|
|
511
|
+
case 'video_note':
|
|
512
|
+
case 'animation':
|
|
513
|
+
return `${label} (${size}) is at ${stored.path}.`;
|
|
514
|
+
default: {
|
|
515
|
+
const named = attachment.fileName ? ` named “${attachment.fileName}”` : '';
|
|
516
|
+
return `${label}${named} (${size}) is at ${stored.path}. Open it before you answer.`;
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
/**
|
|
521
|
+
* The prompt for a turn that arrived with files, a quoted notification, or
|
|
522
|
+
* both.
|
|
523
|
+
*
|
|
524
|
+
* Everything the assistant did not write itself is introduced as what it
|
|
525
|
+
* is: the user's own words stand as they are, a transcript says that it is
|
|
526
|
+
* a transcript, and a quoted notification is fenced off with a line saying
|
|
527
|
+
* where it ends. None of it is trusted less for that - it is all the
|
|
528
|
+
* owner's own material - but a turn that cannot tell a notification apart from an
|
|
529
|
+
* instruction is a turn that will eventually follow the notification.
|
|
530
|
+
*/
|
|
531
|
+
function buildPrompt(job, intake, quoted) {
|
|
532
|
+
const parts = [];
|
|
533
|
+
if (quoted) {
|
|
534
|
+
parts.push('The user is replying on Telegram to this notification from Rookery:\n\n' +
|
|
535
|
+
quoted +
|
|
536
|
+
'\n\n--- end of the notification; their reply follows ---');
|
|
537
|
+
}
|
|
538
|
+
if (intake.lines.length > 0) {
|
|
539
|
+
parts.push('Sent from Telegram:\n' + intake.lines.map((line) => '- ' + line).join('\n'));
|
|
540
|
+
}
|
|
541
|
+
for (const transcript of intake.transcripts) {
|
|
542
|
+
parts.push('What they said:\n"' + transcript + '"');
|
|
543
|
+
}
|
|
544
|
+
const written = job.text?.trim();
|
|
545
|
+
if (written)
|
|
546
|
+
parts.push(intake.transcripts.length > 0 || intake.lines.length > 0 ? 'What they wrote with it:\n' + written : written);
|
|
547
|
+
// A file with nothing said about it is still a request: look at this.
|
|
548
|
+
if (parts.length === 0 || (!written && intake.transcripts.length === 0)) {
|
|
549
|
+
parts.push('They sent this without saying anything. Look at it and say what you make of it.');
|
|
550
|
+
}
|
|
551
|
+
return parts.join('\n\n');
|
|
552
|
+
}
|
|
553
|
+
/* ------------------- the conversation behind a chat ------------------- */
|
|
554
|
+
const sessionChatKey = (sessionId) => 'telegram:session:' + sessionId;
|
|
555
|
+
/** A conversation of its own for this chat, replacing whichever it had. */
|
|
556
|
+
function startChatSession(context, chatId) {
|
|
557
|
+
const session = context.assistant.createSession({ title: 'Telegram', kind: 'chat' });
|
|
558
|
+
context.assistant.store.setMeta(`telegram:chat:${chatId}`, session.id);
|
|
559
|
+
return session;
|
|
560
|
+
}
|
|
561
|
+
/**
|
|
562
|
+
* The conversation behind a chat. Deliberately an ordinary `chat` session
|
|
563
|
+
* rather than a kind of its own, so what was said from the phone shows up
|
|
564
|
+
* in the same sidebar as everything else.
|
|
565
|
+
*/
|
|
566
|
+
function chatSession(context, chatId) {
|
|
567
|
+
const known = context.assistant.store.getMeta(`telegram:chat:${chatId}`);
|
|
568
|
+
return (known ? context.assistant.getSession(known) : null) ?? startChatSession(context, chatId);
|
|
569
|
+
}
|
|
570
|
+
/* ---------------------- what the list commands say ---------------------- */
|
|
571
|
+
const NO_COMPANY = 'No company is configured yet.';
|
|
572
|
+
/** How many open assignments `/status` counts before it stops counting. */
|
|
573
|
+
const STATUS_ASSIGNMENT_LIMIT = 20;
|
|
574
|
+
const TASK_FETCH_LIMIT = 40;
|
|
575
|
+
const RUNNING_ASSIGNMENT_LIMIT = 50;
|
|
576
|
+
/** The order a phone wants tasks in: running first, then what failed, then what is planned, then the rest. */
|
|
577
|
+
const TASK_STATUS_ORDER = ['running', 'failed', 'planned', 'open'];
|
|
578
|
+
/** The command list as `/help` prints it, out of the one table above. */
|
|
579
|
+
function helpText() {
|
|
580
|
+
const rows = COMMANDS.map((entry) => `/${entry.command} – ${entry.description}`);
|
|
581
|
+
return ['What I answer to:', '', ...rows].join('\n');
|
|
582
|
+
}
|
|
583
|
+
function greetingText(context) {
|
|
584
|
+
return (`Hello, this is ${context.config.assistantName}. Send a message and I will reply in ` +
|
|
585
|
+
'the same conversation you can access in the browser.\n\n' +
|
|
586
|
+
'Voice messages are transcribed, and photos and documents are read. ' +
|
|
587
|
+
'Reply to one of my notifications and I will answer about that notification, ' +
|
|
588
|
+
'in a conversation of its own, rather than about whatever we last discussed.\n\n' +
|
|
589
|
+
helpText());
|
|
590
|
+
}
|
|
591
|
+
/** The active organisation, or nothing to report from. */
|
|
592
|
+
function activeOrgId(context) {
|
|
593
|
+
try {
|
|
594
|
+
return context.assistant.org.activeOrganization().id;
|
|
595
|
+
}
|
|
596
|
+
catch {
|
|
597
|
+
// It throws while no company exists, which is a normal state and not a failure.
|
|
598
|
+
return undefined;
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
/** "in 3 h 20 min", "12 min ago" - a clock reading nobody has to subtract. */
|
|
602
|
+
function relativeTime(at) {
|
|
603
|
+
if (!at)
|
|
604
|
+
return '';
|
|
605
|
+
const delta = at - Date.now();
|
|
606
|
+
const minutes = Math.round(Math.abs(delta) / MINUTE_MS);
|
|
607
|
+
const text = minutes < MINUTES_PER_HOUR
|
|
608
|
+
? `${minutes} min`
|
|
609
|
+
: minutes < MINUTES_PER_DAY * 2
|
|
610
|
+
? `${Math.round(minutes / MINUTES_PER_HOUR)} h`
|
|
611
|
+
: `${Math.round(minutes / MINUTES_PER_DAY)} d`;
|
|
612
|
+
return delta >= 0 ? `in ${text}` : `${text} ago`;
|
|
613
|
+
}
|
|
614
|
+
/** A list command's body, with the same shape for all four of them. */
|
|
615
|
+
function listText(title, rows, empty, total = rows.length) {
|
|
616
|
+
if (rows.length === 0)
|
|
617
|
+
return empty;
|
|
618
|
+
const shown = rows.slice(0, LIST_LIMIT);
|
|
619
|
+
const rest = total - shown.length;
|
|
620
|
+
return [title, '', ...shown, ...(rest > 0 ? ['', `… and ${rest} more. The web app has the rest.`] : [])].join('\n');
|
|
621
|
+
}
|
|
622
|
+
async function usageLimitsLine(provider) {
|
|
623
|
+
try {
|
|
624
|
+
const quota = await providerQuota(provider);
|
|
625
|
+
const windows = quota.windows.map((w) => `${w.label} ${w.percent} %`).join(', ');
|
|
626
|
+
return `Usage limits: ${windows || quota.error || 'unknown'}`;
|
|
627
|
+
}
|
|
628
|
+
catch (error) {
|
|
629
|
+
return `Usage limits: unknown (${errorText(error)})`;
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
function activeAssignmentsLine(context) {
|
|
633
|
+
const orgId = activeOrgId(context);
|
|
634
|
+
if (!orgId)
|
|
635
|
+
return 'Active assignments: no company configured';
|
|
636
|
+
try {
|
|
637
|
+
const open = context.assistant.store.org.listAssignments(orgId, {
|
|
638
|
+
status: ['pending', 'running'],
|
|
639
|
+
limit: STATUS_ASSIGNMENT_LIMIT,
|
|
640
|
+
});
|
|
641
|
+
return `Active assignments: ${open.length}`;
|
|
642
|
+
}
|
|
643
|
+
catch (error) {
|
|
644
|
+
return `Active assignments: unknown (${errorText(error)})`;
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
function lastSleepRunLine(context) {
|
|
648
|
+
const [last] = context.assistant.store.listSleepRuns({ owner: ASSISTANT_MEMORY_OWNER, limit: 1 });
|
|
649
|
+
return last
|
|
650
|
+
? `Last sleep run: ${new Date(last.startedAt).toLocaleString('en-GB')} (${last.status})`
|
|
651
|
+
: 'Last sleep run: none yet';
|
|
652
|
+
}
|
|
653
|
+
async function statusText(context) {
|
|
654
|
+
const provider = context.config.defaultProvider;
|
|
655
|
+
const model = context.config.gateways.telegram.model ?? context.config.defaultModel;
|
|
656
|
+
return [
|
|
657
|
+
`Provider: ${provider}${model ? ` (${model})` : ''}`,
|
|
658
|
+
await usageLimitsLine(provider),
|
|
659
|
+
activeAssignmentsLine(context),
|
|
660
|
+
lastSleepRunLine(context),
|
|
661
|
+
].join('\n');
|
|
662
|
+
}
|
|
663
|
+
function tasksText(context) {
|
|
664
|
+
const orgId = activeOrgId(context);
|
|
665
|
+
if (!orgId)
|
|
666
|
+
return NO_COMPANY;
|
|
667
|
+
const store = context.assistant.store.org;
|
|
668
|
+
const open = store.listTasks(orgId, {
|
|
669
|
+
status: ['running', 'planned', 'open', 'failed'],
|
|
670
|
+
limit: TASK_FETCH_LIMIT,
|
|
671
|
+
});
|
|
672
|
+
const rank = (status) => {
|
|
673
|
+
const index = TASK_STATUS_ORDER.indexOf(status);
|
|
674
|
+
return index === -1 ? TASK_STATUS_ORDER.length : index;
|
|
675
|
+
};
|
|
676
|
+
const sorted = [...open].sort((a, b) => rank(a.status) - rank(b.status));
|
|
677
|
+
const rows = sorted.map((task) => {
|
|
678
|
+
const who = task.assigneeId ? store.getAgent(task.assigneeId)?.name : undefined;
|
|
679
|
+
const mark = task.priority === 'high' ? '❗ ' : '';
|
|
680
|
+
return `• ${mark}${oneLine(task.title, ROW_TITLE_WIDTH)} – ${task.status}${who ? `, ${who}` : ''}`;
|
|
681
|
+
});
|
|
682
|
+
// "Unfinished" rather than "open": a failed task is on this list too,
|
|
683
|
+
// and it is the one most worth seeing from a phone.
|
|
684
|
+
return listText(`Board: ${open.length} unfinished`, rows, 'Nothing open on the board.', open.length);
|
|
685
|
+
}
|
|
686
|
+
function inboxText(context) {
|
|
687
|
+
const orgId = activeOrgId(context);
|
|
688
|
+
if (!orgId)
|
|
689
|
+
return NO_COMPANY;
|
|
690
|
+
// Read without marking read: this is a glance at the inbox, not the act
|
|
691
|
+
// of reading a notification, and the web inbox must not go quiet because
|
|
692
|
+
// of it.
|
|
693
|
+
const store = context.assistant.store.org;
|
|
694
|
+
const total = store.unreadNotificationCount(orgId);
|
|
695
|
+
const unread = store.listNotifications({ orgId, unread: true, limit: LIST_LIMIT });
|
|
696
|
+
const rows = unread.map((notification) => `• ${oneLine(notification.title, ROW_TITLE_WIDTH)} – ${notification.kind} (${relativeTime(notification.createdAt)})`);
|
|
697
|
+
return listText(`Inbox: ${total} unread`, rows, 'No unread notifications.', total);
|
|
698
|
+
}
|
|
699
|
+
function agentsText(context) {
|
|
700
|
+
const orgId = activeOrgId(context);
|
|
701
|
+
if (!orgId)
|
|
702
|
+
return NO_COMPANY;
|
|
703
|
+
const store = context.assistant.store.org;
|
|
704
|
+
const agents = store.listAgents(orgId);
|
|
705
|
+
const running = store.listAssignments(orgId, { status: ['running'], limit: RUNNING_ASSIGNMENT_LIMIT });
|
|
706
|
+
const busy = new Map();
|
|
707
|
+
for (const assignment of running)
|
|
708
|
+
busy.set(assignment.agentId, (busy.get(assignment.agentId) ?? 0) + 1);
|
|
709
|
+
const rows = agents.map((agent) => {
|
|
710
|
+
const load = busy.get(agent.id);
|
|
711
|
+
return `• ${agent.name} – ${oneLine(agent.title, ROW_NAME_WIDTH)}${load ? ` (busy: ${load})` : ''}`;
|
|
712
|
+
});
|
|
713
|
+
return listText(`Company: ${agents.length} agents`, rows, 'Nobody works here yet.', agents.length);
|
|
714
|
+
}
|
|
715
|
+
function schedulesText(context) {
|
|
716
|
+
const orgId = activeOrgId(context);
|
|
717
|
+
if (!orgId)
|
|
718
|
+
return NO_COMPANY;
|
|
719
|
+
const jobs = context.assistant.cron.list(orgId);
|
|
720
|
+
const upcoming = [...jobs].sort((a, b) => (a.nextRunAt ?? Infinity) - (b.nextRunAt ?? Infinity));
|
|
721
|
+
const rows = upcoming.map((job) => {
|
|
722
|
+
const when = job.enabled ? (job.nextRunAt ? relativeTime(job.nextRunAt) : 'not scheduled') : 'off';
|
|
723
|
+
const last = job.lastStatus ? `, last ${job.lastStatus}` : '';
|
|
724
|
+
return `• ${oneLine(job.name, ROW_NAME_WIDTH)} – ${job.schedule}, ${when}${last}`;
|
|
725
|
+
});
|
|
726
|
+
return listText(`Schedules: ${jobs.length}`, rows, 'No schedules are set up.', jobs.length);
|
|
727
|
+
}
|
|
400
728
|
export function createTelegramGateway(context) {
|
|
401
729
|
const log = context.log.child('telegram');
|
|
402
730
|
let api;
|
|
@@ -429,25 +757,6 @@ export function createTelegramGateway(context) {
|
|
|
429
757
|
const albums = new Map();
|
|
430
758
|
/** One running turn per sender, so `/stop` knows what to abort. */
|
|
431
759
|
const turns = new Map();
|
|
432
|
-
/**
|
|
433
|
-
* A turn in one of this chat's conversations that nobody here typed - a
|
|
434
|
-
* report-back from work handed off from the phone (R3). The conversation
|
|
435
|
-
* remembers which chat it belongs to; its answer goes there, filed as an
|
|
436
|
-
* answer of that conversation so a reply to it continues it.
|
|
437
|
-
*/
|
|
438
|
-
const sessionChatKey = (sessionId) => 'telegram:session:' + sessionId;
|
|
439
|
-
context.assistant.on('follow-up', (event) => {
|
|
440
|
-
if (!running || !api)
|
|
441
|
-
return;
|
|
442
|
-
const raw = context.assistant.store.getMeta(sessionChatKey(event.sessionId));
|
|
443
|
-
const chatId = raw ? Number(raw) : NaN;
|
|
444
|
-
if (!Number.isFinite(chatId))
|
|
445
|
-
return;
|
|
446
|
-
const text = event.text.trim() || (event.error ? 'Error: ' + event.error : '');
|
|
447
|
-
if (!text)
|
|
448
|
-
return;
|
|
449
|
-
say(chatId, text, { origin: { kind: 'answer', sessionId: event.sessionId } });
|
|
450
|
-
});
|
|
451
760
|
/** Per chat, so two answers never race each other onto the wire. */
|
|
452
761
|
const outbox = new Map();
|
|
453
762
|
const idReplies = new Map();
|
|
@@ -477,7 +786,14 @@ export function createTelegramGateway(context) {
|
|
|
477
786
|
function chain(chatId, run) {
|
|
478
787
|
const previous = outbox.get(chatId) ?? Promise.resolve();
|
|
479
788
|
const next = previous.then(run, run);
|
|
480
|
-
|
|
789
|
+
// Only the order is kept here: a failed delivery is for its caller to
|
|
790
|
+
// handle, and must not stop the next one from going out.
|
|
791
|
+
const tail = next.then(() => undefined, () => undefined);
|
|
792
|
+
outbox.set(chatId, tail);
|
|
793
|
+
void tail.then(() => {
|
|
794
|
+
if (outbox.get(chatId) === tail)
|
|
795
|
+
outbox.delete(chatId);
|
|
796
|
+
});
|
|
481
797
|
return next;
|
|
482
798
|
}
|
|
483
799
|
async function deliver(chatId, text, options = {}) {
|
|
@@ -512,9 +828,7 @@ export function createTelegramGateway(context) {
|
|
|
512
828
|
}
|
|
513
829
|
/** Fire-and-forget delivery: used where a failed line must not break a turn. */
|
|
514
830
|
function say(chatId, text, options = {}) {
|
|
515
|
-
void chain(chatId,
|
|
516
|
-
await deliver(chatId, text, options);
|
|
517
|
-
}).catch((error) => {
|
|
831
|
+
void chain(chatId, () => deliver(chatId, text, options)).catch((error) => {
|
|
518
832
|
log.warn('Telegram send failed', { chatId, error: errorText(error) });
|
|
519
833
|
});
|
|
520
834
|
}
|
|
@@ -532,7 +846,44 @@ export function createTelegramGateway(context) {
|
|
|
532
846
|
log.debug('Telegram reaction not accepted', { chatId, error: errorText(error) });
|
|
533
847
|
});
|
|
534
848
|
}
|
|
849
|
+
/** The typing bubble. Decoration like the reaction: a refused one costs nothing but itself. */
|
|
850
|
+
function showTyping(chatId) {
|
|
851
|
+
void api?.sendChatAction(chatId, 'typing').catch((error) => {
|
|
852
|
+
log.debug('Telegram typing indicator not accepted', { chatId, error: errorText(error) });
|
|
853
|
+
});
|
|
854
|
+
}
|
|
855
|
+
/**
|
|
856
|
+
* A turn in one of this chat's conversations that nobody here typed - a
|
|
857
|
+
* report-back from work handed off from the phone (R3). The conversation
|
|
858
|
+
* remembers which chat it belongs to; its answer goes there, filed as an
|
|
859
|
+
* answer of that conversation so a reply to it continues it.
|
|
860
|
+
*/
|
|
861
|
+
function relayFollowUp(event) {
|
|
862
|
+
if (!running || !api)
|
|
863
|
+
return;
|
|
864
|
+
const raw = context.assistant.store.getMeta(sessionChatKey(event.sessionId));
|
|
865
|
+
const chatId = raw ? Number(raw) : NaN;
|
|
866
|
+
if (!Number.isFinite(chatId))
|
|
867
|
+
return;
|
|
868
|
+
const text = event.text.trim() || (event.error ? 'Error: ' + event.error : '');
|
|
869
|
+
if (!text)
|
|
870
|
+
return;
|
|
871
|
+
say(chatId, text, { origin: { kind: 'answer', sessionId: event.sessionId } });
|
|
872
|
+
}
|
|
873
|
+
/** Whether this stranger may be told their own id now; once told, they wait out the interval. */
|
|
874
|
+
function claimIdReply(userId) {
|
|
875
|
+
const now = Date.now();
|
|
876
|
+
for (const [id, at] of idReplies) {
|
|
877
|
+
if (now - at >= ID_REPLY_INTERVAL_MS)
|
|
878
|
+
idReplies.delete(id);
|
|
879
|
+
}
|
|
880
|
+
if (idReplies.has(userId))
|
|
881
|
+
return false;
|
|
882
|
+
idReplies.set(userId, now);
|
|
883
|
+
return true;
|
|
884
|
+
}
|
|
535
885
|
/* ---------------------------- questions ---------------------------- */
|
|
886
|
+
const postKey = (questionId, chatId) => questionId + '@' + String(chatId);
|
|
536
887
|
/**
|
|
537
888
|
* The assistant asking the person something, carried to the phone.
|
|
538
889
|
*
|
|
@@ -552,7 +903,6 @@ export function createTelegramGateway(context) {
|
|
|
552
903
|
* the same property for free: a `callback_query` is not a message and never
|
|
553
904
|
* was queued.
|
|
554
905
|
*/
|
|
555
|
-
const postKey = (questionId, chatId) => questionId + '@' + String(chatId);
|
|
556
906
|
/** Is somebody being asked something in this chat right now? */
|
|
557
907
|
function openQuestion(chatId) {
|
|
558
908
|
let newest;
|
|
@@ -569,8 +919,20 @@ export function createTelegramGateway(context) {
|
|
|
569
919
|
}
|
|
570
920
|
return newest;
|
|
571
921
|
}
|
|
922
|
+
/** Forget standing questions whose deadline is long gone and whose closing event never came. */
|
|
923
|
+
function pruneExpiredPosts() {
|
|
924
|
+
const cutoff = Date.now() - EXPIRED_QUESTION_GRACE_MS;
|
|
925
|
+
for (const [key, post] of questionPosts) {
|
|
926
|
+
const { expiresAt } = post.question;
|
|
927
|
+
if (expiresAt <= 0 || expiresAt > cutoff)
|
|
928
|
+
continue;
|
|
929
|
+
questionPosts.delete(key);
|
|
930
|
+
settlePost(post, 'expired');
|
|
931
|
+
}
|
|
932
|
+
}
|
|
572
933
|
/** Draw the question in one chat, unless it is already standing there. */
|
|
573
934
|
function offerQuestion(chatId, question, origin) {
|
|
935
|
+
pruneExpiredPosts();
|
|
574
936
|
const key = postKey(question.id, chatId);
|
|
575
937
|
// Claimed before anything is awaited: the turn that asked and the push
|
|
576
938
|
// listener both arrive within the same tick. A Telegram turn claims the
|
|
@@ -676,7 +1038,7 @@ export function createTelegramGateway(context) {
|
|
|
676
1038
|
messageId = id;
|
|
677
1039
|
return;
|
|
678
1040
|
}
|
|
679
|
-
await client.editMessageText(chatId, messageId,
|
|
1041
|
+
await client.editMessageText(chatId, messageId, toTelegramHtml(text), {
|
|
680
1042
|
parseMode: 'HTML',
|
|
681
1043
|
disablePreview: true,
|
|
682
1044
|
});
|
|
@@ -772,9 +1134,7 @@ export function createTelegramGateway(context) {
|
|
|
772
1134
|
return;
|
|
773
1135
|
}
|
|
774
1136
|
writing = true;
|
|
775
|
-
void chain(chatId,
|
|
776
|
-
await write();
|
|
777
|
-
})
|
|
1137
|
+
void chain(chatId, write)
|
|
778
1138
|
.catch((error) => {
|
|
779
1139
|
// A refused edit is not worth the turn: the next pass rewrites the
|
|
780
1140
|
// same text anyway, and the answer still arrives.
|
|
@@ -813,7 +1173,6 @@ export function createTelegramGateway(context) {
|
|
|
813
1173
|
timer.unref?.();
|
|
814
1174
|
}
|
|
815
1175
|
return {
|
|
816
|
-
started: () => ids.length > 0,
|
|
817
1176
|
push(delta) {
|
|
818
1177
|
if (closed)
|
|
819
1178
|
return;
|
|
@@ -822,171 +1181,20 @@ export function createTelegramGateway(context) {
|
|
|
822
1181
|
},
|
|
823
1182
|
async finish(finalText) {
|
|
824
1183
|
closed = true;
|
|
825
|
-
|
|
826
|
-
clearTimeout(timer);
|
|
1184
|
+
clearTimeout(timer);
|
|
827
1185
|
timer = undefined;
|
|
828
1186
|
// The streamed text stands, and the provider's closing answer is
|
|
829
1187
|
// added only when it is not already part of it. The reasoning, and
|
|
830
1188
|
// the bug it repairs, are with `mergeFinalText`.
|
|
831
1189
|
text = mergeFinalText(text, finalText);
|
|
832
|
-
await chain(chatId,
|
|
833
|
-
await write();
|
|
834
|
-
}).catch((error) => {
|
|
1190
|
+
await chain(chatId, write).catch((error) => {
|
|
835
1191
|
log.warn('Telegram stream could not be finished', { chatId, error: errorText(error) });
|
|
836
1192
|
});
|
|
837
1193
|
return ids;
|
|
838
1194
|
},
|
|
839
1195
|
};
|
|
840
1196
|
}
|
|
841
|
-
/* --------------------------- sessions --------------------------- */
|
|
842
|
-
/**
|
|
843
|
-
* The conversation behind a chat. Deliberately an ordinary `chat` session
|
|
844
|
-
* rather than a kind of its own, so what was said from the phone shows up
|
|
845
|
-
* in the same sidebar as everything else.
|
|
846
|
-
*/
|
|
847
|
-
function resolveSession(chatId, fresh = false) {
|
|
848
|
-
const key = `telegram:chat:${chatId}`;
|
|
849
|
-
if (!fresh) {
|
|
850
|
-
const known = context.assistant.store.getMeta(key);
|
|
851
|
-
const session = known ? context.assistant.getSession(known) : null;
|
|
852
|
-
if (session)
|
|
853
|
-
return session;
|
|
854
|
-
}
|
|
855
|
-
const session = context.assistant.createSession({ title: 'Telegram', kind: 'chat' });
|
|
856
|
-
context.assistant.store.setMeta(key, session.id);
|
|
857
|
-
return session;
|
|
858
|
-
}
|
|
859
1197
|
/* --------------------------- commands --------------------------- */
|
|
860
|
-
async function statusText() {
|
|
861
|
-
const lines = [];
|
|
862
|
-
const provider = context.config.defaultProvider;
|
|
863
|
-
const model = settings().model ?? context.config.defaultModel;
|
|
864
|
-
lines.push(`Provider: ${provider}${model ? ` (${model})` : ''}`);
|
|
865
|
-
try {
|
|
866
|
-
const quota = await providerQuota(provider);
|
|
867
|
-
const windows = quota.windows.map((w) => `${w.label} ${w.percent} %`).join(', ');
|
|
868
|
-
lines.push(`Usage limits: ${windows || quota.error || 'unknown'}`);
|
|
869
|
-
}
|
|
870
|
-
catch (error) {
|
|
871
|
-
lines.push(`Usage limits: unknown (${errorText(error)})`);
|
|
872
|
-
}
|
|
873
|
-
try {
|
|
874
|
-
const orgId = context.assistant.org.activeOrganization().id;
|
|
875
|
-
const open = context.assistant.store.org.listAssignments(orgId, {
|
|
876
|
-
status: ['pending', 'running'],
|
|
877
|
-
limit: 20,
|
|
878
|
-
});
|
|
879
|
-
lines.push(`Active assignments: ${open.length}`);
|
|
880
|
-
}
|
|
881
|
-
catch {
|
|
882
|
-
lines.push('Active assignments: no company configured');
|
|
883
|
-
}
|
|
884
|
-
const [last] = context.assistant.store.listSleepRuns({
|
|
885
|
-
owner: ASSISTANT_MEMORY_OWNER,
|
|
886
|
-
limit: 1,
|
|
887
|
-
});
|
|
888
|
-
lines.push(last
|
|
889
|
-
? `Last sleep run: ${new Date(last.startedAt).toLocaleString('en-GB')} (${last.status})`
|
|
890
|
-
: 'Last sleep run: none yet');
|
|
891
|
-
return lines.join('\n');
|
|
892
|
-
}
|
|
893
|
-
/** The command list as `/help` prints it, out of the one table above. */
|
|
894
|
-
function helpText() {
|
|
895
|
-
const rows = COMMANDS.map((entry) => `/${entry.command} – ${entry.description}`);
|
|
896
|
-
return ['What I answer to:', '', ...rows].join('\n');
|
|
897
|
-
}
|
|
898
|
-
/** One organisation, or nothing to report from. */
|
|
899
|
-
function orgId() {
|
|
900
|
-
try {
|
|
901
|
-
return context.assistant.org.activeOrganization().id;
|
|
902
|
-
}
|
|
903
|
-
catch {
|
|
904
|
-
return undefined;
|
|
905
|
-
}
|
|
906
|
-
}
|
|
907
|
-
/** "in 3 h 20 min", "12 min ago" - a clock reading nobody has to subtract. */
|
|
908
|
-
function relativeTime(at) {
|
|
909
|
-
if (!at)
|
|
910
|
-
return '';
|
|
911
|
-
const delta = at - Date.now();
|
|
912
|
-
const minutes = Math.round(Math.abs(delta) / 60_000);
|
|
913
|
-
const text = minutes < 60
|
|
914
|
-
? `${minutes} min`
|
|
915
|
-
: minutes < 60 * 48
|
|
916
|
-
? `${Math.round(minutes / 60)} h`
|
|
917
|
-
: `${Math.round(minutes / (60 * 24))} d`;
|
|
918
|
-
return delta >= 0 ? `in ${text}` : `${text} ago`;
|
|
919
|
-
}
|
|
920
|
-
/** A list command's body, with the same shape for all four of them. */
|
|
921
|
-
function listText(title, rows, empty, total = rows.length) {
|
|
922
|
-
if (rows.length === 0)
|
|
923
|
-
return empty;
|
|
924
|
-
const shown = rows.slice(0, LIST_LIMIT);
|
|
925
|
-
const rest = total - shown.length;
|
|
926
|
-
return [title, '', ...shown, ...(rest > 0 ? ['', `… and ${rest} more. The web app has the rest.`] : [])].join('\n');
|
|
927
|
-
}
|
|
928
|
-
function tasksText() {
|
|
929
|
-
const id = orgId();
|
|
930
|
-
if (!id)
|
|
931
|
-
return 'No company is configured yet.';
|
|
932
|
-
const open = context.assistant.store.org.listTasks(id, {
|
|
933
|
-
status: ['running', 'planned', 'open', 'failed'],
|
|
934
|
-
limit: 40,
|
|
935
|
-
});
|
|
936
|
-
// Running first, then what is planned, then the rest: the order someone
|
|
937
|
-
// looking at a phone actually wants.
|
|
938
|
-
const rank = { running: 0, failed: 1, planned: 2, open: 3 };
|
|
939
|
-
const sorted = [...open].sort((a, b) => (rank[a.status] ?? 9) - (rank[b.status] ?? 9));
|
|
940
|
-
const rows = sorted.map((task) => {
|
|
941
|
-
const who = task.assigneeId ? context.assistant.store.org.getAgent(task.assigneeId)?.name : undefined;
|
|
942
|
-
const mark = task.priority === 'high' ? '❗ ' : '';
|
|
943
|
-
return `• ${mark}${oneLine(task.title, 70)} – ${task.status}${who ? `, ${who}` : ''}`;
|
|
944
|
-
});
|
|
945
|
-
// "Unfinished" rather than "open": a failed task is on this list too,
|
|
946
|
-
// and it is the one most worth seeing from a phone.
|
|
947
|
-
return listText(`Board: ${open.length} unfinished`, rows, 'Nothing open on the board.', open.length);
|
|
948
|
-
}
|
|
949
|
-
function inboxText() {
|
|
950
|
-
const id = orgId();
|
|
951
|
-
if (!id)
|
|
952
|
-
return 'No company is configured yet.';
|
|
953
|
-
// Read without marking read: this is a glance at the inbox, not the act
|
|
954
|
-
// of reading a notification, and the web inbox must not go quiet because
|
|
955
|
-
// of it.
|
|
956
|
-
const store = context.assistant.store.org;
|
|
957
|
-
const total = store.unreadNotificationCount(id);
|
|
958
|
-
const unread = store.listNotifications({ orgId: id, unread: true, limit: LIST_LIMIT });
|
|
959
|
-
const rows = unread.map((notification) => `• ${oneLine(notification.title, 70)} – ${notification.kind} (${relativeTime(notification.createdAt)})`);
|
|
960
|
-
return listText(`Inbox: ${total} unread`, rows, 'No unread notifications.', total);
|
|
961
|
-
}
|
|
962
|
-
function agentsText() {
|
|
963
|
-
const id = orgId();
|
|
964
|
-
if (!id)
|
|
965
|
-
return 'No company is configured yet.';
|
|
966
|
-
const agents = context.assistant.store.org.listAgents(id);
|
|
967
|
-
const running = context.assistant.store.org.listAssignments(id, { status: ['running'], limit: 50 });
|
|
968
|
-
const busy = new Map();
|
|
969
|
-
for (const assignment of running)
|
|
970
|
-
busy.set(assignment.agentId, (busy.get(assignment.agentId) ?? 0) + 1);
|
|
971
|
-
const rows = agents.map((agent) => {
|
|
972
|
-
const load = busy.get(agent.id);
|
|
973
|
-
return `• ${agent.name} – ${oneLine(agent.title, 50)}${load ? ` (busy: ${load})` : ''}`;
|
|
974
|
-
});
|
|
975
|
-
return listText(`Company: ${agents.length} agents`, rows, 'Nobody works here yet.', agents.length);
|
|
976
|
-
}
|
|
977
|
-
function schedulesText() {
|
|
978
|
-
const id = orgId();
|
|
979
|
-
if (!id)
|
|
980
|
-
return 'No company is configured yet.';
|
|
981
|
-
const jobs = context.assistant.cron.list(id);
|
|
982
|
-
const upcoming = [...jobs].sort((a, b) => (a.nextRunAt ?? Infinity) - (b.nextRunAt ?? Infinity));
|
|
983
|
-
const rows = upcoming.map((job) => {
|
|
984
|
-
const when = job.enabled ? (job.nextRunAt ? relativeTime(job.nextRunAt) : 'not scheduled') : 'off';
|
|
985
|
-
const last = job.lastStatus ? `, last ${job.lastStatus}` : '';
|
|
986
|
-
return `• ${oneLine(job.name, 50)} – ${job.schedule}, ${when}${last}`;
|
|
987
|
-
});
|
|
988
|
-
return listText(`Schedules: ${jobs.length}`, rows, 'No schedules are set up.', jobs.length);
|
|
989
|
-
}
|
|
990
1198
|
/**
|
|
991
1199
|
* Empty the chat and start over.
|
|
992
1200
|
*
|
|
@@ -1012,148 +1220,133 @@ export function createTelegramGateway(context) {
|
|
|
1012
1220
|
* is not.
|
|
1013
1221
|
*/
|
|
1014
1222
|
async function clearChat(chatId, commandMessageId) {
|
|
1015
|
-
const client = api;
|
|
1016
1223
|
const known = takeMessages(context, chatId);
|
|
1017
1224
|
const newest = Math.max(commandMessageId ?? 0, ...known, 0);
|
|
1225
|
+
const swept = await sweepMessages(chatId, newest);
|
|
1226
|
+
const session = startChatSession(context, chatId);
|
|
1227
|
+
log.info('Telegram chat cleared', { chatId, swept, newest, sessionId: session.id });
|
|
1228
|
+
say(chatId, takeClearConfirmation(chatId));
|
|
1229
|
+
}
|
|
1230
|
+
/** Delete the id range below `newest`, a batch at a time; returns how many ids were handed to Telegram. */
|
|
1231
|
+
async function sweepMessages(chatId, newest) {
|
|
1232
|
+
const client = api;
|
|
1233
|
+
if (!client || newest <= 0)
|
|
1234
|
+
return 0;
|
|
1018
1235
|
let swept = 0;
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
// not a reason to stop: further down is only older, but further up
|
|
1035
|
-
// may still hold something deletable in a chat with gaps.
|
|
1036
|
-
log.debug('Telegram delete batch refused', { chatId, error: errorText(error) });
|
|
1037
|
-
}
|
|
1236
|
+
// Downwards from the newest, so a flood limit that cuts this short
|
|
1237
|
+
// takes what is on screen first.
|
|
1238
|
+
for (let top = newest; top > 0 && newest - top < CLEAR_SWEEP; top -= DELETE_BATCH) {
|
|
1239
|
+
const batch = sweepBatch(top, newest);
|
|
1240
|
+
if (batch.length === 0)
|
|
1241
|
+
break;
|
|
1242
|
+
try {
|
|
1243
|
+
await client.deleteMessages(chatId, batch);
|
|
1244
|
+
swept += batch.length;
|
|
1245
|
+
}
|
|
1246
|
+
catch (error) {
|
|
1247
|
+
// A batch Telegram refuses outright - every id in it too old - is
|
|
1248
|
+
// not a reason to stop: further down is only older, but further up
|
|
1249
|
+
// may still hold something deletable in a chat with gaps.
|
|
1250
|
+
log.debug('Telegram delete batch refused', { chatId, error: errorText(error) });
|
|
1038
1251
|
}
|
|
1039
1252
|
}
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1253
|
+
return swept;
|
|
1254
|
+
}
|
|
1255
|
+
/**
|
|
1256
|
+
* One line on an empty screen, which is the whole point of the command.
|
|
1257
|
+
* The footnote about Telegram's 48 hours is true every time and worth
|
|
1258
|
+
* reading once, so it comes with the first clear in a chat and never
|
|
1259
|
+
* again - an explanation repeated on every use stops being read and
|
|
1260
|
+
* starts being clutter. Taking the confirmation records that it was shown.
|
|
1261
|
+
*/
|
|
1262
|
+
function takeClearConfirmation(chatId) {
|
|
1047
1263
|
const noticeKey = `telegram:clear-notice:${chatId}`;
|
|
1048
1264
|
const explained = context.assistant.store.getMeta(noticeKey) !== null;
|
|
1049
|
-
if (
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
/** Returns true when the message was a command and is fully dealt with. */
|
|
1265
|
+
if (explained)
|
|
1266
|
+
return '✨ Fresh start.';
|
|
1267
|
+
context.assistant.store.setMeta(noticeKey, String(Date.now()));
|
|
1268
|
+
return ('✨ Fresh start — the old conversation is kept in the web app.\n' +
|
|
1269
|
+
'Telegram lets me delete only the last 48 hours; for anything older: hold the chat → Clear History.');
|
|
1270
|
+
}
|
|
1271
|
+
/** Carries out a command that has already passed the guard; commands never queue. */
|
|
1057
1272
|
async function handleCommand(verdict) {
|
|
1058
|
-
const chatId = verdict
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
switch (verdict.command) {
|
|
1273
|
+
const { chatId, userId, command } = verdict;
|
|
1274
|
+
if (chatId === undefined || userId === undefined || !command)
|
|
1275
|
+
return;
|
|
1276
|
+
switch (command) {
|
|
1063
1277
|
case 'start':
|
|
1064
|
-
say(chatId,
|
|
1065
|
-
|
|
1066
|
-
'Voice messages are transcribed, and photos and documents are read. ' +
|
|
1067
|
-
'Reply to one of my notifications and I will answer about that notification, ' +
|
|
1068
|
-
'in a conversation of its own, rather than about whatever we last discussed.\n\n' +
|
|
1069
|
-
helpText());
|
|
1070
|
-
return true;
|
|
1278
|
+
say(chatId, greetingText(context));
|
|
1279
|
+
return;
|
|
1071
1280
|
case 'help':
|
|
1072
1281
|
case 'hilfe':
|
|
1073
1282
|
say(chatId, helpText());
|
|
1074
|
-
return
|
|
1283
|
+
return;
|
|
1075
1284
|
case 'new':
|
|
1076
1285
|
case 'neu': {
|
|
1077
|
-
const session =
|
|
1286
|
+
const session = startChatSession(context, chatId);
|
|
1078
1287
|
log.info('Telegram session replaced', { from: userId, sessionId: session.id });
|
|
1079
1288
|
say(chatId, 'New conversation created. The previous one is preserved.');
|
|
1080
|
-
return
|
|
1289
|
+
return;
|
|
1081
1290
|
}
|
|
1082
1291
|
case 'clear':
|
|
1083
1292
|
await clearChat(chatId, verdict.messageId);
|
|
1084
|
-
return
|
|
1293
|
+
return;
|
|
1085
1294
|
case 'tasks':
|
|
1086
|
-
say(chatId, tasksText());
|
|
1087
|
-
return
|
|
1295
|
+
say(chatId, tasksText(context));
|
|
1296
|
+
return;
|
|
1088
1297
|
case 'inbox':
|
|
1089
|
-
say(chatId, inboxText());
|
|
1090
|
-
return
|
|
1298
|
+
say(chatId, inboxText(context));
|
|
1299
|
+
return;
|
|
1091
1300
|
// Mail was folded into notifications; the old command still works and
|
|
1092
1301
|
// says where it went.
|
|
1093
1302
|
case 'mail':
|
|
1094
|
-
say(chatId, '/mail is now /inbox.\n\n' + inboxText());
|
|
1095
|
-
return
|
|
1303
|
+
say(chatId, '/mail is now /inbox.\n\n' + inboxText(context));
|
|
1304
|
+
return;
|
|
1096
1305
|
case 'agents':
|
|
1097
|
-
say(chatId, agentsText());
|
|
1098
|
-
return
|
|
1306
|
+
say(chatId, agentsText(context));
|
|
1307
|
+
return;
|
|
1099
1308
|
case 'schedules':
|
|
1100
1309
|
case 'cron':
|
|
1101
|
-
say(chatId, schedulesText());
|
|
1102
|
-
return
|
|
1103
|
-
case 'stop':
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
// branch stays silent unless there was nothing to stop.
|
|
1107
|
-
if (turn)
|
|
1108
|
-
turn.abort();
|
|
1109
|
-
else
|
|
1110
|
-
say(chatId, 'Nothing is running.');
|
|
1111
|
-
return true;
|
|
1112
|
-
}
|
|
1310
|
+
say(chatId, schedulesText(context));
|
|
1311
|
+
return;
|
|
1312
|
+
case 'stop':
|
|
1313
|
+
stopRunningTurn(userId, chatId);
|
|
1314
|
+
return;
|
|
1113
1315
|
case 'status':
|
|
1114
|
-
say(chatId, await statusText());
|
|
1115
|
-
return
|
|
1316
|
+
say(chatId, await statusText(context));
|
|
1317
|
+
return;
|
|
1116
1318
|
case 'id':
|
|
1117
1319
|
say(chatId, String(userId));
|
|
1118
|
-
return
|
|
1320
|
+
return;
|
|
1119
1321
|
case 'off':
|
|
1120
1322
|
case 'aus':
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
// Let the farewell leave before the socket does.
|
|
1124
|
-
void chain(chatId, () => Promise.resolve()).finally(() => {
|
|
1125
|
-
void stop();
|
|
1126
|
-
});
|
|
1127
|
-
return true;
|
|
1323
|
+
silenceUntilRestart(chatId);
|
|
1324
|
+
return;
|
|
1128
1325
|
default:
|
|
1129
1326
|
say(chatId, 'I do not know that one.\n\n' + helpText());
|
|
1130
|
-
return true;
|
|
1131
1327
|
}
|
|
1132
1328
|
}
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
if (config.transcribe !== 'auto')
|
|
1153
|
-
return false;
|
|
1154
|
-
const keys = voiceKeys(context.config.home);
|
|
1155
|
-
return !keys.openai && !keys.elevenlabs;
|
|
1329
|
+
function stopRunningTurn(userId, chatId) {
|
|
1330
|
+
const turn = turns.get(userId);
|
|
1331
|
+
// The turn itself reports "Cancelled." on its way out, so this stays
|
|
1332
|
+
// silent unless there was nothing to stop.
|
|
1333
|
+
if (turn)
|
|
1334
|
+
turn.abort();
|
|
1335
|
+
else
|
|
1336
|
+
say(chatId, 'Nothing is running.');
|
|
1337
|
+
}
|
|
1338
|
+
function silenceUntilRestart(chatId) {
|
|
1339
|
+
silenced = true;
|
|
1340
|
+
say(chatId, 'The gateway is silenced until restart.');
|
|
1341
|
+
// Let the farewell leave before the socket does: the chat's chain is in
|
|
1342
|
+
// order, so once an empty link has run, the farewell is out.
|
|
1343
|
+
void chain(chatId, () => Promise.resolve())
|
|
1344
|
+
.then(() => stop())
|
|
1345
|
+
.catch((error) => {
|
|
1346
|
+
log.warn('Telegram gateway could not be silenced cleanly', { error: errorText(error) });
|
|
1347
|
+
});
|
|
1156
1348
|
}
|
|
1349
|
+
/* --------------------------- attachments --------------------------- */
|
|
1157
1350
|
/**
|
|
1158
1351
|
* Fetch, store and, where there is something to hear, transcribe.
|
|
1159
1352
|
*
|
|
@@ -1163,12 +1356,12 @@ export function createTelegramGateway(context) {
|
|
|
1163
1356
|
* instead of answering a question it never saw.
|
|
1164
1357
|
*/
|
|
1165
1358
|
async function takeIn(job, signal) {
|
|
1166
|
-
const config = settings();
|
|
1167
1359
|
const intake = { lines: [], transcripts: [], saved: 0 };
|
|
1168
1360
|
const client = api;
|
|
1169
1361
|
if (!client || job.attachments.length === 0)
|
|
1170
1362
|
return intake;
|
|
1171
|
-
const
|
|
1363
|
+
const config = settings();
|
|
1364
|
+
const maxBytes = Math.min(Math.max(1, config.maxAttachmentMb), BOT_API_DOWNLOAD_LIMIT_MB) * BYTES_PER_MB;
|
|
1172
1365
|
let announcedColdStart = false;
|
|
1173
1366
|
for (const attachment of job.attachments.slice(0, MAX_ATTACHMENTS)) {
|
|
1174
1367
|
const label = KIND_LABEL[attachment.kind] ?? 'A file';
|
|
@@ -1181,65 +1374,24 @@ export function createTelegramGateway(context) {
|
|
|
1181
1374
|
const bytes = await client.downloadFile(file.path, { maxBytes, signal });
|
|
1182
1375
|
const stored = saveAttachment(context.config.workspace, attachment, bytes);
|
|
1183
1376
|
intake.saved += 1;
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
if (isAudible(attachment) && config.transcribe !== 'off') {
|
|
1187
|
-
const length = humanDuration(attachment.duration);
|
|
1188
|
-
// The local model is fetched once, and that once takes about a
|
|
1189
|
-
// minute on a normal line. Saying so beats a silence that looks
|
|
1190
|
-
// like a bot which stopped working.
|
|
1191
|
-
if (!announcedColdStart && listensLocally(config) && !localModelReady(config.transcribeModel)) {
|
|
1192
|
-
announcedColdStart = true;
|
|
1193
|
-
say(job.chatId, 'Listening. The speech model is being downloaded once, which takes a minute.');
|
|
1194
|
-
}
|
|
1195
|
-
try {
|
|
1196
|
-
const result = await transcribe({
|
|
1197
|
-
audio: bytes,
|
|
1198
|
-
mime: attachment.mime,
|
|
1199
|
-
fileName: attachment.fileName,
|
|
1200
|
-
engine: config.transcribe,
|
|
1201
|
-
model: config.transcribeModel,
|
|
1202
|
-
lang: context.config.voice.lang,
|
|
1203
|
-
home: context.config.home,
|
|
1204
|
-
signal,
|
|
1205
|
-
});
|
|
1206
|
-
intake.transcripts.push(result.text);
|
|
1207
|
-
intake.lines.push(`${label}${length ? ` (${length})` : ''}, transcribed by ${result.engine}; the wording may be` +
|
|
1208
|
-
` imperfect. The audio itself is at ${stored.path}.`);
|
|
1209
|
-
// Echoed back, because a transcript nobody can check is a
|
|
1210
|
-
// misheard sentence the assistant answers with a straight face.
|
|
1211
|
-
const echo = result.text.length > TRANSCRIPT_ECHO ? result.text.slice(0, TRANSCRIPT_ECHO) + ' …' : result.text;
|
|
1212
|
-
say(job.chatId, '🎤 ' + echo);
|
|
1213
|
-
log.info('Telegram voice note transcribed', {
|
|
1214
|
-
from: job.userId,
|
|
1215
|
-
engine: result.engine,
|
|
1216
|
-
ms: result.ms,
|
|
1217
|
-
chars: result.text.length,
|
|
1218
|
-
});
|
|
1219
|
-
}
|
|
1220
|
-
catch (error) {
|
|
1221
|
-
const reason = error instanceof SttError ? error.message : errorText(error);
|
|
1222
|
-
intake.lines.push(`${label}${length ? ` (${length})` : ''} could not be transcribed: ${reason} The audio is at ${stored.path}.`);
|
|
1223
|
-
log.warn('Telegram transcription failed', { from: job.userId, error: reason });
|
|
1224
|
-
}
|
|
1377
|
+
if (!isAudible(attachment) || config.transcribe === 'off') {
|
|
1378
|
+
intake.lines.push(describeStoredFile(attachment, label, stored));
|
|
1225
1379
|
continue;
|
|
1226
1380
|
}
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
case 'video_note':
|
|
1234
|
-
case 'animation':
|
|
1235
|
-
intake.lines.push(`${label} (${size}) is at ${stored.path}.`);
|
|
1236
|
-
break;
|
|
1237
|
-
default:
|
|
1238
|
-
intake.lines.push(`${label}${named} (${size}) is at ${stored.path}. Open it before you answer.`);
|
|
1381
|
+
// The local model is fetched once, and that once takes about a
|
|
1382
|
+
// minute on a normal line. Saying so beats a silence that looks
|
|
1383
|
+
// like a bot which stopped working.
|
|
1384
|
+
if (!announcedColdStart && listensLocally(context, config) && !localModelReady(config.transcribeModel)) {
|
|
1385
|
+
announcedColdStart = true;
|
|
1386
|
+
say(job.chatId, 'Listening. The speech model is being downloaded once, which takes a minute.');
|
|
1239
1387
|
}
|
|
1388
|
+
const heard = await listen(job, { attachment, label, bytes, path: stored.path }, signal);
|
|
1389
|
+
intake.lines.push(heard.line);
|
|
1390
|
+
if (heard.transcript !== undefined)
|
|
1391
|
+
intake.transcripts.push(heard.transcript);
|
|
1240
1392
|
}
|
|
1241
1393
|
catch (error) {
|
|
1242
|
-
const reason =
|
|
1394
|
+
const reason = errorText(error);
|
|
1243
1395
|
intake.lines.push(`${label} could not be taken in: ${reason}`);
|
|
1244
1396
|
log.warn('Telegram attachment failed', { from: job.userId, kind: attachment.kind, error: reason });
|
|
1245
1397
|
}
|
|
@@ -1250,242 +1402,261 @@ export function createTelegramGateway(context) {
|
|
|
1250
1402
|
return intake;
|
|
1251
1403
|
}
|
|
1252
1404
|
/**
|
|
1253
|
-
* The
|
|
1254
|
-
*
|
|
1255
|
-
*
|
|
1256
|
-
* Everything the assistant did not write itself is introduced as what it
|
|
1257
|
-
* is: the user's own words stand as they are, a transcript says that it is
|
|
1258
|
-
* a transcript, and a quoted notification is fenced off with a line saying
|
|
1259
|
-
* where it ends. None of it is trusted less for that - it is all the
|
|
1260
|
-
* owner's own material - but a turn that cannot tell a notification apart from an
|
|
1261
|
-
* instruction is a turn that will eventually follow the notification.
|
|
1405
|
+
* The words in one audible file. A failed transcription is reported in the
|
|
1406
|
+
* line the turn is handed rather than thrown: the audio itself is still on
|
|
1407
|
+
* disk, and the assistant can say so.
|
|
1262
1408
|
*/
|
|
1263
|
-
function
|
|
1264
|
-
const
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1409
|
+
async function listen(job, heard, signal) {
|
|
1410
|
+
const { attachment, label, bytes, path } = heard;
|
|
1411
|
+
const config = settings();
|
|
1412
|
+
const length = humanDuration(attachment.duration);
|
|
1413
|
+
const spoken = length ? `${label} (${length})` : label;
|
|
1414
|
+
try {
|
|
1415
|
+
const result = await transcribe({
|
|
1416
|
+
audio: bytes,
|
|
1417
|
+
mime: attachment.mime,
|
|
1418
|
+
fileName: attachment.fileName,
|
|
1419
|
+
engine: config.transcribe,
|
|
1420
|
+
model: config.transcribeModel,
|
|
1421
|
+
lang: context.config.voice.lang,
|
|
1422
|
+
home: context.config.home,
|
|
1423
|
+
signal,
|
|
1424
|
+
});
|
|
1425
|
+
// Echoed back, because a transcript nobody can check is a
|
|
1426
|
+
// misheard sentence the assistant answers with a straight face.
|
|
1427
|
+
say(job.chatId, '🎤 ' + (result.text.length > TRANSCRIPT_ECHO ? result.text.slice(0, TRANSCRIPT_ECHO) + ' …' : result.text));
|
|
1428
|
+
log.info('Telegram voice note transcribed', {
|
|
1429
|
+
from: job.userId,
|
|
1430
|
+
engine: result.engine,
|
|
1431
|
+
ms: result.ms,
|
|
1432
|
+
chars: result.text.length,
|
|
1433
|
+
});
|
|
1434
|
+
return {
|
|
1435
|
+
line: `${spoken}, transcribed by ${result.engine}; the wording may be imperfect. The audio itself is at ${path}.`,
|
|
1436
|
+
transcript: result.text,
|
|
1437
|
+
};
|
|
1275
1438
|
}
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
if (parts.length === 0 || (!written && intake.transcripts.length === 0)) {
|
|
1281
|
-
parts.push('They sent this without saying anything. Look at it and say what you make of it.');
|
|
1439
|
+
catch (error) {
|
|
1440
|
+
const reason = errorText(error);
|
|
1441
|
+
log.warn('Telegram transcription failed', { from: job.userId, error: reason });
|
|
1442
|
+
return { line: `${spoken} could not be transcribed: ${reason} The audio is at ${path}.` };
|
|
1282
1443
|
}
|
|
1283
|
-
return parts.join('\n\n');
|
|
1284
1444
|
}
|
|
1285
1445
|
/* ----------------------------- turns ----------------------------- */
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1446
|
+
/**
|
|
1447
|
+
* What the phone shows while a turn works. Nothing to show yet is the
|
|
1448
|
+
* normal state of a long turn; without a sign of life the phone looks
|
|
1449
|
+
* broken. So: the typing bubble, a reaction on the message that says it
|
|
1450
|
+
* was seen (without adding a message to a chat the answer is about to
|
|
1451
|
+
* land in anyway), and after a while one progress line, rewritten as the
|
|
1452
|
+
* turn moves on and gone once the answer is there.
|
|
1453
|
+
*/
|
|
1454
|
+
function startPresence(job) {
|
|
1455
|
+
const { chatId } = job;
|
|
1291
1456
|
const typing = setInterval(() => {
|
|
1292
1457
|
// Not while the turn is waiting on an answer: a typing bubble over an
|
|
1293
1458
|
// open question claims the machine is busy when it is the person who
|
|
1294
1459
|
// is being waited for.
|
|
1295
1460
|
if (openQuestion(chatId))
|
|
1296
1461
|
return;
|
|
1297
|
-
|
|
1462
|
+
showTyping(chatId);
|
|
1298
1463
|
}, TYPING_INTERVAL_MS);
|
|
1299
1464
|
typing.unref?.();
|
|
1300
|
-
|
|
1301
|
-
// Seen, and being worked on. A reaction says that without adding a
|
|
1302
|
-
// message to a chat the answer is about to land in anyway.
|
|
1465
|
+
showTyping(chatId);
|
|
1303
1466
|
react(chatId, job.messageId, REACTION.working);
|
|
1304
|
-
// Nothing to show yet is the normal state of a long turn; without a sign
|
|
1305
|
-
// of life the phone looks broken. One line, rewritten as the turn moves
|
|
1306
|
-
// on, and gone once the answer is there.
|
|
1307
|
-
const openedAt = Date.now();
|
|
1308
1467
|
const progress = startProgress(chatId);
|
|
1309
1468
|
const firstNote = setTimeout(() => progress.show('Working on it …'), FIRST_NOTE_MS);
|
|
1310
1469
|
firstNote.unref?.();
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1470
|
+
return {
|
|
1471
|
+
progress,
|
|
1472
|
+
openedAt: Date.now(),
|
|
1473
|
+
end: () => {
|
|
1474
|
+
clearTimeout(firstNote);
|
|
1475
|
+
clearInterval(typing);
|
|
1476
|
+
progress.clear();
|
|
1477
|
+
},
|
|
1478
|
+
};
|
|
1479
|
+
}
|
|
1480
|
+
async function runTurn(job) {
|
|
1481
|
+
const { userId, chatId } = job;
|
|
1482
|
+
const cancel = new AbortController();
|
|
1483
|
+
turns.set(userId, cancel);
|
|
1484
|
+
const turn = { job, signal: cancel.signal, presence: startPresence(job), answer: '', failed: false };
|
|
1318
1485
|
// Set when the message turned out to be the answer to a task's question
|
|
1319
1486
|
// and was handed to the card instead of a turn.
|
|
1320
1487
|
let answeredTask = false;
|
|
1321
1488
|
try {
|
|
1322
|
-
|
|
1323
|
-
// typing bubble and the progress note above already cover the wait.
|
|
1324
|
-
const intake = await takeIn(job, turn.signal);
|
|
1325
|
-
// Where this belongs. A reply to something the bot sent goes back to
|
|
1326
|
-
// whatever that message was about; everything else is the running
|
|
1327
|
-
// Telegram conversation, exactly as before.
|
|
1328
|
-
origin = job.replyTo?.fromBot === true ? findOrigin(context, chatId, job.replyTo.messageId) : undefined;
|
|
1329
|
-
// A reply to an agent's question is the answer, not a conversation:
|
|
1330
|
-
// it goes onto the card and the task carries on, and no chat turn is
|
|
1331
|
-
// started about it.
|
|
1332
|
-
const asked = origin ? questionForOrigin(context, origin) : undefined;
|
|
1333
|
-
if (asked) {
|
|
1334
|
-
answeredTask = true;
|
|
1335
|
-
const text = [job.text?.trim() ?? '', ...intake.transcripts].filter((part) => part.length > 0).join('\n\n');
|
|
1336
|
-
if (!text) {
|
|
1337
|
-
say(chatId, 'Write the answer as text (or say it in a voice message) to answer that question.', {
|
|
1338
|
-
...(job.messageId !== undefined ? { replyTo: job.messageId } : {}),
|
|
1339
|
-
});
|
|
1340
|
-
failed = true;
|
|
1341
|
-
}
|
|
1342
|
-
else {
|
|
1343
|
-
const result = await answerTaskQuestion(context, asked, text);
|
|
1344
|
-
failed = !result.ok;
|
|
1345
|
-
log.info('Telegram reply answered a task question', {
|
|
1346
|
-
from: userId,
|
|
1347
|
-
task: asked.taskId,
|
|
1348
|
-
ok: result.ok,
|
|
1349
|
-
});
|
|
1350
|
-
say(chatId, result.ok ? 'Answered — the task continues.' : `Could not answer: ${result.reason}`, {
|
|
1351
|
-
...(job.messageId !== undefined ? { replyTo: job.messageId } : {}),
|
|
1352
|
-
});
|
|
1353
|
-
}
|
|
1354
|
-
return;
|
|
1355
|
-
}
|
|
1356
|
-
const thread = origin
|
|
1357
|
-
? openThread(context, origin, () => resolveSession(chatId))
|
|
1358
|
-
: { session: resolveSession(chatId), fresh: false };
|
|
1359
|
-
session = thread.session;
|
|
1360
|
-
// Whatever answers in this conversation later without being asked
|
|
1361
|
-
// here - a report-back - knows where to find this chat.
|
|
1362
|
-
context.assistant.store.setMeta(sessionChatKey(session.id), String(chatId));
|
|
1363
|
-
// The notification itself goes in front of the turn only when this
|
|
1364
|
-
// conversation has not seen it yet. A thread being continued already
|
|
1365
|
-
// holds it in its history, and repeating it every time would push the
|
|
1366
|
-
// actual exchange out of the window. A notice that never had a record
|
|
1367
|
-
// is the exception: there is nothing to read back, so its own text is
|
|
1368
|
-
// all the context there will ever be.
|
|
1369
|
-
const quoted = origin
|
|
1370
|
-
? thread.fresh
|
|
1371
|
-
? originContext(context, origin)
|
|
1372
|
-
: origin.ref
|
|
1373
|
-
? undefined
|
|
1374
|
-
: origin.snippet
|
|
1375
|
-
: undefined;
|
|
1376
|
-
const prompt = buildPrompt(job, intake, quoted);
|
|
1377
|
-
log.info('Telegram message accepted', {
|
|
1378
|
-
from: userId,
|
|
1379
|
-
sessionId: session.id,
|
|
1380
|
-
permission: config.permission,
|
|
1381
|
-
attachments: intake.saved,
|
|
1382
|
-
spoken: intake.transcripts.length,
|
|
1383
|
-
replyingTo: origin?.kind,
|
|
1384
|
-
thread: thread.fresh ? 'new' : 'continued',
|
|
1385
|
-
text: prompt.slice(0, AUDIT_TEXT),
|
|
1386
|
-
});
|
|
1387
|
-
// A streamed answer quotes what it answers on its first message, the
|
|
1388
|
-
// way a whole one would.
|
|
1389
|
-
stream = config.stream
|
|
1390
|
-
? startStream(chatId, origin && job.messageId !== undefined ? job.messageId : undefined)
|
|
1391
|
-
: undefined;
|
|
1392
|
-
for await (const event of context.assistant.chat({
|
|
1393
|
-
text: prompt,
|
|
1394
|
-
sessionId: session.id,
|
|
1395
|
-
permission: config.permission,
|
|
1396
|
-
model: config.model,
|
|
1397
|
-
signal: turn.signal,
|
|
1398
|
-
})) {
|
|
1399
|
-
if (event.type === 'text') {
|
|
1400
|
-
if (!stream)
|
|
1401
|
-
continue;
|
|
1402
|
-
// The progress line was standing in for an answer that had not
|
|
1403
|
-
// started. It has started.
|
|
1404
|
-
progress.clear();
|
|
1405
|
-
stream.push(event.delta);
|
|
1406
|
-
}
|
|
1407
|
-
else if (event.type === 'done') {
|
|
1408
|
-
answer = event.text;
|
|
1409
|
-
}
|
|
1410
|
-
else if (event.type === 'error') {
|
|
1411
|
-
// Never swallowed: an error the user does not see is an answer that
|
|
1412
|
-
// simply never arrives.
|
|
1413
|
-
failed = true;
|
|
1414
|
-
say(chatId, `Error: ${event.message}`);
|
|
1415
|
-
}
|
|
1416
|
-
else if (event.type === 'question') {
|
|
1417
|
-
// The turn has stopped and is waiting on a person. Whatever the
|
|
1418
|
-
// progress line last claimed it was doing, it is not doing that.
|
|
1419
|
-
progress.clear();
|
|
1420
|
-
// Idempotent: push may put the same question here in the same tick,
|
|
1421
|
-
// because it cannot know this turn came from the phone.
|
|
1422
|
-
offerQuestion(chatId, event, 'turn');
|
|
1423
|
-
}
|
|
1424
|
-
else if (event.type === 'question-closed') {
|
|
1425
|
-
closeQuestion(event.id, event.reason, event.answer);
|
|
1426
|
-
}
|
|
1427
|
-
else if (event.type === 'status' && Date.now() - openedAt >= FIRST_NOTE_MS) {
|
|
1428
|
-
// Only once the turn has been quiet long enough to worry about;
|
|
1429
|
-
// the line itself then rewrites at its own pace.
|
|
1430
|
-
progress.show(event.detail ? `${event.label} – ${event.detail}` : event.label);
|
|
1431
|
-
}
|
|
1432
|
-
}
|
|
1489
|
+
answeredTask = await converse(turn);
|
|
1433
1490
|
}
|
|
1434
1491
|
catch (error) {
|
|
1435
1492
|
if (!turn.signal.aborted) {
|
|
1436
|
-
failed = true;
|
|
1493
|
+
turn.failed = true;
|
|
1437
1494
|
log.error('Telegram turn failed', { from: userId, error: errorText(error) });
|
|
1438
1495
|
say(chatId, `Error: ${errorText(error)}`);
|
|
1439
1496
|
}
|
|
1440
1497
|
}
|
|
1441
1498
|
finally {
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
progress.clear();
|
|
1445
|
-
if (turns.get(userId) === turn)
|
|
1499
|
+
turn.presence.end();
|
|
1500
|
+
if (turns.get(userId) === cancel)
|
|
1446
1501
|
turns.delete(userId);
|
|
1447
1502
|
}
|
|
1448
1503
|
if (answeredTask) {
|
|
1449
|
-
react(chatId, job.messageId, failed ? REACTION.failed : REACTION.done);
|
|
1504
|
+
react(chatId, job.messageId, turn.failed ? REACTION.failed : REACTION.done);
|
|
1450
1505
|
return;
|
|
1451
1506
|
}
|
|
1507
|
+
await concludeTurn(turn);
|
|
1508
|
+
}
|
|
1509
|
+
/**
|
|
1510
|
+
* Everything up to the end of the provider's event stream. Returns true
|
|
1511
|
+
* when the message was the answer to a task's question and no chat turn
|
|
1512
|
+
* was started for it.
|
|
1513
|
+
*/
|
|
1514
|
+
async function converse(turn) {
|
|
1515
|
+
const { job, signal } = turn;
|
|
1516
|
+
const { userId, chatId } = job;
|
|
1517
|
+
const config = settings();
|
|
1518
|
+
// Files first: downloading and listening is part of the turn, and the
|
|
1519
|
+
// typing bubble and the progress note already cover the wait.
|
|
1520
|
+
const intake = await takeIn(job, signal);
|
|
1521
|
+
// Where this belongs. A reply to something the bot sent goes back to
|
|
1522
|
+
// whatever that message was about; everything else is the running
|
|
1523
|
+
// Telegram conversation, exactly as before.
|
|
1524
|
+
turn.origin = job.replyTo?.fromBot === true ? findOrigin(context, chatId, job.replyTo.messageId) : undefined;
|
|
1525
|
+
// A reply to an agent's question is the answer, not a conversation:
|
|
1526
|
+
// it goes onto the card and the task carries on, and no chat turn is
|
|
1527
|
+
// started about it.
|
|
1528
|
+
const asked = turn.origin ? questionForOrigin(context, turn.origin) : undefined;
|
|
1529
|
+
if (asked) {
|
|
1530
|
+
turn.failed = !(await answerFromReply(job, intake, asked));
|
|
1531
|
+
return true;
|
|
1532
|
+
}
|
|
1533
|
+
const thread = turn.origin
|
|
1534
|
+
? openThread(context, turn.origin, () => chatSession(context, chatId))
|
|
1535
|
+
: { session: chatSession(context, chatId), fresh: false };
|
|
1536
|
+
turn.session = thread.session;
|
|
1537
|
+
// Whatever answers in this conversation later without being asked
|
|
1538
|
+
// here - a report-back - knows where to find this chat.
|
|
1539
|
+
context.assistant.store.setMeta(sessionChatKey(thread.session.id), String(chatId));
|
|
1540
|
+
const prompt = buildPrompt(job, intake, quotedNotification(context, turn.origin, thread.fresh));
|
|
1541
|
+
log.info('Telegram message accepted', {
|
|
1542
|
+
from: userId,
|
|
1543
|
+
sessionId: thread.session.id,
|
|
1544
|
+
permission: config.permission,
|
|
1545
|
+
attachments: intake.saved,
|
|
1546
|
+
spoken: intake.transcripts.length,
|
|
1547
|
+
replyingTo: turn.origin?.kind,
|
|
1548
|
+
thread: thread.fresh ? 'new' : 'continued',
|
|
1549
|
+
text: prompt.slice(0, AUDIT_TEXT),
|
|
1550
|
+
});
|
|
1551
|
+
// A streamed answer quotes what it answers on its first message, the
|
|
1552
|
+
// way a whole one would.
|
|
1553
|
+
turn.stream = config.stream
|
|
1554
|
+
? startStream(chatId, turn.origin && job.messageId !== undefined ? job.messageId : undefined)
|
|
1555
|
+
: undefined;
|
|
1556
|
+
for await (const event of context.assistant.chat({
|
|
1557
|
+
text: prompt,
|
|
1558
|
+
sessionId: thread.session.id,
|
|
1559
|
+
permission: config.permission,
|
|
1560
|
+
model: config.model,
|
|
1561
|
+
signal,
|
|
1562
|
+
})) {
|
|
1563
|
+
relayEvent(turn, event);
|
|
1564
|
+
}
|
|
1565
|
+
return false;
|
|
1566
|
+
}
|
|
1567
|
+
/** Put a reply onto the task card it answers. True when the card took it. */
|
|
1568
|
+
async function answerFromReply(job, intake, asked) {
|
|
1569
|
+
const { userId, chatId } = job;
|
|
1570
|
+
const quote = job.messageId !== undefined ? { replyTo: job.messageId } : {};
|
|
1571
|
+
const text = [job.text?.trim() ?? '', ...intake.transcripts].filter((part) => part.length > 0).join('\n\n');
|
|
1572
|
+
if (!text) {
|
|
1573
|
+
say(chatId, 'Write the answer as text (or say it in a voice message) to answer that question.', quote);
|
|
1574
|
+
return false;
|
|
1575
|
+
}
|
|
1576
|
+
const result = await answerTaskQuestion(context, asked, text);
|
|
1577
|
+
log.info('Telegram reply answered a task question', { from: userId, task: asked.taskId, ok: result.ok });
|
|
1578
|
+
say(chatId, result.ok ? 'Answered — the task continues.' : `Could not answer: ${result.reason}`, quote);
|
|
1579
|
+
return result.ok;
|
|
1580
|
+
}
|
|
1581
|
+
/** Carry one event of the provider's stream onto the phone and into the turn's state. */
|
|
1582
|
+
function relayEvent(turn, event) {
|
|
1583
|
+
const { chatId } = turn.job;
|
|
1584
|
+
const { presence } = turn;
|
|
1585
|
+
switch (event.type) {
|
|
1586
|
+
case 'text':
|
|
1587
|
+
if (!turn.stream)
|
|
1588
|
+
return;
|
|
1589
|
+
// The progress line was standing in for an answer that had not
|
|
1590
|
+
// started. It has started.
|
|
1591
|
+
presence.progress.clear();
|
|
1592
|
+
turn.stream.push(event.delta);
|
|
1593
|
+
return;
|
|
1594
|
+
case 'done':
|
|
1595
|
+
turn.answer = event.text;
|
|
1596
|
+
return;
|
|
1597
|
+
case 'error':
|
|
1598
|
+
// Never swallowed: an error the user does not see is an answer that
|
|
1599
|
+
// simply never arrives.
|
|
1600
|
+
turn.failed = true;
|
|
1601
|
+
say(chatId, `Error: ${event.message}`);
|
|
1602
|
+
return;
|
|
1603
|
+
case 'question':
|
|
1604
|
+
// The turn has stopped and is waiting on a person. Whatever the
|
|
1605
|
+
// progress line last claimed it was doing, it is not doing that.
|
|
1606
|
+
presence.progress.clear();
|
|
1607
|
+
// Idempotent: push may put the same question here in the same tick,
|
|
1608
|
+
// because it cannot know this turn came from the phone.
|
|
1609
|
+
offerQuestion(chatId, event, 'turn');
|
|
1610
|
+
return;
|
|
1611
|
+
case 'question-closed':
|
|
1612
|
+
closeQuestion(event.id, event.reason, event.answer);
|
|
1613
|
+
return;
|
|
1614
|
+
case 'status':
|
|
1615
|
+
// Only once the turn has been quiet long enough to worry about;
|
|
1616
|
+
// the line itself then rewrites at its own pace.
|
|
1617
|
+
if (Date.now() - presence.openedAt >= FIRST_NOTE_MS) {
|
|
1618
|
+
presence.progress.show(event.detail ? `${event.label} – ${event.detail}` : event.label);
|
|
1619
|
+
}
|
|
1620
|
+
return;
|
|
1621
|
+
}
|
|
1622
|
+
}
|
|
1623
|
+
/** What happens once the provider's stream has ended, however it ended. */
|
|
1624
|
+
async function concludeTurn(turn) {
|
|
1625
|
+
const { job, signal } = turn;
|
|
1626
|
+
const { chatId } = job;
|
|
1452
1627
|
// Whatever was streamed is written out one last time, cancelled turns
|
|
1453
1628
|
// included: half an answer that stands is better than half an answer
|
|
1454
1629
|
// that is quietly wound back.
|
|
1455
|
-
const streamed = stream ? await stream.finish(answer) : [];
|
|
1456
|
-
if (
|
|
1630
|
+
const streamed = turn.stream ? await turn.stream.finish(turn.answer) : [];
|
|
1631
|
+
if (signal.aborted) {
|
|
1457
1632
|
react(chatId, job.messageId, REACTION.failed);
|
|
1458
1633
|
say(chatId, 'Cancelled.');
|
|
1459
1634
|
return;
|
|
1460
1635
|
}
|
|
1461
|
-
react(chatId, job.messageId, failed ? REACTION.failed : REACTION.done);
|
|
1636
|
+
react(chatId, job.messageId, turn.failed ? REACTION.failed : REACTION.done);
|
|
1462
1637
|
// The answer carries its own origin: replying to it comes back to this
|
|
1463
1638
|
// conversation, whichever one it turned out to be. That is what lets a
|
|
1464
1639
|
// thread continue days later, and what keeps a reply to an old answer
|
|
1465
1640
|
// out of today's chat.
|
|
1466
|
-
const
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
...(origin?.title ? { title: origin.title } : {}),
|
|
1471
|
-
},
|
|
1472
|
-
// Quote the message being answered when this turn belongs to a thread
|
|
1473
|
-
// of its own, so the phone shows which of the day's notifications it
|
|
1474
|
-
// is about. In the plain chat the quoted line would only be noise.
|
|
1475
|
-
...(origin && job.messageId !== undefined ? { replyTo: job.messageId } : {}),
|
|
1641
|
+
const origin = {
|
|
1642
|
+
kind: 'answer',
|
|
1643
|
+
...(turn.session ? { sessionId: turn.session.id } : {}),
|
|
1644
|
+
...(turn.origin?.title ? { title: turn.origin.title } : {}),
|
|
1476
1645
|
};
|
|
1477
1646
|
if (streamed.length > 0) {
|
|
1478
1647
|
// The answer is already on the screen. What is left is filing it, so
|
|
1479
1648
|
// that a reply to it finds its way back to this conversation.
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
}
|
|
1483
|
-
else if (answer.trim().length > 0) {
|
|
1484
|
-
say(chatId, answer, answered);
|
|
1485
|
-
}
|
|
1486
|
-
else {
|
|
1487
|
-
say(chatId, 'No answer was returned.', answered);
|
|
1649
|
+
rememberOrigin(context, chatId, streamed, origin);
|
|
1650
|
+
return;
|
|
1488
1651
|
}
|
|
1652
|
+
const options = {
|
|
1653
|
+
origin,
|
|
1654
|
+
// Quote the message being answered when this turn belongs to a thread
|
|
1655
|
+
// of its own, so the phone shows which of the day's notifications it
|
|
1656
|
+
// is about. In the plain chat the quoted line would only be noise.
|
|
1657
|
+
...(turn.origin && job.messageId !== undefined ? { replyTo: job.messageId } : {}),
|
|
1658
|
+
};
|
|
1659
|
+
say(chatId, turn.answer.trim().length > 0 ? turn.answer : 'No answer was returned.', options);
|
|
1489
1660
|
}
|
|
1490
1661
|
/* ---------------------------- dispatch ---------------------------- */
|
|
1491
1662
|
function enqueue(userId, job) {
|
|
@@ -1506,24 +1677,6 @@ export function createTelegramGateway(context) {
|
|
|
1506
1677
|
});
|
|
1507
1678
|
return true;
|
|
1508
1679
|
}
|
|
1509
|
-
/**
|
|
1510
|
-
* What an allowed sender is told when their own message was refused.
|
|
1511
|
-
*
|
|
1512
|
-
* Every reason in here is one the guard can only reach *after* the
|
|
1513
|
-
* allowlist has said yes, in the sender's own private chat - so the
|
|
1514
|
-
* silence that protects the bot from strangers buys nothing here, and
|
|
1515
|
-
* costs the owner a message that seems to vanish. Everything else stays
|
|
1516
|
-
* silent, `not_private` included: a word in a group chat is exactly what
|
|
1517
|
-
* the guard refused to allow.
|
|
1518
|
-
*/
|
|
1519
|
-
const REJECTION_NOTE = {
|
|
1520
|
-
forwarded: 'Forwarded messages are not accepted - they carry someone else\'s words. Send the text or the file yourself.',
|
|
1521
|
-
media_off: 'Attachments are switched off for this gateway. You can turn them on in the gateway settings.',
|
|
1522
|
-
unsupported_media: 'Animated and video stickers cannot be read.',
|
|
1523
|
-
too_large: 'That file is larger than this gateway accepts.',
|
|
1524
|
-
too_long: 'That message is too long. Shorten it, or send it as a file.',
|
|
1525
|
-
no_content: 'There was nothing in that message I can work with.',
|
|
1526
|
-
};
|
|
1527
1680
|
/**
|
|
1528
1681
|
* A tap on one of a question's options.
|
|
1529
1682
|
*
|
|
@@ -1545,7 +1698,7 @@ export function createTelegramGateway(context) {
|
|
|
1545
1698
|
return;
|
|
1546
1699
|
}
|
|
1547
1700
|
const taken = submitAnswer(post, { selected: [option], source: 'telegram', at: Date.now() });
|
|
1548
|
-
await acknowledge(taken ? '✓ ' + oneLine(chosen.label,
|
|
1701
|
+
await acknowledge(taken ? '✓ ' + oneLine(chosen.label, TAP_TOAST_WIDTH) : 'That question is no longer open.');
|
|
1549
1702
|
}
|
|
1550
1703
|
/**
|
|
1551
1704
|
* A tapped button: the one gesture on Telegram that means "I have read
|
|
@@ -1588,60 +1741,73 @@ export function createTelegramGateway(context) {
|
|
|
1588
1741
|
// data is never believed because of what it says - the guard above has
|
|
1589
1742
|
// already proved who pressed it.
|
|
1590
1743
|
const action = readCallbackData(data);
|
|
1591
|
-
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
|
|
1595
|
-
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
|
|
1600
|
-
|
|
1601
|
-
|
|
1744
|
+
switch (action.kind) {
|
|
1745
|
+
case 'notification-read-done':
|
|
1746
|
+
case 'mail-read-done':
|
|
1747
|
+
await acknowledge('Already marked as read.');
|
|
1748
|
+
return;
|
|
1749
|
+
case 'question-done':
|
|
1750
|
+
await acknowledge('That question is already settled.');
|
|
1751
|
+
return;
|
|
1752
|
+
case 'question':
|
|
1753
|
+
await answerFromTap(action.questionId, action.option, chatId, acknowledge);
|
|
1754
|
+
return;
|
|
1755
|
+
case 'mail-read':
|
|
1756
|
+
// A button under a mail pushed before mail was removed. The migration
|
|
1757
|
+
// kept the mail's id for the notification it became, so the tap still
|
|
1758
|
+
// lands where it should when that notification is there; otherwise
|
|
1759
|
+
// there is nothing left to mark.
|
|
1760
|
+
markMigratedMailRead(action.mailId);
|
|
1761
|
+
await acknowledge('Already handled.');
|
|
1762
|
+
return;
|
|
1763
|
+
case 'notification-read':
|
|
1764
|
+
await markNotificationRead(action.notificationId, { from: verdict.userId, chatId, messageId }, acknowledge);
|
|
1765
|
+
return;
|
|
1766
|
+
case 'unknown':
|
|
1767
|
+
// A button from an older version of this code, or one we no longer
|
|
1768
|
+
// draw. Saying so beats leaving the phone to guess.
|
|
1769
|
+
await acknowledge('This button no longer does anything.');
|
|
1770
|
+
return;
|
|
1602
1771
|
}
|
|
1772
|
+
}
|
|
1773
|
+
function markMigratedMailRead(mailId) {
|
|
1603
1774
|
const store = context.assistant.store.org;
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
// kept the mail's id for the notification it became, so the tap still
|
|
1607
|
-
// lands where it should when that notification is there; otherwise
|
|
1608
|
-
// there is nothing left to mark.
|
|
1609
|
-
const migrated = action.mailId ? store.getNotification(action.mailId) : null;
|
|
1610
|
-
if (migrated && !migrated.readAt) {
|
|
1611
|
-
store.markNotificationsRead([migrated.id]);
|
|
1612
|
-
context.assistant.emit('changed', { kind: 'notifications', id: 'all' });
|
|
1613
|
-
}
|
|
1614
|
-
await acknowledge('Already handled.');
|
|
1615
|
-
return;
|
|
1616
|
-
}
|
|
1617
|
-
if (action.kind !== 'notification-read') {
|
|
1618
|
-
// A button from an older version of this code, or one we no longer
|
|
1619
|
-
// draw. Saying so beats leaving the phone to guess.
|
|
1620
|
-
await acknowledge('This button no longer does anything.');
|
|
1775
|
+
const migrated = store.getNotification(mailId);
|
|
1776
|
+
if (!migrated || migrated.readAt)
|
|
1621
1777
|
return;
|
|
1622
|
-
|
|
1623
|
-
|
|
1778
|
+
store.markNotificationsRead([migrated.id]);
|
|
1779
|
+
announceNotificationsChanged();
|
|
1780
|
+
}
|
|
1781
|
+
/**
|
|
1782
|
+
* The web inbox follows the socket, so it has to hear about a read - on
|
|
1783
|
+
* `changed`, never on `notification`: push listens to that one and would
|
|
1784
|
+
* send the very notification that was just marked read straight back.
|
|
1785
|
+
*/
|
|
1786
|
+
function announceNotificationsChanged() {
|
|
1787
|
+
context.assistant.emit('changed', { kind: 'notifications', id: 'all' });
|
|
1788
|
+
}
|
|
1789
|
+
async function markNotificationRead(notificationId, tap, acknowledge) {
|
|
1790
|
+
const store = context.assistant.store.org;
|
|
1791
|
+
const notification = store.getNotification(notificationId);
|
|
1624
1792
|
if (!notification) {
|
|
1625
1793
|
await acknowledge('That notification is gone.');
|
|
1626
1794
|
return;
|
|
1627
1795
|
}
|
|
1628
1796
|
store.markNotificationsRead([notification.id]);
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
// send the very notification that was just marked read straight back.
|
|
1632
|
-
context.assistant.emit('changed', { kind: 'notifications', id: 'all' });
|
|
1633
|
-
log.info('Notification marked read from Telegram', { from: verdict.userId, notification: notification.id });
|
|
1797
|
+
announceNotificationsChanged();
|
|
1798
|
+
log.info('Notification marked read from Telegram', { from: tap.from, notification: notification.id });
|
|
1634
1799
|
await acknowledge('✓ Marked as read.');
|
|
1635
1800
|
// The button has done its work; what is left in the chat should say so
|
|
1636
1801
|
// rather than invite a second tap. A failure here costs a stale button,
|
|
1637
1802
|
// never the read state that was already written.
|
|
1638
|
-
|
|
1639
|
-
|
|
1640
|
-
|
|
1641
|
-
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
|
|
1803
|
+
const client = api;
|
|
1804
|
+
if (!client || tap.chatId === undefined || tap.messageId === undefined)
|
|
1805
|
+
return;
|
|
1806
|
+
try {
|
|
1807
|
+
await client.editMessageReplyMarkup(tap.chatId, tap.messageId, notificationReadDone(Date.now()));
|
|
1808
|
+
}
|
|
1809
|
+
catch (error) {
|
|
1810
|
+
log.debug('Telegram read button could not be redrawn', { error: errorText(error) });
|
|
1645
1811
|
}
|
|
1646
1812
|
}
|
|
1647
1813
|
function handleUpdate(update) {
|
|
@@ -1656,41 +1822,14 @@ export function createTelegramGateway(context) {
|
|
|
1656
1822
|
const verdict = classifyUpdate(update, settings());
|
|
1657
1823
|
lastEventAt = Date.now();
|
|
1658
1824
|
// Noted before anything is decided about it: `/clear` empties the chat,
|
|
1659
|
-
// and a message that was refused is standing in it just the same.
|
|
1660
|
-
|
|
1825
|
+
// and a message that was refused is standing in it just the same. Not
|
|
1826
|
+
// for strangers, though: they can never clear anything, and a ledger
|
|
1827
|
+
// entry per stranger would be storage that anybody on Telegram can grow.
|
|
1828
|
+
if (isOwnChat(verdict) && (verdict.reason === undefined || !STRANGER_REJECTIONS.includes(verdict.reason))) {
|
|
1661
1829
|
noteMessages(context, verdict.chatId, [verdict.messageId]);
|
|
1662
1830
|
}
|
|
1663
1831
|
if (!verdict.ok) {
|
|
1664
|
-
|
|
1665
|
-
from: verdict.userId,
|
|
1666
|
-
username: usernameOf(update),
|
|
1667
|
-
reason: verdict.reason,
|
|
1668
|
-
text: verdict.text?.slice(0, REJECT_TEXT),
|
|
1669
|
-
});
|
|
1670
|
-
// An allowed sender in their own chat hears why. Which is not a leak:
|
|
1671
|
-
// they already know the bot answers them.
|
|
1672
|
-
const note = verdict.reason ? REJECTION_NOTE[verdict.reason] : undefined;
|
|
1673
|
-
if (note && verdict.chatId !== undefined && verdict.chatId === verdict.userId) {
|
|
1674
|
-
say(verdict.chatId, note);
|
|
1675
|
-
return;
|
|
1676
|
-
}
|
|
1677
|
-
// The one and only answer a rejected update ever gets: the number the
|
|
1678
|
-
// sender already carries. Without it nobody can put themselves on the
|
|
1679
|
-
// allowlist; with it they learn nothing new. Once an hour, so it cannot
|
|
1680
|
-
// be used as an echo, and only in the sender's own chat - the
|
|
1681
|
-
// allowlist check comes before the private-chat one, so this is the
|
|
1682
|
-
// last place that could turn the bot into a voice in a group.
|
|
1683
|
-
if (verdict.reason === 'not_allowed' && verdict.command === 'id') {
|
|
1684
|
-
const userId = verdict.userId;
|
|
1685
|
-
const chatId = verdict.chatId;
|
|
1686
|
-
if (userId !== undefined && chatId === userId) {
|
|
1687
|
-
const last = idReplies.get(userId) ?? 0;
|
|
1688
|
-
if (Date.now() - last >= ID_REPLY_INTERVAL_MS) {
|
|
1689
|
-
idReplies.set(userId, Date.now());
|
|
1690
|
-
say(chatId, String(userId));
|
|
1691
|
-
}
|
|
1692
|
-
}
|
|
1693
|
-
}
|
|
1832
|
+
refuseUpdate(update, verdict);
|
|
1694
1833
|
return;
|
|
1695
1834
|
}
|
|
1696
1835
|
if (verdict.command) {
|
|
@@ -1704,46 +1843,42 @@ export function createTelegramGateway(context) {
|
|
|
1704
1843
|
});
|
|
1705
1844
|
return;
|
|
1706
1845
|
}
|
|
1846
|
+
acceptMessage(verdict);
|
|
1847
|
+
}
|
|
1848
|
+
/** A refused update gets no answer, except in the two cases below. */
|
|
1849
|
+
function refuseUpdate(update, verdict) {
|
|
1850
|
+
log.warn('Telegram update rejected', {
|
|
1851
|
+
from: verdict.userId,
|
|
1852
|
+
username: usernameOf(update),
|
|
1853
|
+
reason: verdict.reason,
|
|
1854
|
+
text: verdict.text?.slice(0, REJECT_TEXT),
|
|
1855
|
+
});
|
|
1856
|
+
// An allowed sender in their own chat hears why. Which is not a leak:
|
|
1857
|
+
// they already know the bot answers them.
|
|
1858
|
+
const note = verdict.reason ? REJECTION_NOTE[verdict.reason] : undefined;
|
|
1859
|
+
if (note && isOwnChat(verdict)) {
|
|
1860
|
+
say(verdict.chatId, note);
|
|
1861
|
+
return;
|
|
1862
|
+
}
|
|
1863
|
+
// The one and only answer a rejected update ever gets: the number the
|
|
1864
|
+
// sender already carries. Without it nobody can put themselves on the
|
|
1865
|
+
// allowlist; with it they learn nothing new. Once an hour, so it cannot
|
|
1866
|
+
// be used as an echo, and only in the sender's own chat - the
|
|
1867
|
+
// allowlist check comes before the private-chat one, so this is the
|
|
1868
|
+
// last place that could turn the bot into a voice in a group.
|
|
1869
|
+
if (verdict.reason === 'not_allowed' && verdict.command === 'id' && isOwnChat(verdict) && claimIdReply(verdict.userId)) {
|
|
1870
|
+
say(verdict.chatId, String(verdict.userId));
|
|
1871
|
+
}
|
|
1872
|
+
}
|
|
1873
|
+
/** An accepted message that is not a command: an answer to an open question, or a turn. */
|
|
1874
|
+
function acceptMessage(verdict) {
|
|
1707
1875
|
// An accepted verdict always carries the ids, but they are checked
|
|
1708
1876
|
// rather than asserted - nothing here narrows foreign input by claim.
|
|
1709
1877
|
const { userId, chatId } = verdict;
|
|
1710
1878
|
if (userId === undefined || chatId === undefined)
|
|
1711
1879
|
return;
|
|
1712
|
-
|
|
1713
|
-
|
|
1714
|
-
//
|
|
1715
|
-
// This is the branch the whole typed path depends on. Turns are
|
|
1716
|
-
// serialised per sender, and the turn that asked is still holding that
|
|
1717
|
-
// queue while it waits - so an answer that went in as a turn would be
|
|
1718
|
-
// queued behind the very turn it releases, and the two would deadlock
|
|
1719
|
-
// until the question expired. A tap never had this problem: a
|
|
1720
|
-
// `callback_query` is not a message and bypasses the queue by nature.
|
|
1721
|
-
//
|
|
1722
|
-
// But "the turn that asked" is the condition, not "a question exists
|
|
1723
|
-
// somewhere". A card the phone only received as a push - the question
|
|
1724
|
-
// came from a browser tab - leaves an ordinary message alone: swallowing
|
|
1725
|
-
// it would eat the user's next request and hand the blocked turn an
|
|
1726
|
-
// answer nobody gave. Such a card is answered by its buttons, or by a
|
|
1727
|
-
// reply addressed to the card itself.
|
|
1728
|
-
//
|
|
1729
|
-
// Only plain text, though. A photo is content in its own right, and
|
|
1730
|
-
// "here, look at this" is a new turn even mid-question.
|
|
1731
|
-
const candidate = (verdict.text ?? '').trim() && (verdict.attachments ?? []).length === 0 ? openQuestion(chatId) : undefined;
|
|
1732
|
-
const asked = candidate &&
|
|
1733
|
-
(candidate.origin === 'turn' ||
|
|
1734
|
-
(verdict.replyTo?.fromBot === true && verdict.replyTo.messageId === candidate.messageId))
|
|
1735
|
-
? candidate
|
|
1736
|
-
: undefined;
|
|
1737
|
-
if (asked) {
|
|
1738
|
-
if (submitAnswer(asked, readTypedAnswer(verdict.text ?? '', asked.question))) {
|
|
1739
|
-
// No message back: the reaction says it arrived, and the turn that
|
|
1740
|
-
// was waiting is about to say the rest.
|
|
1741
|
-
react(chatId, verdict.messageId, REACTION.done);
|
|
1742
|
-
return;
|
|
1743
|
-
}
|
|
1744
|
-
// The question was already over by the time this got here. Then it was
|
|
1745
|
-
// never an answer, and it goes on as what it looks like: a message.
|
|
1746
|
-
}
|
|
1880
|
+
if (answeredOpenQuestion(verdict, chatId))
|
|
1881
|
+
return;
|
|
1747
1882
|
const job = {
|
|
1748
1883
|
userId,
|
|
1749
1884
|
chatId,
|
|
@@ -1760,9 +1895,65 @@ export function createTelegramGateway(context) {
|
|
|
1760
1895
|
}
|
|
1761
1896
|
dispatch(job);
|
|
1762
1897
|
}
|
|
1898
|
+
/** Takes the message as the answer to the open question, if it is one. False when it is an ordinary message. */
|
|
1899
|
+
function answeredOpenQuestion(verdict, chatId) {
|
|
1900
|
+
const asked = questionBeingAnswered(verdict, chatId);
|
|
1901
|
+
if (!asked)
|
|
1902
|
+
return false;
|
|
1903
|
+
// The question may already have been over by the time this got here.
|
|
1904
|
+
// Then it was never an answer, and it goes on as what it looks like: a
|
|
1905
|
+
// message.
|
|
1906
|
+
if (!submitAnswer(asked, readTypedAnswer(verdict.text ?? '', asked.question)))
|
|
1907
|
+
return false;
|
|
1908
|
+
// No message back: the reaction says it arrived, and the turn that
|
|
1909
|
+
// was waiting is about to say the rest.
|
|
1910
|
+
react(chatId, verdict.messageId, REACTION.done);
|
|
1911
|
+
return true;
|
|
1912
|
+
}
|
|
1913
|
+
/**
|
|
1914
|
+
* The standing question a written message may be the answer to.
|
|
1915
|
+
*
|
|
1916
|
+
* This is the branch the whole typed path depends on. Turns are
|
|
1917
|
+
* serialised per sender, and the turn that asked is still holding that
|
|
1918
|
+
* queue while it waits - so an answer that went in as a turn would be
|
|
1919
|
+
* queued behind the very turn it releases, and the two would deadlock
|
|
1920
|
+
* until the question expired. A tap never had this problem: a
|
|
1921
|
+
* `callback_query` is not a message and bypasses the queue by nature.
|
|
1922
|
+
*
|
|
1923
|
+
* But "the turn that asked" is the condition, not "a question exists
|
|
1924
|
+
* somewhere". A card the phone only received as a push - the question
|
|
1925
|
+
* came from a browser tab - leaves an ordinary message alone: swallowing
|
|
1926
|
+
* it would eat the user's next request and hand the blocked turn an
|
|
1927
|
+
* answer nobody gave. Such a card is answered by its buttons, or by a
|
|
1928
|
+
* reply addressed to the card itself.
|
|
1929
|
+
*
|
|
1930
|
+
* Only plain text, though. A photo is content in its own right, and
|
|
1931
|
+
* "here, look at this" is a new turn even mid-question.
|
|
1932
|
+
*/
|
|
1933
|
+
function questionBeingAnswered(verdict, chatId) {
|
|
1934
|
+
const isPlainText = (verdict.text ?? '').trim() !== '' && (verdict.attachments ?? []).length === 0;
|
|
1935
|
+
if (!isPlainText)
|
|
1936
|
+
return undefined;
|
|
1937
|
+
const candidate = openQuestion(chatId);
|
|
1938
|
+
if (!candidate)
|
|
1939
|
+
return undefined;
|
|
1940
|
+
const repliesToCard = verdict.replyTo?.fromBot === true && verdict.replyTo.messageId === candidate.messageId;
|
|
1941
|
+
return candidate.origin === 'turn' || repliesToCard ? candidate : undefined;
|
|
1942
|
+
}
|
|
1763
1943
|
/** Hand one message to the queue, or say why it is not being taken. */
|
|
1764
1944
|
function dispatch(job) {
|
|
1765
|
-
|
|
1945
|
+
const epoch = lifecycleEpoch;
|
|
1946
|
+
const accepted = enqueue(job.userId, async () => {
|
|
1947
|
+
// A stop or restart while this waited its turn: it belongs to a
|
|
1948
|
+
// connection that is gone, and must not start a provider run now.
|
|
1949
|
+
if (epoch !== lifecycleEpoch) {
|
|
1950
|
+
log.info('Telegram message dropped, the gateway restarted while it was queued', { from: job.userId });
|
|
1951
|
+
say(job.chatId, 'The gateway restarted before I got to this message. Please send it again.');
|
|
1952
|
+
return;
|
|
1953
|
+
}
|
|
1954
|
+
await runTurn(job);
|
|
1955
|
+
});
|
|
1956
|
+
if (!accepted) {
|
|
1766
1957
|
say(job.chatId, 'The queue is full. Please wait until I have answered the previous messages.');
|
|
1767
1958
|
}
|
|
1768
1959
|
}
|
|
@@ -1804,57 +1995,63 @@ export function createTelegramGateway(context) {
|
|
|
1804
1995
|
signal,
|
|
1805
1996
|
});
|
|
1806
1997
|
backoff = BACKOFF_START_MS;
|
|
1807
|
-
|
|
1808
|
-
if (signal.aborted)
|
|
1809
|
-
break;
|
|
1810
|
-
try {
|
|
1811
|
-
handleUpdate(update);
|
|
1812
|
-
}
|
|
1813
|
-
catch (error) {
|
|
1814
|
-
// One unclassifiable update must not become a wall: retrying it
|
|
1815
|
-
// forever would only reproduce the same throw, and leaving the
|
|
1816
|
-
// offset where it is would hand it to us again on every poll.
|
|
1817
|
-
log.error('Telegram update could not be handled', { error: errorText(error) });
|
|
1818
|
-
}
|
|
1819
|
-
// Only now, so a crash mid-poll costs at most this one update
|
|
1820
|
-
// rather than the whole backlog behind it.
|
|
1821
|
-
offset = update.update_id + 1;
|
|
1822
|
-
}
|
|
1998
|
+
handleUpdates(updates, signal);
|
|
1823
1999
|
}
|
|
1824
2000
|
catch (error) {
|
|
1825
2001
|
if (signal.aborted)
|
|
1826
2002
|
break;
|
|
1827
|
-
//
|
|
1828
|
-
// forever. Stopping with a visible reason beats a silent tug of
|
|
1829
|
-
|
|
1830
|
-
|
|
1831
|
-
|
|
1832
|
-
|
|
2003
|
+
// Retrying a hopeless failure on a timer is a log full of the same
|
|
2004
|
+
// line forever. Stopping with a visible reason beats a silent tug of
|
|
2005
|
+
// war with a second process, or a token Telegram will reject again
|
|
2006
|
+
// in sixty seconds and in sixty after that.
|
|
2007
|
+
const hopeless = hopelessReason(error);
|
|
2008
|
+
if (hopeless) {
|
|
2009
|
+
blockGateway(hopeless, activeToken);
|
|
1833
2010
|
break;
|
|
1834
2011
|
}
|
|
1835
|
-
|
|
1836
|
-
// and in sixty after that. Say so once and wait for a new one.
|
|
1837
|
-
if (error instanceof TelegramApiError && error.unauthorized) {
|
|
1838
|
-
lastError = 'Telegram rejected this bot token (401). Gateway stopped.';
|
|
1839
|
-
blocked = { reason: lastError, token: activeToken };
|
|
1840
|
-
log.error('Telegram rejected the bot token, gateway stopped');
|
|
1841
|
-
break;
|
|
1842
|
-
}
|
|
1843
|
-
lastError = error instanceof TelegramApiError ? error.message : errorText(error);
|
|
2012
|
+
lastError = errorText(error);
|
|
1844
2013
|
log.warn('Telegram polling failed, backing off', { waitMs: backoff, error: lastError });
|
|
1845
2014
|
await delay(backoff, signal);
|
|
1846
2015
|
backoff = Math.min(backoff * 2, BACKOFF_MAX_MS);
|
|
1847
2016
|
}
|
|
1848
2017
|
}
|
|
1849
|
-
|
|
2018
|
+
// A loop that a stop() already replaced must not take the news to a
|
|
2019
|
+
// gateway that has been started again since.
|
|
2020
|
+
if (controller?.signal === signal)
|
|
2021
|
+
running = false;
|
|
2022
|
+
}
|
|
2023
|
+
function handleUpdates(updates, signal) {
|
|
2024
|
+
for (const update of updates) {
|
|
2025
|
+
if (signal.aborted)
|
|
2026
|
+
break;
|
|
2027
|
+
try {
|
|
2028
|
+
handleUpdate(update);
|
|
2029
|
+
}
|
|
2030
|
+
catch (error) {
|
|
2031
|
+
// One unclassifiable update must not become a wall: retrying it
|
|
2032
|
+
// forever would only reproduce the same throw, and leaving the
|
|
2033
|
+
// offset where it is would hand it to us again on every poll.
|
|
2034
|
+
log.error('Telegram update could not be handled', { error: errorText(error) });
|
|
2035
|
+
}
|
|
2036
|
+
// Only now, so a crash mid-poll costs at most this one update
|
|
2037
|
+
// rather than the whole backlog behind it.
|
|
2038
|
+
offset = update.update_id + 1;
|
|
2039
|
+
}
|
|
1850
2040
|
}
|
|
1851
2041
|
/* ---------------------------- lifecycle ---------------------------- */
|
|
1852
2042
|
/** Pending retry after a start that failed for a reason that may pass. */
|
|
1853
2043
|
let retryTimer;
|
|
1854
2044
|
let retryDelay = RETRY_START_MS;
|
|
2045
|
+
/**
|
|
2046
|
+
* Counts the stops. A start that was still connecting when one happened
|
|
2047
|
+
* must not turn into a running gateway afterwards, and a message queued
|
|
2048
|
+
* before one must not become a turn after it.
|
|
2049
|
+
*/
|
|
2050
|
+
let lifecycleEpoch = 0;
|
|
2051
|
+
/** Starts run one after another, so two callers can never leave two pollers on one bot. */
|
|
2052
|
+
let startQueue = Promise.resolve();
|
|
1855
2053
|
function clearRetry() {
|
|
1856
|
-
|
|
1857
|
-
clearTimeout(retryTimer);
|
|
2054
|
+
clearTimeout(retryTimer);
|
|
1858
2055
|
retryTimer = undefined;
|
|
1859
2056
|
retryDelay = RETRY_START_MS;
|
|
1860
2057
|
}
|
|
@@ -1881,10 +2078,24 @@ export function createTelegramGateway(context) {
|
|
|
1881
2078
|
}, wait);
|
|
1882
2079
|
retryTimer.unref?.();
|
|
1883
2080
|
}
|
|
1884
|
-
|
|
2081
|
+
/**
|
|
2082
|
+
* Why the channel gave up for good. The token it failed with is part of the
|
|
2083
|
+
* record, see `blocked`.
|
|
2084
|
+
*/
|
|
2085
|
+
function blockGateway(reason, failedToken) {
|
|
2086
|
+
lastError = reason;
|
|
2087
|
+
blocked = { reason, token: failedToken };
|
|
2088
|
+
log.error('Telegram gateway blocked', { reason });
|
|
2089
|
+
}
|
|
2090
|
+
function start() {
|
|
2091
|
+
const attempt = startQueue.then(launch);
|
|
2092
|
+
// The queue only orders attempts; this call's own caller still gets its failure.
|
|
2093
|
+
startQueue = attempt.catch(() => undefined);
|
|
2094
|
+
return attempt;
|
|
2095
|
+
}
|
|
2096
|
+
async function launch() {
|
|
1885
2097
|
if (running)
|
|
1886
2098
|
return;
|
|
1887
|
-
const config = settings();
|
|
1888
2099
|
const secret = token();
|
|
1889
2100
|
// Whoever calls start directly gets the same answer refresh would give:
|
|
1890
2101
|
// a block only lifts when the token it named has changed.
|
|
@@ -1894,47 +2105,62 @@ export function createTelegramGateway(context) {
|
|
|
1894
2105
|
}
|
|
1895
2106
|
// Say which condition was missing, never what the token was. The
|
|
1896
2107
|
// decision itself lives in core/gateway/policy.ts, tested there.
|
|
1897
|
-
const missing = missingGatewaySettings(
|
|
2108
|
+
const missing = missingGatewaySettings(settings(), secret, silenced);
|
|
1898
2109
|
if (missing.length > 0) {
|
|
1899
2110
|
log.info('Telegram gateway not started', { missing });
|
|
1900
2111
|
return;
|
|
1901
2112
|
}
|
|
2113
|
+
const epoch = lifecycleEpoch;
|
|
1902
2114
|
const client = createTelegramApi(secret);
|
|
1903
2115
|
try {
|
|
1904
|
-
|
|
1905
|
-
// commands, so the offset is parked behind the last known update.
|
|
1906
|
-
await client.deleteWebhook(true);
|
|
1907
|
-
const me = await client.getMe();
|
|
1908
|
-
botUsername = me.username;
|
|
1909
|
-
const newest = (await client.getUpdates({ offset: -1, limit: 1, timeout: 0 })).at(-1);
|
|
1910
|
-
offset = newest ? newest.update_id + 1 : 0;
|
|
2116
|
+
await connect(client);
|
|
1911
2117
|
}
|
|
1912
2118
|
catch (error) {
|
|
1913
|
-
|
|
1914
|
-
|
|
1915
|
-
if (error instanceof TelegramApiError && (error.unauthorized || error.conflict)) {
|
|
1916
|
-
lastError = error.unauthorized
|
|
1917
|
-
? 'Telegram rejected this bot token (401). Gateway stopped.'
|
|
1918
|
-
: 'Another process is polling the same bot (409). Gateway stopped.';
|
|
1919
|
-
blocked = { reason: lastError, token: secret };
|
|
1920
|
-
clearRetry();
|
|
1921
|
-
log.error('Telegram gateway cannot run with these settings', { reason: lastError });
|
|
1922
|
-
return;
|
|
1923
|
-
}
|
|
1924
|
-
// Everything else is weather: a DNS hiccup, a laptop whose network
|
|
1925
|
-
// came up a second after the server did, Telegram having a moment.
|
|
1926
|
-
// The first version gave up here and stayed down until somebody
|
|
1927
|
-
// noticed and restarted - which is how a channel that exists to be
|
|
1928
|
-
// reachable ends up silently unreachable for a day. So it tries
|
|
1929
|
-
// again, further apart each time, for as long as the config still
|
|
1930
|
-
// wants it running.
|
|
1931
|
-
lastError = error instanceof TelegramApiError ? error.message : errorText(error);
|
|
1932
|
-
log.error('Telegram gateway failed to start', { error: lastError, retryInMs: retryDelay });
|
|
1933
|
-
scheduleRetry();
|
|
2119
|
+
if (epoch === lifecycleEpoch)
|
|
2120
|
+
failStart(error, secret);
|
|
1934
2121
|
return;
|
|
1935
2122
|
}
|
|
1936
|
-
|
|
1937
|
-
|
|
2123
|
+
if (epoch !== lifecycleEpoch) {
|
|
2124
|
+
log.info('Telegram gateway start abandoned, it was stopped while connecting');
|
|
2125
|
+
return;
|
|
2126
|
+
}
|
|
2127
|
+
sweepInbox();
|
|
2128
|
+
publishBotProfile(client);
|
|
2129
|
+
begin(client, secret);
|
|
2130
|
+
}
|
|
2131
|
+
/**
|
|
2132
|
+
* Webhook and backlog go first. A restart must not replay yesterday's
|
|
2133
|
+
* commands, so the offset is parked behind the last known update.
|
|
2134
|
+
*/
|
|
2135
|
+
async function connect(client) {
|
|
2136
|
+
await client.deleteWebhook(true);
|
|
2137
|
+
const me = await client.getMe();
|
|
2138
|
+
botUsername = me.username;
|
|
2139
|
+
const newest = (await client.getUpdates({ offset: -1, limit: 1, timeout: 0 })).at(-1);
|
|
2140
|
+
offset = newest ? newest.update_id + 1 : 0;
|
|
2141
|
+
}
|
|
2142
|
+
function failStart(error, secret) {
|
|
2143
|
+
// The same two hopeless cases, caught on the way up rather than in the
|
|
2144
|
+
// loop: getMe is where a bad token usually announces itself.
|
|
2145
|
+
const hopeless = hopelessReason(error);
|
|
2146
|
+
if (hopeless) {
|
|
2147
|
+
blockGateway(hopeless, secret);
|
|
2148
|
+
clearRetry();
|
|
2149
|
+
return;
|
|
2150
|
+
}
|
|
2151
|
+
// Everything else is weather: a DNS hiccup, a laptop whose network
|
|
2152
|
+
// came up a second after the server did, Telegram having a moment.
|
|
2153
|
+
// The first version gave up here and stayed down until somebody
|
|
2154
|
+
// noticed and restarted - which is how a channel that exists to be
|
|
2155
|
+
// reachable ends up silently unreachable for a day. So it tries
|
|
2156
|
+
// again, further apart each time, for as long as the config still
|
|
2157
|
+
// wants it running.
|
|
2158
|
+
lastError = errorText(error);
|
|
2159
|
+
log.error('Telegram gateway failed to start', { error: lastError, retryInMs: retryDelay });
|
|
2160
|
+
scheduleRetry();
|
|
2161
|
+
}
|
|
2162
|
+
/** Yesterday's photos are not worth keeping for ever. Best-effort, and never a reason not to start. */
|
|
2163
|
+
function sweepInbox() {
|
|
1938
2164
|
try {
|
|
1939
2165
|
const removed = pruneInbox(context.config.workspace);
|
|
1940
2166
|
if (removed > 0)
|
|
@@ -1943,8 +2169,10 @@ export function createTelegramGateway(context) {
|
|
|
1943
2169
|
catch (error) {
|
|
1944
2170
|
log.warn('Telegram inbox could not be swept', { error: errorText(error) });
|
|
1945
2171
|
}
|
|
1946
|
-
|
|
1947
|
-
|
|
2172
|
+
}
|
|
2173
|
+
/** Best-effort: a bot whose menu or description is a day out of date still answers every one of its commands. */
|
|
2174
|
+
function publishBotProfile(client) {
|
|
2175
|
+
// What draws the blue menu button in the app.
|
|
1948
2176
|
void client.setMyCommands(COMMANDS).catch((error) => {
|
|
1949
2177
|
log.warn('Telegram command menu could not be published', { error: errorText(error) });
|
|
1950
2178
|
});
|
|
@@ -1957,6 +2185,9 @@ export function createTelegramGateway(context) {
|
|
|
1957
2185
|
.catch((error) => {
|
|
1958
2186
|
log.debug('Telegram description could not be set', { error: errorText(error) });
|
|
1959
2187
|
});
|
|
2188
|
+
}
|
|
2189
|
+
function begin(client, secret) {
|
|
2190
|
+
const config = settings();
|
|
1960
2191
|
api = client;
|
|
1961
2192
|
activeToken = secret;
|
|
1962
2193
|
lastError = undefined;
|
|
@@ -1971,10 +2202,11 @@ export function createTelegramGateway(context) {
|
|
|
1971
2202
|
loop = poll(client, controller.signal);
|
|
1972
2203
|
}
|
|
1973
2204
|
async function stop() {
|
|
2205
|
+
lifecycleEpoch += 1;
|
|
1974
2206
|
clearRetry();
|
|
1975
2207
|
controller?.abort();
|
|
1976
|
-
for (const
|
|
1977
|
-
|
|
2208
|
+
for (const cancel of turns.values())
|
|
2209
|
+
cancel.abort();
|
|
1978
2210
|
turns.clear();
|
|
1979
2211
|
// A half-collected album belongs to a connection that is going away.
|
|
1980
2212
|
for (const album of albums.values())
|
|
@@ -1988,8 +2220,11 @@ export function createTelegramGateway(context) {
|
|
|
1988
2220
|
// the phone through `send`: push holds this handle and only stops asking
|
|
1989
2221
|
// when there is nothing left to send with.
|
|
1990
2222
|
api = undefined;
|
|
1991
|
-
if (pending)
|
|
1992
|
-
await pending.catch(() => {
|
|
2223
|
+
if (pending) {
|
|
2224
|
+
await pending.catch((error) => {
|
|
2225
|
+
log.warn('Telegram polling loop ended with an error', { error: errorText(error) });
|
|
2226
|
+
});
|
|
2227
|
+
}
|
|
1993
2228
|
log.info('Telegram gateway stopped');
|
|
1994
2229
|
}
|
|
1995
2230
|
async function refresh() {
|
|
@@ -2018,6 +2253,7 @@ export function createTelegramGateway(context) {
|
|
|
2018
2253
|
return;
|
|
2019
2254
|
}
|
|
2020
2255
|
}
|
|
2256
|
+
context.assistant.on('follow-up', relayFollowUp);
|
|
2021
2257
|
return {
|
|
2022
2258
|
id: 'telegram',
|
|
2023
2259
|
start,
|
|
@@ -2050,11 +2286,7 @@ export function createTelegramGateway(context) {
|
|
|
2050
2286
|
* push hands them straight to the origin registry.
|
|
2051
2287
|
*/
|
|
2052
2288
|
async send(userId, text, options = {}) {
|
|
2053
|
-
|
|
2054
|
-
await chain(userId, async () => {
|
|
2055
|
-
ids = await deliver(userId, text, options);
|
|
2056
|
-
});
|
|
2057
|
-
return ids;
|
|
2289
|
+
return chain(userId, () => deliver(userId, text, options));
|
|
2058
2290
|
},
|
|
2059
2291
|
/**
|
|
2060
2292
|
* A question, put where somebody can answer it. The chat id of a private
|