botinabox 2.5.2 → 2.6.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.
Files changed (277) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +190 -190
  3. package/bin/botinabox.mjs +1 -1
  4. package/dist/{chunk-UACT2WXX.js → chunk-7AGWGYZC.js} +43 -5
  5. package/dist/cli.js +1 -1
  6. package/dist/connectors/google/index.d.ts +10 -1
  7. package/dist/connectors/google/index.js +1 -1
  8. package/dist/{gmail-connector-2FVYTQJH.js → gmail-connector-VP5FF56J.js} +2 -1
  9. package/dist/index.d.ts +64 -1
  10. package/dist/index.js +44 -10
  11. package/package.json +100 -100
  12. package/dist/channels/discord/adapter.d.ts +0 -32
  13. package/dist/channels/discord/adapter.js +0 -70
  14. package/dist/channels/discord/inbound.d.ts +0 -25
  15. package/dist/channels/discord/inbound.js +0 -24
  16. package/dist/channels/discord/models.d.ts +0 -8
  17. package/dist/channels/discord/models.js +0 -5
  18. package/dist/channels/discord/outbound.d.ts +0 -14
  19. package/dist/channels/discord/outbound.js +0 -38
  20. package/dist/channels/slack/adapter.d.ts +0 -33
  21. package/dist/channels/slack/adapter.js +0 -74
  22. package/dist/channels/slack/inbound.d.ts +0 -59
  23. package/dist/channels/slack/inbound.js +0 -96
  24. package/dist/channels/slack/models.d.ts +0 -9
  25. package/dist/channels/slack/models.js +0 -5
  26. package/dist/channels/slack/outbound.d.ts +0 -12
  27. package/dist/channels/slack/outbound.js +0 -18
  28. package/dist/channels/slack/transcribe.d.ts +0 -41
  29. package/dist/channels/slack/transcribe.js +0 -106
  30. package/dist/channels/webhook/adapter.d.ts +0 -23
  31. package/dist/channels/webhook/adapter.js +0 -86
  32. package/dist/channels/webhook/hmac.d.ts +0 -13
  33. package/dist/channels/webhook/hmac.js +0 -26
  34. package/dist/channels/webhook/models.d.ts +0 -9
  35. package/dist/channels/webhook/models.js +0 -5
  36. package/dist/channels/webhook/server.d.ts +0 -20
  37. package/dist/channels/webhook/server.js +0 -91
  38. package/dist/chat-pipeline-C-XlLGNl.d.ts +0 -648
  39. package/dist/chat-pipeline-CR1KF6eX.d.ts +0 -652
  40. package/dist/chat-pipeline-DisuC8SB.d.ts +0 -643
  41. package/dist/chunk-2LGXQPEA.js +0 -41
  42. package/dist/chunk-3X3YKI4T.js +0 -357
  43. package/dist/chunk-D47AIFOD.js +0 -351
  44. package/dist/chunk-DSNJKNEW.js +0 -328
  45. package/dist/chunk-GS2JFL6I.js +0 -144
  46. package/dist/chunk-J6S6QMUY.js +0 -144
  47. package/dist/chunk-QLA6YOFN.js +0 -22
  48. package/dist/cli/templates/config.yml.d.ts +0 -7
  49. package/dist/cli/templates/config.yml.js +0 -61
  50. package/dist/cli/templates/env.d.ts +0 -1
  51. package/dist/cli/templates/env.js +0 -30
  52. package/dist/cli/templates/index.ts.d.ts +0 -2
  53. package/dist/cli/templates/index.ts.js +0 -30
  54. package/dist/cli/templates/package.json.d.ts +0 -5
  55. package/dist/cli/templates/package.json.js +0 -28
  56. package/dist/connector-DDahQw-2.d.ts +0 -63
  57. package/dist/connectors/google/calendar-connector.d.ts +0 -40
  58. package/dist/connectors/google/calendar-connector.js +0 -243
  59. package/dist/connectors/google/gmail-connector.d.ts +0 -42
  60. package/dist/connectors/google/gmail-connector.js +0 -345
  61. package/dist/connectors/google/oauth.d.ts +0 -48
  62. package/dist/connectors/google/oauth.js +0 -112
  63. package/dist/connectors/google/types.d.ts +0 -78
  64. package/dist/connectors/google/types.js +0 -2
  65. package/dist/core/chat/auto-discovery.d.ts +0 -16
  66. package/dist/core/chat/auto-discovery.js +0 -54
  67. package/dist/core/chat/channel-registry.d.ts +0 -45
  68. package/dist/core/chat/channel-registry.js +0 -96
  69. package/dist/core/chat/chat-pipeline.d.ts +0 -113
  70. package/dist/core/chat/chat-pipeline.js +0 -395
  71. package/dist/core/chat/chat-responder.d.ts +0 -90
  72. package/dist/core/chat/chat-responder.js +0 -185
  73. package/dist/core/chat/formatter.d.ts +0 -11
  74. package/dist/core/chat/formatter.js +0 -60
  75. package/dist/core/chat/index.d.ts +0 -24
  76. package/dist/core/chat/index.js +0 -18
  77. package/dist/core/chat/message-interpreter.d.ts +0 -91
  78. package/dist/core/chat/message-interpreter.js +0 -166
  79. package/dist/core/chat/message-store.d.ts +0 -66
  80. package/dist/core/chat/message-store.js +0 -131
  81. package/dist/core/chat/notification-queue.d.ts +0 -34
  82. package/dist/core/chat/notification-queue.js +0 -111
  83. package/dist/core/chat/pipeline.d.ts +0 -38
  84. package/dist/core/chat/pipeline.js +0 -89
  85. package/dist/core/chat/policies.d.ts +0 -16
  86. package/dist/core/chat/policies.js +0 -25
  87. package/dist/core/chat/routing.d.ts +0 -17
  88. package/dist/core/chat/routing.js +0 -36
  89. package/dist/core/chat/session-key.d.ts +0 -30
  90. package/dist/core/chat/session-key.js +0 -65
  91. package/dist/core/chat/session-manager.d.ts +0 -17
  92. package/dist/core/chat/session-manager.js +0 -23
  93. package/dist/core/chat/text-chunker.d.ts +0 -9
  94. package/dist/core/chat/text-chunker.js +0 -48
  95. package/dist/core/chat/triage-router.d.ts +0 -75
  96. package/dist/core/chat/triage-router.js +0 -142
  97. package/dist/core/chat/types.d.ts +0 -5
  98. package/dist/core/chat/types.js +0 -5
  99. package/dist/core/config/defaults.d.ts +0 -2
  100. package/dist/core/config/defaults.js +0 -38
  101. package/dist/core/config/index.d.ts +0 -6
  102. package/dist/core/config/index.js +0 -4
  103. package/dist/core/config/interpolate.d.ts +0 -5
  104. package/dist/core/config/interpolate.js +0 -27
  105. package/dist/core/config/loader.d.ts +0 -24
  106. package/dist/core/config/loader.js +0 -59
  107. package/dist/core/config/schema.d.ts +0 -5
  108. package/dist/core/config/schema.js +0 -119
  109. package/dist/core/data/core-entity-contexts.d.ts +0 -14
  110. package/dist/core/data/core-entity-contexts.js +0 -197
  111. package/dist/core/data/core-migrations.d.ts +0 -5
  112. package/dist/core/data/core-migrations.js +0 -45
  113. package/dist/core/data/core-schema.d.ts +0 -6
  114. package/dist/core/data/core-schema.js +0 -454
  115. package/dist/core/data/data-store.d.ts +0 -67
  116. package/dist/core/data/data-store.js +0 -218
  117. package/dist/core/data/domain-entity-contexts.d.ts +0 -29
  118. package/dist/core/data/domain-entity-contexts.js +0 -321
  119. package/dist/core/data/domain-schema.d.ts +0 -36
  120. package/dist/core/data/domain-schema.js +0 -323
  121. package/dist/core/data/index.d.ts +0 -7
  122. package/dist/core/data/index.js +0 -7
  123. package/dist/core/data/types.d.ts +0 -111
  124. package/dist/core/data/types.js +0 -1
  125. package/dist/core/hooks/hook-bus.d.ts +0 -18
  126. package/dist/core/hooks/hook-bus.js +0 -120
  127. package/dist/core/hooks/index.d.ts +0 -2
  128. package/dist/core/hooks/index.js +0 -1
  129. package/dist/core/hooks/types.d.ts +0 -19
  130. package/dist/core/hooks/types.js +0 -1
  131. package/dist/core/index.d.ts +0 -4
  132. package/dist/core/index.js +0 -4
  133. package/dist/core/llm/auto-discovery.d.ts +0 -11
  134. package/dist/core/llm/auto-discovery.js +0 -49
  135. package/dist/core/llm/cost-tracker.d.ts +0 -6
  136. package/dist/core/llm/cost-tracker.js +0 -38
  137. package/dist/core/llm/index.d.ts +0 -4
  138. package/dist/core/llm/index.js +0 -3
  139. package/dist/core/llm/model-router.d.ts +0 -25
  140. package/dist/core/llm/model-router.js +0 -49
  141. package/dist/core/llm/provider-registry.d.ts +0 -9
  142. package/dist/core/llm/provider-registry.js +0 -25
  143. package/dist/core/llm/types.d.ts +0 -2
  144. package/dist/core/llm/types.js +0 -2
  145. package/dist/core/orchestrator/adapters/api-adapter.d.ts +0 -34
  146. package/dist/core/orchestrator/adapters/api-adapter.js +0 -88
  147. package/dist/core/orchestrator/adapters/cli-adapter.d.ts +0 -22
  148. package/dist/core/orchestrator/adapters/cli-adapter.js +0 -69
  149. package/dist/core/orchestrator/adapters/deterministic-adapter.d.ts +0 -35
  150. package/dist/core/orchestrator/adapters/deterministic-adapter.js +0 -75
  151. package/dist/core/orchestrator/adapters/env-whitelist.d.ts +0 -4
  152. package/dist/core/orchestrator/adapters/env-whitelist.js +0 -27
  153. package/dist/core/orchestrator/adapters/output-extractor.d.ts +0 -11
  154. package/dist/core/orchestrator/adapters/output-extractor.js +0 -59
  155. package/dist/core/orchestrator/adapters/process-manager.d.ts +0 -15
  156. package/dist/core/orchestrator/adapters/process-manager.js +0 -26
  157. package/dist/core/orchestrator/adapters/tool-loop.d.ts +0 -22
  158. package/dist/core/orchestrator/adapters/tool-loop.js +0 -66
  159. package/dist/core/orchestrator/agent-registry.d.ts +0 -31
  160. package/dist/core/orchestrator/agent-registry.js +0 -135
  161. package/dist/core/orchestrator/budget-controller.d.ts +0 -19
  162. package/dist/core/orchestrator/budget-controller.js +0 -73
  163. package/dist/core/orchestrator/chain-guard.d.ts +0 -14
  164. package/dist/core/orchestrator/chain-guard.js +0 -23
  165. package/dist/core/orchestrator/circuit-breaker.d.ts +0 -65
  166. package/dist/core/orchestrator/circuit-breaker.js +0 -159
  167. package/dist/core/orchestrator/claude-stream-parser.d.ts +0 -31
  168. package/dist/core/orchestrator/claude-stream-parser.js +0 -99
  169. package/dist/core/orchestrator/config-revisions.d.ts +0 -6
  170. package/dist/core/orchestrator/config-revisions.js +0 -17
  171. package/dist/core/orchestrator/dependency-resolver.d.ts +0 -20
  172. package/dist/core/orchestrator/dependency-resolver.js +0 -78
  173. package/dist/core/orchestrator/governance-gate.d.ts +0 -110
  174. package/dist/core/orchestrator/governance-gate.js +0 -170
  175. package/dist/core/orchestrator/learning-pipeline.d.ts +0 -109
  176. package/dist/core/orchestrator/learning-pipeline.js +0 -249
  177. package/dist/core/orchestrator/loop-detector.d.ts +0 -51
  178. package/dist/core/orchestrator/loop-detector.js +0 -133
  179. package/dist/core/orchestrator/ndjson-logger.d.ts +0 -6
  180. package/dist/core/orchestrator/ndjson-logger.js +0 -18
  181. package/dist/core/orchestrator/permission-relay.d.ts +0 -72
  182. package/dist/core/orchestrator/permission-relay.js +0 -164
  183. package/dist/core/orchestrator/run-manager.d.ts +0 -31
  184. package/dist/core/orchestrator/run-manager.js +0 -178
  185. package/dist/core/orchestrator/scheduler.d.ts +0 -70
  186. package/dist/core/orchestrator/scheduler.js +0 -198
  187. package/dist/core/orchestrator/secret-store.d.ts +0 -57
  188. package/dist/core/orchestrator/secret-store.js +0 -171
  189. package/dist/core/orchestrator/session-manager.d.ts +0 -13
  190. package/dist/core/orchestrator/session-manager.js +0 -66
  191. package/dist/core/orchestrator/task-queue.d.ts +0 -34
  192. package/dist/core/orchestrator/task-queue.js +0 -83
  193. package/dist/core/orchestrator/template-interpolate.d.ts +0 -5
  194. package/dist/core/orchestrator/template-interpolate.js +0 -18
  195. package/dist/core/orchestrator/user-registry.d.ts +0 -47
  196. package/dist/core/orchestrator/user-registry.js +0 -76
  197. package/dist/core/orchestrator/wakeup-queue.d.ts +0 -9
  198. package/dist/core/orchestrator/wakeup-queue.js +0 -45
  199. package/dist/core/orchestrator/workflow-engine.d.ts +0 -47
  200. package/dist/core/orchestrator/workflow-engine.js +0 -204
  201. package/dist/core/security/audit.d.ts +0 -20
  202. package/dist/core/security/audit.js +0 -33
  203. package/dist/core/security/column-validator.d.ts +0 -20
  204. package/dist/core/security/column-validator.js +0 -37
  205. package/dist/core/security/index.d.ts +0 -5
  206. package/dist/core/security/index.js +0 -5
  207. package/dist/core/security/process-env.d.ts +0 -13
  208. package/dist/core/security/process-env.js +0 -49
  209. package/dist/core/security/sanitizer.d.ts +0 -11
  210. package/dist/core/security/sanitizer.js +0 -39
  211. package/dist/core/security/types.d.ts +0 -11
  212. package/dist/core/security/types.js +0 -1
  213. package/dist/core/update/auto-update.d.ts +0 -21
  214. package/dist/core/update/auto-update.js +0 -102
  215. package/dist/core/update/backup-manager.d.ts +0 -7
  216. package/dist/core/update/backup-manager.js +0 -24
  217. package/dist/core/update/index.d.ts +0 -8
  218. package/dist/core/update/index.js +0 -6
  219. package/dist/core/update/migration-hooks.d.ts +0 -11
  220. package/dist/core/update/migration-hooks.js +0 -10
  221. package/dist/core/update/types.d.ts +0 -11
  222. package/dist/core/update/types.js +0 -1
  223. package/dist/core/update/update-checker.d.ts +0 -11
  224. package/dist/core/update/update-checker.js +0 -63
  225. package/dist/core/update/update-manager.d.ts +0 -25
  226. package/dist/core/update/update-manager.js +0 -101
  227. package/dist/core/update/version-utils.d.ts +0 -6
  228. package/dist/core/update/version-utils.js +0 -34
  229. package/dist/gmail-connector-MNUBRNFM.js +0 -6
  230. package/dist/gmail-connector-PS2VLGNE.js +0 -6
  231. package/dist/gmail-connector-ULSMN6X2.js +0 -6
  232. package/dist/gmail-connector-URRFX6A3.js +0 -6
  233. package/dist/inbound-AFBUPSPG.js +0 -10
  234. package/dist/inbound-AFOHYNUY.js +0 -6
  235. package/dist/inbound-CGIXRXGC.js +0 -8
  236. package/dist/inbound-MCOLRH6U.js +0 -10
  237. package/dist/inbound-SNEMBLGA.js +0 -6
  238. package/dist/inbound-ZJHAYVMF.js +0 -10
  239. package/dist/provider-qqJYv9nv.d.ts +0 -75
  240. package/dist/providers/anthropic/models.d.ts +0 -2
  241. package/dist/providers/anthropic/models.js +0 -29
  242. package/dist/providers/anthropic/provider.d.ts +0 -13
  243. package/dist/providers/anthropic/provider.js +0 -119
  244. package/dist/providers/anthropic/tool-converter.d.ts +0 -10
  245. package/dist/providers/anthropic/tool-converter.js +0 -7
  246. package/dist/providers/ollama/provider.d.ts +0 -17
  247. package/dist/providers/ollama/provider.js +0 -185
  248. package/dist/providers/openai/models.d.ts +0 -2
  249. package/dist/providers/openai/models.js +0 -29
  250. package/dist/providers/openai/provider.d.ts +0 -13
  251. package/dist/providers/openai/provider.js +0 -163
  252. package/dist/providers/openai/tool-converter.d.ts +0 -10
  253. package/dist/providers/openai/tool-converter.js +0 -10
  254. package/dist/shared/constants.d.ts +0 -50
  255. package/dist/shared/constants.js +0 -64
  256. package/dist/shared/index.d.ts +0 -14
  257. package/dist/shared/index.js +0 -14
  258. package/dist/shared/types/agent.d.ts +0 -36
  259. package/dist/shared/types/agent.js +0 -2
  260. package/dist/shared/types/channel.d.ts +0 -70
  261. package/dist/shared/types/channel.js +0 -2
  262. package/dist/shared/types/config.d.ts +0 -111
  263. package/dist/shared/types/config.js +0 -2
  264. package/dist/shared/types/connector.d.ts +0 -77
  265. package/dist/shared/types/connector.js +0 -2
  266. package/dist/shared/types/execution.d.ts +0 -29
  267. package/dist/shared/types/execution.js +0 -2
  268. package/dist/shared/types/provider.d.ts +0 -73
  269. package/dist/shared/types/provider.js +0 -2
  270. package/dist/shared/types/task.d.ts +0 -47
  271. package/dist/shared/types/task.js +0 -2
  272. package/dist/shared/types/workflow.d.ts +0 -39
  273. package/dist/shared/types/workflow.js +0 -2
  274. package/dist/shared/utils.d.ts +0 -6
  275. package/dist/shared/utils.js +0 -13
  276. package/dist/update-check.d.ts +0 -5
  277. package/dist/update-check.js +0 -56
@@ -1,328 +0,0 @@
1
- // src/connectors/google/oauth.ts
2
- var _google;
3
- async function getGoogle() {
4
- if (!_google) {
5
- try {
6
- const mod = await import("googleapis");
7
- _google = mod.google;
8
- } catch {
9
- throw new Error(
10
- "googleapis is required for Google connectors. Install it: npm install googleapis"
11
- );
12
- }
13
- }
14
- return _google;
15
- }
16
- async function createOAuth2Client(config) {
17
- const google = await getGoogle();
18
- return new google.auth.OAuth2(
19
- config.clientId,
20
- config.clientSecret,
21
- config.redirectUri
22
- );
23
- }
24
- function getAuthUrl(client, scopes) {
25
- return client.generateAuthUrl({
26
- access_type: "offline",
27
- prompt: "consent",
28
- scope: scopes
29
- });
30
- }
31
- async function exchangeCode(client, code) {
32
- const { tokens } = await client.getToken(code);
33
- return tokens;
34
- }
35
- async function loadTokens(getter, accountKey) {
36
- const raw = await getter(`google_tokens:${accountKey}`);
37
- if (!raw) return null;
38
- try {
39
- return JSON.parse(raw);
40
- } catch {
41
- return null;
42
- }
43
- }
44
- async function saveTokens(setter, accountKey, tokens) {
45
- await setter(`google_tokens:${accountKey}`, JSON.stringify(tokens));
46
- }
47
- async function refreshIfNeeded(client, tokens, saver) {
48
- const buffer = 6e4;
49
- const isExpired = tokens.expiry_date != null && Date.now() >= tokens.expiry_date - buffer;
50
- if (!isExpired) return tokens;
51
- client.setCredentials(tokens);
52
- const { credentials } = await client.refreshAccessToken();
53
- const refreshed = {
54
- access_token: credentials.access_token,
55
- refresh_token: credentials.refresh_token ?? tokens.refresh_token,
56
- expiry_date: credentials.expiry_date ?? void 0,
57
- token_type: credentials.token_type ?? "Bearer"
58
- };
59
- if (saver) {
60
- await saver(refreshed);
61
- }
62
- return refreshed;
63
- }
64
-
65
- // src/connectors/google/gmail-connector.ts
66
- var GoogleGmailConnector = class {
67
- id = "google-gmail";
68
- meta = {
69
- displayName: "Google Gmail",
70
- provider: "google",
71
- dataType: "email"
72
- };
73
- tokenLoader;
74
- tokenSaver;
75
- client = null;
76
- config = null;
77
- tokens = null;
78
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
79
- gmail = null;
80
- constructor(opts) {
81
- this.tokenLoader = opts.tokenLoader;
82
- this.tokenSaver = opts.tokenSaver;
83
- }
84
- // ── Lifecycle ──────────────────────────────────────────────────
85
- async connect(config) {
86
- this.config = config;
87
- this.client = await createOAuth2Client(config.oauth);
88
- this.tokens = await loadTokens(this.tokenLoader, config.account);
89
- if (!this.tokens) {
90
- throw new Error(
91
- `No stored tokens for account ${config.account}. Complete the OAuth flow first.`
92
- );
93
- }
94
- this.tokens = await refreshIfNeeded(
95
- this.client,
96
- this.tokens,
97
- async (t) => saveTokens(this.tokenSaver, config.account, t)
98
- );
99
- this.client.setCredentials(this.tokens);
100
- const { google } = await import("googleapis");
101
- this.gmail = google.gmail({ version: "v1", auth: this.client });
102
- }
103
- async disconnect() {
104
- this.client = null;
105
- this.gmail = null;
106
- this.tokens = null;
107
- this.config = null;
108
- }
109
- async healthCheck() {
110
- try {
111
- this.ensureConnected();
112
- const res = await this.gmail.users.getProfile({ userId: "me" });
113
- return { ok: true, account: res.data.emailAddress };
114
- } catch (err) {
115
- return { ok: false, error: errorMessage(err) };
116
- }
117
- }
118
- // ── Auth ───────────────────────────────────────────────────────
119
- async authenticate(codeProvider) {
120
- if (!this.config) {
121
- return { success: false, error: "Call connect() first to set config, or pass config and call authenticate() before connect()." };
122
- }
123
- try {
124
- const client = await createOAuth2Client(this.config.oauth);
125
- const scopes = this.config.scopes ?? [
126
- "https://www.googleapis.com/auth/gmail.readonly",
127
- "https://www.googleapis.com/auth/gmail.send"
128
- ];
129
- const authUrl = getAuthUrl(client, scopes);
130
- const code = await codeProvider(authUrl);
131
- const tokens = await exchangeCode(client, code);
132
- await saveTokens(this.tokenSaver, this.config.account, tokens);
133
- this.tokens = tokens;
134
- this.client = client;
135
- this.client.setCredentials(tokens);
136
- const { google } = await import("googleapis");
137
- this.gmail = google.gmail({ version: "v1", auth: this.client });
138
- return { success: true, account: this.config.account };
139
- } catch (err) {
140
- return { success: false, error: errorMessage(err) };
141
- }
142
- }
143
- // ── Sync ───────────────────────────────────────────────────────
144
- async sync(options) {
145
- this.ensureConnected();
146
- if (options?.cursor) {
147
- return this.syncIncremental(options.cursor, options.limit);
148
- }
149
- return this.syncFull(options);
150
- }
151
- /** Incremental sync using Gmail history API. */
152
- async syncIncremental(startHistoryId, limit) {
153
- const records = [];
154
- const errors = [];
155
- const seenIds = /* @__PURE__ */ new Set();
156
- let pageToken;
157
- let latestHistoryId = startHistoryId;
158
- do {
159
- const res = await this.gmail.users.history.list({
160
- userId: "me",
161
- startHistoryId,
162
- historyTypes: ["messageAdded"],
163
- ...pageToken ? { pageToken } : {}
164
- });
165
- latestHistoryId = res.data.historyId ?? latestHistoryId;
166
- const histories = res.data.history ?? [];
167
- for (const h of histories) {
168
- for (const added of h.messagesAdded ?? []) {
169
- const msgId = added.message?.id;
170
- if (!msgId || seenIds.has(msgId)) continue;
171
- seenIds.add(msgId);
172
- try {
173
- const record = await this.fetchMessage(msgId);
174
- records.push(record);
175
- } catch (err) {
176
- errors.push({ id: msgId, error: errorMessage(err) });
177
- }
178
- if (limit && records.length >= limit) {
179
- return { records, cursor: latestHistoryId, hasMore: true, errors };
180
- }
181
- }
182
- }
183
- pageToken = res.data.nextPageToken ?? void 0;
184
- } while (pageToken);
185
- return { records, cursor: latestHistoryId, hasMore: false, errors };
186
- }
187
- /** Full sync — list messages and fetch each one. */
188
- async syncFull(options) {
189
- const records = [];
190
- const errors = [];
191
- const maxResults = options?.limit ?? 100;
192
- let query = "";
193
- if (options?.since) {
194
- const epoch = Math.floor(new Date(options.since).getTime() / 1e3);
195
- query = `after:${epoch}`;
196
- }
197
- if (options?.filters?.q) {
198
- query = query ? `${query} ${options.filters.q}` : String(options.filters.q);
199
- }
200
- let pageToken;
201
- let collected = 0;
202
- do {
203
- const res = await this.gmail.users.messages.list({
204
- userId: "me",
205
- maxResults: Math.min(maxResults - collected, 100),
206
- ...query ? { q: query } : {},
207
- ...pageToken ? { pageToken } : {}
208
- });
209
- const messages = res.data.messages ?? [];
210
- for (const msg of messages) {
211
- try {
212
- const record = await this.fetchMessage(msg.id);
213
- records.push(record);
214
- } catch (err) {
215
- errors.push({ id: msg.id, error: errorMessage(err) });
216
- }
217
- collected++;
218
- if (collected >= maxResults) break;
219
- }
220
- pageToken = res.data.nextPageToken ?? void 0;
221
- } while (pageToken && collected < maxResults);
222
- const profile = await this.gmail.users.getProfile({ userId: "me" });
223
- const cursor = profile.data.historyId ?? void 0;
224
- return {
225
- records,
226
- cursor,
227
- hasMore: !!pageToken,
228
- errors
229
- };
230
- }
231
- // ── Push (send email) ─────────────────────────────────────────
232
- async push(payload) {
233
- this.ensureConnected();
234
- try {
235
- const toHeader = payload.to.map(formatAddress).join(", ");
236
- const ccHeader = payload.cc.length ? `Cc: ${payload.cc.map(formatAddress).join(", ")}\r
237
- ` : "";
238
- const bccHeader = payload.bcc.length ? `Bcc: ${payload.bcc.map(formatAddress).join(", ")}\r
239
- ` : "";
240
- const mime = [
241
- `To: ${toHeader}\r
242
- `,
243
- ccHeader,
244
- bccHeader,
245
- `Subject: ${payload.subject}\r
246
- `,
247
- `Content-Type: text/plain; charset="UTF-8"\r
248
- `,
249
- `\r
250
- `,
251
- payload.body ?? ""
252
- ].join("");
253
- const encoded = Buffer.from(mime).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
254
- const res = await this.gmail.users.messages.send({
255
- userId: "me",
256
- requestBody: { raw: encoded }
257
- });
258
- return { success: true, externalId: res.data.id };
259
- } catch (err) {
260
- return { success: false, error: errorMessage(err) };
261
- }
262
- }
263
- // ── Internals ─────────────────────────────────────────────────
264
- ensureConnected() {
265
- if (!this.gmail || !this.config) {
266
- throw new Error("GoogleGmailConnector is not connected. Call connect() first.");
267
- }
268
- }
269
- /** Fetch a single message by ID and parse into an EmailRecord. */
270
- async fetchMessage(messageId) {
271
- const res = await this.gmail.users.messages.get({
272
- userId: "me",
273
- id: messageId,
274
- format: "metadata",
275
- metadataHeaders: ["From", "To", "Cc", "Bcc", "Subject", "Date"]
276
- });
277
- const msg = res.data;
278
- const headers = msg.payload?.headers ?? [];
279
- const getHeader = (name) => headers.find((h) => h.name.toLowerCase() === name.toLowerCase())?.value ?? "";
280
- return {
281
- gmailId: msg.id,
282
- threadId: msg.threadId,
283
- account: this.config.account,
284
- subject: getHeader("Subject"),
285
- from: parseAddress(getHeader("From")),
286
- to: parseAddressList(getHeader("To")),
287
- cc: parseAddressList(getHeader("Cc")),
288
- bcc: parseAddressList(getHeader("Bcc")),
289
- date: new Date(getHeader("Date")).toISOString(),
290
- snippet: msg.snippet ?? "",
291
- labels: msg.labelIds ?? [],
292
- isRead: !(msg.labelIds ?? []).includes("UNREAD")
293
- };
294
- }
295
- };
296
- function parseAddress(raw) {
297
- const match = raw.match(/^(.+?)\s*<([^>]+)>$/);
298
- if (match) {
299
- return { name: match[1].replace(/^["']|["']$/g, "").trim(), email: match[2] };
300
- }
301
- return { email: raw.trim() };
302
- }
303
- function parseAddressList(raw) {
304
- if (!raw.trim()) return [];
305
- const results = [];
306
- const parts = raw.split(/,(?=(?:[^<]*<[^>]*>)*[^>]*$)/);
307
- for (const part of parts) {
308
- const trimmed = part.trim();
309
- if (trimmed) results.push(parseAddress(trimmed));
310
- }
311
- return results;
312
- }
313
- function formatAddress(addr) {
314
- return addr.name ? `${addr.name} <${addr.email}>` : addr.email;
315
- }
316
- function errorMessage(err) {
317
- return err instanceof Error ? err.message : String(err);
318
- }
319
-
320
- export {
321
- createOAuth2Client,
322
- getAuthUrl,
323
- exchangeCode,
324
- loadTokens,
325
- saveTokens,
326
- refreshIfNeeded,
327
- GoogleGmailConnector
328
- };
@@ -1,144 +0,0 @@
1
- // src/channels/slack/transcribe.ts
2
- import { execSync } from "child_process";
3
- import { writeFileSync, unlinkSync, mkdirSync } from "fs";
4
- import { join } from "path";
5
- import { randomUUID } from "crypto";
6
- import os from "os";
7
- import { createRequire } from "module";
8
- var TEMP_DIR = join(os.tmpdir(), "botinabox-audio");
9
- async function transcribeAudio(audioBuffer, filename, opts) {
10
- let whisper;
11
- try {
12
- const require2 = createRequire(import.meta.url);
13
- const mod = require2("whisper-node");
14
- whisper = mod.whisper ?? mod.default ?? mod;
15
- } catch {
16
- console.warn("[botinabox] whisper-node not installed \u2014 voice transcription unavailable. Run: npm install whisper-node && npx whisper-node download");
17
- return null;
18
- }
19
- try {
20
- execSync("ffmpeg -version", { stdio: "ignore" });
21
- } catch {
22
- console.warn("[botinabox] ffmpeg not found \u2014 required for audio conversion. Install: brew install ffmpeg");
23
- return null;
24
- }
25
- const id = randomUUID().slice(0, 8);
26
- const ext = filename.split(".").pop() ?? "aac";
27
- mkdirSync(TEMP_DIR, { recursive: true });
28
- const inputPath = join(TEMP_DIR, `${id}.${ext}`);
29
- const wavPath = join(TEMP_DIR, `${id}.wav`);
30
- try {
31
- writeFileSync(inputPath, audioBuffer);
32
- execSync(
33
- `ffmpeg -y -i "${inputPath}" -ar 16000 -ac 1 -c:a pcm_s16le "${wavPath}"`,
34
- { stdio: "ignore", timeout: 3e4 }
35
- );
36
- const segments = await whisper(wavPath, {
37
- modelName: opts?.modelName ?? "base.en",
38
- whisperOptions: {
39
- language: opts?.language ?? "auto"
40
- }
41
- });
42
- if (!segments || segments.length === 0) return null;
43
- return segments.map((s) => s.speech).join(" ").trim();
44
- } catch (err) {
45
- console.error("[botinabox] Transcription failed:", err);
46
- return null;
47
- } finally {
48
- try {
49
- unlinkSync(inputPath);
50
- } catch {
51
- }
52
- try {
53
- unlinkSync(wavPath);
54
- } catch {
55
- }
56
- }
57
- }
58
- async function downloadAudio(url, token) {
59
- try {
60
- const resp = await fetch(url, {
61
- headers: { Authorization: `Bearer ${token}` }
62
- });
63
- if (!resp.ok) {
64
- console.error(`[botinabox] Audio download failed: ${resp.status} ${resp.statusText}`);
65
- return null;
66
- }
67
- return Buffer.from(await resp.arrayBuffer());
68
- } catch (err) {
69
- console.error("[botinabox] Audio download error:", err);
70
- return null;
71
- }
72
- }
73
-
74
- // src/channels/slack/inbound.ts
75
- var AUDIO_TYPES = /* @__PURE__ */ new Set(["aac", "mp4", "m4a", "ogg", "webm", "mp3", "wav"]);
76
- function extractVoiceTranscript(file) {
77
- const isAudio = file.subtype === "slack_audio" || AUDIO_TYPES.has(file.filetype ?? "");
78
- if (!isAudio) return null;
79
- const transcript = file.transcription?.preview?.content ?? (typeof file.preview === "string" ? file.preview : null);
80
- return transcript ?? null;
81
- }
82
- function parseSlackEvent(event) {
83
- const id = event.client_msg_id ?? event.ts ?? event.event_ts ?? `slack-${Date.now()}`;
84
- const channel = event.channel ?? "unknown";
85
- const from = event.user ?? "unknown";
86
- const threadId = event.thread_ts !== void 0 ? event.thread_ts : void 0;
87
- const receivedAt = event.ts ? new Date(parseFloat(event.ts) * 1e3).toISOString() : (/* @__PURE__ */ new Date()).toISOString();
88
- let body = event.text ?? "";
89
- if (event.subtype === "file_share" && event.files?.length) {
90
- for (const file of event.files) {
91
- const transcript = extractVoiceTranscript(file);
92
- if (transcript) {
93
- body = body ? `${body}
94
-
95
- [Voice message] ${transcript}` : `[Voice message] ${transcript}`;
96
- break;
97
- }
98
- }
99
- }
100
- if (event.subtype === "file_share" && event.files?.length && !body) {
101
- const hasAudio = event.files.some(
102
- (f) => f.subtype === "slack_audio" || AUDIO_TYPES.has(f.filetype ?? "")
103
- );
104
- if (hasAudio) {
105
- body = "[Voice message \u2014 no transcript available]";
106
- }
107
- }
108
- return {
109
- id,
110
- channel,
111
- from,
112
- body,
113
- threadId,
114
- receivedAt,
115
- raw: event
116
- };
117
- }
118
- async function enrichVoiceMessage(msg, botToken) {
119
- if (!msg.body.includes("[Voice message \u2014 no transcript available]")) return msg;
120
- const raw = msg.raw;
121
- const files = raw?.files;
122
- if (!files?.length) return msg;
123
- const audioFile = files.find(
124
- (f) => f.subtype === "slack_audio" || AUDIO_TYPES.has(f.filetype ?? "")
125
- );
126
- if (!audioFile?.url_private) return msg;
127
- const buffer = await downloadAudio(audioFile.url_private, botToken);
128
- if (!buffer) return msg;
129
- const filename = audioFile.name ?? `voice.${audioFile.filetype ?? "aac"}`;
130
- const transcript = await transcribeAudio(buffer, filename);
131
- if (!transcript) return msg;
132
- return {
133
- ...msg,
134
- body: `[Voice message] ${transcript}`
135
- };
136
- }
137
-
138
- export {
139
- transcribeAudio,
140
- downloadAudio,
141
- extractVoiceTranscript,
142
- parseSlackEvent,
143
- enrichVoiceMessage
144
- };
@@ -1,144 +0,0 @@
1
- // src/channels/slack/transcribe.ts
2
- import { execFileSync } from "child_process";
3
- import { writeFileSync, unlinkSync, mkdirSync } from "fs";
4
- import { join } from "path";
5
- import { randomUUID } from "crypto";
6
- import os from "os";
7
- import { createRequire } from "module";
8
- var TEMP_DIR = join(os.tmpdir(), "botinabox-audio");
9
- async function transcribeAudio(audioBuffer, filename, opts) {
10
- let whisper;
11
- try {
12
- const require2 = createRequire(import.meta.url);
13
- const mod = require2("whisper-node");
14
- whisper = mod.whisper ?? mod.default ?? mod;
15
- } catch {
16
- console.warn("[botinabox] whisper-node not installed \u2014 voice transcription unavailable. Run: npm install whisper-node && npx whisper-node download");
17
- return null;
18
- }
19
- try {
20
- execSync("ffmpeg -version", { stdio: "ignore" });
21
- } catch {
22
- console.warn("[botinabox] ffmpeg not found \u2014 required for audio conversion. Install: brew install ffmpeg");
23
- return null;
24
- }
25
- const id = randomUUID().slice(0, 8);
26
- const ext = filename.split(".").pop() ?? "aac";
27
- mkdirSync(TEMP_DIR, { recursive: true });
28
- const inputPath = join(TEMP_DIR, `${id}.${ext}`);
29
- const wavPath = join(TEMP_DIR, `${id}.wav`);
30
- try {
31
- writeFileSync(inputPath, audioBuffer);
32
- execFileSync("ffmpeg", ["-y", "-i", inputPath, "-ar", "16000", "-ac", "1", "-c:a", "pcm_s16le", wavPath], {
33
- stdio: "ignore",
34
- timeout: 3e4
35
- });
36
- const segments = await whisper(wavPath, {
37
- modelName: opts?.modelName ?? "base.en",
38
- whisperOptions: {
39
- language: opts?.language ?? "auto"
40
- }
41
- });
42
- if (!segments || segments.length === 0) return null;
43
- return segments.map((s) => s.speech).join(" ").trim();
44
- } catch (err) {
45
- console.error("[botinabox] Transcription failed:", err);
46
- return null;
47
- } finally {
48
- try {
49
- unlinkSync(inputPath);
50
- } catch {
51
- }
52
- try {
53
- unlinkSync(wavPath);
54
- } catch {
55
- }
56
- }
57
- }
58
- async function downloadAudio(url, token) {
59
- try {
60
- const resp = await fetch(url, {
61
- headers: { Authorization: `Bearer ${token}` }
62
- });
63
- if (!resp.ok) {
64
- console.error(`[botinabox] Audio download failed: ${resp.status} ${resp.statusText}`);
65
- return null;
66
- }
67
- return Buffer.from(await resp.arrayBuffer());
68
- } catch (err) {
69
- console.error("[botinabox] Audio download error:", err);
70
- return null;
71
- }
72
- }
73
-
74
- // src/channels/slack/inbound.ts
75
- var AUDIO_TYPES = /* @__PURE__ */ new Set(["aac", "mp4", "m4a", "ogg", "webm", "mp3", "wav"]);
76
- function extractVoiceTranscript(file) {
77
- const isAudio = file.subtype === "slack_audio" || AUDIO_TYPES.has(file.filetype ?? "");
78
- if (!isAudio) return null;
79
- const transcript = file.transcription?.preview?.content ?? (typeof file.preview === "string" ? file.preview : null);
80
- return transcript ?? null;
81
- }
82
- function parseSlackEvent(event) {
83
- const id = event.client_msg_id ?? event.ts ?? event.event_ts ?? `slack-${Date.now()}`;
84
- const channel = event.channel ?? "unknown";
85
- const from = event.user ?? "unknown";
86
- const threadId = event.thread_ts !== void 0 ? event.thread_ts : void 0;
87
- const receivedAt = event.ts ? new Date(parseFloat(event.ts) * 1e3).toISOString() : (/* @__PURE__ */ new Date()).toISOString();
88
- let body = event.text ?? "";
89
- if (event.subtype === "file_share" && event.files?.length) {
90
- for (const file of event.files) {
91
- const transcript = extractVoiceTranscript(file);
92
- if (transcript) {
93
- body = body ? `${body}
94
-
95
- [Voice message] ${transcript}` : `[Voice message] ${transcript}`;
96
- break;
97
- }
98
- }
99
- }
100
- if (event.subtype === "file_share" && event.files?.length && !body) {
101
- const hasAudio = event.files.some(
102
- (f) => f.subtype === "slack_audio" || AUDIO_TYPES.has(f.filetype ?? "")
103
- );
104
- if (hasAudio) {
105
- body = "[Voice message \u2014 no transcript available]";
106
- }
107
- }
108
- return {
109
- id,
110
- channel,
111
- from,
112
- body,
113
- threadId,
114
- receivedAt,
115
- raw: event
116
- };
117
- }
118
- async function enrichVoiceMessage(msg, botToken) {
119
- if (!msg.body.includes("[Voice message \u2014 no transcript available]")) return msg;
120
- const raw = msg.raw;
121
- const files = raw?.files;
122
- if (!files?.length) return msg;
123
- const audioFile = files.find(
124
- (f) => f.subtype === "slack_audio" || AUDIO_TYPES.has(f.filetype ?? "")
125
- );
126
- if (!audioFile?.url_private) return msg;
127
- const buffer = await downloadAudio(audioFile.url_private, botToken);
128
- if (!buffer) return msg;
129
- const filename = audioFile.name ?? `voice.${audioFile.filetype ?? "aac"}`;
130
- const transcript = await transcribeAudio(buffer, filename);
131
- if (!transcript) return msg;
132
- return {
133
- ...msg,
134
- body: `[Voice message] ${transcript}`
135
- };
136
- }
137
-
138
- export {
139
- transcribeAudio,
140
- downloadAudio,
141
- extractVoiceTranscript,
142
- parseSlackEvent,
143
- enrichVoiceMessage
144
- };
@@ -1,22 +0,0 @@
1
- // src/channels/slack/inbound.ts
2
- function parseSlackEvent(event) {
3
- const id = event.client_msg_id ?? event.ts ?? event.event_ts ?? `slack-${Date.now()}`;
4
- const channel = event.channel ?? "unknown";
5
- const from = event.user ?? "unknown";
6
- const body = event.text ?? "";
7
- const threadId = event.thread_ts !== void 0 ? event.thread_ts : void 0;
8
- const receivedAt = event.ts ? new Date(parseFloat(event.ts) * 1e3).toISOString() : (/* @__PURE__ */ new Date()).toISOString();
9
- return {
10
- id,
11
- channel,
12
- from,
13
- body,
14
- threadId,
15
- receivedAt,
16
- raw: event
17
- };
18
- }
19
-
20
- export {
21
- parseSlackEvent
22
- };
@@ -1,7 +0,0 @@
1
- export interface ConfigTemplateOptions {
2
- name: string;
3
- channel?: string;
4
- provider?: string;
5
- typescript?: boolean;
6
- }
7
- export declare function configYmlTemplate(opts: ConfigTemplateOptions): string;