teleton 0.1.19 → 0.1.20

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.
@@ -0,0 +1,184 @@
1
+ import {
2
+ TELETON_ROOT
3
+ } from "./chunk-EYWNOHMJ.js";
4
+
5
+ // src/session/transcript.ts
6
+ import {
7
+ appendFileSync,
8
+ readFileSync,
9
+ existsSync,
10
+ mkdirSync,
11
+ unlinkSync,
12
+ renameSync,
13
+ readdirSync,
14
+ statSync
15
+ } from "fs";
16
+ import { join } from "path";
17
+ var SESSIONS_DIR = join(TELETON_ROOT, "sessions");
18
+ function getTranscriptPath(sessionId) {
19
+ return join(SESSIONS_DIR, `${sessionId}.jsonl`);
20
+ }
21
+ function ensureSessionsDir() {
22
+ if (!existsSync(SESSIONS_DIR)) {
23
+ mkdirSync(SESSIONS_DIR, { recursive: true });
24
+ }
25
+ }
26
+ function appendToTranscript(sessionId, message) {
27
+ ensureSessionsDir();
28
+ const transcriptPath = getTranscriptPath(sessionId);
29
+ const line = JSON.stringify(message) + "\n";
30
+ try {
31
+ appendFileSync(transcriptPath, line, "utf-8");
32
+ } catch (error) {
33
+ console.error(`Failed to append to transcript ${sessionId}:`, error);
34
+ }
35
+ }
36
+ function extractToolCallIds(msg) {
37
+ const ids = /* @__PURE__ */ new Set();
38
+ if (msg.role === "assistant" && Array.isArray(msg.content)) {
39
+ for (const block of msg.content) {
40
+ const blockType = block.type;
41
+ if (blockType === "toolCall" || blockType === "tool_use") {
42
+ const id = block.id || block.toolCallId || block.tool_use_id;
43
+ if (id) ids.add(id);
44
+ }
45
+ }
46
+ }
47
+ return ids;
48
+ }
49
+ function sanitizeMessages(messages) {
50
+ const sanitized = [];
51
+ let pendingToolCallIds = /* @__PURE__ */ new Set();
52
+ let removedCount = 0;
53
+ for (let i = 0; i < messages.length; i++) {
54
+ const msg = messages[i];
55
+ if (msg.role === "assistant") {
56
+ const newToolIds = extractToolCallIds(msg);
57
+ if (pendingToolCallIds.size > 0 && newToolIds.size > 0) {
58
+ console.warn(
59
+ `\u26A0\uFE0F Found ${pendingToolCallIds.size} pending tool results that were never received`
60
+ );
61
+ }
62
+ pendingToolCallIds = newToolIds;
63
+ sanitized.push(msg);
64
+ } else if (msg.role === "toolResult" || msg.role === "tool_result") {
65
+ const toolCallId = msg.toolCallId || msg.tool_use_id || msg.tool_call_id;
66
+ if (toolCallId && pendingToolCallIds.has(toolCallId)) {
67
+ pendingToolCallIds.delete(toolCallId);
68
+ sanitized.push(msg);
69
+ } else {
70
+ removedCount++;
71
+ console.warn(
72
+ `\u{1F9F9} Removing out-of-order/orphaned toolResult: ${toolCallId?.slice(0, 20)}...`
73
+ );
74
+ continue;
75
+ }
76
+ } else if (msg.role === "user") {
77
+ if (pendingToolCallIds.size > 0) {
78
+ console.warn(
79
+ `\u26A0\uFE0F User message arrived while ${pendingToolCallIds.size} tool results pending - marking them as orphaned`
80
+ );
81
+ pendingToolCallIds.clear();
82
+ }
83
+ sanitized.push(msg);
84
+ } else {
85
+ sanitized.push(msg);
86
+ }
87
+ }
88
+ if (removedCount > 0) {
89
+ console.log(`\u{1F9F9} Sanitized ${removedCount} orphaned/out-of-order toolResult(s) from transcript`);
90
+ }
91
+ return sanitized;
92
+ }
93
+ function readTranscript(sessionId) {
94
+ const transcriptPath = getTranscriptPath(sessionId);
95
+ if (!existsSync(transcriptPath)) {
96
+ return [];
97
+ }
98
+ try {
99
+ const content = readFileSync(transcriptPath, "utf-8");
100
+ const lines = content.trim().split("\n").filter(Boolean);
101
+ const messages = lines.map((line) => JSON.parse(line));
102
+ return sanitizeMessages(messages);
103
+ } catch (error) {
104
+ console.error(`Failed to read transcript ${sessionId}:`, error);
105
+ return [];
106
+ }
107
+ }
108
+ function transcriptExists(sessionId) {
109
+ return existsSync(getTranscriptPath(sessionId));
110
+ }
111
+ function getTranscriptSize(sessionId) {
112
+ try {
113
+ const messages = readTranscript(sessionId);
114
+ return messages.length;
115
+ } catch {
116
+ return 0;
117
+ }
118
+ }
119
+ function deleteTranscript(sessionId) {
120
+ const transcriptPath = getTranscriptPath(sessionId);
121
+ if (!existsSync(transcriptPath)) {
122
+ return false;
123
+ }
124
+ try {
125
+ unlinkSync(transcriptPath);
126
+ console.log(`\u{1F5D1}\uFE0F Deleted transcript: ${sessionId}`);
127
+ return true;
128
+ } catch (error) {
129
+ console.error(`Failed to delete transcript ${sessionId}:`, error);
130
+ return false;
131
+ }
132
+ }
133
+ function archiveTranscript(sessionId) {
134
+ const transcriptPath = getTranscriptPath(sessionId);
135
+ const timestamp = Date.now();
136
+ const archivePath = `${transcriptPath}.${timestamp}.archived`;
137
+ if (!existsSync(transcriptPath)) {
138
+ return false;
139
+ }
140
+ try {
141
+ renameSync(transcriptPath, archivePath);
142
+ console.log(`\u{1F4E6} Archived transcript: ${sessionId} \u2192 ${timestamp}.archived`);
143
+ return true;
144
+ } catch (error) {
145
+ console.error(`Failed to archive transcript ${sessionId}:`, error);
146
+ return false;
147
+ }
148
+ }
149
+ function cleanupOldTranscripts(maxAgeDays = 30) {
150
+ if (!existsSync(SESSIONS_DIR)) return 0;
151
+ const cutoff = Date.now() - maxAgeDays * 24 * 60 * 60 * 1e3;
152
+ let deleted = 0;
153
+ try {
154
+ for (const file of readdirSync(SESSIONS_DIR)) {
155
+ if (!file.endsWith(".jsonl") && !file.endsWith(".archived")) continue;
156
+ const filePath = join(SESSIONS_DIR, file);
157
+ try {
158
+ const mtime = statSync(filePath).mtimeMs;
159
+ if (mtime < cutoff) {
160
+ unlinkSync(filePath);
161
+ deleted++;
162
+ }
163
+ } catch {
164
+ }
165
+ }
166
+ } catch (error) {
167
+ console.error("Failed to cleanup old transcripts:", error);
168
+ }
169
+ if (deleted > 0) {
170
+ console.log(`\u{1F9F9} Cleaned up ${deleted} transcript(s) older than ${maxAgeDays} days`);
171
+ }
172
+ return deleted;
173
+ }
174
+
175
+ export {
176
+ getTranscriptPath,
177
+ appendToTranscript,
178
+ readTranscript,
179
+ transcriptExists,
180
+ getTranscriptSize,
181
+ deleteTranscript,
182
+ archiveTranscript,
183
+ cleanupOldTranscripts
184
+ };
@@ -1,3 +1,19 @@
1
+ import {
2
+ Mi,
3
+ Mn,
4
+ br,
5
+ dt,
6
+ le,
7
+ qn,
8
+ ut,
9
+ ye
10
+ } from "./chunk-U7FQYCBQ.js";
11
+ import {
12
+ appendToTranscript,
13
+ archiveTranscript,
14
+ readTranscript,
15
+ transcriptExists
16
+ } from "./chunk-OQGNS2FV.js";
1
17
  import {
2
18
  ChatStore,
3
19
  ContextBuilder,
@@ -62,16 +78,6 @@ import {
62
78
  telegramGetMyGiftsExecutor,
63
79
  telegramGetMyGiftsTool
64
80
  } from "./chunk-B2PRMXOH.js";
65
- import {
66
- Mi,
67
- Mn,
68
- br,
69
- dt,
70
- le,
71
- qn,
72
- ut,
73
- ye
74
- } from "./chunk-U7FQYCBQ.js";
75
81
  import {
76
82
  __commonJS,
77
83
  __toESM
@@ -2044,122 +2050,6 @@ import {
2044
2050
  complete,
2045
2051
  getModel
2046
2052
  } from "@mariozechner/pi-ai";
2047
-
2048
- // src/session/transcript.ts
2049
- import { appendFileSync as appendFileSync2, readFileSync as readFileSync5, existsSync as existsSync6, mkdirSync as mkdirSync4, unlinkSync, renameSync } from "fs";
2050
- import { join as join4 } from "path";
2051
- var SESSIONS_DIR = join4(TELETON_ROOT, "sessions");
2052
- function getTranscriptPath(sessionId) {
2053
- return join4(SESSIONS_DIR, `${sessionId}.jsonl`);
2054
- }
2055
- function ensureSessionsDir() {
2056
- if (!existsSync6(SESSIONS_DIR)) {
2057
- mkdirSync4(SESSIONS_DIR, { recursive: true });
2058
- }
2059
- }
2060
- function appendToTranscript(sessionId, message) {
2061
- ensureSessionsDir();
2062
- const transcriptPath = getTranscriptPath(sessionId);
2063
- const line = JSON.stringify(message) + "\n";
2064
- try {
2065
- appendFileSync2(transcriptPath, line, "utf-8");
2066
- } catch (error) {
2067
- console.error(`Failed to append to transcript ${sessionId}:`, error);
2068
- }
2069
- }
2070
- function extractToolCallIds(msg) {
2071
- const ids = /* @__PURE__ */ new Set();
2072
- if (msg.role === "assistant" && Array.isArray(msg.content)) {
2073
- for (const block of msg.content) {
2074
- const blockType = block.type;
2075
- if (blockType === "toolCall" || blockType === "tool_use") {
2076
- const id = block.id || block.toolCallId || block.tool_use_id;
2077
- if (id) ids.add(id);
2078
- }
2079
- }
2080
- }
2081
- return ids;
2082
- }
2083
- function sanitizeMessages(messages) {
2084
- const sanitized = [];
2085
- let pendingToolCallIds = /* @__PURE__ */ new Set();
2086
- let removedCount = 0;
2087
- for (let i = 0; i < messages.length; i++) {
2088
- const msg = messages[i];
2089
- if (msg.role === "assistant") {
2090
- const newToolIds = extractToolCallIds(msg);
2091
- if (pendingToolCallIds.size > 0 && newToolIds.size > 0) {
2092
- console.warn(
2093
- `\u26A0\uFE0F Found ${pendingToolCallIds.size} pending tool results that were never received`
2094
- );
2095
- }
2096
- pendingToolCallIds = newToolIds;
2097
- sanitized.push(msg);
2098
- } else if (msg.role === "toolResult" || msg.role === "tool_result") {
2099
- const toolCallId = msg.toolCallId || msg.tool_use_id || msg.tool_call_id;
2100
- if (toolCallId && pendingToolCallIds.has(toolCallId)) {
2101
- pendingToolCallIds.delete(toolCallId);
2102
- sanitized.push(msg);
2103
- } else {
2104
- removedCount++;
2105
- console.warn(
2106
- `\u{1F9F9} Removing out-of-order/orphaned toolResult: ${toolCallId?.slice(0, 20)}...`
2107
- );
2108
- continue;
2109
- }
2110
- } else if (msg.role === "user") {
2111
- if (pendingToolCallIds.size > 0) {
2112
- console.warn(
2113
- `\u26A0\uFE0F User message arrived while ${pendingToolCallIds.size} tool results pending - marking them as orphaned`
2114
- );
2115
- pendingToolCallIds.clear();
2116
- }
2117
- sanitized.push(msg);
2118
- } else {
2119
- sanitized.push(msg);
2120
- }
2121
- }
2122
- if (removedCount > 0) {
2123
- console.log(`\u{1F9F9} Sanitized ${removedCount} orphaned/out-of-order toolResult(s) from transcript`);
2124
- }
2125
- return sanitized;
2126
- }
2127
- function readTranscript(sessionId) {
2128
- const transcriptPath = getTranscriptPath(sessionId);
2129
- if (!existsSync6(transcriptPath)) {
2130
- return [];
2131
- }
2132
- try {
2133
- const content = readFileSync5(transcriptPath, "utf-8");
2134
- const lines = content.trim().split("\n").filter(Boolean);
2135
- const messages = lines.map((line) => JSON.parse(line));
2136
- return sanitizeMessages(messages);
2137
- } catch (error) {
2138
- console.error(`Failed to read transcript ${sessionId}:`, error);
2139
- return [];
2140
- }
2141
- }
2142
- function transcriptExists(sessionId) {
2143
- return existsSync6(getTranscriptPath(sessionId));
2144
- }
2145
- function archiveTranscript(sessionId) {
2146
- const transcriptPath = getTranscriptPath(sessionId);
2147
- const timestamp = Date.now();
2148
- const archivePath = `${transcriptPath}.${timestamp}.archived`;
2149
- if (!existsSync6(transcriptPath)) {
2150
- return false;
2151
- }
2152
- try {
2153
- renameSync(transcriptPath, archivePath);
2154
- console.log(`\u{1F4E6} Archived transcript: ${sessionId} \u2192 ${timestamp}.archived`);
2155
- return true;
2156
- } catch (error) {
2157
- console.error(`Failed to archive transcript ${sessionId}:`, error);
2158
- return false;
2159
- }
2160
- }
2161
-
2162
- // src/agent/client.ts
2163
2053
  var modelCache = /* @__PURE__ */ new Map();
2164
2054
  function getProviderModel(provider, modelId) {
2165
2055
  const cacheKey = `${provider}:${modelId}`;
@@ -2789,7 +2679,7 @@ ${oversizedNotes.join("\n")}` : "";
2789
2679
 
2790
2680
  // src/session/memory-hook.ts
2791
2681
  import { writeFile, mkdir } from "fs/promises";
2792
- import { join as join5 } from "path";
2682
+ import { join as join4 } from "path";
2793
2683
  import { complete as complete3 } from "@mariozechner/pi-ai";
2794
2684
  async function generateSlugViaClaude(params) {
2795
2685
  const provider = params.provider || "anthropic";
@@ -2830,7 +2720,7 @@ Slug:`,
2830
2720
  async function saveSessionMemory(params) {
2831
2721
  try {
2832
2722
  const { TELETON_ROOT: TELETON_ROOT2 } = await import("./paths-TMNTEDDD.js");
2833
- const memoryDir = join5(TELETON_ROOT2, "memory");
2723
+ const memoryDir = join4(TELETON_ROOT2, "memory");
2834
2724
  await mkdir(memoryDir, { recursive: true });
2835
2725
  const now = /* @__PURE__ */ new Date();
2836
2726
  const dateStr = now.toISOString().split("T")[0];
@@ -2842,7 +2732,7 @@ async function saveSessionMemory(params) {
2842
2732
  utilityModel: params.utilityModel
2843
2733
  });
2844
2734
  const filename = `${dateStr}-${slug}.md`;
2845
- const filepath = join5(memoryDir, filename);
2735
+ const filepath = join4(memoryDir, filename);
2846
2736
  const timeStr = now.toISOString().split("T")[1].split(".")[0];
2847
2737
  console.log("\u{1F4DD} Generating session summary...");
2848
2738
  let summary;
@@ -3722,8 +3612,8 @@ import { TelegramClient, Api } from "telegram";
3722
3612
  import { Logger, LogLevel } from "telegram/extensions/Logger.js";
3723
3613
  import { StringSession } from "telegram/sessions/index.js";
3724
3614
  import { NewMessage } from "telegram/events/index.js";
3725
- import { existsSync as existsSync7, readFileSync as readFileSync6, writeFileSync as writeFileSync3, mkdirSync as mkdirSync5, chmodSync } from "fs";
3726
- import { dirname as dirname4 } from "path";
3615
+ import { existsSync as existsSync6, readFileSync as readFileSync5, writeFileSync as writeFileSync3, mkdirSync as mkdirSync4, chmodSync } from "fs";
3616
+ import { dirname as dirname3 } from "path";
3727
3617
  import { createInterface } from "readline";
3728
3618
 
3729
3619
  // src/telegram/formatting.ts
@@ -3821,8 +3711,8 @@ var TelegramUserClient = class {
3821
3711
  */
3822
3712
  loadSession() {
3823
3713
  try {
3824
- if (existsSync7(this.config.sessionPath)) {
3825
- return readFileSync6(this.config.sessionPath, "utf-8").trim();
3714
+ if (existsSync6(this.config.sessionPath)) {
3715
+ return readFileSync5(this.config.sessionPath, "utf-8").trim();
3826
3716
  }
3827
3717
  } catch (error) {
3828
3718
  console.warn("Failed to load session:", error);
@@ -3839,9 +3729,9 @@ var TelegramUserClient = class {
3839
3729
  console.warn("No session string to save");
3840
3730
  return;
3841
3731
  }
3842
- const dir = dirname4(this.config.sessionPath);
3843
- if (!existsSync7(dir)) {
3844
- mkdirSync5(dir, { recursive: true });
3732
+ const dir = dirname3(this.config.sessionPath);
3733
+ if (!existsSync6(dir)) {
3734
+ mkdirSync4(dir, { recursive: true });
3845
3735
  }
3846
3736
  writeFileSync3(this.config.sessionPath, sessionString, { encoding: "utf-8" });
3847
3737
  chmodSync(this.config.sessionPath, 384);
@@ -3859,7 +3749,7 @@ var TelegramUserClient = class {
3859
3749
  return;
3860
3750
  }
3861
3751
  try {
3862
- const hasSession = existsSync7(this.config.sessionPath);
3752
+ const hasSession = existsSync6(this.config.sessionPath);
3863
3753
  if (hasSession) {
3864
3754
  await this.client.connect();
3865
3755
  } else {
@@ -4352,20 +4242,20 @@ var TelegramBridge = class {
4352
4242
  };
4353
4243
 
4354
4244
  // src/telegram/offset-store.ts
4355
- import { readFileSync as readFileSync7, writeFileSync as writeFileSync4, existsSync as existsSync8, mkdirSync as mkdirSync6 } from "fs";
4356
- import { dirname as dirname5 } from "path";
4357
- import { join as join6 } from "path";
4358
- var OFFSET_FILE = join6(TELETON_ROOT, "telegram-offset.json");
4245
+ import { readFileSync as readFileSync6, writeFileSync as writeFileSync4, existsSync as existsSync7, mkdirSync as mkdirSync5 } from "fs";
4246
+ import { dirname as dirname4 } from "path";
4247
+ import { join as join5 } from "path";
4248
+ var OFFSET_FILE = join5(TELETON_ROOT, "telegram-offset.json");
4359
4249
  var STORE_VERSION = 2;
4360
4250
  var offsetCache = null;
4361
4251
  function loadState() {
4362
4252
  if (offsetCache) return offsetCache;
4363
4253
  try {
4364
- if (!existsSync8(OFFSET_FILE)) {
4254
+ if (!existsSync7(OFFSET_FILE)) {
4365
4255
  offsetCache = { version: STORE_VERSION, perChat: {} };
4366
4256
  return offsetCache;
4367
4257
  }
4368
- const raw = readFileSync7(OFFSET_FILE, "utf-8");
4258
+ const raw = readFileSync6(OFFSET_FILE, "utf-8");
4369
4259
  const state = JSON.parse(raw);
4370
4260
  if (state.version === 1 || !state.perChat) {
4371
4261
  offsetCache = { version: STORE_VERSION, perChat: {} };
@@ -4381,9 +4271,9 @@ function loadState() {
4381
4271
  }
4382
4272
  function saveState(state) {
4383
4273
  try {
4384
- const dir = dirname5(OFFSET_FILE);
4385
- if (!existsSync8(dir)) {
4386
- mkdirSync6(dir, { recursive: true });
4274
+ const dir = dirname4(OFFSET_FILE);
4275
+ if (!existsSync7(dir)) {
4276
+ mkdirSync5(dir, { recursive: true });
4387
4277
  }
4388
4278
  writeFileSync4(OFFSET_FILE, JSON.stringify(state, null, 2), "utf-8");
4389
4279
  offsetCache = state;
@@ -4838,10 +4728,10 @@ var MessageHandler = class {
4838
4728
  // src/ton/wallet-service.ts
4839
4729
  import { mnemonicNew, mnemonicToPrivateKey, mnemonicValidate } from "@ton/crypto";
4840
4730
  import { WalletContractV5R1, TonClient, fromNano } from "@ton/ton";
4841
- import { readFileSync as readFileSync8, writeFileSync as writeFileSync5, existsSync as existsSync9, mkdirSync as mkdirSync7, chmodSync as chmodSync2 } from "fs";
4842
- import { join as join7, dirname as dirname6 } from "path";
4731
+ import { readFileSync as readFileSync7, writeFileSync as writeFileSync5, existsSync as existsSync8, mkdirSync as mkdirSync6, chmodSync as chmodSync2 } from "fs";
4732
+ import { join as join6, dirname as dirname5 } from "path";
4843
4733
  import { getHttpEndpoint } from "@orbs-network/ton-access";
4844
- var WALLET_FILE = join7(TELETON_ROOT, "wallet.json");
4734
+ var WALLET_FILE = join6(TELETON_ROOT, "wallet.json");
4845
4735
  async function generateWallet() {
4846
4736
  const mnemonic = await mnemonicNew(24);
4847
4737
  const keyPair = await mnemonicToPrivateKey(mnemonic);
@@ -4859,19 +4749,19 @@ async function generateWallet() {
4859
4749
  };
4860
4750
  }
4861
4751
  function saveWallet(wallet) {
4862
- const dir = dirname6(WALLET_FILE);
4863
- if (!existsSync9(dir)) {
4864
- mkdirSync7(dir, { recursive: true });
4752
+ const dir = dirname5(WALLET_FILE);
4753
+ if (!existsSync8(dir)) {
4754
+ mkdirSync6(dir, { recursive: true });
4865
4755
  }
4866
4756
  writeFileSync5(WALLET_FILE, JSON.stringify(wallet, null, 2), "utf-8");
4867
4757
  chmodSync2(WALLET_FILE, 384);
4868
4758
  }
4869
4759
  function loadWallet() {
4870
- if (!existsSync9(WALLET_FILE)) {
4760
+ if (!existsSync8(WALLET_FILE)) {
4871
4761
  return null;
4872
4762
  }
4873
4763
  try {
4874
- const content = readFileSync8(WALLET_FILE, "utf-8");
4764
+ const content = readFileSync7(WALLET_FILE, "utf-8");
4875
4765
  return JSON.parse(content);
4876
4766
  } catch (error) {
4877
4767
  console.error("Failed to load wallet:", error);
@@ -4879,7 +4769,7 @@ function loadWallet() {
4879
4769
  }
4880
4770
  }
4881
4771
  function walletExists() {
4882
- return existsSync9(WALLET_FILE);
4772
+ return existsSync8(WALLET_FILE);
4883
4773
  }
4884
4774
  async function importWallet(mnemonic) {
4885
4775
  const valid = await mnemonicValidate(mnemonic);
@@ -4921,14 +4811,20 @@ async function getWalletBalance(address4) {
4921
4811
  return null;
4922
4812
  }
4923
4813
  }
4814
+ var TON_PRICE_CACHE_TTL_MS = 3e4;
4815
+ var _tonPriceCache = null;
4924
4816
  async function getTonPrice() {
4817
+ if (_tonPriceCache && Date.now() - _tonPriceCache.timestamp < TON_PRICE_CACHE_TTL_MS) {
4818
+ return { ..._tonPriceCache };
4819
+ }
4925
4820
  try {
4926
4821
  const response = await tonapiFetch(`/rates?tokens=ton&currencies=usd`);
4927
4822
  if (response.ok) {
4928
4823
  const data = await response.json();
4929
4824
  const price = data?.rates?.TON?.prices?.USD;
4930
4825
  if (typeof price === "number" && price > 0) {
4931
- return { usd: price, source: "TonAPI", timestamp: Date.now() };
4826
+ _tonPriceCache = { usd: price, source: "TonAPI", timestamp: Date.now() };
4827
+ return _tonPriceCache;
4932
4828
  }
4933
4829
  }
4934
4830
  } catch {
@@ -4943,7 +4839,8 @@ async function getTonPrice() {
4943
4839
  const data = await response.json();
4944
4840
  const price = data["the-open-network"]?.usd;
4945
4841
  if (typeof price === "number" && price > 0) {
4946
- return { usd: price, source: "CoinGecko", timestamp: Date.now() };
4842
+ _tonPriceCache = { usd: price, source: "CoinGecko", timestamp: Date.now() };
4843
+ return _tonPriceCache;
4947
4844
  }
4948
4845
  } catch (error) {
4949
4846
  console.error("Failed to get TON price:", error);
@@ -5445,8 +5342,8 @@ var MessageDebouncer = class {
5445
5342
 
5446
5343
  // src/market/db.ts
5447
5344
  import Database from "better-sqlite3";
5448
- import { join as join8 } from "path";
5449
- var DB_PATH = join8(TELETON_ROOT, "gifts.db");
5345
+ import { join as join7 } from "path";
5346
+ var DB_PATH = join7(TELETON_ROOT, "gifts.db");
5450
5347
  function getDb2() {
5451
5348
  const db = new Database(DB_PATH);
5452
5349
  db.pragma("journal_mode = WAL");
@@ -5765,7 +5662,7 @@ var MarketPriceService = class {
5765
5662
  };
5766
5663
 
5767
5664
  // src/index.ts
5768
- import { join as join15 } from "path";
5665
+ import { join as join14 } from "path";
5769
5666
 
5770
5667
  // src/agent/tools/registry.ts
5771
5668
  import { validateToolCall } from "@mariozechner/pi-ai";
@@ -6554,16 +6451,16 @@ var telegramSendPhotoExecutor = async (params, context) => {
6554
6451
  // src/agent/tools/telegram/media/send-voice.ts
6555
6452
  import { Type as Type11 } from "@sinclair/typebox";
6556
6453
  import { Api as Api10 } from "telegram";
6557
- import { unlinkSync as unlinkSync3 } from "fs";
6454
+ import { unlinkSync as unlinkSync2 } from "fs";
6558
6455
 
6559
6456
  // src/services/tts.ts
6560
6457
  import { spawn } from "child_process";
6561
- import { writeFileSync as writeFileSync6, mkdirSync as mkdirSync8, existsSync as existsSync10, unlinkSync as unlinkSync2 } from "fs";
6562
- import { join as join9 } from "path";
6458
+ import { writeFileSync as writeFileSync6, mkdirSync as mkdirSync7, existsSync as existsSync9, unlinkSync } from "fs";
6459
+ import { join as join8 } from "path";
6563
6460
  import { tmpdir } from "os";
6564
6461
  import { randomUUID as randomUUID3 } from "crypto";
6565
- var PIPER_VOICES_DIR = join9(TELETON_ROOT, "piper-voices");
6566
- var PIPER_VENV = join9(TELETON_ROOT, "rvc-env");
6462
+ var PIPER_VOICES_DIR = join8(TELETON_ROOT, "piper-voices");
6463
+ var PIPER_VENV = join8(TELETON_ROOT, "rvc-env");
6567
6464
  var PIPER_VOICES = {
6568
6465
  trump: "en_US-trump-high.onnx",
6569
6466
  // Trump voice (default) ⭐
@@ -6657,21 +6554,21 @@ async function generateSpeech(options) {
6657
6554
  }
6658
6555
  }
6659
6556
  async function generatePiperTTS(text, voice) {
6660
- const tempDir = join9(tmpdir(), "tonnet-tts");
6661
- if (!existsSync10(tempDir)) {
6662
- mkdirSync8(tempDir, { recursive: true });
6557
+ const tempDir = join8(tmpdir(), "tonnet-tts");
6558
+ if (!existsSync9(tempDir)) {
6559
+ mkdirSync7(tempDir, { recursive: true });
6663
6560
  }
6664
6561
  const id = randomUUID3();
6665
- const wavPath = join9(tempDir, `${id}.wav`);
6666
- const oggPath = join9(tempDir, `${id}.ogg`);
6562
+ const wavPath = join8(tempDir, `${id}.wav`);
6563
+ const oggPath = join8(tempDir, `${id}.ogg`);
6667
6564
  const modelFile = PIPER_VOICES[voice.toLowerCase()] ?? voice;
6668
- const modelPath = modelFile.includes("/") ? modelFile : join9(PIPER_VOICES_DIR, modelFile);
6669
- if (!existsSync10(modelPath)) {
6565
+ const modelPath = modelFile.includes("/") ? modelFile : join8(PIPER_VOICES_DIR, modelFile);
6566
+ if (!existsSync9(modelPath)) {
6670
6567
  throw new Error(
6671
6568
  `Piper voice not found: ${modelPath}. Available: ${Object.keys(PIPER_VOICES).join(", ")}`
6672
6569
  );
6673
6570
  }
6674
- const piperBin = join9(PIPER_VENV, "bin", "piper");
6571
+ const piperBin = join8(PIPER_VENV, "bin", "piper");
6675
6572
  await new Promise((resolve2, reject) => {
6676
6573
  const proc = spawn(
6677
6574
  piperBin,
@@ -6695,7 +6592,7 @@ async function generatePiperTTS(text, voice) {
6695
6592
  stderr += data.toString();
6696
6593
  });
6697
6594
  proc.on("close", (code) => {
6698
- if (code === 0 && existsSync10(wavPath)) {
6595
+ if (code === 0 && existsSync9(wavPath)) {
6699
6596
  resolve2();
6700
6597
  } else {
6701
6598
  reject(new Error(`Piper TTS failed (code ${code}): ${stderr}`));
@@ -6734,7 +6631,7 @@ async function generatePiperTTS(text, voice) {
6734
6631
  reject(new Error(`ffmpeg spawn error: ${err.message}`));
6735
6632
  });
6736
6633
  });
6737
- unlinkSync2(wavPath);
6634
+ unlinkSync(wavPath);
6738
6635
  } catch (err) {
6739
6636
  return {
6740
6637
  filePath: wavPath,
@@ -6749,11 +6646,11 @@ async function generatePiperTTS(text, voice) {
6749
6646
  };
6750
6647
  }
6751
6648
  async function generateEdgeTTS(text, voice, rate, pitch) {
6752
- const tempDir = join9(tmpdir(), "tonnet-tts");
6753
- if (!existsSync10(tempDir)) {
6754
- mkdirSync8(tempDir, { recursive: true });
6649
+ const tempDir = join8(tmpdir(), "tonnet-tts");
6650
+ if (!existsSync9(tempDir)) {
6651
+ mkdirSync7(tempDir, { recursive: true });
6755
6652
  }
6756
- const outputPath = join9(tempDir, `${randomUUID3()}.mp3`);
6653
+ const outputPath = join8(tempDir, `${randomUUID3()}.mp3`);
6757
6654
  const args = ["--text", text, "--voice", voice, "--write-media", outputPath];
6758
6655
  if (rate) {
6759
6656
  args.push("--rate", rate);
@@ -6790,11 +6687,11 @@ async function generateOpenAITTS(text, voice) {
6790
6687
  if (!apiKey) {
6791
6688
  throw new Error("OPENAI_API_KEY not set. Use Edge TTS (free) or set API key.");
6792
6689
  }
6793
- const tempDir = join9(tmpdir(), "tonnet-tts");
6794
- if (!existsSync10(tempDir)) {
6795
- mkdirSync8(tempDir, { recursive: true });
6690
+ const tempDir = join8(tmpdir(), "tonnet-tts");
6691
+ if (!existsSync9(tempDir)) {
6692
+ mkdirSync7(tempDir, { recursive: true });
6796
6693
  }
6797
- const outputPath = join9(tempDir, `${randomUUID3()}.mp3`);
6694
+ const outputPath = join8(tempDir, `${randomUUID3()}.mp3`);
6798
6695
  const response = await fetchWithTimeout(OPENAI_TTS_URL, {
6799
6696
  method: "POST",
6800
6697
  headers: {
@@ -6827,11 +6724,11 @@ async function generateElevenLabsTTS(text, voiceId) {
6827
6724
  if (!apiKey) {
6828
6725
  throw new Error("ELEVENLABS_API_KEY not set. Use Edge TTS (free) or set API key.");
6829
6726
  }
6830
- const tempDir = join9(tmpdir(), "tonnet-tts");
6831
- if (!existsSync10(tempDir)) {
6832
- mkdirSync8(tempDir, { recursive: true });
6727
+ const tempDir = join8(tmpdir(), "tonnet-tts");
6728
+ if (!existsSync9(tempDir)) {
6729
+ mkdirSync7(tempDir, { recursive: true });
6833
6730
  }
6834
- const outputPath = join9(tempDir, `${randomUUID3()}.mp3`);
6731
+ const outputPath = join8(tempDir, `${randomUUID3()}.mp3`);
6835
6732
  const response = await fetchWithTimeout(`${ELEVENLABS_TTS_URL}/${voiceId}`, {
6836
6733
  method: "POST",
6837
6734
  headers: {
@@ -7043,7 +6940,7 @@ var telegramSendVoiceExecutor = async (params, context) => {
7043
6940
  } finally {
7044
6941
  if (generatedFile) {
7045
6942
  try {
7046
- unlinkSync3(generatedFile);
6943
+ unlinkSync2(generatedFile);
7047
6944
  } catch (e) {
7048
6945
  }
7049
6946
  }
@@ -7423,7 +7320,7 @@ import { Type as Type15 } from "@sinclair/typebox";
7423
7320
  import {
7424
7321
  completeSimple
7425
7322
  } from "@mariozechner/pi-ai";
7426
- import { readFileSync as readFileSync9, existsSync as existsSync11 } from "fs";
7323
+ import { readFileSync as readFileSync8, existsSync as existsSync10 } from "fs";
7427
7324
  import { extname as extname3 } from "path";
7428
7325
  var visionAnalyzeTool = {
7429
7326
  name: "vision_analyze",
@@ -7495,7 +7392,7 @@ var visionAnalyzeExecutor = async (params, context) => {
7495
7392
  }
7496
7393
  throw error;
7497
7394
  }
7498
- if (!existsSync11(validatedPath.absolutePath)) {
7395
+ if (!existsSync10(validatedPath.absolutePath)) {
7499
7396
  return {
7500
7397
  success: false,
7501
7398
  error: `File not found: ${filePath}`
@@ -7509,7 +7406,7 @@ var visionAnalyzeExecutor = async (params, context) => {
7509
7406
  error: `Unsupported file type: ${ext}. Vision supports: .jpg, .jpeg, .png, .gif, .webp`
7510
7407
  };
7511
7408
  }
7512
- data = readFileSync9(validatedPath.absolutePath);
7409
+ data = readFileSync8(validatedPath.absolutePath);
7513
7410
  source = `file:${filePath}`;
7514
7411
  } else {
7515
7412
  console.log(`\u{1F4F7} Downloading image from message ${messageId}...`);
@@ -8752,7 +8649,7 @@ var telegramCreateGroupExecutor = async (params, context) => {
8752
8649
  // src/agent/tools/telegram/groups/set-chat-photo.ts
8753
8650
  import { Type as Type29 } from "@sinclair/typebox";
8754
8651
  import { Api as Api22 } from "telegram";
8755
- import { readFileSync as readFileSync10 } from "fs";
8652
+ import { readFileSync as readFileSync9 } from "fs";
8756
8653
  var telegramSetChatPhotoTool = {
8757
8654
  name: "telegram_set_chat_photo",
8758
8655
  description: `Set or delete a group/channel profile photo. You need admin rights with change info permission. Provide a local image path to set, or use delete_photo to remove.`,
@@ -8821,7 +8718,7 @@ var telegramSetChatPhotoExecutor = async (params, context) => {
8821
8718
  }
8822
8719
  throw error;
8823
8720
  }
8824
- const fileBuffer = readFileSync10(validatedPath.absolutePath);
8721
+ const fileBuffer = readFileSync9(validatedPath.absolutePath);
8825
8722
  const file = await client.uploadFile({
8826
8723
  file: new CustomFile(
8827
8724
  validatedPath.filename,
@@ -11001,7 +10898,7 @@ var import_big_integer4 = __toESM(require_BigInteger(), 1);
11001
10898
  import { Type as Type59 } from "@sinclair/typebox";
11002
10899
  import { Api as Api51 } from "telegram";
11003
10900
  import { CustomFile as CustomFile2 } from "telegram/client/uploads.js";
11004
- import { readFileSync as readFileSync11, statSync } from "fs";
10901
+ import { readFileSync as readFileSync10, statSync } from "fs";
11005
10902
  import { basename as basename2 } from "path";
11006
10903
  var telegramSendStoryTool = {
11007
10904
  name: "telegram_send_story",
@@ -11050,7 +10947,7 @@ var telegramSendStoryExecutor = async (params, context) => {
11050
10947
  const filePath = validatedPath.absolutePath;
11051
10948
  const fileName = basename2(filePath);
11052
10949
  const fileSize = statSync(filePath).size;
11053
- const fileBuffer = readFileSync11(filePath);
10950
+ const fileBuffer = readFileSync10(filePath);
11054
10951
  const isVideo = filePath.toLowerCase().match(/\.(mp4|mov|avi)$/);
11055
10952
  const customFile = new CustomFile2(fileName, fileSize, filePath, fileBuffer);
11056
10953
  const uploadedFile = await gramJsClient.uploadFile({
@@ -11119,8 +11016,8 @@ var telegramSendStoryExecutor = async (params, context) => {
11119
11016
 
11120
11017
  // src/agent/tools/telegram/memory/memory-write.ts
11121
11018
  import { Type as Type60 } from "@sinclair/typebox";
11122
- import { appendFileSync as appendFileSync3, writeFileSync as writeFileSync8, existsSync as existsSync12, mkdirSync as mkdirSync9 } from "fs";
11123
- import { join as join10 } from "path";
11019
+ import { appendFileSync as appendFileSync2, writeFileSync as writeFileSync8, existsSync as existsSync11, mkdirSync as mkdirSync8 } from "fs";
11020
+ import { join as join9 } from "path";
11124
11021
  var MEMORY_DIR2 = WORKSPACE_PATHS.MEMORY_DIR;
11125
11022
  var MEMORY_FILE = WORKSPACE_PATHS.MEMORY;
11126
11023
  var memoryWriteTool = {
@@ -11142,8 +11039,8 @@ var memoryWriteTool = {
11142
11039
  })
11143
11040
  };
11144
11041
  function ensureMemoryDir2() {
11145
- if (!existsSync12(MEMORY_DIR2)) {
11146
- mkdirSync9(MEMORY_DIR2, { recursive: true });
11042
+ if (!existsSync11(MEMORY_DIR2)) {
11043
+ mkdirSync8(MEMORY_DIR2, { recursive: true });
11147
11044
  }
11148
11045
  }
11149
11046
  function formatDate2(date) {
@@ -11153,7 +11050,7 @@ function formatDate2(date) {
11153
11050
  return `${year}-${month}-${day}`;
11154
11051
  }
11155
11052
  function getDailyLogPath2() {
11156
- return join10(MEMORY_DIR2, `${formatDate2(/* @__PURE__ */ new Date())}.md`);
11053
+ return join9(MEMORY_DIR2, `${formatDate2(/* @__PURE__ */ new Date())}.md`);
11157
11054
  }
11158
11055
  var memoryWriteExecutor = async (params, context) => {
11159
11056
  try {
@@ -11185,10 +11082,10 @@ var memoryWriteExecutor = async (params, context) => {
11185
11082
  entry += `
11186
11083
  _Added: ${now.toISOString()}_
11187
11084
  `;
11188
- if (!existsSync12(MEMORY_FILE)) {
11085
+ if (!existsSync11(MEMORY_FILE)) {
11189
11086
  writeFileSync8(MEMORY_FILE, "# MEMORY.md - Persistent Memory\n\n", "utf-8");
11190
11087
  }
11191
- appendFileSync3(MEMORY_FILE, entry, "utf-8");
11088
+ appendFileSync2(MEMORY_FILE, entry, "utf-8");
11192
11089
  console.log(`\u{1F4DD} Memory written to MEMORY.md${section ? ` (section: ${section})` : ""}`);
11193
11090
  return {
11194
11091
  success: true,
@@ -11201,7 +11098,7 @@ _Added: ${now.toISOString()}_
11201
11098
  };
11202
11099
  } else {
11203
11100
  const logPath = getDailyLogPath2();
11204
- if (!existsSync12(logPath)) {
11101
+ if (!existsSync11(logPath)) {
11205
11102
  const header = `# Daily Log - ${formatDate2(now)}
11206
11103
 
11207
11104
  `;
@@ -11218,7 +11115,7 @@ ${content}
11218
11115
  ---
11219
11116
 
11220
11117
  `;
11221
- appendFileSync3(logPath, entry, "utf-8");
11118
+ appendFileSync2(logPath, entry, "utf-8");
11222
11119
  console.log(`\u{1F4C5} Memory written to daily log${section ? ` (${section})` : ""}`);
11223
11120
  return {
11224
11121
  success: true,
@@ -11241,8 +11138,8 @@ ${content}
11241
11138
 
11242
11139
  // src/agent/tools/telegram/memory/memory-read.ts
11243
11140
  import { Type as Type61 } from "@sinclair/typebox";
11244
- import { readFileSync as readFileSync13, existsSync as existsSync13, readdirSync as readdirSync2 } from "fs";
11245
- import { join as join11 } from "path";
11141
+ import { readFileSync as readFileSync12, existsSync as existsSync12, readdirSync as readdirSync2 } from "fs";
11142
+ import { join as join10 } from "path";
11246
11143
  var MEMORY_DIR3 = WORKSPACE_PATHS.MEMORY_DIR;
11247
11144
  var MEMORY_FILE2 = WORKSPACE_PATHS.MEMORY;
11248
11145
  var memoryReadTool = {
@@ -11271,10 +11168,10 @@ var memoryReadExecutor = async (params, _context) => {
11271
11168
  const { target, date } = params;
11272
11169
  if (target === "list") {
11273
11170
  const files = [];
11274
- if (existsSync13(MEMORY_FILE2)) {
11171
+ if (existsSync12(MEMORY_FILE2)) {
11275
11172
  files.push("MEMORY.md (persistent)");
11276
11173
  }
11277
- if (existsSync13(MEMORY_DIR3)) {
11174
+ if (existsSync12(MEMORY_DIR3)) {
11278
11175
  const dailyLogs = readdirSync2(MEMORY_DIR3).filter((f) => f.endsWith(".md")).sort().reverse();
11279
11176
  files.push(...dailyLogs.map((f) => `memory/${f}`));
11280
11177
  }
@@ -11287,7 +11184,7 @@ var memoryReadExecutor = async (params, _context) => {
11287
11184
  };
11288
11185
  }
11289
11186
  if (target === "persistent") {
11290
- if (!existsSync13(MEMORY_FILE2)) {
11187
+ if (!existsSync12(MEMORY_FILE2)) {
11291
11188
  return {
11292
11189
  success: true,
11293
11190
  data: {
@@ -11296,7 +11193,7 @@ var memoryReadExecutor = async (params, _context) => {
11296
11193
  }
11297
11194
  };
11298
11195
  }
11299
- const content = readFileSync13(MEMORY_FILE2, "utf-8");
11196
+ const content = readFileSync12(MEMORY_FILE2, "utf-8");
11300
11197
  return {
11301
11198
  success: true,
11302
11199
  data: {
@@ -11309,8 +11206,8 @@ var memoryReadExecutor = async (params, _context) => {
11309
11206
  }
11310
11207
  if (target === "daily") {
11311
11208
  const targetDate = date || formatDate3(/* @__PURE__ */ new Date());
11312
- const logPath = join11(MEMORY_DIR3, `${targetDate}.md`);
11313
- if (!existsSync13(logPath)) {
11209
+ const logPath = join10(MEMORY_DIR3, `${targetDate}.md`);
11210
+ if (!existsSync12(logPath)) {
11314
11211
  return {
11315
11212
  success: true,
11316
11213
  data: {
@@ -11320,7 +11217,7 @@ var memoryReadExecutor = async (params, _context) => {
11320
11217
  }
11321
11218
  };
11322
11219
  }
11323
- const content = readFileSync13(logPath, "utf-8");
11220
+ const content = readFileSync12(logPath, "utf-8");
11324
11221
  return {
11325
11222
  success: true,
11326
11223
  data: {
@@ -11339,15 +11236,15 @@ var memoryReadExecutor = async (params, _context) => {
11339
11236
  const todayStr = formatDate3(today);
11340
11237
  const yesterdayStr = formatDate3(yesterday);
11341
11238
  const result = {};
11342
- const yesterdayPath = join11(MEMORY_DIR3, `${yesterdayStr}.md`);
11343
- if (existsSync13(yesterdayPath)) {
11344
- result[yesterdayStr] = readFileSync13(yesterdayPath, "utf-8");
11239
+ const yesterdayPath = join10(MEMORY_DIR3, `${yesterdayStr}.md`);
11240
+ if (existsSync12(yesterdayPath)) {
11241
+ result[yesterdayStr] = readFileSync12(yesterdayPath, "utf-8");
11345
11242
  } else {
11346
11243
  result[yesterdayStr] = null;
11347
11244
  }
11348
- const todayPath = join11(MEMORY_DIR3, `${todayStr}.md`);
11349
- if (existsSync13(todayPath)) {
11350
- result[todayStr] = readFileSync13(todayPath, "utf-8");
11245
+ const todayPath = join10(MEMORY_DIR3, `${todayStr}.md`);
11246
+ if (existsSync12(todayPath)) {
11247
+ result[todayStr] = readFileSync12(todayPath, "utf-8");
11351
11248
  } else {
11352
11249
  result[todayStr] = null;
11353
11250
  }
@@ -19327,7 +19224,7 @@ var journalUpdateExecutor = async (params) => {
19327
19224
  // src/agent/tools/workspace/list.ts
19328
19225
  import { Type as Type99 } from "@sinclair/typebox";
19329
19226
  import { readdirSync as readdirSync3, lstatSync as lstatSync2 } from "fs";
19330
- import { join as join12 } from "path";
19227
+ import { join as join11 } from "path";
19331
19228
  var workspaceListTool = {
19332
19229
  name: "workspace_list",
19333
19230
  description: `List files and directories in your workspace.
@@ -19364,7 +19261,7 @@ function listDir(dirPath, recursive, filter) {
19364
19261
  try {
19365
19262
  const entries = readdirSync3(dirPath);
19366
19263
  for (const entry of entries) {
19367
- const fullPath = join12(dirPath, entry);
19264
+ const fullPath = join11(dirPath, entry);
19368
19265
  const stats = lstatSync2(fullPath);
19369
19266
  const isDir = stats.isDirectory();
19370
19267
  if (filter === "files" && isDir) continue;
@@ -19425,7 +19322,7 @@ var workspaceListExecutor = async (params, _context) => {
19425
19322
 
19426
19323
  // src/agent/tools/workspace/read.ts
19427
19324
  import { Type as Type100 } from "@sinclair/typebox";
19428
- import { readFileSync as readFileSync14, lstatSync as lstatSync3 } from "fs";
19325
+ import { readFileSync as readFileSync13, lstatSync as lstatSync3 } from "fs";
19429
19326
  var workspaceReadTool = {
19430
19327
  name: "workspace_read",
19431
19328
  description: `Read a file from your workspace.
@@ -19497,7 +19394,7 @@ var workspaceReadExecutor = async (params, _context) => {
19497
19394
  }
19498
19395
  };
19499
19396
  }
19500
- const content = readFileSync14(
19397
+ const content = readFileSync13(
19501
19398
  validated.absolutePath,
19502
19399
  encoding === "base64" ? "base64" : "utf-8"
19503
19400
  );
@@ -19527,8 +19424,8 @@ var workspaceReadExecutor = async (params, _context) => {
19527
19424
 
19528
19425
  // src/agent/tools/workspace/write.ts
19529
19426
  import { Type as Type101 } from "@sinclair/typebox";
19530
- import { writeFileSync as writeFileSync9, appendFileSync as appendFileSync4, mkdirSync as mkdirSync10, existsSync as existsSync14 } from "fs";
19531
- import { dirname as dirname7 } from "path";
19427
+ import { writeFileSync as writeFileSync9, appendFileSync as appendFileSync3, mkdirSync as mkdirSync9, existsSync as existsSync13 } from "fs";
19428
+ import { dirname as dirname6 } from "path";
19532
19429
  var workspaceWriteTool = {
19533
19430
  name: "workspace_write",
19534
19431
  description: `Write a file to your workspace.
@@ -19572,9 +19469,9 @@ var workspaceWriteExecutor = async (params, _context) => {
19572
19469
  try {
19573
19470
  const { path, content, encoding = "utf-8", append = false, createDirs = true } = params;
19574
19471
  const validated = validateWritePath(path);
19575
- const parentDir = dirname7(validated.absolutePath);
19576
- if (createDirs && !existsSync14(parentDir)) {
19577
- mkdirSync10(parentDir, { recursive: true });
19472
+ const parentDir = dirname6(validated.absolutePath);
19473
+ if (createDirs && !existsSync13(parentDir)) {
19474
+ mkdirSync9(parentDir, { recursive: true });
19578
19475
  }
19579
19476
  let writeContent;
19580
19477
  if (encoding === "base64") {
@@ -19591,7 +19488,7 @@ var workspaceWriteExecutor = async (params, _context) => {
19591
19488
  };
19592
19489
  }
19593
19490
  if (append && validated.exists) {
19594
- appendFileSync4(validated.absolutePath, writeContent);
19491
+ appendFileSync3(validated.absolutePath, writeContent);
19595
19492
  } else {
19596
19493
  writeFileSync9(validated.absolutePath, writeContent);
19597
19494
  }
@@ -19621,7 +19518,7 @@ var workspaceWriteExecutor = async (params, _context) => {
19621
19518
 
19622
19519
  // src/agent/tools/workspace/delete.ts
19623
19520
  import { Type as Type102 } from "@sinclair/typebox";
19624
- import { unlinkSync as unlinkSync4, rmdirSync, readdirSync as readdirSync4, rmSync } from "fs";
19521
+ import { unlinkSync as unlinkSync3, rmdirSync, readdirSync as readdirSync4, rmSync } from "fs";
19625
19522
  var PROTECTED_WORKSPACE_FILES = [
19626
19523
  "SOUL.md",
19627
19524
  "STRATEGY.md",
@@ -19677,7 +19574,7 @@ var workspaceDeleteExecutor = async (params, _context) => {
19677
19574
  rmdirSync(validated.absolutePath);
19678
19575
  }
19679
19576
  } else {
19680
- unlinkSync4(validated.absolutePath);
19577
+ unlinkSync3(validated.absolutePath);
19681
19578
  }
19682
19579
  return {
19683
19580
  success: true,
@@ -19703,8 +19600,8 @@ var workspaceDeleteExecutor = async (params, _context) => {
19703
19600
 
19704
19601
  // src/agent/tools/workspace/info.ts
19705
19602
  import { Type as Type103 } from "@sinclair/typebox";
19706
- import { lstatSync as lstatSync4, readdirSync as readdirSync5, existsSync as existsSync15 } from "fs";
19707
- import { join as join13 } from "path";
19603
+ import { lstatSync as lstatSync4, readdirSync as readdirSync5, existsSync as existsSync14 } from "fs";
19604
+ import { join as join12 } from "path";
19708
19605
  var MEMES_DIR = WORKSPACE_PATHS.MEMES_DIR;
19709
19606
  var workspaceInfoTool = {
19710
19607
  name: "workspace_info",
@@ -19729,7 +19626,7 @@ function getDirSize(dirPath) {
19729
19626
  try {
19730
19627
  const entries = readdirSync5(dirPath, { withFileTypes: true });
19731
19628
  for (const entry of entries) {
19732
- const fullPath = join13(dirPath, entry.name);
19629
+ const fullPath = join12(dirPath, entry.name);
19733
19630
  if (entry.isDirectory()) {
19734
19631
  const subStats = getDirSize(fullPath);
19735
19632
  count += subStats.count;
@@ -19756,11 +19653,11 @@ function formatBytes(bytes) {
19756
19653
  var workspaceInfoExecutor = async (params, _context) => {
19757
19654
  try {
19758
19655
  const { detailed = false } = params;
19759
- const memoryStats = existsSync15(WORKSPACE_PATHS.MEMORY_DIR) ? getDirSize(WORKSPACE_PATHS.MEMORY_DIR) : { count: 0, size: 0 };
19760
- const downloadsStats = existsSync15(WORKSPACE_PATHS.DOWNLOADS_DIR) ? getDirSize(WORKSPACE_PATHS.DOWNLOADS_DIR) : { count: 0, size: 0 };
19761
- const uploadsStats = existsSync15(WORKSPACE_PATHS.UPLOADS_DIR) ? getDirSize(WORKSPACE_PATHS.UPLOADS_DIR) : { count: 0, size: 0 };
19762
- const tempStats = existsSync15(WORKSPACE_PATHS.TEMP_DIR) ? getDirSize(WORKSPACE_PATHS.TEMP_DIR) : { count: 0, size: 0 };
19763
- const memesStats = existsSync15(MEMES_DIR) ? getDirSize(MEMES_DIR) : { count: 0, size: 0 };
19656
+ const memoryStats = existsSync14(WORKSPACE_PATHS.MEMORY_DIR) ? getDirSize(WORKSPACE_PATHS.MEMORY_DIR) : { count: 0, size: 0 };
19657
+ const downloadsStats = existsSync14(WORKSPACE_PATHS.DOWNLOADS_DIR) ? getDirSize(WORKSPACE_PATHS.DOWNLOADS_DIR) : { count: 0, size: 0 };
19658
+ const uploadsStats = existsSync14(WORKSPACE_PATHS.UPLOADS_DIR) ? getDirSize(WORKSPACE_PATHS.UPLOADS_DIR) : { count: 0, size: 0 };
19659
+ const tempStats = existsSync14(WORKSPACE_PATHS.TEMP_DIR) ? getDirSize(WORKSPACE_PATHS.TEMP_DIR) : { count: 0, size: 0 };
19660
+ const memesStats = existsSync14(MEMES_DIR) ? getDirSize(MEMES_DIR) : { count: 0, size: 0 };
19764
19661
  const totalSize = memoryStats.size + downloadsStats.size + uploadsStats.size + tempStats.size + memesStats.size;
19765
19662
  const info = {
19766
19663
  workspaceRoot: WORKSPACE_ROOT,
@@ -19796,11 +19693,11 @@ var workspaceInfoExecutor = async (params, _context) => {
19796
19693
  };
19797
19694
  if (detailed) {
19798
19695
  info.files = {
19799
- memory: existsSync15(WORKSPACE_PATHS.MEMORY_DIR) ? readdirSync5(WORKSPACE_PATHS.MEMORY_DIR) : [],
19800
- downloads: existsSync15(WORKSPACE_PATHS.DOWNLOADS_DIR) ? readdirSync5(WORKSPACE_PATHS.DOWNLOADS_DIR) : [],
19801
- uploads: existsSync15(WORKSPACE_PATHS.UPLOADS_DIR) ? readdirSync5(WORKSPACE_PATHS.UPLOADS_DIR) : [],
19802
- temp: existsSync15(WORKSPACE_PATHS.TEMP_DIR) ? readdirSync5(WORKSPACE_PATHS.TEMP_DIR) : [],
19803
- memes: existsSync15(MEMES_DIR) ? readdirSync5(MEMES_DIR) : []
19696
+ memory: existsSync14(WORKSPACE_PATHS.MEMORY_DIR) ? readdirSync5(WORKSPACE_PATHS.MEMORY_DIR) : [],
19697
+ downloads: existsSync14(WORKSPACE_PATHS.DOWNLOADS_DIR) ? readdirSync5(WORKSPACE_PATHS.DOWNLOADS_DIR) : [],
19698
+ uploads: existsSync14(WORKSPACE_PATHS.UPLOADS_DIR) ? readdirSync5(WORKSPACE_PATHS.UPLOADS_DIR) : [],
19699
+ temp: existsSync14(WORKSPACE_PATHS.TEMP_DIR) ? readdirSync5(WORKSPACE_PATHS.TEMP_DIR) : [],
19700
+ memes: existsSync14(MEMES_DIR) ? readdirSync5(MEMES_DIR) : []
19804
19701
  };
19805
19702
  }
19806
19703
  return {
@@ -19817,9 +19714,9 @@ var workspaceInfoExecutor = async (params, _context) => {
19817
19714
 
19818
19715
  // src/agent/tools/workspace/rename.ts
19819
19716
  import { Type as Type104 } from "@sinclair/typebox";
19820
- import { renameSync as renameSync2, existsSync as existsSync16 } from "fs";
19821
- import { dirname as dirname8 } from "path";
19822
- import { mkdirSync as mkdirSync11 } from "fs";
19717
+ import { renameSync, existsSync as existsSync15 } from "fs";
19718
+ import { dirname as dirname7 } from "path";
19719
+ import { mkdirSync as mkdirSync10 } from "fs";
19823
19720
  var workspaceRenameTool = {
19824
19721
  name: "workspace_rename",
19825
19722
  description: `Rename or move a file within your workspace.
@@ -19866,11 +19763,11 @@ var workspaceRenameExecutor = async (params, _context) => {
19866
19763
  error: `Destination already exists: '${to}'. Use overwrite=true to replace.`
19867
19764
  };
19868
19765
  }
19869
- const parentDir = dirname8(validatedTo.absolutePath);
19870
- if (!existsSync16(parentDir)) {
19871
- mkdirSync11(parentDir, { recursive: true });
19766
+ const parentDir = dirname7(validatedTo.absolutePath);
19767
+ if (!existsSync15(parentDir)) {
19768
+ mkdirSync10(parentDir, { recursive: true });
19872
19769
  }
19873
- renameSync2(validatedFrom.absolutePath, validatedTo.absolutePath);
19770
+ renameSync(validatedFrom.absolutePath, validatedTo.absolutePath);
19874
19771
  return {
19875
19772
  success: true,
19876
19773
  data: {
@@ -21805,6 +21702,7 @@ async function executeDeal(dealId, db, bridge) {
21805
21702
  WHERE id = ?`
21806
21703
  ).run(txHash, dealId);
21807
21704
  console.log(`\u2705 [Deal] #${dealId} completed - TON sent - TX: ${txHash.slice(0, 8)}...`);
21705
+ logDealToJournal(deal, db, txHash);
21808
21706
  await bridge.sendMessage({
21809
21707
  chatId: deal.chat_id,
21810
21708
  text: `\u2705 **Deal #${dealId} completed!**
@@ -21875,6 +21773,7 @@ Thank you for trading! \u{1F389}`
21875
21773
  WHERE id = ?`
21876
21774
  ).run(sentMsgId, dealId);
21877
21775
  console.log(`\u2705 [Deal] #${dealId} completed - Gift transferred`);
21776
+ logDealToJournal(deal, db);
21878
21777
  await bridge.sendMessage({
21879
21778
  chatId: deal.chat_id,
21880
21779
  text: `\u2705 **Deal #${dealId} completed!**
@@ -21924,6 +21823,40 @@ Thank you for trading! \u{1F389}`
21924
21823
  };
21925
21824
  }
21926
21825
  }
21826
+ function logDealToJournal(deal, db, txHash) {
21827
+ try {
21828
+ const journal = new JournalStore(db);
21829
+ const agentGave = formatAsset(
21830
+ deal.agent_gives_type,
21831
+ deal.agent_gives_ton_amount,
21832
+ deal.agent_gives_gift_slug
21833
+ );
21834
+ const agentReceived = formatAsset(
21835
+ deal.user_gives_type,
21836
+ deal.user_gives_ton_amount,
21837
+ deal.user_gives_gift_slug
21838
+ );
21839
+ const isGiftTrade = deal.agent_gives_type === "gift" || deal.user_gives_type === "gift";
21840
+ journal.addEntry({
21841
+ type: isGiftTrade ? "gift" : "trade",
21842
+ action: deal.agent_gives_type === "gift" ? "sell_gift" : "buy_gift",
21843
+ asset_from: agentGave,
21844
+ asset_to: agentReceived,
21845
+ amount_from: deal.agent_gives_ton_amount ?? void 0,
21846
+ amount_to: deal.user_gives_ton_amount ?? void 0,
21847
+ counterparty: String(deal.user_telegram_id),
21848
+ platform: "telegram_deals",
21849
+ outcome: "neutral",
21850
+ // P&L computed later when floor prices are known
21851
+ tx_hash: txHash,
21852
+ tool_used: "deal_executor",
21853
+ chat_id: deal.chat_id,
21854
+ user_id: deal.user_telegram_id
21855
+ });
21856
+ } catch (error) {
21857
+ console.error(`\u26A0\uFE0F [Deal] Failed to log deal #${deal.id} to journal:`, error);
21858
+ }
21859
+ }
21927
21860
  async function autoExecuteAfterVerification(dealId, db, bridge) {
21928
21861
  console.log(`\u{1F504} [Deal] Auto-executing deal #${dealId} after verification...`);
21929
21862
  const result = await executeDeal(dealId, db, bridge);
@@ -22571,25 +22504,25 @@ function registerAllTools(registry, config) {
22571
22504
  }
22572
22505
 
22573
22506
  // src/agent/tools/plugin-loader.ts
22574
- import { readdirSync as readdirSync6, existsSync as existsSync17, statSync as statSync2 } from "fs";
22575
- import { join as join14 } from "path";
22507
+ import { readdirSync as readdirSync6, existsSync as existsSync16, statSync as statSync2 } from "fs";
22508
+ import { join as join13 } from "path";
22576
22509
  import { pathToFileURL } from "url";
22577
22510
  async function loadPlugins(registry) {
22578
22511
  const pluginsDir = WORKSPACE_PATHS.PLUGINS_DIR;
22579
- if (!existsSync17(pluginsDir)) {
22512
+ if (!existsSync16(pluginsDir)) {
22580
22513
  return 0;
22581
22514
  }
22582
22515
  const entries = readdirSync6(pluginsDir);
22583
22516
  let totalRegistered = 0;
22584
22517
  for (const entry of entries) {
22585
- const entryPath = join14(pluginsDir, entry);
22518
+ const entryPath = join13(pluginsDir, entry);
22586
22519
  let modulePath = null;
22587
22520
  const stat = statSync2(entryPath);
22588
22521
  if (stat.isFile() && entry.endsWith(".js")) {
22589
22522
  modulePath = entryPath;
22590
22523
  } else if (stat.isDirectory()) {
22591
- const indexPath = join14(entryPath, "index.js");
22592
- if (existsSync17(indexPath)) {
22524
+ const indexPath = join13(entryPath, "index.js");
22525
+ if (existsSync16(indexPath)) {
22593
22526
  modulePath = indexPath;
22594
22527
  }
22595
22528
  }
@@ -23874,7 +23807,7 @@ var TonnetApp = class {
23874
23807
  apiId: this.config.telegram.api_id,
23875
23808
  apiHash: this.config.telegram.api_hash,
23876
23809
  phone: this.config.telegram.phone,
23877
- sessionPath: join15(TELETON_ROOT, "telegram_session.txt"),
23810
+ sessionPath: join14(TELETON_ROOT, "telegram_session.txt"),
23878
23811
  connectionRetries: TELEGRAM_CONNECTION_RETRIES,
23879
23812
  autoReconnect: true,
23880
23813
  floodSleepThreshold: TELEGRAM_FLOOD_SLEEP_THRESHOLD
@@ -23882,7 +23815,7 @@ var TonnetApp = class {
23882
23815
  const VECTOR_DIMENSIONS = 512;
23883
23816
  const memory = initializeMemory({
23884
23817
  database: {
23885
- path: join15(TELETON_ROOT, "memory.db"),
23818
+ path: join14(TELETON_ROOT, "memory.db"),
23886
23819
  enableVectorSearch: false,
23887
23820
  vectorDimensions: VECTOR_DIMENSIONS
23888
23821
  },
@@ -23891,7 +23824,7 @@ var TonnetApp = class {
23891
23824
  apiKey: "",
23892
23825
  model: ""
23893
23826
  },
23894
- workspaceDir: join15(TELETON_ROOT)
23827
+ workspaceDir: join14(TELETON_ROOT)
23895
23828
  });
23896
23829
  const db = getDatabase().getDb();
23897
23830
  if (this.config.market.enabled || this.config.deals.enabled) {
@@ -23943,9 +23876,11 @@ ${blue} \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u250
23943
23876
  }
23944
23877
  const { migrateSessionsToDb } = await import("./migrate-F256Q7LW.js");
23945
23878
  migrateSessionsToDb();
23879
+ const { cleanupOldTranscripts } = await import("./transcript-DF2Y6CFY.js");
23880
+ cleanupOldTranscripts(30);
23946
23881
  const memory = initializeMemory({
23947
23882
  database: {
23948
- path: join15(TELETON_ROOT, "memory.db"),
23883
+ path: join14(TELETON_ROOT, "memory.db"),
23949
23884
  enableVectorSearch: false,
23950
23885
  vectorDimensions: 512
23951
23886
  },
@@ -23954,7 +23889,7 @@ ${blue} \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u250
23954
23889
  apiKey: "",
23955
23890
  model: ""
23956
23891
  },
23957
- workspaceDir: join15(TELETON_ROOT)
23892
+ workspaceDir: join14(TELETON_ROOT)
23958
23893
  });
23959
23894
  const indexResult = await memory.knowledge.indexAll();
23960
23895
  const db = getDatabase();
package/dist/cli/index.js CHANGED
@@ -17,7 +17,9 @@ import {
17
17
  saveWallet,
18
18
  validateApiKeyFormat,
19
19
  walletExists
20
- } from "../chunk-ABHUNKXQ.js";
20
+ } from "../chunk-Y4G7HSOQ.js";
21
+ import "../chunk-U7FQYCBQ.js";
22
+ import "../chunk-OQGNS2FV.js";
21
23
  import "../chunk-JDPS46IZ.js";
22
24
  import "../chunk-E2NXSWOS.js";
23
25
  import {
@@ -33,7 +35,6 @@ import {
33
35
  ONBOARDING_PROMPT_TIMEOUT_MS
34
36
  } from "../chunk-LJXYESJJ.js";
35
37
  import "../chunk-B2PRMXOH.js";
36
- import "../chunk-U7FQYCBQ.js";
37
38
  import "../chunk-QGM4M3NI.js";
38
39
 
39
40
  // src/cli/index.ts
package/dist/index.js CHANGED
@@ -1,7 +1,9 @@
1
1
  import {
2
2
  TonnetApp,
3
3
  main
4
- } from "./chunk-ABHUNKXQ.js";
4
+ } from "./chunk-Y4G7HSOQ.js";
5
+ import "./chunk-U7FQYCBQ.js";
6
+ import "./chunk-OQGNS2FV.js";
5
7
  import "./chunk-JDPS46IZ.js";
6
8
  import "./chunk-E2NXSWOS.js";
7
9
  import "./chunk-EYWNOHMJ.js";
@@ -9,7 +11,6 @@ import "./chunk-WMIN6AGX.js";
9
11
  import "./chunk-QMN6ZOA5.js";
10
12
  import "./chunk-LJXYESJJ.js";
11
13
  import "./chunk-B2PRMXOH.js";
12
- import "./chunk-U7FQYCBQ.js";
13
14
  import "./chunk-QGM4M3NI.js";
14
15
  export {
15
16
  TonnetApp,
@@ -0,0 +1,22 @@
1
+ import {
2
+ appendToTranscript,
3
+ archiveTranscript,
4
+ cleanupOldTranscripts,
5
+ deleteTranscript,
6
+ getTranscriptPath,
7
+ getTranscriptSize,
8
+ readTranscript,
9
+ transcriptExists
10
+ } from "./chunk-OQGNS2FV.js";
11
+ import "./chunk-EYWNOHMJ.js";
12
+ import "./chunk-QGM4M3NI.js";
13
+ export {
14
+ appendToTranscript,
15
+ archiveTranscript,
16
+ cleanupOldTranscripts,
17
+ deleteTranscript,
18
+ getTranscriptPath,
19
+ getTranscriptSize,
20
+ readTranscript,
21
+ transcriptExists
22
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "teleton",
3
- "version": "0.1.19",
3
+ "version": "0.1.20",
4
4
  "description": "Personal AI Agent for Telegram",
5
5
  "author": "ZKProof (https://t.me/zkproof)",
6
6
  "license": "MIT",