@theokit/gateway 0.25.0 → 0.27.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 +19 -0
- package/README.md +72 -1
- package/dist/index.cjs +311 -32
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +181 -10
- package/dist/index.d.ts +181 -10
- package/dist/index.js +306 -33
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.d.cts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { KeyObject } from 'node:crypto';
|
|
2
|
+
|
|
1
3
|
/**
|
|
2
4
|
* A bounded set of ids, oldest evicted first, so a long-running process remembers what it delivered
|
|
3
5
|
* without growing for ever (NFR-003).
|
|
@@ -821,14 +823,37 @@ interface OutboundMessage {
|
|
|
821
823
|
*/
|
|
822
824
|
readonly attachments?: ReadonlyArray<OutboundAttachment>;
|
|
823
825
|
}
|
|
824
|
-
/**
|
|
826
|
+
/**
|
|
827
|
+
* Shared failure codes for {@link SendResult}.
|
|
828
|
+
*
|
|
829
|
+
* - `empty_text`, `not_connected`, `invalid_channel`, `attachments_unsupported`: core refused the send.
|
|
830
|
+
* - `rate_limit`: the platform throttled the send; see `retryAfterMs`.
|
|
831
|
+
* - `permission_denied`: the credential is valid but may not post here (HTTP 403).
|
|
832
|
+
* - `auth_failed`: the credential was rejected (HTTP 401).
|
|
833
|
+
* - `timeout`: the platform or the request timed out (HTTP 408).
|
|
834
|
+
* - `server_error`: the platform failed (HTTP 5xx).
|
|
835
|
+
* - `network_error`: the request never got an answer.
|
|
836
|
+
* - `platform_error`: any other platform refusal.
|
|
837
|
+
*/
|
|
838
|
+
type SendErrorCode = "empty_text" | "not_connected" | "invalid_channel" | "attachments_unsupported" | "rate_limit" | "permission_denied" | "auth_failed" | "timeout" | "server_error" | "network_error" | "platform_error";
|
|
839
|
+
/** The error of a failed {@link SendResult}. */
|
|
840
|
+
interface SendError {
|
|
841
|
+
/** A known code, or a platform-specific one an adapter has not mapped yet. */
|
|
842
|
+
readonly code: SendErrorCode | (string & {});
|
|
843
|
+
readonly message: string;
|
|
844
|
+
/** Set when the platform said how long to wait. */
|
|
845
|
+
readonly retryAfterMs?: number;
|
|
846
|
+
/** The platform's own code, kept for logs. */
|
|
847
|
+
readonly platformCode?: string;
|
|
848
|
+
}
|
|
849
|
+
/**
|
|
850
|
+
* Send result — adapters return this instead of throwing on platform errors.
|
|
851
|
+
* `error.code` is a {@link SendErrorCode} or a platform-specific string.
|
|
852
|
+
*/
|
|
825
853
|
interface SendResult {
|
|
826
854
|
readonly ok: boolean;
|
|
827
855
|
readonly messageId?: string;
|
|
828
|
-
readonly error?:
|
|
829
|
-
readonly code: string;
|
|
830
|
-
readonly message: string;
|
|
831
|
-
};
|
|
856
|
+
readonly error?: SendError;
|
|
832
857
|
}
|
|
833
858
|
/** The facts about an adapter that an app picks its rendering from. */
|
|
834
859
|
interface AdapterCapabilities {
|
|
@@ -1010,6 +1035,17 @@ declare abstract class BasePlatformAdapter {
|
|
|
1010
1035
|
stopTyping(_channelId: string): Promise<void>;
|
|
1011
1036
|
}
|
|
1012
1037
|
|
|
1038
|
+
/**
|
|
1039
|
+
* Map an HTTP status to a failed SendResult: 429 -> rate_limit (retryAfterMs from a Retry-After
|
|
1040
|
+
* value in seconds or an HTTP date), 401 -> auth_failed, 403 -> permission_denied,
|
|
1041
|
+
* 408 -> timeout, 5xx -> server_error, other -> platform_error.
|
|
1042
|
+
*/
|
|
1043
|
+
declare function sendErrorFromHttp(status: number, message: string, options?: {
|
|
1044
|
+
retryAfter?: string | null;
|
|
1045
|
+
platformCode?: string;
|
|
1046
|
+
now?: () => number;
|
|
1047
|
+
}): SendResult;
|
|
1048
|
+
|
|
1013
1049
|
/**
|
|
1014
1050
|
* `WeixinAdapterBase` — the connect / token / send / dispatch flow that the WeChat and WeCom
|
|
1015
1051
|
* adapters share. A subclass supplies the platform's endpoints, its signature check and its event
|
|
@@ -1067,7 +1103,7 @@ declare abstract class WeixinAdapterBase extends BasePlatformAdapter {
|
|
|
1067
1103
|
private readonly cfg;
|
|
1068
1104
|
private readonly doFetch;
|
|
1069
1105
|
private connected;
|
|
1070
|
-
private
|
|
1106
|
+
private readonly tokens;
|
|
1071
1107
|
private readonly seen;
|
|
1072
1108
|
constructor(cfg: WeixinAdapterConfig);
|
|
1073
1109
|
/** Path and query of the access-token request. */
|
|
@@ -1089,6 +1125,7 @@ declare abstract class WeixinAdapterBase extends BasePlatformAdapter {
|
|
|
1089
1125
|
/** Turn a plain (decrypted) XML body into one event, dispatch it and answer the webhook. */
|
|
1090
1126
|
protected handleMessage(xml: string): Promise<WeixinWebhookAnswer>;
|
|
1091
1127
|
private token;
|
|
1128
|
+
private requestToken;
|
|
1092
1129
|
private call;
|
|
1093
1130
|
}
|
|
1094
1131
|
|
|
@@ -1101,6 +1138,97 @@ declare abstract class WeixinAdapterBase extends BasePlatformAdapter {
|
|
|
1101
1138
|
*/
|
|
1102
1139
|
declare function parseFlatXml(xml: string): Record<string, string>;
|
|
1103
1140
|
|
|
1141
|
+
/**
|
|
1142
|
+
* A JWKS key-set cache and RS256 JWT signature verification, for platforms that sign their
|
|
1143
|
+
* requests with a JWT. Signature only: issuer, audience and expiry stay with the caller.
|
|
1144
|
+
*/
|
|
1145
|
+
|
|
1146
|
+
/** A key for a `kid`, `"unlisted"` when the key set does not list it, or why no key set is readable. */
|
|
1147
|
+
type JwksLookup = KeyObject | "unlisted" | {
|
|
1148
|
+
readonly unavailable: string;
|
|
1149
|
+
};
|
|
1150
|
+
/** Where a JWKS is read from, and how its cache behaves. */
|
|
1151
|
+
interface JwksKeySetOptions {
|
|
1152
|
+
readonly url: string;
|
|
1153
|
+
readonly fetch?: (url: string, init?: {
|
|
1154
|
+
signal?: AbortSignal;
|
|
1155
|
+
}) => Promise<Response>;
|
|
1156
|
+
readonly now?: () => number;
|
|
1157
|
+
/** Minimum time between refetches triggered by an unknown kid. Default 60_000. */
|
|
1158
|
+
readonly unknownKidRefetchFloorMs?: number;
|
|
1159
|
+
/** Serve a stale key set while one refresh runs. Default true. */
|
|
1160
|
+
readonly staleWhileRevalidate?: boolean;
|
|
1161
|
+
}
|
|
1162
|
+
/** A cache of the keys a JWKS publishes, looked up by `kid`. */
|
|
1163
|
+
interface JwksKeySet {
|
|
1164
|
+
lookup(kid: string): Promise<JwksLookup>;
|
|
1165
|
+
}
|
|
1166
|
+
/**
|
|
1167
|
+
* A JWKS key set cached for the `max-age` its response declares. Concurrent lookups share one
|
|
1168
|
+
* read; a read starts at most once per `unknownKidRefetchFloorMs`. A failed read keeps the last
|
|
1169
|
+
* good copy.
|
|
1170
|
+
*/
|
|
1171
|
+
declare function jwksKeySet(options: JwksKeySetOptions): JwksKeySet;
|
|
1172
|
+
/** A compact JWT split into its parts; nothing in it is verified yet. */
|
|
1173
|
+
interface DecodedJwt {
|
|
1174
|
+
readonly header: Readonly<Record<string, unknown>>;
|
|
1175
|
+
readonly payload: Readonly<Record<string, unknown>>;
|
|
1176
|
+
readonly signingInput: string;
|
|
1177
|
+
readonly signature: Buffer;
|
|
1178
|
+
}
|
|
1179
|
+
/** Split a compact JWT into its parts without checking anything; `undefined` when malformed. */
|
|
1180
|
+
declare function decodeJwt(token: string): DecodedJwt | undefined;
|
|
1181
|
+
/** The outcome of checking a token's signature: its claims, or why it was refused. */
|
|
1182
|
+
type VerifyJwtResult = {
|
|
1183
|
+
readonly ok: true;
|
|
1184
|
+
readonly header: DecodedJwt["header"];
|
|
1185
|
+
readonly payload: DecodedJwt["payload"];
|
|
1186
|
+
} | {
|
|
1187
|
+
readonly ok: false;
|
|
1188
|
+
readonly reason: "malformed" | "unsupported_alg" | "unknown_kid" | "keys_unavailable" | "bad_signature";
|
|
1189
|
+
};
|
|
1190
|
+
/** Signature only. Issuer, audience and expiry stay with the caller. */
|
|
1191
|
+
declare function verifyRs256Jwt(token: string, keys: JwksKeySet): Promise<VerifyJwtResult>;
|
|
1192
|
+
|
|
1193
|
+
/**
|
|
1194
|
+
* `createTokenCache` — holds one expiring access token and shares a single refresh between every
|
|
1195
|
+
* concurrent caller.
|
|
1196
|
+
*
|
|
1197
|
+
* @public
|
|
1198
|
+
*/
|
|
1199
|
+
/** A token as the platform reported it. @public */
|
|
1200
|
+
interface FetchedToken {
|
|
1201
|
+
readonly value: string;
|
|
1202
|
+
/** Lifetime in seconds as the platform reported it; `defaultTtlS` when absent or not positive. */
|
|
1203
|
+
readonly expiresInS?: number;
|
|
1204
|
+
}
|
|
1205
|
+
/** Options of {@link createTokenCache}. @public */
|
|
1206
|
+
interface TokenCacheOptions {
|
|
1207
|
+
/** Fetch a fresh token. Receives the signal of the caller that started the fetch. */
|
|
1208
|
+
readonly fetchToken: (signal?: AbortSignal) => Promise<FetchedToken>;
|
|
1209
|
+
/** Refresh this long before expiry. Default 60_000. */
|
|
1210
|
+
readonly marginMs?: number;
|
|
1211
|
+
/** Default 7200. */
|
|
1212
|
+
readonly defaultTtlS?: number;
|
|
1213
|
+
readonly now?: () => number;
|
|
1214
|
+
}
|
|
1215
|
+
/** A cached expiring token. @public */
|
|
1216
|
+
interface TokenCache {
|
|
1217
|
+
/**
|
|
1218
|
+
* The cached token, or one fetch shared by every concurrent caller. `force` skips the cache
|
|
1219
|
+
* (but still joins a fetch already in flight). The signal of the caller that starts a fetch
|
|
1220
|
+
* governs it; later callers' signals do not cancel their wait.
|
|
1221
|
+
*/
|
|
1222
|
+
get(options?: {
|
|
1223
|
+
force?: boolean;
|
|
1224
|
+
signal?: AbortSignal;
|
|
1225
|
+
}): Promise<string>;
|
|
1226
|
+
/** Forget the cached token (after a 401, for example). */
|
|
1227
|
+
clear(): void;
|
|
1228
|
+
}
|
|
1229
|
+
/** Build a {@link TokenCache}. A failed fetch rejects every waiting caller and is not cached. @public */
|
|
1230
|
+
declare function createTokenCache(options: TokenCacheOptions): TokenCache;
|
|
1231
|
+
|
|
1104
1232
|
/**
|
|
1105
1233
|
* `GatewayConfigurationError` — shared base for per-adapter configuration
|
|
1106
1234
|
* errors (roadmap M0/M2).
|
|
@@ -1933,6 +2061,42 @@ interface MediaUnderstandingOptions {
|
|
|
1933
2061
|
/** Wraps a handler: the event it receives has the transcript or description appended to text. */
|
|
1934
2062
|
declare function withMediaUnderstanding(handler: GatewayHandler, options: MediaUnderstandingOptions): GatewayHandler;
|
|
1935
2063
|
|
|
2064
|
+
/**
|
|
2065
|
+
* Options for {@link ReconnectBackoff}. Delay fields default as documented on `ReconnectPolicy`.
|
|
2066
|
+
*
|
|
2067
|
+
* @public
|
|
2068
|
+
*/
|
|
2069
|
+
interface ReconnectBackoffOptions extends ReconnectPolicy {
|
|
2070
|
+
/** A connection open at least this long resets the delay. Default 60_000. */
|
|
2071
|
+
readonly stableAfterMs?: number;
|
|
2072
|
+
/** Clock in ms; defaults to `Date.now`. */
|
|
2073
|
+
readonly now?: () => number;
|
|
2074
|
+
}
|
|
2075
|
+
/**
|
|
2076
|
+
* Reconnect delay for an adapter that holds a long-lived connection: `min(initialDelayMs *
|
|
2077
|
+
* factor^(n-1), maxDelayMs)` for attempt n, reset after a connection that stayed open for
|
|
2078
|
+
* `stableAfterMs`.
|
|
2079
|
+
*
|
|
2080
|
+
* @public
|
|
2081
|
+
*/
|
|
2082
|
+
declare class ReconnectBackoff {
|
|
2083
|
+
private readonly initialDelayMs;
|
|
2084
|
+
private readonly maxDelayMs;
|
|
2085
|
+
private readonly factor;
|
|
2086
|
+
private readonly maxAttempts;
|
|
2087
|
+
private readonly stableAfterMs;
|
|
2088
|
+
private readonly now;
|
|
2089
|
+
private attempts;
|
|
2090
|
+
private openedAt;
|
|
2091
|
+
constructor(options?: ReconnectBackoffOptions);
|
|
2092
|
+
/** Call when the connection opens. */
|
|
2093
|
+
opened(): void;
|
|
2094
|
+
/** Delay before the next attempt; `undefined` once `maxAttempts` is spent. Resets first if the last connection was stable. */
|
|
2095
|
+
nextDelayMs(): number | undefined;
|
|
2096
|
+
/** Back to the initial delay. */
|
|
2097
|
+
reset(): void;
|
|
2098
|
+
}
|
|
2099
|
+
|
|
1936
2100
|
/** A credential shape this module masks, and the cost of matching it. */
|
|
1937
2101
|
interface CoveredShape {
|
|
1938
2102
|
/** The platform and field, for the reader of the table. */
|
|
@@ -2305,11 +2469,18 @@ declare function scanFences(text: string): readonly FenceRegion[];
|
|
|
2305
2469
|
*
|
|
2306
2470
|
* @internal
|
|
2307
2471
|
*/
|
|
2472
|
+
/** The unit `partLimit` is measured in. */
|
|
2473
|
+
interface SplitKeepingRowsOptions {
|
|
2474
|
+
/** How `partLimit` is measured. Default "utf16" (UTF-16 units). */
|
|
2475
|
+
readonly unit?: "utf16" | "codepoint";
|
|
2476
|
+
}
|
|
2308
2477
|
/**
|
|
2309
|
-
* Parts of at most `partLimit` units,
|
|
2310
|
-
* Shared by the SMS and LINE splitters (text no
|
|
2478
|
+
* Parts of at most `partLimit` units (UTF-16 units, or code points with `unit: "codepoint"`), cut
|
|
2479
|
+
* at grapheme boundaries and before straddled rows. Shared by the SMS and LINE splitters (text no
|
|
2480
|
+
* longer than a part is theirs to handle). In code-point mode `partLimit` must be a positive
|
|
2481
|
+
* integer and a single grapheme longer than it throws `RangeError`.
|
|
2311
2482
|
*/
|
|
2312
|
-
declare function splitKeepingRows(text: string, partLimit: number): string[];
|
|
2483
|
+
declare function splitKeepingRows(text: string, partLimit: number, options?: SplitKeepingRowsOptions): string[];
|
|
2313
2484
|
|
|
2314
2485
|
/** The outcome of delivering one event to the runner's handlers. */
|
|
2315
2486
|
type DeliverOutcome = "ok" | "no_handler" | "handler_threw";
|
|
@@ -2457,4 +2628,4 @@ interface WebhookHandlerOptions {
|
|
|
2457
2628
|
*/
|
|
2458
2629
|
declare function createWebhookHandler(options: WebhookHandlerOptions): (request: Request) => Promise<Response>;
|
|
2459
2630
|
|
|
2460
|
-
export { type AccessPolicyOptions, type AdapterCapabilities, type AdapterState, type AgentBindingRule, type AgentBindings, type AgentBindingsOptions, type AgentIdStrategy, type BaseMessageEvent, BasePlatformAdapter, type BuiltChannel, type BuzzMessageEvent, CREDENTIAL_SHAPES, type ChannelConfigField, type ChannelConfigInput, type ChannelConfigReaders, type ChannelDescriptor, type ChannelEntry, type ChannelRejection, type ChannelRendering, type ChannelWebhook, type ChatCommand, type ChunkByGraphemeOptions, type ChunkTextOptions, type ClickClackMessageEvent, type ConnectFailure, type CoveredShape, type CreateChannelsResult, type CredentialStore, DEFAULT_WEBHOOK_MAX_BYTES, type DeliveryRequest, DeliveryRouter, type DeliveryTarget, type DiscordMessageEvent, type DmPolicy, type DmScope, type EmailMessageEvent, type EnvConfig, type FeishuLarkMessageEvent, type FenceRegion, GatewayConfigurationError, type GatewayConfigurationErrorOptions, type GatewayContext, type GatewayHandler, type GatewayHook, GatewayLifecycleError, type GatewayLifecycleErrorOptions, GatewayRunner, type GatewayRunnerOptions, type GoogleChatMessageEvent, type HookDecision, HookExecutor, type HookName, type IMessageMessageEvent, type InboundAudio, type IngestResult, type IrcMessageEvent, type LineMessageEvent, type ListenableApp, type ListenerLike, type MatrixMessageEvent, type MattermostMessageEvent, type MediaUnderstandingOptions, type MessageEvent, type NextcloudTalkMessageEvent, type NostrMessageEvent, type OnErrorContext, type OutboundAttachment, type OutboundMessage, type PairingStore, type ParsedChatCommand, type PlatformEventRegistry, type PlatformName, type PostOutboundContext, type PreInboundContext, type QQMessageEvent, type RaftMessageEvent, type RawBodyCaptureOptions, type RawBodyRequest, type ReconnectPolicy, type SMSMessageEvent, type ScopedStrategyOptions, SeenIds, type SendResult, type SenderIdentity, SessionRouter, type SignalMessageEvent, type SlackMessageEvent, type StartResult, type SynologyChatMessageEvent, type TeamsMessageEvent, type TelegramMessageEvent, type TlonUrbitMessageEvent, type TwitchMessageEvent, type UncoveredShape, type WeChatMessageEvent, type WeComMessageEvent, type WebhookAnswer, type WebhookHandlerOptions, type WebhookRequest, WeixinAdapterBase, type WeixinAdapterConfig, type WeixinFetch, type WeixinSendRequest, type WeixinWebhookAnswer, type WhatsAppMessageEvent, type XMessageEvent, type XThreadTweet, type YuanbaoMessageEvent, type ZaloMessageEvent, type ZaloPersonalMessageEvent, bindingStrategy, channelConfigReaders, channelRendering, chunkByGrapheme, chunkText, commandHook, configFromEnv, createAccessPolicyHook, createAgentBindings, createChannels, createFileCredentialStore, createFilePairingStore, createWebhookHandler, defaultStrategy, helpText, isAuthenticatedSender, listenerLifecycle, loadPeer, maskSecrets, maskShapes, parseChatCommand, parseFlatXml, rawBodyCapture, redactSecrets, scanFences, scopedStrategy, selectVariant, senderKey, splitKeepingRows, statusForDeliver, toDialect, withMediaUnderstanding };
|
|
2631
|
+
export { type AccessPolicyOptions, type AdapterCapabilities, type AdapterState, type AgentBindingRule, type AgentBindings, type AgentBindingsOptions, type AgentIdStrategy, type BaseMessageEvent, BasePlatformAdapter, type BuiltChannel, type BuzzMessageEvent, CREDENTIAL_SHAPES, type ChannelConfigField, type ChannelConfigInput, type ChannelConfigReaders, type ChannelDescriptor, type ChannelEntry, type ChannelRejection, type ChannelRendering, type ChannelWebhook, type ChatCommand, type ChunkByGraphemeOptions, type ChunkTextOptions, type ClickClackMessageEvent, type ConnectFailure, type CoveredShape, type CreateChannelsResult, type CredentialStore, DEFAULT_WEBHOOK_MAX_BYTES, type DecodedJwt, type DeliveryRequest, DeliveryRouter, type DeliveryTarget, type DiscordMessageEvent, type DmPolicy, type DmScope, type EmailMessageEvent, type EnvConfig, type FeishuLarkMessageEvent, type FenceRegion, type FetchedToken, GatewayConfigurationError, type GatewayConfigurationErrorOptions, type GatewayContext, type GatewayHandler, type GatewayHook, GatewayLifecycleError, type GatewayLifecycleErrorOptions, GatewayRunner, type GatewayRunnerOptions, type GoogleChatMessageEvent, type HookDecision, HookExecutor, type HookName, type IMessageMessageEvent, type InboundAudio, type IngestResult, type IrcMessageEvent, type JwksKeySet, type JwksKeySetOptions, type JwksLookup, type LineMessageEvent, type ListenableApp, type ListenerLike, type MatrixMessageEvent, type MattermostMessageEvent, type MediaUnderstandingOptions, type MessageEvent, type NextcloudTalkMessageEvent, type NostrMessageEvent, type OnErrorContext, type OutboundAttachment, type OutboundMessage, type PairingStore, type ParsedChatCommand, type PlatformEventRegistry, type PlatformName, type PostOutboundContext, type PreInboundContext, type QQMessageEvent, type RaftMessageEvent, type RawBodyCaptureOptions, type RawBodyRequest, ReconnectBackoff, type ReconnectBackoffOptions, type ReconnectPolicy, type SMSMessageEvent, type ScopedStrategyOptions, SeenIds, type SendError, type SendErrorCode, type SendResult, type SenderIdentity, SessionRouter, type SignalMessageEvent, type SlackMessageEvent, type SplitKeepingRowsOptions, type StartResult, type SynologyChatMessageEvent, type TeamsMessageEvent, type TelegramMessageEvent, type TlonUrbitMessageEvent, type TokenCache, type TokenCacheOptions, type TwitchMessageEvent, type UncoveredShape, type VerifyJwtResult, type WeChatMessageEvent, type WeComMessageEvent, type WebhookAnswer, type WebhookHandlerOptions, type WebhookRequest, WeixinAdapterBase, type WeixinAdapterConfig, type WeixinFetch, type WeixinSendRequest, type WeixinWebhookAnswer, type WhatsAppMessageEvent, type XMessageEvent, type XThreadTweet, type YuanbaoMessageEvent, type ZaloMessageEvent, type ZaloPersonalMessageEvent, bindingStrategy, channelConfigReaders, channelRendering, chunkByGrapheme, chunkText, commandHook, configFromEnv, createAccessPolicyHook, createAgentBindings, createChannels, createFileCredentialStore, createFilePairingStore, createTokenCache, createWebhookHandler, decodeJwt, defaultStrategy, helpText, isAuthenticatedSender, jwksKeySet, listenerLifecycle, loadPeer, maskSecrets, maskShapes, parseChatCommand, parseFlatXml, rawBodyCapture, redactSecrets, scanFences, scopedStrategy, selectVariant, sendErrorFromHttp, senderKey, splitKeepingRows, statusForDeliver, toDialect, verifyRs256Jwt, withMediaUnderstanding };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { KeyObject } from 'node:crypto';
|
|
2
|
+
|
|
1
3
|
/**
|
|
2
4
|
* A bounded set of ids, oldest evicted first, so a long-running process remembers what it delivered
|
|
3
5
|
* without growing for ever (NFR-003).
|
|
@@ -821,14 +823,37 @@ interface OutboundMessage {
|
|
|
821
823
|
*/
|
|
822
824
|
readonly attachments?: ReadonlyArray<OutboundAttachment>;
|
|
823
825
|
}
|
|
824
|
-
/**
|
|
826
|
+
/**
|
|
827
|
+
* Shared failure codes for {@link SendResult}.
|
|
828
|
+
*
|
|
829
|
+
* - `empty_text`, `not_connected`, `invalid_channel`, `attachments_unsupported`: core refused the send.
|
|
830
|
+
* - `rate_limit`: the platform throttled the send; see `retryAfterMs`.
|
|
831
|
+
* - `permission_denied`: the credential is valid but may not post here (HTTP 403).
|
|
832
|
+
* - `auth_failed`: the credential was rejected (HTTP 401).
|
|
833
|
+
* - `timeout`: the platform or the request timed out (HTTP 408).
|
|
834
|
+
* - `server_error`: the platform failed (HTTP 5xx).
|
|
835
|
+
* - `network_error`: the request never got an answer.
|
|
836
|
+
* - `platform_error`: any other platform refusal.
|
|
837
|
+
*/
|
|
838
|
+
type SendErrorCode = "empty_text" | "not_connected" | "invalid_channel" | "attachments_unsupported" | "rate_limit" | "permission_denied" | "auth_failed" | "timeout" | "server_error" | "network_error" | "platform_error";
|
|
839
|
+
/** The error of a failed {@link SendResult}. */
|
|
840
|
+
interface SendError {
|
|
841
|
+
/** A known code, or a platform-specific one an adapter has not mapped yet. */
|
|
842
|
+
readonly code: SendErrorCode | (string & {});
|
|
843
|
+
readonly message: string;
|
|
844
|
+
/** Set when the platform said how long to wait. */
|
|
845
|
+
readonly retryAfterMs?: number;
|
|
846
|
+
/** The platform's own code, kept for logs. */
|
|
847
|
+
readonly platformCode?: string;
|
|
848
|
+
}
|
|
849
|
+
/**
|
|
850
|
+
* Send result — adapters return this instead of throwing on platform errors.
|
|
851
|
+
* `error.code` is a {@link SendErrorCode} or a platform-specific string.
|
|
852
|
+
*/
|
|
825
853
|
interface SendResult {
|
|
826
854
|
readonly ok: boolean;
|
|
827
855
|
readonly messageId?: string;
|
|
828
|
-
readonly error?:
|
|
829
|
-
readonly code: string;
|
|
830
|
-
readonly message: string;
|
|
831
|
-
};
|
|
856
|
+
readonly error?: SendError;
|
|
832
857
|
}
|
|
833
858
|
/** The facts about an adapter that an app picks its rendering from. */
|
|
834
859
|
interface AdapterCapabilities {
|
|
@@ -1010,6 +1035,17 @@ declare abstract class BasePlatformAdapter {
|
|
|
1010
1035
|
stopTyping(_channelId: string): Promise<void>;
|
|
1011
1036
|
}
|
|
1012
1037
|
|
|
1038
|
+
/**
|
|
1039
|
+
* Map an HTTP status to a failed SendResult: 429 -> rate_limit (retryAfterMs from a Retry-After
|
|
1040
|
+
* value in seconds or an HTTP date), 401 -> auth_failed, 403 -> permission_denied,
|
|
1041
|
+
* 408 -> timeout, 5xx -> server_error, other -> platform_error.
|
|
1042
|
+
*/
|
|
1043
|
+
declare function sendErrorFromHttp(status: number, message: string, options?: {
|
|
1044
|
+
retryAfter?: string | null;
|
|
1045
|
+
platformCode?: string;
|
|
1046
|
+
now?: () => number;
|
|
1047
|
+
}): SendResult;
|
|
1048
|
+
|
|
1013
1049
|
/**
|
|
1014
1050
|
* `WeixinAdapterBase` — the connect / token / send / dispatch flow that the WeChat and WeCom
|
|
1015
1051
|
* adapters share. A subclass supplies the platform's endpoints, its signature check and its event
|
|
@@ -1067,7 +1103,7 @@ declare abstract class WeixinAdapterBase extends BasePlatformAdapter {
|
|
|
1067
1103
|
private readonly cfg;
|
|
1068
1104
|
private readonly doFetch;
|
|
1069
1105
|
private connected;
|
|
1070
|
-
private
|
|
1106
|
+
private readonly tokens;
|
|
1071
1107
|
private readonly seen;
|
|
1072
1108
|
constructor(cfg: WeixinAdapterConfig);
|
|
1073
1109
|
/** Path and query of the access-token request. */
|
|
@@ -1089,6 +1125,7 @@ declare abstract class WeixinAdapterBase extends BasePlatformAdapter {
|
|
|
1089
1125
|
/** Turn a plain (decrypted) XML body into one event, dispatch it and answer the webhook. */
|
|
1090
1126
|
protected handleMessage(xml: string): Promise<WeixinWebhookAnswer>;
|
|
1091
1127
|
private token;
|
|
1128
|
+
private requestToken;
|
|
1092
1129
|
private call;
|
|
1093
1130
|
}
|
|
1094
1131
|
|
|
@@ -1101,6 +1138,97 @@ declare abstract class WeixinAdapterBase extends BasePlatformAdapter {
|
|
|
1101
1138
|
*/
|
|
1102
1139
|
declare function parseFlatXml(xml: string): Record<string, string>;
|
|
1103
1140
|
|
|
1141
|
+
/**
|
|
1142
|
+
* A JWKS key-set cache and RS256 JWT signature verification, for platforms that sign their
|
|
1143
|
+
* requests with a JWT. Signature only: issuer, audience and expiry stay with the caller.
|
|
1144
|
+
*/
|
|
1145
|
+
|
|
1146
|
+
/** A key for a `kid`, `"unlisted"` when the key set does not list it, or why no key set is readable. */
|
|
1147
|
+
type JwksLookup = KeyObject | "unlisted" | {
|
|
1148
|
+
readonly unavailable: string;
|
|
1149
|
+
};
|
|
1150
|
+
/** Where a JWKS is read from, and how its cache behaves. */
|
|
1151
|
+
interface JwksKeySetOptions {
|
|
1152
|
+
readonly url: string;
|
|
1153
|
+
readonly fetch?: (url: string, init?: {
|
|
1154
|
+
signal?: AbortSignal;
|
|
1155
|
+
}) => Promise<Response>;
|
|
1156
|
+
readonly now?: () => number;
|
|
1157
|
+
/** Minimum time between refetches triggered by an unknown kid. Default 60_000. */
|
|
1158
|
+
readonly unknownKidRefetchFloorMs?: number;
|
|
1159
|
+
/** Serve a stale key set while one refresh runs. Default true. */
|
|
1160
|
+
readonly staleWhileRevalidate?: boolean;
|
|
1161
|
+
}
|
|
1162
|
+
/** A cache of the keys a JWKS publishes, looked up by `kid`. */
|
|
1163
|
+
interface JwksKeySet {
|
|
1164
|
+
lookup(kid: string): Promise<JwksLookup>;
|
|
1165
|
+
}
|
|
1166
|
+
/**
|
|
1167
|
+
* A JWKS key set cached for the `max-age` its response declares. Concurrent lookups share one
|
|
1168
|
+
* read; a read starts at most once per `unknownKidRefetchFloorMs`. A failed read keeps the last
|
|
1169
|
+
* good copy.
|
|
1170
|
+
*/
|
|
1171
|
+
declare function jwksKeySet(options: JwksKeySetOptions): JwksKeySet;
|
|
1172
|
+
/** A compact JWT split into its parts; nothing in it is verified yet. */
|
|
1173
|
+
interface DecodedJwt {
|
|
1174
|
+
readonly header: Readonly<Record<string, unknown>>;
|
|
1175
|
+
readonly payload: Readonly<Record<string, unknown>>;
|
|
1176
|
+
readonly signingInput: string;
|
|
1177
|
+
readonly signature: Buffer;
|
|
1178
|
+
}
|
|
1179
|
+
/** Split a compact JWT into its parts without checking anything; `undefined` when malformed. */
|
|
1180
|
+
declare function decodeJwt(token: string): DecodedJwt | undefined;
|
|
1181
|
+
/** The outcome of checking a token's signature: its claims, or why it was refused. */
|
|
1182
|
+
type VerifyJwtResult = {
|
|
1183
|
+
readonly ok: true;
|
|
1184
|
+
readonly header: DecodedJwt["header"];
|
|
1185
|
+
readonly payload: DecodedJwt["payload"];
|
|
1186
|
+
} | {
|
|
1187
|
+
readonly ok: false;
|
|
1188
|
+
readonly reason: "malformed" | "unsupported_alg" | "unknown_kid" | "keys_unavailable" | "bad_signature";
|
|
1189
|
+
};
|
|
1190
|
+
/** Signature only. Issuer, audience and expiry stay with the caller. */
|
|
1191
|
+
declare function verifyRs256Jwt(token: string, keys: JwksKeySet): Promise<VerifyJwtResult>;
|
|
1192
|
+
|
|
1193
|
+
/**
|
|
1194
|
+
* `createTokenCache` — holds one expiring access token and shares a single refresh between every
|
|
1195
|
+
* concurrent caller.
|
|
1196
|
+
*
|
|
1197
|
+
* @public
|
|
1198
|
+
*/
|
|
1199
|
+
/** A token as the platform reported it. @public */
|
|
1200
|
+
interface FetchedToken {
|
|
1201
|
+
readonly value: string;
|
|
1202
|
+
/** Lifetime in seconds as the platform reported it; `defaultTtlS` when absent or not positive. */
|
|
1203
|
+
readonly expiresInS?: number;
|
|
1204
|
+
}
|
|
1205
|
+
/** Options of {@link createTokenCache}. @public */
|
|
1206
|
+
interface TokenCacheOptions {
|
|
1207
|
+
/** Fetch a fresh token. Receives the signal of the caller that started the fetch. */
|
|
1208
|
+
readonly fetchToken: (signal?: AbortSignal) => Promise<FetchedToken>;
|
|
1209
|
+
/** Refresh this long before expiry. Default 60_000. */
|
|
1210
|
+
readonly marginMs?: number;
|
|
1211
|
+
/** Default 7200. */
|
|
1212
|
+
readonly defaultTtlS?: number;
|
|
1213
|
+
readonly now?: () => number;
|
|
1214
|
+
}
|
|
1215
|
+
/** A cached expiring token. @public */
|
|
1216
|
+
interface TokenCache {
|
|
1217
|
+
/**
|
|
1218
|
+
* The cached token, or one fetch shared by every concurrent caller. `force` skips the cache
|
|
1219
|
+
* (but still joins a fetch already in flight). The signal of the caller that starts a fetch
|
|
1220
|
+
* governs it; later callers' signals do not cancel their wait.
|
|
1221
|
+
*/
|
|
1222
|
+
get(options?: {
|
|
1223
|
+
force?: boolean;
|
|
1224
|
+
signal?: AbortSignal;
|
|
1225
|
+
}): Promise<string>;
|
|
1226
|
+
/** Forget the cached token (after a 401, for example). */
|
|
1227
|
+
clear(): void;
|
|
1228
|
+
}
|
|
1229
|
+
/** Build a {@link TokenCache}. A failed fetch rejects every waiting caller and is not cached. @public */
|
|
1230
|
+
declare function createTokenCache(options: TokenCacheOptions): TokenCache;
|
|
1231
|
+
|
|
1104
1232
|
/**
|
|
1105
1233
|
* `GatewayConfigurationError` — shared base for per-adapter configuration
|
|
1106
1234
|
* errors (roadmap M0/M2).
|
|
@@ -1933,6 +2061,42 @@ interface MediaUnderstandingOptions {
|
|
|
1933
2061
|
/** Wraps a handler: the event it receives has the transcript or description appended to text. */
|
|
1934
2062
|
declare function withMediaUnderstanding(handler: GatewayHandler, options: MediaUnderstandingOptions): GatewayHandler;
|
|
1935
2063
|
|
|
2064
|
+
/**
|
|
2065
|
+
* Options for {@link ReconnectBackoff}. Delay fields default as documented on `ReconnectPolicy`.
|
|
2066
|
+
*
|
|
2067
|
+
* @public
|
|
2068
|
+
*/
|
|
2069
|
+
interface ReconnectBackoffOptions extends ReconnectPolicy {
|
|
2070
|
+
/** A connection open at least this long resets the delay. Default 60_000. */
|
|
2071
|
+
readonly stableAfterMs?: number;
|
|
2072
|
+
/** Clock in ms; defaults to `Date.now`. */
|
|
2073
|
+
readonly now?: () => number;
|
|
2074
|
+
}
|
|
2075
|
+
/**
|
|
2076
|
+
* Reconnect delay for an adapter that holds a long-lived connection: `min(initialDelayMs *
|
|
2077
|
+
* factor^(n-1), maxDelayMs)` for attempt n, reset after a connection that stayed open for
|
|
2078
|
+
* `stableAfterMs`.
|
|
2079
|
+
*
|
|
2080
|
+
* @public
|
|
2081
|
+
*/
|
|
2082
|
+
declare class ReconnectBackoff {
|
|
2083
|
+
private readonly initialDelayMs;
|
|
2084
|
+
private readonly maxDelayMs;
|
|
2085
|
+
private readonly factor;
|
|
2086
|
+
private readonly maxAttempts;
|
|
2087
|
+
private readonly stableAfterMs;
|
|
2088
|
+
private readonly now;
|
|
2089
|
+
private attempts;
|
|
2090
|
+
private openedAt;
|
|
2091
|
+
constructor(options?: ReconnectBackoffOptions);
|
|
2092
|
+
/** Call when the connection opens. */
|
|
2093
|
+
opened(): void;
|
|
2094
|
+
/** Delay before the next attempt; `undefined` once `maxAttempts` is spent. Resets first if the last connection was stable. */
|
|
2095
|
+
nextDelayMs(): number | undefined;
|
|
2096
|
+
/** Back to the initial delay. */
|
|
2097
|
+
reset(): void;
|
|
2098
|
+
}
|
|
2099
|
+
|
|
1936
2100
|
/** A credential shape this module masks, and the cost of matching it. */
|
|
1937
2101
|
interface CoveredShape {
|
|
1938
2102
|
/** The platform and field, for the reader of the table. */
|
|
@@ -2305,11 +2469,18 @@ declare function scanFences(text: string): readonly FenceRegion[];
|
|
|
2305
2469
|
*
|
|
2306
2470
|
* @internal
|
|
2307
2471
|
*/
|
|
2472
|
+
/** The unit `partLimit` is measured in. */
|
|
2473
|
+
interface SplitKeepingRowsOptions {
|
|
2474
|
+
/** How `partLimit` is measured. Default "utf16" (UTF-16 units). */
|
|
2475
|
+
readonly unit?: "utf16" | "codepoint";
|
|
2476
|
+
}
|
|
2308
2477
|
/**
|
|
2309
|
-
* Parts of at most `partLimit` units,
|
|
2310
|
-
* Shared by the SMS and LINE splitters (text no
|
|
2478
|
+
* Parts of at most `partLimit` units (UTF-16 units, or code points with `unit: "codepoint"`), cut
|
|
2479
|
+
* at grapheme boundaries and before straddled rows. Shared by the SMS and LINE splitters (text no
|
|
2480
|
+
* longer than a part is theirs to handle). In code-point mode `partLimit` must be a positive
|
|
2481
|
+
* integer and a single grapheme longer than it throws `RangeError`.
|
|
2311
2482
|
*/
|
|
2312
|
-
declare function splitKeepingRows(text: string, partLimit: number): string[];
|
|
2483
|
+
declare function splitKeepingRows(text: string, partLimit: number, options?: SplitKeepingRowsOptions): string[];
|
|
2313
2484
|
|
|
2314
2485
|
/** The outcome of delivering one event to the runner's handlers. */
|
|
2315
2486
|
type DeliverOutcome = "ok" | "no_handler" | "handler_threw";
|
|
@@ -2457,4 +2628,4 @@ interface WebhookHandlerOptions {
|
|
|
2457
2628
|
*/
|
|
2458
2629
|
declare function createWebhookHandler(options: WebhookHandlerOptions): (request: Request) => Promise<Response>;
|
|
2459
2630
|
|
|
2460
|
-
export { type AccessPolicyOptions, type AdapterCapabilities, type AdapterState, type AgentBindingRule, type AgentBindings, type AgentBindingsOptions, type AgentIdStrategy, type BaseMessageEvent, BasePlatformAdapter, type BuiltChannel, type BuzzMessageEvent, CREDENTIAL_SHAPES, type ChannelConfigField, type ChannelConfigInput, type ChannelConfigReaders, type ChannelDescriptor, type ChannelEntry, type ChannelRejection, type ChannelRendering, type ChannelWebhook, type ChatCommand, type ChunkByGraphemeOptions, type ChunkTextOptions, type ClickClackMessageEvent, type ConnectFailure, type CoveredShape, type CreateChannelsResult, type CredentialStore, DEFAULT_WEBHOOK_MAX_BYTES, type DeliveryRequest, DeliveryRouter, type DeliveryTarget, type DiscordMessageEvent, type DmPolicy, type DmScope, type EmailMessageEvent, type EnvConfig, type FeishuLarkMessageEvent, type FenceRegion, GatewayConfigurationError, type GatewayConfigurationErrorOptions, type GatewayContext, type GatewayHandler, type GatewayHook, GatewayLifecycleError, type GatewayLifecycleErrorOptions, GatewayRunner, type GatewayRunnerOptions, type GoogleChatMessageEvent, type HookDecision, HookExecutor, type HookName, type IMessageMessageEvent, type InboundAudio, type IngestResult, type IrcMessageEvent, type LineMessageEvent, type ListenableApp, type ListenerLike, type MatrixMessageEvent, type MattermostMessageEvent, type MediaUnderstandingOptions, type MessageEvent, type NextcloudTalkMessageEvent, type NostrMessageEvent, type OnErrorContext, type OutboundAttachment, type OutboundMessage, type PairingStore, type ParsedChatCommand, type PlatformEventRegistry, type PlatformName, type PostOutboundContext, type PreInboundContext, type QQMessageEvent, type RaftMessageEvent, type RawBodyCaptureOptions, type RawBodyRequest, type ReconnectPolicy, type SMSMessageEvent, type ScopedStrategyOptions, SeenIds, type SendResult, type SenderIdentity, SessionRouter, type SignalMessageEvent, type SlackMessageEvent, type StartResult, type SynologyChatMessageEvent, type TeamsMessageEvent, type TelegramMessageEvent, type TlonUrbitMessageEvent, type TwitchMessageEvent, type UncoveredShape, type WeChatMessageEvent, type WeComMessageEvent, type WebhookAnswer, type WebhookHandlerOptions, type WebhookRequest, WeixinAdapterBase, type WeixinAdapterConfig, type WeixinFetch, type WeixinSendRequest, type WeixinWebhookAnswer, type WhatsAppMessageEvent, type XMessageEvent, type XThreadTweet, type YuanbaoMessageEvent, type ZaloMessageEvent, type ZaloPersonalMessageEvent, bindingStrategy, channelConfigReaders, channelRendering, chunkByGrapheme, chunkText, commandHook, configFromEnv, createAccessPolicyHook, createAgentBindings, createChannels, createFileCredentialStore, createFilePairingStore, createWebhookHandler, defaultStrategy, helpText, isAuthenticatedSender, listenerLifecycle, loadPeer, maskSecrets, maskShapes, parseChatCommand, parseFlatXml, rawBodyCapture, redactSecrets, scanFences, scopedStrategy, selectVariant, senderKey, splitKeepingRows, statusForDeliver, toDialect, withMediaUnderstanding };
|
|
2631
|
+
export { type AccessPolicyOptions, type AdapterCapabilities, type AdapterState, type AgentBindingRule, type AgentBindings, type AgentBindingsOptions, type AgentIdStrategy, type BaseMessageEvent, BasePlatformAdapter, type BuiltChannel, type BuzzMessageEvent, CREDENTIAL_SHAPES, type ChannelConfigField, type ChannelConfigInput, type ChannelConfigReaders, type ChannelDescriptor, type ChannelEntry, type ChannelRejection, type ChannelRendering, type ChannelWebhook, type ChatCommand, type ChunkByGraphemeOptions, type ChunkTextOptions, type ClickClackMessageEvent, type ConnectFailure, type CoveredShape, type CreateChannelsResult, type CredentialStore, DEFAULT_WEBHOOK_MAX_BYTES, type DecodedJwt, type DeliveryRequest, DeliveryRouter, type DeliveryTarget, type DiscordMessageEvent, type DmPolicy, type DmScope, type EmailMessageEvent, type EnvConfig, type FeishuLarkMessageEvent, type FenceRegion, type FetchedToken, GatewayConfigurationError, type GatewayConfigurationErrorOptions, type GatewayContext, type GatewayHandler, type GatewayHook, GatewayLifecycleError, type GatewayLifecycleErrorOptions, GatewayRunner, type GatewayRunnerOptions, type GoogleChatMessageEvent, type HookDecision, HookExecutor, type HookName, type IMessageMessageEvent, type InboundAudio, type IngestResult, type IrcMessageEvent, type JwksKeySet, type JwksKeySetOptions, type JwksLookup, type LineMessageEvent, type ListenableApp, type ListenerLike, type MatrixMessageEvent, type MattermostMessageEvent, type MediaUnderstandingOptions, type MessageEvent, type NextcloudTalkMessageEvent, type NostrMessageEvent, type OnErrorContext, type OutboundAttachment, type OutboundMessage, type PairingStore, type ParsedChatCommand, type PlatformEventRegistry, type PlatformName, type PostOutboundContext, type PreInboundContext, type QQMessageEvent, type RaftMessageEvent, type RawBodyCaptureOptions, type RawBodyRequest, ReconnectBackoff, type ReconnectBackoffOptions, type ReconnectPolicy, type SMSMessageEvent, type ScopedStrategyOptions, SeenIds, type SendError, type SendErrorCode, type SendResult, type SenderIdentity, SessionRouter, type SignalMessageEvent, type SlackMessageEvent, type SplitKeepingRowsOptions, type StartResult, type SynologyChatMessageEvent, type TeamsMessageEvent, type TelegramMessageEvent, type TlonUrbitMessageEvent, type TokenCache, type TokenCacheOptions, type TwitchMessageEvent, type UncoveredShape, type VerifyJwtResult, type WeChatMessageEvent, type WeComMessageEvent, type WebhookAnswer, type WebhookHandlerOptions, type WebhookRequest, WeixinAdapterBase, type WeixinAdapterConfig, type WeixinFetch, type WeixinSendRequest, type WeixinWebhookAnswer, type WhatsAppMessageEvent, type XMessageEvent, type XThreadTweet, type YuanbaoMessageEvent, type ZaloMessageEvent, type ZaloPersonalMessageEvent, bindingStrategy, channelConfigReaders, channelRendering, chunkByGrapheme, chunkText, commandHook, configFromEnv, createAccessPolicyHook, createAgentBindings, createChannels, createFileCredentialStore, createFilePairingStore, createTokenCache, createWebhookHandler, decodeJwt, defaultStrategy, helpText, isAuthenticatedSender, jwksKeySet, listenerLifecycle, loadPeer, maskSecrets, maskShapes, parseChatCommand, parseFlatXml, rawBodyCapture, redactSecrets, scanFences, scopedStrategy, selectVariant, sendErrorFromHttp, senderKey, splitKeepingRows, statusForDeliver, toDialect, verifyRs256Jwt, withMediaUnderstanding };
|