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,345 +0,0 @@
1
- /**
2
- * Gmail connector — pulls email metadata and optionally sends mail.
3
- *
4
- * Produces `EmailRecord` objects. Does NOT write to any database table;
5
- * the consuming application decides how to store records.
6
- */
7
- import { createOAuth2Client, createServiceAccountClient, getAuthUrl, exchangeCode, loadTokens, saveTokens, refreshIfNeeded, } from './oauth.js';
8
- // ── Connector ──────────────────────────────────────────────────────
9
- export class GoogleGmailConnector {
10
- id = 'google-gmail';
11
- meta = {
12
- displayName: 'Google Gmail',
13
- provider: 'google',
14
- dataType: 'email',
15
- };
16
- tokenLoader;
17
- tokenSaver;
18
- client = null;
19
- config = null;
20
- tokens = null;
21
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
22
- gmail = null;
23
- constructor(opts = {}) {
24
- this.tokenLoader = opts.tokenLoader;
25
- this.tokenSaver = opts.tokenSaver;
26
- }
27
- // ── Lifecycle ──────────────────────────────────────────────────
28
- async connect(config) {
29
- this.config = config;
30
- const scopes = config.scopes ?? [
31
- 'https://www.googleapis.com/auth/gmail.readonly',
32
- ];
33
- if (config.serviceAccount) {
34
- // Service account auth — headless, no browser
35
- this.client = await createServiceAccountClient(config.serviceAccount, scopes);
36
- }
37
- else if (config.oauth) {
38
- // OAuth2 user flow — requires tokens from prior browser auth
39
- this.client = await createOAuth2Client(config.oauth);
40
- if (!this.tokenLoader) {
41
- throw new Error('tokenLoader required for OAuth2 flow');
42
- }
43
- this.tokens = await loadTokens(this.tokenLoader, config.account);
44
- if (!this.tokens) {
45
- throw new Error(`No stored tokens for account ${config.account}. Complete the OAuth flow first.`);
46
- }
47
- this.tokens = await refreshIfNeeded(this.client, this.tokens, this.tokenSaver
48
- ? async (t) => saveTokens(this.tokenSaver, config.account, t)
49
- : undefined);
50
- this.client.setCredentials(this.tokens);
51
- }
52
- else {
53
- throw new Error('Either serviceAccount or oauth config is required');
54
- }
55
- const { google } = await import('googleapis');
56
- this.gmail = google.gmail({ version: 'v1', auth: this.client });
57
- }
58
- async disconnect() {
59
- this.client = null;
60
- this.gmail = null;
61
- this.tokens = null;
62
- this.config = null;
63
- }
64
- async healthCheck() {
65
- try {
66
- this.ensureConnected();
67
- const res = await this.gmail.users.getProfile({ userId: 'me' });
68
- return { ok: true, account: res.data.emailAddress };
69
- }
70
- catch (err) {
71
- return { ok: false, error: errorMessage(err) };
72
- }
73
- }
74
- // ── Auth ───────────────────────────────────────────────────────
75
- async authenticate(codeProvider) {
76
- if (!this.config) {
77
- return { success: false, error: 'Call connect() first to set config, or pass config and call authenticate() before connect().' };
78
- }
79
- try {
80
- if (!this.config.oauth) {
81
- return { success: false, error: 'OAuth config required for browser-based authenticate(). Use serviceAccount for headless auth.' };
82
- }
83
- if (!this.tokenSaver) {
84
- return { success: false, error: 'tokenSaver required for authenticate() flow.' };
85
- }
86
- const client = await createOAuth2Client(this.config.oauth);
87
- const scopes = this.config.scopes ?? [
88
- 'https://www.googleapis.com/auth/gmail.readonly',
89
- 'https://www.googleapis.com/auth/gmail.send',
90
- ];
91
- const authUrl = getAuthUrl(client, scopes);
92
- const code = await codeProvider(authUrl);
93
- const tokens = await exchangeCode(client, code);
94
- await saveTokens(this.tokenSaver, this.config.account, tokens);
95
- this.tokens = tokens;
96
- this.client = client;
97
- this.client.setCredentials(tokens);
98
- const { google } = await import('googleapis');
99
- this.gmail = google.gmail({ version: 'v1', auth: this.client });
100
- return { success: true, account: this.config.account };
101
- }
102
- catch (err) {
103
- return { success: false, error: errorMessage(err) };
104
- }
105
- }
106
- // ── Sync ───────────────────────────────────────────────────────
107
- async sync(options) {
108
- this.ensureConnected();
109
- if (options?.cursor) {
110
- return this.syncIncremental(options.cursor, options.limit);
111
- }
112
- return this.syncFull(options);
113
- }
114
- /** Incremental sync using Gmail history API. */
115
- async syncIncremental(startHistoryId, limit) {
116
- const records = [];
117
- const errors = [];
118
- const seenIds = new Set();
119
- let pageToken;
120
- let latestHistoryId = startHistoryId;
121
- do {
122
- const res = await this.gmail.users.history.list({
123
- userId: 'me',
124
- startHistoryId,
125
- historyTypes: ['messageAdded'],
126
- ...(pageToken ? { pageToken } : {}),
127
- });
128
- latestHistoryId = res.data.historyId ?? latestHistoryId;
129
- const histories = res.data.history ?? [];
130
- for (const h of histories) {
131
- for (const added of h.messagesAdded ?? []) {
132
- const msgId = added.message?.id;
133
- if (!msgId || seenIds.has(msgId))
134
- continue;
135
- seenIds.add(msgId);
136
- try {
137
- const record = await this.fetchMessage(msgId);
138
- records.push(record);
139
- }
140
- catch (err) {
141
- errors.push({ id: msgId, error: errorMessage(err) });
142
- }
143
- if (limit && records.length >= limit) {
144
- return { records, cursor: latestHistoryId, hasMore: true, errors };
145
- }
146
- }
147
- }
148
- pageToken = res.data.nextPageToken ?? undefined;
149
- } while (pageToken);
150
- return { records, cursor: latestHistoryId, hasMore: false, errors };
151
- }
152
- /** Full sync — list messages and fetch each one. */
153
- async syncFull(options) {
154
- const records = [];
155
- const errors = [];
156
- const maxResults = options?.limit ?? 100;
157
- let query = '';
158
- if (options?.since) {
159
- // Gmail `after:` uses epoch seconds
160
- const epoch = Math.floor(new Date(options.since).getTime() / 1000);
161
- query = `after:${epoch}`;
162
- }
163
- if (options?.filters?.q) {
164
- query = query ? `${query} ${options.filters.q}` : String(options.filters.q);
165
- }
166
- let pageToken;
167
- let collected = 0;
168
- do {
169
- const res = await this.gmail.users.messages.list({
170
- userId: 'me',
171
- maxResults: Math.min(maxResults - collected, 100),
172
- ...(query ? { q: query } : {}),
173
- ...(pageToken ? { pageToken } : {}),
174
- });
175
- const messages = res.data.messages ?? [];
176
- for (const msg of messages) {
177
- try {
178
- const record = await this.fetchMessage(msg.id);
179
- records.push(record);
180
- }
181
- catch (err) {
182
- errors.push({ id: msg.id, error: errorMessage(err) });
183
- }
184
- collected++;
185
- if (collected >= maxResults)
186
- break;
187
- }
188
- pageToken = res.data.nextPageToken ?? undefined;
189
- } while (pageToken && collected < maxResults);
190
- // Get current historyId for future incremental syncs
191
- const profile = await this.gmail.users.getProfile({ userId: 'me' });
192
- const cursor = profile.data.historyId ?? undefined;
193
- return {
194
- records,
195
- cursor,
196
- hasMore: !!pageToken,
197
- errors,
198
- };
199
- }
200
- // ── Push (send email) ─────────────────────────────────────────
201
- async push(payload) {
202
- this.ensureConnected();
203
- try {
204
- const toHeader = payload.to.map(formatAddress).join(', ');
205
- const ccHeader = payload.cc.length
206
- ? `Cc: ${payload.cc.map(formatAddress).join(', ')}\r\n`
207
- : '';
208
- const bccHeader = payload.bcc.length
209
- ? `Bcc: ${payload.bcc.map(formatAddress).join(', ')}\r\n`
210
- : '';
211
- const mime = [
212
- `To: ${toHeader}\r\n`,
213
- ccHeader,
214
- bccHeader,
215
- `Subject: ${payload.subject}\r\n`,
216
- `Content-Type: text/plain; charset="UTF-8"\r\n`,
217
- `\r\n`,
218
- payload.body ?? '',
219
- ].join('');
220
- const encoded = Buffer.from(mime)
221
- .toString('base64')
222
- .replace(/\+/g, '-')
223
- .replace(/\//g, '_')
224
- .replace(/=+$/, '');
225
- const res = await this.gmail.users.messages.send({
226
- userId: 'me',
227
- requestBody: { raw: encoded },
228
- });
229
- return { success: true, externalId: res.data.id };
230
- }
231
- catch (err) {
232
- return { success: false, error: errorMessage(err) };
233
- }
234
- }
235
- // ── Internals ─────────────────────────────────────────────────
236
- ensureConnected() {
237
- if (!this.gmail || !this.config) {
238
- throw new Error('GoogleGmailConnector is not connected. Call connect() first.');
239
- }
240
- }
241
- /** Fetch a single message by ID and parse into an EmailRecord. */
242
- async fetchMessage(messageId) {
243
- const res = await this.gmail.users.messages.get({
244
- userId: 'me',
245
- id: messageId,
246
- format: 'full',
247
- });
248
- const msg = res.data;
249
- const headers = msg.payload?.headers ?? [];
250
- const getHeader = (name) => headers.find((h) => h.name.toLowerCase() === name.toLowerCase())?.value ?? '';
251
- return {
252
- gmailId: msg.id,
253
- threadId: msg.threadId,
254
- account: this.config.account,
255
- subject: getHeader('Subject'),
256
- from: parseAddress(getHeader('From')),
257
- to: parseAddressList(getHeader('To')),
258
- cc: parseAddressList(getHeader('Cc')),
259
- bcc: parseAddressList(getHeader('Bcc')),
260
- date: new Date(getHeader('Date')).toISOString(),
261
- snippet: msg.snippet ?? '',
262
- body: extractPlainTextBody(msg.payload),
263
- labels: msg.labelIds ?? [],
264
- isRead: !(msg.labelIds ?? []).includes('UNREAD'),
265
- };
266
- }
267
- }
268
- // ── MIME body extraction ──────────────────────────────────────────
269
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
270
- function extractPlainTextBody(payload) {
271
- if (!payload)
272
- return undefined;
273
- // Single-part message: body is directly on the payload
274
- if (payload.mimeType === 'text/plain' && payload.body?.data) {
275
- return decodeBase64Url(payload.body.data);
276
- }
277
- // Multipart: recurse through parts, prefer text/plain
278
- if (payload.parts) {
279
- // First pass: look for text/plain
280
- for (const part of payload.parts) {
281
- if (part.mimeType === 'text/plain' && part.body?.data) {
282
- return decodeBase64Url(part.body.data);
283
- }
284
- }
285
- // Second pass: recurse into nested multipart
286
- for (const part of payload.parts) {
287
- if (part.mimeType?.startsWith('multipart/')) {
288
- const result = extractPlainTextBody(part);
289
- if (result)
290
- return result;
291
- }
292
- }
293
- }
294
- return undefined;
295
- }
296
- function decodeBase64Url(data) {
297
- const base64 = data.replace(/-/g, '+').replace(/_/g, '/');
298
- return Buffer.from(base64, 'base64').toString('utf-8');
299
- }
300
- // ── Address parsing utilities ──────────────────────────────────────
301
- /**
302
- * Parse a single "Name <email>" or bare "email" string.
303
- */
304
- function parseAddress(raw) {
305
- const match = raw.match(/^(.+?)\s*<([^>]+)>$/);
306
- if (match) {
307
- return { name: match[1].replace(/^["']|["']$/g, '').trim(), email: match[2] };
308
- }
309
- return { email: raw.trim() };
310
- }
311
- /**
312
- * Parse a comma-separated list of addresses.
313
- */
314
- function parseAddressList(raw) {
315
- if (!raw.trim())
316
- return [];
317
- const results = [];
318
- let current = '';
319
- let depth = 0;
320
- for (const ch of raw) {
321
- if (ch === '<')
322
- depth++;
323
- else if (ch === '>')
324
- depth--;
325
- else if (ch === ',' && depth === 0) {
326
- if (current.trim())
327
- results.push(parseAddress(current.trim()));
328
- current = '';
329
- continue;
330
- }
331
- current += ch;
332
- }
333
- if (current.trim())
334
- results.push(parseAddress(current.trim()));
335
- return results;
336
- }
337
- /**
338
- * Format an EmailAddress back into "Name <email>" string.
339
- */
340
- function formatAddress(addr) {
341
- return addr.name ? `${addr.name} <${addr.email}>` : addr.email;
342
- }
343
- function errorMessage(err) {
344
- return err instanceof Error ? err.message : String(err);
345
- }
@@ -1,48 +0,0 @@
1
- /**
2
- * Google OAuth2 helpers.
3
- *
4
- * Uses dynamic `import('googleapis')` so the package is only required
5
- * at runtime by consumers who actually use the Google connectors.
6
- */
7
- import type { GoogleOAuthConfig, GoogleServiceAccountConfig, GoogleTokens } from './types.js';
8
- type OAuth2Client = any;
9
- /**
10
- * Create a Google OAuth2 client from app credentials.
11
- */
12
- export declare function createOAuth2Client(config: GoogleOAuthConfig): Promise<OAuth2Client>;
13
- /**
14
- * Generate the consent screen URL for the given scopes.
15
- */
16
- export declare function getAuthUrl(client: OAuth2Client, scopes: string[]): string;
17
- /**
18
- * Exchange an authorization code for tokens.
19
- */
20
- export declare function exchangeCode(client: OAuth2Client, code: string): Promise<GoogleTokens>;
21
- /**
22
- * Create an authenticated client using a service account with
23
- * domain-wide delegation (impersonation). No browser flow needed.
24
- */
25
- export declare function createServiceAccountClient(config: GoogleServiceAccountConfig, scopes: string[]): Promise<OAuth2Client>;
26
- /**
27
- * Load persisted tokens via a generic getter callback.
28
- *
29
- * @param getter Reads a string value by key (e.g. SecretStore.get)
30
- * @param accountKey Unique key prefix for this account
31
- */
32
- export declare function loadTokens(getter: (key: string) => Promise<string | null>, accountKey: string): Promise<GoogleTokens | null>;
33
- /**
34
- * Persist tokens via a generic setter callback.
35
- *
36
- * @param setter Writes a string value by key (e.g. SecretStore.set)
37
- * @param accountKey Unique key prefix for this account
38
- * @param tokens Tokens to persist
39
- */
40
- export declare function saveTokens(setter: (key: string, value: string) => Promise<void>, accountKey: string, tokens: GoogleTokens): Promise<void>;
41
- /**
42
- * Refresh the access token if it has expired (or is about to within 60 s).
43
- *
44
- * If the token was refreshed and a `saver` callback is provided, the new
45
- * tokens are persisted automatically.
46
- */
47
- export declare function refreshIfNeeded(client: OAuth2Client, tokens: GoogleTokens, saver?: (tokens: GoogleTokens) => Promise<void>): Promise<GoogleTokens>;
48
- export {};
@@ -1,112 +0,0 @@
1
- /**
2
- * Google OAuth2 helpers.
3
- *
4
- * Uses dynamic `import('googleapis')` so the package is only required
5
- * at runtime by consumers who actually use the Google connectors.
6
- */
7
- // ── Lazy googleapis import ─────────────────────────────────────────
8
- let _google;
9
- async function getGoogle() {
10
- if (!_google) {
11
- try {
12
- const mod = await import('googleapis');
13
- _google = mod.google;
14
- }
15
- catch {
16
- throw new Error('googleapis is required for Google connectors. Install it: npm install googleapis');
17
- }
18
- }
19
- return _google;
20
- }
21
- // ── Public helpers ─────────────────────────────────────────────────
22
- /**
23
- * Create a Google OAuth2 client from app credentials.
24
- */
25
- export async function createOAuth2Client(config) {
26
- const google = await getGoogle();
27
- return new google.auth.OAuth2(config.clientId, config.clientSecret, config.redirectUri);
28
- }
29
- /**
30
- * Generate the consent screen URL for the given scopes.
31
- */
32
- export function getAuthUrl(client, scopes) {
33
- return client.generateAuthUrl({
34
- access_type: 'offline',
35
- prompt: 'consent',
36
- scope: scopes,
37
- });
38
- }
39
- /**
40
- * Exchange an authorization code for tokens.
41
- */
42
- export async function exchangeCode(client, code) {
43
- const { tokens } = await client.getToken(code);
44
- return tokens;
45
- }
46
- // ── Service account auth ──────────────────────────────────────────
47
- /**
48
- * Create an authenticated client using a service account with
49
- * domain-wide delegation (impersonation). No browser flow needed.
50
- */
51
- export async function createServiceAccountClient(config, scopes) {
52
- const google = await getGoogle();
53
- const auth = new google.auth.GoogleAuth({
54
- ...(config.keyFile ? { keyFile: config.keyFile } : {}),
55
- ...(config.credentials ? { credentials: config.credentials } : {}),
56
- scopes,
57
- clientOptions: { subject: config.subject },
58
- });
59
- return auth.getClient();
60
- }
61
- // ── Token persistence ──────────────────────────────────────────────
62
- /**
63
- * Load persisted tokens via a generic getter callback.
64
- *
65
- * @param getter Reads a string value by key (e.g. SecretStore.get)
66
- * @param accountKey Unique key prefix for this account
67
- */
68
- export async function loadTokens(getter, accountKey) {
69
- const raw = await getter(`google_tokens:${accountKey}`);
70
- if (!raw)
71
- return null;
72
- try {
73
- return JSON.parse(raw);
74
- }
75
- catch {
76
- return null;
77
- }
78
- }
79
- /**
80
- * Persist tokens via a generic setter callback.
81
- *
82
- * @param setter Writes a string value by key (e.g. SecretStore.set)
83
- * @param accountKey Unique key prefix for this account
84
- * @param tokens Tokens to persist
85
- */
86
- export async function saveTokens(setter, accountKey, tokens) {
87
- await setter(`google_tokens:${accountKey}`, JSON.stringify(tokens));
88
- }
89
- /**
90
- * Refresh the access token if it has expired (or is about to within 60 s).
91
- *
92
- * If the token was refreshed and a `saver` callback is provided, the new
93
- * tokens are persisted automatically.
94
- */
95
- export async function refreshIfNeeded(client, tokens, saver) {
96
- const buffer = 60_000; // 60 seconds
97
- const isExpired = tokens.expiry_date != null && Date.now() >= tokens.expiry_date - buffer;
98
- if (!isExpired)
99
- return tokens;
100
- client.setCredentials(tokens);
101
- const { credentials } = await client.refreshAccessToken();
102
- const refreshed = {
103
- access_token: credentials.access_token,
104
- refresh_token: credentials.refresh_token ?? tokens.refresh_token,
105
- expiry_date: credentials.expiry_date ?? undefined,
106
- token_type: credentials.token_type ?? 'Bearer',
107
- };
108
- if (saver) {
109
- await saver(refreshed);
110
- }
111
- return refreshed;
112
- }
@@ -1,78 +0,0 @@
1
- /** Google connector types. */
2
- import type { ConnectorConfig } from '../../shared/types/connector.js';
3
- export interface GoogleOAuthConfig {
4
- clientId: string;
5
- clientSecret: string;
6
- redirectUri: string;
7
- }
8
- export interface GoogleTokens {
9
- access_token: string;
10
- refresh_token?: string;
11
- expiry_date?: number;
12
- token_type: string;
13
- }
14
- export interface GoogleServiceAccountConfig {
15
- /** Path to service account key JSON file */
16
- keyFile?: string;
17
- /** Inline service account credentials (alternative to keyFile) */
18
- credentials?: {
19
- client_email: string;
20
- private_key: string;
21
- project_id?: string;
22
- };
23
- /** Email of the user to impersonate via domain-wide delegation */
24
- subject: string;
25
- }
26
- export interface GoogleConnectorConfig extends ConnectorConfig {
27
- /** Google account email */
28
- account: string;
29
- /** OAuth2 user auth (requires browser flow) */
30
- oauth?: GoogleOAuthConfig;
31
- /** Service account auth (headless, for cloud deployments) */
32
- serviceAccount?: GoogleServiceAccountConfig;
33
- scopes?: string[];
34
- }
35
- export interface EmailAddress {
36
- name?: string;
37
- email: string;
38
- }
39
- export interface EmailRecord {
40
- gmailId: string;
41
- threadId: string;
42
- account: string;
43
- subject: string;
44
- from: EmailAddress;
45
- to: EmailAddress[];
46
- cc: EmailAddress[];
47
- bcc: EmailAddress[];
48
- /** ISO 8601 timestamp */
49
- date: string;
50
- snippet: string;
51
- body?: string;
52
- labels: string[];
53
- isRead: boolean;
54
- }
55
- export interface CalendarAttendee {
56
- email: string;
57
- displayName?: string;
58
- responseStatus?: string;
59
- }
60
- export interface CalendarEventRecord {
61
- googleEventId: string;
62
- calendarId: string;
63
- account: string;
64
- title: string;
65
- description?: string;
66
- location?: string;
67
- /** ISO 8601 timestamp */
68
- startAt: string;
69
- /** ISO 8601 timestamp */
70
- endAt: string;
71
- allDay: boolean;
72
- timezone?: string;
73
- status: string;
74
- organizerEmail: string;
75
- attendees: CalendarAttendee[];
76
- recurrence?: string[];
77
- htmlLink?: string;
78
- }
@@ -1,2 +0,0 @@
1
- /** Google connector types. */
2
- export {};
@@ -1,16 +0,0 @@
1
- /**
2
- * Auto-discovery for channel adapters.
3
- * Scans @botinabox/* packages for botinabox.type === 'channel'.
4
- * Story 4.1
5
- */
6
- import type { ChannelAdapter } from "./types.js";
7
- type Importer = (packageName: string) => Promise<unknown>;
8
- /**
9
- * Scans nodeModulesPath/@botinabox/{pkg}/package.json for each package in the scope.
10
- * If pkg.botinabox?.type === 'channel', dynamically imports the package
11
- * and returns the discovered ChannelAdapter instances.
12
- *
13
- * The optional importer parameter allows injection for testing.
14
- */
15
- export declare function discoverChannels(nodeModulesPath: string, importer?: Importer): Promise<ChannelAdapter[]>;
16
- export {};
@@ -1,54 +0,0 @@
1
- /**
2
- * Auto-discovery for channel adapters.
3
- * Scans @botinabox/* packages for botinabox.type === 'channel'.
4
- * Story 4.1
5
- */
6
- import { readdir, readFile } from "node:fs/promises";
7
- import { join } from "node:path";
8
- /**
9
- * Scans nodeModulesPath/@botinabox/{pkg}/package.json for each package in the scope.
10
- * If pkg.botinabox?.type === 'channel', dynamically imports the package
11
- * and returns the discovered ChannelAdapter instances.
12
- *
13
- * The optional importer parameter allows injection for testing.
14
- */
15
- export async function discoverChannels(nodeModulesPath, importer = (name) => import(name)) {
16
- const scopeDir = join(nodeModulesPath, "@botinabox");
17
- let entries;
18
- try {
19
- entries = await readdir(scopeDir);
20
- }
21
- catch {
22
- // No @botinabox scope directory — gracefully return empty
23
- return [];
24
- }
25
- const adapters = [];
26
- for (const entry of entries) {
27
- const pkgPath = join(scopeDir, entry, "package.json");
28
- let pkg;
29
- try {
30
- const raw = await readFile(pkgPath, "utf8");
31
- pkg = JSON.parse(raw);
32
- }
33
- catch {
34
- continue;
35
- }
36
- const botinabox = pkg.botinabox;
37
- if (botinabox?.type !== "channel") {
38
- continue;
39
- }
40
- const packageName = pkg.name;
41
- if (!packageName) {
42
- continue;
43
- }
44
- try {
45
- const mod = await importer(packageName);
46
- const adapter = "default" in mod && mod.default ? mod.default : mod;
47
- adapters.push(adapter);
48
- }
49
- catch {
50
- // Failed to import — skip silently
51
- }
52
- }
53
- return adapters;
54
- }