@lobu/runtime-device 24.1.1 → 24.2.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 (158) hide show
  1. package/dist/component.json +1 -1
  2. package/dist/dependencies.bun.lock +26 -28
  3. package/npm-shrinkwrap.json +155 -172
  4. package/package.json +1 -1
  5. package/vendor/cli/dist/bundled-skills/lobu/SKILL.md +14 -5
  6. package/vendor/cli/dist/chrome-extension/accessibility-tree.js +834 -0
  7. package/vendor/cli/dist/chrome-extension/ambient-context.js +53 -0
  8. package/vendor/cli/dist/chrome-extension/auth-refresh.js +167 -0
  9. package/vendor/cli/dist/chrome-extension/automation-run.js +13 -0
  10. package/vendor/cli/dist/chrome-extension/background.js +1155 -0
  11. package/vendor/cli/dist/chrome-extension/bridge.js +140 -0
  12. package/vendor/cli/dist/chrome-extension/browser-origin-policy.js +62 -0
  13. package/vendor/cli/dist/chrome-extension/browser-recovery.js +260 -0
  14. package/vendor/cli/dist/chrome-extension/browser-url-sanitizer.js +284 -0
  15. package/vendor/cli/dist/chrome-extension/completion-response.js +12 -0
  16. package/vendor/cli/dist/chrome-extension/config.js +144 -0
  17. package/vendor/cli/dist/chrome-extension/connector-manifests/chrome.json +1516 -0
  18. package/vendor/cli/dist/chrome-extension/connector-manifests/chrome_bookmarks.json +84 -0
  19. package/vendor/cli/dist/chrome-extension/connector-manifests/chrome_downloads.json +86 -0
  20. package/vendor/cli/dist/chrome-extension/connector-manifests/chrome_history.json +78 -0
  21. package/vendor/cli/dist/chrome-extension/connector-manifests.js +1767 -0
  22. package/vendor/cli/dist/chrome-extension/console-capture.js +627 -0
  23. package/vendor/cli/dist/chrome-extension/control-activity.js +70 -0
  24. package/vendor/cli/dist/chrome-extension/debugger-lease.js +439 -0
  25. package/vendor/cli/dist/chrome-extension/feed-listener.js +488 -0
  26. package/vendor/cli/dist/chrome-extension/feed-transaction.js +48 -0
  27. package/vendor/cli/dist/chrome-extension/feeds.js +632 -0
  28. package/vendor/cli/dist/chrome-extension/focus-tab.js +25 -0
  29. package/vendor/cli/dist/chrome-extension/fonts/dm-mono-latin-500-normal.woff2 +0 -0
  30. package/vendor/cli/dist/chrome-extension/fonts/dm-sans-latin-400-normal.woff2 +0 -0
  31. package/vendor/cli/dist/chrome-extension/fonts/dm-sans-latin-600-normal.woff2 +0 -0
  32. package/vendor/cli/dist/chrome-extension/heartbeat.js +140 -0
  33. package/vendor/cli/dist/chrome-extension/icons/icon-128-rec.png +0 -0
  34. package/vendor/cli/dist/chrome-extension/icons/icon-128.png +0 -0
  35. package/vendor/cli/dist/chrome-extension/icons/icon-16-rec.png +0 -0
  36. package/vendor/cli/dist/chrome-extension/icons/icon-16.png +0 -0
  37. package/vendor/cli/dist/chrome-extension/icons/icon-32-rec.png +0 -0
  38. package/vendor/cli/dist/chrome-extension/icons/icon-32.png +0 -0
  39. package/vendor/cli/dist/chrome-extension/icons/icon-48-rec.png +0 -0
  40. package/vendor/cli/dist/chrome-extension/icons/icon-48.png +0 -0
  41. package/vendor/cli/dist/chrome-extension/lens-page.js +135 -0
  42. package/vendor/cli/dist/chrome-extension/lens-target.js +20 -0
  43. package/vendor/cli/dist/chrome-extension/manifest.json +76 -0
  44. package/vendor/cli/dist/chrome-extension/network-intercept.js +657 -0
  45. package/vendor/cli/dist/chrome-extension/page-activation.js +120 -0
  46. package/vendor/cli/dist/chrome-extension/page-dialogs.js +125 -0
  47. package/vendor/cli/dist/chrome-extension/page-url.js +11 -0
  48. package/vendor/cli/dist/chrome-extension/panel-session.js +184 -0
  49. package/vendor/cli/dist/chrome-extension/poll-auth.js +85 -0
  50. package/vendor/cli/dist/chrome-extension/poll-backoff.js +22 -0
  51. package/vendor/cli/dist/chrome-extension/run-fence.js +117 -0
  52. package/vendor/cli/dist/chrome-extension/setup-status.js +71 -0
  53. package/vendor/cli/dist/chrome-extension/side-panel-action-click.js +65 -0
  54. package/vendor/cli/dist/chrome-extension/sidepanel-context.js +50 -0
  55. package/vendor/cli/dist/chrome-extension/sidepanel.html +680 -0
  56. package/vendor/cli/dist/chrome-extension/sidepanel.js +1643 -0
  57. package/vendor/cli/dist/chrome-extension/tab-labels.js +233 -0
  58. package/vendor/cli/dist/chrome-extension/tools.js +3354 -0
  59. package/vendor/cli/dist/chrome-extension/watch-observer.js +354 -0
  60. package/vendor/cli/dist/chrome-extension/watch-redact.js +96 -0
  61. package/vendor/cli/dist/chrome-extension/watch.js +348 -0
  62. package/vendor/cli/dist/commands/_lib/apply/desired-state.d.ts +6 -4
  63. package/vendor/cli/dist/commands/_lib/apply/desired-state.js +5 -3
  64. package/vendor/cli/dist/commands/_lib/apply/diff.js +4 -3
  65. package/vendor/cli/dist/commands/_lib/chrome-for-testing.d.ts +13 -0
  66. package/vendor/cli/dist/commands/_lib/chrome-for-testing.js +226 -0
  67. package/vendor/cli/dist/commands/_lib/device-credential.d.ts +34 -0
  68. package/vendor/cli/dist/commands/_lib/device-credential.js +157 -0
  69. package/vendor/cli/dist/commands/_lib/device-wizard.d.ts +17 -0
  70. package/vendor/cli/dist/commands/_lib/device-wizard.js +11 -2
  71. package/vendor/cli/dist/commands/_lib/native-messaging.d.ts +7 -0
  72. package/vendor/cli/dist/commands/_lib/native-messaging.js +40 -0
  73. package/vendor/cli/dist/commands/browser.d.ts +23 -0
  74. package/vendor/cli/dist/commands/browser.js +492 -0
  75. package/vendor/cli/dist/commands/call.d.ts +12 -0
  76. package/vendor/cli/dist/commands/call.js +48 -26
  77. package/vendor/cli/dist/commands/context.d.ts +3 -1
  78. package/vendor/cli/dist/commands/context.js +13 -2
  79. package/vendor/cli/dist/commands/daemon.js +2 -152
  80. package/vendor/cli/dist/commands/memory/_lib/errors.d.ts +4 -1
  81. package/vendor/cli/dist/commands/memory/_lib/errors.js +9 -1
  82. package/vendor/cli/dist/commands/memory/_lib/mcp.d.ts +0 -9
  83. package/vendor/cli/dist/commands/memory/_lib/mcp.js +1 -23
  84. package/vendor/cli/dist/commands/memory/_lib/memory-auth.d.ts +20 -4
  85. package/vendor/cli/dist/commands/memory/_lib/memory-auth.js +21 -17
  86. package/vendor/cli/dist/commands/memory/_lib/seed-cmd.js +6 -17
  87. package/vendor/cli/dist/commands/memory/run.js +4 -25
  88. package/vendor/cli/dist/connectors/google_gmail.ts +70 -41
  89. package/vendor/cli/dist/connectors/google_gmail_references.ts +406 -0
  90. package/vendor/cli/dist/connectors/linkedin-inbox-adapter.js +107 -36
  91. package/vendor/cli/dist/connectors/linkedin-inbox.ts +13 -0
  92. package/vendor/cli/dist/connectors/linkedin.ts +1 -1
  93. package/vendor/cli/dist/connectors/postgres.ts +5 -3
  94. package/vendor/cli/dist/connectors/reddit.ts +171 -5
  95. package/vendor/cli/dist/connectors/whatsapp-web-adapter.js +147 -61
  96. package/vendor/cli/dist/connectors/whatsapp-web-helpers.ts +6 -2
  97. package/vendor/cli/dist/connectors/whatsapp_web.ts +48 -17
  98. package/vendor/cli/dist/connectors/x-dm-adapter.js +252 -35
  99. package/vendor/cli/dist/connectors/x.ts +189 -13
  100. package/vendor/cli/dist/index.js +46 -6
  101. package/vendor/cli/dist/internal/device-state.d.ts +2 -0
  102. package/vendor/cli/dist/internal/device-state.js +4 -0
  103. package/vendor/cli/dist/runtime-components.json +4 -4
  104. package/vendor/cli/dist/templates/AGENTS.md.tmpl +3 -1
  105. package/vendor/cli/dist/templates/TESTING.md.tmpl +8 -8
  106. package/vendor/cli/package.json +1 -1
  107. package/vendor/connector-sdk/dist/browser-requirement.js +1 -1
  108. package/vendor/connector-sdk/dist/connector-types.d.ts +5 -1
  109. package/vendor/connector-sdk/package.json +1 -1
  110. package/vendor/connector-worker/dist/agent-turn/gateway-tools.d.ts +9 -0
  111. package/vendor/connector-worker/dist/agent-turn/gateway-tools.js +23 -2
  112. package/vendor/connector-worker/dist/agent-turn/guest-entry.js +14 -6
  113. package/vendor/connector-worker/dist/agent-turn/guest.bundle.js +62 -25
  114. package/vendor/connector-worker/dist/agent-turn/media-tools.d.ts +1 -0
  115. package/vendor/connector-worker/dist/agent-turn/media-tools.js +5 -2
  116. package/vendor/connector-worker/dist/bin.js +2 -0
  117. package/vendor/connector-worker/dist/daemon/agent-turn.js +52 -17
  118. package/vendor/connector-worker/dist/daemon/automation.js +2 -12
  119. package/vendor/connector-worker/dist/daemon/client.d.ts +8 -2
  120. package/vendor/connector-worker/dist/daemon/client.js +8 -1
  121. package/vendor/connector-worker/dist/daemon/interactive-session.js +29 -6
  122. package/vendor/connector-worker/dist/daemon/poll-loop.js +23 -1
  123. package/vendor/connector-worker/dist/daemon/terminal-delivery.d.ts +5 -10
  124. package/vendor/connector-worker/dist/daemon/terminal-delivery.js +55 -23
  125. package/vendor/connector-worker/dist/daemon/terminal-failure.js +2 -2
  126. package/vendor/connector-worker/dist/executor/isolate.js +3 -0
  127. package/vendor/connector-worker/package.json +1 -1
  128. package/vendor/core/dist/agent-tooling.d.ts +8 -0
  129. package/vendor/core/dist/agent-tooling.js +9 -1
  130. package/vendor/core/dist/capabilities.d.ts +1 -1
  131. package/vendor/core/dist/capabilities.js +5 -0
  132. package/vendor/core/dist/contracts/entity-reference.d.ts +3 -0
  133. package/vendor/core/dist/contracts/entity-reference.js +31 -0
  134. package/vendor/core/dist/contracts/tools/manage-automations.d.ts +3 -0
  135. package/vendor/core/dist/contracts/tools/manage-automations.js +3 -0
  136. package/vendor/core/dist/contracts/tools/manage-connections.js +1 -1
  137. package/vendor/core/dist/contracts/tools/manage-entity-schema.js +1 -1
  138. package/vendor/core/dist/contracts/tools/manage-entity.d.ts +113 -34
  139. package/vendor/core/dist/contracts/tools/manage-entity.js +41 -14
  140. package/vendor/core/dist/contracts/tools/manage-operations.d.ts +13 -4
  141. package/vendor/core/dist/contracts/tools/manage-operations.js +19 -7
  142. package/vendor/core/dist/contracts/tools/read-knowledge.d.ts +6 -1
  143. package/vendor/core/dist/contracts/tools/read-knowledge.js +20 -1
  144. package/vendor/core/dist/contracts/tools/view-attach.d.ts +1 -1
  145. package/vendor/core/dist/contracts/tools/view-runtime.d.ts +2 -0
  146. package/vendor/core/dist/contracts/tools/view-runtime.js +3 -1
  147. package/vendor/core/dist/contracts/worker/device-automation.d.ts +4 -9
  148. package/vendor/core/dist/contracts/worker/device-automation.js +10 -15
  149. package/vendor/core/dist/contracts/worker/protocol.d.ts +20 -0
  150. package/vendor/core/dist/contracts/worker/protocol.js +20 -0
  151. package/vendor/core/dist/reserved.d.ts +6 -3
  152. package/vendor/core/dist/reserved.js +6 -3
  153. package/vendor/core/dist/worker/auth.d.ts +3 -2
  154. package/vendor/core/package.json +6 -1
  155. package/vendor/postgres/cf/src/query.js +3 -1
  156. package/vendor/postgres/cjs/src/query.js +3 -1
  157. package/vendor/postgres/src/query.js +3 -1
  158. /package/vendor/postgres/{.bun-tag-2f292c6554a8475e → .bun-tag-22d644c2873790db} +0 -0
@@ -34,6 +34,13 @@ function inboxOf(feedKey: string, config: unknown): unknown {
34
34
  : undefined;
35
35
  }
36
36
 
37
+ function savedAccount(ctx: { sessionState?: Record<string, unknown> | null }): string {
38
+ const account = ctx.sessionState?.account_id;
39
+ if (typeof account !== "string" || !/^urn:li:fs_miniProfile:.+$/.test(account))
40
+ throw new Error("LinkedIn source requires the connection's saved account; reconnect this source");
41
+ return account;
42
+ }
43
+
37
44
  async function readyTab(browser: ChromeActionDispatcher): Promise<number> {
38
45
  // Opening the inbox itself marks conversations seen. A scrape-owned neutral
39
46
  // tab supplies authentication without changing notification/message state.
@@ -81,12 +88,14 @@ export async function sendLinkedInMessage(
81
88
  ctx: ActionContext
82
89
  ): Promise<ActionResult> {
83
90
  try {
91
+ const expectedAccount = savedAccount(ctx);
84
92
  const browser = requireBrowser(ctx);
85
93
  const output = await invoke<Record<string, unknown>>(
86
94
  browser,
87
95
  await readyTab(browser),
88
96
  "send",
89
97
  {
98
+ expected_account: expectedAccount,
90
99
  conversation_id: ctx.input.conversation_id,
91
100
  text: ctx.input.text,
92
101
  idempotency_key: ctx.input.idempotency_key,
@@ -116,8 +125,10 @@ export async function readLinkedInInbox<F>(
116
125
  } else {
117
126
  assertInboxSourceRead(ctx, "LinkedIn");
118
127
  }
128
+ const expectedAccount = savedAccount(ctx);
119
129
  const browser = requireBrowser(ctx);
120
130
  return invoke(browser, await readyTab(browser), "read", {
131
+ expected_account: expectedAccount,
121
132
  feed: ctx.feedKey,
122
133
  inbox: inboxOf(ctx.feedKey, ctx.config),
123
134
  query: ctx.query,
@@ -130,6 +141,7 @@ export async function observeLinkedInInbox<
130
141
  C extends LinkedInInboxCheckpoint,
131
142
  F,
132
143
  >(ctx: FeedObserveContext<C, F>): Promise<void> {
144
+ const expectedAccount = savedAccount(ctx);
133
145
  const browser = requireBrowser(ctx);
134
146
  const tabId = await readyTab(browser);
135
147
  const binding = await browser.dispatch<{
@@ -150,6 +162,7 @@ export async function observeLinkedInInbox<
150
162
  feed: ctx.feedKey,
151
163
  inbox: inboxOf(ctx.feedKey, ctx.config),
152
164
  checkpoint: ctx.checkpoint,
165
+ expected_account: expectedAccount,
153
166
  bridge_id: binding.bridge_id,
154
167
  token: binding.token,
155
168
  });
@@ -2933,7 +2933,7 @@ export default class LinkedInConnector extends ConnectorRuntime<
2933
2933
  name: "LinkedIn",
2934
2934
  description:
2935
2935
  "Read LinkedIn feeds, notifications, and recent inbox messages through paired Chrome. Subscribe to source changes, answer direct messages, and prepare message, post, or comment drafts for human submission. Also supports local LinkedIn Data Export CSV files.",
2936
- version: "3.20.1",
2936
+ version: "3.20.2",
2937
2937
  faviconDomain: "linkedin.com",
2938
2938
  // Live feeds bind a signed-in Chrome account. Local takeout imports need no browser.
2939
2939
  browser: {
@@ -354,7 +354,7 @@ export default class PostgresConnector extends ConnectorRuntime {
354
354
  description:
355
355
  'Bring your own PostgreSQL database as memory, read a configured feed directly, or run governed connection-level SQL.',
356
356
  version: '1.1.0',
357
- queryCapabilities: { exactMatch: true, selection: true },
357
+ queryCapabilities: { exactMatch: true, verbatimExactMatch: true, selection: true },
358
358
  faviconDomain: 'postgresql.org',
359
359
  authSchema: {
360
360
  methods: [
@@ -530,7 +530,7 @@ export default class PostgresConnector extends ConnectorRuntime {
530
530
  const bind = (value: string) => { params.push(value); return `$${params.length}::text`; };
531
531
  let where = '';
532
532
  if (ctx.exactMatch) {
533
- const { columns, value } = ctx.exactMatch;
533
+ const { columns, value, verbatim } = ctx.exactMatch;
534
534
  if (!columns.length) throw new Error('exactMatch.columns must not be empty');
535
535
  for (const column of columns) assertIdentifier(column, 'exactMatch.column');
536
536
  const projection = await tx.unsafe(`SELECT * FROM (\n${baseSql}\n) q LIMIT 0`);
@@ -541,7 +541,9 @@ export default class PostgresConnector extends ConnectorRuntime {
541
541
  if (!candidates.some(isScalar)) {
542
542
  throw Object.assign(new Error('Exact-match identity must be a scalar; project a text key in the source query'), { status: 400 });
543
543
  }
544
- const textMatch = (ref: string) => `btrim(${ref}, ${bind('\t\n\v\f\r \u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000\ufeff')}) = ${bind(value)}`;
544
+ const textMatch = (ref: string) => verbatim
545
+ ? `${ref} = ${bind(value)}`
546
+ : `btrim(${ref}, ${bind('\t\n\v\f\r \u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000\ufeff')}) = ${bind(value)}`;
545
547
  const numberMatch = (ref: string, cast: string) => Number.isFinite(Number(value)) && String(Number(value)) === value
546
548
  ? `${ref} = ${bind(value)}::${cast}` : 'FALSE';
547
549
  const cases = candidates.map((column) => {
@@ -1,9 +1,9 @@
1
1
  /**
2
2
  * Reddit Connector (V1 runtime)
3
3
  *
4
- * Fetches posts and comments from Reddit subreddits or search queries, and the
5
- * connected user's home feed. Supports both authenticated (OAuth) and
6
- * unauthenticated (public JSON API) modes.
4
+ * Fetches posts and comments from Reddit subreddits or search queries, the
5
+ * connected user's home feed, and inbox notification references. Supports
6
+ * both authenticated (OAuth) and unauthenticated (public JSON API) modes.
7
7
  */
8
8
 
9
9
  import {
@@ -12,8 +12,11 @@ import {
12
12
  calculateEngagementScore,
13
13
  createHttpClient,
14
14
  type EventEnvelope,
15
+ type FeedReadContext,
16
+ type FeedReadResult,
15
17
  HttpStatusError,
16
18
  paginateByCursor,
19
+ sleep,
17
20
  type SyncContext,
18
21
  type SyncResult,
19
22
  } from '@lobu/connector-sdk';
@@ -71,6 +74,35 @@ interface RedditCheckpoint {
71
74
  last_timestamp?: string;
72
75
  pagination_token?: string;
73
76
  pagination_cutoff?: string;
77
+ inbox_head?: string | null;
78
+ }
79
+
80
+ interface RedditInboxItem {
81
+ kind: string;
82
+ data: {
83
+ name: string;
84
+ author?: string | null;
85
+ subject?: string;
86
+ body?: string;
87
+ context?: string;
88
+ created_utc: number;
89
+ new?: boolean;
90
+ };
91
+ }
92
+
93
+ interface RedditInboxListing {
94
+ data: { children: RedditInboxItem[]; after: string | null };
95
+ }
96
+
97
+ function inboxUrl(item: RedditInboxItem): string {
98
+ const fallback = `https://www.reddit.com/message/messages/${encodeURIComponent(item.data.name.slice(3))}`;
99
+ if (!item.data.context) return fallback;
100
+ try {
101
+ const url = new URL(item.data.context, 'https://www.reddit.com');
102
+ return url.origin === 'https://www.reddit.com' ? url.href : fallback;
103
+ } catch {
104
+ return fallback;
105
+ }
74
106
  }
75
107
 
76
108
  // Use the gateway's URI format check: WHATWG URL parsing also accepts non-URI characters.
@@ -92,8 +124,8 @@ export default class RedditConnector extends ConnectorRuntime {
92
124
  key: 'reddit',
93
125
  name: 'Reddit',
94
126
  description:
95
- "Fetches posts and comments from Reddit subreddits or search queries, and the connected user's home feed.",
96
- version: '1.2.1',
127
+ "Fetches posts and comments from Reddit subreddits or search queries, the connected user's home feed, and inbox notification references.",
128
+ version: '1.3.0',
97
129
  faviconDomain: 'reddit.com',
98
130
  authSchema: {
99
131
  methods: [
@@ -101,6 +133,8 @@ export default class RedditConnector extends ConnectorRuntime {
101
133
  type: 'oauth',
102
134
  provider: 'reddit',
103
135
  requiredScopes: ['identity', 'read', 'history'],
136
+ // Explicit reconnect requests for new scopes use method optionalScopes.
137
+ optionalScopes: ['privatemessages'],
104
138
  loginScopes: ['identity'],
105
139
  setupInstructions:
106
140
  'Create a Reddit app at https://www.reddit.com/prefs/apps — choose "web app" as the type. Set the redirect URI to {{redirect_uri}}, then copy the client ID and secret below.',
@@ -111,6 +145,29 @@ export default class RedditConnector extends ConnectorRuntime {
111
145
  ],
112
146
  },
113
147
  feeds: {
148
+ inbox: {
149
+ key: 'inbox',
150
+ name: 'Inbox notifications',
151
+ description:
152
+ 'Capture metadata-only references to the OAuth inbox (comment/post replies, mentions and legacy private messages exposed by Reddit). Read original bodies explicitly from the source. Does not mark messages read. Chat, reactions and the modern notification bell are not covered by this API.',
153
+ requiredScopes: ['privatemessages'],
154
+ sync: (ctx) => this.syncInbox(ctx),
155
+ read: (ctx) => this.readInbox(ctx),
156
+ eventKinds: {
157
+ inbox_notification: {
158
+ description: 'A source reference to an item in the Reddit OAuth inbox',
159
+ metadataSchema: {
160
+ type: 'object',
161
+ properties: {
162
+ source_id: { type: 'string' },
163
+ source_kind: { type: 'string' },
164
+ category: { type: 'string' },
165
+ },
166
+ required: ['source_id', 'source_kind', 'category'],
167
+ },
168
+ },
169
+ },
170
+ },
114
171
  posts: {
115
172
  key: 'posts',
116
173
  name: 'Posts',
@@ -301,6 +358,115 @@ export default class RedditConnector extends ConnectorRuntime {
301
358
  private readonly RATE_LIMIT_MS = 1000;
302
359
  private readonly USER_AGENT = 'Lobu-Connector/1.0.0';
303
360
 
361
+ private async inboxPage(
362
+ ctx: Pick<FeedReadContext, 'credentials'>,
363
+ after?: string,
364
+ limit = 100,
365
+ ): Promise<RedditInboxListing['data']> {
366
+ const token = ctx.credentials?.accessToken;
367
+ if (!token) throw new Error('Reddit inbox requires user OAuth with the privatemessages scope.');
368
+ const params = new URLSearchParams({ limit: String(limit), mark: 'false', raw_json: '1' });
369
+ if (after) params.set('after', after);
370
+ const http = createHttpClient({ token, headers: { 'User-Agent': this.USER_AGENT }, errorPrefix: 'Reddit inbox' });
371
+ const response = await http.get<RedditInboxListing>(`https://oauth.reddit.com/message/inbox?${params}`);
372
+ // An access/error page must not be mistaken for an exhausted inbox.
373
+ if (!response.data || !Array.isArray(response.data.children)
374
+ || !(response.data.after === null || typeof response.data.after === 'string')) {
375
+ throw new Error('Reddit returned an invalid inbox listing.');
376
+ }
377
+ for (const item of response.data.children) {
378
+ if (!item.data || !/^t[14]_[A-Za-z0-9]+$/.test(item.data.name)
379
+ || !item.data.name.startsWith(`${item.kind}_`)
380
+ || !Number.isFinite(item.data.created_utc)) {
381
+ throw new Error('Reddit returned an invalid inbox item identity or date.');
382
+ }
383
+ }
384
+ return response.data;
385
+ }
386
+
387
+ private async readInbox(ctx: FeedReadContext): Promise<FeedReadResult> {
388
+ if (ctx.window || ctx.query || ctx.match || (ctx.offset ?? 0) > 0 || ctx.sort) {
389
+ throw new Error('Reddit inbox reads support cursor pagination only; query, window, match, offset and sort are unsupported.');
390
+ }
391
+ const page = await this.inboxPage(ctx, ctx.cursor, Math.max(1, Math.min(100, Math.trunc(ctx.limit ?? 25))));
392
+ if (page.after && page.after === ctx.cursor) throw new Error('Reddit inbox cursor did not advance.');
393
+ return {
394
+ rows: page.children.map(item => ({
395
+ id: item.data.name, kind: item.kind, subject: item.data.subject ?? null,
396
+ body: item.data.body ?? null, author: item.data.author ?? null,
397
+ occurred_at: new Date(item.data.created_utc * 1000).toISOString(),
398
+ unread: item.data.new ?? null, url: inboxUrl(item),
399
+ })),
400
+ nextCursor: page.after ?? undefined,
401
+ };
402
+ }
403
+
404
+ private async syncInbox(ctx: SyncContext): Promise<SyncResult> {
405
+ const saved = (ctx.checkpoint?.pagination_token as string | undefined) ?? undefined;
406
+ const previousHead = ctx.checkpoint?.inbox_head;
407
+ let head: string | undefined;
408
+ let catchingUp = !!saved;
409
+ const seenCursors = new Set<string>();
410
+ const seenItems = new Set<string>();
411
+ const events: EventEnvelope[] = [];
412
+ let after: string | undefined;
413
+ let exhausted = false;
414
+ // Old checkpoints have no evidence that the refreshed head meets the tail.
415
+ // Rewalk from the head instead of skipping an unobserved arrival interval.
416
+ let cursorReset = !!saved && !previousHead;
417
+ for (let page = 0; page < this.MAX_PAGES; page++) {
418
+ if (page) await sleep(this.RATE_LIMIT_MS);
419
+ if (after) seenCursors.add(after);
420
+ let listing: RedditInboxListing['data'];
421
+ try {
422
+ listing = await this.inboxPage(ctx, after);
423
+ } catch (error) {
424
+ // A deleted saved anchor must not wedge capture indefinitely. Rewalk
425
+ // the retained inbox once; auth, permission and quota failures propagate.
426
+ if (!cursorReset && after && after === saved && error instanceof HttpStatusError
427
+ && [400, 404].includes(error.status)) {
428
+ cursorReset = true;
429
+ after = undefined;
430
+ seenCursors.clear();
431
+ continue;
432
+ }
433
+ throw error;
434
+ }
435
+ head ??= listing.children[0]?.data.name;
436
+ for (const item of listing.children) {
437
+ if (seenItems.has(item.data.name)) continue;
438
+ seenItems.add(item.data.name);
439
+ const category = item.kind === 't4' ? 'private_message' : 'comment_notification';
440
+ events.push({
441
+ origin_id: `reddit_inbox_${item.data.name}`, origin_type: 'inbox_notification',
442
+ payload_text: '',
443
+ title: item.kind === 't4' ? 'Reddit private message' : 'Reddit comment notification',
444
+ source_url: inboxUrl(item), occurred_at: new Date(item.data.created_utc * 1000),
445
+ metadata: { source_id: item.data.name, source_kind: item.kind, category },
446
+ });
447
+ }
448
+ after = listing.after ?? undefined;
449
+ // Re-read every arrival page through the prior head before resuming the
450
+ // unfinished history sweep. A deleted/missing boundary falls back to a
451
+ // bounded full sweep; occurrence time cannot safely exclude older items.
452
+ if (catchingUp && listing.children.some(item => item.data.name === previousHead)) {
453
+ catchingUp = false;
454
+ if (after && saved) after = saved;
455
+ }
456
+ if (!after) {
457
+ exhausted = true;
458
+ break;
459
+ }
460
+ if (seenCursors.has(after)) throw new Error('Reddit inbox cursor did not advance.');
461
+ }
462
+ await ctx.commit(events, { pagination_token: after ?? null, inbox_head: head ?? null });
463
+ // A reset on the final request leaves no cursor but still needs a new sweep.
464
+ return { status: exhausted ? 'complete' : 'more', metadata: {
465
+ items_found: events.length,
466
+ ...(cursorReset ? { cursor_reset: true } : {}),
467
+ } };
468
+ }
469
+
304
470
  // -------------------------------------------------------------------------
305
471
  // sync
306
472
  // -------------------------------------------------------------------------