@myrialabs/clopen 0.4.47 → 0.4.49
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 +11 -11
- package/backend/artifacts/project/sources.ts +1 -1
- package/backend/auth/auth-service.ts +52 -358
- package/backend/auth/onboarding.test.ts +2 -3
- package/backend/auth/permissions.test.ts +10 -20
- package/backend/auth/permissions.ts +4 -290
- package/backend/auth/rate-limiter.test.ts +8 -9
- package/backend/auth/rate-limiter.ts +0 -2
- package/backend/auth/tokens.ts +1 -8
- package/backend/bootstrap.ts +7 -0
- package/backend/chat/attachments.test.ts +88 -0
- package/backend/chat/attachments.ts +159 -0
- package/backend/chat/engine-handoff.test.ts +0 -2
- package/backend/chat/message-pages.test.ts +163 -0
- package/backend/chat/message-pages.ts +233 -0
- package/backend/chat/stream-manager.ts +91 -67
- package/backend/chat/turn-answer.test.ts +64 -0
- package/backend/chat/turn-answer.ts +125 -0
- package/backend/chat-apps/awaiting.test.ts +39 -0
- package/backend/chat-apps/awaiting.ts +49 -0
- package/backend/chat-apps/conversation.ts +746 -0
- package/backend/chat-apps/inbound.ts +324 -0
- package/backend/chat-apps/index.ts +309 -0
- package/backend/chat-apps/link-events.ts +20 -0
- package/backend/chat-apps/media.test.ts +62 -0
- package/backend/chat-apps/media.ts +208 -0
- package/backend/chat-apps/messages.test.ts +229 -0
- package/backend/chat-apps/messages.ts +365 -0
- package/backend/chat-apps/outbound.ts +243 -0
- package/backend/chat-apps/pairing.test.ts +45 -0
- package/backend/chat-apps/pairing.ts +74 -0
- package/backend/chat-apps/platforms/index.ts +20 -0
- package/backend/chat-apps/platforms/telegram.test.ts +35 -0
- package/backend/chat-apps/platforms/telegram.ts +191 -0
- package/backend/chat-apps/platforms/types.ts +114 -0
- package/backend/chat-apps/questions.ts +133 -0
- package/backend/chat-apps/runtime.ts +572 -0
- package/backend/chat-apps/storage.test.ts +201 -0
- package/backend/chat-apps/turns.test.ts +45 -0
- package/backend/chat-apps/turns.ts +208 -0
- package/backend/containers/pty.ts +3 -11
- package/backend/control/actions/accounts.ts +89 -0
- package/backend/control/actions/files.ts +116 -0
- package/backend/control/actions/models.ts +188 -0
- package/backend/control/actions/projects.ts +272 -0
- package/backend/control/actions/sessions.ts +280 -0
- package/backend/control/actions/skills.ts +111 -0
- package/backend/control/control.test.ts +169 -0
- package/backend/control/define.ts +20 -0
- package/backend/control/folders.test.ts +67 -0
- package/backend/control/index.ts +213 -0
- package/backend/control/invoke.ts +44 -0
- package/backend/control/links.ts +35 -0
- package/backend/control/paging.ts +26 -0
- package/backend/control/types.ts +117 -0
- package/backend/control/workspace.ts +127 -0
- package/backend/database/migrations/084_create_channel_links.ts +71 -0
- package/backend/database/migrations/085_add_home_projects.ts +36 -0
- package/backend/database/migrations/086_single_owner.ts +418 -0
- package/backend/database/migrations/087_create_blob_line_stats.ts +37 -0
- package/backend/database/migrations/index.ts +28 -0
- package/backend/database/queries/auth-queries.ts +7 -85
- package/backend/database/queries/blob-line-stats-queries.ts +48 -0
- package/backend/database/queries/channel-queries.ts +270 -0
- package/backend/database/queries/db-client-connection-queries.ts +18 -56
- package/backend/database/queries/file-share-queries.ts +5 -23
- package/backend/database/queries/git-identity-queries.ts +31 -42
- package/backend/database/queries/graph-queries.ts +1 -1
- package/backend/database/queries/index.ts +15 -1
- package/backend/database/queries/message-queries.test.ts +146 -0
- package/backend/database/queries/message-queries.ts +42 -1
- package/backend/database/queries/permission-set-queries.ts +1 -1
- package/backend/database/queries/profile-queries.ts +1 -1
- package/backend/database/queries/project-mcp-trust-queries.ts +1 -1
- package/backend/database/queries/project-queries.ts +50 -63
- package/backend/database/queries/session-queries.ts +28 -56
- package/backend/database/queries/ssh-connection-queries.ts +18 -41
- package/backend/db-client/env/diff.ts +9 -33
- package/backend/db-client/env/env.test.ts +8 -8
- package/backend/db-client/env/service.ts +1 -1
- package/backend/db-client/integrations/projector.ts +0 -5
- package/backend/engine/adapters/claude/message-converter.test.ts +47 -0
- package/backend/engine/adapters/claude/message-converter.ts +25 -2
- package/backend/engine/adapters/cline/message-converter.ts +0 -1
- package/backend/engine/adapters/cline/stream.ts +11 -15
- package/backend/engine/adapters/codex/message-converter.ts +0 -2
- package/backend/engine/adapters/copilot/message-converter.ts +1 -2
- package/backend/engine/adapters/cursor/message-converter.ts +0 -1
- package/backend/engine/adapters/opencode/message-converter.ts +2 -4
- package/backend/engine/adapters/opencode/stream.ts +11 -0
- package/backend/engine/adapters/parent-scope.test.ts +38 -0
- package/backend/engine/adapters/parent-scope.ts +44 -0
- package/backend/engine/adapters/pi/message-converter.ts +0 -1
- package/backend/engine/adapters/pi/stream.ts +4 -5
- package/backend/engine/adapters/qwen/message-converter.ts +0 -2
- package/backend/engine/bootstrap-default-engine.ts +2 -2
- package/backend/engine/docs/adapter-contract.md +8 -1
- package/backend/engine/install-runner.ts +8 -17
- package/backend/files/file-shares.ts +20 -44
- package/backend/files/file-size-limit.ts +3 -3
- package/backend/files/file-watcher.ts +19 -0
- package/backend/files/image-processing.ts +1 -1
- package/backend/files/os-clipboard.ts +2 -2
- package/backend/git/contributors.test.ts +35 -0
- package/backend/git/contributors.ts +46 -0
- package/backend/git/git-executor.ts +25 -5
- package/backend/git/git-service.ts +420 -19
- package/backend/git/identity/credential-helper.test.ts +2 -7
- package/backend/git/identity/import-local.test.ts +11 -16
- package/backend/git/identity/import-local.ts +12 -12
- package/backend/git/identity/index.ts +10 -24
- package/backend/git/identity/resolve.ts +13 -14
- package/backend/git/identity/scope-config.ts +33 -28
- package/backend/git/identity/service.ts +44 -47
- package/backend/git/op-lock.test.ts +111 -0
- package/backend/git/op-lock.ts +180 -0
- package/backend/git/remote-sync.test.ts +249 -0
- package/backend/host/metrics.ts +1 -1
- package/backend/http/bearer-auth.ts +1 -2
- package/backend/http/files-download.test.ts +8 -9
- package/backend/http/files-download.ts +2 -2
- package/backend/http/files-shared.test.ts +62 -89
- package/backend/http/files-shared.ts +2 -2
- package/backend/http/files-upload.test.ts +3 -7
- package/backend/http/files-upload.ts +3 -3
- package/backend/http/notes-images.test.ts +15 -38
- package/backend/http/notes-images.ts +6 -8
- package/backend/http/ssh-sftp.ts +5 -10
- package/backend/http/static-assets.test.ts +78 -0
- package/backend/http/static-assets.ts +104 -0
- package/backend/index.ts +32 -16
- package/backend/integrations/accounts.ts +61 -3
- package/backend/integrations/index.ts +2 -2
- package/backend/integrations/registry/define.ts +15 -0
- package/backend/integrations/registry/index.ts +2 -0
- package/backend/integrations/registry/providers/telegram.ts +54 -0
- package/backend/integrations/registry/types.ts +21 -1
- package/backend/integrations/webhooks/gateway.ts +7 -6
- package/backend/integrations/webhooks/verify.test.ts +30 -0
- package/backend/integrations/webhooks/verify.ts +4 -0
- package/backend/mcp/external/project.ts +1 -1
- package/backend/mcp/internal/remote-server.test.ts +1 -3
- package/backend/mcp/internal/remote-server.ts +4 -4
- package/backend/mcp/internal/servers/browser-automation/actions/dialogs.ts +67 -0
- package/backend/mcp/internal/servers/browser-automation/actions/index.ts +3 -1
- package/backend/mcp/internal/servers/browser-automation/actions/input.ts +5 -5
- package/backend/mcp/internal/servers/browser-automation/actions/tabs.ts +157 -28
- package/backend/mcp/internal/servers/browser-automation/context.ts +1 -0
- package/backend/mcp/internal/servers/browser-automation/description.ts +5 -2
- package/backend/mcp/internal/servers/browser-automation/format.ts +24 -1
- package/backend/mcp/internal/servers/browser-automation/runner.ts +68 -3
- package/backend/memory/redact.ts +1 -1
- package/backend/notes/access.test.ts +28 -29
- package/backend/notes/access.ts +6 -11
- package/backend/permissions/service.ts +1 -1
- package/backend/preview/browser/browser-clipboard.test.ts +46 -0
- package/backend/preview/browser/browser-clipboard.ts +67 -0
- package/backend/preview/browser/browser-dialog-handler.ts +95 -6
- package/backend/preview/browser/browser-host-bridge.ts +9 -0
- package/backend/preview/browser/browser-interaction-handler.ts +316 -86
- package/backend/preview/browser/browser-mcp-control.ts +34 -0
- package/backend/preview/browser/browser-pool.ts +67 -6
- package/backend/preview/browser/browser-preview-service.ts +383 -29
- package/backend/preview/browser/browser-tab-manager.ts +66 -23
- package/backend/preview/browser/browser-video-capture.ts +92 -5
- package/backend/preview/browser/element-locator.ts +190 -17
- package/backend/preview/browser/keyboard-chords.test.ts +68 -0
- package/backend/preview/browser/keyboard-chords.ts +132 -0
- package/backend/preview/browser/paste.ts +81 -0
- package/backend/preview/browser/process-usage.ts +142 -0
- package/backend/preview/browser/profile-lock.ts +209 -0
- package/backend/preview/browser/scripts/host-bridge.ts +59 -0
- package/backend/preview/browser/scripts/video-stream.ts +58 -0
- package/backend/preview/browser/types.ts +40 -2
- package/backend/preview/browser/viewport.test.ts +45 -0
- package/backend/preview/browser/viewport.ts +96 -0
- package/backend/profiles/service.ts +2 -2
- package/backend/project/status-manager.ts +43 -172
- package/backend/projects/home.ts +61 -0
- package/backend/projects/project-cleanup.integration.test.ts +2 -2
- package/backend/projects/project-cleanup.ts +0 -8
- package/backend/skills/service.ts +2 -3
- package/backend/snapshot/blob-store.ts +9 -1
- package/backend/snapshot/helpers.ts +3 -11
- package/backend/snapshot/line-stats.test.ts +80 -0
- package/backend/snapshot/line-stats.ts +64 -0
- package/backend/snapshot/restore.ts +252 -0
- package/backend/snapshot/snapshot-service.ts +14 -27
- package/backend/snapshot/turn-changes.test.ts +10 -5
- package/backend/snapshot/turn-changes.ts +78 -40
- package/backend/ssh/ptykit.ts +1 -2
- package/backend/terminal/ptykit.ts +10 -8
- package/backend/tunnel/public-origin.ts +31 -20
- package/backend/utils/user-helpers.ts +0 -55
- package/backend/utils/ws-wire.test.ts +87 -0
- package/backend/utils/ws-wire.ts +189 -0
- package/backend/utils/ws.ts +101 -192
- package/backend/worktrees/branching/engine.ts +3 -16
- package/backend/worktrees/branching/index.ts +1 -1
- package/backend/worktrees/branching/projector.ts +1 -1
- package/backend/worktrees/branching/service.ts +13 -25
- package/backend/ws/access.ts +12 -21
- package/backend/ws/artifacts/generate.ts +2 -2
- package/backend/ws/auth/device.ts +16 -71
- package/backend/ws/auth/index.ts +4 -22
- package/backend/ws/auth/login.test.ts +14 -60
- package/backend/ws/auth/login.ts +24 -124
- package/backend/ws/auth/status.ts +0 -1
- package/backend/ws/chat/composer.ts +118 -118
- package/backend/ws/chat/stream.ts +105 -57
- package/backend/ws/chat-apps/index.ts +117 -0
- package/backend/ws/containers/actions.ts +11 -25
- package/backend/ws/containers/index.ts +3 -4
- package/backend/ws/containers/list.ts +10 -36
- package/backend/ws/containers/logs.ts +2 -2
- package/backend/ws/containers/tunnel.ts +1 -2
- package/backend/ws/db-client/access.ts +2 -16
- package/backend/ws/db-client/accounts.ts +5 -15
- package/backend/ws/db-client/connections.ts +17 -25
- package/backend/ws/db-client/context.ts +1 -1
- package/backend/ws/db-client/env.ts +7 -10
- package/backend/ws/db-client/index.ts +2 -2
- package/backend/ws/db-client/io.ts +5 -5
- package/backend/ws/db-client/query-history-retention.test.ts +8 -8
- package/backend/ws/db-client/query.ts +18 -17
- package/backend/ws/db-client/schema.ts +13 -13
- package/backend/ws/db-client/structure.ts +35 -35
- package/backend/ws/db-client/supabase.ts +4 -21
- package/backend/ws/deployments/context.ts +1 -1
- package/backend/ws/deployments/crud.ts +0 -5
- package/backend/ws/engine/access.ts +7 -20
- package/backend/ws/engine/claude/accounts.ts +4 -4
- package/backend/ws/engine/cline/accounts.ts +5 -5
- package/backend/ws/engine/codex/accounts.ts +3 -3
- package/backend/ws/engine/pi/accounts.ts +5 -5
- package/backend/ws/files/clipboard.ts +8 -27
- package/backend/ws/files/image-edit.ts +6 -6
- package/backend/ws/files/index.ts +1 -1
- package/backend/ws/files/path-access.test.ts +32 -131
- package/backend/ws/files/path-access.ts +8 -87
- package/backend/ws/files/read.ts +45 -19
- package/backend/ws/files/reveal.ts +3 -3
- package/backend/ws/files/search.ts +7 -7
- package/backend/ws/files/share.ts +9 -13
- package/backend/ws/files/state.ts +9 -12
- package/backend/ws/files/watch.ts +3 -3
- package/backend/ws/files/write.ts +30 -31
- package/backend/ws/git/branch.ts +80 -59
- package/backend/ws/git/commit.ts +63 -44
- package/backend/ws/git/conflict.ts +16 -18
- package/backend/ws/git/identity-context.ts +8 -17
- package/backend/ws/git/identity.ts +17 -27
- package/backend/ws/git/index.ts +3 -1
- package/backend/ws/git/log.ts +52 -0
- package/backend/ws/git/op-state.ts +139 -0
- package/backend/ws/git/remote.ts +241 -141
- package/backend/ws/git/repo-context.ts +67 -0
- package/backend/ws/git/staging.ts +18 -28
- package/backend/ws/git/status.ts +5 -2
- package/backend/ws/index.ts +5 -1
- package/backend/ws/instructions/crud.ts +1 -1
- package/backend/ws/integrations/crud.ts +1 -3
- package/backend/ws/mcp/crud.ts +3 -5
- package/backend/ws/mcp/tools.ts +1 -1
- package/backend/ws/memory/crud.ts +14 -46
- package/backend/ws/memory/index.ts +2 -2
- package/backend/ws/messages/crud.ts +78 -8
- package/backend/ws/notes/index.ts +33 -39
- package/backend/ws/permissions/crud.ts +3 -4
- package/backend/ws/ports/index.ts +1 -2
- package/backend/ws/ports/kill.ts +5 -10
- package/backend/ws/ports/list.ts +4 -10
- package/backend/ws/preview/access.ts +1 -1
- package/backend/ws/preview/browser/interact.ts +52 -79
- package/backend/ws/preview/browser/native-ui.ts +24 -0
- package/backend/ws/preview/browser/stats.ts +98 -1
- package/backend/ws/preview/browser/tab-info.ts +15 -0
- package/backend/ws/preview/browser/tab.ts +19 -4
- package/backend/ws/preview/index.ts +29 -0
- package/backend/ws/preview/watchers.ts +84 -0
- package/backend/ws/profiles/crud.ts +6 -8
- package/backend/ws/project-artifacts/index.ts +30 -31
- package/backend/ws/projects/crud.ts +33 -35
- package/backend/ws/projects/index.ts +3 -8
- package/backend/ws/projects/info.ts +3 -3
- package/backend/ws/projects/overview.ts +19 -30
- package/backend/ws/projects/status.ts +17 -57
- package/backend/ws/sessions/crud.ts +42 -57
- package/backend/ws/sessions/index.ts +1 -1
- package/backend/ws/settings/crud.ts +1 -1
- package/backend/ws/skills/crud.ts +3 -4
- package/backend/ws/skills/index.ts +1 -1
- package/backend/ws/snapshot/changes.ts +12 -13
- package/backend/ws/snapshot/restore.ts +11 -295
- package/backend/ws/snapshot/timeline.ts +2 -4
- package/backend/ws/ssh/access.ts +6 -21
- package/backend/ws/ssh/connections.ts +21 -31
- package/backend/ws/ssh/forwards.ts +12 -12
- package/backend/ws/ssh/sftp.ts +34 -34
- package/backend/ws/ssh/tunnel.ts +1 -2
- package/backend/ws/stack/install.ts +7 -17
- package/backend/ws/subagents/crud.ts +1 -1
- package/backend/ws/terminal/tunnel.ts +2 -2
- package/backend/ws/tunnel/share.ts +0 -2
- package/backend/ws/user/crud.ts +1 -59
- package/backend/ws/user/index.ts +1 -1
- package/backend/ws/work/context.ts +1 -1
- package/backend/ws/work/crud.ts +0 -5
- package/backend/ws/workspace/state.ts +10 -13
- package/backend/ws/worktrees/branching.ts +7 -36
- package/backend/ws/worktrees/crud.ts +2 -2
- package/bin/clopen.ts +46 -41
- package/dist/assets/addon-clipboard-wHJhZAA4.js.br +0 -0
- package/dist/assets/addon-clipboard-wHJhZAA4.js.gz +0 -0
- package/dist/assets/addon-fit-DX4qG4td.js.br +1 -0
- package/dist/assets/addon-fit-DX4qG4td.js.gz +0 -0
- package/dist/assets/addon-ligatures-DpDY8N_X.js.br +0 -0
- package/dist/assets/addon-ligatures-DpDY8N_X.js.gz +0 -0
- package/dist/assets/addon-unicode11-Bt8F3D7-.js.br +0 -0
- package/dist/assets/addon-unicode11-Bt8F3D7-.js.gz +0 -0
- package/dist/assets/addon-web-links-DIbG5aQx.js.br +0 -0
- package/dist/assets/addon-web-links-DIbG5aQx.js.gz +0 -0
- package/dist/assets/diff.worker-BoHLxmr2.js +7 -0
- package/dist/assets/diff.worker-BoHLxmr2.js.br +0 -0
- package/dist/assets/diff.worker-BoHLxmr2.js.gz +0 -0
- package/dist/assets/graph-layout.worker-CRFqN7ZQ.js.br +0 -0
- package/dist/assets/graph-layout.worker-CRFqN7ZQ.js.gz +0 -0
- package/dist/assets/{index-CwuKQelV.js → index-CrVWZH_D.js} +1 -1
- package/dist/assets/index-CrVWZH_D.js.br +0 -0
- package/dist/assets/index-CrVWZH_D.js.gz +0 -0
- package/dist/assets/{index-BTcR1byF.js → index-DD0-3EWg.js} +1 -1
- package/dist/assets/index-DD0-3EWg.js.br +0 -0
- package/dist/assets/index-DD0-3EWg.js.gz +0 -0
- package/dist/assets/main-D2_TmcwQ.js +1240 -0
- package/dist/assets/main-D2_TmcwQ.js.br +0 -0
- package/dist/assets/main-D2_TmcwQ.js.gz +0 -0
- package/dist/assets/main-Yucigcmf.css +1 -0
- package/dist/assets/main-Yucigcmf.css.br +0 -0
- package/dist/assets/main-Yucigcmf.css.gz +0 -0
- package/dist/assets/preview-video.worker-DcpDhCWL.js.br +0 -0
- package/dist/assets/preview-video.worker-DcpDhCWL.js.gz +0 -0
- package/dist/assets/xterm-B-qIQCd3.js.br +0 -0
- package/dist/assets/xterm-B-qIQCd3.js.gz +0 -0
- package/dist/assets/zipkit-engine-CaR0t_Uy.wasm.br +0 -0
- package/dist/assets/zipkit-engine-CaR0t_Uy.wasm.gz +0 -0
- package/dist/fonts/dm-sans.css.br +0 -0
- package/dist/fonts/dm-sans.css.gz +0 -0
- package/dist/index.html +2 -2
- package/dist/index.html.br +0 -0
- package/dist/index.html.gz +0 -0
- package/dist/sw.js.br +0 -0
- package/dist/sw.js.gz +0 -0
- package/package.json +3 -3
- package/shared/constants/attachments.ts +14 -0
- package/shared/constants/engine-tools.ts +1 -1
- package/shared/constants/preview.test.ts +259 -0
- package/shared/constants/preview.ts +1018 -57
- package/shared/constants/tool-icons.ts +5 -0
- package/shared/types/containers/container.ts +1 -1
- package/shared/types/database/schema.ts +9 -6
- package/shared/types/git-identity.ts +1 -1
- package/shared/types/git.ts +116 -0
- package/shared/types/integrations.ts +7 -0
- package/shared/types/stores/settings.ts +1 -1
- package/shared/types/unified/index.ts +1 -1
- package/shared/types/unified/message.ts +0 -7
- package/shared/types/unified/stream.ts +13 -5
- package/shared/types/unified/tool.ts +15 -1
- package/shared/utils/ask-user-question.test.ts +319 -0
- package/shared/utils/ask-user-question.ts +154 -0
- package/shared/utils/diff-calculator.test.ts +178 -41
- package/shared/utils/diff-calculator.ts +383 -100
- package/shared/utils/home-project.ts +25 -0
- package/shared/utils/logger.ts +2 -0
- package/shared/utils/process-supervisor.test.ts +172 -0
- package/shared/utils/process-supervisor.ts +251 -0
- package/shared/utils/ws-chunk.test.ts +33 -0
- package/shared/utils/ws-chunk.ts +73 -0
- package/shared/utils/ws-client-chunks.test.ts +45 -0
- package/shared/utils/ws-client.ts +43 -0
- package/shared/utils/ws-server.ts +49 -21
- package/backend/auth/session-invalidation.test.ts +0 -112
- package/backend/auth/session-invalidation.ts +0 -77
- package/backend/project/status-manager.test.ts +0 -32
- package/backend/ws/auth/invites.ts +0 -94
- package/backend/ws/auth/users.ts +0 -112
- package/backend/ws/projects/presence.ts +0 -46
- package/backend/ws/stack/access.ts +0 -31
- package/dist/assets/main-BiDNMWb3.css +0 -1
- package/dist/assets/main-BlhKWz2B.js +0 -1241
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pairing codes — how a chat proves it belongs to a Clopen user.
|
|
3
|
+
*
|
|
4
|
+
* The user asks Clopen for a link while signed in; the link opens a chat with
|
|
5
|
+
* the bot carrying a one-time code; the bot receives `/start <code>` from the
|
|
6
|
+
* chat and binds that chat to whoever asked. Holding the code is the proof, so
|
|
7
|
+
* it is single-use and short-lived.
|
|
8
|
+
*
|
|
9
|
+
* In memory on purpose. A code lives for minutes and only means something to
|
|
10
|
+
* the process that issued it; a restart in between costs the user one more
|
|
11
|
+
* tap on "Link", which is cheaper than a table whose every row is garbage ten
|
|
12
|
+
* minutes after it is written.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { randomBytes } from 'crypto';
|
|
16
|
+
|
|
17
|
+
export const PAIRING_TTL_MS = 10 * 60 * 1000;
|
|
18
|
+
|
|
19
|
+
interface PendingPairing {
|
|
20
|
+
userId: string;
|
|
21
|
+
accountId: string;
|
|
22
|
+
expiresAt: number;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const pending = new Map<string, PendingPairing>();
|
|
26
|
+
|
|
27
|
+
function sweep(now: number): void {
|
|
28
|
+
for (const [code, entry] of pending) {
|
|
29
|
+
if (entry.expiresAt <= now) pending.delete(code);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Issue a code. Telegram's `start` parameter allows `A-Za-z0-9_-` up to 64
|
|
35
|
+
* characters; 24 base64url characters is 144 bits.
|
|
36
|
+
*
|
|
37
|
+
* A user asking again replaces their previous code for the same bot, so only
|
|
38
|
+
* the newest link they were shown works.
|
|
39
|
+
*/
|
|
40
|
+
export function issuePairingCode(userId: string, accountId: string): { code: string; expiresAt: string } {
|
|
41
|
+
const now = Date.now();
|
|
42
|
+
sweep(now);
|
|
43
|
+
for (const [code, entry] of pending) {
|
|
44
|
+
if (entry.userId === userId && entry.accountId === accountId) pending.delete(code);
|
|
45
|
+
}
|
|
46
|
+
const code = randomBytes(18).toString('base64url');
|
|
47
|
+
const expiresAt = now + PAIRING_TTL_MS;
|
|
48
|
+
pending.set(code, { userId, accountId, expiresAt });
|
|
49
|
+
return { code, expiresAt: new Date(expiresAt).toISOString() };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Withdraw a user's open code for a bot: the link they were shown stops working. */
|
|
53
|
+
export function revokePairingCode(userId: string, accountId: string): void {
|
|
54
|
+
for (const [code, entry] of pending) {
|
|
55
|
+
if (entry.userId === userId && entry.accountId === accountId) pending.delete(code);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Redeem a code for the bot it was issued for. Consumed whether or not it
|
|
61
|
+
* matches that bot — a code that reached the wrong bot has leaked.
|
|
62
|
+
*/
|
|
63
|
+
export function redeemPairingCode(code: string, accountId: string): { userId: string } | null {
|
|
64
|
+
const entry = pending.get(code);
|
|
65
|
+
if (!entry) return null;
|
|
66
|
+
pending.delete(code);
|
|
67
|
+
if (entry.expiresAt <= Date.now() || entry.accountId !== accountId) return null;
|
|
68
|
+
return { userId: entry.userId };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Tests only. */
|
|
72
|
+
export function resetPairingCodes(): void {
|
|
73
|
+
pending.clear();
|
|
74
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Chat-app platforms, keyed by integration provider id.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import { telegramPlatform } from './telegram';
|
|
6
|
+
import type { ChannelPlatform } from './types';
|
|
7
|
+
|
|
8
|
+
export type { ChannelButton, ChannelCard, ChannelCommand, ChannelFile, ChannelFragment, ChannelHealth, ChannelPlatform, DeliveryMode } from './types';
|
|
9
|
+
|
|
10
|
+
const PLATFORMS: readonly ChannelPlatform[] = [telegramPlatform];
|
|
11
|
+
|
|
12
|
+
const byProvider = new Map(PLATFORMS.map((platform) => [platform.provider, platform]));
|
|
13
|
+
|
|
14
|
+
export function getChannelPlatform(provider: string): ChannelPlatform | null {
|
|
15
|
+
return byProvider.get(provider) ?? null;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function listChannelPlatforms(): readonly ChannelPlatform[] {
|
|
19
|
+
return PLATFORMS;
|
|
20
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A webhook delivery must get past ChatKit's own check, not only the
|
|
3
|
+
* gateway's: an adapter built without the secret rejects every delivery.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { describe, it, expect } from 'bun:test';
|
|
7
|
+
import { telegramPlatform } from './telegram';
|
|
8
|
+
|
|
9
|
+
const request = (secret?: string) => {
|
|
10
|
+
const headers: Record<string, string> = secret ? { 'x-telegram-bot-api-secret-token': secret } : {};
|
|
11
|
+
return { method: 'POST', headers, body: '{}' };
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
describe('the Telegram webhook adapter', () => {
|
|
15
|
+
it('accepts a delivery carrying the bot’s secret, and only that one', () => {
|
|
16
|
+
const adapter = telegramPlatform.createAdapter({ account: 'a', credentials: { botToken: '1:x', webhookSecret: 's3cret' }, mode: 'webhook' });
|
|
17
|
+
expect(adapter.verifyInbound?.(request('s3cret'))).toBe(true);
|
|
18
|
+
expect(adapter.verifyInbound?.(request('other'))).toBe(false);
|
|
19
|
+
expect(adapter.verifyInbound?.(request())).toBe(false);
|
|
20
|
+
});
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
describe('what Telegram calls a command', () => {
|
|
24
|
+
const parse = (text: string) => telegramPlatform.parseCommand(text);
|
|
25
|
+
|
|
26
|
+
it('reads /name and /name@bot with their argument', () => {
|
|
27
|
+
expect(parse('/run review_pr 123')).toEqual({ command: 'run', argument: 'review_pr 123' });
|
|
28
|
+
expect(parse('/Model@clopen_bot claude')).toEqual({ command: 'model', argument: 'claude' });
|
|
29
|
+
expect(parse('/status')).toEqual({ command: 'status', argument: '' });
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
it('leaves a skill’s own /slug, a path and a URL path as plain text, so none can shadow a command', () => {
|
|
33
|
+
for (const text of ['/new-feature add login', '/review-pr 12', '/usr/bin/env', '/api/v1/users', 'not a /command']) expect(parse(text)).toBeNull();
|
|
34
|
+
});
|
|
35
|
+
});
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Telegram, through ChatKit's Bot API adapter.
|
|
3
|
+
*
|
|
4
|
+
* Buttons are inline keyboards; their `callback_data` holds at most 64 bytes,
|
|
5
|
+
* which is why a button carries a prompt id and the meaning lives in
|
|
6
|
+
* `channel_messages`. A message is re-rendered with `editMessageText`
|
|
7
|
+
* carrying a fresh keyboard — an empty one removes the buttons once a question
|
|
8
|
+
* is settled, so a stale tap has nothing to land on.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { TelegramAdapter } from '@myrialabs/chatkit/adapters';
|
|
12
|
+
import { telegramButtons, telegramEditMessage, type TelegramButton } from '@myrialabs/chatkit/interactive';
|
|
13
|
+
import { media, richText, type Adapter, type MediaType, type TextRun, type UniversalMessage } from '@myrialabs/chatkit';
|
|
14
|
+
import type { ChannelButton, ChannelCard, ChannelFile, ChannelPlatform, DeliveryMode } from './types';
|
|
15
|
+
|
|
16
|
+
/** Telegram caps a message at 4096 UTF-16 units. Callers split longer output; this is the last guard. */
|
|
17
|
+
const MAX_TEXT = 4096;
|
|
18
|
+
/** `getFile` refuses anything bigger: a bot never sees larger uploads. */
|
|
19
|
+
const MAX_INBOUND_FILE = 20 * 1024 * 1024;
|
|
20
|
+
/** A photo is recompressed and capped at 10 MB; anything else goes as a document. */
|
|
21
|
+
const MAX_PHOTO = 10 * 1024 * 1024;
|
|
22
|
+
/** Caption ceiling for any media message. */
|
|
23
|
+
const MAX_CAPTION = 1024;
|
|
24
|
+
const PHOTO_TYPES = new Set(['image/jpeg', 'image/png', 'image/webp']);
|
|
25
|
+
|
|
26
|
+
/** Trim runs to Telegram's ceiling — only ever reached by a card nobody split. */
|
|
27
|
+
function clampRuns(runs: TextRun[]): TextRun[] {
|
|
28
|
+
// An empty message is refused outright; a space is the smallest valid one.
|
|
29
|
+
if (!runs.some((run) => run.text.length > 0)) return [{ text: ' ' }];
|
|
30
|
+
let room = MAX_TEXT - 1;
|
|
31
|
+
const out: TextRun[] = [];
|
|
32
|
+
for (const run of runs) {
|
|
33
|
+
if (room <= 0) break;
|
|
34
|
+
if (run.text.length <= room) {
|
|
35
|
+
out.push(run);
|
|
36
|
+
room -= run.text.length;
|
|
37
|
+
} else {
|
|
38
|
+
out.push({ ...run, text: `${run.text.slice(0, room)}…` });
|
|
39
|
+
room = 0;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return out;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function plain(runs: TextRun[]): string {
|
|
46
|
+
return runs.map((run) => run.text).join('') || ' ';
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function toTelegramButton(button: ChannelButton): TelegramButton {
|
|
50
|
+
return 'url' in button ? { text: button.label, url: button.url } : { text: button.label, data: button.data };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function rowsOf(card: ChannelCard): TelegramButton[][] {
|
|
54
|
+
return (card.buttons ?? []).map((row) => row.map(toTelegramButton));
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function asTelegram(adapter: Adapter): TelegramAdapter {
|
|
58
|
+
if (!(adapter instanceof TelegramAdapter)) throw new Error('Not a Telegram adapter');
|
|
59
|
+
return adapter;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** `getMe` is cached per adapter: the username does not change while the token does not. */
|
|
63
|
+
const botInfo = new WeakMap<TelegramAdapter, Promise<{ username: string }>>();
|
|
64
|
+
|
|
65
|
+
function getBot(adapter: TelegramAdapter): Promise<{ username: string }> {
|
|
66
|
+
let pending = botInfo.get(adapter);
|
|
67
|
+
if (!pending) {
|
|
68
|
+
pending = adapter.getMe();
|
|
69
|
+
// A failed lookup must not be cached — the next call should try again.
|
|
70
|
+
pending.catch(() => botInfo.delete(adapter));
|
|
71
|
+
botInfo.set(adapter, pending);
|
|
72
|
+
}
|
|
73
|
+
return pending;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function describeError(error: unknown): string {
|
|
77
|
+
return error instanceof Error ? error.message : String(error);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export const telegramPlatform: ChannelPlatform = {
|
|
81
|
+
provider: 'telegram',
|
|
82
|
+
chatkit: 'telegram',
|
|
83
|
+
deliveryModes: ['webhook', 'polling'],
|
|
84
|
+
maxMessageLength: MAX_TEXT,
|
|
85
|
+
maxInboundFileBytes: MAX_INBOUND_FILE,
|
|
86
|
+
|
|
87
|
+
createAdapter({ account, credentials, mode }) {
|
|
88
|
+
const token = credentials.botToken ?? '';
|
|
89
|
+
// The integration gateway checks the secret header first (it is how it
|
|
90
|
+
// knows WHICH bot sent a delivery), and ChatKit refuses any webhook its
|
|
91
|
+
// adapter cannot verify itself. Both read the same generated secret, so
|
|
92
|
+
// the two checks cannot disagree.
|
|
93
|
+
return new TelegramAdapter({ token, account, polling: mode === 'polling', secretToken: credentials.webhookSecret || undefined });
|
|
94
|
+
},
|
|
95
|
+
|
|
96
|
+
async registerWebhook(adapter, url, secret) {
|
|
97
|
+
await asTelegram(adapter).setWebhook({ url, secretToken: secret });
|
|
98
|
+
},
|
|
99
|
+
|
|
100
|
+
async unregisterWebhook(adapter) {
|
|
101
|
+
await asTelegram(adapter).deleteWebhook();
|
|
102
|
+
},
|
|
103
|
+
|
|
104
|
+
async registerCommands(adapter, commands) {
|
|
105
|
+
await asTelegram(adapter).setMyCommands(commands, {});
|
|
106
|
+
},
|
|
107
|
+
|
|
108
|
+
async clearCommands(adapter, conversationId) {
|
|
109
|
+
await asTelegram(adapter).deleteMyCommands({ scope: { type: 'chat', chat_id: conversationId } });
|
|
110
|
+
},
|
|
111
|
+
|
|
112
|
+
render(card) {
|
|
113
|
+
const runs = clampRuns(card.runs);
|
|
114
|
+
if (!card.buttons?.length) return { content: richText(runs) };
|
|
115
|
+
return telegramButtons(plain(runs), rowsOf(card), { rich: runs });
|
|
116
|
+
},
|
|
117
|
+
|
|
118
|
+
renderEdit(platformMessageId, card) {
|
|
119
|
+
const runs = clampRuns(card.runs);
|
|
120
|
+
return telegramEditMessage(platformMessageId, plain(runs), {
|
|
121
|
+
rich: runs,
|
|
122
|
+
...(card.buttons?.length ? { buttons: rowsOf(card) } : {})
|
|
123
|
+
});
|
|
124
|
+
},
|
|
125
|
+
|
|
126
|
+
renderFile(file: ChannelFile) {
|
|
127
|
+
// GIFs become silent videos as a photo; a document keeps them intact.
|
|
128
|
+
const asPhoto = PHOTO_TYPES.has(file.mime) && file.data.byteLength <= MAX_PHOTO;
|
|
129
|
+
const mediaType: MediaType = asPhoto ? 'image' : 'document';
|
|
130
|
+
const caption = file.caption ? (file.caption.length > MAX_CAPTION ? `${file.caption.slice(0, MAX_CAPTION - 1)}…` : file.caption) : undefined;
|
|
131
|
+
return { content: media({ mediaType, data: file.data, mime: file.mime, filename: file.filename, caption }) };
|
|
132
|
+
},
|
|
133
|
+
|
|
134
|
+
albumOf(message: UniversalMessage) {
|
|
135
|
+
const raw = message.raw as { message?: { media_group_id?: string }; edited_message?: { media_group_id?: string } } | undefined;
|
|
136
|
+
return raw?.message?.media_group_id ?? raw?.edited_message?.media_group_id ?? null;
|
|
137
|
+
},
|
|
138
|
+
|
|
139
|
+
async pairingLink(adapter, code) {
|
|
140
|
+
const { username } = await getBot(asTelegram(adapter));
|
|
141
|
+
return `https://t.me/${username}?start=${encodeURIComponent(code)}`;
|
|
142
|
+
},
|
|
143
|
+
|
|
144
|
+
async botName(adapter) {
|
|
145
|
+
try {
|
|
146
|
+
return `@${(await getBot(asTelegram(adapter))).username}`;
|
|
147
|
+
} catch {
|
|
148
|
+
return null;
|
|
149
|
+
}
|
|
150
|
+
},
|
|
151
|
+
|
|
152
|
+
isDirect(message: UniversalMessage) {
|
|
153
|
+
// In a private chat Telegram's chat id IS the user's id; in a group it is
|
|
154
|
+
// the group's (negative) id. Reading the raw `chat.type` would say the
|
|
155
|
+
// same thing, but this survives a callback whose raw shape differs.
|
|
156
|
+
return message.from?.user_id != null && message.address.conversation_id === message.from.user_id;
|
|
157
|
+
},
|
|
158
|
+
|
|
159
|
+
parseCommand(input) {
|
|
160
|
+
const match = /^\/([a-zA-Z0-9_]+)(?:@[a-zA-Z0-9_]+)?(?:\s+([\s\S]*))?$/.exec(input.trim());
|
|
161
|
+
if (!match) return null;
|
|
162
|
+
return { command: match[1].toLowerCase(), argument: (match[2] ?? '').trim() };
|
|
163
|
+
},
|
|
164
|
+
|
|
165
|
+
async probe(adapter, mode: DeliveryMode) {
|
|
166
|
+
const bot = asTelegram(adapter);
|
|
167
|
+
let username: string;
|
|
168
|
+
try {
|
|
169
|
+
username = (await getBot(bot)).username;
|
|
170
|
+
} catch (error) {
|
|
171
|
+
const message = describeError(error);
|
|
172
|
+
// 401 is the one answer that means "this token is wrong".
|
|
173
|
+
return /\b401\b|Unauthorized/i.test(message)
|
|
174
|
+
? { status: 'needs_auth', detail: 'Telegram rejected the bot token' }
|
|
175
|
+
: { status: 'error', detail: message };
|
|
176
|
+
}
|
|
177
|
+
if (mode === 'polling') return { status: 'ok', detail: `@${username} · polling` };
|
|
178
|
+
|
|
179
|
+
try {
|
|
180
|
+
const info = await bot.getWebhookInfo();
|
|
181
|
+
// Telegram keeps the last error for as long as it is the latest event,
|
|
182
|
+
// so only a recent one says deliveries are failing NOW.
|
|
183
|
+
const recentError = info.last_error_date && Date.now() / 1000 - info.last_error_date < 15 * 60;
|
|
184
|
+
if (!info.url) return { status: 'error', detail: `@${username} · no webhook registered` };
|
|
185
|
+
if (recentError) return { status: 'error', detail: `@${username} · Telegram cannot reach Clopen: ${info.last_error_message ?? 'delivery failed'}` };
|
|
186
|
+
return { status: 'ok', detail: `@${username} · webhook` };
|
|
187
|
+
} catch (error) {
|
|
188
|
+
return { status: 'error', detail: describeError(error) };
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
};
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The per-platform contract of the chat-channel surface.
|
|
3
|
+
*
|
|
4
|
+
* ChatKit already makes sending, receiving, button presses, edits and rich
|
|
5
|
+
* text universal, so what is left per platform is small and genuinely
|
|
6
|
+
* platform-shaped: how a bot is built from a credential, how it is pointed at
|
|
7
|
+
* a webhook, how a card with buttons is rendered and re-rendered, how long a
|
|
8
|
+
* message may be, what a pairing link looks like, and how its command menu is
|
|
9
|
+
* published. Everything else — what to send, when, and where an answer goes —
|
|
10
|
+
* is Clopen's and lives once, above this line.
|
|
11
|
+
*
|
|
12
|
+
* Adding a platform (`Task 14`) is one file implementing this and one line in
|
|
13
|
+
* `platforms/index.ts`. Anything that needs MORE than this is a gap in ChatKit,
|
|
14
|
+
* not a reason to grow this interface.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import type { Adapter, OutboundContent, PlatformId, TextRun, UniversalMessage } from '@myrialabs/chatkit';
|
|
18
|
+
|
|
19
|
+
/** A tappable control. `data` comes back as a postback; `url` opens a page. */
|
|
20
|
+
export type ChannelButton = { label: string; data: string } | { label: string; url: string };
|
|
21
|
+
|
|
22
|
+
/** A message as Clopen composes it: formatted runs plus optional rows of buttons. */
|
|
23
|
+
export interface ChannelCard {
|
|
24
|
+
runs: TextRun[];
|
|
25
|
+
buttons?: ChannelButton[][];
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** What `chat.send()` takes besides the address. */
|
|
29
|
+
export interface ChannelFragment {
|
|
30
|
+
content: OutboundContent;
|
|
31
|
+
platform_meta?: Record<string, unknown>;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export type DeliveryMode = 'webhook' | 'polling';
|
|
35
|
+
|
|
36
|
+
export interface ChannelHealth {
|
|
37
|
+
status: 'ok' | 'needs_auth' | 'needs_config' | 'error';
|
|
38
|
+
detail: string | null;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface ChannelCommand {
|
|
42
|
+
command: string;
|
|
43
|
+
description: string;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** A file Clopen sends: bytes in hand, and what they are. */
|
|
47
|
+
export interface ChannelFile {
|
|
48
|
+
data: Uint8Array;
|
|
49
|
+
filename: string;
|
|
50
|
+
mime: string;
|
|
51
|
+
caption?: string;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface ChannelPlatform {
|
|
55
|
+
/** Integration provider id — the account this platform's bots are stored under. */
|
|
56
|
+
provider: string;
|
|
57
|
+
/** The ChatKit platform its adapters register as. */
|
|
58
|
+
chatkit: PlatformId;
|
|
59
|
+
/** Which delivery modes the platform supports, in order of preference. */
|
|
60
|
+
deliveryModes: DeliveryMode[];
|
|
61
|
+
/** Longest message the platform accepts, in the unit it counts. Longer output is split. */
|
|
62
|
+
maxMessageLength: number;
|
|
63
|
+
/** Largest file a bot may download from a chat. Bigger ones never reach Clopen. */
|
|
64
|
+
maxInboundFileBytes: number;
|
|
65
|
+
|
|
66
|
+
/** Build an adapter for one account. `account` is the integration account id. */
|
|
67
|
+
createAdapter(input: { account: string; credentials: Record<string, string>; mode: DeliveryMode }): Adapter;
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Point the bot at `url` (webhook mode), echoing `secret` back on every
|
|
71
|
+
* delivery. Throws when the platform refuses — the caller falls back to
|
|
72
|
+
* polling rather than leaving the bot deaf.
|
|
73
|
+
*/
|
|
74
|
+
registerWebhook(adapter: Adapter, url: string, secret: string): Promise<void>;
|
|
75
|
+
/** Undo `registerWebhook`. Best effort: called on disconnect, and failure is not fatal. */
|
|
76
|
+
unregisterWebhook(adapter: Adapter): Promise<void>;
|
|
77
|
+
/**
|
|
78
|
+
* Publish the bot's command menu. Best effort: a platform without a menu
|
|
79
|
+
* ignores it.
|
|
80
|
+
*/
|
|
81
|
+
registerCommands(adapter: Adapter, commands: ChannelCommand[]): Promise<void>;
|
|
82
|
+
/** Drop a chat's own menu, so it falls back to the default. */
|
|
83
|
+
clearCommands(adapter: Adapter, conversationId: string): Promise<void>;
|
|
84
|
+
|
|
85
|
+
render(card: ChannelCard): ChannelFragment;
|
|
86
|
+
/** Re-render a sent message in place — new text, new (or no) buttons. */
|
|
87
|
+
renderEdit(platformMessageId: string, card: ChannelCard): ChannelFragment;
|
|
88
|
+
/** A file: shown inline when the platform can (a photo), else as a document. */
|
|
89
|
+
renderFile(file: ChannelFile): ChannelFragment;
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* The album a message belongs to, when the platform sends several photos
|
|
93
|
+
* or files as separate messages that the user picked together. Null for a
|
|
94
|
+
* message on its own.
|
|
95
|
+
*/
|
|
96
|
+
albumOf(message: UniversalMessage): string | null;
|
|
97
|
+
|
|
98
|
+
/** A link that opens a chat with the bot and hands it `code`. */
|
|
99
|
+
pairingLink(adapter: Adapter, code: string): Promise<string>;
|
|
100
|
+
/** The bot's display handle, for the settings UI. */
|
|
101
|
+
botName(adapter: Adapter): Promise<string | null>;
|
|
102
|
+
|
|
103
|
+
/** True for a one-to-one chat with the bot. Group chats are never paired. */
|
|
104
|
+
isDirect(message: UniversalMessage): boolean;
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* `/start <code>`-style commands, normalised: the command without its
|
|
108
|
+
* slash (and without a `@botname` suffix) and whatever followed it.
|
|
109
|
+
*/
|
|
110
|
+
parseCommand(text: string): { command: string; argument: string } | null;
|
|
111
|
+
|
|
112
|
+
/** Live check of the credential and of webhook delivery. */
|
|
113
|
+
probe(adapter: Adapter, mode: DeliveryMode): Promise<ChannelHealth>;
|
|
114
|
+
}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Answering an AskUserQuestion from a chat.
|
|
3
|
+
*
|
|
4
|
+
* Each question of a tool use is its own message, laid out like the web form:
|
|
5
|
+
* options as buttons (checkboxes when several apply) and "Other…" to type an
|
|
6
|
+
* answer. A tap, Submit, a typed answer or a reply to the message answers one, and once every question of the tool
|
|
7
|
+
* use has its answer they go to the engine together — through the same
|
|
8
|
+
* `resolveUserAnswer` the web form calls, in the same shape, so the engine
|
|
9
|
+
* cannot tell which side answered.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import type { UniversalMessage } from '@myrialabs/chatkit';
|
|
13
|
+
import { channelMessageQueries, type ChannelMessageRow, type ChannelLinkRow } from '$backend/database/queries';
|
|
14
|
+
import { streamManager } from '$backend/chat/stream-manager';
|
|
15
|
+
import { channelRuntime, type ActiveChannel } from './runtime';
|
|
16
|
+
import { parsePayload } from './outbound';
|
|
17
|
+
import { clearAwaiting, isAwaiting, setAwaiting } from './awaiting';
|
|
18
|
+
import { REPLIES, answerFromSelection, questionAnsweredCard, questionCard, textCard, type ButtonAction, type QuestionPayload } from './messages';
|
|
19
|
+
|
|
20
|
+
export async function replyText(channel: ActiveChannel, message: UniversalMessage, text: string): Promise<void> {
|
|
21
|
+
const replyTo = message.content.type !== 'postback' ? message.platform_message_id ?? null : null;
|
|
22
|
+
await channelRuntime.send(channel.accountId, message.address.conversation_id, textCard(text), replyTo).catch(() => {});
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** A tap on a question's button. */
|
|
26
|
+
export async function handleQuestionButton(
|
|
27
|
+
channel: ActiveChannel,
|
|
28
|
+
message: UniversalMessage,
|
|
29
|
+
link: ChannelLinkRow,
|
|
30
|
+
row: ChannelMessageRow,
|
|
31
|
+
action: ButtonAction
|
|
32
|
+
): Promise<void> {
|
|
33
|
+
if (row.state !== 'open') {
|
|
34
|
+
await replyText(channel, message, REPLIES.staleQuestion);
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
const payload = parsePayload<QuestionPayload>(row);
|
|
38
|
+
|
|
39
|
+
const redraw = (typing = false) =>
|
|
40
|
+
channelRuntime.edit(link.account_id, link.conversation_id, row.platform_message_id, questionCard(row.id, payload, { typing }));
|
|
41
|
+
|
|
42
|
+
if (action.type === 'option' && payload.question.multiSelect) {
|
|
43
|
+
if (action.index < 0 || action.index >= payload.question.options.length) return;
|
|
44
|
+
const selected = new Set(payload.selected ?? []);
|
|
45
|
+
if (selected.has(action.index)) selected.delete(action.index);
|
|
46
|
+
else selected.add(action.index);
|
|
47
|
+
payload.selected = [...selected].sort((a, b) => a - b);
|
|
48
|
+
channelMessageQueries.setPayload(row.id, payload);
|
|
49
|
+
await redraw(isAwaiting(link.id, row.id));
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
if (action.type === 'other') {
|
|
54
|
+
// A ticked "Other" on a multi-select is unticked like any checkbox.
|
|
55
|
+
if (payload.question.multiSelect && payload.custom) {
|
|
56
|
+
payload.custom = undefined;
|
|
57
|
+
channelMessageQueries.setPayload(row.id, payload);
|
|
58
|
+
await redraw();
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
setAwaiting(link.id, { kind: 'question', rowId: row.id });
|
|
62
|
+
await redraw(true);
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
if (action.type === 'option') await answerQuestion(channel, message, link, row, payload, [action.index]);
|
|
67
|
+
else if (action.type === 'submit') await answerQuestion(channel, message, link, row, payload, payload.selected ?? [], payload.custom);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* A typed answer: after "Other…", as a reply to the question, or the one
|
|
72
|
+
* question waiting. On a single-choice question it is the answer. On a
|
|
73
|
+
* multi-select one it becomes the ticked "Other" next to the ticked options,
|
|
74
|
+
* sent with Submit, as in the web form.
|
|
75
|
+
*/
|
|
76
|
+
export async function answerQuestionWithText(
|
|
77
|
+
channel: ActiveChannel,
|
|
78
|
+
message: UniversalMessage,
|
|
79
|
+
link: ChannelLinkRow,
|
|
80
|
+
row: ChannelMessageRow,
|
|
81
|
+
text: string
|
|
82
|
+
): Promise<void> {
|
|
83
|
+
if (row.state !== 'open') {
|
|
84
|
+
await replyText(channel, message, REPLIES.staleQuestion);
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
clearAwaiting(link.id);
|
|
88
|
+
const payload = parsePayload<QuestionPayload>(row);
|
|
89
|
+
if (payload.question.multiSelect) {
|
|
90
|
+
payload.custom = text.trim();
|
|
91
|
+
channelMessageQueries.setPayload(row.id, payload);
|
|
92
|
+
await channelRuntime.edit(link.account_id, link.conversation_id, row.platform_message_id, questionCard(row.id, payload));
|
|
93
|
+
await replyText(channel, message, REPLIES.otherAdded);
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
await answerQuestion(channel, message, link, row, payload, [], text);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
async function answerQuestion(
|
|
100
|
+
channel: ActiveChannel,
|
|
101
|
+
message: UniversalMessage,
|
|
102
|
+
link: ChannelLinkRow,
|
|
103
|
+
row: ChannelMessageRow,
|
|
104
|
+
payload: QuestionPayload,
|
|
105
|
+
selection: number[],
|
|
106
|
+
custom?: string
|
|
107
|
+
): Promise<void> {
|
|
108
|
+
const answer = answerFromSelection(payload.question, selection, custom);
|
|
109
|
+
// Settle first: a tap and a web-UI answer racing for one question must not
|
|
110
|
+
// both reach the engine. Whoever settles it wins; the other stands down.
|
|
111
|
+
if (!channelMessageQueries.settle(row.id, 'answered')) {
|
|
112
|
+
await replyText(channel, message, REPLIES.staleQuestion);
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
if (isAwaiting(link.id, row.id)) clearAwaiting(link.id);
|
|
116
|
+
payload.answer = answer;
|
|
117
|
+
payload.selected = selection;
|
|
118
|
+
channelMessageQueries.setPayload(row.id, payload);
|
|
119
|
+
|
|
120
|
+
const siblings = channelMessageQueries.forToolUse(row.tool_use_id ?? '').filter((sibling) => sibling.link_id === link.id);
|
|
121
|
+
const pending = siblings.filter((sibling) => sibling.id !== row.id && sibling.state === 'open').length;
|
|
122
|
+
await channelRuntime.edit(link.account_id, link.conversation_id, row.platform_message_id, questionAnsweredCard(payload, answer, pending));
|
|
123
|
+
if (pending > 0 || !row.tool_use_id || !row.chat_session_id) return;
|
|
124
|
+
|
|
125
|
+
const answers: Record<string, string> = {};
|
|
126
|
+
for (const sibling of siblings) {
|
|
127
|
+
const siblingPayload = sibling.id === row.id ? payload : parsePayload<QuestionPayload>(sibling);
|
|
128
|
+
answers[siblingPayload.question.question] = siblingPayload.answer ?? '';
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const handled = streamManager.resolveUserAnswer(row.chat_session_id, row.project_id ?? undefined, row.tool_use_id, answers);
|
|
132
|
+
if (!handled) await replyText(channel, message, REPLIES.answerFailed);
|
|
133
|
+
}
|