teleton 0.8.1 → 0.8.3

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 (43) hide show
  1. package/dist/bootstrap-DDFVEMYI.js +128 -0
  2. package/dist/{server-3FHI2SEB.js → chunk-2ERTYRHA.js} +26 -372
  3. package/dist/{chunk-5FNWBZ5K.js → chunk-33Z47EXI.js} +264 -274
  4. package/dist/{chunk-3S4GGLLR.js → chunk-35MX4ZUI.js} +23 -104
  5. package/dist/chunk-3UFPFWYP.js +12 -0
  6. package/dist/chunk-5SEMA47R.js +75 -0
  7. package/dist/{chunk-PHSAHTK4.js → chunk-6OOHHJ4N.js} +3 -108
  8. package/dist/{chunk-CGOXE4WP.js → chunk-7MWKT67G.js} +467 -914
  9. package/dist/chunk-AEHTQI3H.js +142 -0
  10. package/dist/{chunk-S6PHGKOC.js → chunk-AERHOXGC.js} +88 -322
  11. package/dist/chunk-ALKAAG4O.js +487 -0
  12. package/dist/{chunk-UP55PXFH.js → chunk-C4NKJT2Z.js} +8 -0
  13. package/dist/chunk-CUE4UZXR.js +129 -0
  14. package/dist/chunk-FUNF6H4W.js +251 -0
  15. package/dist/{chunk-7U7BOHCL.js → chunk-GHMXWAXI.js} +147 -63
  16. package/dist/{chunk-QBHRXLZS.js → chunk-H7MFXJZK.js} +2 -2
  17. package/dist/{chunk-QV2GLOTK.js → chunk-LC4TV3KL.js} +1 -1
  18. package/dist/{chunk-AYWEJCDB.js → chunk-LVTKJQ7O.js} +12 -10
  19. package/dist/{chunk-RCMD3U65.js → chunk-NQ6FZKCE.js} +13 -0
  20. package/dist/chunk-NVKBBTI6.js +128 -0
  21. package/dist/{setup-server-32XGDPE6.js → chunk-OIMAE24Q.js} +55 -216
  22. package/dist/{chunk-OJCLKU5Z.js → chunk-WFTC3JJW.js} +16 -0
  23. package/dist/chunk-WTDAICGT.js +175 -0
  24. package/dist/{chunk-KVXV7EF7.js → chunk-XDZDOKIF.js} +2 -2
  25. package/dist/cli/index.js +91 -27
  26. package/dist/{client-MPHPIZB6.js → client-5KD25NOP.js} +5 -4
  27. package/dist/{get-my-gifts-CC6HAVWB.js → get-my-gifts-Y7EN7RK4.js} +3 -3
  28. package/dist/index.js +19 -13
  29. package/dist/local-IHKJFQJS.js +9 -0
  30. package/dist/{memory-UBHM7ILG.js → memory-QMJRM3XJ.js} +9 -5
  31. package/dist/memory-hook-VUNWZ3NY.js +19 -0
  32. package/dist/{migrate-UBBEJ5BL.js → migrate-5VBAP52B.js} +5 -4
  33. package/dist/server-JF6FX772.js +813 -0
  34. package/dist/server-N4T7E25M.js +396 -0
  35. package/dist/setup-server-IX3BFPPH.js +217 -0
  36. package/dist/{store-M5IMUQCL.js → store-BY7S6IFN.js} +6 -5
  37. package/dist/{task-dependency-resolver-RR2O5S7B.js → task-dependency-resolver-L6UUMTHK.js} +2 -2
  38. package/dist/{task-executor-6W5HRX5C.js → task-executor-XBNJLUCS.js} +2 -2
  39. package/dist/{tool-adapter-IH5VGBOO.js → tool-adapter-IVX2XQJE.js} +1 -1
  40. package/dist/{tool-index-PMAOXWUA.js → tool-index-FTERJSZK.js} +4 -3
  41. package/dist/{transcript-NGDPSNIH.js → transcript-IM7G25OS.js} +2 -2
  42. package/package.json +4 -2
  43. package/dist/chunk-XBE4JB7C.js +0 -8
@@ -1,7 +1,10 @@
1
+ import {
2
+ AgentLifecycle
3
+ } from "./chunk-NVKBBTI6.js";
1
4
  import {
2
5
  telegramGetMyGiftsExecutor,
3
6
  telegramGetMyGiftsTool
4
- } from "./chunk-QBHRXLZS.js";
7
+ } from "./chunk-H7MFXJZK.js";
5
8
  import {
6
9
  AgentRuntime,
7
10
  DEDUST_API_URL,
@@ -22,11 +25,9 @@ import {
22
25
  fromUnits,
23
26
  getBlocklistConfig,
24
27
  getDecimals,
25
- getDefaultConfigPath,
26
28
  getTriggersConfig,
27
29
  hasStyledButtons,
28
30
  listPluginSecretKeys,
29
- loadConfig,
30
31
  loadEnhancedPlugins,
31
32
  loadSoul,
32
33
  module_default,
@@ -50,7 +51,7 @@ import {
50
51
  withTxLock,
51
52
  writePluginSecret,
52
53
  writeRawConfig
53
- } from "./chunk-CGOXE4WP.js";
54
+ } from "./chunk-7MWKT67G.js";
54
55
  import {
55
56
  getCachedTonClient,
56
57
  getKeyPair,
@@ -58,20 +59,16 @@ import {
58
59
  getWalletAddress,
59
60
  getWalletBalance,
60
61
  invalidateTonClientCache,
61
- loadTemplate,
62
62
  loadWallet,
63
63
  setToncenterApiKey
64
- } from "./chunk-S6PHGKOC.js";
64
+ } from "./chunk-FUNF6H4W.js";
65
65
  import {
66
- getErrorMessage
67
- } from "./chunk-XBE4JB7C.js";
68
- import {
69
- getEffectiveApiKey,
70
- getProviderModel
71
- } from "./chunk-AYWEJCDB.js";
66
+ getDefaultConfigPath,
67
+ loadConfig
68
+ } from "./chunk-AEHTQI3H.js";
72
69
  import {
73
- getProviderMetadata
74
- } from "./chunk-PHSAHTK4.js";
70
+ loadTemplate
71
+ } from "./chunk-AERHOXGC.js";
75
72
  import {
76
73
  ChatStore,
77
74
  JOURNAL_SCHEMA,
@@ -84,7 +81,10 @@ import {
84
81
  initializeMemory,
85
82
  migrateFromMainDb,
86
83
  openModuleDb
87
- } from "./chunk-7U7BOHCL.js";
84
+ } from "./chunk-GHMXWAXI.js";
85
+ import {
86
+ getErrorMessage
87
+ } from "./chunk-3UFPFWYP.js";
88
88
  import {
89
89
  ELEVENLABS_TTS_URL,
90
90
  GECKOTERMINAL_API_URL,
@@ -110,7 +110,14 @@ import {
110
110
  TELEGRAM_MAX_MESSAGE_LENGTH,
111
111
  WEB_FETCH_MAX_TEXT_LENGTH,
112
112
  WEB_SEARCH_MAX_RESULTS
113
- } from "./chunk-UP55PXFH.js";
113
+ } from "./chunk-C4NKJT2Z.js";
114
+ import {
115
+ getEffectiveApiKey,
116
+ getProviderModel
117
+ } from "./chunk-LVTKJQ7O.js";
118
+ import {
119
+ getProviderMetadata
120
+ } from "./chunk-6OOHHJ4N.js";
114
121
  import {
115
122
  fetchWithTimeout
116
123
  } from "./chunk-XQUHC3JZ.js";
@@ -133,7 +140,7 @@ import {
133
140
  initLoggerFromConfig,
134
141
  isVerbose,
135
142
  setVerbose
136
- } from "./chunk-RCMD3U65.js";
143
+ } from "./chunk-NQ6FZKCE.js";
137
144
 
138
145
  // src/telegram/client.ts
139
146
  import { TelegramClient, Api } from "telegram";
@@ -435,13 +442,11 @@ var TelegramUserClient = class {
435
442
  }
436
443
  addServiceMessageHandler(handler) {
437
444
  this.client.addEventHandler(async (update) => {
438
- if ((update instanceof Api.UpdateNewMessage || update instanceof Api.UpdateNewChannelMessage) && // eslint-disable-next-line @typescript-eslint/no-explicit-any -- GramJS update.message lacks proper typing
439
- update.message instanceof Api.MessageService) {
445
+ if ((update instanceof Api.UpdateNewMessage || update instanceof Api.UpdateNewChannelMessage) && update.message instanceof Api.MessageService) {
440
446
  await handler(update.message);
441
447
  }
442
448
  });
443
449
  }
444
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- GramJS raw update event
445
450
  addCallbackQueryHandler(handler) {
446
451
  this.client.addEventHandler(async (update) => {
447
452
  if (update.className === "UpdateBotCallbackQuery" || update.className === "UpdateInlineBotCallbackQuery") {
@@ -469,16 +474,13 @@ var TelegramUserClient = class {
469
474
  const parseMode = options.parseMode ?? "html";
470
475
  const formattedMessage = parseMode === "html" ? markdownToTelegramHtml(options.message) : options.message;
471
476
  return withFloodRetry(
472
- () => (
473
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- GramJS sendMessage accepts string | Entity
474
- this.client.sendMessage(entity, {
475
- message: formattedMessage,
476
- replyTo: options.replyTo,
477
- silent: options.silent,
478
- parseMode: parseMode === "none" ? void 0 : parseMode,
479
- linkPreview: false
480
- })
481
- )
477
+ () => this.client.sendMessage(entity, {
478
+ message: formattedMessage,
479
+ replyTo: options.replyTo,
480
+ silent: options.silent,
481
+ parseMode: parseMode === "none" ? void 0 : parseMode,
482
+ linkPreview: false
483
+ })
482
484
  );
483
485
  }
484
486
  async getMessages(entity, options) {
@@ -823,12 +825,11 @@ var TelegramBridge = class {
823
825
  let text = "";
824
826
  if (action instanceof Api2.MessageActionStarGiftPurchaseOffer) {
825
827
  const gift = action.gift;
826
- const price = action.price;
827
- const isUnique = gift.className === "StarGiftUnique";
828
+ const isUnique = gift instanceof Api2.StarGiftUnique;
828
829
  const title = gift.title || "Unknown Gift";
829
830
  const slug = isUnique ? gift.slug : void 0;
830
831
  const num = isUnique ? gift.num : void 0;
831
- const priceStars = price?.amount?.toString() || "?";
832
+ const priceStars = action.price.amount?.toString() || "?";
832
833
  const status = action.accepted ? "accepted" : action.declined ? "declined" : "pending";
833
834
  const expires = action.expiresAt ? new Date(action.expiresAt * 1e3).toISOString() : "unknown";
834
835
  text = `[Gift Offer Received]
@@ -847,12 +848,11 @@ var TelegramBridge = class {
847
848
  );
848
849
  } else if (action instanceof Api2.MessageActionStarGiftPurchaseOfferDeclined) {
849
850
  const gift = action.gift;
850
- const price = action.price;
851
- const isUnique = gift.className === "StarGiftUnique";
851
+ const isUnique = gift instanceof Api2.StarGiftUnique;
852
852
  const title = gift.title || "Unknown Gift";
853
853
  const slug = isUnique ? gift.slug : void 0;
854
854
  const num = isUnique ? gift.num : void 0;
855
- const priceStars = price?.amount?.toString() || "?";
855
+ const priceStars = action.price.amount?.toString() || "?";
856
856
  const reason = action.expired ? "expired" : "declined";
857
857
  text = `[Gift Offer ${action.expired ? "Expired" : "Declined"}]
858
858
  `;
@@ -861,7 +861,7 @@ var TelegramBridge = class {
861
861
  } else if (action instanceof Api2.MessageActionStarGift) {
862
862
  const gift = action.gift;
863
863
  const title = gift.title || "Unknown Gift";
864
- const stars = gift.stars?.toString() || "?";
864
+ const stars = gift instanceof Api2.StarGift ? gift.stars?.toString() || "?" : "?";
865
865
  const giftMessage = action.message?.text || "";
866
866
  const fromAnonymous = action.nameHidden;
867
867
  text = `[Gift Received]
@@ -3285,8 +3285,7 @@ var telegramGetRepliesExecutor = async (params, context) => {
3285
3285
  limit,
3286
3286
  maxId: 0,
3287
3287
  minId: 0,
3288
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- GramJS API response is untyped
3289
- hash: 0n
3288
+ hash: toLong(0n)
3290
3289
  })
3291
3290
  );
3292
3291
  const messages = [];
@@ -3381,8 +3380,7 @@ var telegramGetScheduledMessagesExecutor = async (params, context) => {
3381
3380
  const result = await gramJsClient.invoke(
3382
3381
  new Api11.messages.GetScheduledHistory({
3383
3382
  peer: entity,
3384
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- GramJS API response is untyped
3385
- hash: 0n
3383
+ hash: toLong(0n)
3386
3384
  })
3387
3385
  );
3388
3386
  const messages = "messages" in result ? result.messages : [];
@@ -7065,8 +7063,7 @@ var telegramGetFoldersExecutor = async (_params, context) => {
7065
7063
  const filterList = dialogFilters.filters ?? [];
7066
7064
  const folders = filterList.filter((filter) => filter.className === "DialogFilter").map((filter) => ({
7067
7065
  id: filter.id,
7068
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- GramJS API response is untyped
7069
- title: filter.title?.text ?? filter.title,
7066
+ title: filter.title.text,
7070
7067
  emoji: filter.emoticon || null,
7071
7068
  pinnedPeersCount: filter.pinnedPeers?.length || 0,
7072
7069
  includedPeersCount: filter.includePeers?.length || 0,
@@ -8092,19 +8089,15 @@ function decodeInlineMessageId(encoded) {
8092
8089
  if (buf.length === 20) {
8093
8090
  return new Api49.InputBotInlineMessageID({
8094
8091
  dcId: buf.readInt32LE(0),
8095
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- GramJS BigInteger compat
8096
- id: buf.readBigInt64LE(4),
8097
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- GramJS BigInteger compat
8098
- accessHash: buf.readBigInt64LE(12)
8092
+ id: toLong(buf.readBigInt64LE(4)),
8093
+ accessHash: toLong(buf.readBigInt64LE(12))
8099
8094
  });
8100
8095
  } else if (buf.length === 24) {
8101
8096
  return new Api49.InputBotInlineMessageID64({
8102
8097
  dcId: buf.readInt32LE(0),
8103
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- GramJS BigInteger compat
8104
- ownerId: buf.readBigInt64LE(4),
8098
+ ownerId: toLong(buf.readBigInt64LE(4)),
8105
8099
  id: buf.readInt32LE(12),
8106
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- GramJS BigInteger compat
8107
- accessHash: buf.readBigInt64LE(16)
8100
+ accessHash: toLong(buf.readBigInt64LE(16))
8108
8101
  });
8109
8102
  }
8110
8103
  throw new Error(`Unknown inline_message_id format (${buf.length} bytes)`);
@@ -8863,7 +8856,7 @@ var VerificationPoller = class {
8863
8856
  const me = this.bridge.getClient().getMe();
8864
8857
  if (!me) return { verified: false };
8865
8858
  const botUserId = Number(me.id);
8866
- const { telegramGetMyGiftsExecutor: telegramGetMyGiftsExecutor2 } = await import("./get-my-gifts-CC6HAVWB.js");
8859
+ const { telegramGetMyGiftsExecutor: telegramGetMyGiftsExecutor2 } = await import("./get-my-gifts-Y7EN7RK4.js");
8867
8860
  const toolContext = {
8868
8861
  bridge: this.bridge,
8869
8862
  db: this.db,
@@ -8878,7 +8871,8 @@ var VerificationPoller = class {
8878
8871
  if (!result.success || !result.data) {
8879
8872
  return { verified: false };
8880
8873
  }
8881
- const gifts = result.data.gifts || [];
8874
+ const verifyData = result.data;
8875
+ const gifts = verifyData.gifts || [];
8882
8876
  const matchingGift = gifts.find(
8883
8877
  (g) => g.slug === deal.userGivesGiftSlug && Number(g.fromId) === deal.userId && g.date && g.date >= deal.createdAt
8884
8878
  );
@@ -9759,7 +9753,8 @@ var GiftDetector = class {
9759
9753
  if (!result.success || !result.data) {
9760
9754
  return [];
9761
9755
  }
9762
- const gifts = result.data.gifts || [];
9756
+ const data = result.data;
9757
+ const gifts = data.gifts || [];
9763
9758
  const seenSet = this.seenGifts.get(userId) || /* @__PURE__ */ new Set();
9764
9759
  const newGifts = [];
9765
9760
  const currentMsgIds = /* @__PURE__ */ new Set();
@@ -10444,8 +10439,7 @@ var telegramSendGiftExecutor = async (params, context) => {
10444
10439
  const user = await gramJsClient.getInputEntity(userId);
10445
10440
  const invoiceData = {
10446
10441
  peer: user,
10447
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- GramJS API response is untyped
10448
- giftId: BigInt(giftId),
10442
+ giftId: toLong(giftId),
10449
10443
  hideName: anonymous,
10450
10444
  message: message ? new Api51.TextWithEntities({ text: message, entities: [] }) : void 0
10451
10445
  };
@@ -10631,8 +10625,7 @@ var telegramSetCollectiblePriceExecutor = async (params, context) => {
10631
10625
  new Api53.payments.UpdateStarGiftPrice({
10632
10626
  stargift: new Api53.InputSavedStarGiftUser({ msgId }),
10633
10627
  resellAmount: new Api53.StarsAmount({
10634
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- GramJS API response is untyped
10635
- amount: BigInt(isListing ? price : 0),
10628
+ amount: toLong(isListing ? price : 0),
10636
10629
  nanos: 0
10637
10630
  })
10638
10631
  })
@@ -10710,8 +10703,7 @@ var telegramGetResaleGiftsExecutor = async (params, context) => {
10710
10703
  }
10711
10704
  const result = await gramJsClient.invoke(
10712
10705
  new Api54.payments.GetResaleStarGifts({
10713
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- GramJS API response is untyped
10714
- giftId: BigInt(giftId),
10706
+ giftId: toLong(giftId),
10715
10707
  offset: "",
10716
10708
  limit,
10717
10709
  sortByPrice
@@ -10866,8 +10858,7 @@ var telegramSetGiftStatusExecutor = async (params, context) => {
10866
10858
  emojiStatus = new Api56.EmojiStatusEmpty();
10867
10859
  } else {
10868
10860
  emojiStatus = new Api56.InputEmojiStatusCollectible({
10869
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- GramJS API response is untyped
10870
- collectibleId: BigInt(collectibleId)
10861
+ collectibleId: toLong(collectibleId)
10871
10862
  });
10872
10863
  }
10873
10864
  await gramJsClient.invoke(
@@ -11104,8 +11095,7 @@ var telegramSendGiftOfferExecutor = async (params, context) => {
11104
11095
  new Api60.payments.SendStarGiftOffer({
11105
11096
  peer,
11106
11097
  slug,
11107
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- GramJS API response is untyped
11108
- price: new Api60.StarsAmount({ amount: BigInt(price), nanos: 0 }),
11098
+ price: new Api60.StarsAmount({ amount: toLong(price), nanos: 0 }),
11109
11099
  duration,
11110
11100
  randomId: randomLong()
11111
11101
  })
@@ -17052,7 +17042,6 @@ function runCommand(command, options) {
17052
17042
  detached: true,
17053
17043
  stdio: ["ignore", "pipe", "pipe"],
17054
17044
  encoding: "utf8"
17055
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Node.js spawn options type doesn't include encoding
17056
17045
  });
17057
17046
  const finish = (exitCode, signal) => {
17058
17047
  if (resolved) return;
@@ -18055,127 +18044,6 @@ var UserHookEvaluator = class {
18055
18044
  }
18056
18045
  };
18057
18046
 
18058
- // src/agent/lifecycle.ts
18059
- import { EventEmitter } from "events";
18060
- var log136 = createLogger("Lifecycle");
18061
- var AgentLifecycle = class extends EventEmitter {
18062
- state = "stopped";
18063
- error;
18064
- startPromise = null;
18065
- stopPromise = null;
18066
- runningSince = null;
18067
- registeredStartFn = null;
18068
- registeredStopFn = null;
18069
- getState() {
18070
- return this.state;
18071
- }
18072
- getError() {
18073
- return this.error;
18074
- }
18075
- getUptime() {
18076
- if (this.state !== "running" || this.runningSince === null) {
18077
- return null;
18078
- }
18079
- return Math.floor((Date.now() - this.runningSince) / 1e3);
18080
- }
18081
- /**
18082
- * Register the start/stop callbacks so start()/stop() can be called without args.
18083
- */
18084
- registerCallbacks(startFn, stopFn) {
18085
- this.registeredStartFn = startFn;
18086
- this.registeredStopFn = stopFn;
18087
- }
18088
- /**
18089
- * Start the agent. Uses the provided callback or falls back to registered one.
18090
- * - No-op if already running
18091
- * - Returns existing promise if already starting
18092
- * - Throws if currently stopping
18093
- */
18094
- async start(startFn) {
18095
- const fn = startFn ?? this.registeredStartFn;
18096
- if (!fn) {
18097
- throw new Error("No start function provided or registered");
18098
- }
18099
- if (this.state === "running") {
18100
- return;
18101
- }
18102
- if (this.state === "starting") {
18103
- return this.startPromise ?? Promise.resolve();
18104
- }
18105
- if (this.state === "stopping") {
18106
- throw new Error("Cannot start while agent is stopping");
18107
- }
18108
- this.transition("starting");
18109
- this.startPromise = (async () => {
18110
- try {
18111
- await fn();
18112
- this.error = void 0;
18113
- this.runningSince = Date.now();
18114
- this.transition("running");
18115
- } catch (err) {
18116
- const message = err instanceof Error ? err.message : String(err);
18117
- this.error = message;
18118
- this.runningSince = null;
18119
- this.transition("stopped", message);
18120
- throw err;
18121
- } finally {
18122
- this.startPromise = null;
18123
- }
18124
- })();
18125
- return this.startPromise;
18126
- }
18127
- /**
18128
- * Stop the agent. Uses the provided callback or falls back to registered one.
18129
- * - No-op if already stopped
18130
- * - Returns existing promise if already stopping
18131
- * - If starting, waits for start to complete then stops
18132
- */
18133
- async stop(stopFn) {
18134
- const fn = stopFn ?? this.registeredStopFn;
18135
- if (!fn) {
18136
- throw new Error("No stop function provided or registered");
18137
- }
18138
- if (this.state === "stopped") {
18139
- return;
18140
- }
18141
- if (this.state === "stopping") {
18142
- return this.stopPromise ?? Promise.resolve();
18143
- }
18144
- if (this.state === "starting" && this.startPromise) {
18145
- try {
18146
- await this.startPromise;
18147
- } catch {
18148
- return;
18149
- }
18150
- }
18151
- this.transition("stopping");
18152
- this.stopPromise = (async () => {
18153
- try {
18154
- await fn();
18155
- } catch (err) {
18156
- log136.error({ err }, "Error during agent stop");
18157
- } finally {
18158
- this.runningSince = null;
18159
- this.transition("stopped");
18160
- this.stopPromise = null;
18161
- }
18162
- })();
18163
- return this.stopPromise;
18164
- }
18165
- transition(newState, error) {
18166
- this.state = newState;
18167
- const event = {
18168
- state: newState,
18169
- timestamp: Date.now()
18170
- };
18171
- if (error !== void 0) {
18172
- event.error = error;
18173
- }
18174
- log136.info(`Agent state: ${newState}${error ? ` (${error})` : ""}`);
18175
- this.emit("stateChange", event);
18176
- }
18177
- };
18178
-
18179
18047
  // src/bot/rate-limiter.ts
18180
18048
  var PluginRateLimiter = class {
18181
18049
  windows = /* @__PURE__ */ new Map();
@@ -18217,7 +18085,7 @@ var PluginRateLimiter = class {
18217
18085
  };
18218
18086
 
18219
18087
  // src/index.ts
18220
- var log137 = createLogger("App");
18088
+ var log136 = createLogger("App");
18221
18089
  var TeletonApp = class {
18222
18090
  config;
18223
18091
  agent;
@@ -18232,9 +18100,11 @@ var TeletonApp = class {
18232
18100
  memory;
18233
18101
  sdkDeps;
18234
18102
  webuiServer = null;
18103
+ apiServer = null;
18235
18104
  pluginWatcher = null;
18236
18105
  mcpConnections = [];
18237
18106
  callbackHandlerRegistered = false;
18107
+ messageHandlersRegistered = false;
18238
18108
  lifecycle = new AgentLifecycle();
18239
18109
  hookRunner;
18240
18110
  userHookEvaluator = null;
@@ -18309,13 +18179,52 @@ var TeletonApp = class {
18309
18179
  getLifecycle() {
18310
18180
  return this.lifecycle;
18311
18181
  }
18182
+ // --- Public accessors for API-only bootstrap mode ---
18183
+ getAgent() {
18184
+ return this.agent;
18185
+ }
18186
+ getBridge() {
18187
+ return this.bridge;
18188
+ }
18189
+ getMemory() {
18190
+ return this.memory;
18191
+ }
18192
+ getToolRegistry() {
18193
+ return this.toolRegistry;
18194
+ }
18195
+ getPlugins() {
18196
+ return this.modules.filter((m) => this.toolRegistry.isPluginModule(m.name)).map((m) => ({ name: m.name, version: m.version ?? "0.0.0" }));
18197
+ }
18198
+ getWebuiConfig() {
18199
+ return this.config.webui;
18200
+ }
18201
+ getConfigPath() {
18202
+ return this.configPath;
18203
+ }
18204
+ /** Start agent subsystems without WebUI/API servers. For bootstrap mode. */
18205
+ async startAgentSubsystems() {
18206
+ this.lifecycle.registerCallbacks(
18207
+ () => this.startAgent(),
18208
+ () => this.stopAgent()
18209
+ );
18210
+ await this.lifecycle.start();
18211
+ }
18212
+ /** Stop agent subsystems and close database. For bootstrap mode. */
18213
+ async stopAgentSubsystems() {
18214
+ await this.lifecycle.stop();
18215
+ try {
18216
+ closeDatabase();
18217
+ } catch (e) {
18218
+ log136.error({ err: e }, "Database close failed");
18219
+ }
18220
+ }
18312
18221
  /**
18313
18222
  * Start the agent
18314
18223
  */
18315
18224
  async start() {
18316
18225
  const blue = "\x1B[34m";
18317
18226
  const reset = "\x1B[0m";
18318
- log137.info(`
18227
+ log136.info(`
18319
18228
  ${blue} \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510
18320
18229
  \u2502 \u2502
18321
18230
  \u2502 ______________ ________________ _ __ ___ _____________ ________ \u2502
@@ -18332,7 +18241,7 @@ ${blue} \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u250
18332
18241
  );
18333
18242
  if (this.config.webui.enabled) {
18334
18243
  try {
18335
- const { WebUIServer } = await import("./server-3FHI2SEB.js");
18244
+ const { WebUIServer } = await import("./server-N4T7E25M.js");
18336
18245
  const mcpServers = () => Object.entries(this.config.mcp.servers).map(([name, serverConfig]) => {
18337
18246
  const type = serverConfig.command ? "stdio" : serverConfig.url ? "streamable-http" : "sse";
18338
18247
  const target = serverConfig.command ?? serverConfig.url ?? "";
@@ -18379,8 +18288,68 @@ ${blue} \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u250
18379
18288
  });
18380
18289
  await this.webuiServer.start();
18381
18290
  } catch (error) {
18382
- log137.error({ err: error }, "\u274C Failed to start WebUI server");
18383
- log137.warn("\u26A0\uFE0F Continuing without WebUI...");
18291
+ log136.error({ err: error }, "\u274C Failed to start WebUI server");
18292
+ log136.warn("\u26A0\uFE0F Continuing without WebUI...");
18293
+ }
18294
+ }
18295
+ if (this.config.api?.enabled) {
18296
+ try {
18297
+ const { ApiServer: ApiServerClass } = await import("./server-JF6FX772.js");
18298
+ const mcpServers = () => Object.entries(this.config.mcp.servers).map(([name, serverConfig]) => {
18299
+ const type = serverConfig.command ? "stdio" : serverConfig.url ? "streamable-http" : "sse";
18300
+ const target = serverConfig.command ?? serverConfig.url ?? "";
18301
+ const connected = this.mcpConnections.some((c) => c.serverName === name);
18302
+ const moduleName = `mcp_${name}`;
18303
+ const moduleTools = this.toolRegistry.getModuleTools(moduleName);
18304
+ return {
18305
+ name,
18306
+ type,
18307
+ target,
18308
+ scope: serverConfig.scope ?? "always",
18309
+ enabled: serverConfig.enabled ?? true,
18310
+ connected,
18311
+ toolCount: moduleTools.length,
18312
+ tools: moduleTools.map((t) => t.name),
18313
+ envKeys: Object.keys(serverConfig.env ?? {})
18314
+ };
18315
+ });
18316
+ const builtinNames = this.modules.map((m) => m.name);
18317
+ const pluginContext = {
18318
+ bridge: this.bridge,
18319
+ db: getDatabase().getDb(),
18320
+ config: this.config
18321
+ };
18322
+ this.apiServer = new ApiServerClass(
18323
+ {
18324
+ agent: this.agent,
18325
+ bridge: this.bridge,
18326
+ memory: this.memory,
18327
+ toolRegistry: this.toolRegistry,
18328
+ plugins: this.modules.filter((m) => this.toolRegistry.isPluginModule(m.name)).map((m) => ({ name: m.name, version: m.version ?? "0.0.0" })),
18329
+ mcpServers,
18330
+ config: this.config.webui,
18331
+ configPath: this.configPath,
18332
+ lifecycle: this.lifecycle,
18333
+ marketplace: {
18334
+ modules: this.modules,
18335
+ config: this.config,
18336
+ sdkDeps: this.sdkDeps,
18337
+ pluginContext,
18338
+ loadedModuleNames: builtinNames,
18339
+ rewireHooks: () => this.wirePluginEventHooks()
18340
+ },
18341
+ userHookEvaluator: this.userHookEvaluator
18342
+ },
18343
+ this.config.api
18344
+ );
18345
+ await this.apiServer.start();
18346
+ if (process.env.TELETON_JSON_CREDENTIALS === "true") {
18347
+ const creds = this.apiServer.getCredentials();
18348
+ process.stdout.write(JSON.stringify(creds) + "\n");
18349
+ }
18350
+ } catch (error) {
18351
+ log136.error({ err: error }, "Failed to start Management API server");
18352
+ log136.warn("Continuing without Management API...");
18384
18353
  }
18385
18354
  }
18386
18355
  await this.lifecycle.start(() => this.startAgent());
@@ -18413,7 +18382,7 @@ ${blue} \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u250
18413
18382
  }
18414
18383
  this.modules.push(mod);
18415
18384
  } catch (error) {
18416
- log137.error(
18385
+ log136.error(
18417
18386
  `\u274C Plugin "${mod.name}" failed to load: ${error instanceof Error ? error.message : error}`
18418
18387
  );
18419
18388
  }
@@ -18429,7 +18398,7 @@ ${blue} \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u250
18429
18398
  if (mcp.count > 0) {
18430
18399
  this.toolCount = this.toolRegistry.count;
18431
18400
  mcpServerNames.push(...mcp.names);
18432
- log137.info(
18401
+ log136.info(
18433
18402
  `\u{1F50C} MCP: ${mcp.count} tools from ${mcp.names.length} server(s) (${mcp.names.join(", ")})`
18434
18403
  );
18435
18404
  }
@@ -18437,7 +18406,7 @@ ${blue} \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u250
18437
18406
  }
18438
18407
  this.toolRegistry.loadConfigFromDB(getDatabase().getDb());
18439
18408
  if (this.config.tool_rag.enabled) {
18440
- const { ToolIndex } = await import("./tool-index-PMAOXWUA.js");
18409
+ const { ToolIndex } = await import("./tool-index-FTERJSZK.js");
18441
18410
  const toolIndex2 = new ToolIndex(
18442
18411
  getDatabase().getDb(),
18443
18412
  this.memory.embedder,
@@ -18457,50 +18426,61 @@ ${blue} \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u250
18457
18426
  const provider = this.config.agent.provider || "anthropic";
18458
18427
  const providerMeta = getProviderMetadata(provider);
18459
18428
  const allNames = [...moduleNames, ...pluginNames, ...mcpServerNames];
18460
- log137.info(
18429
+ log136.info(
18461
18430
  `\u{1F50C} ${this.toolCount} tools loaded (${allNames.join(", ")})${pluginToolCount > 0 ? ` \u2014 ${pluginToolCount} from plugins` : ""}`
18462
18431
  );
18463
18432
  if (providerMeta.toolLimit !== null && this.toolCount > providerMeta.toolLimit) {
18464
- log137.warn(
18433
+ log136.warn(
18465
18434
  `\u26A0\uFE0F Tool count (${this.toolCount}) exceeds ${providerMeta.displayName} limit (${providerMeta.toolLimit})`
18466
18435
  );
18467
18436
  }
18468
- const { migrateSessionsToDb } = await import("./migrate-UBBEJ5BL.js");
18437
+ const { migrateSessionsToDb } = await import("./migrate-5VBAP52B.js");
18469
18438
  migrateSessionsToDb();
18470
- const { cleanupOldTranscripts } = await import("./transcript-NGDPSNIH.js");
18439
+ const { cleanupOldTranscripts } = await import("./transcript-IM7G25OS.js");
18471
18440
  cleanupOldTranscripts(30);
18472
- const { pruneOldSessions } = await import("./store-M5IMUQCL.js");
18441
+ const { pruneOldSessions } = await import("./store-BY7S6IFN.js");
18473
18442
  pruneOldSessions(30);
18474
18443
  if (this.memory.embedder.warmup) {
18475
18444
  await this.memory.embedder.warmup();
18476
18445
  }
18477
- const indexResult = await this.memory.knowledge.indexAll();
18478
18446
  const db2 = getDatabase();
18447
+ const forceReindex = db2.didDimensionsChange();
18448
+ const indexResult = await this.memory.knowledge.indexAll({ force: forceReindex });
18479
18449
  let ftsResult = { knowledge: 0, messages: 0 };
18480
18450
  if (indexResult.indexed > 0) {
18481
18451
  ftsResult = db2.rebuildFtsIndexes();
18482
18452
  }
18453
+ import("./memory-hook-VUNWZ3NY.js").then(
18454
+ ({ consolidateOldMemoryFiles }) => consolidateOldMemoryFiles({
18455
+ apiKey: this.config.agent.api_key,
18456
+ provider: this.config.agent.provider,
18457
+ utilityModel: this.config.agent.utility_model
18458
+ })
18459
+ ).then((r) => {
18460
+ if (r.consolidated > 0)
18461
+ log136.info(`\u{1F9F9} Consolidated ${r.consolidated} old session memory files`);
18462
+ }).catch((error) => log136.warn({ err: error }, "Memory consolidation skipped"));
18483
18463
  const toolIndex = this.toolRegistry.getToolIndex();
18484
18464
  if (toolIndex) {
18485
18465
  const t0 = Date.now();
18486
18466
  const indexedCount = await toolIndex.indexAll(this.toolRegistry.getAll());
18487
- log137.info(`\u{1F50D} Tool RAG: ${indexedCount} tools indexed (${Date.now() - t0}ms)`);
18467
+ log136.info(`\u{1F50D} Tool RAG: ${indexedCount} tools indexed (${Date.now() - t0}ms)`);
18488
18468
  }
18489
18469
  this.agent.initializeContextBuilder(this.memory.embedder, db2.isVectorSearchReady());
18490
18470
  if (this.config.agent.provider === "cocoon") {
18491
18471
  try {
18492
- const { registerCocoonModels } = await import("./client-MPHPIZB6.js");
18472
+ const { registerCocoonModels } = await import("./client-5KD25NOP.js");
18493
18473
  const port = this.config.cocoon?.port ?? 1e4;
18494
18474
  const models = await registerCocoonModels(port);
18495
18475
  if (models.length === 0) {
18496
18476
  throw new Error(`No models found on port ${port}`);
18497
18477
  }
18498
- log137.info(`Cocoon Network ready \u2014 ${models.length} model(s) on port ${port}`);
18478
+ log136.info(`Cocoon Network ready \u2014 ${models.length} model(s) on port ${port}`);
18499
18479
  } catch (err) {
18500
- log137.error(
18480
+ log136.error(
18501
18481
  `Cocoon Network unavailable on port ${this.config.cocoon?.port ?? 1e4}: ${getErrorMessage(err)}`
18502
18482
  );
18503
- log137.error("Start the Cocoon client first: cocoon start");
18483
+ log136.error("Start the Cocoon client first: cocoon start");
18504
18484
  throw new Error(`Cocoon Network unavailable: ${getErrorMessage(err)}`);
18505
18485
  }
18506
18486
  }
@@ -18511,22 +18491,22 @@ ${blue} \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u250
18511
18491
  }
18512
18492
  if (this.config.agent.provider === "local" && this.config.agent.base_url) {
18513
18493
  try {
18514
- const { registerLocalModels } = await import("./client-MPHPIZB6.js");
18494
+ const { registerLocalModels } = await import("./client-5KD25NOP.js");
18515
18495
  const models = await registerLocalModels(this.config.agent.base_url);
18516
18496
  if (models.length > 0) {
18517
- log137.info(`Discovered ${models.length} local model(s): ${models.join(", ")}`);
18497
+ log136.info(`Discovered ${models.length} local model(s): ${models.join(", ")}`);
18518
18498
  if (!this.config.agent.model || this.config.agent.model === "auto") {
18519
18499
  this.config.agent.model = models[0];
18520
- log137.info(`Using local model: ${models[0]}`);
18500
+ log136.info(`Using local model: ${models[0]}`);
18521
18501
  }
18522
18502
  } else {
18523
- log137.warn("No models found on local LLM server \u2014 is it running?");
18503
+ log136.warn("No models found on local LLM server \u2014 is it running?");
18524
18504
  }
18525
18505
  } catch (err) {
18526
- log137.error(
18506
+ log136.error(
18527
18507
  `Local LLM server unavailable at ${this.config.agent.base_url}: ${getErrorMessage(err)}`
18528
18508
  );
18529
- log137.error("Start the LLM server first (e.g. ollama serve)");
18509
+ log136.error("Start the LLM server first (e.g. ollama serve)");
18530
18510
  throw new Error(`Local LLM server unavailable: ${getErrorMessage(err)}`);
18531
18511
  }
18532
18512
  }
@@ -18557,12 +18537,12 @@ ${blue} \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u250
18557
18537
  startedModules.push(mod);
18558
18538
  }
18559
18539
  } catch (error) {
18560
- log137.error({ err: error }, "\u274C Module start failed, cleaning up started modules");
18540
+ log136.error({ err: error }, "\u274C Module start failed, cleaning up started modules");
18561
18541
  for (const mod of startedModules.reverse()) {
18562
18542
  try {
18563
18543
  await mod.stop?.();
18564
18544
  } catch (e) {
18565
- log137.error({ err: e }, `\u26A0\uFE0F Module "${mod.name}" cleanup failed`);
18545
+ log136.error({ err: e }, `\u26A0\uFE0F Module "${mod.name}" cleanup failed`);
18566
18546
  }
18567
18547
  }
18568
18548
  throw error;
@@ -18574,10 +18554,10 @@ ${blue} \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u250
18574
18554
  this.sdkDeps.grammyBot = activeDealBot.getBot();
18575
18555
  this.sdkDeps.rateLimiter = rateLimiter;
18576
18556
  inlineRouter.setGramJSBot(activeDealBot.getGramJSBot());
18577
- log137.info("\u{1F50C} Bot SDK: inline router installed");
18557
+ log136.info("\u{1F50C} Bot SDK: inline router installed");
18578
18558
  }
18579
18559
  if (hookRegistry.hasAnyHooks()) {
18580
- const hookRunner = createHookRunner(hookRegistry, { logger: log137 });
18560
+ const hookRunner = createHookRunner(hookRegistry, { logger: log136 });
18581
18561
  this.agent.setHookRunner(hookRunner);
18582
18562
  this.hookRunner = hookRunner;
18583
18563
  const activeHooks = [
@@ -18596,7 +18576,7 @@ ${blue} \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u250
18596
18576
  "agent:stop"
18597
18577
  ];
18598
18578
  const active = activeHooks.filter((n) => hookRegistry.hasHooks(n));
18599
- log137.info(`\u{1FA9D} Hook runner created (${active.join(", ")})`);
18579
+ log136.info(`\u{1FA9D} Hook runner created (${active.join(", ")})`);
18600
18580
  }
18601
18581
  this.wirePluginEventHooks();
18602
18582
  if (this.config.dev.hot_reload) {
@@ -18610,22 +18590,22 @@ ${blue} \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u250
18610
18590
  });
18611
18591
  this.pluginWatcher.start();
18612
18592
  }
18613
- log137.info(`\u2705 SOUL.md loaded`);
18614
- log137.info(`\u2705 Knowledge: ${indexResult.indexed} files, ${ftsResult.knowledge} chunks indexed`);
18615
- log137.info(`\u2705 Telegram: @${username} connected`);
18616
- log137.info(`\u2705 TON Blockchain: connected`);
18593
+ log136.info(`\u2705 SOUL.md loaded`);
18594
+ log136.info(`\u2705 Knowledge: ${indexResult.indexed} files, ${ftsResult.knowledge} chunks indexed`);
18595
+ log136.info(`\u2705 Telegram: @${username} connected`);
18596
+ log136.info(`\u2705 TON Blockchain: connected`);
18617
18597
  if (this.config.tonapi_key) {
18618
- log137.info(`\u{1F511} TonAPI key configured`);
18598
+ log136.info(`\u{1F511} TonAPI key configured`);
18619
18599
  }
18620
- log137.info(`\u2705 DEXs: STON.fi, DeDust connected`);
18621
- log137.info(`\u2705 Wallet: ${walletAddress || "not configured"}`);
18622
- log137.info(`\u2705 Model: ${provider}/${this.config.agent.model}`);
18623
- log137.info(`\u2705 Admins: ${this.config.telegram.admin_ids.join(", ")}`);
18624
- log137.info(
18600
+ log136.info(`\u2705 DEXs: STON.fi, DeDust connected`);
18601
+ log136.info(`\u2705 Wallet: ${walletAddress || "not configured"}`);
18602
+ log136.info(`\u2705 Model: ${provider}/${this.config.agent.model}`);
18603
+ log136.info(`\u2705 Admins: ${this.config.telegram.admin_ids.join(", ")}`);
18604
+ log136.info(
18625
18605
  `\u2705 Policy: DM ${this.config.telegram.dm_policy}, Groups ${this.config.telegram.group_policy}, Debounce ${this.config.telegram.debounce_ms}ms
18626
18606
  `
18627
18607
  );
18628
- log137.info("Teleton Agent is running! Press Ctrl+C to stop.");
18608
+ log136.info("Teleton Agent is running! Press Ctrl+C to stop.");
18629
18609
  this.startTime = Date.now();
18630
18610
  this.messagesProcessed = 0;
18631
18611
  if (this.hookRunner) {
@@ -18666,23 +18646,26 @@ ${blue} \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u250
18666
18646
  }
18667
18647
  },
18668
18648
  (error, messages) => {
18669
- log137.error({ err: error }, `Error processing batch of ${messages.length} messages`);
18649
+ log136.error({ err: error }, `Error processing batch of ${messages.length} messages`);
18670
18650
  }
18671
18651
  );
18672
- this.bridge.onNewMessage(async (message) => {
18673
- try {
18674
- await this.debouncer.enqueue(message);
18675
- } catch (error) {
18676
- log137.error({ err: error }, "Error enqueueing message");
18677
- }
18678
- });
18679
- this.bridge.onServiceMessage(async (message) => {
18680
- try {
18681
- await this.debouncer.enqueue(message);
18682
- } catch (error) {
18683
- log137.error({ err: error }, "Error enqueueing service message");
18684
- }
18685
- });
18652
+ if (!this.messageHandlersRegistered) {
18653
+ this.bridge.onNewMessage(async (message) => {
18654
+ try {
18655
+ await this.debouncer.enqueue(message);
18656
+ } catch (error) {
18657
+ log136.error({ err: error }, "Error enqueueing message");
18658
+ }
18659
+ });
18660
+ this.bridge.onServiceMessage(async (message) => {
18661
+ try {
18662
+ await this.debouncer.enqueue(message);
18663
+ } catch (error) {
18664
+ log136.error({ err: error }, "Error enqueueing service message");
18665
+ }
18666
+ });
18667
+ this.messageHandlersRegistered = true;
18668
+ }
18686
18669
  }
18687
18670
  /**
18688
18671
  * Resolve owner name and username from Telegram API if not already configured.
@@ -18725,10 +18708,10 @@ ${blue} \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u250
18725
18708
  writeRawConfig(raw, this.configPath);
18726
18709
  const displayName = this.config.telegram.owner_name || "Unknown";
18727
18710
  const displayUsername = this.config.telegram.owner_username ? ` (@${this.config.telegram.owner_username})` : "";
18728
- log137.info(`\u{1F464} Owner resolved: ${displayName}${displayUsername}`);
18711
+ log136.info(`\u{1F464} Owner resolved: ${displayName}${displayUsername}`);
18729
18712
  }
18730
18713
  } catch (error) {
18731
- log137.warn(
18714
+ log136.warn(
18732
18715
  `\u26A0\uFE0F Could not resolve owner info: ${error instanceof Error ? error.message : error}`
18733
18716
  );
18734
18717
  }
@@ -18797,7 +18780,7 @@ Task: "${taskDescription}"`;
18797
18780
  if (this.adminHandler.isPaused()) return;
18798
18781
  await this.messageHandler.handleMessage(message);
18799
18782
  } catch (error) {
18800
- log137.error({ err: error }, "Error handling message");
18783
+ log136.error({ err: error }, "Error handling message");
18801
18784
  }
18802
18785
  }
18803
18786
  /**
@@ -18805,21 +18788,21 @@ Task: "${taskDescription}"`;
18805
18788
  */
18806
18789
  async handleScheduledTask(message) {
18807
18790
  const { getTaskStore } = await import("./tasks-WQIKXDX5.js");
18808
- const { executeScheduledTask } = await import("./task-executor-6W5HRX5C.js");
18809
- const { TaskDependencyResolver } = await import("./task-dependency-resolver-RR2O5S7B.js");
18810
- const { getDatabase: getDatabase2 } = await import("./memory-UBHM7ILG.js");
18791
+ const { executeScheduledTask } = await import("./task-executor-XBNJLUCS.js");
18792
+ const { TaskDependencyResolver } = await import("./task-dependency-resolver-L6UUMTHK.js");
18793
+ const { getDatabase: getDatabase2 } = await import("./memory-QMJRM3XJ.js");
18811
18794
  const db2 = getDatabase2().getDb();
18812
18795
  const taskStore = getTaskStore(db2);
18813
18796
  const match = message.text.match(/^\[TASK:([^\]]+)\]/);
18814
18797
  if (!match) {
18815
- log137.warn(`Invalid task format: ${message.text}`);
18798
+ log136.warn(`Invalid task format: ${message.text}`);
18816
18799
  return;
18817
18800
  }
18818
18801
  const taskId = match[1];
18819
18802
  try {
18820
18803
  const task = taskStore.getTask(taskId);
18821
18804
  if (!task) {
18822
- log137.warn(`Task ${taskId} not found in database`);
18805
+ log136.warn(`Task ${taskId} not found in database`);
18823
18806
  await this.bridge.sendMessage({
18824
18807
  chatId: message.chatId,
18825
18808
  text: `\u26A0\uFE0F Task ${taskId} not found. It may have been deleted.`,
@@ -18828,11 +18811,11 @@ Task: "${taskDescription}"`;
18828
18811
  return;
18829
18812
  }
18830
18813
  if (task.status === "cancelled" || task.status === "done" || task.status === "failed") {
18831
- log137.info(`\u23ED\uFE0F Task ${taskId} already ${task.status}, skipping`);
18814
+ log136.info(`\u23ED\uFE0F Task ${taskId} already ${task.status}, skipping`);
18832
18815
  return;
18833
18816
  }
18834
18817
  if (!taskStore.canExecute(taskId)) {
18835
- log137.warn(`Task ${taskId} cannot execute yet - dependencies not satisfied`);
18818
+ log136.warn(`Task ${taskId} cannot execute yet - dependencies not satisfied`);
18836
18819
  await this.bridge.sendMessage({
18837
18820
  chatId: message.chatId,
18838
18821
  text: `\u23F3 Task "${task.description}" is waiting for parent tasks to complete.`,
@@ -18875,13 +18858,13 @@ Task: "${taskDescription}"`;
18875
18858
  });
18876
18859
  }
18877
18860
  taskStore.completeTask(taskId, response.content);
18878
- log137.info(`\u2705 Executed scheduled task ${taskId}: ${task.description}`);
18861
+ log136.info(`\u2705 Executed scheduled task ${taskId}: ${task.description}`);
18879
18862
  if (!this.dependencyResolver) {
18880
18863
  this.dependencyResolver = new TaskDependencyResolver(taskStore, this.bridge);
18881
18864
  }
18882
18865
  await this.dependencyResolver.onTaskComplete(taskId);
18883
18866
  } catch (error) {
18884
- log137.error({ err: error }, "Error handling scheduled task");
18867
+ log136.error({ err: error }, "Error handling scheduled task");
18885
18868
  try {
18886
18869
  taskStore.failTask(taskId, getErrorMessage(error));
18887
18870
  if (!this.dependencyResolver) {
@@ -18906,7 +18889,7 @@ Task: "${taskDescription}"`;
18906
18889
  try {
18907
18890
  await withHooks.onMessage(event);
18908
18891
  } catch (err) {
18909
- log137.error(
18892
+ log136.error(
18910
18893
  `\u274C [${mod.name}] onMessage error: ${err instanceof Error ? err.message : err}`
18911
18894
  );
18912
18895
  }
@@ -18916,7 +18899,7 @@ Task: "${taskDescription}"`;
18916
18899
  ]);
18917
18900
  const hookCount = this.modules.filter((m) => m.onMessage).length;
18918
18901
  if (hookCount > 0) {
18919
- log137.info(`\u{1F517} ${hookCount} plugin onMessage hook(s) registered`);
18902
+ log136.info(`\u{1F517} ${hookCount} plugin onMessage hook(s) registered`);
18920
18903
  }
18921
18904
  if (!this.callbackHandlerRegistered) {
18922
18905
  this.bridge.getClient().addCallbackQueryHandler(async (update) => {
@@ -18936,7 +18919,7 @@ Task: "${taskDescription}"`;
18936
18919
  try {
18937
18920
  await this.bridge.getClient().answerCallbackQuery(queryId, { message: text, alert });
18938
18921
  } catch (err) {
18939
- log137.error(
18922
+ log136.error(
18940
18923
  `\u274C Failed to answer callback query: ${err instanceof Error ? err.message : err}`
18941
18924
  );
18942
18925
  }
@@ -18956,7 +18939,7 @@ Task: "${taskDescription}"`;
18956
18939
  try {
18957
18940
  await withHooks.onCallbackQuery(event);
18958
18941
  } catch (err) {
18959
- log137.error(
18942
+ log136.error(
18960
18943
  `\u274C [${mod.name}] onCallbackQuery error: ${err instanceof Error ? err.message : err}`
18961
18944
  );
18962
18945
  }
@@ -18968,7 +18951,7 @@ Task: "${taskDescription}"`;
18968
18951
  (m) => m.onCallbackQuery
18969
18952
  ).length;
18970
18953
  if (cbCount > 0) {
18971
- log137.info(`\u{1F517} ${cbCount} plugin onCallbackQuery hook(s) registered`);
18954
+ log136.info(`\u{1F517} ${cbCount} plugin onCallbackQuery hook(s) registered`);
18972
18955
  }
18973
18956
  }
18974
18957
  }
@@ -18976,19 +18959,26 @@ Task: "${taskDescription}"`;
18976
18959
  * Stop the agent
18977
18960
  */
18978
18961
  async stop() {
18979
- log137.info("\u{1F44B} Stopping Teleton AI...");
18962
+ log136.info("\u{1F44B} Stopping Teleton AI...");
18980
18963
  await this.lifecycle.stop(() => this.stopAgent());
18981
18964
  if (this.webuiServer) {
18982
18965
  try {
18983
18966
  await this.webuiServer.stop();
18984
18967
  } catch (e) {
18985
- log137.error({ err: e }, "\u26A0\uFE0F WebUI stop failed");
18968
+ log136.error({ err: e }, "\u26A0\uFE0F WebUI stop failed");
18969
+ }
18970
+ }
18971
+ if (this.apiServer) {
18972
+ try {
18973
+ await this.apiServer.stop();
18974
+ } catch (e) {
18975
+ log136.error({ err: e }, "\u26A0\uFE0F Management API stop failed");
18986
18976
  }
18987
18977
  }
18988
18978
  try {
18989
18979
  closeDatabase();
18990
18980
  } catch (e) {
18991
- log137.error({ err: e }, "\u26A0\uFE0F Database close failed");
18981
+ log136.error({ err: e }, "\u26A0\uFE0F Database close failed");
18992
18982
  }
18993
18983
  }
18994
18984
  /**
@@ -19006,46 +18996,46 @@ Task: "${taskDescription}"`;
19006
18996
  };
19007
18997
  await this.hookRunner.runObservingHook("agent:stop", agentStopEvent);
19008
18998
  } catch (e) {
19009
- log137.error({ err: e }, "\u26A0\uFE0F agent:stop hook failed");
18999
+ log136.error({ err: e }, "\u26A0\uFE0F agent:stop hook failed");
19010
19000
  }
19011
19001
  }
19012
19002
  if (this.pluginWatcher) {
19013
19003
  try {
19014
19004
  await this.pluginWatcher.stop();
19015
19005
  } catch (e) {
19016
- log137.error({ err: e }, "\u26A0\uFE0F Plugin watcher stop failed");
19006
+ log136.error({ err: e }, "\u26A0\uFE0F Plugin watcher stop failed");
19017
19007
  }
19018
19008
  }
19019
19009
  if (this.mcpConnections.length > 0) {
19020
19010
  try {
19021
19011
  await closeMcpServers(this.mcpConnections);
19022
19012
  } catch (e) {
19023
- log137.error({ err: e }, "\u26A0\uFE0F MCP close failed");
19013
+ log136.error({ err: e }, "\u26A0\uFE0F MCP close failed");
19024
19014
  }
19025
19015
  }
19026
19016
  if (this.debouncer) {
19027
19017
  try {
19028
19018
  await this.debouncer.flushAll();
19029
19019
  } catch (e) {
19030
- log137.error({ err: e }, "\u26A0\uFE0F Debouncer flush failed");
19020
+ log136.error({ err: e }, "\u26A0\uFE0F Debouncer flush failed");
19031
19021
  }
19032
19022
  }
19033
19023
  try {
19034
19024
  await this.messageHandler.drain();
19035
19025
  } catch (e) {
19036
- log137.error({ err: e }, "\u26A0\uFE0F Message queue drain failed");
19026
+ log136.error({ err: e }, "\u26A0\uFE0F Message queue drain failed");
19037
19027
  }
19038
19028
  for (const mod of this.modules) {
19039
19029
  try {
19040
19030
  await mod.stop?.();
19041
19031
  } catch (e) {
19042
- log137.error({ err: e }, `\u26A0\uFE0F Module "${mod.name}" stop failed`);
19032
+ log136.error({ err: e }, `\u26A0\uFE0F Module "${mod.name}" stop failed`);
19043
19033
  }
19044
19034
  }
19045
19035
  try {
19046
19036
  await this.bridge.disconnect();
19047
19037
  } catch (e) {
19048
- log137.error({ err: e }, "\u26A0\uFE0F Bridge disconnect failed");
19038
+ log136.error({ err: e }, "\u26A0\uFE0F Bridge disconnect failed");
19049
19039
  }
19050
19040
  }
19051
19041
  };
@@ -19054,14 +19044,14 @@ async function main(configPath) {
19054
19044
  try {
19055
19045
  app = new TeletonApp(configPath);
19056
19046
  } catch (error) {
19057
- log137.error(`Failed to initialize: ${error instanceof Error ? error.message : error}`);
19047
+ log136.error(`Failed to initialize: ${error instanceof Error ? error.message : error}`);
19058
19048
  process.exit(1);
19059
19049
  }
19060
19050
  process.on("unhandledRejection", (reason) => {
19061
- log137.error({ err: reason }, "\u26A0\uFE0F Unhandled promise rejection");
19051
+ log136.error({ err: reason }, "\u26A0\uFE0F Unhandled promise rejection");
19062
19052
  });
19063
19053
  process.on("uncaughtException", (error) => {
19064
- log137.error({ err: error }, "\u{1F4A5} Uncaught exception");
19054
+ log136.error({ err: error }, "\u{1F4A5} Uncaught exception");
19065
19055
  process.exit(1);
19066
19056
  });
19067
19057
  let shutdownInProgress = false;
@@ -19069,7 +19059,7 @@ async function main(configPath) {
19069
19059
  if (shutdownInProgress) return;
19070
19060
  shutdownInProgress = true;
19071
19061
  const forceExit = setTimeout(() => {
19072
- log137.error("\u26A0\uFE0F Shutdown timed out, forcing exit");
19062
+ log136.error("\u26A0\uFE0F Shutdown timed out, forcing exit");
19073
19063
  process.exit(1);
19074
19064
  }, SHUTDOWN_TIMEOUT_MS);
19075
19065
  forceExit.unref();
@@ -19083,7 +19073,7 @@ async function main(configPath) {
19083
19073
  }
19084
19074
  if (import.meta.url === `file://${process.argv[1]}`) {
19085
19075
  main().catch((error) => {
19086
- log137.fatal({ err: error }, "Fatal error");
19076
+ log136.fatal({ err: error }, "Fatal error");
19087
19077
  process.exit(1);
19088
19078
  });
19089
19079
  }