@arnilo/prism-hosts 0.0.0-stage → 0.13.0
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/CHANGELOG.md +394 -0
- package/LICENSE +21 -0
- package/README.md +34 -2
- package/acp/README.md +87 -0
- package/acp/src/capabilities.ts +184 -0
- package/acp/src/errors.ts +24 -0
- package/acp/src/host.ts +36 -0
- package/acp/src/index.ts +25 -0
- package/acp/src/limits.ts +49 -0
- package/acp/src/mapper.ts +419 -0
- package/acp/src/permission.ts +37 -0
- package/acp/src/projection.ts +39 -0
- package/acp/src/prompt.ts +170 -0
- package/acp/src/serve.ts +345 -0
- package/acp/src/session-map.ts +49 -0
- package/ag-ui/README.md +56 -0
- package/ag-ui/src/a2ui.ts +570 -0
- package/ag-ui/src/ag-ui-mapper.ts +507 -0
- package/ag-ui/src/encrypted-value.ts +40 -0
- package/ag-ui/src/errors.ts +29 -0
- package/ag-ui/src/handler.ts +642 -0
- package/ag-ui/src/index.ts +177 -0
- package/ag-ui/src/input.ts +190 -0
- package/ag-ui/src/limits.ts +279 -0
- package/ag-ui/src/mcp-apps.ts +256 -0
- package/ag-ui/src/mcp.ts +94 -0
- package/ag-ui/src/projection.ts +201 -0
- package/ag-ui/src/projectors.ts +272 -0
- package/ag-ui/src/renderer/bind.ts +152 -0
- package/ag-ui/src/renderer/core.ts +270 -0
- package/ag-ui/src/renderer/index.ts +165 -0
- package/ag-ui/src/replay.ts +189 -0
- package/ag-ui/src/types.ts +66 -0
- package/channels/README.md +139 -0
- package/channels/src/admission.ts +8 -0
- package/channels/src/approvals.ts +262 -0
- package/channels/src/checkpoint-contract.ts +97 -0
- package/channels/src/delivery.ts +116 -0
- package/channels/src/host-ui.ts +356 -0
- package/channels/src/identity.ts +46 -0
- package/channels/src/index.ts +82 -0
- package/channels/src/limits.ts +49 -0
- package/channels/src/memory-stores.ts +112 -0
- package/channels/src/pairing.ts +178 -0
- package/channels/src/runtime-admit.ts +389 -0
- package/channels/src/runtime-core.ts +621 -0
- package/channels/src/runtime-reconcile.ts +299 -0
- package/channels/src/runtime-turn.ts +664 -0
- package/channels/src/runtime-types.ts +95 -0
- package/channels/src/runtime.ts +86 -0
- package/channels/src/secret-ref.ts +42 -0
- package/channels/src/signal.ts +790 -0
- package/channels/src/state.ts +355 -0
- package/channels/src/telegram.ts +1317 -0
- package/channels/src/types.ts +442 -0
- package/devtools/README.md +92 -0
- package/devtools/bin/prism-devtools.ts +63 -0
- package/devtools/src/args.ts +71 -0
- package/devtools/src/bun.d.ts +27 -0
- package/devtools/src/compare.ts +190 -0
- package/devtools/src/errors.ts +15 -0
- package/devtools/src/index.ts +25 -0
- package/devtools/src/replay.ts +36 -0
- package/devtools/src/security.ts +80 -0
- package/devtools/src/serve.ts +259 -0
- package/devtools/src/ui/assets.ts +108 -0
- package/devtools/src/ui/inspector.ts +182 -0
- package/driver-process/README.md +197 -0
- package/driver-process/src/abort.ts +74 -0
- package/driver-process/src/adapter.ts +211 -0
- package/driver-process/src/driver.ts +303 -0
- package/driver-process/src/errors.ts +17 -0
- package/driver-process/src/extend.ts +72 -0
- package/driver-process/src/index.ts +5 -0
- package/driver-process/src/inspect.ts +33 -0
- package/driver-process/src/session.ts +72 -0
- package/driver-process/src/testing.ts +394 -0
- package/driver-process/src/transports/json-rpc.ts +147 -0
- package/driver-process/src/transports/jsonl-stream.ts +12 -0
- package/driver-process/src/transports/types.ts +11 -0
- package/driver-process/src/turn.ts +106 -0
- package/evals/README.md +843 -0
- package/evals/src/calibration.ts +179 -0
- package/evals/src/citation-integrity.ts +98 -0
- package/evals/src/citations.ts +45 -0
- package/evals/src/compare-experiments.ts +153 -0
- package/evals/src/comparison.ts +230 -0
- package/evals/src/curate.ts +257 -0
- package/evals/src/dataset.ts +81 -0
- package/evals/src/erp-invariants.ts +163 -0
- package/evals/src/errors.ts +23 -0
- package/evals/src/experiment.ts +537 -0
- package/evals/src/failure-injection.ts +77 -0
- package/evals/src/feedback.ts +53 -0
- package/evals/src/index.ts +198 -0
- package/evals/src/injection.ts +247 -0
- package/evals/src/judge-panel.ts +109 -0
- package/evals/src/judge.ts +89 -0
- package/evals/src/limits.ts +50 -0
- package/evals/src/report-record.ts +47 -0
- package/evals/src/rubric-judge.ts +334 -0
- package/evals/src/scenario-runner.ts +317 -0
- package/evals/src/scenarios.ts +81 -0
- package/evals/src/score.ts +328 -0
- package/evals/src/scorer.ts +21 -0
- package/evals/src/state-match.ts +130 -0
- package/evals/src/stats.ts +635 -0
- package/evals/src/threshold.ts +117 -0
- package/evals/src/timeline.ts +38 -0
- package/evals/src/toolless-session.ts +33 -0
- package/evals/src/trace.ts +80 -0
- package/evals/src/trajectory.ts +623 -0
- package/evals/src/types.ts +672 -0
- package/evals/src/user-simulator.ts +101 -0
- package/evals/src/util.ts +207 -0
- package/headless/README.md +172 -0
- package/headless/src/answers.ts +91 -0
- package/headless/src/authority.ts +32 -0
- package/headless/src/errors.ts +36 -0
- package/headless/src/index.ts +17 -0
- package/headless/src/limits.ts +11 -0
- package/headless/src/pending.ts +16 -0
- package/headless/src/policy.ts +36 -0
- package/headless/src/resume.ts +103 -0
- package/headless/src/route.ts +153 -0
- package/headless/src/scheduler/clock.ts +22 -0
- package/headless/src/scheduler/cron.ts +19 -0
- package/headless/src/scheduler/firing.ts +58 -0
- package/headless/src/scheduler/index.ts +399 -0
- package/headless/src/scheduler/lease.ts +38 -0
- package/headless/src/scheduler/missed.ts +12 -0
- package/headless/src/scheduler/state.ts +132 -0
- package/host-builder/README.md +251 -0
- package/host-builder/bin/prism-host-builder.ts +169 -0
- package/host-builder/data/api.json +6167 -0
- package/host-builder/data/errors.json +546 -0
- package/host-builder/data/examples/acp.ts +63 -0
- package/host-builder/data/examples/adapters/conformance.ts +34 -0
- package/host-builder/data/examples/adapters/fixtures/rpc-server.json +26 -0
- package/host-builder/data/examples/adapters/fixtures/stream-cli.json +27 -0
- package/host-builder/data/examples/adapters/fixtures/workspace-config.json +28 -0
- package/host-builder/data/examples/adapters/rpc-server.dialect.ts +218 -0
- package/host-builder/data/examples/adapters/rpc-server.ts +309 -0
- package/host-builder/data/examples/adapters/stream-cli.dialect.ts +165 -0
- package/host-builder/data/examples/adapters/stream-cli.ts +256 -0
- package/host-builder/data/examples/adapters/workspace-config.dialect.ts +172 -0
- package/host-builder/data/examples/adapters/workspace-config.ts +251 -0
- package/host-builder/data/examples/advisor.ts +94 -0
- package/host-builder/data/examples/ag-ui-a2ui.ts +80 -0
- package/host-builder/data/examples/ag-ui-mcp-apps.ts +44 -0
- package/host-builder/data/examples/ag-ui-server.ts +118 -0
- package/host-builder/data/examples/agent-durable-approval.ts +43 -0
- package/host-builder/data/examples/api-key-auth.ts +23 -0
- package/host-builder/data/examples/approval.ts +92 -0
- package/host-builder/data/examples/attention-compiler.ts +81 -0
- package/host-builder/data/examples/autonomous-coding-loop.ts +343 -0
- package/host-builder/data/examples/behavior-evaluation.ts +303 -0
- package/host-builder/data/examples/build-workflow.ts +334 -0
- package/host-builder/data/examples/cache-aware-prompt-assembly.ts +139 -0
- package/host-builder/data/examples/caveman-ponytail.ts +197 -0
- package/host-builder/data/examples/cli.ts +31 -0
- package/host-builder/data/examples/coding-approval.ts +115 -0
- package/host-builder/data/examples/coding-browser-evaluation.ts +208 -0
- package/host-builder/data/examples/coding-compaction.ts +30 -0
- package/host-builder/data/examples/coding-goal-verify.ts +121 -0
- package/host-builder/data/examples/coding-tools-capability-gaps.ts +75 -0
- package/host-builder/data/examples/compaction.ts +36 -0
- package/host-builder/data/examples/connected-slack-mcp.ts +67 -0
- package/host-builder/data/examples/context.ts +29 -0
- package/host-builder/data/examples/custom-adapter.ts +256 -0
- package/host-builder/data/examples/custom-builders.ts +66 -0
- package/host-builder/data/examples/custom-loop.ts +89 -0
- package/host-builder/data/examples/custom-provider.ts +70 -0
- package/host-builder/data/examples/custom-session-store.ts +72 -0
- package/host-builder/data/examples/custom-tools-skills-context.ts +97 -0
- package/host-builder/data/examples/decision-models.ts +98 -0
- package/host-builder/data/examples/define-package.ts +188 -0
- package/host-builder/data/examples/delegate.ts +200 -0
- package/host-builder/data/examples/discover-skills.ts +65 -0
- package/host-builder/data/examples/drive-rag-sync.ts +44 -0
- package/host-builder/data/examples/durable-approval.ts +139 -0
- package/host-builder/data/examples/durable-investigation.ts +93 -0
- package/host-builder/data/examples/durable-loops-and-approvals.ts +94 -0
- package/host-builder/data/examples/enterprise-identity.ts +21 -0
- package/host-builder/data/examples/enterprise-policy-audit.ts +50 -0
- package/host-builder/data/examples/enterprise-work-connectors.ts +103 -0
- package/host-builder/data/examples/eval-injection.ts +73 -0
- package/host-builder/data/examples/eval-judges.ts +145 -0
- package/host-builder/data/examples/evals.ts +86 -0
- package/host-builder/data/examples/evaluation-gate.ts +40 -0
- package/host-builder/data/examples/execution-timeline.ts +173 -0
- package/host-builder/data/examples/external-agent.ts +541 -0
- package/host-builder/data/examples/external-app-db-backed.ts +344 -0
- package/host-builder/data/examples/governance-deny.ts +122 -0
- package/host-builder/data/examples/guardrail-packs.ts +240 -0
- package/host-builder/data/examples/headless-host.ts +245 -0
- package/host-builder/data/examples/hooks-audit-command.mjs +31 -0
- package/host-builder/data/examples/hooks-json.ts +87 -0
- package/host-builder/data/examples/host-builder-agent.ts +150 -0
- package/host-builder/data/examples/host-hooks.ts +71 -0
- package/host-builder/data/examples/host-step-loop-timeline.ts +212 -0
- package/host-builder/data/examples/hosted-sandbox.ts +48 -0
- package/host-builder/data/examples/instruction-injection.ts +127 -0
- package/host-builder/data/examples/jsonl-stores-branching.ts +49 -0
- package/host-builder/data/examples/long-term-memory.ts +158 -0
- package/host-builder/data/examples/manifest.ts +112 -0
- package/host-builder/data/examples/mcp-server.ts +48 -0
- package/host-builder/data/examples/mcp-trust.ts +173 -0
- package/host-builder/data/examples/memory-and-wiki.ts +315 -0
- package/host-builder/data/examples/memory-lifecycle.ts +302 -0
- package/host-builder/data/examples/memory-system.ts +252 -0
- package/host-builder/data/examples/messaging-agent.ts +70 -0
- package/host-builder/data/examples/minimal-host-app.ts +41 -0
- package/host-builder/data/examples/model-router-aggregate-budgets.ts +364 -0
- package/host-builder/data/examples/model-router.ts +106 -0
- package/host-builder/data/examples/obscura.ts +48 -0
- package/host-builder/data/examples/observability.ts +116 -0
- package/host-builder/data/examples/open-connector-sidecar.ts +105 -0
- package/host-builder/data/examples/openai-compatible.ts +70 -0
- package/host-builder/data/examples/package-skills.ts +85 -0
- package/host-builder/data/examples/phase9-coding-intelligence.ts +221 -0
- package/host-builder/data/examples/provider-registration.ts +29 -0
- package/host-builder/data/examples/provider-resolver.ts +39 -0
- package/host-builder/data/examples/rag.ts +40 -0
- package/host-builder/data/examples/remote-agent-server.ts +45 -0
- package/host-builder/data/examples/remote-agent.ts +124 -0
- package/host-builder/data/examples/research-ledger.ts +79 -0
- package/host-builder/data/examples/revocation-propagation.ts +287 -0
- package/host-builder/data/examples/run-feedback.ts +93 -0
- package/host-builder/data/examples/scanned-document-rag.ts +48 -0
- package/host-builder/data/examples/sdk-basics.ts +21 -0
- package/host-builder/data/examples/secure-agent.ts +55 -0
- package/host-builder/data/examples/semantic-memory.ts +52 -0
- package/host-builder/data/examples/serve-tools.ts +495 -0
- package/host-builder/data/examples/session-memory.ts +317 -0
- package/host-builder/data/examples/session-search.ts +131 -0
- package/host-builder/data/examples/session.ts +52 -0
- package/host-builder/data/examples/side-call.ts +64 -0
- package/host-builder/data/examples/signal-agent.ts +9 -0
- package/host-builder/data/examples/skills-progressive-disclosure.ts +88 -0
- package/host-builder/data/examples/skills.ts +19 -0
- package/host-builder/data/examples/sqlite-resume.ts +147 -0
- package/host-builder/data/examples/system-project-prompts.ts +74 -0
- package/host-builder/data/examples/system-prompts.ts +19 -0
- package/host-builder/data/examples/telegram-agent.ts +30 -0
- package/host-builder/data/examples/tool-narrowing-planes.ts +99 -0
- package/host-builder/data/examples/tools.ts +29 -0
- package/host-builder/data/examples/validator.ts +67 -0
- package/host-builder/data/examples/web-no-key.ts +85 -0
- package/host-builder/data/examples/web-research.ts +35 -0
- package/host-builder/data/examples/workflow-event-sink.ts +114 -0
- package/host-builder/data/examples/workflow-loop.ts +93 -0
- package/host-builder/data/examples/workflow-multimodal-document.ts +94 -0
- package/host-builder/data/examples/workflow-parallel-research.ts +111 -0
- package/host-builder/data/examples/workflow-postgres-resume.ts +75 -0
- package/host-builder/data/examples/workflow-research-and-review.ts +98 -0
- package/host-builder/data/examples/workflow-sqlite-resume.ts +163 -0
- package/host-builder/data/examples.json +130 -0
- package/host-builder/skills/prism-host-builder/SKILL.md +85 -0
- package/host-builder/skills/prism-host-builder/references/choosing.md +101 -0
- package/host-builder/skills/prism-host-builder/references/layout.md +52 -0
- package/host-builder/skills/prism-host-builder/references/pitfalls.md +50 -0
- package/host-builder/skills/prism-host-builder/references/recipes.md +129 -0
- package/host-builder/skills/prism-host-builder/references/security.md +52 -0
- package/host-builder/skills/prism-host-builder/references/upgrading.md +67 -0
- package/host-builder/skills/prism-host-builder/references/verification.md +108 -0
- package/host-builder/src/check/child.ts +108 -0
- package/host-builder/src/check/conformance.ts +13 -0
- package/host-builder/src/check/inspect.ts +20 -0
- package/host-builder/src/check/manifest.ts +23 -0
- package/host-builder/src/check/runner.ts +181 -0
- package/host-builder/src/check/targets.ts +65 -0
- package/host-builder/src/errors.ts +35 -0
- package/host-builder/src/index.ts +25 -0
- package/host-builder/src/indexes.ts +145 -0
- package/host-builder/src/install/install.ts +400 -0
- package/host-builder/src/install/targets.ts +50 -0
- package/host-builder/src/lookup/api.ts +127 -0
- package/host-builder/src/lookup/bound.ts +38 -0
- package/host-builder/src/lookup/docs.ts +238 -0
- package/host-builder/src/lookup/errors.ts +92 -0
- package/host-builder/src/lookup/examples.ts +117 -0
- package/host-builder/src/lookup/text.ts +60 -0
- package/host-builder/src/server.ts +300 -0
- package/host-builder/src/version.ts +38 -0
- package/mcp-server/README.md +219 -0
- package/mcp-server/src/bounds.ts +23 -0
- package/mcp-server/src/host.ts +31 -0
- package/mcp-server/src/index.ts +27 -0
- package/mcp-server/src/serve-tools.ts +408 -0
- package/mcp-server/src/serve.ts +329 -0
- package/mcp-server/src/server.ts +331 -0
- package/mcp-server/src/session-map.ts +47 -0
- package/mcp-server/src/skill-resources.ts +85 -0
- package/mcp-server/src/types.ts +215 -0
- package/package.json +130 -4
- package/remote/README.md +244 -0
- package/remote/src/attribution.ts +22 -0
- package/remote/src/auth.ts +30 -0
- package/remote/src/bun-module.d.ts +34 -0
- package/remote/src/channel.ts +86 -0
- package/remote/src/connect.ts +212 -0
- package/remote/src/dispatcher.ts +282 -0
- package/remote/src/errors.ts +59 -0
- package/remote/src/host-ui.ts +152 -0
- package/remote/src/http-gate.ts +43 -0
- package/remote/src/index.ts +53 -0
- package/remote/src/jsonl.ts +69 -0
- package/remote/src/limits.ts +43 -0
- package/remote/src/mirror.ts +90 -0
- package/remote/src/pending.ts +22 -0
- package/remote/src/protocol.ts +107 -0
- package/remote/src/serve.ts +560 -0
- package/remote/src/session-proxy.ts +219 -0
- package/remote/src/sse.ts +38 -0
- package/remote/src/stdio-client.ts +41 -0
- package/remote/src/testing-fixtures/serve-stdio.ts +32 -0
- package/remote/src/testing.ts +230 -0
- package/remote/src/transport.ts +139 -0
- package/remote/src/transports/client.ts +126 -0
- package/remote/src/transports/network.ts +268 -0
- package/remote/src/wire.ts +244 -0
|
@@ -0,0 +1,1317 @@
|
|
|
1
|
+
// Plan 079 Task 5: native-fetch Telegram Bot API adapter. Importing and constructing are inert;
|
|
2
|
+
// `start` is the only polling lifecycle entry point and the webhook handler is host-mounted.
|
|
3
|
+
import { createHash, randomUUID, timingSafeEqual } from "node:crypto";
|
|
4
|
+
import { type Agent, type OwnershipScope } from "@arnilo/prism";
|
|
5
|
+
import type { CheckpointStore, LeaseRecord, LeaseStore } from "./checkpoint-contract.js";
|
|
6
|
+
import { bindChannelHostUi } from "./host-ui.js";
|
|
7
|
+
import { retryableAdmission } from "./admission.js";
|
|
8
|
+
import { DEFAULT_CHANNEL_LIMITS, HARD_CHANNEL_LIMITS } from "./limits.js";
|
|
9
|
+
import { createChannelStateStore } from "./state.js";
|
|
10
|
+
import { type ChannelSecretSource, resolveChannelSecretRef, createChannelRedactor } from "./secret-ref.js";
|
|
11
|
+
import { createMemoryCheckpointStore, createMemoryLeaseStore } from "./memory-stores.js";
|
|
12
|
+
import { createChannelRuntime } from "./runtime.js";
|
|
13
|
+
import type {
|
|
14
|
+
ChannelAdapter,
|
|
15
|
+
ChannelAssistantDelta,
|
|
16
|
+
ChannelAttachmentBytes,
|
|
17
|
+
ChannelAttachmentRef,
|
|
18
|
+
ChannelAuthorizeInput,
|
|
19
|
+
ChannelAuthorization,
|
|
20
|
+
ChannelConnectionHandle,
|
|
21
|
+
ChannelInboundEvent,
|
|
22
|
+
ChannelReceive,
|
|
23
|
+
ChannelReply,
|
|
24
|
+
ChannelReplyControl,
|
|
25
|
+
} from "./types.js";
|
|
26
|
+
|
|
27
|
+
export type { ChannelConnectionHandle };
|
|
28
|
+
export type { ChannelSecretSource };
|
|
29
|
+
|
|
30
|
+
const DEFAULT_API_ORIGIN = "https://api.telegram.org";
|
|
31
|
+
const DEFAULT_POLL_TIMEOUT_SECONDS = 30;
|
|
32
|
+
const DEFAULT_POLL_LIMIT = 100;
|
|
33
|
+
const DEFAULT_LEASE_TTL_MS = 90_000;
|
|
34
|
+
const DEFAULT_MAX_REQUEST_BYTES = 128 * 1024;
|
|
35
|
+
const HARD_MAX_REQUEST_BYTES = 1024 * 1024;
|
|
36
|
+
const TELEGRAM_TEXT_CODE_UNITS = 3500;
|
|
37
|
+
const MAX_SEND_ATTEMPTS = 5;
|
|
38
|
+
/** One preview slot per chat: repeated updates with the same id replace that draft; a new id would create a second one. */
|
|
39
|
+
const DRAFT_ID = 1;
|
|
40
|
+
const RECEIVER_LEASE_NAMESPACE = "prism.channels.v1.telegram.receiver";
|
|
41
|
+
const RECEIVER_LEASE_KEY_PREFIX = "r1:";
|
|
42
|
+
/** One event references at most this many attachments (a photo album collapses to its largest size). */
|
|
43
|
+
const MAX_ATTACHMENT_REFS = 8;
|
|
44
|
+
const MAX_ATTACHMENT_META_BYTES = 256;
|
|
45
|
+
/** Bot API `sendVoice` accepts OGG/OPUS, MP3 and M4A; anything else stays text-only. */
|
|
46
|
+
const VOICE_FORMATS: ReadonlyMap<string, string> = new Map([
|
|
47
|
+
["ogg", "audio/ogg"],
|
|
48
|
+
["oga", "audio/ogg"],
|
|
49
|
+
["opus", "audio/ogg"],
|
|
50
|
+
["mp3", "audio/mpeg"],
|
|
51
|
+
["m4a", "audio/mp4"],
|
|
52
|
+
]);
|
|
53
|
+
|
|
54
|
+
export interface TelegramAdapterOptions {
|
|
55
|
+
/** Stable host-selected connection id; it is never read from Telegram input. */
|
|
56
|
+
readonly connectionId: string;
|
|
57
|
+
/** Resolved only immediately before a Bot API request; the adapter never reads environment variables. */
|
|
58
|
+
readonly botToken: ChannelSecretSource;
|
|
59
|
+
/** Durable service-owned polling cursor. Required: memory-only polling is not restart-safe. */
|
|
60
|
+
readonly checkpoints: CheckpointStore;
|
|
61
|
+
/** One receiver per connection. Required to fence concurrent pollers and webhook workers. */
|
|
62
|
+
readonly leases: LeaseStore;
|
|
63
|
+
/** Service ownership for the connection cursor/receiver lease, separate from user bindings. */
|
|
64
|
+
readonly cursorOwnership: OwnershipScope;
|
|
65
|
+
/**
|
|
66
|
+
* Opt-in text admission from `group`/`supergroup` chats (forum topics keep their topic id as
|
|
67
|
+
* `threadId`). Defaults to `false`, so only private text DMs are parsed. Host `authorize`
|
|
68
|
+
* remains the only admission gate and is still deny-by-default per chat/thread/sender.
|
|
69
|
+
*/
|
|
70
|
+
readonly allowGroups?: boolean;
|
|
71
|
+
/**
|
|
72
|
+
* Opt-in ephemeral previews of the answer being produced (Bot API `sendMessageDraft`), sent by
|
|
73
|
+
* `TelegramAdapter.sendDraft`. Defaults to `false`, so nothing streams unless the host also wires
|
|
74
|
+
* `ChannelRuntimeOptions.onAssistantDelta` to `sendDraft`. Previews are never journaled, never
|
|
75
|
+
* carry controls, and are skipped for group chats (Bot API drafts are private-chat only).
|
|
76
|
+
*/
|
|
77
|
+
readonly sendDrafts?: boolean;
|
|
78
|
+
/**
|
|
79
|
+
* Per-attachment byte ceiling for one `getFile` download (default 1 MiB, hard 4 MiB). Oversize
|
|
80
|
+
* fails closed before the body is buffered; bytes are never journaled, logged or written to disk.
|
|
81
|
+
*/
|
|
82
|
+
readonly maxAttachmentBytes?: number;
|
|
83
|
+
/**
|
|
84
|
+
* Host-wrapped `TranscriptionProvider.transcribe` for inbound voice notes. Only the current
|
|
85
|
+
* event's file id is fetched (bounded by `maxAttachmentBytes`), the transcript becomes ordinary
|
|
86
|
+
* turn text, and the audio is discarded. Without it a voice-only message is unsupported.
|
|
87
|
+
*/
|
|
88
|
+
readonly transcribe?: (audio: Uint8Array, format: string | undefined, signal?: AbortSignal) => Promise<string>;
|
|
89
|
+
/**
|
|
90
|
+
* Host-wrapped `SpeechProvider` synthesis for outbound text. Runs only for `final` replies and
|
|
91
|
+
* only alongside the text message (a voice failure never fails the reply). The destination is
|
|
92
|
+
* always the bound chat/thread; a caller can never select a `file_id` or URL.
|
|
93
|
+
*/
|
|
94
|
+
readonly synthesize?: (text: string, signal?: AbortSignal) => Promise<{ readonly audio: Uint8Array; readonly format: string }>;
|
|
95
|
+
/**
|
|
96
|
+
* Host-wrapped document-text extraction for inbound documents. Only with it does a document
|
|
97
|
+
* become turn text; documents are never silently dumped into the model context.
|
|
98
|
+
*/
|
|
99
|
+
readonly extractDocumentText?: (bytes: Uint8Array, mimeType: string | undefined, signal?: AbortSignal) => Promise<string>;
|
|
100
|
+
/** Trusted exact HTTPS Bot API origin; defaults to the official API. */
|
|
101
|
+
readonly apiOrigin?: string;
|
|
102
|
+
readonly fetch?: typeof globalThis.fetch;
|
|
103
|
+
readonly pollTimeoutSeconds?: number;
|
|
104
|
+
readonly pollLimit?: number;
|
|
105
|
+
readonly leaseTtlMs?: number;
|
|
106
|
+
/** Bounds webhook/admin response bodies read by the adapter. */
|
|
107
|
+
readonly maxResponseBytes?: number;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export interface TelegramWebhookHandlerOptions {
|
|
111
|
+
readonly connectionId: string;
|
|
112
|
+
readonly botToken: ChannelSecretSource;
|
|
113
|
+
/** Resolved once on the first request; must yield 1-256 URL-safe characters or every request fails closed. */
|
|
114
|
+
readonly webhookSecret: ChannelSecretSource;
|
|
115
|
+
readonly admit: ChannelReceive;
|
|
116
|
+
readonly leases: LeaseStore;
|
|
117
|
+
readonly cursorOwnership: OwnershipScope;
|
|
118
|
+
/** Same contract as `TelegramAdapterOptions.allowGroups`; parsed updates match the poller exactly. */
|
|
119
|
+
readonly allowGroups?: boolean;
|
|
120
|
+
/** Same contract as `TelegramAdapterOptions.maxAttachmentBytes`. */
|
|
121
|
+
readonly maxAttachmentBytes?: number;
|
|
122
|
+
/** Same contract as `TelegramAdapterOptions.transcribe`; inbound voice text is resolved before `admit`. */
|
|
123
|
+
readonly transcribe?: (audio: Uint8Array, format: string | undefined, signal?: AbortSignal) => Promise<string>;
|
|
124
|
+
/** Same contract as `TelegramAdapterOptions.extractDocumentText`. */
|
|
125
|
+
readonly extractDocumentText?: (bytes: Uint8Array, mimeType: string | undefined, signal?: AbortSignal) => Promise<string>;
|
|
126
|
+
readonly apiOrigin?: string;
|
|
127
|
+
readonly fetch?: typeof globalThis.fetch;
|
|
128
|
+
readonly leaseTtlMs?: number;
|
|
129
|
+
readonly maxRequestBytes?: number;
|
|
130
|
+
readonly maxResponseBytes?: number;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** A separately mountable Web-standard Telegram webhook handler. */
|
|
134
|
+
export type TelegramWebhookHandler = (request: Request) => Promise<Response>;
|
|
135
|
+
|
|
136
|
+
/** Channel adapter with Telegram's ephemeral draft preview (Bot API `sendMessageDraft`). */
|
|
137
|
+
export interface TelegramAdapter extends ChannelAdapter {
|
|
138
|
+
/**
|
|
139
|
+
* Fire-and-forget preview of the answer being produced for one bound conversation. No-op unless
|
|
140
|
+
* `sendDrafts` is enabled, the delta names this connection, and the chat is private. Previews are
|
|
141
|
+
* coalesced (one request in flight, latest text wins), capped to the tail of the outbound budget,
|
|
142
|
+
* and silently dropped on failure — the terminal `send` is unaffected.
|
|
143
|
+
*/
|
|
144
|
+
sendDraft(delta: ChannelAssistantDelta): void;
|
|
145
|
+
/**
|
|
146
|
+
* Bounded bytes for one inbound attachment ref (Bot API `getFile` + file download), or `undefined`
|
|
147
|
+
* when the ref is malformed, oversize, unavailable, or the adapter is stopped. Wire it as
|
|
148
|
+
* `ChannelRuntimeOptions.fetchAttachment` so a model that declares `image` input can receive the
|
|
149
|
+
* image; the runtime only ever passes refs of the event it is running, never model output.
|
|
150
|
+
*/
|
|
151
|
+
fetchAttachment(ref: ChannelAttachmentRef): Promise<ChannelAttachmentBytes | undefined>;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
interface TelegramApiErrorShape {
|
|
155
|
+
readonly status?: number;
|
|
156
|
+
readonly retryAfter?: number;
|
|
157
|
+
readonly kind: "api" | "credential" | "network" | "response";
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
class TelegramApiError extends Error {
|
|
161
|
+
readonly status?: number;
|
|
162
|
+
readonly retryAfter?: number;
|
|
163
|
+
readonly kind: TelegramApiErrorShape["kind"];
|
|
164
|
+
|
|
165
|
+
constructor(shape: TelegramApiErrorShape) {
|
|
166
|
+
super("Telegram API request failed");
|
|
167
|
+
this.name = "TelegramApiError";
|
|
168
|
+
this.status = shape.status;
|
|
169
|
+
this.retryAfter = shape.retryAfter;
|
|
170
|
+
this.kind = shape.kind;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
class TelegramDeliveryUnknownError extends Error {
|
|
175
|
+
constructor() {
|
|
176
|
+
super("Telegram delivery outcome unknown");
|
|
177
|
+
this.name = "TelegramDeliveryUnknownError";
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function asRecord(value: unknown): Record<string, unknown> | undefined {
|
|
182
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function asId(value: unknown): string | undefined {
|
|
186
|
+
if (typeof value === "string" && value.length > 0 && Buffer.byteLength(value, "utf8") <= 128) return value;
|
|
187
|
+
if (typeof value === "number" && Number.isSafeInteger(value) && value >= 0) return String(value);
|
|
188
|
+
return undefined;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function asPositiveInteger(value: unknown): number | undefined {
|
|
192
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : undefined;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** Telegram `chat.id` is a signed int64: group/supergroup ids are negative, user ids are not. */
|
|
196
|
+
function asChatId(value: unknown): string | undefined {
|
|
197
|
+
if (typeof value === "string" && value.length > 0 && Buffer.byteLength(value, "utf8") <= 128) return value;
|
|
198
|
+
return typeof value === "number" && Number.isSafeInteger(value) ? String(value) : undefined;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function apiOrigin(value: string | undefined): string {
|
|
202
|
+
const raw = value ?? DEFAULT_API_ORIGIN;
|
|
203
|
+
let parsed: URL;
|
|
204
|
+
try {
|
|
205
|
+
parsed = new URL(raw);
|
|
206
|
+
} catch {
|
|
207
|
+
throw new TypeError("Telegram apiOrigin must be an exact HTTPS origin");
|
|
208
|
+
}
|
|
209
|
+
if (
|
|
210
|
+
parsed.protocol !== "https:" ||
|
|
211
|
+
parsed.username ||
|
|
212
|
+
parsed.password ||
|
|
213
|
+
parsed.pathname !== "/" ||
|
|
214
|
+
parsed.search ||
|
|
215
|
+
parsed.hash ||
|
|
216
|
+
parsed.origin !== raw
|
|
217
|
+
) {
|
|
218
|
+
throw new TypeError("Telegram apiOrigin must be an exact HTTPS origin");
|
|
219
|
+
}
|
|
220
|
+
return parsed.origin;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function boundedInteger(value: number | undefined, fallback: number, min: number, max: number, name: string): number {
|
|
224
|
+
const resolved = value ?? fallback;
|
|
225
|
+
if (!Number.isSafeInteger(resolved) || resolved < min || resolved > max) {
|
|
226
|
+
throw new TypeError(`Telegram ${name} must be an integer between ${min} and ${max}`);
|
|
227
|
+
}
|
|
228
|
+
return resolved;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function scope(ownership: OwnershipScope): OwnershipScope {
|
|
232
|
+
return {
|
|
233
|
+
...(ownership.tenantId === undefined ? {} : { tenantId: ownership.tenantId }),
|
|
234
|
+
...(ownership.accountId === undefined ? {} : { accountId: ownership.accountId }),
|
|
235
|
+
...(ownership.userId === undefined ? {} : { userId: ownership.userId }),
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function receiverKey(connectionId: string): string {
|
|
240
|
+
return `${RECEIVER_LEASE_KEY_PREFIX}${connectionId}`;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function constantTimeEqual(expected: string, actual: string | null): boolean {
|
|
244
|
+
if (actual === null) return false;
|
|
245
|
+
const expectedHash = createHash("sha256").update(expected).digest();
|
|
246
|
+
const actualHash = createHash("sha256").update(actual).digest();
|
|
247
|
+
return timingSafeEqual(expectedHash, actualHash);
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
function validWebhookSecret(value: string): boolean {
|
|
251
|
+
return /^[A-Za-z0-9_-]{1,256}$/.test(value);
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
function chunkText(text: string): readonly string[] {
|
|
255
|
+
if (text.length === 0) return [];
|
|
256
|
+
const chunks: string[] = [];
|
|
257
|
+
let chunk = "";
|
|
258
|
+
for (const codePoint of text) {
|
|
259
|
+
if (chunk.length > 0 && chunk.length + codePoint.length > TELEGRAM_TEXT_CODE_UNITS) {
|
|
260
|
+
chunks.push(chunk);
|
|
261
|
+
chunk = "";
|
|
262
|
+
}
|
|
263
|
+
chunk += codePoint;
|
|
264
|
+
}
|
|
265
|
+
if (chunk.length) chunks.push(chunk);
|
|
266
|
+
return chunks;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/** A draft is one ephemeral preview: the newest part of the text, capped to the outbound budget. */
|
|
270
|
+
function draftText(text: string): string {
|
|
271
|
+
if (text.length <= TELEGRAM_TEXT_CODE_UNITS) return text;
|
|
272
|
+
let start = text.length - TELEGRAM_TEXT_CODE_UNITS;
|
|
273
|
+
// Never start on a low surrogate: that would split a pair and render as a replacement character.
|
|
274
|
+
const code = text.charCodeAt(start);
|
|
275
|
+
if (code >= 0xdc00 && code <= 0xdfff) start += 1;
|
|
276
|
+
return text.slice(start);
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
async function readJson(response: Response, maxBytes: number): Promise<unknown> {
|
|
280
|
+
const reader = response.body?.getReader();
|
|
281
|
+
if (reader === undefined) return undefined;
|
|
282
|
+
const chunks: Uint8Array[] = [];
|
|
283
|
+
let size = 0;
|
|
284
|
+
try {
|
|
285
|
+
for (;;) {
|
|
286
|
+
const next = await reader.read();
|
|
287
|
+
if (next.done) break;
|
|
288
|
+
size += next.value.byteLength;
|
|
289
|
+
if (size > maxBytes) {
|
|
290
|
+
await reader.cancel();
|
|
291
|
+
throw new TelegramApiError({ kind: "response" });
|
|
292
|
+
}
|
|
293
|
+
chunks.push(next.value);
|
|
294
|
+
}
|
|
295
|
+
} finally {
|
|
296
|
+
reader.releaseLock();
|
|
297
|
+
}
|
|
298
|
+
try {
|
|
299
|
+
return JSON.parse(Buffer.concat(chunks).toString("utf8")) as unknown;
|
|
300
|
+
} catch {
|
|
301
|
+
throw new TelegramApiError({ kind: "response" });
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
async function readRequestJson(request: Request, maxBytes: number): Promise<unknown> {
|
|
306
|
+
const reader = request.body?.getReader();
|
|
307
|
+
if (reader === undefined) throw new TypeError("missing body");
|
|
308
|
+
const chunks: Uint8Array[] = [];
|
|
309
|
+
let size = 0;
|
|
310
|
+
try {
|
|
311
|
+
for (;;) {
|
|
312
|
+
const next = await reader.read();
|
|
313
|
+
if (next.done) break;
|
|
314
|
+
size += next.value.byteLength;
|
|
315
|
+
if (size > maxBytes) {
|
|
316
|
+
await reader.cancel();
|
|
317
|
+
throw new RangeError("request too large");
|
|
318
|
+
}
|
|
319
|
+
chunks.push(next.value);
|
|
320
|
+
}
|
|
321
|
+
} finally {
|
|
322
|
+
reader.releaseLock();
|
|
323
|
+
}
|
|
324
|
+
return JSON.parse(Buffer.concat(chunks).toString("utf8")) as unknown;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
function retryAfter(payload: Record<string, unknown>): number | undefined {
|
|
328
|
+
const parameters = asRecord(payload.parameters);
|
|
329
|
+
const seconds = parameters === undefined ? undefined : asPositiveInteger(parameters.retry_after);
|
|
330
|
+
return seconds;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
function updateId(update: Record<string, unknown>): number | undefined {
|
|
334
|
+
const value = update.update_id;
|
|
335
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : undefined;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/** Bounded binary read; `RangeError` marks an oversize body before it is fully buffered. */
|
|
339
|
+
async function readBytes(response: Response, maxBytes: number): Promise<Uint8Array> {
|
|
340
|
+
const reader = response.body?.getReader();
|
|
341
|
+
if (reader === undefined) throw new RangeError("missing body");
|
|
342
|
+
const chunks: Uint8Array[] = [];
|
|
343
|
+
let size = 0;
|
|
344
|
+
try {
|
|
345
|
+
for (;;) {
|
|
346
|
+
const next = await reader.read();
|
|
347
|
+
if (next.done) break;
|
|
348
|
+
size += next.value.byteLength;
|
|
349
|
+
if (size > maxBytes) {
|
|
350
|
+
await reader.cancel();
|
|
351
|
+
throw new RangeError("attachment exceeds maxAttachmentBytes");
|
|
352
|
+
}
|
|
353
|
+
chunks.push(next.value);
|
|
354
|
+
}
|
|
355
|
+
} finally {
|
|
356
|
+
reader.releaseLock();
|
|
357
|
+
}
|
|
358
|
+
return Buffer.concat(chunks);
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
/** Telegram `file_path` values are relative `segments/file_name`; anything else is refused. */
|
|
362
|
+
function safeFilePath(value: string): boolean {
|
|
363
|
+
if (value.length === 0 || Buffer.byteLength(value, "utf8") > 256) return false;
|
|
364
|
+
const segments = value.split("/");
|
|
365
|
+
if (segments.length > 4) return false;
|
|
366
|
+
return segments.every((segment) => /^[A-Za-z0-9._-]+$/.test(segment) && segment !== "." && segment !== "..");
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
function boundedMeta(value: unknown): string | undefined {
|
|
370
|
+
return typeof value === "string" && value.length > 0 && Buffer.byteLength(value, "utf8") <= MAX_ATTACHMENT_META_BYTES ? value : undefined;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
type TelegramChatKind = "private" | "group" | "supergroup";
|
|
374
|
+
|
|
375
|
+
function chatKind(chat: Record<string, unknown> | undefined): TelegramChatKind | undefined {
|
|
376
|
+
const type = chat?.type;
|
|
377
|
+
return type === "private" || type === "group" || type === "supergroup" ? type : undefined;
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/** Group text is opt-in; `sender_chat` (channel/anonymous admin) is rejected before this is used. */
|
|
381
|
+
function admittedChatKind(chat: Record<string, unknown> | undefined, allowGroups: boolean): TelegramChatKind | undefined {
|
|
382
|
+
const kind = chatKind(chat);
|
|
383
|
+
if (kind === undefined || (kind !== "private" && !allowGroups)) return undefined;
|
|
384
|
+
return kind;
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/** Forum topics and group reply threads are isolated by `message_thread_id`; it is never model-selected. */
|
|
388
|
+
function messageThreadId(message: Record<string, unknown>): string | undefined {
|
|
389
|
+
return asPositiveInteger(message.message_thread_id)?.toString();
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/** Modality refs for one message: identifiers only, bounded, largest photo size only. */
|
|
393
|
+
function attachmentRefs(message: Record<string, unknown>): ChannelAttachmentRef[] | undefined {
|
|
394
|
+
const refs: ChannelAttachmentRef[] = [];
|
|
395
|
+
const photo = message.photo;
|
|
396
|
+
if (Array.isArray(photo)) {
|
|
397
|
+
let best: { readonly id: string; readonly size?: number } | undefined;
|
|
398
|
+
for (const raw of photo) {
|
|
399
|
+
const size = asRecord(raw);
|
|
400
|
+
const id = asId(size?.file_id);
|
|
401
|
+
if (id === undefined) continue;
|
|
402
|
+
const bytes = asPositiveInteger(size?.file_size);
|
|
403
|
+
if (best === undefined || (bytes ?? 0) > (best.size ?? 0)) best = { id, ...(bytes === undefined ? {} : { size: bytes }) };
|
|
404
|
+
}
|
|
405
|
+
if (best !== undefined) {
|
|
406
|
+
refs.push({ kind: "image", transportFileId: best.id, ...(best.size === undefined ? {} : { byteLength: best.size }) });
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
const voice = asRecord(message.voice);
|
|
410
|
+
const voiceId = asId(voice?.file_id);
|
|
411
|
+
if (voiceId !== undefined) {
|
|
412
|
+
const mimeType = boundedMeta(voice?.mime_type);
|
|
413
|
+
const byteLength = asPositiveInteger(voice?.file_size);
|
|
414
|
+
refs.push({
|
|
415
|
+
kind: "voice",
|
|
416
|
+
transportFileId: voiceId,
|
|
417
|
+
...(mimeType === undefined ? {} : { mimeType }),
|
|
418
|
+
...(byteLength === undefined ? {} : { byteLength }),
|
|
419
|
+
});
|
|
420
|
+
}
|
|
421
|
+
const document = asRecord(message.document);
|
|
422
|
+
const documentId = asId(document?.file_id);
|
|
423
|
+
if (documentId !== undefined) {
|
|
424
|
+
const mimeType = boundedMeta(document?.mime_type);
|
|
425
|
+
const byteLength = asPositiveInteger(document?.file_size);
|
|
426
|
+
const fileName = boundedMeta(document?.file_name);
|
|
427
|
+
refs.push({
|
|
428
|
+
kind: "document",
|
|
429
|
+
transportFileId: documentId,
|
|
430
|
+
...(mimeType === undefined ? {} : { mimeType }),
|
|
431
|
+
...(byteLength === undefined ? {} : { byteLength }),
|
|
432
|
+
...(fileName === undefined ? {} : { fileName }),
|
|
433
|
+
});
|
|
434
|
+
}
|
|
435
|
+
return refs.length === 0 ? undefined : refs.slice(0, MAX_ATTACHMENT_REFS);
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
function parseMessageUpdate(connectionId: string, update: Record<string, unknown>, allowGroups: boolean): ChannelInboundEvent | undefined {
|
|
439
|
+
const id = updateId(update);
|
|
440
|
+
const message = asRecord(update.message);
|
|
441
|
+
if (id === undefined || message === undefined) return undefined;
|
|
442
|
+
const chat = asRecord(message.chat);
|
|
443
|
+
const from = asRecord(message.from);
|
|
444
|
+
const kind = admittedChatKind(chat, allowGroups);
|
|
445
|
+
if (kind === undefined || from === undefined || from.is_bot === true || asRecord(message.sender_chat) !== undefined) {
|
|
446
|
+
return undefined;
|
|
447
|
+
}
|
|
448
|
+
const chatId = asChatId(chat?.id);
|
|
449
|
+
const actorId = asId(from.id);
|
|
450
|
+
if (chatId === undefined || actorId === undefined) return undefined;
|
|
451
|
+
const text = typeof message.text === "string" ? message.text : typeof message.caption === "string" ? message.caption : "";
|
|
452
|
+
const attachments = attachmentRefs(message);
|
|
453
|
+
if (text.length === 0 && attachments === undefined) return undefined;
|
|
454
|
+
const threadId = messageThreadId(message);
|
|
455
|
+
const forwarded = message.forward_origin !== undefined || message.forward_date !== undefined;
|
|
456
|
+
return {
|
|
457
|
+
connectionId,
|
|
458
|
+
externalConversationId: chatId,
|
|
459
|
+
externalActorId: actorId,
|
|
460
|
+
eventId: String(id),
|
|
461
|
+
text,
|
|
462
|
+
...(attachments === undefined ? {} : { attachments }),
|
|
463
|
+
...(threadId === undefined ? {} : { threadId }),
|
|
464
|
+
receivedAt: new Date().toISOString(),
|
|
465
|
+
claims: {
|
|
466
|
+
platform: "telegram",
|
|
467
|
+
chatType: kind,
|
|
468
|
+
...(chat?.is_forum === true ? { isForum: true } : {}),
|
|
469
|
+
...(forwarded ? { forwarded: true } : {}),
|
|
470
|
+
},
|
|
471
|
+
};
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
function callbackId(update: Record<string, unknown>): string | undefined {
|
|
475
|
+
const callback = asRecord(update.callback_query);
|
|
476
|
+
if (callback === undefined || typeof callback.id !== "string" || callback.id.length === 0) return undefined;
|
|
477
|
+
if (typeof callback.data === "string" && Buffer.byteLength(callback.data, "utf8") > 64) return undefined;
|
|
478
|
+
return callback.id;
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
function parseCallbackUpdate(connectionId: string, update: Record<string, unknown>, allowGroups: boolean): ChannelInboundEvent | undefined {
|
|
482
|
+
const id = updateId(update);
|
|
483
|
+
const callback = asRecord(update.callback_query);
|
|
484
|
+
const message = callback === undefined ? undefined : asRecord(callback.message);
|
|
485
|
+
const chat = message === undefined ? undefined : asRecord(message.chat);
|
|
486
|
+
const from = callback === undefined ? undefined : asRecord(callback.from);
|
|
487
|
+
const data = callback?.data;
|
|
488
|
+
const uiMatch = typeof data === "string" ? /^q:([A-Za-z0-9_-]{43}):([0-7])$/.exec(data) : null;
|
|
489
|
+
const match = typeof data === "string" ? /^p:([ad]):([A-Za-z0-9_-]{32,64})$/.exec(data) : null;
|
|
490
|
+
const kind = admittedChatKind(chat, allowGroups);
|
|
491
|
+
if (
|
|
492
|
+
id === undefined ||
|
|
493
|
+
callback === undefined ||
|
|
494
|
+
kind === undefined ||
|
|
495
|
+
from === undefined ||
|
|
496
|
+
from.is_bot === true ||
|
|
497
|
+
(match === null && uiMatch === null)
|
|
498
|
+
) {
|
|
499
|
+
return undefined;
|
|
500
|
+
}
|
|
501
|
+
const chatId = asChatId(chat?.id);
|
|
502
|
+
const actorId = asId(from.id);
|
|
503
|
+
const token = uiMatch?.[1] ?? match?.[2];
|
|
504
|
+
if (chatId === undefined || actorId === undefined || token === undefined) return undefined;
|
|
505
|
+
const threadId = messageThreadId(message ?? {});
|
|
506
|
+
return {
|
|
507
|
+
connectionId,
|
|
508
|
+
externalConversationId: chatId,
|
|
509
|
+
externalActorId: actorId,
|
|
510
|
+
eventId: String(id),
|
|
511
|
+
text: uiMatch ? `/answer ${token} ${uiMatch[2]}` : "",
|
|
512
|
+
...(!uiMatch ? { approval: { token, outcome: match?.[1] === "a" ? ("allow_once" as const) : ("reject_once" as const) } } : {}),
|
|
513
|
+
...(threadId === undefined ? {} : { threadId }),
|
|
514
|
+
receivedAt: new Date().toISOString(),
|
|
515
|
+
claims: { platform: "telegram", chatType: kind, control: "approval" },
|
|
516
|
+
};
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
function inlineKeyboard(controls: readonly ChannelReplyControl[] | undefined) {
|
|
520
|
+
if (controls === undefined) return undefined;
|
|
521
|
+
if (controls.length === 0 || controls.length > 8) return null;
|
|
522
|
+
const buttons: Array<{ text: string; callback_data: string }> = [];
|
|
523
|
+
for (const control of controls) {
|
|
524
|
+
if (
|
|
525
|
+
typeof control?.label !== "string" ||
|
|
526
|
+
typeof control.value !== "string" ||
|
|
527
|
+
control.label.length === 0 ||
|
|
528
|
+
Buffer.byteLength(control.label, "utf8") > 64 ||
|
|
529
|
+
Buffer.byteLength(control.value, "utf8") > 64
|
|
530
|
+
) {
|
|
531
|
+
return null;
|
|
532
|
+
}
|
|
533
|
+
buttons.push({ text: control.label, callback_data: control.value });
|
|
534
|
+
}
|
|
535
|
+
return { inline_keyboard: [buttons] };
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
function knownSendFailure(error: unknown): string {
|
|
539
|
+
if (!(error instanceof TelegramApiError)) return "telegram_api_error";
|
|
540
|
+
if (error.status === 401) return "telegram_unauthorized";
|
|
541
|
+
if (error.status === 403) return "telegram_forbidden";
|
|
542
|
+
if (error.status === 429) return "telegram_rate_limited";
|
|
543
|
+
if (error.kind === "credential") return "telegram_credential";
|
|
544
|
+
return "telegram_api_error";
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
function delay(ms: number, signal: AbortSignal): Promise<void> {
|
|
548
|
+
return new Promise((resolve) => {
|
|
549
|
+
if (signal.aborted) {
|
|
550
|
+
resolve();
|
|
551
|
+
return;
|
|
552
|
+
}
|
|
553
|
+
let timer: ReturnType<typeof setTimeout>;
|
|
554
|
+
function abort() {
|
|
555
|
+
clearTimeout(timer);
|
|
556
|
+
signal.removeEventListener("abort", abort);
|
|
557
|
+
resolve();
|
|
558
|
+
}
|
|
559
|
+
function done() {
|
|
560
|
+
signal.removeEventListener("abort", abort);
|
|
561
|
+
resolve();
|
|
562
|
+
}
|
|
563
|
+
timer = setTimeout(done, ms);
|
|
564
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
565
|
+
});
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
interface TelegramApi {
|
|
569
|
+
call<T>(method: string, body: Record<string, unknown>, signal: AbortSignal): Promise<T>;
|
|
570
|
+
upload<T>(method: string, form: FormData, signal: AbortSignal): Promise<T>;
|
|
571
|
+
/** Bounded GET of `api.telegram.org/file/bot<token>/<path>`; the token never leaves this module. */
|
|
572
|
+
download(filePath: string, maxBytes: number, signal: AbortSignal): Promise<Uint8Array | undefined>;
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
function telegramApi(options: {
|
|
576
|
+
readonly botToken: ChannelSecretSource;
|
|
577
|
+
readonly apiOrigin?: string;
|
|
578
|
+
readonly fetch?: typeof globalThis.fetch;
|
|
579
|
+
readonly maxResponseBytes: number;
|
|
580
|
+
}): TelegramApi {
|
|
581
|
+
const origin = apiOrigin(options.apiOrigin);
|
|
582
|
+
const fetcher = options.fetch ?? globalThis.fetch;
|
|
583
|
+
|
|
584
|
+
async function credential(): Promise<string> {
|
|
585
|
+
const token = await options.botToken();
|
|
586
|
+
if (!token || Buffer.byteLength(token, "utf8") > 1024) throw new TelegramApiError({ kind: "credential" });
|
|
587
|
+
return token;
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
async function perform(method: string, init: RequestInit, signal: AbortSignal): Promise<unknown> {
|
|
591
|
+
const token = await credential();
|
|
592
|
+
let response: Response;
|
|
593
|
+
try {
|
|
594
|
+
response = await fetcher(`${origin}/bot${token}/${method}`, { ...init, redirect: "error", signal });
|
|
595
|
+
} catch {
|
|
596
|
+
throw new TelegramApiError({ kind: "network" });
|
|
597
|
+
}
|
|
598
|
+
const payload = asRecord(await readJson(response, options.maxResponseBytes));
|
|
599
|
+
if (!response.ok || payload?.ok !== true) {
|
|
600
|
+
throw new TelegramApiError({
|
|
601
|
+
kind: "api",
|
|
602
|
+
status: typeof payload?.error_code === "number" ? payload.error_code : response.status,
|
|
603
|
+
...(payload === undefined ? {} : { retryAfter: retryAfter(payload) }),
|
|
604
|
+
});
|
|
605
|
+
}
|
|
606
|
+
return payload.result;
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
return {
|
|
610
|
+
call<T>(method: string, body: Record<string, unknown>, signal: AbortSignal): Promise<T> {
|
|
611
|
+
return perform(
|
|
612
|
+
method,
|
|
613
|
+
{ method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) },
|
|
614
|
+
signal,
|
|
615
|
+
) as Promise<T>;
|
|
616
|
+
},
|
|
617
|
+
upload<T>(method: string, form: FormData, signal: AbortSignal): Promise<T> {
|
|
618
|
+
return perform(method, { method: "POST", body: form }, signal) as Promise<T>;
|
|
619
|
+
},
|
|
620
|
+
async download(filePath, maxBytes, signal) {
|
|
621
|
+
const token = await credential();
|
|
622
|
+
let response: Response;
|
|
623
|
+
try {
|
|
624
|
+
response = await fetcher(`${origin}/file/bot${token}/${filePath}`, { method: "GET", redirect: "error", signal });
|
|
625
|
+
} catch {
|
|
626
|
+
return undefined;
|
|
627
|
+
}
|
|
628
|
+
if (!response.ok) return undefined;
|
|
629
|
+
const declared = Number(response.headers.get("content-length"));
|
|
630
|
+
if (Number.isFinite(declared) && declared > maxBytes) return undefined;
|
|
631
|
+
try {
|
|
632
|
+
return await readBytes(response, maxBytes);
|
|
633
|
+
} catch {
|
|
634
|
+
return undefined;
|
|
635
|
+
}
|
|
636
|
+
},
|
|
637
|
+
};
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
async function releaseReceiver(
|
|
641
|
+
leases: LeaseStore,
|
|
642
|
+
ownership: OwnershipScope,
|
|
643
|
+
connectionId: string,
|
|
644
|
+
ownerId: string,
|
|
645
|
+
lease: LeaseRecord | undefined,
|
|
646
|
+
) {
|
|
647
|
+
if (lease === undefined) return;
|
|
648
|
+
try {
|
|
649
|
+
await leases.releaseLease({
|
|
650
|
+
namespace: RECEIVER_LEASE_NAMESPACE,
|
|
651
|
+
key: receiverKey(connectionId),
|
|
652
|
+
...scope(ownership),
|
|
653
|
+
ownerId,
|
|
654
|
+
token: lease.token,
|
|
655
|
+
});
|
|
656
|
+
} catch {
|
|
657
|
+
// A lease expiry/release failure cannot make this process the receiver again.
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
interface TelegramInboundMediaConfig {
|
|
662
|
+
readonly connectionId: string;
|
|
663
|
+
readonly allowGroups: boolean;
|
|
664
|
+
readonly api: TelegramApi;
|
|
665
|
+
readonly maxAttachmentBytes: number;
|
|
666
|
+
readonly transcribe?: TelegramAdapterOptions["transcribe"];
|
|
667
|
+
readonly extractDocumentText?: TelegramAdapterOptions["extractDocumentText"];
|
|
668
|
+
readonly isStopped?: () => boolean;
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
/**
|
|
672
|
+
* Shared inbound media pipeline for both ingress paths (poller and mounted webhook): parse the
|
|
673
|
+
* update, resolve voice/document text through host hooks, and download one bounded body per ref.
|
|
674
|
+
* Bytes never leave this scope — they are not put on the event, journaled, logged or written to disk.
|
|
675
|
+
*/
|
|
676
|
+
function createInboundMedia(config: TelegramInboundMediaConfig) {
|
|
677
|
+
function validAttachmentRef(ref: ChannelAttachmentRef | undefined): ref is ChannelAttachmentRef {
|
|
678
|
+
if (ref === null || typeof ref !== "object") return false;
|
|
679
|
+
if (ref.kind !== "image" && ref.kind !== "document" && ref.kind !== "voice") return false;
|
|
680
|
+
if (typeof ref.transportFileId !== "string" || ref.transportFileId.length === 0) return false;
|
|
681
|
+
if (Buffer.byteLength(ref.transportFileId, "utf8") > 256) return false;
|
|
682
|
+
if (ref.mimeType !== undefined && boundedMeta(ref.mimeType) === undefined) return false;
|
|
683
|
+
if (ref.fileName !== undefined && boundedMeta(ref.fileName) === undefined) return false;
|
|
684
|
+
return ref.byteLength === undefined || (Number.isSafeInteger(ref.byteLength) && ref.byteLength >= 0);
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
/** One `getFile` plus one bounded download for a ref that came from a parsed update. */
|
|
688
|
+
async function fetchAttachment(ref: ChannelAttachmentRef, signal: AbortSignal): Promise<Uint8Array | undefined> {
|
|
689
|
+
if (config.isStopped?.() === true || !validAttachmentRef(ref)) return undefined;
|
|
690
|
+
try {
|
|
691
|
+
const file = asRecord(await config.api.call<unknown>("getFile", { file_id: ref.transportFileId }, signal));
|
|
692
|
+
const path = typeof file?.file_path === "string" ? file.file_path : undefined;
|
|
693
|
+
if (path === undefined || !safeFilePath(path)) return undefined;
|
|
694
|
+
const declared = asPositiveInteger(file?.file_size) ?? ref.byteLength;
|
|
695
|
+
if (declared !== undefined && declared > config.maxAttachmentBytes) return undefined;
|
|
696
|
+
return await config.api.download(path, config.maxAttachmentBytes, signal);
|
|
697
|
+
} catch {
|
|
698
|
+
// Fail closed: oversize, network, credential and API failures all yield no bytes.
|
|
699
|
+
return undefined;
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
/** Voice/document become ordinary turn text; images stay refs for the runtime's model-input gate. */
|
|
704
|
+
async function attachmentText(ref: ChannelAttachmentRef, signal: AbortSignal): Promise<string | undefined> {
|
|
705
|
+
const hook = ref.kind === "voice" ? config.transcribe : ref.kind === "document" ? config.extractDocumentText : undefined;
|
|
706
|
+
if (hook === undefined) return undefined;
|
|
707
|
+
const bytes = await fetchAttachment(ref, signal);
|
|
708
|
+
if (bytes === undefined) return undefined;
|
|
709
|
+
try {
|
|
710
|
+
const text = await hook(bytes, ref.mimeType, signal);
|
|
711
|
+
return typeof text === "string" && text.trim().length > 0 ? text : undefined;
|
|
712
|
+
} catch {
|
|
713
|
+
return undefined;
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
/** Parse one update and resolve its attachment text before admission; bytes never leave this scope. */
|
|
718
|
+
async function prepareInboundEvent(update: Record<string, unknown>, signal: AbortSignal): Promise<ChannelInboundEvent | undefined> {
|
|
719
|
+
const event =
|
|
720
|
+
parseMessageUpdate(config.connectionId, update, config.allowGroups) ??
|
|
721
|
+
parseCallbackUpdate(config.connectionId, update, config.allowGroups);
|
|
722
|
+
const refs = event?.attachments;
|
|
723
|
+
if (event === undefined || refs === undefined) return event;
|
|
724
|
+
const parts = [event.text];
|
|
725
|
+
for (const ref of refs) {
|
|
726
|
+
const text = await attachmentText(ref, signal);
|
|
727
|
+
if (text !== undefined) parts.push(text);
|
|
728
|
+
}
|
|
729
|
+
const text = parts.filter((part) => part.length > 0).join("\n\n");
|
|
730
|
+
return text === event.text ? event : { ...event, text };
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
return { fetchAttachment, prepareInboundEvent };
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
/**
|
|
737
|
+
* Creates an explicit long-polling adapter. It refuses to start when Telegram reports an active
|
|
738
|
+
* webhook and holds a service-owned lease for its full receive loop.
|
|
739
|
+
*/
|
|
740
|
+
export function createTelegramAdapter(options: TelegramAdapterOptions): TelegramAdapter {
|
|
741
|
+
if (
|
|
742
|
+
typeof options.connectionId !== "string" ||
|
|
743
|
+
options.connectionId.length === 0 ||
|
|
744
|
+
Buffer.byteLength(options.connectionId, "utf8") > 256
|
|
745
|
+
) {
|
|
746
|
+
throw new TypeError("Telegram connectionId must be a bounded non-empty string");
|
|
747
|
+
}
|
|
748
|
+
const pollTimeoutSeconds = boundedInteger(options.pollTimeoutSeconds, DEFAULT_POLL_TIMEOUT_SECONDS, 1, 50, "pollTimeoutSeconds");
|
|
749
|
+
const pollLimit = boundedInteger(options.pollLimit, DEFAULT_POLL_LIMIT, 1, 100, "pollLimit");
|
|
750
|
+
const leaseTtlMs = boundedInteger(options.leaseTtlMs, DEFAULT_LEASE_TTL_MS, pollTimeoutSeconds * 1000 + 10_000, 300_000, "leaseTtlMs");
|
|
751
|
+
const maxResponseBytes = boundedInteger(
|
|
752
|
+
options.maxResponseBytes,
|
|
753
|
+
DEFAULT_MAX_REQUEST_BYTES,
|
|
754
|
+
1024,
|
|
755
|
+
HARD_MAX_REQUEST_BYTES,
|
|
756
|
+
"maxResponseBytes",
|
|
757
|
+
);
|
|
758
|
+
const maxAttachmentBytes = boundedInteger(
|
|
759
|
+
options.maxAttachmentBytes,
|
|
760
|
+
DEFAULT_CHANNEL_LIMITS.maxAttachmentBytes,
|
|
761
|
+
1,
|
|
762
|
+
HARD_CHANNEL_LIMITS.maxAttachmentBytes,
|
|
763
|
+
"maxAttachmentBytes",
|
|
764
|
+
);
|
|
765
|
+
const api = telegramApi({ ...options, maxResponseBytes });
|
|
766
|
+
const allowGroups = options.allowGroups === true;
|
|
767
|
+
const sendDrafts = options.sendDrafts === true;
|
|
768
|
+
const media = createInboundMedia({
|
|
769
|
+
connectionId: options.connectionId,
|
|
770
|
+
allowGroups,
|
|
771
|
+
api,
|
|
772
|
+
maxAttachmentBytes,
|
|
773
|
+
...(options.transcribe === undefined ? {} : { transcribe: options.transcribe }),
|
|
774
|
+
...(options.extractDocumentText === undefined ? {} : { extractDocumentText: options.extractDocumentText }),
|
|
775
|
+
isStopped: () => stopped,
|
|
776
|
+
});
|
|
777
|
+
const state = createChannelStateStore({ checkpoints: options.checkpoints, maxJournalRecordBytes: 1024 });
|
|
778
|
+
const ownerId = `telegram-poll-${randomUUID()}`;
|
|
779
|
+
let controller: AbortController | undefined;
|
|
780
|
+
let polling: Promise<void> | undefined;
|
|
781
|
+
let lease: LeaseRecord | undefined;
|
|
782
|
+
let stopped = false;
|
|
783
|
+
let pendingDraft: { readonly chatId: string; readonly threadId?: string; readonly text: string } | undefined;
|
|
784
|
+
let draftsInFlight: Promise<void> | undefined;
|
|
785
|
+
|
|
786
|
+
/** One request in flight, latest partial wins: a token stream never floods the Bot API. */
|
|
787
|
+
function flushDrafts(): void {
|
|
788
|
+
if (draftsInFlight !== undefined) return;
|
|
789
|
+
draftsInFlight = (async () => {
|
|
790
|
+
try {
|
|
791
|
+
for (;;) {
|
|
792
|
+
const draft = pendingDraft;
|
|
793
|
+
if (draft === undefined || stopped) return;
|
|
794
|
+
pendingDraft = undefined;
|
|
795
|
+
try {
|
|
796
|
+
await api.call<Record<string, unknown>>(
|
|
797
|
+
"sendMessageDraft",
|
|
798
|
+
{
|
|
799
|
+
chat_id: draft.chatId,
|
|
800
|
+
draft_id: DRAFT_ID,
|
|
801
|
+
text: draft.text,
|
|
802
|
+
...(draft.threadId === undefined ? {} : { message_thread_id: draft.threadId }),
|
|
803
|
+
},
|
|
804
|
+
controller?.signal ?? new AbortController().signal,
|
|
805
|
+
);
|
|
806
|
+
} catch {
|
|
807
|
+
// Ephemeral preview only: a failed draft never affects the turn or its terminal send.
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
} finally {
|
|
811
|
+
draftsInFlight = undefined;
|
|
812
|
+
}
|
|
813
|
+
})();
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
async function renew(signal: AbortSignal): Promise<boolean> {
|
|
817
|
+
if (lease === undefined) return false;
|
|
818
|
+
try {
|
|
819
|
+
const renewed = await options.leases.renewLease({
|
|
820
|
+
namespace: RECEIVER_LEASE_NAMESPACE,
|
|
821
|
+
key: receiverKey(options.connectionId),
|
|
822
|
+
...scope(options.cursorOwnership),
|
|
823
|
+
ownerId,
|
|
824
|
+
token: lease.token,
|
|
825
|
+
ttlMs: leaseTtlMs,
|
|
826
|
+
signal,
|
|
827
|
+
});
|
|
828
|
+
if (renewed === null) return false;
|
|
829
|
+
lease = renewed;
|
|
830
|
+
return true;
|
|
831
|
+
} catch {
|
|
832
|
+
return false;
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
async function sendCall(body: Record<string, unknown>, signal: AbortSignal): Promise<Record<string, unknown>> {
|
|
837
|
+
let last: TelegramApiError | undefined;
|
|
838
|
+
for (let attempt = 0; attempt < MAX_SEND_ATTEMPTS; attempt += 1) {
|
|
839
|
+
try {
|
|
840
|
+
return await api.call<Record<string, unknown>>("sendMessage", body, signal);
|
|
841
|
+
} catch (error) {
|
|
842
|
+
if (!(error instanceof TelegramApiError)) throw error;
|
|
843
|
+
last = error;
|
|
844
|
+
if (error.retryAfter === undefined || attempt + 1 === MAX_SEND_ATTEMPTS) throw error;
|
|
845
|
+
await delay(error.retryAfter * 1000, signal);
|
|
846
|
+
}
|
|
847
|
+
}
|
|
848
|
+
throw last ?? new TelegramApiError({ kind: "api" });
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
/**
|
|
852
|
+
* Optional host synthesis for `final` replies: a voice note next to the text, never instead of
|
|
853
|
+
* it. Best effort — synthesis or upload failures are swallowed so an already-delivered text
|
|
854
|
+
* message is never reported as failed, and nothing here can be steered by model output.
|
|
855
|
+
*/
|
|
856
|
+
async function sendVoice(reply: ChannelReply, signal: AbortSignal): Promise<void> {
|
|
857
|
+
const synthesize = options.synthesize;
|
|
858
|
+
if (synthesize === undefined || reply.kind !== "final" || stopped) return;
|
|
859
|
+
const text = reply.text.trim();
|
|
860
|
+
if (text.length === 0) return;
|
|
861
|
+
try {
|
|
862
|
+
const audio = await synthesize(text, signal);
|
|
863
|
+
const format =
|
|
864
|
+
typeof audio?.format === "string"
|
|
865
|
+
? audio.format
|
|
866
|
+
.toLowerCase()
|
|
867
|
+
.replace(/^audio\//, "")
|
|
868
|
+
.replace(/^\./, "")
|
|
869
|
+
: "";
|
|
870
|
+
const mimeType = VOICE_FORMATS.get(format);
|
|
871
|
+
if (mimeType === undefined || !(audio?.audio instanceof Uint8Array) || audio.audio.byteLength === 0) return;
|
|
872
|
+
const copy = new Uint8Array(audio.audio.byteLength);
|
|
873
|
+
copy.set(audio.audio);
|
|
874
|
+
const form = new FormData();
|
|
875
|
+
form.append("chat_id", reply.externalConversationId);
|
|
876
|
+
if (typeof reply.threadId === "string" && reply.threadId.length > 0) form.append("message_thread_id", reply.threadId);
|
|
877
|
+
form.append("voice", new Blob([copy], { type: mimeType }), `reply.${format === "oga" ? "ogg" : format}`);
|
|
878
|
+
await api.upload<Record<string, unknown>>("sendVoice", form, signal);
|
|
879
|
+
} catch {
|
|
880
|
+
// Voice is additive: the text reply already settled.
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
|
|
884
|
+
async function answerCallbackQuery(id: string, signal: AbortSignal): Promise<void> {
|
|
885
|
+
try {
|
|
886
|
+
await api.call<boolean>("answerCallbackQuery", { callback_query_id: id }, signal);
|
|
887
|
+
} catch (error) {
|
|
888
|
+
if (error instanceof TelegramApiError && error.retryAfter !== undefined) {
|
|
889
|
+
try {
|
|
890
|
+
await delay(error.retryAfter * 1000, signal);
|
|
891
|
+
await api.call<boolean>("answerCallbackQuery", { callback_query_id: id }, signal);
|
|
892
|
+
} catch {
|
|
893
|
+
// Telegram requires a callback acknowledgement even when control handling later fails closed.
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
async function poll(receive: ChannelReceive, signal: AbortSignal): Promise<void> {
|
|
900
|
+
const cursor = await state.loadCursor({ ownership: options.cursorOwnership, connectionId: options.connectionId });
|
|
901
|
+
let offset = cursor?.record.lastEventId === undefined ? undefined : Number(cursor.record.lastEventId) + 1;
|
|
902
|
+
if (offset !== undefined && (!Number.isSafeInteger(offset) || offset < 0)) offset = undefined;
|
|
903
|
+
for (;;) {
|
|
904
|
+
if (signal.aborted) return;
|
|
905
|
+
let updates: unknown;
|
|
906
|
+
try {
|
|
907
|
+
updates = await api.call<unknown>(
|
|
908
|
+
"getUpdates",
|
|
909
|
+
{
|
|
910
|
+
...(offset === undefined ? {} : { offset }),
|
|
911
|
+
timeout: pollTimeoutSeconds,
|
|
912
|
+
limit: pollLimit,
|
|
913
|
+
allowed_updates: ["message", "callback_query"],
|
|
914
|
+
},
|
|
915
|
+
signal,
|
|
916
|
+
);
|
|
917
|
+
} catch (error) {
|
|
918
|
+
if (signal.aborted) return;
|
|
919
|
+
if (error instanceof TelegramApiError && error.retryAfter !== undefined) {
|
|
920
|
+
await delay(error.retryAfter * 1000, signal);
|
|
921
|
+
} else if (error instanceof TelegramApiError && (error.status === 401 || error.status === 403 || error.kind === "credential")) {
|
|
922
|
+
return;
|
|
923
|
+
} else {
|
|
924
|
+
await delay(1000, signal);
|
|
925
|
+
}
|
|
926
|
+
continue;
|
|
927
|
+
}
|
|
928
|
+
if (!(await renew(signal))) return;
|
|
929
|
+
if (!Array.isArray(updates)) {
|
|
930
|
+
await delay(1000, signal);
|
|
931
|
+
continue;
|
|
932
|
+
}
|
|
933
|
+
const ordered: Array<{ update: Record<string, unknown>; id: number }> = [];
|
|
934
|
+
for (const raw of updates) {
|
|
935
|
+
const update = asRecord(raw);
|
|
936
|
+
const id = update === undefined ? undefined : updateId(update);
|
|
937
|
+
if (update !== undefined && id !== undefined) ordered.push({ update, id });
|
|
938
|
+
}
|
|
939
|
+
ordered.sort((a, b) => a.id - b.id);
|
|
940
|
+
try {
|
|
941
|
+
for (const { update, id } of ordered) {
|
|
942
|
+
if (offset !== undefined && id < offset) continue;
|
|
943
|
+
const callback = callbackId(update);
|
|
944
|
+
if (callback !== undefined) await answerCallbackQuery(callback, signal);
|
|
945
|
+
const event = await media.prepareInboundEvent(update, signal);
|
|
946
|
+
if (event !== undefined) {
|
|
947
|
+
const admission = await receive(event);
|
|
948
|
+
if (retryableAdmission(admission)) throw new TelegramApiError({ kind: "api" });
|
|
949
|
+
}
|
|
950
|
+
// A non-text/unsupported update is a final disposition. Advancing only happens after
|
|
951
|
+
// its callback acknowledgement or `receive` durable admission has settled.
|
|
952
|
+
await state.advanceCursor({ ownership: options.cursorOwnership, connectionId: options.connectionId }, String(id));
|
|
953
|
+
offset = id + 1;
|
|
954
|
+
}
|
|
955
|
+
} catch {
|
|
956
|
+
if (!signal.aborted) await delay(1000, signal);
|
|
957
|
+
}
|
|
958
|
+
}
|
|
959
|
+
}
|
|
960
|
+
|
|
961
|
+
return {
|
|
962
|
+
connectionId: options.connectionId,
|
|
963
|
+
capabilities: { acknowledgement: "telegram_offset", controls: "callback", maxTextCodeUnits: TELEGRAM_TEXT_CODE_UNITS },
|
|
964
|
+
async start(receive) {
|
|
965
|
+
if (stopped) throw new Error("Telegram adapter is stopped");
|
|
966
|
+
if (polling !== undefined) throw new Error("Telegram adapter is already started");
|
|
967
|
+
controller = new AbortController();
|
|
968
|
+
try {
|
|
969
|
+
const acquired = await options.leases.tryAcquireLease({
|
|
970
|
+
namespace: RECEIVER_LEASE_NAMESPACE,
|
|
971
|
+
key: receiverKey(options.connectionId),
|
|
972
|
+
...scope(options.cursorOwnership),
|
|
973
|
+
ownerId,
|
|
974
|
+
ttlMs: leaseTtlMs,
|
|
975
|
+
signal: controller.signal,
|
|
976
|
+
});
|
|
977
|
+
if (acquired === null) throw new Error("Telegram receiver is already active");
|
|
978
|
+
lease = acquired;
|
|
979
|
+
await api.call<Record<string, unknown>>("getMe", {}, controller.signal);
|
|
980
|
+
const webhook = asRecord(await api.call<unknown>("getWebhookInfo", {}, controller.signal));
|
|
981
|
+
if (typeof webhook?.url === "string" && webhook.url.length > 0) throw new Error("Telegram webhook is active; polling is refused");
|
|
982
|
+
polling = poll(receive, controller.signal)
|
|
983
|
+
.catch(() => undefined)
|
|
984
|
+
.finally(async () => {
|
|
985
|
+
await releaseReceiver(options.leases, options.cursorOwnership, options.connectionId, ownerId, lease);
|
|
986
|
+
lease = undefined;
|
|
987
|
+
});
|
|
988
|
+
} catch (error) {
|
|
989
|
+
await releaseReceiver(options.leases, options.cursorOwnership, options.connectionId, ownerId, lease);
|
|
990
|
+
lease = undefined;
|
|
991
|
+
controller = undefined;
|
|
992
|
+
throw error instanceof TelegramApiError ? new Error("Telegram adapter start failed") : error;
|
|
993
|
+
}
|
|
994
|
+
},
|
|
995
|
+
async send(reply) {
|
|
996
|
+
if (
|
|
997
|
+
reply.connectionId !== options.connectionId ||
|
|
998
|
+
typeof reply.externalConversationId !== "string" ||
|
|
999
|
+
reply.externalConversationId.length === 0
|
|
1000
|
+
) {
|
|
1001
|
+
return { delivered: false, reason: "invalid_destination" };
|
|
1002
|
+
}
|
|
1003
|
+
const chunks = chunkText(reply.text);
|
|
1004
|
+
if (chunks.length === 0) return { delivered: false, reason: "empty_reply" };
|
|
1005
|
+
const keyboard = inlineKeyboard(reply.controls);
|
|
1006
|
+
if (keyboard === null) return { delivered: false, reason: "invalid_controls" };
|
|
1007
|
+
const signal = controller?.signal ?? new AbortController().signal;
|
|
1008
|
+
let messageId: string | undefined;
|
|
1009
|
+
let sent = false;
|
|
1010
|
+
try {
|
|
1011
|
+
for (const [index, text] of chunks.entries()) {
|
|
1012
|
+
const result = await sendCall(
|
|
1013
|
+
{
|
|
1014
|
+
chat_id: reply.externalConversationId,
|
|
1015
|
+
text,
|
|
1016
|
+
...(typeof reply.threadId === "string" && reply.threadId.length > 0 ? { message_thread_id: reply.threadId } : {}),
|
|
1017
|
+
...(index + 1 === chunks.length && keyboard !== undefined ? { reply_markup: keyboard } : {}),
|
|
1018
|
+
},
|
|
1019
|
+
signal,
|
|
1020
|
+
);
|
|
1021
|
+
const id = asId(asRecord(result)?.message_id);
|
|
1022
|
+
if (id !== undefined) messageId = id;
|
|
1023
|
+
sent = true;
|
|
1024
|
+
}
|
|
1025
|
+
await sendVoice(reply, signal);
|
|
1026
|
+
return { delivered: true, ...(messageId === undefined ? {} : { messageId }) };
|
|
1027
|
+
} catch (error) {
|
|
1028
|
+
// A network error after any chunk (or before its response) cannot prove non-delivery.
|
|
1029
|
+
if (sent || !(error instanceof TelegramApiError) || error.kind === "network") throw new TelegramDeliveryUnknownError();
|
|
1030
|
+
return { delivered: false, reason: knownSendFailure(error) };
|
|
1031
|
+
}
|
|
1032
|
+
},
|
|
1033
|
+
async stop() {
|
|
1034
|
+
stopped = true;
|
|
1035
|
+
controller?.abort(new Error("Telegram adapter stopped"));
|
|
1036
|
+
await polling;
|
|
1037
|
+
await releaseReceiver(options.leases, options.cursorOwnership, options.connectionId, ownerId, lease);
|
|
1038
|
+
lease = undefined;
|
|
1039
|
+
},
|
|
1040
|
+
sendDraft(delta) {
|
|
1041
|
+
if (!sendDrafts || stopped) return;
|
|
1042
|
+
if (delta.connectionId !== options.connectionId) return;
|
|
1043
|
+
// Bot API has no group drafts: group/supergroup chat ids are negative, private ids are not.
|
|
1044
|
+
if (delta.externalConversationId.startsWith("-")) return;
|
|
1045
|
+
const text = draftText(delta.text);
|
|
1046
|
+
if (text.length === 0) return;
|
|
1047
|
+
pendingDraft = {
|
|
1048
|
+
chatId: delta.externalConversationId,
|
|
1049
|
+
...(delta.threadId === undefined ? {} : { threadId: delta.threadId }),
|
|
1050
|
+
text,
|
|
1051
|
+
};
|
|
1052
|
+
flushDrafts();
|
|
1053
|
+
},
|
|
1054
|
+
fetchAttachment(ref) {
|
|
1055
|
+
return media.fetchAttachment(ref, controller?.signal ?? new AbortController().signal).then((bytes) =>
|
|
1056
|
+
bytes === undefined
|
|
1057
|
+
? undefined
|
|
1058
|
+
: {
|
|
1059
|
+
bytes,
|
|
1060
|
+
...(ref.mimeType === undefined ? {} : { mimeType: ref.mimeType }),
|
|
1061
|
+
...(ref.fileName === undefined ? {} : { fileName: ref.fileName }),
|
|
1062
|
+
},
|
|
1063
|
+
);
|
|
1064
|
+
},
|
|
1065
|
+
};
|
|
1066
|
+
}
|
|
1067
|
+
|
|
1068
|
+
/**
|
|
1069
|
+
* Creates a host-mounted Web Request/Response handler. It neither configures a webhook nor
|
|
1070
|
+
* starts a listener; operators deliberately call Telegram's `setWebhook` themselves.
|
|
1071
|
+
*/
|
|
1072
|
+
export function createTelegramWebhookHandler(options: TelegramWebhookHandlerOptions): TelegramWebhookHandler {
|
|
1073
|
+
if (
|
|
1074
|
+
typeof options.connectionId !== "string" ||
|
|
1075
|
+
options.connectionId.length === 0 ||
|
|
1076
|
+
Buffer.byteLength(options.connectionId, "utf8") > 256
|
|
1077
|
+
) {
|
|
1078
|
+
throw new TypeError("Telegram connectionId must be a bounded non-empty string");
|
|
1079
|
+
}
|
|
1080
|
+
if (typeof options.webhookSecret !== "function") throw new TypeError("Telegram webhookSecret must be a secret source, not a literal");
|
|
1081
|
+
let webhookSecret: Promise<string> | undefined;
|
|
1082
|
+
const expectedSecret = (): Promise<string> =>
|
|
1083
|
+
(webhookSecret ??= options.webhookSecret().then((value) => {
|
|
1084
|
+
if (!validWebhookSecret(value)) throw new TypeError("Telegram webhookSecret must be 1-256 URL-safe characters");
|
|
1085
|
+
return value;
|
|
1086
|
+
}));
|
|
1087
|
+
const leaseTtlMs = boundedInteger(options.leaseTtlMs, DEFAULT_LEASE_TTL_MS, 5_000, 300_000, "leaseTtlMs");
|
|
1088
|
+
const maxRequestBytes = boundedInteger(
|
|
1089
|
+
options.maxRequestBytes,
|
|
1090
|
+
DEFAULT_MAX_REQUEST_BYTES,
|
|
1091
|
+
1024,
|
|
1092
|
+
HARD_MAX_REQUEST_BYTES,
|
|
1093
|
+
"maxRequestBytes",
|
|
1094
|
+
);
|
|
1095
|
+
const maxResponseBytes = boundedInteger(
|
|
1096
|
+
options.maxResponseBytes,
|
|
1097
|
+
DEFAULT_MAX_REQUEST_BYTES,
|
|
1098
|
+
1024,
|
|
1099
|
+
HARD_MAX_REQUEST_BYTES,
|
|
1100
|
+
"maxResponseBytes",
|
|
1101
|
+
);
|
|
1102
|
+
const api = telegramApi({ ...options, maxResponseBytes });
|
|
1103
|
+
const allowGroups = options.allowGroups === true;
|
|
1104
|
+
const maxAttachmentBytes = boundedInteger(
|
|
1105
|
+
options.maxAttachmentBytes,
|
|
1106
|
+
DEFAULT_CHANNEL_LIMITS.maxAttachmentBytes,
|
|
1107
|
+
1,
|
|
1108
|
+
HARD_CHANNEL_LIMITS.maxAttachmentBytes,
|
|
1109
|
+
"maxAttachmentBytes",
|
|
1110
|
+
);
|
|
1111
|
+
const media = createInboundMedia({
|
|
1112
|
+
connectionId: options.connectionId,
|
|
1113
|
+
allowGroups,
|
|
1114
|
+
api,
|
|
1115
|
+
maxAttachmentBytes,
|
|
1116
|
+
...(options.transcribe === undefined ? {} : { transcribe: options.transcribe }),
|
|
1117
|
+
...(options.extractDocumentText === undefined ? {} : { extractDocumentText: options.extractDocumentText }),
|
|
1118
|
+
});
|
|
1119
|
+
|
|
1120
|
+
return async (request) => {
|
|
1121
|
+
if (request.method !== "POST") return new Response("Method not allowed", { status: 405 });
|
|
1122
|
+
if (!request.headers.get("content-type")?.toLowerCase().startsWith("application/json")) {
|
|
1123
|
+
return new Response("Unsupported media type", { status: 415 });
|
|
1124
|
+
}
|
|
1125
|
+
if (!constantTimeEqual(await expectedSecret(), request.headers.get("x-telegram-bot-api-secret-token"))) {
|
|
1126
|
+
return new Response("Unauthorized", { status: 401 });
|
|
1127
|
+
}
|
|
1128
|
+
const ownerId = `telegram-webhook-${randomUUID()}`;
|
|
1129
|
+
let lease: LeaseRecord | null = null;
|
|
1130
|
+
try {
|
|
1131
|
+
lease = await options.leases.tryAcquireLease({
|
|
1132
|
+
namespace: RECEIVER_LEASE_NAMESPACE,
|
|
1133
|
+
key: receiverKey(options.connectionId),
|
|
1134
|
+
...scope(options.cursorOwnership),
|
|
1135
|
+
ownerId,
|
|
1136
|
+
ttlMs: leaseTtlMs,
|
|
1137
|
+
signal: request.signal,
|
|
1138
|
+
});
|
|
1139
|
+
if (lease === null) return new Response("Unavailable", { status: 503 });
|
|
1140
|
+
let update: Record<string, unknown> | undefined;
|
|
1141
|
+
try {
|
|
1142
|
+
update = asRecord(await readRequestJson(request, maxRequestBytes));
|
|
1143
|
+
} catch (error) {
|
|
1144
|
+
return new Response(error instanceof RangeError ? "Payload too large" : "Malformed request", {
|
|
1145
|
+
status: error instanceof RangeError ? 413 : 400,
|
|
1146
|
+
});
|
|
1147
|
+
}
|
|
1148
|
+
if (update === undefined || updateId(update) === undefined) return new Response("Malformed request", { status: 400 });
|
|
1149
|
+
const callback = callbackId(update);
|
|
1150
|
+
if (callback !== undefined) {
|
|
1151
|
+
try {
|
|
1152
|
+
await api.call<boolean>("answerCallbackQuery", { callback_query_id: callback }, request.signal);
|
|
1153
|
+
} catch {
|
|
1154
|
+
return new Response("Unavailable", { status: 503 });
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1157
|
+
const event = await media.prepareInboundEvent(update, request.signal);
|
|
1158
|
+
if (event === undefined) return new Response(null, { status: 204 });
|
|
1159
|
+
const admission = await options.admit(event);
|
|
1160
|
+
if (retryableAdmission(admission)) return new Response("Unavailable", { status: 503 });
|
|
1161
|
+
return new Response(null, { status: 204 });
|
|
1162
|
+
} catch {
|
|
1163
|
+
return new Response("Unavailable", { status: 503 });
|
|
1164
|
+
} finally {
|
|
1165
|
+
await releaseReceiver(options.leases, options.cursorOwnership, options.connectionId, ownerId, lease ?? undefined);
|
|
1166
|
+
}
|
|
1167
|
+
};
|
|
1168
|
+
}
|
|
1169
|
+
|
|
1170
|
+
export interface TelegramConnectOptions {
|
|
1171
|
+
readonly limits?: import("./types.js").ChannelLimits;
|
|
1172
|
+
/** Telegram bot token reference (env: or keyring:). Literal tokens fail with ChannelTokenLiteralError. */
|
|
1173
|
+
readonly token: string;
|
|
1174
|
+
readonly connectionId?: string;
|
|
1175
|
+
readonly checkpoints?: CheckpointStore;
|
|
1176
|
+
readonly leases?: LeaseStore;
|
|
1177
|
+
readonly cursorOwnership?: OwnershipScope;
|
|
1178
|
+
readonly ownership?: OwnershipScope;
|
|
1179
|
+
readonly stateStore?: import("./state.js").ChannelStateStore;
|
|
1180
|
+
readonly deliveryJournal?: import("./delivery.js").ChannelDeliveryJournal;
|
|
1181
|
+
readonly approvalStore?: import("./approvals.js").ChannelApprovalStore;
|
|
1182
|
+
readonly pairingStore?: import("./pairing.js").ChannelPairingStore;
|
|
1183
|
+
readonly pairing?: {
|
|
1184
|
+
readonly ttlMs?: number;
|
|
1185
|
+
};
|
|
1186
|
+
readonly authorize?: (
|
|
1187
|
+
input: ChannelAuthorizeInput,
|
|
1188
|
+
) => ChannelAuthorization | false | undefined | Promise<ChannelAuthorization | false | undefined>;
|
|
1189
|
+
readonly allowGroups?: boolean;
|
|
1190
|
+
readonly sendDrafts?: boolean;
|
|
1191
|
+
readonly maxAttachmentBytes?: number;
|
|
1192
|
+
readonly transcribe?: (audio: Uint8Array, format: string | undefined, signal?: AbortSignal) => Promise<string>;
|
|
1193
|
+
readonly synthesize?: (text: string, signal?: AbortSignal) => Promise<{ readonly audio: Uint8Array; readonly format: string }>;
|
|
1194
|
+
readonly extractDocumentText?: (bytes: Uint8Array, mimeType: string | undefined, signal?: AbortSignal) => Promise<string>;
|
|
1195
|
+
readonly apiOrigin?: string;
|
|
1196
|
+
readonly fetch?: typeof globalThis.fetch;
|
|
1197
|
+
/** Webhook secret reference (env: or keyring:). Literal string throws ChannelTokenLiteralError. */
|
|
1198
|
+
readonly webhookSecret?: string;
|
|
1199
|
+
}
|
|
1200
|
+
|
|
1201
|
+
export async function connectTelegram(agent: Agent, options: TelegramConnectOptions): Promise<ChannelConnectionHandle> {
|
|
1202
|
+
const resolvedToken = await resolveChannelSecretRef(agent, options.token);
|
|
1203
|
+
const resolvedWebhookSecret =
|
|
1204
|
+
options.webhookSecret === undefined ? undefined : await resolveChannelSecretRef(agent, options.webhookSecret);
|
|
1205
|
+
const secretRedactor = createChannelRedactor(
|
|
1206
|
+
resolvedWebhookSecret === undefined ? resolvedToken : [resolvedToken, resolvedWebhookSecret],
|
|
1207
|
+
agent.config?.redactor,
|
|
1208
|
+
);
|
|
1209
|
+
const botToken: ChannelSecretSource = async () => resolvedToken;
|
|
1210
|
+
const connectionId = options.connectionId ?? "telegram-default";
|
|
1211
|
+
const checkpoints = options.checkpoints ?? createMemoryCheckpointStore();
|
|
1212
|
+
const leases = options.leases ?? createMemoryLeaseStore();
|
|
1213
|
+
const cursorOwnership = options.cursorOwnership ?? { tenantId: "default", accountId: "default", userId: "service" };
|
|
1214
|
+
|
|
1215
|
+
const adapter = createTelegramAdapter({
|
|
1216
|
+
connectionId,
|
|
1217
|
+
botToken,
|
|
1218
|
+
checkpoints,
|
|
1219
|
+
leases,
|
|
1220
|
+
cursorOwnership,
|
|
1221
|
+
allowGroups: options.allowGroups,
|
|
1222
|
+
sendDrafts: options.sendDrafts,
|
|
1223
|
+
maxAttachmentBytes: options.maxAttachmentBytes,
|
|
1224
|
+
transcribe: options.transcribe,
|
|
1225
|
+
synthesize: options.synthesize,
|
|
1226
|
+
extractDocumentText: options.extractDocumentText,
|
|
1227
|
+
apiOrigin: options.apiOrigin,
|
|
1228
|
+
fetch: options.fetch,
|
|
1229
|
+
});
|
|
1230
|
+
|
|
1231
|
+
const runtime = createChannelRuntime(agent, {
|
|
1232
|
+
deliver: (reply) => adapter.send(reply),
|
|
1233
|
+
checkpoints,
|
|
1234
|
+
leases,
|
|
1235
|
+
redactor: secretRedactor,
|
|
1236
|
+
authorize: options.authorize,
|
|
1237
|
+
limits: options.limits,
|
|
1238
|
+
onAssistantDelta: options.sendDrafts ? (delta) => adapter.sendDraft(delta) : undefined,
|
|
1239
|
+
fetchAttachment: (ref) => adapter.fetchAttachment(ref),
|
|
1240
|
+
});
|
|
1241
|
+
|
|
1242
|
+
const webhookHandler =
|
|
1243
|
+
resolvedWebhookSecret !== undefined
|
|
1244
|
+
? createTelegramWebhookHandler({
|
|
1245
|
+
connectionId,
|
|
1246
|
+
botToken,
|
|
1247
|
+
webhookSecret: async () => resolvedWebhookSecret,
|
|
1248
|
+
admit: (event) => runtime.admit(event),
|
|
1249
|
+
leases,
|
|
1250
|
+
cursorOwnership,
|
|
1251
|
+
allowGroups: options.allowGroups,
|
|
1252
|
+
maxAttachmentBytes: options.maxAttachmentBytes,
|
|
1253
|
+
transcribe: options.transcribe,
|
|
1254
|
+
extractDocumentText: options.extractDocumentText,
|
|
1255
|
+
apiOrigin: options.apiOrigin,
|
|
1256
|
+
fetch: options.fetch,
|
|
1257
|
+
})
|
|
1258
|
+
: undefined;
|
|
1259
|
+
|
|
1260
|
+
const api = telegramApi({
|
|
1261
|
+
botToken,
|
|
1262
|
+
apiOrigin: options.apiOrigin,
|
|
1263
|
+
fetch: options.fetch,
|
|
1264
|
+
maxResponseBytes: DEFAULT_MAX_REQUEST_BYTES,
|
|
1265
|
+
});
|
|
1266
|
+
|
|
1267
|
+
const media = createInboundMedia({
|
|
1268
|
+
connectionId,
|
|
1269
|
+
allowGroups: options.allowGroups === true,
|
|
1270
|
+
api,
|
|
1271
|
+
maxAttachmentBytes: options.maxAttachmentBytes ?? DEFAULT_CHANNEL_LIMITS.maxAttachmentBytes,
|
|
1272
|
+
transcribe: options.transcribe,
|
|
1273
|
+
extractDocumentText: options.extractDocumentText,
|
|
1274
|
+
});
|
|
1275
|
+
|
|
1276
|
+
const handle: ChannelConnectionHandle = {
|
|
1277
|
+
async handle(update: unknown): Promise<unknown> {
|
|
1278
|
+
if (typeof Response !== "undefined" && typeof Request !== "undefined" && update instanceof Request) {
|
|
1279
|
+
if (webhookHandler) return await webhookHandler(update);
|
|
1280
|
+
const json = (await update.json()) as Record<string, unknown>;
|
|
1281
|
+
const event = await media.prepareInboundEvent(json, update.signal);
|
|
1282
|
+
if (!event) return new Response(null, { status: 204 });
|
|
1283
|
+
const admission = await runtime.admit(event);
|
|
1284
|
+
if (retryableAdmission(admission)) return new Response("Unavailable", { status: 503 });
|
|
1285
|
+
return new Response(null, { status: 204 });
|
|
1286
|
+
}
|
|
1287
|
+
if (typeof update === "object" && update !== null) {
|
|
1288
|
+
if ("connectionId" in update && "externalActorId" in update && "eventId" in update) {
|
|
1289
|
+
return await runtime.admit(update as ChannelInboundEvent);
|
|
1290
|
+
}
|
|
1291
|
+
const event = await media.prepareInboundEvent(update as Record<string, unknown>, new AbortController().signal);
|
|
1292
|
+
if (event) return await runtime.admit(event);
|
|
1293
|
+
return undefined;
|
|
1294
|
+
}
|
|
1295
|
+
return undefined;
|
|
1296
|
+
},
|
|
1297
|
+
async start() {
|
|
1298
|
+
await adapter.start((event) => runtime.admit(event));
|
|
1299
|
+
},
|
|
1300
|
+
async close() {
|
|
1301
|
+
const stopping = runtime.stop();
|
|
1302
|
+
try {
|
|
1303
|
+
await adapter.stop();
|
|
1304
|
+
} finally {
|
|
1305
|
+
await stopping;
|
|
1306
|
+
}
|
|
1307
|
+
},
|
|
1308
|
+
async stop() {
|
|
1309
|
+
await handle.close();
|
|
1310
|
+
},
|
|
1311
|
+
async drain(opts) {
|
|
1312
|
+
return await runtime.drain(opts);
|
|
1313
|
+
},
|
|
1314
|
+
};
|
|
1315
|
+
bindChannelHostUi(handle, runtime, connectionId);
|
|
1316
|
+
return handle;
|
|
1317
|
+
}
|