hybrid 1.3.0 → 1.3.2

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.
@@ -1,5 +1,5 @@
1
- import { z } from 'zod';
2
1
  import { UIMessage } from 'ai';
2
+ import { z } from 'zod';
3
3
  import { XmtpConversation, XmtpMessage, XmtpSender, XmtpSubjects, XmtpServiceClient } from '@hybrd/xmtp';
4
4
  import * as viem_chains from 'viem/chains';
5
5
  import * as viem from 'viem';
@@ -65,12 +65,12 @@ interface Tool<TInput extends z.ZodTypeAny = z.ZodTypeAny, TOutput extends z.Zod
65
65
  * Factory function to create tools with custom runtime extensions.
66
66
  * Provides proper type inference for input/output schemas and runtime extensions.
67
67
  */
68
- declare function toolFactory<TRuntimeExtension = DefaultRuntimeExtension>(): <TInput extends z.ZodTypeAny, TOutput extends z.ZodTypeAny = z.ZodTypeAny>(config: ToolConfig<TInput, TOutput, TRuntimeExtension>) => Tool<TInput, TOutput, TRuntimeExtension>;
68
+ declare function toolFactory<TRuntimeExtension = DefaultRuntimeExtension>(): <TInput extends z.ZodTypeAny = z.ZodTypeAny, TOutput extends z.ZodTypeAny = z.ZodTypeAny>(config: ToolConfig<TInput, TOutput, TRuntimeExtension>) => Tool<TInput, TOutput, TRuntimeExtension>;
69
69
  /**
70
70
  * Default tool factory with no runtime extensions.
71
71
  * Type-safe at creation time with proper schema inference.
72
72
  */
73
- declare const createTool: <TInput extends z.ZodTypeAny, TOutput extends z.ZodTypeAny = z.ZodTypeAny>(config: ToolConfig<TInput, TOutput, DefaultRuntimeExtension>) => Tool<TInput, TOutput, DefaultRuntimeExtension>;
73
+ declare const createTool: <TInput extends z.ZodTypeAny = z.ZodTypeAny, TOutput extends z.ZodTypeAny = z.ZodTypeAny>(config: ToolConfig<TInput, TOutput, DefaultRuntimeExtension>) => Tool<TInput, TOutput, DefaultRuntimeExtension>;
74
74
 
75
75
  declare const SUPPORTED_CHAINS: {
76
76
  readonly mainnet: {
@@ -1564,14 +1564,14 @@ declare const sendMessageTool: Tool<z.ZodEffects<z.ZodObject<{
1564
1564
  }, "strip", z.ZodTypeAny, {
1565
1565
  content: string;
1566
1566
  success: boolean;
1567
- conversationId?: string | undefined;
1568
1567
  error?: string | undefined;
1568
+ conversationId?: string | undefined;
1569
1569
  messageId?: string | undefined;
1570
1570
  }, {
1571
1571
  content: string;
1572
1572
  success: boolean;
1573
- conversationId?: string | undefined;
1574
1573
  error?: string | undefined;
1574
+ conversationId?: string | undefined;
1575
1575
  messageId?: string | undefined;
1576
1576
  }>, {
1577
1577
  [x: string]: never;
@@ -1662,9 +1662,9 @@ declare const getMessageTool: Tool<z.ZodObject<{
1662
1662
  versionMinor?: number | undefined;
1663
1663
  }>>;
1664
1664
  }, "strip", z.ZodTypeAny, {
1665
+ id: string;
1665
1666
  conversationId: string;
1666
1667
  content: string | Record<string, unknown>;
1667
- id: string;
1668
1668
  senderInboxId: string;
1669
1669
  sentAt: string;
1670
1670
  contentType?: {
@@ -1674,9 +1674,9 @@ declare const getMessageTool: Tool<z.ZodObject<{
1674
1674
  versionMinor?: number | undefined;
1675
1675
  } | undefined;
1676
1676
  }, {
1677
+ id: string;
1677
1678
  conversationId: string;
1678
1679
  content: string | Record<string, unknown>;
1679
- id: string;
1680
1680
  senderInboxId: string;
1681
1681
  sentAt: string;
1682
1682
  contentType?: {
@@ -1690,9 +1690,9 @@ declare const getMessageTool: Tool<z.ZodObject<{
1690
1690
  }, "strip", z.ZodTypeAny, {
1691
1691
  success: boolean;
1692
1692
  message?: {
1693
+ id: string;
1693
1694
  conversationId: string;
1694
1695
  content: string | Record<string, unknown>;
1695
- id: string;
1696
1696
  senderInboxId: string;
1697
1697
  sentAt: string;
1698
1698
  contentType?: {
@@ -1706,9 +1706,9 @@ declare const getMessageTool: Tool<z.ZodObject<{
1706
1706
  }, {
1707
1707
  success: boolean;
1708
1708
  message?: {
1709
+ id: string;
1709
1710
  conversationId: string;
1710
1711
  content: string | Record<string, unknown>;
1711
- id: string;
1712
1712
  senderInboxId: string;
1713
1713
  sentAt: string;
1714
1714
  contentType?: {
@@ -1765,14 +1765,14 @@ declare const xmtpTools: {
1765
1765
  }, "strip", z.ZodTypeAny, {
1766
1766
  content: string;
1767
1767
  success: boolean;
1768
- conversationId?: string | undefined;
1769
1768
  error?: string | undefined;
1769
+ conversationId?: string | undefined;
1770
1770
  messageId?: string | undefined;
1771
1771
  }, {
1772
1772
  content: string;
1773
1773
  success: boolean;
1774
- conversationId?: string | undefined;
1775
1774
  error?: string | undefined;
1775
+ conversationId?: string | undefined;
1776
1776
  messageId?: string | undefined;
1777
1777
  }>, {
1778
1778
  [x: string]: never;
@@ -1862,9 +1862,9 @@ declare const xmtpTools: {
1862
1862
  versionMinor?: number | undefined;
1863
1863
  }>>;
1864
1864
  }, "strip", z.ZodTypeAny, {
1865
+ id: string;
1865
1866
  conversationId: string;
1866
1867
  content: string | Record<string, unknown>;
1867
- id: string;
1868
1868
  senderInboxId: string;
1869
1869
  sentAt: string;
1870
1870
  contentType?: {
@@ -1874,9 +1874,9 @@ declare const xmtpTools: {
1874
1874
  versionMinor?: number | undefined;
1875
1875
  } | undefined;
1876
1876
  }, {
1877
+ id: string;
1877
1878
  conversationId: string;
1878
1879
  content: string | Record<string, unknown>;
1879
- id: string;
1880
1880
  senderInboxId: string;
1881
1881
  sentAt: string;
1882
1882
  contentType?: {
@@ -1890,9 +1890,9 @@ declare const xmtpTools: {
1890
1890
  }, "strip", z.ZodTypeAny, {
1891
1891
  success: boolean;
1892
1892
  message?: {
1893
+ id: string;
1893
1894
  conversationId: string;
1894
1895
  content: string | Record<string, unknown>;
1895
- id: string;
1896
1896
  senderInboxId: string;
1897
1897
  sentAt: string;
1898
1898
  contentType?: {
@@ -1906,9 +1906,9 @@ declare const xmtpTools: {
1906
1906
  }, {
1907
1907
  success: boolean;
1908
1908
  message?: {
1909
+ id: string;
1909
1910
  conversationId: string;
1910
1911
  content: string | Record<string, unknown>;
1911
- id: string;
1912
1912
  senderInboxId: string;
1913
1913
  sentAt: string;
1914
1914
  contentType?: {
@@ -1,5 +1,5 @@
1
- import { z } from 'zod';
2
1
  import { UIMessage } from 'ai';
2
+ import { z } from 'zod';
3
3
  import { XmtpConversation, XmtpMessage, XmtpSender, XmtpSubjects, XmtpServiceClient } from '@hybrd/xmtp';
4
4
  import * as viem_chains from 'viem/chains';
5
5
  import * as viem from 'viem';
@@ -65,12 +65,12 @@ interface Tool<TInput extends z.ZodTypeAny = z.ZodTypeAny, TOutput extends z.Zod
65
65
  * Factory function to create tools with custom runtime extensions.
66
66
  * Provides proper type inference for input/output schemas and runtime extensions.
67
67
  */
68
- declare function toolFactory<TRuntimeExtension = DefaultRuntimeExtension>(): <TInput extends z.ZodTypeAny, TOutput extends z.ZodTypeAny = z.ZodTypeAny>(config: ToolConfig<TInput, TOutput, TRuntimeExtension>) => Tool<TInput, TOutput, TRuntimeExtension>;
68
+ declare function toolFactory<TRuntimeExtension = DefaultRuntimeExtension>(): <TInput extends z.ZodTypeAny = z.ZodTypeAny, TOutput extends z.ZodTypeAny = z.ZodTypeAny>(config: ToolConfig<TInput, TOutput, TRuntimeExtension>) => Tool<TInput, TOutput, TRuntimeExtension>;
69
69
  /**
70
70
  * Default tool factory with no runtime extensions.
71
71
  * Type-safe at creation time with proper schema inference.
72
72
  */
73
- declare const createTool: <TInput extends z.ZodTypeAny, TOutput extends z.ZodTypeAny = z.ZodTypeAny>(config: ToolConfig<TInput, TOutput, DefaultRuntimeExtension>) => Tool<TInput, TOutput, DefaultRuntimeExtension>;
73
+ declare const createTool: <TInput extends z.ZodTypeAny = z.ZodTypeAny, TOutput extends z.ZodTypeAny = z.ZodTypeAny>(config: ToolConfig<TInput, TOutput, DefaultRuntimeExtension>) => Tool<TInput, TOutput, DefaultRuntimeExtension>;
74
74
 
75
75
  declare const SUPPORTED_CHAINS: {
76
76
  readonly mainnet: {
@@ -1564,14 +1564,14 @@ declare const sendMessageTool: Tool<z.ZodEffects<z.ZodObject<{
1564
1564
  }, "strip", z.ZodTypeAny, {
1565
1565
  content: string;
1566
1566
  success: boolean;
1567
- conversationId?: string | undefined;
1568
1567
  error?: string | undefined;
1568
+ conversationId?: string | undefined;
1569
1569
  messageId?: string | undefined;
1570
1570
  }, {
1571
1571
  content: string;
1572
1572
  success: boolean;
1573
- conversationId?: string | undefined;
1574
1573
  error?: string | undefined;
1574
+ conversationId?: string | undefined;
1575
1575
  messageId?: string | undefined;
1576
1576
  }>, {
1577
1577
  [x: string]: never;
@@ -1662,9 +1662,9 @@ declare const getMessageTool: Tool<z.ZodObject<{
1662
1662
  versionMinor?: number | undefined;
1663
1663
  }>>;
1664
1664
  }, "strip", z.ZodTypeAny, {
1665
+ id: string;
1665
1666
  conversationId: string;
1666
1667
  content: string | Record<string, unknown>;
1667
- id: string;
1668
1668
  senderInboxId: string;
1669
1669
  sentAt: string;
1670
1670
  contentType?: {
@@ -1674,9 +1674,9 @@ declare const getMessageTool: Tool<z.ZodObject<{
1674
1674
  versionMinor?: number | undefined;
1675
1675
  } | undefined;
1676
1676
  }, {
1677
+ id: string;
1677
1678
  conversationId: string;
1678
1679
  content: string | Record<string, unknown>;
1679
- id: string;
1680
1680
  senderInboxId: string;
1681
1681
  sentAt: string;
1682
1682
  contentType?: {
@@ -1690,9 +1690,9 @@ declare const getMessageTool: Tool<z.ZodObject<{
1690
1690
  }, "strip", z.ZodTypeAny, {
1691
1691
  success: boolean;
1692
1692
  message?: {
1693
+ id: string;
1693
1694
  conversationId: string;
1694
1695
  content: string | Record<string, unknown>;
1695
- id: string;
1696
1696
  senderInboxId: string;
1697
1697
  sentAt: string;
1698
1698
  contentType?: {
@@ -1706,9 +1706,9 @@ declare const getMessageTool: Tool<z.ZodObject<{
1706
1706
  }, {
1707
1707
  success: boolean;
1708
1708
  message?: {
1709
+ id: string;
1709
1710
  conversationId: string;
1710
1711
  content: string | Record<string, unknown>;
1711
- id: string;
1712
1712
  senderInboxId: string;
1713
1713
  sentAt: string;
1714
1714
  contentType?: {
@@ -1765,14 +1765,14 @@ declare const xmtpTools: {
1765
1765
  }, "strip", z.ZodTypeAny, {
1766
1766
  content: string;
1767
1767
  success: boolean;
1768
- conversationId?: string | undefined;
1769
1768
  error?: string | undefined;
1769
+ conversationId?: string | undefined;
1770
1770
  messageId?: string | undefined;
1771
1771
  }, {
1772
1772
  content: string;
1773
1773
  success: boolean;
1774
- conversationId?: string | undefined;
1775
1774
  error?: string | undefined;
1775
+ conversationId?: string | undefined;
1776
1776
  messageId?: string | undefined;
1777
1777
  }>, {
1778
1778
  [x: string]: never;
@@ -1862,9 +1862,9 @@ declare const xmtpTools: {
1862
1862
  versionMinor?: number | undefined;
1863
1863
  }>>;
1864
1864
  }, "strip", z.ZodTypeAny, {
1865
+ id: string;
1865
1866
  conversationId: string;
1866
1867
  content: string | Record<string, unknown>;
1867
- id: string;
1868
1868
  senderInboxId: string;
1869
1869
  sentAt: string;
1870
1870
  contentType?: {
@@ -1874,9 +1874,9 @@ declare const xmtpTools: {
1874
1874
  versionMinor?: number | undefined;
1875
1875
  } | undefined;
1876
1876
  }, {
1877
+ id: string;
1877
1878
  conversationId: string;
1878
1879
  content: string | Record<string, unknown>;
1879
- id: string;
1880
1880
  senderInboxId: string;
1881
1881
  sentAt: string;
1882
1882
  contentType?: {
@@ -1890,9 +1890,9 @@ declare const xmtpTools: {
1890
1890
  }, "strip", z.ZodTypeAny, {
1891
1891
  success: boolean;
1892
1892
  message?: {
1893
+ id: string;
1893
1894
  conversationId: string;
1894
1895
  content: string | Record<string, unknown>;
1895
- id: string;
1896
1896
  senderInboxId: string;
1897
1897
  sentAt: string;
1898
1898
  contentType?: {
@@ -1906,9 +1906,9 @@ declare const xmtpTools: {
1906
1906
  }, {
1907
1907
  success: boolean;
1908
1908
  message?: {
1909
+ id: string;
1909
1910
  conversationId: string;
1910
1911
  content: string | Record<string, unknown>;
1911
- id: string;
1912
1912
  senderInboxId: string;
1913
1913
  sentAt: string;
1914
1914
  contentType?: {
package/dist/index.cjs CHANGED
@@ -1,9 +1,7 @@
1
1
  "use strict";
2
- var __create = Object.create;
3
2
  var __defProp = Object.defineProperty;
4
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
5
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
6
  var __export = (target, all) => {
9
7
  for (var name in all)
@@ -17,14 +15,6 @@ var __copyProps = (to, from, except, desc) => {
17
15
  }
18
16
  return to;
19
17
  };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
19
 
30
20
  // src/index.ts
@@ -35,7 +25,6 @@ __export(src_exports, {
35
25
  blockchainTools: () => blockchainTools,
36
26
  createTool: () => createTool,
37
27
  estimateGasTool: () => estimateGasTool,
38
- generateXMTPToolsToken: () => generateXMTPToolsToken,
39
28
  getBalanceTool: () => getBalanceTool,
40
29
  getBgState: () => getBgState,
41
30
  getBlockTool: () => getBlockTool,
@@ -77,58 +66,224 @@ var import_xmtp = require("@hybrd/xmtp");
77
66
  var import_node_crypto = require("crypto");
78
67
  var import_viem = require("viem");
79
68
  var import_chains = require("viem/chains");
80
-
81
- // src/lib/jwt.ts
82
- var import_jsonwebtoken = __toESM(require("jsonwebtoken"), 1);
83
- var JWT_SECRET = (() => {
84
- const secret = process.env.XMTP_JWT_SECRET;
85
- const nodeEnv = process.env.NODE_ENV || "development";
86
- if (nodeEnv === "production" && !secret) {
87
- throw new Error(
88
- "XMTP_JWT_SECRET environment variable is required in production. Generate a secure random secret for JWT token signing."
89
- );
90
- }
91
- if (!secret) {
92
- console.warn(
93
- "\u26A0\uFE0F [SECURITY] Using fallback JWT secret for development. Set XMTP_JWT_SECRET environment variable for production."
94
- );
95
- return "fallback-secret-for-dev-only";
96
- }
97
- return secret;
98
- })();
99
- var API_KEY = (() => {
100
- const apiKey = process.env.XMTP_API_KEY;
101
- const nodeEnv = process.env.NODE_ENV || "development";
102
- if (nodeEnv === "production" && !apiKey) {
69
+ var BG_STARTED = Symbol("BG_STARTED");
70
+ var BG_STATE = Symbol("BG_STATE");
71
+ var BG_STOP = Symbol("BG_STOP");
72
+ function sleep(ms, signal) {
73
+ return new Promise((resolve, reject) => {
74
+ if (signal?.aborted) {
75
+ reject(new Error("AbortError"));
76
+ return;
77
+ }
78
+ const timeout = setTimeout(resolve, ms);
79
+ if (signal) {
80
+ signal.addEventListener(
81
+ "abort",
82
+ () => {
83
+ clearTimeout(timeout);
84
+ reject(new Error("AbortError"));
85
+ },
86
+ { once: true }
87
+ );
88
+ }
89
+ });
90
+ }
91
+ function createBackgroundMessageProcessor(opts) {
92
+ if (!opts?.agent || !opts?.xmtpClient) {
103
93
  throw new Error(
104
- "XMTP_API_KEY environment variable is required in production. Generate a secure random API key for authentication."
94
+ "createBackgroundMessageProcessor: agent and xmtpClient are required"
105
95
  );
106
96
  }
107
- if (!apiKey) {
108
- console.warn(
109
- "\u26A0\uFE0F [SECURITY] Using fallback API key for development. Set XMTP_API_KEY environment variable for production."
97
+ const intervalMs = Math.max(250, opts.intervalMs ?? 5e3);
98
+ const baseBackoffMs = Math.max(100, opts.backoffMs ?? 1e3);
99
+ const maxBackoffMs = Math.max(baseBackoffMs, opts.maxBackoffMs ?? 3e4);
100
+ if (!globalThis[BG_STARTED]) {
101
+ ;
102
+ globalThis[BG_STARTED] = true;
103
+ const state = {
104
+ running: true,
105
+ lastStartAt: Date.now(),
106
+ consecutiveErrors: 0,
107
+ messagesProcessed: 0,
108
+ listenerRunning: false
109
+ };
110
+ globalThis[BG_STATE] = state;
111
+ const ac = new AbortController();
112
+ const signal = ac.signal;
113
+ const stop = () => {
114
+ if (!state.running) return;
115
+ state.running = false;
116
+ ac.abort();
117
+ console.log("[XMTP Background] Stopping message processor...");
118
+ };
119
+ globalThis[BG_STOP] = stop;
120
+ process.once("SIGINT", stop);
121
+ process.once("SIGTERM", stop);
122
+ const publicClient = (0, import_viem.createPublicClient)({
123
+ chain: import_chains.base,
124
+ transport: (0, import_viem.http)()
125
+ });
126
+ const listener = new import_xmtp.MessageListener({
127
+ publicClient,
128
+ xmtpClient: opts.xmtpClient,
129
+ filter: opts.messageFilter,
130
+ heartbeatInterval: 5 * 60 * 1e3,
131
+ // 5 minutes
132
+ conversationCheckInterval: 30 * 1e3
133
+ // 30 seconds
134
+ });
135
+ listener.on("message", async (messageEvent) => {
136
+ try {
137
+ console.log(
138
+ `[XMTP Background] Processing message: ${messageEvent.message.content}`
139
+ );
140
+ console.log(
141
+ `[XMTP Background] Sender: ${messageEvent.sender?.address || "unknown"}`
142
+ );
143
+ console.log(
144
+ `[XMTP Background] Conversation: ${messageEvent.message.conversationId}`
145
+ );
146
+ const messages = [
147
+ {
148
+ id: (0, import_node_crypto.randomUUID)(),
149
+ role: "user",
150
+ parts: [
151
+ {
152
+ type: "text",
153
+ text: messageEvent.message.content?.toString() || ""
154
+ }
155
+ ]
156
+ }
157
+ ];
158
+ const serviceUrl = process.env.AGENT_URL || "http://localhost:8454";
159
+ const serviceToken = (0, import_xmtp.generateXMTPToolsToken)({
160
+ action: "send",
161
+ conversationId: messageEvent.message.conversationId,
162
+ content: messageEvent.message.content?.toString() || ""
163
+ });
164
+ const serviceClient = (0, import_xmtp.createAuthenticatedXmtpClient)(
165
+ serviceUrl,
166
+ serviceToken
167
+ );
168
+ const baseRuntime = {
169
+ chatId: messageEvent.message.conversationId,
170
+ messages,
171
+ conversation: messageEvent.conversation,
172
+ message: messageEvent.message,
173
+ parentMessage: messageEvent.parentMessage,
174
+ rootMessage: messageEvent.rootMessage,
175
+ sender: messageEvent.sender,
176
+ subjects: messageEvent.subjects,
177
+ xmtpClient: serviceClient
178
+ };
179
+ const runtime = await opts.agent.createRuntimeContext(baseRuntime);
180
+ console.log("[XMTP Background] Calling agent to process message...");
181
+ const result = await opts.agent.generate(messages, { runtime });
182
+ if (result.text) {
183
+ await messageEvent.conversation.send(result.text);
184
+ console.log(`[XMTP Background] Agent response sent: ${result.text}`);
185
+ }
186
+ state.messagesProcessed++;
187
+ state.lastOkAt = Date.now();
188
+ state.consecutiveErrors = 0;
189
+ console.log(
190
+ `[XMTP Background] Message processed successfully. Total: ${state.messagesProcessed}`
191
+ );
192
+ } catch (error) {
193
+ state.lastErrAt = Date.now();
194
+ state.consecutiveErrors++;
195
+ console.error("[XMTP Background] Error processing message:", error);
196
+ try {
197
+ await messageEvent.conversation.send(
198
+ "Sorry, I encountered an error processing your message."
199
+ );
200
+ } catch (sendError) {
201
+ console.error(
202
+ "[XMTP Background] Failed to send error message:",
203
+ sendError
204
+ );
205
+ }
206
+ }
207
+ });
208
+ listener.on("error", (error) => {
209
+ state.lastErrAt = Date.now();
210
+ state.consecutiveErrors++;
211
+ console.error("[XMTP Background] Message listener error:", error);
212
+ });
213
+ listener.on("started", () => {
214
+ state.listenerRunning = true;
215
+ console.log("[XMTP Background] Message listener started");
216
+ });
217
+ listener.on("stopped", () => {
218
+ state.listenerRunning = false;
219
+ console.log("[XMTP Background] Message listener stopped");
220
+ });
221
+ listener.on("heartbeat", (stats) => {
222
+ console.log(
223
+ `[XMTP Background] Heartbeat - Messages: ${stats.messageCount}, Conversations: ${stats.conversationCount}`
224
+ );
225
+ });
226
+ (async function supervise() {
227
+ let nextDelay = intervalMs;
228
+ while (state.running) {
229
+ try {
230
+ if (!state.listenerRunning) {
231
+ console.log("[XMTP Background] Starting message listener...");
232
+ await listener.start();
233
+ }
234
+ if (state.listenerRunning) {
235
+ state.lastOkAt = Date.now();
236
+ state.consecutiveErrors = 0;
237
+ nextDelay = intervalMs;
238
+ } else {
239
+ throw new Error("Message listener is not running");
240
+ }
241
+ } catch (error) {
242
+ state.lastErrAt = Date.now();
243
+ state.consecutiveErrors += 1;
244
+ const backoff = Math.min(
245
+ maxBackoffMs,
246
+ baseBackoffMs * 2 ** (state.consecutiveErrors - 1)
247
+ );
248
+ nextDelay = backoff;
249
+ console.error("[XMTP Background] Supervisor error:", error);
250
+ try {
251
+ if (state.listenerRunning) {
252
+ await listener.stop();
253
+ }
254
+ await sleep(1e3);
255
+ } catch (restartError) {
256
+ console.error(
257
+ "[XMTP Background] Error restarting listener:",
258
+ restartError
259
+ );
260
+ }
261
+ }
262
+ try {
263
+ await sleep(nextDelay, signal);
264
+ } catch (error) {
265
+ if (error instanceof Error && error.name === "AbortError") {
266
+ break;
267
+ }
268
+ throw error;
269
+ }
270
+ }
271
+ try {
272
+ if (state.listenerRunning) {
273
+ console.log("[XMTP Background] Stopping message listener...");
274
+ await listener.stop();
275
+ }
276
+ } catch (error) {
277
+ console.error("[XMTP Background] Error stopping listener:", error);
278
+ }
279
+ console.log("[XMTP Background] Supervisor stopped");
280
+ })();
281
+ console.log(
282
+ "[XMTP Background] Message processor started (always-on, in-process)"
110
283
  );
111
- return "fallback-api-key-for-dev-only";
112
284
  }
113
- return apiKey;
114
- })();
115
- var JWT_EXPIRY = 5 * 60;
116
- function generateXMTPToolsToken(payload) {
117
- const now = Math.floor(Date.now() / 1e3);
118
- const fullPayload = {
119
- ...payload,
120
- issued: now,
121
- expires: now + JWT_EXPIRY
122
- };
123
- return import_jsonwebtoken.default.sign(fullPayload, JWT_SECRET, {
124
- expiresIn: JWT_EXPIRY
125
- });
285
+ return async (_c, next) => next();
126
286
  }
127
-
128
- // src/server/processor.ts
129
- var BG_STARTED = Symbol("BG_STARTED");
130
- var BG_STATE = Symbol("BG_STATE");
131
- var BG_STOP = Symbol("BG_STOP");
132
287
  function getBgState() {
133
288
  return globalThis[BG_STATE];
134
289
  }
@@ -138,6 +293,12 @@ function stopBackground() {
138
293
  }
139
294
 
140
295
  // src/server/listen.ts
296
+ function createHonoMiddleware(client) {
297
+ return async (c, next) => {
298
+ c.set("xmtpClient", client);
299
+ return next();
300
+ };
301
+ }
141
302
  async function listen({
142
303
  agent,
143
304
  port,
@@ -148,6 +309,33 @@ async function listen({
148
309
  const context = {
149
310
  agent
150
311
  };
312
+ const { XMTP_WALLET_KEY, XMTP_ENCRYPTION_KEY } = process.env;
313
+ if (!XMTP_WALLET_KEY) {
314
+ throw new Error("XMTP_WALLET_KEY must be set");
315
+ }
316
+ if (!XMTP_ENCRYPTION_KEY) {
317
+ throw new Error("XMTP_ENCRYPTION_KEY must be set");
318
+ }
319
+ const cloudflareStoragePath = (0, import_utils.getCloudflareStoragePath)("xmtp");
320
+ const xmtpClient = await (0, import_xmtp2.createXMTPClient)(XMTP_WALLET_KEY, {
321
+ persist: true,
322
+ storagePath: cloudflareStoragePath
323
+ });
324
+ app.use(createHonoMiddleware(xmtpClient));
325
+ app.use(
326
+ createBackgroundMessageProcessor({
327
+ agent,
328
+ xmtpClient,
329
+ messageFilter: filter,
330
+ // Use the provided filter
331
+ intervalMs: 5e3,
332
+ // Check every 5 seconds
333
+ backoffMs: 1e3,
334
+ // Start with 1 second backoff
335
+ maxBackoffMs: 3e4
336
+ // Max 30 seconds backoff
337
+ })
338
+ );
151
339
  const xmtpPlugin = (0, import_xmtp2.XMTPPlugin)({
152
340
  filter
153
341
  });
@@ -206,7 +394,8 @@ async function listen({
206
394
  fetch: app.fetch,
207
395
  port: httpPort
208
396
  });
209
- console.log(`\u2705 XMTP Tools HTTP Server running on port ${httpPort}`);
397
+ console.log(`\u2705 Hybrid server running on port ${httpPort}`);
398
+ console.log(`\u{1F3A7} Background message listener is active`);
210
399
  } catch (error) {
211
400
  if (error.code === "EADDRINUSE") {
212
401
  console.error(
@@ -1197,7 +1386,6 @@ var xmtpTools = {
1197
1386
  blockchainTools,
1198
1387
  createTool,
1199
1388
  estimateGasTool,
1200
- generateXMTPToolsToken,
1201
1389
  getBalanceTool,
1202
1390
  getBgState,
1203
1391
  getBlockTool,