@agenticmail/enterprise 0.5.259 → 0.5.261

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,45 @@
1
+ import {
2
+ AgentRuntime,
3
+ EmailChannel,
4
+ FollowUpScheduler,
5
+ SessionManager,
6
+ SubAgentManager,
7
+ ToolRegistry,
8
+ callLLM,
9
+ createAgentRuntime,
10
+ createNoopHooks,
11
+ createRuntimeHooks,
12
+ estimateMessageTokens,
13
+ estimateTokens,
14
+ executeTool,
15
+ runAgentLoop,
16
+ toolsToDefinitions
17
+ } from "./chunk-PHQXZJVW.js";
18
+ import {
19
+ PROVIDER_REGISTRY,
20
+ listAllProviders,
21
+ resolveApiKeyForProvider,
22
+ resolveProvider
23
+ } from "./chunk-UF3ZJMJO.js";
24
+ import "./chunk-KFQGP6VL.js";
25
+ export {
26
+ AgentRuntime,
27
+ EmailChannel,
28
+ FollowUpScheduler,
29
+ PROVIDER_REGISTRY,
30
+ SessionManager,
31
+ SubAgentManager,
32
+ ToolRegistry,
33
+ callLLM,
34
+ createAgentRuntime,
35
+ createNoopHooks,
36
+ createRuntimeHooks,
37
+ estimateMessageTokens,
38
+ estimateTokens,
39
+ executeTool,
40
+ listAllProviders,
41
+ resolveApiKeyForProvider,
42
+ resolveProvider,
43
+ runAgentLoop,
44
+ toolsToDefinitions
45
+ };
@@ -0,0 +1,45 @@
1
+ import {
2
+ AgentRuntime,
3
+ EmailChannel,
4
+ FollowUpScheduler,
5
+ SessionManager,
6
+ SubAgentManager,
7
+ ToolRegistry,
8
+ callLLM,
9
+ createAgentRuntime,
10
+ createNoopHooks,
11
+ createRuntimeHooks,
12
+ estimateMessageTokens,
13
+ estimateTokens,
14
+ executeTool,
15
+ runAgentLoop,
16
+ toolsToDefinitions
17
+ } from "./chunk-BHXKIZGM.js";
18
+ import {
19
+ PROVIDER_REGISTRY,
20
+ listAllProviders,
21
+ resolveApiKeyForProvider,
22
+ resolveProvider
23
+ } from "./chunk-UF3ZJMJO.js";
24
+ import "./chunk-KFQGP6VL.js";
25
+ export {
26
+ AgentRuntime,
27
+ EmailChannel,
28
+ FollowUpScheduler,
29
+ PROVIDER_REGISTRY,
30
+ SessionManager,
31
+ SubAgentManager,
32
+ ToolRegistry,
33
+ callLLM,
34
+ createAgentRuntime,
35
+ createNoopHooks,
36
+ createRuntimeHooks,
37
+ estimateMessageTokens,
38
+ estimateTokens,
39
+ executeTool,
40
+ listAllProviders,
41
+ resolveApiKeyForProvider,
42
+ resolveProvider,
43
+ runAgentLoop,
44
+ toolsToDefinitions
45
+ };
@@ -0,0 +1,15 @@
1
+ import {
2
+ createServer
3
+ } from "./chunk-GW65LEIJ.js";
4
+ import "./chunk-OF4MUWWS.js";
5
+ import "./chunk-UF3ZJMJO.js";
6
+ import "./chunk-3OC6RH7W.js";
7
+ import "./chunk-2DDKGTD6.js";
8
+ import "./chunk-YVK6F5OD.js";
9
+ import "./chunk-MKRNEM5A.js";
10
+ import "./chunk-DRXMYYKN.js";
11
+ import "./chunk-6WSX7QXF.js";
12
+ import "./chunk-KFQGP6VL.js";
13
+ export {
14
+ createServer
15
+ };
@@ -0,0 +1,15 @@
1
+ import {
2
+ createServer
3
+ } from "./chunk-S4KFD3GO.js";
4
+ import "./chunk-OF4MUWWS.js";
5
+ import "./chunk-UF3ZJMJO.js";
6
+ import "./chunk-3OC6RH7W.js";
7
+ import "./chunk-2DDKGTD6.js";
8
+ import "./chunk-YVK6F5OD.js";
9
+ import "./chunk-MKRNEM5A.js";
10
+ import "./chunk-DRXMYYKN.js";
11
+ import "./chunk-6WSX7QXF.js";
12
+ import "./chunk-KFQGP6VL.js";
13
+ export {
14
+ createServer
15
+ };
@@ -0,0 +1,20 @@
1
+ import {
2
+ promptCompanyInfo,
3
+ promptDatabase,
4
+ promptDeployment,
5
+ promptDomain,
6
+ promptRegistration,
7
+ provision,
8
+ runSetupWizard
9
+ } from "./chunk-MTD6I7DM.js";
10
+ import "./chunk-ULRBF2T7.js";
11
+ import "./chunk-KFQGP6VL.js";
12
+ export {
13
+ promptCompanyInfo,
14
+ promptDatabase,
15
+ promptDeployment,
16
+ promptDomain,
17
+ promptRegistration,
18
+ provision,
19
+ runSetupWizard
20
+ };
@@ -0,0 +1,20 @@
1
+ import {
2
+ promptCompanyInfo,
3
+ promptDatabase,
4
+ promptDeployment,
5
+ promptDomain,
6
+ promptRegistration,
7
+ provision,
8
+ runSetupWizard
9
+ } from "./chunk-CO2KR3YH.js";
10
+ import "./chunk-ULRBF2T7.js";
11
+ import "./chunk-KFQGP6VL.js";
12
+ export {
13
+ promptCompanyInfo,
14
+ promptDatabase,
15
+ promptDeployment,
16
+ promptDomain,
17
+ promptRegistration,
18
+ provision,
19
+ runSetupWizard
20
+ };
@@ -0,0 +1,7 @@
1
+ import {
2
+ TaskQueueManager
3
+ } from "./chunk-2BQMGELC.js";
4
+ import "./chunk-KFQGP6VL.js";
5
+ export {
6
+ TaskQueueManager
7
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agenticmail/enterprise",
3
- "version": "0.5.259",
3
+ "version": "0.5.261",
4
4
  "description": "AgenticMail Enterprise — cloud-hosted AI agent identity, email, auth & compliance for organizations",
5
5
  "type": "module",
6
6
  "bin": {
@@ -394,6 +394,22 @@ export class TaskQueueManager {
394
394
  return res.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
395
395
  }
396
396
 
397
+ async getTaskBySessionId(sessionId: string): Promise<TaskRecord | null> {
398
+ if (this.db) {
399
+ try {
400
+ const row = await this.db.get(
401
+ `SELECT * FROM task_pipeline WHERE session_id = ? AND status = 'in_progress' ORDER BY created_at DESC LIMIT 1`,
402
+ [sessionId]
403
+ );
404
+ return row ? this.rowToTask(row) : null;
405
+ } catch { /* fall through */ }
406
+ }
407
+ for (const task of this.tasks.values()) {
408
+ if (task.sessionId === sessionId && task.status === 'in_progress') return task;
409
+ }
410
+ return null;
411
+ }
412
+
397
413
  async getTaskHistory(orgId: string, limit = 50, offset = 0): Promise<TaskRecord[]> {
398
414
  if (this.db) {
399
415
  try {
@@ -14,6 +14,7 @@
14
14
  import type { AgentConfig, AgentMessage, RuntimeHooks, SessionState, StreamEvent, ToolCall } from './types.js';
15
15
  import { callLLM, toolsToDefinitions, estimateMessageTokens, type LLMResponse } from './llm-client.js';
16
16
  import { ToolRegistry, executeTool } from './tool-executor.js';
17
+ import { compactContext, needsCompaction, COMPACTION_THRESHOLD } from './compaction.js';
17
18
 
18
19
  // ─── Constants ───────────────────────────────────────────
19
20
 
@@ -21,7 +22,7 @@ const DEFAULT_MAX_TURNS = 0; // 0 = unlimited
21
22
  const DEFAULT_MAX_TOKENS = 8192;
22
23
  const DEFAULT_TEMPERATURE = 0.7;
23
24
  const DEFAULT_CONTEXT_WINDOW = 2_000_000; // 1M — most frontier models support this (Feb 2026)
24
- const COMPACTION_THRESHOLD = 0.8; // compact when 80% of context used
25
+ // COMPACTION_THRESHOLD imported from ./compaction.js
25
26
 
26
27
  /**
27
28
  * Fix ALL tool_use / tool_result pairing issues in message history.
@@ -722,203 +723,5 @@ function buildResult(
722
723
  };
723
724
  }
724
725
 
725
- /**
726
- * Compact the context window using LLM-generated summary.
727
- *
728
- * When the context fills up (80% of window), this function:
729
- * 1. Takes all messages except system + last 20
730
- * 2. Asks the LLM to produce a structured summary preserving ALL critical data
731
- * 3. Saves the summary to persistent agent memory (survives crashes)
732
- * 4. Returns: system messages + summary + last 20 messages
733
- *
734
- * The summary is structured to preserve:
735
- * - Original task/goal
736
- * - Work completed so far
737
- * - Key data: IDs, paths, URLs, names, numbers (exact values, not paraphrases)
738
- * - Decisions made and why
739
- * - Current state and next steps
740
- * - Errors encountered and resolutions
741
- *
742
- * Fallback: If LLM call fails, uses extractive summary (500 chars per message)
743
- * which is still much better than losing context entirely.
744
- */
745
- var KEEP_RECENT_MESSAGES = 20;
746
-
747
- async function compactContext(
748
- messages: AgentMessage[],
749
- config: AgentConfig,
750
- hooks: RuntimeHooks,
751
- options?: { apiKey?: string; sessionId?: string },
752
- ): Promise<AgentMessage[]> {
753
- var systemMessages = messages.filter(function(m) { return m.role === 'system'; });
754
- var nonSystem = messages.filter(function(m) { return m.role !== 'system'; });
755
-
756
- if (nonSystem.length <= KEEP_RECENT_MESSAGES) return messages;
757
-
758
- // Find a safe cut point that doesn't split tool_use/tool_result pairs.
759
- // We start at the desired cut index and walk backwards until we find a safe boundary.
760
- var desiredCut = nonSystem.length - KEEP_RECENT_MESSAGES;
761
- var cutIndex = desiredCut;
762
-
763
- // A safe cut point is one where the message AT cutIndex (first of keepRecent)
764
- // does NOT start with tool_result blocks that reference tool_use from the message before it.
765
- for (var ci = desiredCut; ci > 0; ci--) {
766
- var msg = nonSystem[ci];
767
- if (msg.role === 'user' && Array.isArray(msg.content)) {
768
- var hasToolResult = (msg.content as any[]).some((b: any) => b.type === 'tool_result');
769
- if (hasToolResult) {
770
- // This message has tool_results — cutting here would orphan them.
771
- // Move cut point earlier (include this message AND its preceding assistant tool_use).
772
- continue;
773
- }
774
- }
775
- cutIndex = ci;
776
- break;
777
- }
778
-
779
- var keepRecent = nonSystem.slice(cutIndex);
780
- var toSummarize = nonSystem.slice(0, cutIndex);
781
-
782
- console.log(`[compaction] Compacting ${toSummarize.length} messages (keeping ${keepRecent.length} recent + ${systemMessages.length} system)`);
783
-
784
- // Build transcript of messages to summarize
785
- var transcript: string[] = [];
786
- for (var msg of toSummarize) {
787
- var text = '';
788
- if (typeof msg.content === 'string') {
789
- text = msg.content;
790
- } else if (Array.isArray(msg.content)) {
791
- var parts: string[] = [];
792
- for (var block of msg.content) {
793
- if (block && typeof block === 'object') {
794
- if ((block as any).type === 'text') parts.push((block as any).text || '');
795
- else if ((block as any).type === 'tool_use') parts.push(`[Tool Call: ${(block as any).name}(${JSON.stringify((block as any).input || {}).slice(0, 300)})]`);
796
- else if ((block as any).type === 'tool_result') {
797
- var resultContent = String((block as any).content || '').slice(0, 500);
798
- parts.push(`[Tool Result: ${resultContent}]`);
799
- }
800
- }
801
- }
802
- text = parts.join('\n');
803
- }
804
- if (text.length > 0) {
805
- transcript.push(`[${msg.role}]: ${text.slice(0, 1000)}`);
806
- }
807
- }
808
-
809
- var transcriptText = transcript.join('\n\n');
810
- if (transcriptText.length > 100_000) {
811
- transcriptText = transcriptText.slice(0, 100_000) + '\n\n... (earlier messages truncated for summary)';
812
- }
813
-
814
- // Try LLM-powered summarization
815
- var summaryText = '';
816
- var usedLLM = false;
817
-
818
- if (options?.apiKey) {
819
- try {
820
- var summaryPrompt: AgentMessage[] = [
821
- {
822
- role: 'system' as const,
823
- content: `You are a context summarizer for an AI agent that is in the middle of a long-running task. Your job is to create a comprehensive summary that preserves ALL critical information the agent needs to continue working seamlessly.
824
-
825
- Your summary MUST include ALL of these sections:
826
-
827
- ## Original Task
828
- What was the agent asked to do? What's the overall goal?
829
-
830
- ## Work Completed
831
- What has been accomplished so far? List specific actions taken, in order.
832
-
833
- ## Key Data & References
834
- ALL important identifiers, file paths, URLs, names, numbers, email addresses, message IDs, thread IDs, API response values, folder IDs, document IDs — ANYTHING the agent might need to reference later. Be exhaustive and use exact values. Losing a single ID means the agent cannot continue its work.
835
-
836
- ## Decisions Made
837
- What choices were made and why? Include any corrections or changes in approach.
838
-
839
- ## Current State
840
- Where did things leave off? What was the agent in the middle of doing?
841
-
842
- ## Pending / Next Steps
843
- What still needs to be done? Any scheduled tasks, follow-ups, or promises made?
844
-
845
- ## Errors & Lessons
846
- Any errors encountered, what caused them, and how they were resolved. Include workarounds discovered.
847
-
848
- CRITICAL: This summary REPLACES the full conversation. If you omit something, the agent loses it forever. When in doubt, include it. Use exact values — never paraphrase IDs, paths, or technical data.`,
849
- },
850
- {
851
- role: 'user' as const,
852
- content: `Summarize this conversation transcript:\n\n${transcriptText}`,
853
- },
854
- ];
855
-
856
- var summaryResponse = await callLLM(
857
- {
858
- provider: config.model.provider,
859
- modelId: config.model.modelId,
860
- apiKey: options.apiKey,
861
- },
862
- summaryPrompt,
863
- [],
864
- { maxTokens: 4096, temperature: 0.3 },
865
- );
866
-
867
- if (summaryResponse.textContent && summaryResponse.textContent.length > 50) {
868
- summaryText = summaryResponse.textContent;
869
- usedLLM = true;
870
- console.log(`[compaction] LLM summary generated: ${summaryText.length} chars (${summaryResponse.usage?.inputTokens || 0} in / ${summaryResponse.usage?.outputTokens || 0} out tokens)`);
871
- }
872
- } catch (err: any) {
873
- console.warn(`[compaction] LLM summary failed: ${err.message} — using extractive fallback`);
874
- }
875
- }
876
-
877
- // Fallback: extractive summary (keeps 500 chars per message instead of old 200)
878
- if (!usedLLM) {
879
- var extractParts: string[] = [];
880
- extractParts.push(`[Context Summary — ${toSummarize.length} earlier messages compacted (extractive fallback)]`);
881
- extractParts.push('');
882
-
883
- for (var msg2 of toSummarize) {
884
- if (typeof msg2.content === 'string' && msg2.content.length > 0) {
885
- extractParts.push(`[${msg2.role}]: ${msg2.content.slice(0, 500)}`);
886
- } else if (Array.isArray(msg2.content)) {
887
- for (var block2 of msg2.content) {
888
- if (block2 && typeof block2 === 'object') {
889
- if ((block2 as any).type === 'text' && (block2 as any).text?.length > 0) {
890
- extractParts.push(`[${msg2.role}]: ${(block2 as any).text.slice(0, 500)}`);
891
- } else if ((block2 as any).type === 'tool_use') {
892
- extractParts.push(`[tool_call]: ${(block2 as any).name}(${JSON.stringify((block2 as any).input || {}).slice(0, 400)})`);
893
- } else if ((block2 as any).type === 'tool_result') {
894
- extractParts.push(`[tool_result]: ${String((block2 as any).content || '').slice(0, 400)}`);
895
- }
896
- }
897
- }
898
- }
899
- }
900
-
901
- summaryText = extractParts.join('\n');
902
- if (summaryText.length > 20_000) {
903
- summaryText = summaryText.slice(0, 20_000) + '\n\n... (truncated)';
904
- }
905
- console.log(`[compaction] Extractive fallback: ${summaryText.length} chars`);
906
- }
907
-
908
- // Save to persistent agent memory (survives crashes, available to future sessions)
909
- try {
910
- await hooks.onContextCompaction(options?.sessionId || '', config.agentId, summaryText);
911
- console.log(`[compaction] Summary persisted to agent memory`);
912
- } catch (memErr: any) {
913
- console.warn(`[compaction] Memory save failed: ${memErr?.message}`);
914
- }
915
-
916
- var summaryMessage: AgentMessage = {
917
- role: 'user' as const,
918
- content: `[CONTEXT COMPACTION — Your conversation history was summarized to fit the context window. Below is a comprehensive summary of everything that happened before your most recent ${keepRecent.length} messages. Treat this as ground truth.]\n\n${summaryText}`,
919
- };
920
-
921
- var result = [...systemMessages, summaryMessage, ...keepRecent];
922
- console.log(`[compaction] ${messages.length} messages → ${result.length} messages`);
923
- return result;
924
- }
726
+ // Context compaction is now in ./compaction.ts
727
+ // Exported: compactContext, needsCompaction, COMPACTION_THRESHOLD