botinabox 2.4.3 → 2.5.1

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 (276) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +190 -190
  3. package/bin/botinabox.mjs +1 -1
  4. package/dist/cli.js +0 -0
  5. package/dist/connectors/google/index.d.ts +67 -1
  6. package/dist/connectors/google/index.js +240 -0
  7. package/dist/index.js +19 -5
  8. package/package.json +100 -99
  9. package/dist/channels/discord/adapter.d.ts +0 -32
  10. package/dist/channels/discord/adapter.js +0 -70
  11. package/dist/channels/discord/inbound.d.ts +0 -25
  12. package/dist/channels/discord/inbound.js +0 -24
  13. package/dist/channels/discord/models.d.ts +0 -8
  14. package/dist/channels/discord/models.js +0 -5
  15. package/dist/channels/discord/outbound.d.ts +0 -14
  16. package/dist/channels/discord/outbound.js +0 -38
  17. package/dist/channels/slack/adapter.d.ts +0 -33
  18. package/dist/channels/slack/adapter.js +0 -74
  19. package/dist/channels/slack/inbound.d.ts +0 -59
  20. package/dist/channels/slack/inbound.js +0 -96
  21. package/dist/channels/slack/models.d.ts +0 -9
  22. package/dist/channels/slack/models.js +0 -5
  23. package/dist/channels/slack/outbound.d.ts +0 -12
  24. package/dist/channels/slack/outbound.js +0 -18
  25. package/dist/channels/slack/transcribe.d.ts +0 -41
  26. package/dist/channels/slack/transcribe.js +0 -106
  27. package/dist/channels/webhook/adapter.d.ts +0 -23
  28. package/dist/channels/webhook/adapter.js +0 -86
  29. package/dist/channels/webhook/hmac.d.ts +0 -13
  30. package/dist/channels/webhook/hmac.js +0 -26
  31. package/dist/channels/webhook/models.d.ts +0 -9
  32. package/dist/channels/webhook/models.js +0 -5
  33. package/dist/channels/webhook/server.d.ts +0 -20
  34. package/dist/channels/webhook/server.js +0 -91
  35. package/dist/chat-pipeline-C-XlLGNl.d.ts +0 -648
  36. package/dist/chat-pipeline-CR1KF6eX.d.ts +0 -652
  37. package/dist/chat-pipeline-DisuC8SB.d.ts +0 -643
  38. package/dist/chunk-2LGXQPEA.js +0 -41
  39. package/dist/chunk-3X3YKI4T.js +0 -357
  40. package/dist/chunk-D47AIFOD.js +0 -351
  41. package/dist/chunk-DSNJKNEW.js +0 -328
  42. package/dist/chunk-GS2JFL6I.js +0 -144
  43. package/dist/chunk-J6S6QMUY.js +0 -144
  44. package/dist/chunk-QLA6YOFN.js +0 -22
  45. package/dist/chunk-UACT2WXX.js +0 -381
  46. package/dist/cli/templates/config.yml.d.ts +0 -7
  47. package/dist/cli/templates/config.yml.js +0 -61
  48. package/dist/cli/templates/env.d.ts +0 -1
  49. package/dist/cli/templates/env.js +0 -30
  50. package/dist/cli/templates/index.ts.d.ts +0 -2
  51. package/dist/cli/templates/index.ts.js +0 -30
  52. package/dist/cli/templates/package.json.d.ts +0 -5
  53. package/dist/cli/templates/package.json.js +0 -28
  54. package/dist/connector-DDahQw-2.d.ts +0 -63
  55. package/dist/connectors/google/calendar-connector.d.ts +0 -40
  56. package/dist/connectors/google/calendar-connector.js +0 -243
  57. package/dist/connectors/google/gmail-connector.d.ts +0 -42
  58. package/dist/connectors/google/gmail-connector.js +0 -345
  59. package/dist/connectors/google/oauth.d.ts +0 -48
  60. package/dist/connectors/google/oauth.js +0 -112
  61. package/dist/connectors/google/types.d.ts +0 -78
  62. package/dist/connectors/google/types.js +0 -2
  63. package/dist/core/chat/auto-discovery.d.ts +0 -16
  64. package/dist/core/chat/auto-discovery.js +0 -54
  65. package/dist/core/chat/channel-registry.d.ts +0 -45
  66. package/dist/core/chat/channel-registry.js +0 -96
  67. package/dist/core/chat/chat-pipeline.d.ts +0 -113
  68. package/dist/core/chat/chat-pipeline.js +0 -395
  69. package/dist/core/chat/chat-responder.d.ts +0 -90
  70. package/dist/core/chat/chat-responder.js +0 -185
  71. package/dist/core/chat/formatter.d.ts +0 -11
  72. package/dist/core/chat/formatter.js +0 -60
  73. package/dist/core/chat/index.d.ts +0 -24
  74. package/dist/core/chat/index.js +0 -18
  75. package/dist/core/chat/message-interpreter.d.ts +0 -91
  76. package/dist/core/chat/message-interpreter.js +0 -166
  77. package/dist/core/chat/message-store.d.ts +0 -66
  78. package/dist/core/chat/message-store.js +0 -131
  79. package/dist/core/chat/notification-queue.d.ts +0 -34
  80. package/dist/core/chat/notification-queue.js +0 -111
  81. package/dist/core/chat/pipeline.d.ts +0 -38
  82. package/dist/core/chat/pipeline.js +0 -89
  83. package/dist/core/chat/policies.d.ts +0 -16
  84. package/dist/core/chat/policies.js +0 -25
  85. package/dist/core/chat/routing.d.ts +0 -17
  86. package/dist/core/chat/routing.js +0 -36
  87. package/dist/core/chat/session-key.d.ts +0 -30
  88. package/dist/core/chat/session-key.js +0 -65
  89. package/dist/core/chat/session-manager.d.ts +0 -17
  90. package/dist/core/chat/session-manager.js +0 -23
  91. package/dist/core/chat/text-chunker.d.ts +0 -9
  92. package/dist/core/chat/text-chunker.js +0 -48
  93. package/dist/core/chat/triage-router.d.ts +0 -75
  94. package/dist/core/chat/triage-router.js +0 -142
  95. package/dist/core/chat/types.d.ts +0 -5
  96. package/dist/core/chat/types.js +0 -5
  97. package/dist/core/config/defaults.d.ts +0 -2
  98. package/dist/core/config/defaults.js +0 -38
  99. package/dist/core/config/index.d.ts +0 -6
  100. package/dist/core/config/index.js +0 -4
  101. package/dist/core/config/interpolate.d.ts +0 -5
  102. package/dist/core/config/interpolate.js +0 -27
  103. package/dist/core/config/loader.d.ts +0 -24
  104. package/dist/core/config/loader.js +0 -59
  105. package/dist/core/config/schema.d.ts +0 -5
  106. package/dist/core/config/schema.js +0 -119
  107. package/dist/core/data/core-entity-contexts.d.ts +0 -14
  108. package/dist/core/data/core-entity-contexts.js +0 -197
  109. package/dist/core/data/core-migrations.d.ts +0 -5
  110. package/dist/core/data/core-migrations.js +0 -45
  111. package/dist/core/data/core-schema.d.ts +0 -6
  112. package/dist/core/data/core-schema.js +0 -454
  113. package/dist/core/data/data-store.d.ts +0 -67
  114. package/dist/core/data/data-store.js +0 -218
  115. package/dist/core/data/domain-entity-contexts.d.ts +0 -29
  116. package/dist/core/data/domain-entity-contexts.js +0 -321
  117. package/dist/core/data/domain-schema.d.ts +0 -36
  118. package/dist/core/data/domain-schema.js +0 -323
  119. package/dist/core/data/index.d.ts +0 -7
  120. package/dist/core/data/index.js +0 -7
  121. package/dist/core/data/types.d.ts +0 -111
  122. package/dist/core/data/types.js +0 -1
  123. package/dist/core/hooks/hook-bus.d.ts +0 -18
  124. package/dist/core/hooks/hook-bus.js +0 -120
  125. package/dist/core/hooks/index.d.ts +0 -2
  126. package/dist/core/hooks/index.js +0 -1
  127. package/dist/core/hooks/types.d.ts +0 -19
  128. package/dist/core/hooks/types.js +0 -1
  129. package/dist/core/index.d.ts +0 -4
  130. package/dist/core/index.js +0 -4
  131. package/dist/core/llm/auto-discovery.d.ts +0 -11
  132. package/dist/core/llm/auto-discovery.js +0 -49
  133. package/dist/core/llm/cost-tracker.d.ts +0 -6
  134. package/dist/core/llm/cost-tracker.js +0 -38
  135. package/dist/core/llm/index.d.ts +0 -4
  136. package/dist/core/llm/index.js +0 -3
  137. package/dist/core/llm/model-router.d.ts +0 -25
  138. package/dist/core/llm/model-router.js +0 -49
  139. package/dist/core/llm/provider-registry.d.ts +0 -9
  140. package/dist/core/llm/provider-registry.js +0 -25
  141. package/dist/core/llm/types.d.ts +0 -2
  142. package/dist/core/llm/types.js +0 -2
  143. package/dist/core/orchestrator/adapters/api-adapter.d.ts +0 -34
  144. package/dist/core/orchestrator/adapters/api-adapter.js +0 -88
  145. package/dist/core/orchestrator/adapters/cli-adapter.d.ts +0 -22
  146. package/dist/core/orchestrator/adapters/cli-adapter.js +0 -69
  147. package/dist/core/orchestrator/adapters/deterministic-adapter.d.ts +0 -35
  148. package/dist/core/orchestrator/adapters/deterministic-adapter.js +0 -75
  149. package/dist/core/orchestrator/adapters/env-whitelist.d.ts +0 -4
  150. package/dist/core/orchestrator/adapters/env-whitelist.js +0 -27
  151. package/dist/core/orchestrator/adapters/output-extractor.d.ts +0 -11
  152. package/dist/core/orchestrator/adapters/output-extractor.js +0 -59
  153. package/dist/core/orchestrator/adapters/process-manager.d.ts +0 -15
  154. package/dist/core/orchestrator/adapters/process-manager.js +0 -26
  155. package/dist/core/orchestrator/adapters/tool-loop.d.ts +0 -22
  156. package/dist/core/orchestrator/adapters/tool-loop.js +0 -66
  157. package/dist/core/orchestrator/agent-registry.d.ts +0 -31
  158. package/dist/core/orchestrator/agent-registry.js +0 -135
  159. package/dist/core/orchestrator/budget-controller.d.ts +0 -19
  160. package/dist/core/orchestrator/budget-controller.js +0 -73
  161. package/dist/core/orchestrator/chain-guard.d.ts +0 -14
  162. package/dist/core/orchestrator/chain-guard.js +0 -23
  163. package/dist/core/orchestrator/circuit-breaker.d.ts +0 -65
  164. package/dist/core/orchestrator/circuit-breaker.js +0 -159
  165. package/dist/core/orchestrator/claude-stream-parser.d.ts +0 -31
  166. package/dist/core/orchestrator/claude-stream-parser.js +0 -99
  167. package/dist/core/orchestrator/config-revisions.d.ts +0 -6
  168. package/dist/core/orchestrator/config-revisions.js +0 -17
  169. package/dist/core/orchestrator/dependency-resolver.d.ts +0 -20
  170. package/dist/core/orchestrator/dependency-resolver.js +0 -78
  171. package/dist/core/orchestrator/governance-gate.d.ts +0 -110
  172. package/dist/core/orchestrator/governance-gate.js +0 -170
  173. package/dist/core/orchestrator/learning-pipeline.d.ts +0 -109
  174. package/dist/core/orchestrator/learning-pipeline.js +0 -249
  175. package/dist/core/orchestrator/loop-detector.d.ts +0 -51
  176. package/dist/core/orchestrator/loop-detector.js +0 -133
  177. package/dist/core/orchestrator/ndjson-logger.d.ts +0 -6
  178. package/dist/core/orchestrator/ndjson-logger.js +0 -18
  179. package/dist/core/orchestrator/permission-relay.d.ts +0 -72
  180. package/dist/core/orchestrator/permission-relay.js +0 -164
  181. package/dist/core/orchestrator/run-manager.d.ts +0 -31
  182. package/dist/core/orchestrator/run-manager.js +0 -178
  183. package/dist/core/orchestrator/scheduler.d.ts +0 -70
  184. package/dist/core/orchestrator/scheduler.js +0 -198
  185. package/dist/core/orchestrator/secret-store.d.ts +0 -57
  186. package/dist/core/orchestrator/secret-store.js +0 -171
  187. package/dist/core/orchestrator/session-manager.d.ts +0 -13
  188. package/dist/core/orchestrator/session-manager.js +0 -66
  189. package/dist/core/orchestrator/task-queue.d.ts +0 -34
  190. package/dist/core/orchestrator/task-queue.js +0 -83
  191. package/dist/core/orchestrator/template-interpolate.d.ts +0 -5
  192. package/dist/core/orchestrator/template-interpolate.js +0 -18
  193. package/dist/core/orchestrator/user-registry.d.ts +0 -47
  194. package/dist/core/orchestrator/user-registry.js +0 -76
  195. package/dist/core/orchestrator/wakeup-queue.d.ts +0 -9
  196. package/dist/core/orchestrator/wakeup-queue.js +0 -45
  197. package/dist/core/orchestrator/workflow-engine.d.ts +0 -47
  198. package/dist/core/orchestrator/workflow-engine.js +0 -204
  199. package/dist/core/security/audit.d.ts +0 -20
  200. package/dist/core/security/audit.js +0 -33
  201. package/dist/core/security/column-validator.d.ts +0 -20
  202. package/dist/core/security/column-validator.js +0 -37
  203. package/dist/core/security/index.d.ts +0 -5
  204. package/dist/core/security/index.js +0 -5
  205. package/dist/core/security/process-env.d.ts +0 -13
  206. package/dist/core/security/process-env.js +0 -49
  207. package/dist/core/security/sanitizer.d.ts +0 -11
  208. package/dist/core/security/sanitizer.js +0 -39
  209. package/dist/core/security/types.d.ts +0 -11
  210. package/dist/core/security/types.js +0 -1
  211. package/dist/core/update/auto-update.d.ts +0 -21
  212. package/dist/core/update/auto-update.js +0 -102
  213. package/dist/core/update/backup-manager.d.ts +0 -7
  214. package/dist/core/update/backup-manager.js +0 -24
  215. package/dist/core/update/index.d.ts +0 -8
  216. package/dist/core/update/index.js +0 -6
  217. package/dist/core/update/migration-hooks.d.ts +0 -11
  218. package/dist/core/update/migration-hooks.js +0 -10
  219. package/dist/core/update/types.d.ts +0 -11
  220. package/dist/core/update/types.js +0 -1
  221. package/dist/core/update/update-checker.d.ts +0 -11
  222. package/dist/core/update/update-checker.js +0 -63
  223. package/dist/core/update/update-manager.d.ts +0 -25
  224. package/dist/core/update/update-manager.js +0 -101
  225. package/dist/core/update/version-utils.d.ts +0 -6
  226. package/dist/core/update/version-utils.js +0 -34
  227. package/dist/gmail-connector-2FVYTQJH.js +0 -6
  228. package/dist/gmail-connector-MNUBRNFM.js +0 -6
  229. package/dist/gmail-connector-PS2VLGNE.js +0 -6
  230. package/dist/gmail-connector-ULSMN6X2.js +0 -6
  231. package/dist/gmail-connector-URRFX6A3.js +0 -6
  232. package/dist/inbound-AFBUPSPG.js +0 -10
  233. package/dist/inbound-AFOHYNUY.js +0 -6
  234. package/dist/inbound-CGIXRXGC.js +0 -8
  235. package/dist/inbound-MCOLRH6U.js +0 -10
  236. package/dist/inbound-SNEMBLGA.js +0 -6
  237. package/dist/inbound-ZJHAYVMF.js +0 -10
  238. package/dist/provider-qqJYv9nv.d.ts +0 -75
  239. package/dist/providers/anthropic/models.d.ts +0 -2
  240. package/dist/providers/anthropic/models.js +0 -29
  241. package/dist/providers/anthropic/provider.d.ts +0 -13
  242. package/dist/providers/anthropic/provider.js +0 -119
  243. package/dist/providers/anthropic/tool-converter.d.ts +0 -10
  244. package/dist/providers/anthropic/tool-converter.js +0 -7
  245. package/dist/providers/ollama/provider.d.ts +0 -17
  246. package/dist/providers/ollama/provider.js +0 -185
  247. package/dist/providers/openai/models.d.ts +0 -2
  248. package/dist/providers/openai/models.js +0 -29
  249. package/dist/providers/openai/provider.d.ts +0 -13
  250. package/dist/providers/openai/provider.js +0 -163
  251. package/dist/providers/openai/tool-converter.d.ts +0 -10
  252. package/dist/providers/openai/tool-converter.js +0 -10
  253. package/dist/shared/constants.d.ts +0 -50
  254. package/dist/shared/constants.js +0 -64
  255. package/dist/shared/index.d.ts +0 -14
  256. package/dist/shared/index.js +0 -14
  257. package/dist/shared/types/agent.d.ts +0 -36
  258. package/dist/shared/types/agent.js +0 -2
  259. package/dist/shared/types/channel.d.ts +0 -70
  260. package/dist/shared/types/channel.js +0 -2
  261. package/dist/shared/types/config.d.ts +0 -111
  262. package/dist/shared/types/config.js +0 -2
  263. package/dist/shared/types/connector.d.ts +0 -77
  264. package/dist/shared/types/connector.js +0 -2
  265. package/dist/shared/types/execution.d.ts +0 -29
  266. package/dist/shared/types/execution.js +0 -2
  267. package/dist/shared/types/provider.d.ts +0 -73
  268. package/dist/shared/types/provider.js +0 -2
  269. package/dist/shared/types/task.d.ts +0 -47
  270. package/dist/shared/types/task.js +0 -2
  271. package/dist/shared/types/workflow.d.ts +0 -39
  272. package/dist/shared/types/workflow.js +0 -2
  273. package/dist/shared/utils.d.ts +0 -6
  274. package/dist/shared/utils.js +0 -13
  275. package/dist/update-check.d.ts +0 -5
  276. package/dist/update-check.js +0 -56
@@ -1,243 +0,0 @@
1
- /**
2
- * Google Calendar connector — pulls calendar events.
3
- *
4
- * Produces `CalendarEventRecord` objects. Does NOT write to any database
5
- * table; 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 GoogleCalendarConnector {
10
- id = 'google-calendar';
11
- meta = {
12
- displayName: 'Google Calendar',
13
- provider: 'google',
14
- dataType: 'calendar',
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
- calendar = 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/calendar.readonly',
32
- ];
33
- if (config.serviceAccount) {
34
- this.client = await createServiceAccountClient(config.serviceAccount, scopes);
35
- }
36
- else if (config.oauth) {
37
- this.client = await createOAuth2Client(config.oauth);
38
- if (!this.tokenLoader) {
39
- throw new Error('tokenLoader required for OAuth2 flow');
40
- }
41
- this.tokens = await loadTokens(this.tokenLoader, config.account);
42
- if (!this.tokens) {
43
- throw new Error(`No stored tokens for account ${config.account}. Complete the OAuth flow first.`);
44
- }
45
- this.tokens = await refreshIfNeeded(this.client, this.tokens, this.tokenSaver
46
- ? async (t) => saveTokens(this.tokenSaver, config.account, t)
47
- : undefined);
48
- this.client.setCredentials(this.tokens);
49
- }
50
- else {
51
- throw new Error('Either serviceAccount or oauth config is required');
52
- }
53
- const { google } = await import('googleapis');
54
- this.calendar = google.calendar({ version: 'v3', auth: this.client });
55
- }
56
- async disconnect() {
57
- this.client = null;
58
- this.calendar = null;
59
- this.tokens = null;
60
- this.config = null;
61
- }
62
- async healthCheck() {
63
- try {
64
- this.ensureConnected();
65
- const res = await this.calendar.calendarList.list({ maxResults: 1 });
66
- const primary = (res.data.items ?? []).find(
67
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
68
- (c) => c.primary);
69
- return { ok: true, account: primary?.id ?? this.config.account };
70
- }
71
- catch (err) {
72
- return { ok: false, error: errorMessage(err) };
73
- }
74
- }
75
- // ── Auth ───────────────────────────────────────────────────────
76
- async authenticate(codeProvider) {
77
- if (!this.config) {
78
- return { success: false, error: 'Call connect() first to set config, or pass config and call authenticate() before connect().' };
79
- }
80
- try {
81
- if (!this.config.oauth) {
82
- return { success: false, error: 'OAuth config required for browser-based authenticate(). Use serviceAccount for headless auth.' };
83
- }
84
- if (!this.tokenSaver) {
85
- return { success: false, error: 'tokenSaver required for authenticate() flow.' };
86
- }
87
- const client = await createOAuth2Client(this.config.oauth);
88
- const scopes = this.config.scopes ?? [
89
- 'https://www.googleapis.com/auth/calendar.readonly',
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.calendar = google.calendar({ version: 'v3', 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);
111
- }
112
- return this.syncFull(options);
113
- }
114
- /** Incremental sync using Calendar syncToken. */
115
- async syncIncremental(syncToken, options) {
116
- const calendarId = options?.filters?.calendarId ?? 'primary';
117
- const records = [];
118
- const errors = [];
119
- let pageToken;
120
- let nextSyncToken;
121
- try {
122
- do {
123
- const res = await this.calendar.events.list({
124
- calendarId,
125
- syncToken,
126
- ...(pageToken ? { pageToken } : {}),
127
- maxResults: options?.limit ? Math.min(options.limit - records.length, 250) : 250,
128
- });
129
- for (const event of res.data.items ?? []) {
130
- try {
131
- records.push(this.mapEvent(event, calendarId));
132
- }
133
- catch (err) {
134
- errors.push({ id: event.id, error: errorMessage(err) });
135
- }
136
- if (options?.limit && records.length >= options.limit)
137
- break;
138
- }
139
- pageToken = res.data.nextPageToken ?? undefined;
140
- nextSyncToken = res.data.nextSyncToken ?? undefined;
141
- } while (pageToken && (!options?.limit || records.length < options.limit));
142
- }
143
- catch (err) {
144
- // If syncToken is expired/invalid, fall back to full sync
145
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
146
- if (err?.code === 410) {
147
- return this.syncFull(options);
148
- }
149
- throw err;
150
- }
151
- return {
152
- records,
153
- cursor: nextSyncToken,
154
- hasMore: !!pageToken,
155
- errors,
156
- };
157
- }
158
- /** Full sync using timeMin. */
159
- async syncFull(options) {
160
- const calendarId = options?.filters?.calendarId ?? 'primary';
161
- const records = [];
162
- const errors = [];
163
- const maxResults = options?.limit ?? 250;
164
- const timeMin = options?.since
165
- ? new Date(options.since).toISOString()
166
- : new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString(); // default: 30 days ago
167
- let pageToken;
168
- let nextSyncToken;
169
- do {
170
- const res = await this.calendar.events.list({
171
- calendarId,
172
- timeMin,
173
- singleEvents: true,
174
- orderBy: 'startTime',
175
- maxResults: Math.min(maxResults - records.length, 250),
176
- ...(pageToken ? { pageToken } : {}),
177
- });
178
- for (const event of res.data.items ?? []) {
179
- try {
180
- records.push(this.mapEvent(event, calendarId));
181
- }
182
- catch (err) {
183
- errors.push({ id: event.id, error: errorMessage(err) });
184
- }
185
- if (records.length >= maxResults)
186
- break;
187
- }
188
- pageToken = res.data.nextPageToken ?? undefined;
189
- nextSyncToken = res.data.nextSyncToken ?? undefined;
190
- } while (pageToken && records.length < maxResults);
191
- return {
192
- records,
193
- cursor: nextSyncToken,
194
- hasMore: !!pageToken,
195
- errors,
196
- };
197
- }
198
- // ── Internals ─────────────────────────────────────────────────
199
- ensureConnected() {
200
- if (!this.calendar || !this.config) {
201
- throw new Error('GoogleCalendarConnector is not connected. Call connect() first.');
202
- }
203
- }
204
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
205
- mapEvent(event, calendarId) {
206
- const start = event.start ?? {};
207
- const end = event.end ?? {};
208
- const allDay = !!start.date;
209
- const startAt = allDay
210
- ? new Date(start.date).toISOString()
211
- : new Date(start.dateTime).toISOString();
212
- const endAt = allDay
213
- ? new Date(end.date).toISOString()
214
- : new Date(end.dateTime).toISOString();
215
- const attendees = (event.attendees ?? []).map(
216
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
217
- (a) => ({
218
- email: a.email,
219
- displayName: a.displayName,
220
- responseStatus: a.responseStatus,
221
- }));
222
- return {
223
- googleEventId: event.id,
224
- calendarId,
225
- account: this.config.account,
226
- title: event.summary ?? '(No title)',
227
- description: event.description ?? undefined,
228
- location: event.location ?? undefined,
229
- startAt,
230
- endAt,
231
- allDay,
232
- timezone: start.timeZone ?? undefined,
233
- status: event.status ?? 'confirmed',
234
- organizerEmail: event.organizer?.email ?? '',
235
- attendees,
236
- recurrence: event.recurrence ?? undefined,
237
- htmlLink: event.htmlLink ?? undefined,
238
- };
239
- }
240
- }
241
- function errorMessage(err) {
242
- return err instanceof Error ? err.message : String(err);
243
- }
@@ -1,42 +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 type { Connector, ConnectorMeta, AuthResult, SyncOptions, SyncResult, PushResult } from '../../shared/types/connector.js';
8
- import type { EmailRecord, GoogleConnectorConfig } from './types.js';
9
- export interface GmailConnectorOpts {
10
- /** Load persisted tokens for a given account key (OAuth2 flow only). */
11
- tokenLoader?: (key: string) => Promise<string | null>;
12
- /** Persist tokens for a given account key (OAuth2 flow only). */
13
- tokenSaver?: (key: string, value: string) => Promise<void>;
14
- }
15
- export declare class GoogleGmailConnector implements Connector<EmailRecord> {
16
- readonly id = "google-gmail";
17
- readonly meta: ConnectorMeta;
18
- private tokenLoader?;
19
- private tokenSaver?;
20
- private client;
21
- private config;
22
- private tokens;
23
- private gmail;
24
- constructor(opts?: GmailConnectorOpts);
25
- connect(config: GoogleConnectorConfig): Promise<void>;
26
- disconnect(): Promise<void>;
27
- healthCheck(): Promise<{
28
- ok: boolean;
29
- account?: string;
30
- error?: string;
31
- }>;
32
- authenticate(codeProvider: (authUrl: string) => Promise<string>): Promise<AuthResult>;
33
- sync(options?: SyncOptions): Promise<SyncResult<EmailRecord>>;
34
- /** Incremental sync using Gmail history API. */
35
- private syncIncremental;
36
- /** Full sync — list messages and fetch each one. */
37
- private syncFull;
38
- push(payload: EmailRecord): Promise<PushResult>;
39
- private ensureConnected;
40
- /** Fetch a single message by ID and parse into an EmailRecord. */
41
- private fetchMessage;
42
- }
@@ -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 {};