teleton 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025-2026 Digital Resistance
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,12 +1,12 @@
1
- # Teleton Agent
1
+ <h1 align="center">Teleton Agent</h1>
2
2
 
3
- **Autonomous AI Agent for Telegram with TON Blockchain Integration**
3
+ <p align="center"><b>Your personal AI that lives on Telegram and trades on TON</b></p>
4
4
 
5
- ![Now in Public Beta](https://img.shields.io/badge/Now_in_Public_Beta-0088cc?style=for-the-badge&logoColor=white)
6
-
7
- [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
8
- [![Node.js](https://img.shields.io/badge/node-%3E%3D20.0.0-brightgreen)](https://nodejs.org/)
9
- [![TypeScript](https://img.shields.io/badge/TypeScript-5.7-blue)](https://www.typescriptlang.org/)
5
+ <p align="center">
6
+ <a href="https://opensource.org/licenses/MIT"><img src="https://img.shields.io/badge/License-MIT-yellow.svg" alt="License: MIT"></a>
7
+ <a href="https://nodejs.org/"><img src="https://img.shields.io/badge/node-%3E%3D20.0.0-brightgreen" alt="Node.js"></a>
8
+ <a href="https://www.typescriptlang.org/"><img src="https://img.shields.io/badge/TypeScript-5.7-blue" alt="TypeScript"></a>
9
+ </p>
10
10
 
11
11
  ---
12
12
 
@@ -16,13 +16,14 @@ Teleton is a production-grade autonomous AI agent that operates as a real Telegr
16
16
 
17
17
  ### Key Highlights
18
18
 
19
- - **True Autonomy** - Operates as a Telegram userbot with access to full API (not limited like bots)
20
- - **Multi-Provider LLM** - Anthropic, OpenAI, Google Gemini, xAI Grok, Groq, OpenRouter
21
- - **TON Native** - Built-in W5R1 wallet, jetton swaps, DNS, and DeFi integrations
22
- - **Deals System** - Secure gift/TON trading with strategy enforcement and inline bot confirmations
23
- - **Advanced Memory** - RAG system with hybrid FTS5 + vector search, auto-compaction, daily logs
24
- - **121 Tools** - Telegram operations, blockchain transactions, market analysis, deals, and more
25
- - **Production Ready** - SQLite storage, sandboxed workspace, multi-layer security
19
+ - **Full Telegram access**: Operates as a real user with the full API, not a limited bot
20
+ - **Multi-Provider LLM**: Anthropic, OpenAI, Google Gemini, xAI Grok, Groq, OpenRouter
21
+ - **TON Blockchain**: Built-in wallet, send/receive TON, swap jettons on STON.fi and DeDust, NFT auctions
22
+ - **Gift trading**: Buy and sell Telegram collectible gifts with real-time floor prices and strategy enforcement
23
+ - **Persistent memory**: Remembers context across restarts with automatic context management
24
+ - **121 tools**: Messaging, media, blockchain transactions, DEX swaps, market analysis, deals, and more
25
+ - **Plugin system**: Drop a `.js` file in a folder and restart, no rebuild needed
26
+ - **Secure by design**: Sandboxed workspace, immutable config, strategy rules enforced in code
26
27
 
27
28
  ---
28
29
 
@@ -82,7 +83,7 @@ Teleton is a production-grade autonomous AI agent that operates as a real Telegr
82
83
 
83
84
  **One-liner (recommended):**
84
85
  ```bash
85
- curl -fsSL https://raw.githubusercontent.com/TONresistor/teleton-agent-dev/main/install.sh | bash
86
+ curl -fsSL https://raw.githubusercontent.com/TONresistor/teleton-agent/main/install.sh | bash
86
87
  ```
87
88
 
88
89
  **npm:**
@@ -92,13 +93,13 @@ npm install -g teleton
92
93
 
93
94
  **Docker:**
94
95
  ```bash
95
- docker run -it -v ~/.teleton:/data ghcr.io/tonresistor/teleton-agent-dev:latest setup
96
+ docker run -it -v ~/.teleton:/data ghcr.io/tonresistor/teleton:latest setup
96
97
  ```
97
98
 
98
99
  **From source (development):**
99
100
  ```bash
100
- git clone https://github.com/TONresistor/teleton-agent-dev.git
101
- cd teleton-agent-dev
101
+ git clone https://github.com/TONresistor/teleton-agent.git
102
+ cd teleton
102
103
  npm install && npm run build
103
104
  ```
104
105
 
@@ -114,7 +115,7 @@ The wizard will configure:
114
115
  - Access policies (DM/group response rules)
115
116
  - Admin user ID
116
117
  - TON wallet generation (W5R1 with 24-word mnemonic)
117
- - Workspace initialization (SOUL.md, STRATEGY.md, SECURITY.md, MEMORY.md)
118
+ - Workspace initialization (SOUL.md, IDENTITY.md, STRATEGY.md, SECURITY.md, USER.md, BOOTSTRAP.md, MEMORY.md)
118
119
 
119
120
  Configuration files created:
120
121
  - `~/.teleton/config.yaml` - Main configuration
@@ -124,6 +125,8 @@ Configuration files created:
124
125
 
125
126
  ### 3. Start
126
127
 
128
+ If setup completed without errors, your agent is ready to go:
129
+
127
130
  ```bash
128
131
  teleton start
129
132
  ```
@@ -140,11 +143,13 @@ You: /status
140
143
  Agent: [Displays uptime, model, tool count, wallet balance]
141
144
  ```
142
145
 
146
+ > **Need more details?** See [GETTING_STARTED.md](GETTING_STARTED.md) for the full guide — admin commands, troubleshooting, workspace templates, plugins, and more.
147
+
143
148
  ---
144
149
 
145
150
  ## Configuration
146
151
 
147
- Edit `~/.teleton/config.yaml`:
152
+ The `teleton setup` wizard generates a fully configured `~/.teleton/config.yaml` file. Manual editing is only necessary if you want to adjust settings after the initial setup.
148
153
 
149
154
  ```yaml
150
155
  agent:
@@ -183,15 +188,20 @@ telegram:
183
188
 
184
189
  ### Workspace Files
185
190
 
186
- The agent's personality and rules are configured via markdown files in `~/.teleton/workspace/`:
191
+ The agent's personality and rules are configured via markdown files in `~/.teleton/workspace/`. Default templates are generated during `teleton setup` — you can edit any of them to customize your agent:
187
192
 
188
193
  | File | Purpose | Mutable by Agent |
189
194
  |------|---------|-----------------|
190
- | `SOUL.md` | Personality, behavior guidelines | No |
191
- | `STRATEGY.md` | Trading rules, pricing thresholds | No |
195
+ | `SOUL.md` | Personality, tone, behavior guidelines | No |
196
+ | `IDENTITY.md` | Agent name, bio, public-facing identity | No |
197
+ | `STRATEGY.md` | Trading rules, buy/sell thresholds | No |
192
198
  | `SECURITY.md` | Security principles, threat recognition | No |
199
+ | `USER.md` | Owner information and preferences | No |
200
+ | `BOOTSTRAP.md` | First-run instructions (read once at startup) | No |
193
201
  | `MEMORY.md` | Persistent memory (facts, contacts, decisions) | Yes |
194
202
 
203
+ > **Tip**: Templates are located in `src/templates/` if installing from source. Edit the workspace copies in `~/.teleton/workspace/` — not the source templates.
204
+
195
205
  ### Admin Commands
196
206
 
197
207
  | Command | Description |
@@ -308,8 +318,8 @@ Do not open public issues for security vulnerabilities. Contact maintainers (t.m
308
318
  ### Setup
309
319
 
310
320
  ```bash
311
- git clone https://github.com/TONresistor/teleton-agent-dev.git
312
- cd teleton-agent-dev
321
+ git clone https://github.com/TONresistor/teleton-agent.git
322
+ cd teleton
313
323
  npm install
314
324
  npm run setup
315
325
  npm run dev # Watch mode with auto-restart
@@ -328,30 +338,47 @@ npm run lint # ESLint
328
338
  npm run format # Prettier
329
339
  ```
330
340
 
331
- ### Adding Custom Tools
332
-
333
- ```typescript
334
- // src/agent/tools/custom/my-tool.ts
335
- import { Type } from "@sinclair/typebox";
336
- import type { Tool, ToolExecutor, ToolResult } from "../types.js";
337
-
338
- export const myTool: Tool = {
339
- name: "my_custom_tool",
340
- description: "Does something useful",
341
- parameters: Type.Object({
342
- input: Type.String({ description: "Input parameter" }),
343
- }),
344
- };
345
-
346
- export const myToolExecutor: ToolExecutor<{ input: string }> = async (
347
- params,
348
- context
349
- ): Promise<ToolResult> => {
350
- return { success: true, data: { result: "..." } };
351
- };
352
-
353
- // Register in src/index.ts:
354
- // this.toolRegistry.register(myTool, myToolExecutor);
341
+ ### Plugins
342
+
343
+ Teleton supports external plugins loaded from `~/.teleton/plugins/`. Drop a `.js` file or a folder with `index.js`, and it's automatically loaded at startup — no rebuild needed.
344
+
345
+ ```
346
+ ~/.teleton/plugins/
347
+ ├── weather.js # Single file plugin
348
+ └── rss-reader/
349
+ └── index.js # Folder plugin
350
+ ```
351
+
352
+ Each plugin exports a `tools` array:
353
+
354
+ ```js
355
+ // ~/.teleton/plugins/weather.js
356
+ export const tools = [
357
+ {
358
+ name: "weather_get",
359
+ description: "Get current weather for a city",
360
+ parameters: {
361
+ type: "object",
362
+ properties: {
363
+ city: { type: "string", description: "City name" }
364
+ },
365
+ required: ["city"]
366
+ },
367
+ execute: async (params, context) => {
368
+ const res = await fetch(`https://wttr.in/${params.city}?format=j1`);
369
+ const data = await res.json();
370
+ return { success: true, data: { temp: data.current_condition[0].temp_C } };
371
+ }
372
+ }
373
+ ];
374
+ ```
375
+
376
+ The `context` object gives access to `bridge` (Telegram), `db` (SQLite), `chatId`, `senderId`, `config`, and `marketService`.
377
+
378
+ At startup you'll see:
379
+ ```
380
+ 🔌 Plugin "weather.js": 1 tool registered
381
+ ✅ 122 tools loaded (1 from plugins)
355
382
  ```
356
383
 
357
384
  ---
@@ -390,6 +417,7 @@ MIT License - See [LICENSE](LICENSE) for details.
390
417
 
391
418
  ## Support
392
419
 
393
- - **Issues**: [GitHub Issues](https://github.com/TONresistor/teleton-agent-dev/issues)
420
+ - **Issues**: [GitHub Issues](https://github.com/TONresistor/teleton-agent/issues)
394
421
  - **Channel**: [@ResistanceTools](https://t.me/ResistanceTools)
422
+ - **Group Chat**: [@ResistanceForum](https://t.me/ResistanceForum)
395
423
  - **Contact**: [@zkproof](https://t.me/zkproof)
@@ -1,6 +1,8 @@
1
1
  // src/agent/tools/telegram/gifts/get-my-gifts.ts
2
2
  import { Type } from "@sinclair/typebox";
3
3
  import { Api } from "telegram";
4
+ var giftCatalogCache = null;
5
+ var CATALOG_CACHE_TTL_MS = 5 * 60 * 1e3;
4
6
  function extractEmoji(sticker) {
5
7
  if (!sticker?.attributes) return null;
6
8
  const attr = sticker.attributes.find(
@@ -61,28 +63,56 @@ NEVER dump all raw data. Keep responses natural and concise.`,
61
63
  description: "Sort by value instead of date. Default: false (sorted by date)"
62
64
  })
63
65
  )
64
- })
66
+ }),
67
+ category: "data-bearing"
65
68
  };
66
69
  var telegramGetMyGiftsExecutor = async (params, context) => {
67
70
  try {
68
- const { userId, viewSender, limit = 50, excludeUnsaved, excludeSaved, sortByValue = false } = params;
71
+ const {
72
+ userId,
73
+ viewSender,
74
+ limit = 50,
75
+ excludeUnsaved,
76
+ excludeSaved,
77
+ sortByValue = false
78
+ } = params;
69
79
  const gramJsClient = context.bridge.getClient().getClient();
70
80
  const targetUserId = viewSender ? context.senderId.toString() : userId;
71
81
  const peer = targetUserId ? await gramJsClient.getEntity(targetUserId) : new Api.InputPeerSelf();
72
- const catalog = await gramJsClient.invoke(
73
- new Api.payments.GetStarGifts({ hash: 0 })
74
- );
75
- const catalogMap = /* @__PURE__ */ new Map();
76
- for (const catalogGift of catalog.gifts || []) {
77
- const id = catalogGift.id?.toString();
78
- if (id) {
79
- catalogMap.set(id, {
80
- limited: catalogGift.limited || false,
81
- soldOut: catalogGift.soldOut || false,
82
- emoji: extractEmoji(catalogGift.sticker),
83
- availabilityTotal: catalogGift.availabilityTotal,
84
- availabilityRemains: catalogGift.availabilityRemains
85
- });
82
+ let catalogMap;
83
+ if (giftCatalogCache && Date.now() < giftCatalogCache.expiresAt) {
84
+ catalogMap = giftCatalogCache.map;
85
+ } else {
86
+ const prevHash = giftCatalogCache?.hash ?? 0;
87
+ const catalog = await gramJsClient.invoke(
88
+ new Api.payments.GetStarGifts({ hash: prevHash })
89
+ );
90
+ if (catalog.gifts && catalog.gifts.length > 0) {
91
+ catalogMap = /* @__PURE__ */ new Map();
92
+ for (const catalogGift of catalog.gifts) {
93
+ const id = catalogGift.id?.toString();
94
+ if (id) {
95
+ catalogMap.set(id, {
96
+ limited: catalogGift.limited || false,
97
+ soldOut: catalogGift.soldOut || false,
98
+ emoji: extractEmoji(catalogGift.sticker),
99
+ availabilityTotal: catalogGift.availabilityTotal,
100
+ availabilityRemains: catalogGift.availabilityRemains
101
+ });
102
+ }
103
+ }
104
+ giftCatalogCache = {
105
+ map: catalogMap,
106
+ hash: catalog.hash ?? 0,
107
+ expiresAt: Date.now() + CATALOG_CACHE_TTL_MS
108
+ };
109
+ } else {
110
+ catalogMap = giftCatalogCache?.map ?? /* @__PURE__ */ new Map();
111
+ giftCatalogCache = {
112
+ map: catalogMap,
113
+ hash: catalog.hash ?? giftCatalogCache?.hash ?? 0,
114
+ expiresAt: Date.now() + CATALOG_CACHE_TTL_MS
115
+ };
86
116
  }
87
117
  }
88
118
  const result = await gramJsClient.invoke(
@@ -123,9 +153,15 @@ var telegramGetMyGiftsExecutor = async (params, context) => {
123
153
  compactGift.num = gift.num;
124
154
  compactGift.slug = gift.slug;
125
155
  compactGift.nftLink = `t.me/nft/${gift.slug}`;
126
- const modelAttr = gift.attributes?.find((a) => a.className === "StarGiftAttributeModel");
127
- const patternAttr = gift.attributes?.find((a) => a.className === "StarGiftAttributePattern");
128
- const backdropAttr = gift.attributes?.find((a) => a.className === "StarGiftAttributeBackdrop");
156
+ const modelAttr = gift.attributes?.find(
157
+ (a) => a.className === "StarGiftAttributeModel"
158
+ );
159
+ const patternAttr = gift.attributes?.find(
160
+ (a) => a.className === "StarGiftAttributePattern"
161
+ );
162
+ const backdropAttr = gift.attributes?.find(
163
+ (a) => a.className === "StarGiftAttributeBackdrop"
164
+ );
129
165
  compactGift.model = extractAttrSummary(modelAttr);
130
166
  compactGift.pattern = extractAttrSummary(patternAttr);
131
167
  compactGift.backdrop = extractAttrSummary(backdropAttr);
@@ -145,7 +181,9 @@ var telegramGetMyGiftsExecutor = async (params, context) => {
145
181
  const unlimited = gifts.filter((g) => !g.isLimited);
146
182
  const collectibles = gifts.filter((g) => g.isCollectible);
147
183
  const viewingLabel = viewSender ? `sender (${context.senderId})` : userId || "self";
148
- console.log(`\u{1F4E6} get_my_gifts: viewing ${viewingLabel}, found ${gifts.length} gifts (${collectibles.length} collectibles)`);
184
+ console.log(
185
+ `\u{1F4E6} get_my_gifts: viewing ${viewingLabel}, found ${gifts.length} gifts (${collectibles.length} collectibles)`
186
+ );
149
187
  return {
150
188
  success: true,
151
189
  data: {
@@ -241,7 +241,9 @@ var TaskStore = class {
241
241
  `Cannot add dependency: would create circular dependency (${taskId} \u2192 ${parentTaskId})`
242
242
  );
243
243
  }
244
- this.db.prepare(`INSERT OR IGNORE INTO task_dependencies (task_id, depends_on_task_id) VALUES (?, ?)`).run(taskId, parentTaskId);
244
+ this.db.prepare(
245
+ `INSERT OR IGNORE INTO task_dependencies (task_id, depends_on_task_id) VALUES (?, ?)`
246
+ ).run(taskId, parentTaskId);
245
247
  }
246
248
  /**
247
249
  * Get all tasks that this task depends on
@@ -0,0 +1,56 @@
1
+ // src/constants/timeouts.ts
2
+ var TTS_TIMEOUT_MS = 3e4;
3
+ var BROWSER_NAVIGATION_TIMEOUT_MS = 3e4;
4
+ var MESSAGE_HANDLER_LOCK_TIMEOUT_MS = 12e4;
5
+ var ONBOARDING_PROMPT_TIMEOUT_MS = 12e4;
6
+ var BATCH_TRIGGER_DELAY_MS = 500;
7
+ var DEFAULT_FETCH_TIMEOUT_MS = 15e3;
8
+ var SCRAPER_PAGE_LOAD_MS = 2500;
9
+ var SCRAPER_FILTER_CLICK_MS = 3e3;
10
+ var SCRAPER_MODEL_CLICK_MS = 2e3;
11
+ var SCRAPER_FILTER_OPEN_MS = 600;
12
+ var SCRAPER_MODEL_OPEN_MS = 800;
13
+ var SCRAPER_SCROLL_STEP_MS = 80;
14
+ var SCRAPER_PRE_SCROLL_MS = 4e3;
15
+ var SCRAPER_COLLECTION_SCROLL_MS = 200;
16
+ var SCRAPER_SCROLL_INCREMENT_PX = 250;
17
+ var SCRAPER_SCROLL_PADDING_PX = 500;
18
+ var SCRAPER_MAX_SCROLL_ITERATIONS = 15;
19
+ var SCRAPER_COLLECTION_NAV_MS = 6e4;
20
+ var RETRY_DEFAULT_MAX_ATTEMPTS = 3;
21
+ var RETRY_DEFAULT_BASE_DELAY_MS = 1e3;
22
+ var RETRY_DEFAULT_MAX_DELAY_MS = 1e4;
23
+ var RETRY_DEFAULT_TIMEOUT_MS = 15e3;
24
+ var RETRY_BLOCKCHAIN_BASE_DELAY_MS = 2e3;
25
+ var RETRY_BLOCKCHAIN_MAX_DELAY_MS = 15e3;
26
+ var RETRY_BLOCKCHAIN_TIMEOUT_MS = 3e4;
27
+ var GRAMJS_RETRY_DELAY_MS = 1e3;
28
+
29
+ export {
30
+ TTS_TIMEOUT_MS,
31
+ BROWSER_NAVIGATION_TIMEOUT_MS,
32
+ MESSAGE_HANDLER_LOCK_TIMEOUT_MS,
33
+ ONBOARDING_PROMPT_TIMEOUT_MS,
34
+ BATCH_TRIGGER_DELAY_MS,
35
+ DEFAULT_FETCH_TIMEOUT_MS,
36
+ SCRAPER_PAGE_LOAD_MS,
37
+ SCRAPER_FILTER_CLICK_MS,
38
+ SCRAPER_MODEL_CLICK_MS,
39
+ SCRAPER_FILTER_OPEN_MS,
40
+ SCRAPER_MODEL_OPEN_MS,
41
+ SCRAPER_SCROLL_STEP_MS,
42
+ SCRAPER_PRE_SCROLL_MS,
43
+ SCRAPER_COLLECTION_SCROLL_MS,
44
+ SCRAPER_SCROLL_INCREMENT_PX,
45
+ SCRAPER_SCROLL_PADDING_PX,
46
+ SCRAPER_MAX_SCROLL_ITERATIONS,
47
+ SCRAPER_COLLECTION_NAV_MS,
48
+ RETRY_DEFAULT_MAX_ATTEMPTS,
49
+ RETRY_DEFAULT_BASE_DELAY_MS,
50
+ RETRY_DEFAULT_MAX_DELAY_MS,
51
+ RETRY_DEFAULT_TIMEOUT_MS,
52
+ RETRY_BLOCKCHAIN_BASE_DELAY_MS,
53
+ RETRY_BLOCKCHAIN_MAX_DELAY_MS,
54
+ RETRY_BLOCKCHAIN_TIMEOUT_MS,
55
+ GRAMJS_RETRY_DELAY_MS
56
+ };
@@ -1,3 +1,17 @@
1
+ import {
2
+ VOYAGE_API_URL
3
+ } from "./chunk-ST5CO7TV.js";
4
+ import {
5
+ KNOWLEDGE_CHUNK_OVERLAP,
6
+ KNOWLEDGE_CHUNK_SIZE,
7
+ SQLITE_CACHE_SIZE_KB,
8
+ SQLITE_MMAP_SIZE,
9
+ VOYAGE_BATCH_SIZE
10
+ } from "./chunk-QMN6ZOA5.js";
11
+ import {
12
+ DEFAULT_FETCH_TIMEOUT_MS
13
+ } from "./chunk-LJXYESJJ.js";
14
+
1
15
  // src/memory/database.ts
2
16
  import Database from "better-sqlite3";
3
17
  import { existsSync, mkdirSync } from "fs";
@@ -250,6 +264,48 @@ function ensureSchema(db) {
250
264
  CREATE INDEX IF NOT EXISTS idx_embedding_cache_model ON embedding_cache(provider, model);
251
265
  CREATE INDEX IF NOT EXISTS idx_embedding_cache_accessed ON embedding_cache(accessed_at);
252
266
 
267
+ -- =====================================================
268
+ -- CASINO
269
+ -- =====================================================
270
+
271
+ CREATE TABLE IF NOT EXISTS casino_users (
272
+ telegram_id TEXT PRIMARY KEY,
273
+ wallet_address TEXT,
274
+ total_bets INTEGER NOT NULL DEFAULT 0,
275
+ total_wagered REAL NOT NULL DEFAULT 0,
276
+ total_wins INTEGER NOT NULL DEFAULT 0,
277
+ total_losses INTEGER NOT NULL DEFAULT 0,
278
+ total_won REAL NOT NULL DEFAULT 0,
279
+ last_bet_at INTEGER
280
+ );
281
+
282
+ CREATE TABLE IF NOT EXISTS used_transactions (
283
+ tx_hash TEXT PRIMARY KEY,
284
+ user_id TEXT NOT NULL,
285
+ amount REAL NOT NULL,
286
+ game_type TEXT NOT NULL,
287
+ used_at INTEGER NOT NULL DEFAULT (unixepoch())
288
+ );
289
+
290
+ CREATE INDEX IF NOT EXISTS idx_used_tx_user ON used_transactions(user_id);
291
+ CREATE INDEX IF NOT EXISTS idx_used_tx_used_at ON used_transactions(used_at);
292
+
293
+ CREATE TABLE IF NOT EXISTS casino_cooldowns (
294
+ user_id TEXT PRIMARY KEY,
295
+ last_spin_at INTEGER NOT NULL
296
+ );
297
+
298
+ CREATE TABLE IF NOT EXISTS casino_jackpot (
299
+ id INTEGER PRIMARY KEY CHECK(id = 1),
300
+ amount REAL NOT NULL DEFAULT 0,
301
+ last_awarded_at INTEGER,
302
+ last_winner_id TEXT,
303
+ last_winner_amount REAL
304
+ );
305
+
306
+ -- Insert default jackpot row
307
+ INSERT OR IGNORE INTO casino_jackpot (id, amount) VALUES (1, 0);
308
+
253
309
  -- =====================================================
254
310
  -- JOURNAL (Trading & Business Operations)
255
311
  -- =====================================================
@@ -321,7 +377,7 @@ function setSchemaVersion(db, version) {
321
377
  `
322
378
  ).run(version);
323
379
  }
324
- var CURRENT_SCHEMA_VERSION = "1.6.0";
380
+ var CURRENT_SCHEMA_VERSION = "1.7.0";
325
381
  function runMigrations(db) {
326
382
  const currentVersion = getSchemaVersion(db);
327
383
  if (!currentVersion || versionLessThan(currentVersion, "1.1.0")) {
@@ -577,6 +633,53 @@ function runMigrations(db) {
577
633
  throw error;
578
634
  }
579
635
  }
636
+ if (!currentVersion || versionLessThan(currentVersion, "1.7.0")) {
637
+ try {
638
+ console.log("\u{1F504} Running migration 1.7.0: Add casino tables");
639
+ db.exec(`
640
+ CREATE TABLE IF NOT EXISTS casino_users (
641
+ telegram_id TEXT PRIMARY KEY,
642
+ wallet_address TEXT,
643
+ total_bets INTEGER NOT NULL DEFAULT 0,
644
+ total_wagered REAL NOT NULL DEFAULT 0,
645
+ total_wins INTEGER NOT NULL DEFAULT 0,
646
+ total_losses INTEGER NOT NULL DEFAULT 0,
647
+ total_won REAL NOT NULL DEFAULT 0,
648
+ last_bet_at INTEGER
649
+ );
650
+
651
+ CREATE TABLE IF NOT EXISTS used_transactions (
652
+ tx_hash TEXT PRIMARY KEY,
653
+ user_id TEXT NOT NULL,
654
+ amount REAL NOT NULL,
655
+ game_type TEXT NOT NULL,
656
+ used_at INTEGER NOT NULL DEFAULT (unixepoch())
657
+ );
658
+
659
+ CREATE INDEX IF NOT EXISTS idx_used_tx_user ON used_transactions(user_id);
660
+ CREATE INDEX IF NOT EXISTS idx_used_tx_used_at ON used_transactions(used_at);
661
+
662
+ CREATE TABLE IF NOT EXISTS casino_cooldowns (
663
+ user_id TEXT PRIMARY KEY,
664
+ last_spin_at INTEGER NOT NULL
665
+ );
666
+
667
+ CREATE TABLE IF NOT EXISTS casino_jackpot (
668
+ id INTEGER PRIMARY KEY CHECK(id = 1),
669
+ amount REAL NOT NULL DEFAULT 0,
670
+ last_awarded_at INTEGER,
671
+ last_winner_id TEXT,
672
+ last_winner_amount REAL
673
+ );
674
+
675
+ INSERT OR IGNORE INTO casino_jackpot (id, amount) VALUES (1, 0);
676
+ `);
677
+ console.log("\u2705 Migration 1.7.0 complete: Casino tables added");
678
+ } catch (error) {
679
+ console.error("\u274C Migration 1.7.0 failed:", error);
680
+ throw error;
681
+ }
682
+ }
580
683
  setSchemaVersion(db, CURRENT_SCHEMA_VERSION);
581
684
  }
582
685
 
@@ -596,9 +699,9 @@ var MemoryDatabase = class {
596
699
  });
597
700
  this.db.pragma("journal_mode = WAL");
598
701
  this.db.pragma("synchronous = NORMAL");
599
- this.db.pragma("cache_size = -64000");
702
+ this.db.pragma(`cache_size = -${SQLITE_CACHE_SIZE_KB}`);
600
703
  this.db.pragma("temp_store = MEMORY");
601
- this.db.pragma("mmap_size = 30000000000");
704
+ this.db.pragma(`mmap_size = ${SQLITE_MMAP_SIZE}`);
602
705
  this.db.pragma("foreign_keys = ON");
603
706
  this.initialize();
604
707
  }
@@ -781,13 +884,26 @@ var NoopEmbeddingProvider = class {
781
884
  }
782
885
  };
783
886
 
887
+ // src/utils/fetch.ts
888
+ var DEFAULT_TIMEOUT_MS = DEFAULT_FETCH_TIMEOUT_MS;
889
+ function fetchWithTimeout(url, init) {
890
+ const { timeoutMs = DEFAULT_TIMEOUT_MS, ...fetchInit } = init ?? {};
891
+ if (fetchInit.signal) {
892
+ return fetch(url, fetchInit);
893
+ }
894
+ return fetch(url, {
895
+ ...fetchInit,
896
+ signal: AbortSignal.timeout(timeoutMs)
897
+ });
898
+ }
899
+
784
900
  // src/memory/embeddings/anthropic.ts
785
901
  var AnthropicEmbeddingProvider = class {
786
902
  id = "anthropic";
787
903
  model;
788
904
  dimensions;
789
905
  apiKey;
790
- baseUrl = "https://api.voyageai.com/v1";
906
+ baseUrl = VOYAGE_API_URL;
791
907
  constructor(config) {
792
908
  this.apiKey = config.apiKey;
793
909
  this.model = config.model ?? "voyage-3-lite";
@@ -807,7 +923,7 @@ var AnthropicEmbeddingProvider = class {
807
923
  }
808
924
  async embedBatch(texts) {
809
925
  if (texts.length === 0) return [];
810
- const batchSize = 128;
926
+ const batchSize = VOYAGE_BATCH_SIZE;
811
927
  const results = [];
812
928
  for (let i = 0; i < texts.length; i += batchSize) {
813
929
  const batch = texts.slice(i, i + batchSize);
@@ -817,7 +933,7 @@ var AnthropicEmbeddingProvider = class {
817
933
  return results;
818
934
  }
819
935
  async embed(texts) {
820
- const response = await fetch(`${this.baseUrl}/embeddings`, {
936
+ const response = await fetchWithTimeout(`${this.baseUrl}/embeddings`, {
821
937
  method: "POST",
822
938
  headers: {
823
939
  "Content-Type": "application/json",
@@ -1007,8 +1123,8 @@ var KnowledgeIndexer = class {
1007
1123
  chunkMarkdown(content, path) {
1008
1124
  const lines = content.split("\n");
1009
1125
  const chunks = [];
1010
- const chunkSize = 500;
1011
- const overlap = 50;
1126
+ const chunkSize = KNOWLEDGE_CHUNK_SIZE;
1127
+ const overlap = KNOWLEDGE_CHUNK_OVERLAP;
1012
1128
  let currentChunk = "";
1013
1129
  let startLine = 1;
1014
1130
  let currentLine = 1;
@@ -1238,9 +1354,7 @@ var MessageStore = class {
1238
1354
  ensureChat(chatId, isGroup = false) {
1239
1355
  const existing = this.db.prepare(`SELECT id FROM tg_chats WHERE id = ?`).get(chatId);
1240
1356
  if (!existing) {
1241
- this.db.prepare(
1242
- `INSERT INTO tg_chats (id, type, is_monitored) VALUES (?, ?, 1)`
1243
- ).run(chatId, isGroup ? "group" : "dm");
1357
+ this.db.prepare(`INSERT INTO tg_chats (id, type, is_monitored) VALUES (?, ?, 1)`).run(chatId, isGroup ? "group" : "dm");
1244
1358
  }
1245
1359
  }
1246
1360
  /**
@@ -1250,9 +1364,7 @@ var MessageStore = class {
1250
1364
  if (!userId) return;
1251
1365
  const existing = this.db.prepare(`SELECT id FROM tg_users WHERE id = ?`).get(userId);
1252
1366
  if (!existing) {
1253
- this.db.prepare(
1254
- `INSERT INTO tg_users (id) VALUES (?)`
1255
- ).run(userId);
1367
+ this.db.prepare(`INSERT INTO tg_users (id) VALUES (?)`).run(userId);
1256
1368
  }
1257
1369
  }
1258
1370
  /**
@@ -1912,6 +2024,7 @@ export {
1912
2024
  getDatabase,
1913
2025
  closeDatabase,
1914
2026
  NoopEmbeddingProvider,
2027
+ fetchWithTimeout,
1915
2028
  AnthropicEmbeddingProvider,
1916
2029
  LocalEmbeddingProvider,
1917
2030
  createEmbeddingProvider,