@arcadialdev/arcality 2.4.37 → 2.4.49

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/src/index.ts CHANGED
@@ -2,13 +2,31 @@ import 'dotenv/config';
2
2
  import { showBanner } from './consoleBanner';
3
3
  import { promptAndRunPlaywrightTests } from './testRunner';
4
4
  import { KnowledgeService } from './KnowledgeService';
5
- import { ArcalityClient } from './arcalityClient';
5
+ import { ArcalityClient, validateApiKey } from './arcalityClient';
6
6
  import { loadConfig } from './configLoader';
7
+ import chalk from 'chalk';
7
8
 
8
9
  async function main() {
9
10
  showBanner();
10
11
 
11
12
  const config = loadConfig();
13
+
14
+ // Validar API Key y obtener contexto de organización
15
+ console.log(chalk.blue('Validating API Key...'));
16
+ const auth = await validateApiKey();
17
+ if (auth.valid) {
18
+ const orgId = auth.organization_id || auth.organizationId || auth.OrganizationId;
19
+ if (orgId) {
20
+ process.env.ARCALITY_ORG_ID = orgId;
21
+ console.log(chalk.green(`✅ Session initialized for organization: ${auth.organization_name || auth.organizationName || auth.OrganizationName || orgId}`));
22
+ } else {
23
+ console.warn(chalk.yellow('⚠️ API Key is valid but no organization_id was returned.'));
24
+ }
25
+ } else {
26
+ console.error(chalk.red(`❌ Invalid API Key: ${auth.error || 'Unknown error'}`));
27
+ process.exit(1);
28
+ }
29
+
12
30
  const arcalityClient = new ArcalityClient(config.ARCALITY_API_KEY);
13
31
  const knowledgeService = KnowledgeService.getInstance();
14
32
 
@@ -11,18 +11,32 @@
11
11
  */
12
12
 
13
13
  const getBase = () => process.env.ARCALITY_API_URL ? `${process.env.ARCALITY_API_URL}/api/v1` : null;
14
- const getKey = () => process.env.ARCALITY_API_KEY || '';
15
- const getPid = () => process.env.ARCALITY_PROJECT_ID || '';
14
+ const getKey = () => process.env.ARCALITY_API_KEY || '';
15
+ const getPid = () => process.env.ARCALITY_PROJECT_ID || '';
16
+ const getOrgId = () => process.env.ARCALITY_ORG_ID;
17
+ const getMissionId = () => process.env.ARCALITY_MISSION_ID || EMPTY_GUID;
16
18
 
17
19
  const EMPTY_GUID = '00000000-0000-0000-0000-000000000000';
18
20
 
21
+ let configWarningLogged = false;
22
+
19
23
  function isConfigured(): boolean {
20
24
  const base = getBase();
21
- const key = getKey();
22
- const pid = getPid();
25
+ const key = getKey();
26
+ const pid = getPid();
27
+ const orgId = getOrgId();
23
28
 
24
- if (!base || !key || !pid || pid === EMPTY_GUID) {
25
- // Silencioso — no loguear en cada percepción para no hacer ruido
29
+ if (!base || !key || !pid || pid === EMPTY_GUID || !orgId) {
30
+ if (!configWarningLogged) {
31
+ const missing = [];
32
+ if (!base) missing.push('ARCALITY_API_URL');
33
+ if (!key) missing.push('ARCALITY_API_KEY');
34
+ if (!pid || pid === EMPTY_GUID) missing.push('ARCALITY_PROJECT_ID');
35
+ if (!orgId) missing.push('ARCALITY_ORG_ID');
36
+
37
+ console.warn(`[CollectiveMemory] Service disabled. Missing: ${missing.join(', ')}`);
38
+ configWarningLogged = true;
39
+ }
26
40
  return false;
27
41
  }
28
42
  return true;
@@ -48,6 +62,7 @@ export async function pushRule(rule: {
48
62
  'x-api-key': getKey()
49
63
  },
50
64
  body: JSON.stringify({
65
+ organization_id: getOrgId(),
51
66
  project_id: getPid(),
52
67
  rule_type: rule.rule_type,
53
68
  title: rule.title.substring(0, 100),
@@ -98,6 +113,7 @@ export async function pushField(field: {
98
113
  'x-api-key': getKey()
99
114
  },
100
115
  body: JSON.stringify({
116
+ organization_id: getOrgId(),
101
117
  project_id: getPid(),
102
118
  page_id: field.page_id ?? null,
103
119
  field_identifier: field.field_identifier.substring(0, 100),
@@ -138,6 +154,7 @@ export async function pushKnowledge(knowledge: {
138
154
  'x-api-key': getKey()
139
155
  },
140
156
  body: JSON.stringify({
157
+ organization_id: getOrgId(),
141
158
  project_id: getPid(),
142
159
  doc_type: knowledge.doc_type,
143
160
  title: knowledge.title.substring(0, 150),
@@ -160,13 +177,87 @@ export async function pushKnowledge(knowledge: {
160
177
  }
161
178
  }
162
179
 
180
+ // ─── 4. PROMPT EXECUTION PATTERNS ─────────────────────────────────────────────
181
+
182
+ export async function searchPromptPattern(prompt: string, limit: number = 5): Promise<any[]> {
183
+ if (!isConfigured()) return [];
184
+ try {
185
+ const apiUrl = process.env.ARCALITY_API_URL ? `${process.env.ARCALITY_API_URL}/api/v1/prompt-execution-patterns/search` : `${getBase()}/prompt-execution-patterns/search`;
186
+
187
+ const payload = {
188
+ organization_id: getOrgId(),
189
+ project_id: getPid(),
190
+ prompt: prompt,
191
+ limit: limit
192
+ };
193
+
194
+ console.log(`[PatternSearch] 🔍 Buscando patrones en: ${apiUrl}`);
195
+ console.log(`[PatternSearch] 📦 Payload: ${JSON.stringify(payload, null, 2)}`);
196
+
197
+ const res = await fetch(apiUrl, {
198
+ method: 'POST',
199
+ headers: {
200
+ 'Content-Type': 'application/json',
201
+ 'x-api-key': getKey()
202
+ },
203
+ body: JSON.stringify(payload)
204
+ });
205
+
206
+ if (!res.ok) {
207
+ console.warn(`[PatternSearch] HTTP ${res.status} from ${apiUrl}`);
208
+ return [];
209
+ }
210
+ const data = await res.json();
211
+ const results = Array.isArray(data) ? data : (data.matches || data.results || []);
212
+ console.log(`[PatternSearch] ✅ ${results.length} patrones encontrados.`);
213
+ return results;
214
+ } catch (err: any) {
215
+ console.warn(`[PatternSearch] ⚠️ Error buscando patrones: ${err?.message || 'unknown'}`);
216
+ return [];
217
+ }
218
+ }
219
+
220
+ export async function savePromptPattern(patternData: any): Promise<boolean> {
221
+ if (!isConfigured()) return false;
222
+ try {
223
+ const apiUrl = process.env.ARCALITY_API_URL ? `${process.env.ARCALITY_API_URL}/api/v1/prompt-execution-patterns` : `${getBase()}/prompt-execution-patterns`;
224
+
225
+ const payload = {
226
+ organization_id: getOrgId(),
227
+ project_id: getPid(),
228
+ mission_id: getMissionId(),
229
+ ...patternData
230
+ };
231
+ console.log(`[PatternSave] 📤 POST ${apiUrl} | org=${payload.organization_id} proj=${payload.project_id} mission=${payload.mission_id}`);
232
+
233
+ const res = await fetch(apiUrl, {
234
+ method: 'POST',
235
+ headers: {
236
+ 'Content-Type': 'application/json',
237
+ 'x-api-key': getKey()
238
+ },
239
+ body: JSON.stringify(payload)
240
+ });
241
+
242
+ if (!res.ok) {
243
+ console.warn(`[PatternSave] ⚠️ HTTP ${res.status} al guardar patrón en ${apiUrl}: ${await res.text().catch(() => '')}`);
244
+ } else {
245
+ console.log(`[PatternSave] ✅ Patrón guardado exitosamente.`);
246
+ }
247
+ return res.ok;
248
+ } catch (err: any) {
249
+ console.warn(`[PatternSave] ⚠️ Error guardando patrón: ${err?.message || 'unknown'}`);
250
+ return false;
251
+ }
252
+ }
253
+
163
254
  // ─── HELPER: Obtener campos ya conocidos para deduplicación ─────────────────
164
255
 
165
256
  export async function getKnownFieldIdentifiers(pathUrl: string): Promise<string[]> {
166
257
  if (!isConfigured()) return [];
167
258
  try {
168
259
  const res = await fetch(
169
- `${getBase()}/portal/context?project_id=${getPid()}&path=${encodeURIComponent(pathUrl)}`,
260
+ `${getBase()}/portal/context?organization_id=${getOrgId()}&project_id=${getPid()}&path=${encodeURIComponent(pathUrl)}`,
170
261
  { headers: { 'x-api-key': getKey() } }
171
262
  );
172
263
  if (!res.ok) return [];