@ai.ntellect/core 0.3.3 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/.nvmrc +1 -0
  2. package/README.FR.md +201 -261
  3. package/README.md +208 -260
  4. package/agent/index.ts +199 -216
  5. package/agent/tools/get-rss.ts +64 -0
  6. package/bull.ts +5 -0
  7. package/dist/agent/index.d.ts +29 -26
  8. package/dist/agent/index.js +123 -112
  9. package/dist/agent/tools/get-rss.d.ts +16 -0
  10. package/dist/agent/tools/get-rss.js +62 -0
  11. package/dist/bull.d.ts +1 -0
  12. package/dist/bull.js +9 -0
  13. package/dist/examples/index.d.ts +2 -0
  14. package/dist/examples/index.js +89 -0
  15. package/dist/llm/interpreter/context.d.ts +5 -22
  16. package/dist/llm/interpreter/context.js +8 -9
  17. package/dist/llm/interpreter/index.d.ts +9 -5
  18. package/dist/llm/interpreter/index.js +55 -48
  19. package/dist/llm/memory-manager/context.d.ts +2 -0
  20. package/dist/llm/memory-manager/context.js +22 -0
  21. package/dist/llm/memory-manager/index.d.ts +17 -0
  22. package/dist/llm/memory-manager/index.js +107 -0
  23. package/dist/llm/orchestrator/context.d.ts +2 -10
  24. package/dist/llm/orchestrator/context.js +19 -14
  25. package/dist/llm/orchestrator/index.d.ts +36 -21
  26. package/dist/llm/orchestrator/index.js +122 -88
  27. package/dist/llm/orchestrator/types.d.ts +12 -0
  28. package/dist/llm/orchestrator/types.js +2 -0
  29. package/dist/memory/cache.d.ts +6 -5
  30. package/dist/memory/cache.js +31 -21
  31. package/dist/memory/persistent.d.ts +5 -3
  32. package/dist/memory/persistent.js +89 -73
  33. package/dist/services/redis-cache.d.ts +37 -0
  34. package/dist/services/redis-cache.js +93 -0
  35. package/dist/services/scheduler.d.ts +39 -16
  36. package/dist/services/scheduler.js +81 -103
  37. package/dist/services/telegram-monitor.d.ts +0 -15
  38. package/dist/services/telegram-monitor.js +117 -101
  39. package/dist/test.js +106 -172
  40. package/dist/types.d.ts +38 -7
  41. package/dist/utils/generate-object.d.ts +12 -0
  42. package/dist/utils/generate-object.js +90 -0
  43. package/dist/utils/header-builder.d.ts +11 -0
  44. package/dist/utils/header-builder.js +34 -0
  45. package/dist/utils/inject-actions.js +2 -2
  46. package/dist/utils/queue-item-transformer.d.ts +2 -2
  47. package/dist/utils/schema-generator.d.ts +16 -0
  48. package/dist/utils/schema-generator.js +46 -0
  49. package/examples/index.ts +103 -0
  50. package/llm/interpreter/context.ts +20 -8
  51. package/llm/interpreter/index.ts +81 -54
  52. package/llm/memory-manager/context.ts +21 -0
  53. package/llm/memory-manager/index.ts +163 -0
  54. package/llm/orchestrator/context.ts +20 -13
  55. package/llm/orchestrator/index.ts +210 -130
  56. package/llm/orchestrator/types.ts +14 -0
  57. package/memory/cache.ts +37 -31
  58. package/memory/persistent.ts +121 -99
  59. package/package.json +11 -2
  60. package/services/redis-cache.ts +128 -0
  61. package/services/scheduler.ts +102 -141
  62. package/services/telegram-monitor.ts +138 -138
  63. package/t.py +79 -0
  64. package/t.spec +38 -0
  65. package/types.ts +40 -7
  66. package/utils/generate-object.ts +105 -0
  67. package/utils/header-builder.ts +40 -0
  68. package/utils/inject-actions.ts +4 -6
  69. package/utils/queue-item-transformer.ts +2 -1
  70. package/utils/schema-generator.ts +73 -0
  71. package/agent/handlers/ActionHandler.ts +0 -48
  72. package/agent/handlers/ConfirmationHandler.ts +0 -37
  73. package/agent/handlers/EventHandler.ts +0 -35
  74. package/dist/agent/handlers/ActionHandler.d.ts +0 -8
  75. package/dist/agent/handlers/ActionHandler.js +0 -36
  76. package/dist/agent/handlers/ConfirmationHandler.d.ts +0 -7
  77. package/dist/agent/handlers/ConfirmationHandler.js +0 -31
  78. package/dist/agent/handlers/EventHandler.d.ts +0 -10
  79. package/dist/agent/handlers/EventHandler.js +0 -34
  80. package/dist/llm/evaluator/context.d.ts +0 -10
  81. package/dist/llm/evaluator/context.js +0 -24
  82. package/dist/llm/evaluator/index.d.ts +0 -16
  83. package/dist/llm/evaluator/index.js +0 -150
  84. package/llm/evaluator/context.ts +0 -21
  85. package/llm/evaluator/index.ts +0 -193
@@ -1,167 +1,128 @@
1
- import { Orchestrator } from "../llm/orchestrator";
2
- import { ActionSchema, ScheduledAction, ScheduledActionEvents } from "../types";
3
- import { ActionQueueManager } from "./queue";
4
-
5
- export class ActionScheduler {
6
- private scheduledActions: Map<string, NodeJS.Timeout> = new Map();
7
- private storage: ScheduledActionStorage;
8
- private events: ScheduledActionEvents;
9
-
10
- constructor(
11
- private actionQueueManager: ActionQueueManager,
12
- private orchestrator: Orchestrator,
13
- events: ScheduledActionEvents = {}
14
- ) {
15
- this.storage = new ScheduledActionStorage();
16
- this.events = events;
17
- this.initializeScheduledActions();
1
+ import cron from "node-cron";
2
+ import { AgentRuntime } from "../llm/orchestrator";
3
+ import { RedisCache } from "./redis-cache";
4
+
5
+ interface ScheduledRequest {
6
+ id: string;
7
+ originalRequest: string;
8
+ cronExpression: string;
9
+ isRecurring: boolean;
10
+ createdAt: Date;
11
+ }
12
+
13
+ export class TaskScheduler {
14
+ private scheduledRequests: Map<string, ScheduledRequest> = new Map();
15
+ private cronJobs: Map<string, cron.ScheduledTask> = new Map();
16
+ private readonly agentRuntime: AgentRuntime;
17
+ private readonly cache: RedisCache;
18
+
19
+ constructor(agentRuntime: AgentRuntime, cache: RedisCache) {
20
+ this.agentRuntime = agentRuntime;
21
+ this.cache = cache;
18
22
  }
19
23
 
20
- async scheduleAction(
21
- action: ActionSchema,
22
- scheduledTime: Date,
23
- userId: string,
24
- recurrence?: ScheduledAction["recurrence"]
25
- ): Promise<string> {
26
- const scheduledAction: ScheduledAction = {
27
- id: crypto.randomUUID(),
28
- action: {
29
- name: action.name,
30
- parameters: [],
31
- },
32
- scheduledTime,
33
- userId,
34
- status: "pending",
35
- recurrence,
24
+ /**
25
+ * Schedule a new request to be processed later
26
+ */
27
+ async scheduleRequest(request: {
28
+ originalRequest: string;
29
+ cronExpression: string;
30
+ }): Promise<string> {
31
+ const id = crypto.randomUUID();
32
+
33
+ const scheduledRequest: ScheduledRequest = {
34
+ id,
35
+ originalRequest: request.originalRequest,
36
+ cronExpression: request.cronExpression,
37
+ isRecurring: false,
38
+ createdAt: new Date(),
36
39
  };
37
40
 
38
- await this.storage.saveScheduledAction(scheduledAction);
39
- this.scheduleExecution(scheduledAction);
40
- this.events.onActionScheduled?.(scheduledAction);
41
+ // Create cron job
42
+ const cronJob = cron.schedule(request.cronExpression, async () => {
43
+ await this.executeScheduledRequest(scheduledRequest);
41
44
 
42
- return scheduledAction.id;
43
- }
45
+ if (!scheduledRequest.isRecurring) {
46
+ this.cancelScheduledRequest(id);
47
+ }
48
+ });
44
49
 
45
- private async initializeScheduledActions() {
46
- const pendingActions = await this.storage.getPendingActions();
47
- pendingActions.forEach((action) => this.scheduleExecution(action));
48
- }
50
+ // Store request and job
51
+ this.scheduledRequests.set(id, scheduledRequest);
52
+ this.cronJobs.set(id, cronJob);
49
53
 
50
- private scheduleExecution(scheduledAction: ScheduledAction) {
51
- const now = new Date();
52
- const delay = scheduledAction.scheduledTime.getTime() - now.getTime();
53
-
54
- if (delay < 0) return;
55
-
56
- const timeout = setTimeout(async () => {
57
- try {
58
- await this.executeScheduledAction(scheduledAction);
59
-
60
- if (scheduledAction.recurrence) {
61
- const nextExecutionTime = this.calculateNextExecutionTime(
62
- scheduledAction.scheduledTime,
63
- scheduledAction.recurrence
64
- );
65
- const actionSchema = this.orchestrator.tools.find(
66
- (tool: ActionSchema) => tool.name === scheduledAction.action.name
67
- );
68
- if (actionSchema) {
69
- await this.scheduleAction(
70
- actionSchema,
71
- nextExecutionTime,
72
- scheduledAction.userId,
73
- scheduledAction.recurrence
74
- );
75
- }
76
- }
77
- } catch (error) {
78
- console.error(
79
- `Failed to execute scheduled action ${scheduledAction.id}:`,
80
- error
81
- );
82
- await this.storage.updateActionStatus(scheduledAction.id, "failed");
83
- }
84
- }, delay);
54
+ console.log(
55
+ `✅ Request scheduled with cron expression: ${request.cronExpression}`
56
+ );
85
57
 
86
- this.scheduledActions.set(scheduledAction.id, timeout);
58
+ return id;
87
59
  }
88
60
 
89
- private async executeScheduledAction(scheduledAction: ScheduledAction) {
61
+ /**
62
+ * Execute a scheduled request by launching a new process
63
+ */
64
+ private async executeScheduledRequest(
65
+ request: ScheduledRequest
66
+ ): Promise<void> {
90
67
  try {
91
- this.events.onActionStart?.(scheduledAction);
92
-
93
- this.actionQueueManager.addToQueue({
94
- name: scheduledAction.action.name,
95
- parameters: scheduledAction.action.parameters,
68
+ console.log(`🔄 Executing scheduled request from ${request.createdAt}`);
69
+
70
+ // Récupérer les actions précédentes du cache
71
+ const previousActions = await this.cache.getPreviousActions(request.id);
72
+
73
+ // Add context about when this request was scheduled
74
+ const contextualRequest = `You are a scheduler.
75
+ You were asked to execute this request: ${request.originalRequest}\n
76
+ Date of the request: ${request.createdAt.toISOString()}\n
77
+ Act like if you know the request was scheduled.
78
+ Don't reschedule the same action.
79
+ Just execute it.`;
80
+
81
+ // Process the request as if it was just received
82
+ const result = await this.agentRuntime.process({
83
+ currentContext: contextualRequest,
84
+ previousActions,
96
85
  });
97
86
 
98
- const result = await this.actionQueueManager.processQueue();
99
- await this.storage.updateActionStatus(scheduledAction.id, "completed");
87
+ // Store the new actions in cache
88
+ if (result.actions.length > 0) {
89
+ await this.cache.storePreviousActions(request.id, result.actions);
90
+ }
100
91
 
101
- this.events.onActionComplete?.(scheduledAction, result);
92
+ console.log(`✅ Scheduled request executed successfully`);
102
93
  } catch (error) {
103
- await this.storage.updateActionStatus(scheduledAction.id, "failed");
104
- this.events.onActionFailed?.(scheduledAction, error as Error);
105
- throw error;
94
+ console.error(`❌ Failed to execute scheduled request:`, error);
106
95
  }
107
96
  }
108
97
 
109
- private calculateNextExecutionTime(
110
- currentTime: Date,
111
- recurrence: NonNullable<ScheduledAction["recurrence"]>
112
- ): Date {
113
- const nextTime = new Date(currentTime);
114
-
115
- switch (recurrence.type) {
116
- case "daily":
117
- nextTime.setDate(nextTime.getDate() + recurrence.interval);
118
- break;
119
- case "weekly":
120
- nextTime.setDate(nextTime.getDate() + 7 * recurrence.interval);
121
- break;
122
- case "monthly":
123
- nextTime.setMonth(nextTime.getMonth() + recurrence.interval);
124
- break;
98
+ /**
99
+ * Cancel a scheduled request
100
+ */
101
+ cancelScheduledRequest(requestId: string): boolean {
102
+ const cronJob = this.cronJobs.get(requestId);
103
+ if (cronJob) {
104
+ cronJob.stop();
105
+ this.cronJobs.delete(requestId);
125
106
  }
126
-
127
- return nextTime;
107
+ return this.scheduledRequests.delete(requestId);
128
108
  }
129
109
 
130
- async cancelScheduledAction(actionId: string): Promise<boolean> {
131
- const timeout = this.scheduledActions.get(actionId);
132
- if (timeout) {
133
- clearTimeout(timeout);
134
- this.scheduledActions.delete(actionId);
135
- await this.storage.deleteScheduledAction(actionId);
136
- this.events.onActionCancelled?.(actionId);
137
- return true;
138
- }
139
- return false;
140
- }
141
- }
142
-
143
- class ScheduledActionStorage {
144
- private actions: ScheduledAction[] = [];
145
-
146
- async saveScheduledAction(action: ScheduledAction): Promise<void> {
147
- this.actions.push(action);
110
+ /**
111
+ * Get all scheduled requests
112
+ */
113
+ getScheduledRequests(): ScheduledRequest[] {
114
+ return Array.from(this.scheduledRequests.values());
148
115
  }
149
116
 
150
- async getPendingActions(): Promise<ScheduledAction[]> {
151
- return this.actions.filter((action) => action.status === "pending");
152
- }
153
-
154
- async updateActionStatus(
155
- actionId: string,
156
- status: ScheduledAction["status"]
157
- ): Promise<void> {
158
- const action = this.actions.find((a) => a.id === actionId);
159
- if (action) {
160
- action.status = status;
117
+ /**
118
+ * Stop all cron jobs
119
+ */
120
+ stopAll(): void {
121
+ for (const [id, cronJob] of this.cronJobs) {
122
+ cronJob.stop();
123
+ this.cronJobs.delete(id);
124
+ this.scheduledRequests.delete(id);
161
125
  }
162
- }
163
-
164
- async deleteScheduledAction(actionId: string): Promise<void> {
165
- this.actions = this.actions.filter((a) => a.id !== actionId);
126
+ console.log("All scheduled requests stopped");
166
127
  }
167
128
  }
@@ -1,138 +1,138 @@
1
- import dotenv from "dotenv";
2
- import promptSync from "prompt-sync";
3
- import { TelegramClient } from "telegram";
4
- import { NewMessage } from "telegram/events";
5
- import { StringSession } from "telegram/sessions";
6
-
7
- dotenv.config();
8
-
9
- const prompt = promptSync({ sigint: true });
10
-
11
- export interface TokenLaunch {
12
- tokenAddress: string;
13
- messageUrl: string;
14
- timestamp: string;
15
- }
16
-
17
- export class TelegramMonitor {
18
- private client: TelegramClient;
19
- private botStartTime: Date;
20
-
21
- constructor() {
22
- if (!process.env.TELEGRAM_API_ID || !process.env.TELEGRAM_API_HASH) {
23
- throw new Error("TELEGRAM_API_ID and TELEGRAM_API_HASH must be set");
24
- }
25
- this.botStartTime = new Date();
26
-
27
- const apiId = parseInt(process.env.TELEGRAM_API_ID);
28
- const apiHash = process.env.TELEGRAM_API_HASH;
29
-
30
- // Utiliser une session stockée si disponible
31
- const sessionString = process.env.TELEGRAM_SESSION;
32
- this.client = new TelegramClient(
33
- new StringSession(sessionString),
34
- apiId,
35
- apiHash,
36
- {
37
- connectionRetries: 5,
38
- }
39
- );
40
- }
41
-
42
- async connect() {
43
- // Se connecter en tant qu'utilisateur
44
- await this.client.start({
45
- phoneNumber: async () => prompt("Numéro de téléphone ? "),
46
- password: async () => prompt("Mot de passe ? "),
47
- phoneCode: async () => prompt("Code reçu ? "),
48
- onError: (err) => console.log(err),
49
- });
50
-
51
- // Sauvegarder la session pour une utilisation ultérieure
52
- console.log("Session string à sauvegarder:", this.client.session.save());
53
- }
54
-
55
- async startMonitoring(
56
- channelUsername: string,
57
- callback: {
58
- onNewLaunch: (message: string) => void;
59
- }
60
- ) {
61
- console.log(`Démarrage du monitoring pour ${channelUsername}`);
62
-
63
- try {
64
- // S'assurer que le client est connecté
65
- if (!this.client.connected) {
66
- console.log("Client non connecté, tentative de connexion...");
67
- await this.client.connect();
68
- console.log("Client connecté avec succès");
69
- }
70
-
71
- console.log("État de la connexion:", this.client.connected);
72
-
73
- // Vérifier si le canal existe et est accessible
74
- try {
75
- const channel = await this.client.getEntity(channelUsername);
76
- console.log("Canal trouvé:", channel.id);
77
- } catch (e) {
78
- console.error("Erreur lors de l'accès au canal:", e);
79
- }
80
-
81
- this.client.addEventHandler(async (event: any) => {
82
- const message = event.message;
83
- if (!message) {
84
- console.log("Pas de message dans l'événement");
85
- return;
86
- }
87
-
88
- if (!message.text) {
89
- console.log("Message sans texte:", message);
90
- return;
91
- }
92
-
93
- try {
94
- callback.onNewLaunch(message.text);
95
- } catch (error) {
96
- console.error("Erreur lors du traitement du message:", error);
97
- }
98
- }, new NewMessage({ chats: [channelUsername] }));
99
-
100
- console.log("Handler d'événements ajouté avec succès");
101
- } catch (error) {
102
- console.error("Erreur lors du démarrage du monitoring:", error);
103
- }
104
- }
105
-
106
- static async generateNewSession() {
107
- // Supprimer la session existante
108
- const client = new TelegramClient(
109
- new StringSession(""),
110
- parseInt(process.env.TELEGRAM_API_ID || ""),
111
- process.env.TELEGRAM_API_HASH || "",
112
- {
113
- connectionRetries: 5,
114
- }
115
- );
116
-
117
- // Se connecter en tant qu'utilisateur
118
- await client.start({
119
- phoneNumber: async () => prompt("Numéro de téléphone ? "),
120
- password: async () => prompt("Mot de passe ? "),
121
- phoneCode: async () => prompt("Code reçu ? "),
122
- onError: (err) => console.log(err),
123
- });
124
-
125
- // Sauvegarder la nouvelle session pour une utilisation ultérieure
126
- console.log(
127
- "Nouvelle session string à sauvegarder:",
128
- client.session.save()
129
- );
130
- }
131
- }
132
-
133
- const telegramMonitor = new TelegramMonitor();
134
- telegramMonitor.startMonitoring("testcalldegen", {
135
- onNewLaunch: (message: string) => {
136
- console.log("Nouveau message:", message);
137
- },
138
- });
1
+ // import dotenv from "dotenv";
2
+ // import promptSync from "prompt-sync";
3
+ // import { TelegramClient } from "telegram";
4
+ // import { NewMessage } from "telegram/events";
5
+ // import { StringSession } from "telegram/sessions";
6
+
7
+ // dotenv.config();
8
+
9
+ // const prompt = promptSync({ sigint: true });
10
+
11
+ // export interface TokenLaunch {
12
+ // tokenAddress: string;
13
+ // messageUrl: string;
14
+ // timestamp: string;
15
+ // }
16
+
17
+ // export class TelegramMonitor {
18
+ // private client: TelegramClient;
19
+ // private botStartTime: Date;
20
+
21
+ // constructor() {
22
+ // if (!process.env.TELEGRAM_API_ID || !process.env.TELEGRAM_API_HASH) {
23
+ // throw new Error("TELEGRAM_API_ID and TELEGRAM_API_HASH must be set");
24
+ // }
25
+ // this.botStartTime = new Date();
26
+
27
+ // const apiId = parseInt(process.env.TELEGRAM_API_ID);
28
+ // const apiHash = process.env.TELEGRAM_API_HASH;
29
+
30
+ // // Utiliser une session stockée si disponible
31
+ // const sessionString = process.env.TELEGRAM_SESSION;
32
+ // this.client = new TelegramClient(
33
+ // new StringSession(sessionString),
34
+ // apiId,
35
+ // apiHash,
36
+ // {
37
+ // connectionRetries: 5,
38
+ // }
39
+ // );
40
+ // }
41
+
42
+ // async connect() {
43
+ // // Se connecter en tant qu'utilisateur
44
+ // await this.client.start({
45
+ // phoneNumber: async () => prompt("Numéro de téléphone ? "),
46
+ // password: async () => prompt("Mot de passe ? "),
47
+ // phoneCode: async () => prompt("Code reçu ? "),
48
+ // onError: (err) => console.log(err),
49
+ // });
50
+
51
+ // // Sauvegarder la session pour une utilisation ultérieure
52
+ // console.log("Session string à sauvegarder:", this.client.session.save());
53
+ // }
54
+
55
+ // async startMonitoring(
56
+ // channelUsername: string,
57
+ // callback: {
58
+ // onNewLaunch: (message: string) => void;
59
+ // }
60
+ // ) {
61
+ // console.log(`Démarrage du monitoring pour ${channelUsername}`);
62
+
63
+ // try {
64
+ // // S'assurer que le client est connecté
65
+ // if (!this.client.connected) {
66
+ // console.log("Client non connecté, tentative de connexion...");
67
+ // await this.client.connect();
68
+ // console.log("Client connecté avec succès");
69
+ // }
70
+
71
+ // console.log("État de la connexion:", this.client.connected);
72
+
73
+ // // Vérifier si le canal existe et est accessible
74
+ // try {
75
+ // const channel = await this.client.getEntity(channelUsername);
76
+ // console.log("Canal trouvé:", channel.id);
77
+ // } catch (e) {
78
+ // console.error("Erreur lors de l'accès au canal:", e);
79
+ // }
80
+
81
+ // this.client.addEventHandler(async (event: any) => {
82
+ // const message = event.message;
83
+ // if (!message) {
84
+ // console.log("Pas de message dans l'événement");
85
+ // return;
86
+ // }
87
+
88
+ // if (!message.text) {
89
+ // console.log("Message sans texte:", message);
90
+ // return;
91
+ // }
92
+
93
+ // try {
94
+ // callback.onNewLaunch(message.text);
95
+ // } catch (error) {
96
+ // console.error("Erreur lors du traitement du message:", error);
97
+ // }
98
+ // }, new NewMessage({ chats: [channelUsername] }));
99
+
100
+ // console.log("Handler d'événements ajouté avec succès");
101
+ // } catch (error) {
102
+ // console.error("Erreur lors du démarrage du monitoring:", error);
103
+ // }
104
+ // }
105
+
106
+ // static async generateNewSession() {
107
+ // // Supprimer la session existante
108
+ // const client = new TelegramClient(
109
+ // new StringSession(""),
110
+ // parseInt(process.env.TELEGRAM_API_ID || ""),
111
+ // process.env.TELEGRAM_API_HASH || "",
112
+ // {
113
+ // connectionRetries: 5,
114
+ // }
115
+ // );
116
+
117
+ // // Se connecter en tant qu'utilisateur
118
+ // await client.start({
119
+ // phoneNumber: async () => prompt("Numéro de téléphone ? "),
120
+ // password: async () => prompt("Mot de passe ? "),
121
+ // phoneCode: async () => prompt("Code reçu ? "),
122
+ // onError: (err) => console.log(err),
123
+ // });
124
+
125
+ // // Sauvegarder la nouvelle session pour une utilisation ultérieure
126
+ // console.log(
127
+ // "Nouvelle session string à sauvegarder:",
128
+ // client.session.save()
129
+ // );
130
+ // }
131
+ // }
132
+
133
+ // const telegramMonitor = new TelegramMonitor();
134
+ // telegramMonitor.startMonitoring("testcalldegen", {
135
+ // onNewLaunch: (message: string) => {
136
+ // console.log("Nouveau message:", message);
137
+ // },
138
+ // });
package/t.py ADDED
@@ -0,0 +1,79 @@
1
+ import os
2
+ import platform
3
+ import subprocess
4
+ import urllib.request
5
+ import sys
6
+
7
+ def download_meilisearch():
8
+ """Download the Meilisearch binary for the current OS."""
9
+ print("Checking operating system...")
10
+ os_name = platform.system().lower()
11
+ if os_name == "windows":
12
+ binary_url = "https://github.com/meilisearch/meilisearch/releases/latest/download/meilisearch-windows-amd64.exe"
13
+ binary_name = "meilisearch.exe"
14
+ elif os_name == "darwin": # macOS
15
+ binary_url = "https://github.com/meilisearch/meilisearch/releases/latest/download/meilisearch-macos-amd64"
16
+ binary_name = "meilisearch"
17
+ elif os_name == "linux":
18
+ binary_url = "https://github.com/meilisearch/meilisearch/releases/latest/download/meilisearch-linux-amd64"
19
+ binary_name = "meilisearch"
20
+ else:
21
+ print(f"Unsupported operating system: {os_name}")
22
+ sys.exit(1)
23
+
24
+ # Download the binary
25
+ if not os.path.exists(binary_name):
26
+ print(f"Downloading Meilisearch binary for {os_name}...")
27
+ try:
28
+ urllib.request.urlretrieve(binary_url, binary_name)
29
+ print("Download complete.")
30
+ except Exception as e:
31
+ print(f"Failed to download Meilisearch: {e}")
32
+ sys.exit(1)
33
+
34
+ # Add execute permissions for Linux/macOS
35
+ if os_name != "windows":
36
+ os.chmod(binary_name, 0o755)
37
+ else:
38
+ print("Meilisearch binary already exists.")
39
+
40
+ return binary_name
41
+
42
+
43
+ def create_data_directory():
44
+ """Create a directory for Meilisearch data if it doesn't exist."""
45
+ data_dir = "./data"
46
+ if not os.path.exists(data_dir):
47
+ print("Creating data directory...")
48
+ os.makedirs(data_dir)
49
+ else:
50
+ print("Data directory already exists.")
51
+ return data_dir
52
+
53
+ def launch_meilisearch(binary_name, data_dir):
54
+ """Launch the Meilisearch server."""
55
+ print("Launching Meilisearch...")
56
+ try:
57
+ process = subprocess.Popen(
58
+ [
59
+ f"./{binary_name}" if platform.system().lower() != "windows" else binary_name,
60
+ "--db-path",
61
+ data_dir,
62
+ "--master-key",
63
+ "DEFAULT_MASTER_KEY",
64
+ ],
65
+ stdout=subprocess.PIPE,
66
+ stderr=subprocess.PIPE,
67
+ )
68
+ print("Meilisearch is running! Access it at http://localhost:7700")
69
+ for line in iter(process.stdout.readline, b""):
70
+ print("Meilisearch Log:", line.decode().strip())
71
+ except Exception as e:
72
+ print(f"Failed to launch Meilisearch: {e}")
73
+ sys.exit(1)
74
+
75
+
76
+ if __name__ == "__main__":
77
+ binary = download_meilisearch()
78
+ data_directory = create_data_directory()
79
+ launch_meilisearch(binary, data_directory)
package/t.spec ADDED
@@ -0,0 +1,38 @@
1
+ # -*- mode: python ; coding: utf-8 -*-
2
+
3
+
4
+ a = Analysis(
5
+ ['t.py'],
6
+ pathex=[],
7
+ binaries=[],
8
+ datas=[],
9
+ hiddenimports=[],
10
+ hookspath=[],
11
+ hooksconfig={},
12
+ runtime_hooks=[],
13
+ excludes=[],
14
+ noarchive=False,
15
+ optimize=0,
16
+ )
17
+ pyz = PYZ(a.pure)
18
+
19
+ exe = EXE(
20
+ pyz,
21
+ a.scripts,
22
+ a.binaries,
23
+ a.datas,
24
+ [],
25
+ name='t',
26
+ debug=False,
27
+ bootloader_ignore_signals=False,
28
+ strip=False,
29
+ upx=True,
30
+ upx_exclude=[],
31
+ runtime_tmpdir=None,
32
+ console=True,
33
+ disable_windowed_traceback=False,
34
+ argv_emulation=False,
35
+ target_arch=None,
36
+ codesign_identity=None,
37
+ entitlements_file=None,
38
+ )