@almadar/agent 1.1.3 → 1.1.4

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/dist/index.js CHANGED
@@ -5,7 +5,7 @@ import { exec, spawn } from 'child_process';
5
5
  import * as path from 'path';
6
6
  import { promisify } from 'util';
7
7
  import * as fs4 from 'fs/promises';
8
- import { isStructuredOutputAvailable, getStructuredOutputClient, LLMClient, ANTHROPIC_MODELS, createAnthropicClient, OPENAI_MODELS, createOpenAIClient, DEEPSEEK_MODELS, createDeepSeekClient } from '@almadar/llm';
8
+ import { isStructuredOutputAvailable, getStructuredOutputClient, LLMClient, createRequirementsClient, ANTHROPIC_MODELS, createAnthropicClient, OPENAI_MODELS, createOpenAIClient, DEEPSEEK_MODELS, createDeepSeekClient } from '@almadar/llm';
9
9
  import * as domain_language_star from '@almadar/core/domain-language';
10
10
  import * as fs3 from 'fs';
11
11
  import crypto, { randomUUID } from 'crypto';
@@ -4693,10 +4693,30 @@ ${skillSummaries}
4693
4693
 
4694
4694
  ${skillContents}`;
4695
4695
  }
4696
+ let userPreferences = null;
4697
+ let projectContext = null;
4698
+ if (options.memoryManager && options.userId) {
4699
+ try {
4700
+ userPreferences = await options.memoryManager.getUserPreferences(options.userId);
4701
+ if (userPreferences && verbose) {
4702
+ console.log(`[SkillAgent] Loaded user preferences: ${userPreferences.namingConvention} naming, ${userPreferences.preferredPatterns.length} patterns`);
4703
+ }
4704
+ if (options.appId) {
4705
+ projectContext = await options.memoryManager.getProjectContext(options.appId);
4706
+ if (projectContext && verbose) {
4707
+ console.log(`[SkillAgent] Loaded project context: ${projectContext.existingEntities.length} entities`);
4708
+ }
4709
+ }
4710
+ } catch (error) {
4711
+ console.warn("[SkillAgent] Failed to load memory:", error);
4712
+ }
4713
+ }
4714
+ const memoryContext = buildMemoryContext(userPreferences, projectContext);
4696
4715
  const systemPrompt = [
4697
4716
  BASE_SYSTEM_PROMPT,
4698
4717
  "\n## Skill Instructions\n\n" + skillInstructions,
4699
- references ? "\n## Reference Documentation\n\n" + references : ""
4718
+ references ? "\n## Reference Documentation\n\n" + references : "",
4719
+ memoryContext ? "\n## User Context\n\n" + memoryContext : ""
4700
4720
  ].filter(Boolean).join("\n");
4701
4721
  const threadId = providedThreadId || v4();
4702
4722
  const llmClient = createLLMClient(provider, model, verbose);
@@ -4799,9 +4819,54 @@ ${skillContents}`;
4799
4819
  workDir,
4800
4820
  setOrbitalEventCallback,
4801
4821
  setOrbitalCompleteCallback,
4802
- setDomainCompleteCallback
4822
+ setDomainCompleteCallback,
4823
+ userPreferences,
4824
+ projectContext,
4825
+ memoryManager: options.memoryManager
4803
4826
  };
4804
4827
  }
4828
+ function buildMemoryContext(userPreferences, projectContext) {
4829
+ const sections = [];
4830
+ if (userPreferences) {
4831
+ const prefs = [];
4832
+ if (userPreferences.namingConvention) {
4833
+ prefs.push(`- Preferred naming: ${userPreferences.namingConvention}`);
4834
+ }
4835
+ if (userPreferences.validationStyle) {
4836
+ prefs.push(`- Validation style: ${userPreferences.validationStyle}`);
4837
+ }
4838
+ if (userPreferences.preferredPatterns.length > 0) {
4839
+ prefs.push(`- Preferred patterns: ${userPreferences.preferredPatterns.join(", ")}`);
4840
+ }
4841
+ if (userPreferences.commonEntities.length > 0) {
4842
+ prefs.push(`- Commonly used entities: ${userPreferences.commonEntities.join(", ")}`);
4843
+ }
4844
+ if (prefs.length > 0) {
4845
+ sections.push(`### User Preferences
4846
+ ${prefs.join("\n")}`);
4847
+ }
4848
+ }
4849
+ if (projectContext) {
4850
+ const ctx = [];
4851
+ if (projectContext.projectName) {
4852
+ ctx.push(`- Project: ${projectContext.projectName}`);
4853
+ }
4854
+ if (projectContext.domain) {
4855
+ ctx.push(`- Domain: ${projectContext.domain}`);
4856
+ }
4857
+ if (projectContext.existingEntities.length > 0) {
4858
+ ctx.push(`- Existing entities: ${projectContext.existingEntities.join(", ")}`);
4859
+ }
4860
+ if (projectContext.conventions.length > 0) {
4861
+ ctx.push(`- Project conventions: ${projectContext.conventions.join(", ")}`);
4862
+ }
4863
+ if (ctx.length > 0) {
4864
+ sections.push(`### Project Context
4865
+ ${ctx.join("\n")}`);
4866
+ }
4867
+ }
4868
+ return sections.length > 0 ? sections.join("\n\n") : null;
4869
+ }
4805
4870
  async function resumeSkillAgent(threadId, options) {
4806
4871
  const sessions = options.sessionManager ?? getDefaultSessionManager();
4807
4872
  const metadata = sessions.get(threadId);
@@ -5310,11 +5375,602 @@ function extractFileOperation(event) {
5310
5375
  }
5311
5376
  return null;
5312
5377
  }
5378
+
5379
+ // src/memory/memory-orbital.ts
5380
+ var UserPreferenceEntity = {
5381
+ name: "UserPreference",
5382
+ persistence: "persistent",
5383
+ fields: [
5384
+ { name: "id", type: "string", required: true },
5385
+ { name: "userId", type: "string", required: true },
5386
+ { name: "namingConvention", type: "enum", values: ["PascalCase", "camelCase", "snake_case"], default: "PascalCase" },
5387
+ { name: "validationStyle", type: "enum", values: ["strict", "minimal", "none"], default: "strict" },
5388
+ { name: "preferredPatterns", type: "array", items: { name: "pattern", type: "string" }, default: [] },
5389
+ { name: "commonEntities", type: "array", items: { name: "entity", type: "string" }, default: [] },
5390
+ { name: "commonTraits", type: "array", items: { name: "trait", type: "string" }, default: [] },
5391
+ { name: "learnedAt", type: "timestamp" },
5392
+ { name: "confidence", type: "number", default: 0.5 }
5393
+ ]
5394
+ };
5395
+ var GenerationSessionEntity = {
5396
+ name: "GenerationSession",
5397
+ persistence: "persistent",
5398
+ fields: [
5399
+ { name: "id", type: "string", required: true },
5400
+ { name: "userId", type: "string", required: true },
5401
+ { name: "threadId", type: "string", required: true },
5402
+ { name: "prompt", type: "string", required: true },
5403
+ { name: "skill", type: "string", required: true },
5404
+ { name: "entities", type: "array", items: { name: "entity", type: "string" }, default: [] },
5405
+ { name: "patterns", type: "array", items: { name: "pattern", type: "string" }, default: [] },
5406
+ { name: "createdAt", type: "timestamp", required: true },
5407
+ { name: "completedAt", type: "timestamp" },
5408
+ { name: "success", type: "boolean", default: false }
5409
+ ]
5410
+ };
5411
+ var ProjectContextEntity = {
5412
+ name: "ProjectContext",
5413
+ persistence: "persistent",
5414
+ fields: [
5415
+ { name: "id", type: "string", required: true },
5416
+ { name: "appId", type: "string", required: true },
5417
+ { name: "userId", type: "string", required: true },
5418
+ { name: "projectName", type: "string" },
5419
+ { name: "description", type: "string" },
5420
+ { name: "existingEntities", type: "array", items: { name: "entity", type: "string" }, default: [] },
5421
+ { name: "conventions", type: "array", items: { name: "convention", type: "string" }, default: [] },
5422
+ { name: "domain", type: "enum", values: ["business", "ecommerce", "cms", "dashboard", "workflow"], default: "business" },
5423
+ { name: "lastUpdatedAt", type: "timestamp", required: true }
5424
+ ]
5425
+ };
5426
+ var MemoryOrbitalSchema = {
5427
+ name: "AgentMemory",
5428
+ version: "1.0.0",
5429
+ description: "Memory system for KFlow DeepAgent - stores user preferences, generation history, and project context",
5430
+ orbitals: [
5431
+ {
5432
+ name: "UserPreferenceMemory",
5433
+ entity: UserPreferenceEntity,
5434
+ traits: [],
5435
+ pages: []
5436
+ },
5437
+ {
5438
+ name: "GenerationHistoryMemory",
5439
+ entity: GenerationSessionEntity,
5440
+ traits: [],
5441
+ pages: []
5442
+ },
5443
+ {
5444
+ name: "ProjectContextMemory",
5445
+ entity: ProjectContextEntity,
5446
+ traits: [],
5447
+ pages: []
5448
+ }
5449
+ ]
5450
+ };
5451
+
5452
+ // src/memory/MemoryManager.ts
5453
+ var MemoryManager = class {
5454
+ constructor(options) {
5455
+ this.db = options.db;
5456
+ this.usersCollection = options.usersCollection ?? "agent_memory_users";
5457
+ this.generationsCollection = options.generationsCollection ?? "agent_memory_generations";
5458
+ this.projectsCollection = options.projectsCollection ?? "agent_memory_projects";
5459
+ this.patternsCollection = options.patternsCollection ?? "agent_memory_patterns";
5460
+ this.feedbackCollection = options.feedbackCollection ?? "agent_memory_feedback";
5461
+ }
5462
+ // ============================================================================
5463
+ // User Preferences
5464
+ // ============================================================================
5465
+ /**
5466
+ * Get user preferences with defaults
5467
+ */
5468
+ async getUserPreferences(userId) {
5469
+ const doc = await this.db.collection(this.usersCollection).doc(userId).get();
5470
+ if (!doc.exists) return null;
5471
+ return this.parsePreference(doc.data());
5472
+ }
5473
+ /**
5474
+ * Update user preferences
5475
+ */
5476
+ async updateUserPreferences(userId, preferences) {
5477
+ const existing = await this.getUserPreferences(userId);
5478
+ const merged = {
5479
+ id: existing?.id ?? `pref_${Date.now()}`,
5480
+ userId,
5481
+ namingConvention: preferences.namingConvention ?? existing?.namingConvention ?? "PascalCase",
5482
+ validationStyle: preferences.validationStyle ?? existing?.validationStyle ?? "strict",
5483
+ preferredPatterns: [
5484
+ ...existing?.preferredPatterns ?? [],
5485
+ ...preferences.preferredPatterns ?? []
5486
+ ],
5487
+ commonEntities: [
5488
+ ...existing?.commonEntities ?? [],
5489
+ ...preferences.commonEntities ?? []
5490
+ ],
5491
+ commonTraits: [
5492
+ ...existing?.commonTraits ?? [],
5493
+ ...preferences.commonTraits ?? []
5494
+ ],
5495
+ learnedAt: existing?.learnedAt ?? /* @__PURE__ */ new Date(),
5496
+ confidence: preferences.confidence ?? existing?.confidence ?? 0.5
5497
+ };
5498
+ await this.db.collection(this.usersCollection).doc(userId).set(this.serializePreference(merged));
5499
+ }
5500
+ // ============================================================================
5501
+ // Generation Session History
5502
+ // ============================================================================
5503
+ /**
5504
+ * Record a new generation session
5505
+ */
5506
+ async recordGeneration(userId, session) {
5507
+ const sessionId = `gen_${Date.now()}_${Math.random().toString(36).slice(2)}`;
5508
+ const fullSession = {
5509
+ id: sessionId,
5510
+ userId,
5511
+ createdAt: /* @__PURE__ */ new Date(),
5512
+ ...session
5513
+ };
5514
+ await this.db.collection(this.generationsCollection).doc(sessionId).set(this.serializeSession(fullSession));
5515
+ return sessionId;
5516
+ }
5517
+ /**
5518
+ * Get a specific generation session
5519
+ */
5520
+ async getGenerationSession(sessionId) {
5521
+ const doc = await this.db.collection(this.generationsCollection).doc(sessionId).get();
5522
+ if (!doc.exists) return null;
5523
+ return this.parseSession(doc.data());
5524
+ }
5525
+ /**
5526
+ * Get generation history for a user
5527
+ */
5528
+ async getUserGenerationHistory(userId, limit = 50) {
5529
+ const snapshot = await this.db.collection(this.generationsCollection).where("userId", "==", userId).orderBy("createdAt", "desc").limit(limit).get();
5530
+ return snapshot.docs.map((doc) => this.parseSession(doc.data()));
5531
+ }
5532
+ /**
5533
+ * Update generation session status
5534
+ */
5535
+ async updateGenerationStatus(sessionId, status, validationResult) {
5536
+ const doc = await this.db.collection(this.generationsCollection).doc(sessionId).get();
5537
+ if (!doc.exists) return;
5538
+ const data = doc.data();
5539
+ await this.db.collection(this.generationsCollection).doc(sessionId).set({
5540
+ ...data,
5541
+ success: status,
5542
+ completedAt: /* @__PURE__ */ new Date(),
5543
+ ...validationResult && { validationResult }
5544
+ });
5545
+ }
5546
+ // ============================================================================
5547
+ // Project Context
5548
+ // ============================================================================
5549
+ /**
5550
+ * Get project context
5551
+ */
5552
+ async getProjectContext(appId) {
5553
+ const doc = await this.db.collection(this.projectsCollection).doc(appId).get();
5554
+ if (!doc.exists) return null;
5555
+ return this.parseContext(doc.data());
5556
+ }
5557
+ /**
5558
+ * Update project context with new information
5559
+ */
5560
+ async updateProjectContext(appId, update) {
5561
+ const existing = await this.getProjectContext(appId);
5562
+ if (!existing) {
5563
+ if (!update.userId) {
5564
+ throw new Error("userId is required when creating new project context");
5565
+ }
5566
+ const newContext = {
5567
+ id: `ctx_${Date.now()}`,
5568
+ appId,
5569
+ userId: update.userId,
5570
+ existingEntities: update.existingEntities ?? [],
5571
+ conventions: update.conventions ?? [],
5572
+ domain: update.domain ?? "business",
5573
+ lastUpdatedAt: /* @__PURE__ */ new Date(),
5574
+ ...update.projectName && { projectName: update.projectName },
5575
+ ...update.description && { description: update.description }
5576
+ };
5577
+ await this.db.collection(this.projectsCollection).doc(appId).set(this.serializeContext(newContext));
5578
+ return;
5579
+ }
5580
+ const merged = {
5581
+ ...existing,
5582
+ existingEntities: [
5583
+ ...existing.existingEntities,
5584
+ ...update.existingEntities ?? []
5585
+ ],
5586
+ conventions: [
5587
+ ...existing.conventions,
5588
+ ...update.conventions ?? []
5589
+ ],
5590
+ lastUpdatedAt: /* @__PURE__ */ new Date(),
5591
+ ...update.projectName && { projectName: update.projectName },
5592
+ ...update.description && { description: update.description },
5593
+ ...update.domain && { domain: update.domain }
5594
+ };
5595
+ await this.db.collection(this.projectsCollection).doc(appId).set(this.serializeContext(merged));
5596
+ }
5597
+ // ============================================================================
5598
+ // Pattern Affinity
5599
+ // ============================================================================
5600
+ /**
5601
+ * Update pattern affinity based on usage
5602
+ */
5603
+ async updatePatternAffinity(userId, patternId, outcome, context) {
5604
+ const affinityId = `${userId}_${patternId}`;
5605
+ const existing = await this.db.collection(this.patternsCollection).doc(affinityId).get();
5606
+ if (!existing.exists) {
5607
+ const affinity = {
5608
+ userId,
5609
+ patternId,
5610
+ usageCount: 1,
5611
+ successCount: outcome === "success" ? 1 : 0,
5612
+ failureCount: outcome === "failure" ? 1 : 0,
5613
+ contexts: context ? [context] : [],
5614
+ lastUsedAt: /* @__PURE__ */ new Date(),
5615
+ createdAt: /* @__PURE__ */ new Date()
5616
+ };
5617
+ await this.db.collection(this.patternsCollection).doc(affinityId).set(affinity);
5618
+ } else {
5619
+ const data = existing.data();
5620
+ const affinity = {
5621
+ ...data,
5622
+ usageCount: data.usageCount + 1,
5623
+ successCount: data.successCount + (outcome === "success" ? 1 : 0),
5624
+ failureCount: data.failureCount + (outcome === "failure" ? 1 : 0),
5625
+ contexts: context ? [...data.contexts ?? [], context] : data.contexts,
5626
+ lastUsedAt: /* @__PURE__ */ new Date()
5627
+ };
5628
+ await this.db.collection(this.patternsCollection).doc(affinityId).set(affinity);
5629
+ }
5630
+ }
5631
+ /**
5632
+ * Get pattern affinity for a user
5633
+ */
5634
+ async getPatternAffinity(userId, patternId) {
5635
+ const affinityId = `${userId}_${patternId}`;
5636
+ const doc = await this.db.collection(this.patternsCollection).doc(affinityId).get();
5637
+ if (!doc.exists) return null;
5638
+ return doc.data();
5639
+ }
5640
+ /**
5641
+ * Get all patterns used by a user
5642
+ */
5643
+ async getUserPatterns(userId) {
5644
+ const snapshot = await this.db.collection(this.patternsCollection).where("userId", "==", userId).orderBy("usageCount", "desc").get();
5645
+ return snapshot.docs.map((doc) => doc.data());
5646
+ }
5647
+ // ============================================================================
5648
+ // User Feedback
5649
+ // ============================================================================
5650
+ /**
5651
+ * Record user feedback on a generation
5652
+ */
5653
+ async recordFeedback(sessionId, feedback) {
5654
+ const feedbackId = `fb_${Date.now()}_${Math.random().toString(36).slice(2)}`;
5655
+ const fullFeedback = {
5656
+ feedbackId,
5657
+ sessionId,
5658
+ ...feedback,
5659
+ timestamp: /* @__PURE__ */ new Date()
5660
+ };
5661
+ await this.db.collection(this.feedbackCollection).doc(feedbackId).set(fullFeedback);
5662
+ }
5663
+ /**
5664
+ * Get feedback for a session
5665
+ */
5666
+ async getSessionFeedback(sessionId) {
5667
+ const snapshot = await this.db.collection(this.feedbackCollection).where("sessionId", "==", sessionId).orderBy("timestamp", "desc").get();
5668
+ return snapshot.docs.map((doc) => doc.data());
5669
+ }
5670
+ // ============================================================================
5671
+ // Serialization Helpers
5672
+ // ============================================================================
5673
+ parsePreference(data) {
5674
+ const timestampToDate = (ts) => {
5675
+ if (ts instanceof Date) return ts;
5676
+ if (typeof ts === "object" && ts !== null && "toDate" in ts) {
5677
+ return ts.toDate();
5678
+ }
5679
+ return new Date(ts);
5680
+ };
5681
+ return {
5682
+ id: data.id,
5683
+ userId: data.userId,
5684
+ namingConvention: data.namingConvention,
5685
+ validationStyle: data.validationStyle,
5686
+ preferredPatterns: data.preferredPatterns ?? [],
5687
+ commonEntities: data.commonEntities ?? [],
5688
+ commonTraits: data.commonTraits ?? [],
5689
+ learnedAt: timestampToDate(data.learnedAt),
5690
+ confidence: data.confidence ?? 0.5
5691
+ };
5692
+ }
5693
+ serializePreference(pref) {
5694
+ return { ...pref };
5695
+ }
5696
+ parseSession(data) {
5697
+ const timestampToDate = (ts) => {
5698
+ if (ts instanceof Date) return ts;
5699
+ if (typeof ts === "object" && ts !== null && "toDate" in ts) {
5700
+ return ts.toDate();
5701
+ }
5702
+ return new Date(ts);
5703
+ };
5704
+ return {
5705
+ id: data.id,
5706
+ userId: data.userId,
5707
+ threadId: data.threadId,
5708
+ prompt: data.prompt,
5709
+ skill: data.skill,
5710
+ generatedSchema: data.generatedSchema,
5711
+ entities: data.entities ?? [],
5712
+ patterns: data.patterns ?? [],
5713
+ validationResult: data.validationResult,
5714
+ createdAt: timestampToDate(data.createdAt),
5715
+ completedAt: data.completedAt ? timestampToDate(data.completedAt) : void 0,
5716
+ success: data.success
5717
+ };
5718
+ }
5719
+ serializeSession(session) {
5720
+ return { ...session };
5721
+ }
5722
+ parseContext(data) {
5723
+ const timestampToDate = (ts) => {
5724
+ if (ts instanceof Date) return ts;
5725
+ if (typeof ts === "object" && ts !== null && "toDate" in ts) {
5726
+ return ts.toDate();
5727
+ }
5728
+ return new Date(ts);
5729
+ };
5730
+ return {
5731
+ id: data.id,
5732
+ appId: data.appId,
5733
+ userId: data.userId,
5734
+ projectName: data.projectName,
5735
+ description: data.description,
5736
+ existingEntities: data.existingEntities ?? [],
5737
+ conventions: data.conventions ?? [],
5738
+ domain: data.domain,
5739
+ lastUpdatedAt: timestampToDate(data.lastUpdatedAt)
5740
+ };
5741
+ }
5742
+ serializeContext(context) {
5743
+ return { ...context };
5744
+ }
5745
+ };
5746
+ var PreferenceLearner = class {
5747
+ constructor(options) {
5748
+ this.llmClient = options.llmClient ?? createRequirementsClient();
5749
+ this.memoryManager = options.memoryManager;
5750
+ this.confidenceThreshold = options.confidenceThreshold ?? 0.7;
5751
+ }
5752
+ /**
5753
+ * Analyze a session and infer user preferences
5754
+ */
5755
+ async analyzeSession(session) {
5756
+ const prompt = this.buildAnalysisPrompt(session);
5757
+ const content = await this.llmClient.call({
5758
+ systemPrompt: "You analyze generation sessions and infer user preferences. Respond with JSON.",
5759
+ userPrompt: prompt
5760
+ });
5761
+ return this.parseAnalysisResponse(content);
5762
+ }
5763
+ /**
5764
+ * Learn from a session and update preferences if confidence is high
5765
+ */
5766
+ async learnFromSession(session) {
5767
+ let preferences = await this.memoryManager.getUserPreferences(session.userId);
5768
+ if (!preferences) {
5769
+ preferences = {
5770
+ id: session.userId,
5771
+ userId: session.userId,
5772
+ namingConvention: "PascalCase",
5773
+ validationStyle: "strict",
5774
+ preferredPatterns: [],
5775
+ commonEntities: [],
5776
+ commonTraits: [],
5777
+ learnedAt: /* @__PURE__ */ new Date(),
5778
+ confidence: 0.5
5779
+ };
5780
+ }
5781
+ const analysis = await this.analyzeSession(session);
5782
+ let updated = false;
5783
+ for (const inference of analysis.inferences) {
5784
+ if (inference.confidence >= this.confidenceThreshold) {
5785
+ switch (inference.field) {
5786
+ case "namingConvention":
5787
+ if (this.isValidNamingConvention(inference.value)) {
5788
+ preferences.namingConvention = inference.value;
5789
+ updated = true;
5790
+ }
5791
+ break;
5792
+ case "validationStyle":
5793
+ if (this.isValidValidationStyle(inference.value)) {
5794
+ preferences.validationStyle = inference.value;
5795
+ updated = true;
5796
+ }
5797
+ break;
5798
+ case "preferredPatterns":
5799
+ if (Array.isArray(inference.value)) {
5800
+ preferences.preferredPatterns = [
5801
+ .../* @__PURE__ */ new Set([...preferences.preferredPatterns, ...inference.value])
5802
+ ].slice(0, 10);
5803
+ updated = true;
5804
+ }
5805
+ break;
5806
+ case "commonEntities":
5807
+ if (Array.isArray(inference.value)) {
5808
+ preferences.commonEntities = [
5809
+ .../* @__PURE__ */ new Set([...preferences.commonEntities, ...inference.value])
5810
+ ].slice(0, 20);
5811
+ updated = true;
5812
+ }
5813
+ break;
5814
+ }
5815
+ }
5816
+ }
5817
+ if (updated) {
5818
+ preferences.confidence = Math.min(1, preferences.confidence + 0.05);
5819
+ await this.memoryManager.updateUserPreferences(session.userId, preferences);
5820
+ }
5821
+ return updated ? preferences : null;
5822
+ }
5823
+ /**
5824
+ * Batch learn from multiple sessions
5825
+ */
5826
+ async batchLearn(sessions) {
5827
+ if (sessions.length === 0) return null;
5828
+ const userId = sessions[0].userId;
5829
+ let preferences = await this.memoryManager.getUserPreferences(userId);
5830
+ if (!preferences) {
5831
+ preferences = {
5832
+ id: userId,
5833
+ userId,
5834
+ namingConvention: "PascalCase",
5835
+ validationStyle: "strict",
5836
+ preferredPatterns: [],
5837
+ commonEntities: [],
5838
+ commonTraits: [],
5839
+ learnedAt: /* @__PURE__ */ new Date(),
5840
+ confidence: 0.5
5841
+ };
5842
+ }
5843
+ const allPatterns = /* @__PURE__ */ new Set();
5844
+ const allEntities = /* @__PURE__ */ new Set();
5845
+ for (const session of sessions) {
5846
+ session.patterns.forEach((p) => allPatterns.add(p));
5847
+ session.entities.forEach((e) => allEntities.add(e));
5848
+ }
5849
+ preferences.preferredPatterns = [...allPatterns].slice(0, 10);
5850
+ preferences.commonEntities = [...allEntities].slice(0, 20);
5851
+ preferences.confidence = Math.min(1, 0.5 + sessions.length * 0.05);
5852
+ const aggregatePrompt = this.buildAggregatePrompt(sessions);
5853
+ const content = await this.llmClient.call({
5854
+ systemPrompt: "You analyze generation sessions and infer user preferences. Respond with JSON.",
5855
+ userPrompt: aggregatePrompt
5856
+ });
5857
+ const analysis = this.parseAnalysisResponse(content);
5858
+ for (const inference of analysis.inferences) {
5859
+ if (inference.confidence >= this.confidenceThreshold) {
5860
+ if (inference.field === "namingConvention" && this.isValidNamingConvention(inference.value)) {
5861
+ preferences.namingConvention = inference.value;
5862
+ }
5863
+ if (inference.field === "validationStyle" && this.isValidValidationStyle(inference.value)) {
5864
+ preferences.validationStyle = inference.value;
5865
+ }
5866
+ }
5867
+ }
5868
+ await this.memoryManager.updateUserPreferences(userId, preferences);
5869
+ return preferences;
5870
+ }
5871
+ // ==========================================================================
5872
+ // Prompt Building
5873
+ // ==========================================================================
5874
+ buildAnalysisPrompt(session) {
5875
+ return `Analyze this generation session and infer the user's preferences.
5876
+
5877
+ Session Details:
5878
+ - Prompt: "${session.prompt}"
5879
+ - Generated Entities: ${session.entities.join(", ")}
5880
+ - Used Patterns: ${session.patterns.join(", ")}
5881
+ - Skill: ${session.skill}
5882
+
5883
+ Schema Excerpt:
5884
+ ${JSON.stringify(session.generatedSchema, null, 2).slice(0, 2e3)}
5885
+
5886
+ Analyze and infer:
5887
+ 1. Naming convention preference (PascalCase, camelCase, snake_case)
5888
+ 2. Validation style (strict, minimal, none)
5889
+ 3. Preferred UI patterns
5890
+ 4. Common entity types
5891
+
5892
+ Respond in JSON format:
5893
+ {
5894
+ "inferences": [
5895
+ {
5896
+ "field": "namingConvention",
5897
+ "value": "PascalCase",
5898
+ "confidence": 0.85,
5899
+ "reasoning": "User consistently uses PascalCase for entity names"
5900
+ }
5901
+ ],
5902
+ "isHighConfidence": true
5903
+ }`;
5904
+ }
5905
+ buildAggregatePrompt(sessions) {
5906
+ const summaries = sessions.slice(0, 10).map((s) => ({
5907
+ prompt: s.prompt.slice(0, 100),
5908
+ entities: s.entities,
5909
+ patterns: s.patterns
5910
+ }));
5911
+ return `Analyze these ${sessions.length} generation sessions and infer the user's aggregate preferences.
5912
+
5913
+ Session Summaries:
5914
+ ${JSON.stringify(summaries, null, 2)}
5915
+
5916
+ Infer the user's overall:
5917
+ 1. Naming convention preference (PascalCase, camelCase, snake_case)
5918
+ 2. Validation style (strict, minimal, none)
5919
+
5920
+ Respond in JSON format:
5921
+ {
5922
+ "inferences": [
5923
+ {
5924
+ "field": "namingConvention",
5925
+ "value": "PascalCase",
5926
+ "confidence": 0.9,
5927
+ "reasoning": "Used PascalCase in 8 out of 10 sessions"
5928
+ }
5929
+ ],
5930
+ "isHighConfidence": true
5931
+ }`;
5932
+ }
5933
+ // ==========================================================================
5934
+ // Response Parsing
5935
+ // ==========================================================================
5936
+ parseAnalysisResponse(content) {
5937
+ try {
5938
+ const jsonMatch = content.match(/\{[\s\S]*\}/);
5939
+ if (!jsonMatch) {
5940
+ return { inferences: [], isHighConfidence: false };
5941
+ }
5942
+ const parsed = JSON.parse(jsonMatch[0]);
5943
+ if (Array.isArray(parsed.inferences)) {
5944
+ return {
5945
+ inferences: parsed.inferences.filter(
5946
+ (inf) => inf.field && inf.value !== void 0 && typeof inf.confidence === "number"
5947
+ ),
5948
+ isHighConfidence: parsed.isHighConfidence ?? false
5949
+ };
5950
+ }
5951
+ return { inferences: [], isHighConfidence: false };
5952
+ } catch {
5953
+ return { inferences: [], isHighConfidence: false };
5954
+ }
5955
+ }
5956
+ // ==========================================================================
5957
+ // Validation Helpers
5958
+ // ==========================================================================
5959
+ isValidNamingConvention(value) {
5960
+ return typeof value === "string" && ["PascalCase", "camelCase", "snake_case"].includes(value);
5961
+ }
5962
+ isValidValidationStyle(value) {
5963
+ return typeof value === "string" && ["strict", "minimal", "none"].includes(value);
5964
+ }
5965
+ };
5966
+ function createPreferenceLearner(options) {
5967
+ return new PreferenceLearner(options);
5968
+ }
5313
5969
  var export_applySectionUpdate = domain_language_exports.applySectionUpdate;
5314
5970
  var export_convertDomainToSchema = domain_language_exports.convertDomainToSchema;
5315
5971
  var export_convertSchemaToDomain = domain_language_exports.convertSchemaToDomain;
5316
5972
  var export_deleteSection = domain_language_exports.deleteSection;
5317
5973
 
5318
- export { ContinueRequestSchema, DEFAULT_COMPACTION_CONFIG, EVENT_BUDGETS, ExtractedRequirementsSchema, FirestoreCheckpointer, FirestoreSessionStore, FirestoreStore, GenerateRequestSchema, MemorySessionBackend, MetricsCollector, ResumeRequestSchema, SessionManager, analyzeFailures, export_applySectionUpdate as applySectionUpdate, combineOrbitals, combineOrbitalsToSchema, export_convertDomainToSchema as convertDomainToSchema, export_convertSchemaToDomain as convertSchemaToDomain, createAgentTools, createApplyChunkTool, createCombineSchemasTool, createCompactSystemPrompt, createConstructCombinedDomainTool, createDomainOrbitalTools, createErrorFixerSubagent, createExecuteTool, createExtractChunkTool, createFinishTaskTool, createGenerateOrbitalDomainTool, createGenerateSchemaTool, createOrbitalSubagentTool, createQuerySchemaStructureTool, createSSEEvent, createSchemaChunkingTools, createSchemaGeneratorSubagent, createSkillAgent, createSubagentConfigs, createSubagentEventWrapper, createSubagents, createSummaryPrompt, createSystemPrompt, createTestAnalyzerSubagent, createTraitEventWrapper, createTraitSubagentTool, createValidateSchemaTool, export_deleteSection as deleteSection, estimateCacheSavings, estimateCombineComplexity, estimateTokens, extractFileOperation, extractInterruptData, formatSSEEvent, formatSummary, generateFullOrbital, getBudgetWarningMessage, getEventBudget, getInterruptConfig, hasInterrupt, isCompleteEvent, isErrorEvent, isExecutionEvent, isFileOperation, isSSECompleteEvent, isSSEErrorEvent, isSSEGenerationLogEvent, isSSEInterruptEvent, isSSEMessageEvent, isSSEStartEvent, isSSESubagentEvent, isSSETodoDetailEvent, isSSETodoUpdateEvent, isSSEToolCallEvent, isSchemaEvent, isStartEvent, isTodoUpdate, needsCompaction, parseDeepAgentEvent, parseSSEEvent, resumeSkillAgent, transformAgentEvent, transformAgentEventMulti, validateCommandPaths };
5974
+ export { ContinueRequestSchema, DEFAULT_COMPACTION_CONFIG, EVENT_BUDGETS, ExtractedRequirementsSchema, FirestoreCheckpointer, FirestoreSessionStore, FirestoreStore, GenerateRequestSchema, MemoryManager, MemoryOrbitalSchema, MemorySessionBackend, MetricsCollector, PreferenceLearner, ResumeRequestSchema, SessionManager, analyzeFailures, export_applySectionUpdate as applySectionUpdate, combineOrbitals, combineOrbitalsToSchema, export_convertDomainToSchema as convertDomainToSchema, export_convertSchemaToDomain as convertSchemaToDomain, createAgentTools, createApplyChunkTool, createCombineSchemasTool, createCompactSystemPrompt, createConstructCombinedDomainTool, createDomainOrbitalTools, createErrorFixerSubagent, createExecuteTool, createExtractChunkTool, createFinishTaskTool, createGenerateOrbitalDomainTool, createGenerateSchemaTool, createOrbitalSubagentTool, createPreferenceLearner, createQuerySchemaStructureTool, createSSEEvent, createSchemaChunkingTools, createSchemaGeneratorSubagent, createSkillAgent, createSubagentConfigs, createSubagentEventWrapper, createSubagents, createSummaryPrompt, createSystemPrompt, createTestAnalyzerSubagent, createTraitEventWrapper, createTraitSubagentTool, createValidateSchemaTool, export_deleteSection as deleteSection, estimateCacheSavings, estimateCombineComplexity, estimateTokens, extractFileOperation, extractInterruptData, formatSSEEvent, formatSummary, generateFullOrbital, getBudgetWarningMessage, getEventBudget, getInterruptConfig, hasInterrupt, isCompleteEvent, isErrorEvent, isExecutionEvent, isFileOperation, isSSECompleteEvent, isSSEErrorEvent, isSSEGenerationLogEvent, isSSEInterruptEvent, isSSEMessageEvent, isSSEStartEvent, isSSESubagentEvent, isSSETodoDetailEvent, isSSETodoUpdateEvent, isSSEToolCallEvent, isSchemaEvent, isStartEvent, isTodoUpdate, needsCompaction, parseDeepAgentEvent, parseSSEEvent, resumeSkillAgent, transformAgentEvent, transformAgentEventMulti, validateCommandPaths };
5319
5975
  //# sourceMappingURL=index.js.map
5320
5976
  //# sourceMappingURL=index.js.map