@theokit/gateway 0.20.0 → 0.22.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/dist/index.d.cts CHANGED
@@ -1101,6 +1101,83 @@ declare abstract class WeixinAdapterBase extends BasePlatformAdapter {
1101
1101
  */
1102
1102
  declare function parseFlatXml(xml: string): Record<string, string>;
1103
1103
 
1104
+ /**
1105
+ * `GatewayConfigurationError` — shared base for per-adapter configuration
1106
+ * errors (roadmap M0/M2).
1107
+ *
1108
+ * Every platform adapter previously defined an identical
1109
+ * `ConfigurationError extends Error` (same `code`/`detail` fields, same
1110
+ * options interface, same `` `${pkg}: ${code}` `` default message) — only the
1111
+ * package prefix differed. This base single-sources that contract. Adapters
1112
+ * extend it, pin their prefix, and keep `name = "ConfigurationError"` plus
1113
+ * their own subclasses (`SDKNotInstalledError`, `BackendNotInstalledError`, …).
1114
+ *
1115
+ * @public
1116
+ */
1117
+ /** Public input shape for the {@link GatewayConfigurationError} constructor. */
1118
+ interface GatewayConfigurationErrorOptions {
1119
+ readonly code: string;
1120
+ readonly message?: string;
1121
+ readonly detail?: string;
1122
+ }
1123
+ /**
1124
+ * Base configuration error. Not thrown directly by adapters — they subclass it
1125
+ * with a fixed package prefix.
1126
+ */
1127
+ declare class GatewayConfigurationError extends Error {
1128
+ readonly name: string;
1129
+ readonly code: string;
1130
+ readonly detail: string | undefined;
1131
+ /**
1132
+ * @param prefix Package prefix used in the default message (e.g. `"gateway-line"`).
1133
+ * @param opts `code` (required), optional explicit `message`, optional `detail`.
1134
+ */
1135
+ constructor(prefix: string, opts: GatewayConfigurationErrorOptions);
1136
+ }
1137
+
1138
+ /**
1139
+ * `channelConfigReaders` — the config readers every channel's `create` needs, written once.
1140
+ *
1141
+ * Each channel package used to carry its own copy of `invalid`, `readString`, `requiredString`
1142
+ * and friends; only the error prefix differed. The readers throw a configuration error coded
1143
+ * `invalid_config` with the message `${prefix}: config.${key} must be ${expected}`.
1144
+ *
1145
+ * @public
1146
+ */
1147
+
1148
+ /** A channel's config object, as `create` receives it. */
1149
+ type ChannelConfigInput = Readonly<Record<string, unknown>>;
1150
+ /** The readers bound to one package prefix. */
1151
+ interface ChannelConfigReaders {
1152
+ /** Builds (does not throw) the `invalid_config` error for `key`. */
1153
+ invalid(key: string, expected: string): GatewayConfigurationError;
1154
+ /** `undefined`, `null` and `""` are absent. */
1155
+ isAbsent(value: unknown): boolean;
1156
+ /** An optional string; absent gives `undefined`, a non-string throws. */
1157
+ readString(config: ChannelConfigInput, key: string): string | undefined;
1158
+ /** A required string; absent, empty or a non-string throws. */
1159
+ requiredString(config: ChannelConfigInput, key: string): string;
1160
+ /** An optional boolean; absent gives `undefined`, a non-boolean throws. */
1161
+ readBoolean(config: ChannelConfigInput, key: string): boolean | undefined;
1162
+ /**
1163
+ * An optional function; absent gives `undefined`, a non-function throws. Only callability is
1164
+ * checked: the caller names the signature `T` and is responsible for it.
1165
+ */
1166
+ readFunction<T extends (...args: never[]) => unknown>(config: ChannelConfigInput, key: string): T | undefined;
1167
+ }
1168
+ /**
1169
+ * Returns the config readers for a package.
1170
+ *
1171
+ * @param prefix Package prefix in every message, e.g. `"gateway-line"`.
1172
+ * @param createError Builds the error to throw; defaults to `GatewayConfigurationError`. Pass a
1173
+ * package's own subclass to keep its `instanceof` contract.
1174
+ */
1175
+ declare function channelConfigReaders(prefix: string, createError?: (options: {
1176
+ readonly code: string;
1177
+ readonly message: string;
1178
+ readonly detail: string;
1179
+ }) => GatewayConfigurationError): ChannelConfigReaders;
1180
+
1104
1181
  /**
1105
1182
  * `ChannelDescriptor` — one platform's channel described as data (FR-001, ADR D1 of B-018).
1106
1183
  *
@@ -1240,11 +1317,12 @@ interface EnvConfig {
1240
1317
  /** Values of present fields marked secret, for a log mask. Never logged. */
1241
1318
  readonly secrets: readonly string[];
1242
1319
  }
1320
+ type Env = Readonly<Record<string, string | undefined>>;
1243
1321
  /**
1244
1322
  * Read a descriptor's fields from `env`, using `prefix + field.env` as the variable name. Fields
1245
1323
  * without `env` are skipped.
1246
1324
  */
1247
- declare function configFromEnv(descriptor: ChannelDescriptor, env: Readonly<Record<string, string | undefined>>, prefix?: string): EnvConfig;
1325
+ declare function configFromEnv(descriptor: ChannelDescriptor, env: Env, prefix?: string): EnvConfig;
1248
1326
  /**
1249
1327
  * The descriptor to use for `name`: the descriptor itself when `name` is undefined and it has no
1250
1328
  * variants, otherwise the named variant. Throws `unknown_channel_variant` for a name that is not a
@@ -1253,40 +1331,6 @@ declare function configFromEnv(descriptor: ChannelDescriptor, env: Readonly<Reco
1253
1331
  */
1254
1332
  declare function selectVariant(descriptor: ChannelDescriptor, name: string | undefined): ChannelDescriptor;
1255
1333
 
1256
- /**
1257
- * `GatewayConfigurationError` — shared base for per-adapter configuration
1258
- * errors (roadmap M0/M2).
1259
- *
1260
- * Every platform adapter previously defined an identical
1261
- * `ConfigurationError extends Error` (same `code`/`detail` fields, same
1262
- * options interface, same `` `${pkg}: ${code}` `` default message) — only the
1263
- * package prefix differed. This base single-sources that contract. Adapters
1264
- * extend it, pin their prefix, and keep `name = "ConfigurationError"` plus
1265
- * their own subclasses (`SDKNotInstalledError`, `BackendNotInstalledError`, …).
1266
- *
1267
- * @public
1268
- */
1269
- /** Public input shape for the {@link GatewayConfigurationError} constructor. */
1270
- interface GatewayConfigurationErrorOptions {
1271
- readonly code: string;
1272
- readonly message?: string;
1273
- readonly detail?: string;
1274
- }
1275
- /**
1276
- * Base configuration error. Not thrown directly by adapters — they subclass it
1277
- * with a fixed package prefix.
1278
- */
1279
- declare class GatewayConfigurationError extends Error {
1280
- readonly name: string;
1281
- readonly code: string;
1282
- readonly detail: string | undefined;
1283
- /**
1284
- * @param prefix Package prefix used in the default message (e.g. `"gateway-line"`).
1285
- * @param opts `code` (required), optional explicit `message`, optional `detail`.
1286
- */
1287
- constructor(prefix: string, opts: GatewayConfigurationErrorOptions);
1288
- }
1289
-
1290
1334
  /**
1291
1335
  * `createChannels` — build every configured channel from its descriptor (FR-002 of B-018).
1292
1336
  *
@@ -1303,6 +1347,11 @@ interface ChannelEntry {
1303
1347
  readonly descriptor: ChannelDescriptor<BasePlatformAdapter>;
1304
1348
  /** Values keyed by the descriptor's field keys. Absent means every required field is missing. */
1305
1349
  readonly config?: Readonly<Record<string, unknown>>;
1350
+ /**
1351
+ * The prefix passed to `configFromEnv` for this entry, so a missing field's rejection names its
1352
+ * full environment variable. Defaults to `""`.
1353
+ */
1354
+ readonly envPrefix?: string;
1306
1355
  }
1307
1356
  /** A channel that was not built, and the configuration error that says why. */
1308
1357
  interface ChannelRejection {
@@ -1933,6 +1982,22 @@ declare function redactSecrets(value: unknown): string;
1933
1982
  */
1934
1983
  declare function maskSecrets(text: string, secrets: ReadonlyArray<string>): string;
1935
1984
 
1985
+ /**
1986
+ * A small key/value store for credentials an adapter must keep across restarts, such as a rotated
1987
+ * OAuth refresh token.
1988
+ *
1989
+ * @public
1990
+ */
1991
+ /** Reads and writes one string credential per key. @public */
1992
+ interface CredentialStore {
1993
+ /** The stored value, or `undefined` when the key was never set. */
1994
+ get(key: string): Promise<string | undefined>;
1995
+ /** Store `value` under `key`, replacing any earlier value. */
1996
+ set(key: string, value: string): Promise<void>;
1997
+ }
1998
+ /** One file per key under `dir`, mode 0600, written to a temp file and renamed. @public */
1999
+ declare function createFileCredentialStore(dir: string): CredentialStore;
2000
+
1936
2001
  /**
1937
2002
  * `SessionRouter` — pure routing logic: `MessageEvent → agentId`
1938
2003
  * (T2.1, ADR D174).
@@ -2007,6 +2072,41 @@ declare function createAgentBindings(options: AgentBindingsOptions): AgentBindin
2007
2072
  /** Prefixes another strategy's key with the bound agent, so two agents never share a session. */
2008
2073
  declare function bindingStrategy(bindings: AgentBindings, inner: AgentIdStrategy): AgentIdStrategy;
2009
2074
 
2075
+ /**
2076
+ * `scopedStrategy` — session keys with DM scopes, peer links and account labels.
2077
+ *
2078
+ * `dm` is always the second key segment, so no label or peer name can make a
2079
+ * DM key equal a group (`grp`) or thread (`tpc`) key. Every segment is encoded
2080
+ * with `encodeURIComponent` and joined with `:`, which it never emits, so the
2081
+ * key mapping is injective. Linked peers and `main` use a leading `@` segment,
2082
+ * which no encoded platform can start with (`@` encodes to `%40`).
2083
+ *
2084
+ * @public
2085
+ */
2086
+
2087
+ /** How DMs are keyed: one conversation, per peer, per channel and peer, or per account too. */
2088
+ type DmScope = "main" | "per-peer" | "per-channel-peer" | "per-account-channel-peer";
2089
+ /** Options for {@link scopedStrategy}. */
2090
+ interface ScopedStrategyOptions {
2091
+ readonly dmScope: DmScope;
2092
+ /** `<platform>:<senderId>` to a peer name. Used by `per-peer`. */
2093
+ readonly peerLinks?: ReadonlyMap<string, string>;
2094
+ /** Required when `dmScope` is `per-account-channel-peer`. */
2095
+ readonly accountLabel?: string;
2096
+ /** Group key: one per channel (default) or one per channel and sender. */
2097
+ readonly groupScope?: "channel" | "channel-sender";
2098
+ }
2099
+ /**
2100
+ * Builds a strategy for the chosen DM scope. Keys:
2101
+ * `main` → `_m-dm`; `per-peer` linked → `_p-dm-<peer>`, unlinked → the
2102
+ * per-channel-peer key; `per-channel-peer` → `<platform>-dm-<sender>`;
2103
+ * `per-account-channel-peer` → `<platform>-dm-<account>-<sender>`.
2104
+ * Groups are `<platform>-grp-<channel>[-<sender>]`, topic threads
2105
+ * `<platform>-tpc-<channel>-<topic>`. Every segment is escaped with `sanitize`.
2106
+ * Throws `GatewayConfigurationError` (`invalid_session_scope`) on bad options, never per event.
2107
+ */
2108
+ declare function scopedStrategy(options: ScopedStrategyOptions): AgentIdStrategy;
2109
+
2010
2110
  /**
2011
2111
  * What `ChatPresenter` needs to know about one platform: how to rewrite the text, and which
2012
2112
  * `format` to declare on the message (B-019 FR-001, FR-002).
@@ -2346,4 +2446,4 @@ interface WebhookHandlerOptions {
2346
2446
  */
2347
2447
  declare function createWebhookHandler(options: WebhookHandlerOptions): (request: Request) => Promise<Response>;
2348
2448
 
2349
- 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 ChannelDescriptor, type ChannelEntry, type ChannelRejection, type ChannelRendering, type ChannelWebhook, type ChatCommand, type ChunkByGraphemeOptions, type ChunkTextOptions, type ClickClackMessageEvent, type ConnectFailure, type CoveredShape, type CreateChannelsResult, DEFAULT_WEBHOOK_MAX_BYTES, type DeliveryRequest, DeliveryRouter, type DeliveryTarget, type DiscordMessageEvent, type DmPolicy, 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, 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, channelRendering, chunkByGrapheme, chunkText, commandHook, configFromEnv, createAccessPolicyHook, createAgentBindings, createChannels, createFilePairingStore, createWebhookHandler, defaultStrategy, helpText, isAuthenticatedSender, listenerLifecycle, loadPeer, maskSecrets, maskShapes, parseChatCommand, parseFlatXml, rawBodyCapture, redactSecrets, scanFences, selectVariant, senderKey, splitKeepingRows, statusForDeliver, toDialect, withMediaUnderstanding };
2449
+ 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 };
package/dist/index.d.ts CHANGED
@@ -1101,6 +1101,83 @@ declare abstract class WeixinAdapterBase extends BasePlatformAdapter {
1101
1101
  */
1102
1102
  declare function parseFlatXml(xml: string): Record<string, string>;
1103
1103
 
1104
+ /**
1105
+ * `GatewayConfigurationError` — shared base for per-adapter configuration
1106
+ * errors (roadmap M0/M2).
1107
+ *
1108
+ * Every platform adapter previously defined an identical
1109
+ * `ConfigurationError extends Error` (same `code`/`detail` fields, same
1110
+ * options interface, same `` `${pkg}: ${code}` `` default message) — only the
1111
+ * package prefix differed. This base single-sources that contract. Adapters
1112
+ * extend it, pin their prefix, and keep `name = "ConfigurationError"` plus
1113
+ * their own subclasses (`SDKNotInstalledError`, `BackendNotInstalledError`, …).
1114
+ *
1115
+ * @public
1116
+ */
1117
+ /** Public input shape for the {@link GatewayConfigurationError} constructor. */
1118
+ interface GatewayConfigurationErrorOptions {
1119
+ readonly code: string;
1120
+ readonly message?: string;
1121
+ readonly detail?: string;
1122
+ }
1123
+ /**
1124
+ * Base configuration error. Not thrown directly by adapters — they subclass it
1125
+ * with a fixed package prefix.
1126
+ */
1127
+ declare class GatewayConfigurationError extends Error {
1128
+ readonly name: string;
1129
+ readonly code: string;
1130
+ readonly detail: string | undefined;
1131
+ /**
1132
+ * @param prefix Package prefix used in the default message (e.g. `"gateway-line"`).
1133
+ * @param opts `code` (required), optional explicit `message`, optional `detail`.
1134
+ */
1135
+ constructor(prefix: string, opts: GatewayConfigurationErrorOptions);
1136
+ }
1137
+
1138
+ /**
1139
+ * `channelConfigReaders` — the config readers every channel's `create` needs, written once.
1140
+ *
1141
+ * Each channel package used to carry its own copy of `invalid`, `readString`, `requiredString`
1142
+ * and friends; only the error prefix differed. The readers throw a configuration error coded
1143
+ * `invalid_config` with the message `${prefix}: config.${key} must be ${expected}`.
1144
+ *
1145
+ * @public
1146
+ */
1147
+
1148
+ /** A channel's config object, as `create` receives it. */
1149
+ type ChannelConfigInput = Readonly<Record<string, unknown>>;
1150
+ /** The readers bound to one package prefix. */
1151
+ interface ChannelConfigReaders {
1152
+ /** Builds (does not throw) the `invalid_config` error for `key`. */
1153
+ invalid(key: string, expected: string): GatewayConfigurationError;
1154
+ /** `undefined`, `null` and `""` are absent. */
1155
+ isAbsent(value: unknown): boolean;
1156
+ /** An optional string; absent gives `undefined`, a non-string throws. */
1157
+ readString(config: ChannelConfigInput, key: string): string | undefined;
1158
+ /** A required string; absent, empty or a non-string throws. */
1159
+ requiredString(config: ChannelConfigInput, key: string): string;
1160
+ /** An optional boolean; absent gives `undefined`, a non-boolean throws. */
1161
+ readBoolean(config: ChannelConfigInput, key: string): boolean | undefined;
1162
+ /**
1163
+ * An optional function; absent gives `undefined`, a non-function throws. Only callability is
1164
+ * checked: the caller names the signature `T` and is responsible for it.
1165
+ */
1166
+ readFunction<T extends (...args: never[]) => unknown>(config: ChannelConfigInput, key: string): T | undefined;
1167
+ }
1168
+ /**
1169
+ * Returns the config readers for a package.
1170
+ *
1171
+ * @param prefix Package prefix in every message, e.g. `"gateway-line"`.
1172
+ * @param createError Builds the error to throw; defaults to `GatewayConfigurationError`. Pass a
1173
+ * package's own subclass to keep its `instanceof` contract.
1174
+ */
1175
+ declare function channelConfigReaders(prefix: string, createError?: (options: {
1176
+ readonly code: string;
1177
+ readonly message: string;
1178
+ readonly detail: string;
1179
+ }) => GatewayConfigurationError): ChannelConfigReaders;
1180
+
1104
1181
  /**
1105
1182
  * `ChannelDescriptor` — one platform's channel described as data (FR-001, ADR D1 of B-018).
1106
1183
  *
@@ -1240,11 +1317,12 @@ interface EnvConfig {
1240
1317
  /** Values of present fields marked secret, for a log mask. Never logged. */
1241
1318
  readonly secrets: readonly string[];
1242
1319
  }
1320
+ type Env = Readonly<Record<string, string | undefined>>;
1243
1321
  /**
1244
1322
  * Read a descriptor's fields from `env`, using `prefix + field.env` as the variable name. Fields
1245
1323
  * without `env` are skipped.
1246
1324
  */
1247
- declare function configFromEnv(descriptor: ChannelDescriptor, env: Readonly<Record<string, string | undefined>>, prefix?: string): EnvConfig;
1325
+ declare function configFromEnv(descriptor: ChannelDescriptor, env: Env, prefix?: string): EnvConfig;
1248
1326
  /**
1249
1327
  * The descriptor to use for `name`: the descriptor itself when `name` is undefined and it has no
1250
1328
  * variants, otherwise the named variant. Throws `unknown_channel_variant` for a name that is not a
@@ -1253,40 +1331,6 @@ declare function configFromEnv(descriptor: ChannelDescriptor, env: Readonly<Reco
1253
1331
  */
1254
1332
  declare function selectVariant(descriptor: ChannelDescriptor, name: string | undefined): ChannelDescriptor;
1255
1333
 
1256
- /**
1257
- * `GatewayConfigurationError` — shared base for per-adapter configuration
1258
- * errors (roadmap M0/M2).
1259
- *
1260
- * Every platform adapter previously defined an identical
1261
- * `ConfigurationError extends Error` (same `code`/`detail` fields, same
1262
- * options interface, same `` `${pkg}: ${code}` `` default message) — only the
1263
- * package prefix differed. This base single-sources that contract. Adapters
1264
- * extend it, pin their prefix, and keep `name = "ConfigurationError"` plus
1265
- * their own subclasses (`SDKNotInstalledError`, `BackendNotInstalledError`, …).
1266
- *
1267
- * @public
1268
- */
1269
- /** Public input shape for the {@link GatewayConfigurationError} constructor. */
1270
- interface GatewayConfigurationErrorOptions {
1271
- readonly code: string;
1272
- readonly message?: string;
1273
- readonly detail?: string;
1274
- }
1275
- /**
1276
- * Base configuration error. Not thrown directly by adapters — they subclass it
1277
- * with a fixed package prefix.
1278
- */
1279
- declare class GatewayConfigurationError extends Error {
1280
- readonly name: string;
1281
- readonly code: string;
1282
- readonly detail: string | undefined;
1283
- /**
1284
- * @param prefix Package prefix used in the default message (e.g. `"gateway-line"`).
1285
- * @param opts `code` (required), optional explicit `message`, optional `detail`.
1286
- */
1287
- constructor(prefix: string, opts: GatewayConfigurationErrorOptions);
1288
- }
1289
-
1290
1334
  /**
1291
1335
  * `createChannels` — build every configured channel from its descriptor (FR-002 of B-018).
1292
1336
  *
@@ -1303,6 +1347,11 @@ interface ChannelEntry {
1303
1347
  readonly descriptor: ChannelDescriptor<BasePlatformAdapter>;
1304
1348
  /** Values keyed by the descriptor's field keys. Absent means every required field is missing. */
1305
1349
  readonly config?: Readonly<Record<string, unknown>>;
1350
+ /**
1351
+ * The prefix passed to `configFromEnv` for this entry, so a missing field's rejection names its
1352
+ * full environment variable. Defaults to `""`.
1353
+ */
1354
+ readonly envPrefix?: string;
1306
1355
  }
1307
1356
  /** A channel that was not built, and the configuration error that says why. */
1308
1357
  interface ChannelRejection {
@@ -1933,6 +1982,22 @@ declare function redactSecrets(value: unknown): string;
1933
1982
  */
1934
1983
  declare function maskSecrets(text: string, secrets: ReadonlyArray<string>): string;
1935
1984
 
1985
+ /**
1986
+ * A small key/value store for credentials an adapter must keep across restarts, such as a rotated
1987
+ * OAuth refresh token.
1988
+ *
1989
+ * @public
1990
+ */
1991
+ /** Reads and writes one string credential per key. @public */
1992
+ interface CredentialStore {
1993
+ /** The stored value, or `undefined` when the key was never set. */
1994
+ get(key: string): Promise<string | undefined>;
1995
+ /** Store `value` under `key`, replacing any earlier value. */
1996
+ set(key: string, value: string): Promise<void>;
1997
+ }
1998
+ /** One file per key under `dir`, mode 0600, written to a temp file and renamed. @public */
1999
+ declare function createFileCredentialStore(dir: string): CredentialStore;
2000
+
1936
2001
  /**
1937
2002
  * `SessionRouter` — pure routing logic: `MessageEvent → agentId`
1938
2003
  * (T2.1, ADR D174).
@@ -2007,6 +2072,41 @@ declare function createAgentBindings(options: AgentBindingsOptions): AgentBindin
2007
2072
  /** Prefixes another strategy's key with the bound agent, so two agents never share a session. */
2008
2073
  declare function bindingStrategy(bindings: AgentBindings, inner: AgentIdStrategy): AgentIdStrategy;
2009
2074
 
2075
+ /**
2076
+ * `scopedStrategy` — session keys with DM scopes, peer links and account labels.
2077
+ *
2078
+ * `dm` is always the second key segment, so no label or peer name can make a
2079
+ * DM key equal a group (`grp`) or thread (`tpc`) key. Every segment is encoded
2080
+ * with `encodeURIComponent` and joined with `:`, which it never emits, so the
2081
+ * key mapping is injective. Linked peers and `main` use a leading `@` segment,
2082
+ * which no encoded platform can start with (`@` encodes to `%40`).
2083
+ *
2084
+ * @public
2085
+ */
2086
+
2087
+ /** How DMs are keyed: one conversation, per peer, per channel and peer, or per account too. */
2088
+ type DmScope = "main" | "per-peer" | "per-channel-peer" | "per-account-channel-peer";
2089
+ /** Options for {@link scopedStrategy}. */
2090
+ interface ScopedStrategyOptions {
2091
+ readonly dmScope: DmScope;
2092
+ /** `<platform>:<senderId>` to a peer name. Used by `per-peer`. */
2093
+ readonly peerLinks?: ReadonlyMap<string, string>;
2094
+ /** Required when `dmScope` is `per-account-channel-peer`. */
2095
+ readonly accountLabel?: string;
2096
+ /** Group key: one per channel (default) or one per channel and sender. */
2097
+ readonly groupScope?: "channel" | "channel-sender";
2098
+ }
2099
+ /**
2100
+ * Builds a strategy for the chosen DM scope. Keys:
2101
+ * `main` → `_m-dm`; `per-peer` linked → `_p-dm-<peer>`, unlinked → the
2102
+ * per-channel-peer key; `per-channel-peer` → `<platform>-dm-<sender>`;
2103
+ * `per-account-channel-peer` → `<platform>-dm-<account>-<sender>`.
2104
+ * Groups are `<platform>-grp-<channel>[-<sender>]`, topic threads
2105
+ * `<platform>-tpc-<channel>-<topic>`. Every segment is escaped with `sanitize`.
2106
+ * Throws `GatewayConfigurationError` (`invalid_session_scope`) on bad options, never per event.
2107
+ */
2108
+ declare function scopedStrategy(options: ScopedStrategyOptions): AgentIdStrategy;
2109
+
2010
2110
  /**
2011
2111
  * What `ChatPresenter` needs to know about one platform: how to rewrite the text, and which
2012
2112
  * `format` to declare on the message (B-019 FR-001, FR-002).
@@ -2346,4 +2446,4 @@ interface WebhookHandlerOptions {
2346
2446
  */
2347
2447
  declare function createWebhookHandler(options: WebhookHandlerOptions): (request: Request) => Promise<Response>;
2348
2448
 
2349
- 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 ChannelDescriptor, type ChannelEntry, type ChannelRejection, type ChannelRendering, type ChannelWebhook, type ChatCommand, type ChunkByGraphemeOptions, type ChunkTextOptions, type ClickClackMessageEvent, type ConnectFailure, type CoveredShape, type CreateChannelsResult, DEFAULT_WEBHOOK_MAX_BYTES, type DeliveryRequest, DeliveryRouter, type DeliveryTarget, type DiscordMessageEvent, type DmPolicy, 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, 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, channelRendering, chunkByGrapheme, chunkText, commandHook, configFromEnv, createAccessPolicyHook, createAgentBindings, createChannels, createFilePairingStore, createWebhookHandler, defaultStrategy, helpText, isAuthenticatedSender, listenerLifecycle, loadPeer, maskSecrets, maskShapes, parseChatCommand, parseFlatXml, rawBodyCapture, redactSecrets, scanFences, selectVariant, senderKey, splitKeepingRows, statusForDeliver, toDialect, withMediaUnderstanding };
2449
+ 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 };
package/dist/index.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import { Security } from '@theokit/sdk';
2
- import { randomInt, randomUUID } from 'crypto';
2
+ import { randomInt, randomBytes, randomUUID } from 'crypto';
3
3
  import { readFileSync, mkdirSync, writeFileSync, renameSync } from 'fs';
4
4
  import { join } from 'path';
5
+ import { mkdir, writeFile, chmod, rename, unlink, readFile } from 'fs/promises';
5
6
 
6
7
  // src/text/fence.ts
7
8
  var MAY_FENCE = /^ {0,3}(?:`{3}|~{3})/m;
@@ -555,11 +556,6 @@ var WeixinAdapterBase = class extends BasePlatformAdapter {
555
556
  }
556
557
  };
557
558
 
558
- // src/channel/channel-descriptor.ts
559
- function isAuthenticatedSender(descriptor) {
560
- return descriptor.senderIdentity === "authenticated";
561
- }
562
-
563
559
  // src/errors/config-error.ts
564
560
  var GatewayConfigurationError = class extends Error {
565
561
  name = "GatewayConfigurationError";
@@ -576,18 +572,63 @@ var GatewayConfigurationError = class extends Error {
576
572
  }
577
573
  };
578
574
 
575
+ // src/channel/channel-config-readers.ts
576
+ function channelConfigReaders(prefix, createError = (options) => new GatewayConfigurationError(prefix, options)) {
577
+ const invalid2 = (key, expected) => createError({
578
+ code: "invalid_config",
579
+ message: `${prefix}: config.${key} must be ${expected}`,
580
+ detail: key
581
+ });
582
+ const isAbsent2 = (value) => value === void 0 || value === null || value === "";
583
+ const readString = (config, key) => {
584
+ const value = config[key];
585
+ if (isAbsent2(value)) return void 0;
586
+ if (typeof value !== "string") throw invalid2(key, "a string");
587
+ return value;
588
+ };
589
+ return {
590
+ invalid: invalid2,
591
+ isAbsent: isAbsent2,
592
+ readString,
593
+ requiredString(config, key) {
594
+ const value = config[key];
595
+ if (typeof value !== "string" || value === "") throw invalid2(key, "a non-empty string");
596
+ return value;
597
+ },
598
+ readBoolean(config, key) {
599
+ const value = config[key];
600
+ if (isAbsent2(value)) return void 0;
601
+ if (typeof value !== "boolean") throw invalid2(key, "a boolean");
602
+ return value;
603
+ },
604
+ readFunction(config, key) {
605
+ const value = config[key];
606
+ if (isAbsent2(value)) return void 0;
607
+ if (typeof value !== "function") throw invalid2(key, "a function");
608
+ return value;
609
+ }
610
+ };
611
+ }
612
+
613
+ // src/channel/channel-descriptor.ts
614
+ function isAuthenticatedSender(descriptor) {
615
+ return descriptor.senderIdentity === "authenticated";
616
+ }
617
+
579
618
  // src/channel/config-from-env.ts
619
+ function envVarName(field, prefix = "") {
620
+ return field.env === void 0 ? void 0 : prefix + field.env;
621
+ }
580
622
  function readValue(env, name) {
581
- const value = env[name]?.trim();
582
- return value ? value : void 0;
623
+ return env[name]?.trim() || void 0;
583
624
  }
584
625
  function configFromEnv(descriptor, env, prefix = "") {
585
626
  const config = {};
586
627
  const missing = [];
587
628
  const secrets = [];
588
629
  for (const field of descriptor.config) {
589
- if (field.env === void 0) continue;
590
- const name = prefix + field.env;
630
+ const name = envVarName(field, prefix);
631
+ if (name === void 0) continue;
591
632
  const value = readValue(env, name);
592
633
  if (value === void 0) {
593
634
  if (field.required) missing.push(name);
@@ -629,7 +670,10 @@ function isAbsent(value) {
629
670
  return value === void 0 || value === null || value === "";
630
671
  }
631
672
  function missingRequiredKeys(entry, values) {
632
- return entry.descriptor.config.filter((field) => field.required && isAbsent(values[field.key])).map((field) => field.key);
673
+ return entry.descriptor.config.filter((field) => field.required && isAbsent(values[field.key])).map((field) => {
674
+ const name = envVarName(field, entry.envPrefix);
675
+ return name === void 0 ? field.key : `${field.key} (env ${name})`;
676
+ });
633
677
  }
634
678
  function refused(platform, code, reason) {
635
679
  return {
@@ -1695,6 +1739,46 @@ function withMediaUnderstanding(handler, options) {
1695
1739
  return handler(wrapped, ctx);
1696
1740
  };
1697
1741
  }
1742
+ var KEY_PATTERN = /^[A-Za-z0-9._:-]+$(?![\s\S])/;
1743
+ function fileFor(dir, key) {
1744
+ if (!KEY_PATTERN.test(key) || key === "." || key === "..") {
1745
+ throw new GatewayConfigurationError("gateway", {
1746
+ code: "invalid_credential_key",
1747
+ message: `gateway: invalid_credential_key (keys match [A-Za-z0-9._:-]+): ${JSON.stringify(key)}`
1748
+ });
1749
+ }
1750
+ return join(dir, key.replaceAll(":", "%3A"));
1751
+ }
1752
+ function createFileCredentialStore(dir) {
1753
+ return {
1754
+ async get(key) {
1755
+ const path = fileFor(dir, key);
1756
+ try {
1757
+ return await readFile(path, "utf8");
1758
+ } catch (err) {
1759
+ if (err.code === "ENOENT") return void 0;
1760
+ throw new GatewayConfigurationError("gateway", {
1761
+ code: "credential_store_unreadable",
1762
+ message: `gateway: credential_store_unreadable: ${path}`,
1763
+ detail: err instanceof Error ? err.message : String(err)
1764
+ });
1765
+ }
1766
+ },
1767
+ async set(key, value) {
1768
+ const path = fileFor(dir, key);
1769
+ await mkdir(dir, { recursive: true });
1770
+ const tmp = `${path}.${randomBytes(6).toString("hex")}.tmp`;
1771
+ try {
1772
+ await writeFile(tmp, value, { mode: 384 });
1773
+ await chmod(tmp, 384);
1774
+ await rename(tmp, path);
1775
+ } catch (err) {
1776
+ await unlink(tmp).catch(() => void 0);
1777
+ throw err;
1778
+ }
1779
+ }
1780
+ };
1781
+ }
1698
1782
 
1699
1783
  // src/session/router.ts
1700
1784
  function defaultStrategy(event) {
@@ -1787,6 +1871,49 @@ function bindingStrategy(bindings, inner) {
1787
1871
  return (event) => `${sanitize(bindings.agentFor(event))}-${inner(event)}`;
1788
1872
  }
1789
1873
 
1874
+ // src/session/scoped-strategy.ts
1875
+ var join3 = (...segments) => segments.map(sanitize).join("-");
1876
+ function invalid(message, detail) {
1877
+ return new GatewayConfigurationError("gateway", {
1878
+ code: "invalid_session_scope",
1879
+ message: `gateway: invalid_session_scope: ${message}`,
1880
+ ...detail === void 0 ? {} : { detail }
1881
+ });
1882
+ }
1883
+ function scopedStrategy(options) {
1884
+ const { dmScope, peerLinks, accountLabel, groupScope = "channel" } = options;
1885
+ if (dmScope === "per-account-channel-peer" && (accountLabel === void 0 || accountLabel === "")) {
1886
+ throw invalid("per-account-channel-peer requires a non-empty accountLabel", "accountLabel");
1887
+ }
1888
+ if (peerLinks !== void 0) {
1889
+ for (const [from, peer] of peerLinks) {
1890
+ if (peer === "") throw invalid(`empty peer name for ${from}`, from);
1891
+ }
1892
+ }
1893
+ const dmKey = (platform, senderId) => {
1894
+ switch (dmScope) {
1895
+ case "main":
1896
+ return "_m-dm";
1897
+ case "per-peer": {
1898
+ const peer = peerLinks?.get(`${platform}:${senderId}`);
1899
+ return peer === void 0 ? join3(platform, "dm", senderId) : `_p-dm-${sanitize(peer)}`;
1900
+ }
1901
+ case "per-channel-peer":
1902
+ return join3(platform, "dm", senderId);
1903
+ case "per-account-channel-peer":
1904
+ return join3(platform, "dm", accountLabel ?? "", senderId);
1905
+ }
1906
+ };
1907
+ return (event) => {
1908
+ const { platform, channel, sender } = event;
1909
+ if (channel.type === "dm") return dmKey(platform, sender.id);
1910
+ if (channel.type === "thread" && channel.topicId !== void 0) {
1911
+ return join3(platform, "tpc", channel.id, channel.topicId);
1912
+ }
1913
+ return groupScope === "channel-sender" ? join3(platform, "grp", channel.id, sender.id) : join3(platform, "grp", channel.id);
1914
+ };
1915
+ }
1916
+
1790
1917
  // src/text/chunk.ts
1791
1918
  function searchBoundary(remaining, window, boundaries) {
1792
1919
  let cut = window;
@@ -2266,6 +2393,6 @@ async function dispatch(webhook, adapter, request) {
2266
2393
  return runDefault(webhook, adapter, request);
2267
2394
  }
2268
2395
 
2269
- export { BasePlatformAdapter, CREDENTIAL_SHAPES, DEFAULT_WEBHOOK_MAX_BYTES, DeliveryRouter, GatewayConfigurationError, GatewayLifecycleError, GatewayRunner, HookExecutor, SeenIds, SessionRouter, WeixinAdapterBase, bindingStrategy, channelRendering, chunkByGrapheme, chunkText, commandHook, configFromEnv, createAccessPolicyHook, createAgentBindings, createChannels, createFilePairingStore, createWebhookHandler, defaultStrategy, helpText, isAuthenticatedSender, listenerLifecycle, loadPeer, maskSecrets, maskShapes, parseChatCommand, parseFlatXml, rawBodyCapture, redactSecrets, scanFences, selectVariant, senderKey, splitKeepingRows, statusForDeliver, toDialect, withMediaUnderstanding };
2396
+ export { BasePlatformAdapter, CREDENTIAL_SHAPES, DEFAULT_WEBHOOK_MAX_BYTES, DeliveryRouter, GatewayConfigurationError, GatewayLifecycleError, GatewayRunner, HookExecutor, SeenIds, SessionRouter, WeixinAdapterBase, 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 };
2270
2397
  //# sourceMappingURL=index.js.map
2271
2398
  //# sourceMappingURL=index.js.map