@xagent/one-shot 1.2.14 → 1.2.16

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
@@ -409,7 +409,8 @@ var init_settings_manager = __esm({
409
409
  ],
410
410
  verbosityLevel: "quiet",
411
411
  explainLevel: "brief",
412
- requireConfirmation: true
412
+ requireConfirmation: true,
413
+ tokenThreshold: 0.9
413
414
  };
414
415
  DEFAULT_PROJECT_SETTINGS = {
415
416
  model: "grok-code-fast-1"
@@ -13425,6 +13426,7 @@ var init_token_counter = __esm({
13425
13426
  "src/utils/token-counter.ts"() {
13426
13427
  TokenCounter = class {
13427
13428
  constructor(model = "gpt-4") {
13429
+ this.model = model;
13428
13430
  try {
13429
13431
  this.encoder = encoding_for_model(model);
13430
13432
  } catch {
@@ -13445,13 +13447,21 @@ var init_token_counter = __esm({
13445
13447
  let totalTokens = 0;
13446
13448
  for (const message of messages) {
13447
13449
  totalTokens += 3;
13448
- if (message.content && typeof message.content === "string") {
13449
- totalTokens += this.countTokens(message.content);
13450
+ if (message.content) {
13451
+ if (typeof message.content === "string") {
13452
+ totalTokens += this.countTokens(message.content);
13453
+ } else if (Array.isArray(message.content)) {
13454
+ for (const part of message.content) {
13455
+ if (part.type === "text" && part.text) {
13456
+ totalTokens += this.countTokens(part.text);
13457
+ }
13458
+ }
13459
+ }
13450
13460
  }
13451
13461
  if (message.role) {
13452
13462
  totalTokens += this.countTokens(message.role);
13453
13463
  }
13454
- if (message.tool_calls) {
13464
+ if ("tool_calls" in message && message.tool_calls) {
13455
13465
  totalTokens += this.countTokens(JSON.stringify(message.tool_calls));
13456
13466
  }
13457
13467
  }
@@ -13465,6 +13475,20 @@ var init_token_counter = __esm({
13465
13475
  estimateStreamingTokens(accumulatedContent) {
13466
13476
  return this.countTokens(accumulatedContent);
13467
13477
  }
13478
+ /**
13479
+ * Get maximum context window tokens for the current model
13480
+ */
13481
+ getMaxTokens() {
13482
+ const modelName = this.model.toLowerCase();
13483
+ if (modelName.includes("grok-2")) return 128e3;
13484
+ if (modelName.includes("grok-1")) return 128e3;
13485
+ if (modelName.includes("grok-beta")) return 128e3;
13486
+ if (modelName.includes("gpt-4o")) return 128e3;
13487
+ if (modelName.includes("gpt-4-turbo")) return 128e3;
13488
+ if (modelName.includes("gpt-4")) return 8192;
13489
+ if (modelName.includes("gpt-3.5")) return 4096;
13490
+ return 4096;
13491
+ }
13468
13492
  /**
13469
13493
  * Clean up resources
13470
13494
  */
@@ -14384,6 +14408,355 @@ ${option.id}) ${option.title}`);
14384
14408
  }
14385
14409
  });
14386
14410
 
14411
+ // src/subagents/subagent-framework.ts
14412
+ var SubagentFramework;
14413
+ var init_subagent_framework = __esm({
14414
+ "src/subagents/subagent-framework.ts"() {
14415
+ SubagentFramework = class {
14416
+ constructor() {
14417
+ this.activeTasks = /* @__PURE__ */ new Map();
14418
+ this.results = /* @__PURE__ */ new Map();
14419
+ this.configs = /* @__PURE__ */ new Map();
14420
+ this.initializeConfigs();
14421
+ }
14422
+ initializeConfigs() {
14423
+ const defaultConfigs = {
14424
+ "docgen": {
14425
+ type: "docgen",
14426
+ contextLimit: 2e3,
14427
+ timeout: 3e4,
14428
+ maxRetries: 2
14429
+ },
14430
+ "prd-assistant": {
14431
+ type: "prd-assistant",
14432
+ contextLimit: 2e3,
14433
+ timeout: 2e4,
14434
+ maxRetries: 1
14435
+ },
14436
+ "delta": {
14437
+ type: "delta",
14438
+ contextLimit: 1500,
14439
+ timeout: 15e3,
14440
+ maxRetries: 1
14441
+ },
14442
+ "token-optimizer": {
14443
+ type: "token-optimizer",
14444
+ contextLimit: 1e3,
14445
+ timeout: 1e4,
14446
+ maxRetries: 1
14447
+ },
14448
+ "summarizer": {
14449
+ type: "summarizer",
14450
+ contextLimit: 2e3,
14451
+ timeout: 25e3,
14452
+ maxRetries: 2
14453
+ },
14454
+ "sentinel": {
14455
+ type: "sentinel",
14456
+ contextLimit: 1e3,
14457
+ timeout: 1e4,
14458
+ maxRetries: 1
14459
+ },
14460
+ "regression-hunter": {
14461
+ type: "regression-hunter",
14462
+ contextLimit: 1500,
14463
+ timeout: 15e3,
14464
+ maxRetries: 1
14465
+ },
14466
+ "guardrail": {
14467
+ type: "guardrail",
14468
+ contextLimit: 1e3,
14469
+ timeout: 1e4,
14470
+ maxRetries: 1
14471
+ }
14472
+ };
14473
+ for (const [type, config2] of Object.entries(defaultConfigs)) {
14474
+ this.configs.set(type, config2);
14475
+ }
14476
+ }
14477
+ async spawnSubagent(task) {
14478
+ const taskId = this.generateTaskId();
14479
+ const fullTask = {
14480
+ ...task,
14481
+ id: taskId,
14482
+ createdAt: Date.now()
14483
+ };
14484
+ this.activeTasks.set(taskId, fullTask);
14485
+ this.executeSubagent(fullTask);
14486
+ return taskId;
14487
+ }
14488
+ async executeSubagent(task) {
14489
+ const config2 = this.configs.get(task.type);
14490
+ if (!config2) {
14491
+ this.setResult(task.id, {
14492
+ taskId: task.id,
14493
+ type: task.type,
14494
+ success: false,
14495
+ error: "Unknown subagent type",
14496
+ tokensUsed: 0,
14497
+ executionTime: 0,
14498
+ summary: "Failed to execute: unknown type"
14499
+ });
14500
+ return;
14501
+ }
14502
+ const startTime = Date.now();
14503
+ try {
14504
+ const context = {
14505
+ id: this.generateContextId(),
14506
+ type: task.type,
14507
+ prompt: this.generatePromptForType(task.type, task.input),
14508
+ data: task.input,
14509
+ startTime,
14510
+ tokenBudget: config2.contextLimit
14511
+ };
14512
+ const result = await this.executeInIsolatedContext(context, config2);
14513
+ this.setResult(task.id, {
14514
+ taskId: task.id,
14515
+ type: task.type,
14516
+ success: true,
14517
+ output: result.output,
14518
+ tokensUsed: result.tokensUsed,
14519
+ executionTime: Date.now() - startTime,
14520
+ summary: result.summary
14521
+ });
14522
+ } catch (error) {
14523
+ this.setResult(task.id, {
14524
+ taskId: task.id,
14525
+ type: task.type,
14526
+ success: false,
14527
+ error: error.message,
14528
+ tokensUsed: 0,
14529
+ executionTime: Date.now() - startTime,
14530
+ summary: `Failed: ${error.message}`
14531
+ });
14532
+ }
14533
+ this.activeTasks.delete(task.id);
14534
+ }
14535
+ async executeInIsolatedContext(context, _config) {
14536
+ switch (context.type) {
14537
+ case "docgen":
14538
+ return this.simulateDocGenAgent(context);
14539
+ case "prd-assistant":
14540
+ return this.simulatePRDAssistantAgent(context);
14541
+ case "delta":
14542
+ return this.simulateDeltaAgent(context);
14543
+ case "token-optimizer":
14544
+ return this.simulateTokenOptimizerAgent(context);
14545
+ case "summarizer":
14546
+ return this.simulateSummarizerAgent(context);
14547
+ case "sentinel":
14548
+ return this.simulateSentinelAgent(context);
14549
+ case "regression-hunter":
14550
+ return this.simulateRegressionHunterAgent(context);
14551
+ case "guardrail":
14552
+ return this.simulateGuardrailAgent(context);
14553
+ default:
14554
+ throw new Error(`Unsupported subagent type: ${context.type}`);
14555
+ }
14556
+ }
14557
+ async simulateDocGenAgent(context) {
14558
+ const { projectPath, docType } = context.data;
14559
+ await this.delay(2e3);
14560
+ return {
14561
+ output: {
14562
+ documentType: docType,
14563
+ content: `# Generated ${docType}
14564
+
14565
+ This is a generated document for ${projectPath}.
14566
+
14567
+ *Generated by DocGenAgent*`,
14568
+ metadata: {
14569
+ projectPath,
14570
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
14571
+ wordCount: 150
14572
+ }
14573
+ },
14574
+ tokensUsed: 1500,
14575
+ summary: `Generated ${docType} documentation (150 words)`
14576
+ };
14577
+ }
14578
+ async simulatePRDAssistantAgent(context) {
14579
+ const { prdPath: _prdPath, prdContent: _prdContent } = context.data;
14580
+ await this.delay(1500);
14581
+ return {
14582
+ output: {
14583
+ suggestions: [
14584
+ "Consider existing MCP integration patterns",
14585
+ "Reference user-settings.json structure",
14586
+ "Check CLI command naming conventions"
14587
+ ],
14588
+ conflicts: [],
14589
+ similarTasks: ["user-management-prd.md"],
14590
+ architectureImpact: "May need new tools/ folder"
14591
+ },
14592
+ tokensUsed: 1200,
14593
+ summary: `Analyzed PRD: 3 suggestions, 1 similar task found`
14594
+ };
14595
+ }
14596
+ async simulateDeltaAgent(context) {
14597
+ const { fromCommit, toCommit: _toCommit } = context.data;
14598
+ await this.delay(1e3);
14599
+ return {
14600
+ output: {
14601
+ filesChanged: ["src/tools/documentation/", "src/hooks/use-input-handler.ts"],
14602
+ architectureChanges: true,
14603
+ newFeatures: ["documentation system"],
14604
+ impact: "Major feature addition - documentation generation"
14605
+ },
14606
+ tokensUsed: 800,
14607
+ summary: `Analyzed changes from ${fromCommit}: 2 files, architecture changes detected`
14608
+ };
14609
+ }
14610
+ async simulateTokenOptimizerAgent(context) {
14611
+ const { currentTokens, targetReduction: _targetReduction } = context.data;
14612
+ await this.delay(500);
14613
+ return {
14614
+ output: {
14615
+ currentUsage: currentTokens,
14616
+ optimizedUsage: Math.floor(currentTokens * 0.3),
14617
+ reduction: Math.floor(currentTokens * 0.7),
14618
+ suggestions: [
14619
+ "Compress conversation history",
14620
+ "Archive old tool results",
14621
+ "Summarize repeated patterns"
14622
+ ]
14623
+ },
14624
+ tokensUsed: 300,
14625
+ summary: `Token optimization: ${Math.floor(currentTokens * 0.7)} tokens can be saved (70% reduction)`
14626
+ };
14627
+ }
14628
+ async simulateSummarizerAgent(context) {
14629
+ const { content, compressionTarget } = context.data;
14630
+ await this.delay(2500);
14631
+ const originalLength = content.length;
14632
+ const targetLength = Math.floor(originalLength * (compressionTarget || 0.3));
14633
+ return {
14634
+ output: {
14635
+ originalLength,
14636
+ compressedLength: targetLength,
14637
+ compressionRatio: 1 - (compressionTarget || 0.3),
14638
+ summary: content.substring(0, targetLength) + "...",
14639
+ keyPoints: [
14640
+ "Main objectives completed",
14641
+ "Documentation system implemented",
14642
+ "Multiple commands added"
14643
+ ]
14644
+ },
14645
+ tokensUsed: 1800,
14646
+ summary: `Compressed content from ${originalLength} to ${targetLength} chars (${Math.round((1 - (compressionTarget || 0.3)) * 100)}% reduction)`
14647
+ };
14648
+ }
14649
+ async simulateSentinelAgent(context) {
14650
+ const { errorLogs: _errorLogs, recentCommands: _recentCommands } = context.data;
14651
+ await this.delay(800);
14652
+ return {
14653
+ output: {
14654
+ errorsDetected: 0,
14655
+ patternsFound: [],
14656
+ recommendations: ["System running normally"],
14657
+ alertLevel: "green"
14658
+ },
14659
+ tokensUsed: 400,
14660
+ summary: "System monitoring: No issues detected"
14661
+ };
14662
+ }
14663
+ async simulateRegressionHunterAgent(context) {
14664
+ const { proposedChanges: _proposedChanges, knownFailures: _knownFailures } = context.data;
14665
+ await this.delay(1200);
14666
+ return {
14667
+ output: {
14668
+ riskLevel: "low",
14669
+ potentialIssues: [],
14670
+ recommendations: ["Changes appear safe to proceed"],
14671
+ testsSuggested: []
14672
+ },
14673
+ tokensUsed: 900,
14674
+ summary: "Regression analysis: Low risk, no conflicts with known failures"
14675
+ };
14676
+ }
14677
+ async simulateGuardrailAgent(context) {
14678
+ const { planDescription: _planDescription, rules: _rules } = context.data;
14679
+ await this.delay(600);
14680
+ return {
14681
+ output: {
14682
+ violationsFound: [],
14683
+ warnings: [],
14684
+ compliance: "passed",
14685
+ newRuleSuggestions: []
14686
+ },
14687
+ tokensUsed: 350,
14688
+ summary: "Guardrail check: All rules satisfied"
14689
+ };
14690
+ }
14691
+ delay(ms) {
14692
+ return new Promise((resolve8) => setTimeout(resolve8, ms));
14693
+ }
14694
+ generateTaskId() {
14695
+ return `task_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
14696
+ }
14697
+ generateContextId() {
14698
+ return `ctx_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
14699
+ }
14700
+ generatePromptForType(type, input) {
14701
+ const prompts = {
14702
+ "docgen": `Generate documentation for the provided project. Focus on clarity and completeness. Input: ${JSON.stringify(input)}`,
14703
+ "prd-assistant": `Analyze this PRD for potential issues, suggestions, and conflicts with existing project context. Input: ${JSON.stringify(input)}`,
14704
+ "delta": `Analyze the changes between commits and summarize the impact. Input: ${JSON.stringify(input)}`,
14705
+ "token-optimizer": `Analyze token usage and suggest optimizations. Input: ${JSON.stringify(input)}`,
14706
+ "summarizer": `Summarize and compress the provided content while preserving key information. Input: ${JSON.stringify(input)}`,
14707
+ "sentinel": `Monitor for errors and patterns in the provided logs/commands. Input: ${JSON.stringify(input)}`,
14708
+ "regression-hunter": `Check proposed changes against known failure patterns. Input: ${JSON.stringify(input)}`,
14709
+ "guardrail": `Validate the plan against established rules and constraints. Input: ${JSON.stringify(input)}`
14710
+ };
14711
+ return prompts[type];
14712
+ }
14713
+ setResult(taskId, result) {
14714
+ this.results.set(taskId, result);
14715
+ }
14716
+ async getResult(taskId) {
14717
+ return this.results.get(taskId) || null;
14718
+ }
14719
+ async waitForResult(taskId, timeoutMs = 3e4) {
14720
+ const startTime = Date.now();
14721
+ while (Date.now() - startTime < timeoutMs) {
14722
+ const result = await this.getResult(taskId);
14723
+ if (result) {
14724
+ return result;
14725
+ }
14726
+ await this.delay(100);
14727
+ }
14728
+ throw new Error(`Subagent task ${taskId} timed out after ${timeoutMs}ms`);
14729
+ }
14730
+ getActiveTaskCount() {
14731
+ return this.activeTasks.size;
14732
+ }
14733
+ getCompletedTaskCount() {
14734
+ return this.results.size;
14735
+ }
14736
+ getPerformanceMetrics() {
14737
+ const results = Array.from(this.results.values());
14738
+ const avgExecTime = results.length > 0 ? results.reduce((sum, r) => sum + r.executionTime, 0) / results.length : 0;
14739
+ const totalTokens = results.reduce((sum, r) => sum + r.tokensUsed, 0);
14740
+ return {
14741
+ totalTasks: this.activeTasks.size + this.results.size,
14742
+ activeTasks: this.activeTasks.size,
14743
+ completedTasks: this.results.size,
14744
+ averageExecutionTime: Math.round(avgExecTime),
14745
+ totalTokensUsed: totalTokens
14746
+ };
14747
+ }
14748
+ clearOldResults(maxAge = 36e5) {
14749
+ const now = Date.now();
14750
+ for (const [taskId, result] of this.results.entries()) {
14751
+ if (now - result.executionTime > maxAge) {
14752
+ this.results.delete(taskId);
14753
+ }
14754
+ }
14755
+ }
14756
+ };
14757
+ }
14758
+ });
14759
+
14387
14760
  // src/utils/regex-helper.ts
14388
14761
  var RegexHelper;
14389
14762
  var init_regex_helper = __esm({
@@ -14562,6 +14935,239 @@ var init_regex_helper = __esm({
14562
14935
  }
14563
14936
  });
14564
14937
 
14938
+ // src/services/ui-state.ts
14939
+ var ui_state_exports = {};
14940
+ __export(ui_state_exports, {
14941
+ onUIEvent: () => onUIEvent,
14942
+ uiState: () => uiState,
14943
+ useUIState: () => useUIState
14944
+ });
14945
+ function useUIState() {
14946
+ return uiState;
14947
+ }
14948
+ function onUIEvent(eventType, listener) {
14949
+ uiState.on(eventType, listener);
14950
+ return () => uiState.off(eventType, listener);
14951
+ }
14952
+ var UIStateService, uiState;
14953
+ var init_ui_state = __esm({
14954
+ "src/services/ui-state.ts"() {
14955
+ UIStateService = class _UIStateService extends EventEmitter {
14956
+ constructor() {
14957
+ super();
14958
+ this.currentSpinner = null;
14959
+ this.activeProgress = /* @__PURE__ */ new Map();
14960
+ this.backgroundActivities = /* @__PURE__ */ new Map();
14961
+ this.notifications = [];
14962
+ this.setMaxListeners(50);
14963
+ }
14964
+ static getInstance() {
14965
+ if (!_UIStateService.instance) {
14966
+ _UIStateService.instance = new _UIStateService();
14967
+ }
14968
+ return _UIStateService.instance;
14969
+ }
14970
+ // Spinner management
14971
+ startSpinner(event) {
14972
+ this.currentSpinner = event;
14973
+ this.emit("spinner:start", event);
14974
+ }
14975
+ updateSpinner(updates) {
14976
+ if (this.currentSpinner) {
14977
+ this.currentSpinner = { ...this.currentSpinner, ...updates };
14978
+ this.emit("spinner:update", this.currentSpinner);
14979
+ }
14980
+ }
14981
+ stopSpinner() {
14982
+ this.currentSpinner = null;
14983
+ this.emit("spinner:stop");
14984
+ }
14985
+ getCurrentSpinner() {
14986
+ return this.currentSpinner;
14987
+ }
14988
+ // Progress management
14989
+ startProgress(id, event) {
14990
+ this.activeProgress.set(id, { ...event, startTime: event.startTime || Date.now() });
14991
+ this.emit("progress:start", { id, ...event });
14992
+ }
14993
+ updateProgress(id, updates) {
14994
+ const existing = this.activeProgress.get(id);
14995
+ if (existing) {
14996
+ const updated = { ...existing, ...updates };
14997
+ this.activeProgress.set(id, updated);
14998
+ this.emit("progress:update", { id, ...updated });
14999
+ }
15000
+ }
15001
+ completeProgress(id) {
15002
+ const progress = this.activeProgress.get(id);
15003
+ if (progress) {
15004
+ this.activeProgress.delete(id);
15005
+ this.emit("progress:complete", { id, ...progress });
15006
+ }
15007
+ }
15008
+ getProgress(id) {
15009
+ return this.activeProgress.get(id);
15010
+ }
15011
+ getAllProgress() {
15012
+ return new Map(this.activeProgress);
15013
+ }
15014
+ // Background activity management
15015
+ startBackgroundActivity(id, event) {
15016
+ this.backgroundActivities.set(id, event);
15017
+ const eventType = `background:${event.activity}:start`;
15018
+ this.emit(eventType, { id, ...event });
15019
+ }
15020
+ updateBackgroundActivity(id, updates) {
15021
+ const existing = this.backgroundActivities.get(id);
15022
+ if (existing) {
15023
+ const updated = { ...existing, ...updates };
15024
+ this.backgroundActivities.set(id, updated);
15025
+ const eventType = `background:${updated.activity}:progress`;
15026
+ this.emit(eventType, { id, ...updated });
15027
+ }
15028
+ }
15029
+ stopBackgroundActivity(id) {
15030
+ const activity = this.backgroundActivities.get(id);
15031
+ if (activity) {
15032
+ this.backgroundActivities.delete(id);
15033
+ const eventType = `background:${activity.activity}:complete`;
15034
+ this.emit(eventType, { id, ...activity });
15035
+ }
15036
+ }
15037
+ getBackgroundActivities() {
15038
+ return new Map(this.backgroundActivities);
15039
+ }
15040
+ // Notification management
15041
+ showNotification(notification) {
15042
+ this.notifications.push(notification);
15043
+ this.emit("notification:show", notification);
15044
+ if (notification.duration) {
15045
+ setTimeout(() => {
15046
+ this.hideNotification(notification);
15047
+ }, notification.duration);
15048
+ }
15049
+ }
15050
+ hideNotification(notification) {
15051
+ const index = this.notifications.indexOf(notification);
15052
+ if (index !== -1) {
15053
+ this.notifications.splice(index, 1);
15054
+ this.emit("notification:hide", notification);
15055
+ }
15056
+ }
15057
+ getNotifications() {
15058
+ return [...this.notifications];
15059
+ }
15060
+ // Convenience methods for common operations
15061
+ showWorkspaceIndexing(totalFiles, currentFile) {
15062
+ this.startProgress("workspace-indexing", {
15063
+ operation: "indexing",
15064
+ current: 0,
15065
+ total: totalFiles,
15066
+ message: currentFile ? `Indexing ${currentFile}` : "Indexing workspace"
15067
+ });
15068
+ this.startBackgroundActivity("workspace-watcher", {
15069
+ activity: "indexing",
15070
+ details: `0/${totalFiles} files`
15071
+ });
15072
+ }
15073
+ updateWorkspaceIndexing(current, total, currentFile) {
15074
+ this.updateProgress("workspace-indexing", {
15075
+ current,
15076
+ message: currentFile ? `Indexing ${currentFile}` : void 0
15077
+ });
15078
+ this.updateBackgroundActivity("workspace-watcher", {
15079
+ details: `${current}/${total} files`
15080
+ });
15081
+ }
15082
+ completeWorkspaceIndexing() {
15083
+ this.completeProgress("workspace-indexing");
15084
+ this.stopBackgroundActivity("workspace-watcher");
15085
+ this.showNotification({
15086
+ message: "Workspace indexing complete",
15087
+ type: "success",
15088
+ icon: "\u2705",
15089
+ duration: 3e3
15090
+ });
15091
+ }
15092
+ showTokenCompaction(usedTokens, targetTokens) {
15093
+ this.startSpinner({
15094
+ operation: "compact",
15095
+ message: `Compacting context (${usedTokens}\u2192${targetTokens} tokens)`
15096
+ });
15097
+ this.startProgress("token-compaction", {
15098
+ operation: "compacting",
15099
+ current: 0,
15100
+ total: usedTokens
15101
+ });
15102
+ }
15103
+ updateTokenCompaction(compactedTokens) {
15104
+ this.updateProgress("token-compaction", {
15105
+ current: compactedTokens
15106
+ });
15107
+ const progress = this.getProgress("token-compaction");
15108
+ if (progress) {
15109
+ const percentage = Math.round(compactedTokens / progress.total * 100);
15110
+ this.updateSpinner({
15111
+ progress: percentage
15112
+ });
15113
+ }
15114
+ }
15115
+ completeTokenCompaction() {
15116
+ this.completeProgress("token-compaction");
15117
+ this.stopSpinner();
15118
+ this.showNotification({
15119
+ message: "Context compaction complete",
15120
+ type: "success",
15121
+ icon: "\u{1F504}",
15122
+ duration: 2e3
15123
+ });
15124
+ }
15125
+ // Error handling
15126
+ showError(message, details) {
15127
+ this.showNotification({
15128
+ message: details ? `${message}: ${details}` : message,
15129
+ type: "error",
15130
+ icon: "\u274C",
15131
+ duration: 5e3
15132
+ });
15133
+ }
15134
+ showSuccess(message) {
15135
+ this.showNotification({
15136
+ message,
15137
+ type: "success",
15138
+ icon: "\u2705",
15139
+ duration: 3e3
15140
+ });
15141
+ }
15142
+ showInfo(message) {
15143
+ this.showNotification({
15144
+ message,
15145
+ type: "info",
15146
+ icon: "\u2139\uFE0F",
15147
+ duration: 4e3
15148
+ });
15149
+ }
15150
+ // Debug helpers
15151
+ getState() {
15152
+ return {
15153
+ spinner: this.currentSpinner,
15154
+ progress: Object.fromEntries(this.activeProgress),
15155
+ backgroundActivities: Object.fromEntries(this.backgroundActivities),
15156
+ notifications: this.notifications
15157
+ };
15158
+ }
15159
+ reset() {
15160
+ this.currentSpinner = null;
15161
+ this.activeProgress.clear();
15162
+ this.backgroundActivities.clear();
15163
+ this.notifications = [];
15164
+ this.emit("ui:reset");
15165
+ }
15166
+ };
15167
+ uiState = UIStateService.getInstance();
15168
+ }
15169
+ });
15170
+
14565
15171
  // node_modules/zod/v3/helpers/util.js
14566
15172
  var util, objectUtil, ZodParsedType, getParsedType;
14567
15173
  var init_util = __esm({
@@ -20604,6 +21210,7 @@ var init_grok_agent = __esm({
20604
21210
  init_custom_instructions();
20605
21211
  init_settings_manager();
20606
21212
  init_research_recommend();
21213
+ init_subagent_framework();
20607
21214
  init_execution_orchestrator();
20608
21215
  init_regex_helper();
20609
21216
  GrokAgent = class extends EventEmitter {
@@ -20611,6 +21218,7 @@ var init_grok_agent = __esm({
20611
21218
  super();
20612
21219
  this.chatHistory = [];
20613
21220
  this.messages = [];
21221
+ this.totalTokensUsed = 0;
20614
21222
  this.abortController = null;
20615
21223
  this.mcpInitialized = false;
20616
21224
  this.lastToolExecutionTime = 0;
@@ -20894,6 +21502,13 @@ Current working directory: ${process.cwd()}`
20894
21502
  const maxToolRounds = this.maxToolRounds;
20895
21503
  let toolRounds = 0;
20896
21504
  try {
21505
+ const threshold = getSettingsManager().getUserSetting("tokenThreshold") || 0.9;
21506
+ const currentTokens = this.tokenCounter.countMessageTokens(this.messages);
21507
+ const maxTokens = this.tokenCounter.getMaxTokens();
21508
+ this.totalTokensUsed = Math.max(this.totalTokensUsed, currentTokens);
21509
+ if (currentTokens > threshold * maxTokens) {
21510
+ await this.performAutomaticCompaction();
21511
+ }
20897
21512
  const tools = await getAllGrokTools();
20898
21513
  let currentResponse = await this.grokClient.chat(
20899
21514
  this.messages,
@@ -20999,6 +21614,81 @@ Current working directory: ${process.cwd()}`
20999
21614
  return [userEntry, errorEntry];
21000
21615
  }
21001
21616
  }
21617
+ /**
21618
+ * Perform automatic context compaction when token threshold is exceeded
21619
+ */
21620
+ async performAutomaticCompaction() {
21621
+ try {
21622
+ const { uiState: uiState2 } = await Promise.resolve().then(() => (init_ui_state(), ui_state_exports));
21623
+ const currentTokens = this.tokenCounter.countMessageTokens(this.messages);
21624
+ uiState2.showTokenCompaction(currentTokens, this.tokenCounter.getMaxTokens());
21625
+ const systemMessages = this.messages.filter((m) => m.role === "system");
21626
+ const recentMessages = this.messages.slice(-5);
21627
+ const messagesToCompress = this.messages.filter(
21628
+ (_, i) => !systemMessages.includes(this.messages[i]) && !recentMessages.includes(this.messages[i])
21629
+ );
21630
+ if (messagesToCompress.length === 0) {
21631
+ uiState2.completeTokenCompaction();
21632
+ return;
21633
+ }
21634
+ const contentToCompress = messagesToCompress.map((m) => `${m.role}: ${m.content}`).join("\n");
21635
+ const subagentFramework = new SubagentFramework();
21636
+ const taskId = await subagentFramework.spawnSubagent({
21637
+ type: "summarizer",
21638
+ input: {
21639
+ content: contentToCompress,
21640
+ compressionTarget: 0.3
21641
+ // 70% reduction
21642
+ },
21643
+ priority: "high"
21644
+ });
21645
+ const result = await subagentFramework.waitForResult(taskId, 3e4);
21646
+ if (result.success && result.summary) {
21647
+ const compactedChatHistory = [];
21648
+ const compactedMessages = [];
21649
+ systemMessages.forEach((msg) => {
21650
+ compactedMessages.push(msg);
21651
+ const entry = this.chatHistory.find((e) => e.content === msg.content && e.type === "user");
21652
+ if (entry) compactedChatHistory.push(entry);
21653
+ });
21654
+ const summaryEntry = {
21655
+ type: "assistant",
21656
+ content: `\u{1F9F9} **Context Compacted Automatically**
21657
+
21658
+ ${result.summary}
21659
+
21660
+ *Older conversation history has been summarized to prevent token limit issues.*`,
21661
+ timestamp: /* @__PURE__ */ new Date()
21662
+ };
21663
+ compactedChatHistory.push(summaryEntry);
21664
+ compactedMessages.push({ role: "assistant", content: summaryEntry.content });
21665
+ recentMessages.forEach((msg) => {
21666
+ compactedMessages.push(msg);
21667
+ const entry = this.chatHistory.find(
21668
+ (e) => e.content === msg.content && (e.type === "user" && msg.role === "user" || e.type === "assistant" && msg.role === "assistant")
21669
+ );
21670
+ if (entry) compactedChatHistory.push(entry);
21671
+ });
21672
+ this.chatHistory = compactedChatHistory;
21673
+ this.messages = compactedMessages;
21674
+ this.totalTokensUsed = this.tokenCounter.countMessageTokens(this.messages);
21675
+ uiState2.updateTokenCompaction(this.totalTokensUsed);
21676
+ uiState2.completeTokenCompaction();
21677
+ console.log(`Context compacted: ${messagesToCompress.length} messages -> ${compactedMessages.length} messages`);
21678
+ } else {
21679
+ uiState2.completeTokenCompaction();
21680
+ console.warn("Automatic compaction failed");
21681
+ }
21682
+ } catch (error) {
21683
+ console.error("Error during automatic compaction:", error);
21684
+ try {
21685
+ const { uiState: uiState2 } = await Promise.resolve().then(() => (init_ui_state(), ui_state_exports));
21686
+ uiState2.completeTokenCompaction();
21687
+ } catch (error2) {
21688
+ console.warn("Failed to complete compaction UI feedback:", error2);
21689
+ }
21690
+ }
21691
+ }
21002
21692
  messageReducer(previous, item) {
21003
21693
  const reduce = (acc, delta) => {
21004
21694
  acc = { ...acc };
@@ -21047,6 +21737,13 @@ Current working directory: ${process.cwd()}`
21047
21737
  let totalOutputTokens = 0;
21048
21738
  let lastTokenUpdate = 0;
21049
21739
  try {
21740
+ const threshold = getSettingsManager().getUserSetting("tokenThreshold") || 0.9;
21741
+ const currentTokens = this.tokenCounter.countMessageTokens(this.messages);
21742
+ const maxTokens = this.tokenCounter.getMaxTokens();
21743
+ this.totalTokensUsed = Math.max(this.totalTokensUsed, currentTokens);
21744
+ if (currentTokens > threshold * maxTokens) {
21745
+ await this.performAutomaticCompaction();
21746
+ }
21050
21747
  while (toolRounds < maxToolRounds) {
21051
21748
  if (this.abortController?.signal.aborted) {
21052
21749
  yield {
@@ -28501,355 +29198,6 @@ Updated By: /update-agent-docs after detecting changes${recentChangesSection}`
28501
29198
  };
28502
29199
  }
28503
29200
  });
28504
-
28505
- // src/subagents/subagent-framework.ts
28506
- var SubagentFramework;
28507
- var init_subagent_framework = __esm({
28508
- "src/subagents/subagent-framework.ts"() {
28509
- SubagentFramework = class {
28510
- constructor() {
28511
- this.activeTasks = /* @__PURE__ */ new Map();
28512
- this.results = /* @__PURE__ */ new Map();
28513
- this.configs = /* @__PURE__ */ new Map();
28514
- this.initializeConfigs();
28515
- }
28516
- initializeConfigs() {
28517
- const defaultConfigs = {
28518
- "docgen": {
28519
- type: "docgen",
28520
- contextLimit: 2e3,
28521
- timeout: 3e4,
28522
- maxRetries: 2
28523
- },
28524
- "prd-assistant": {
28525
- type: "prd-assistant",
28526
- contextLimit: 2e3,
28527
- timeout: 2e4,
28528
- maxRetries: 1
28529
- },
28530
- "delta": {
28531
- type: "delta",
28532
- contextLimit: 1500,
28533
- timeout: 15e3,
28534
- maxRetries: 1
28535
- },
28536
- "token-optimizer": {
28537
- type: "token-optimizer",
28538
- contextLimit: 1e3,
28539
- timeout: 1e4,
28540
- maxRetries: 1
28541
- },
28542
- "summarizer": {
28543
- type: "summarizer",
28544
- contextLimit: 2e3,
28545
- timeout: 25e3,
28546
- maxRetries: 2
28547
- },
28548
- "sentinel": {
28549
- type: "sentinel",
28550
- contextLimit: 1e3,
28551
- timeout: 1e4,
28552
- maxRetries: 1
28553
- },
28554
- "regression-hunter": {
28555
- type: "regression-hunter",
28556
- contextLimit: 1500,
28557
- timeout: 15e3,
28558
- maxRetries: 1
28559
- },
28560
- "guardrail": {
28561
- type: "guardrail",
28562
- contextLimit: 1e3,
28563
- timeout: 1e4,
28564
- maxRetries: 1
28565
- }
28566
- };
28567
- for (const [type, config2] of Object.entries(defaultConfigs)) {
28568
- this.configs.set(type, config2);
28569
- }
28570
- }
28571
- async spawnSubagent(task) {
28572
- const taskId = this.generateTaskId();
28573
- const fullTask = {
28574
- ...task,
28575
- id: taskId,
28576
- createdAt: Date.now()
28577
- };
28578
- this.activeTasks.set(taskId, fullTask);
28579
- this.executeSubagent(fullTask);
28580
- return taskId;
28581
- }
28582
- async executeSubagent(task) {
28583
- const config2 = this.configs.get(task.type);
28584
- if (!config2) {
28585
- this.setResult(task.id, {
28586
- taskId: task.id,
28587
- type: task.type,
28588
- success: false,
28589
- error: "Unknown subagent type",
28590
- tokensUsed: 0,
28591
- executionTime: 0,
28592
- summary: "Failed to execute: unknown type"
28593
- });
28594
- return;
28595
- }
28596
- const startTime = Date.now();
28597
- try {
28598
- const context = {
28599
- id: this.generateContextId(),
28600
- type: task.type,
28601
- prompt: this.generatePromptForType(task.type, task.input),
28602
- data: task.input,
28603
- startTime,
28604
- tokenBudget: config2.contextLimit
28605
- };
28606
- const result = await this.executeInIsolatedContext(context, config2);
28607
- this.setResult(task.id, {
28608
- taskId: task.id,
28609
- type: task.type,
28610
- success: true,
28611
- output: result.output,
28612
- tokensUsed: result.tokensUsed,
28613
- executionTime: Date.now() - startTime,
28614
- summary: result.summary
28615
- });
28616
- } catch (error) {
28617
- this.setResult(task.id, {
28618
- taskId: task.id,
28619
- type: task.type,
28620
- success: false,
28621
- error: error.message,
28622
- tokensUsed: 0,
28623
- executionTime: Date.now() - startTime,
28624
- summary: `Failed: ${error.message}`
28625
- });
28626
- }
28627
- this.activeTasks.delete(task.id);
28628
- }
28629
- async executeInIsolatedContext(context, _config) {
28630
- switch (context.type) {
28631
- case "docgen":
28632
- return this.simulateDocGenAgent(context);
28633
- case "prd-assistant":
28634
- return this.simulatePRDAssistantAgent(context);
28635
- case "delta":
28636
- return this.simulateDeltaAgent(context);
28637
- case "token-optimizer":
28638
- return this.simulateTokenOptimizerAgent(context);
28639
- case "summarizer":
28640
- return this.simulateSummarizerAgent(context);
28641
- case "sentinel":
28642
- return this.simulateSentinelAgent(context);
28643
- case "regression-hunter":
28644
- return this.simulateRegressionHunterAgent(context);
28645
- case "guardrail":
28646
- return this.simulateGuardrailAgent(context);
28647
- default:
28648
- throw new Error(`Unsupported subagent type: ${context.type}`);
28649
- }
28650
- }
28651
- async simulateDocGenAgent(context) {
28652
- const { projectPath, docType } = context.data;
28653
- await this.delay(2e3);
28654
- return {
28655
- output: {
28656
- documentType: docType,
28657
- content: `# Generated ${docType}
28658
-
28659
- This is a generated document for ${projectPath}.
28660
-
28661
- *Generated by DocGenAgent*`,
28662
- metadata: {
28663
- projectPath,
28664
- generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
28665
- wordCount: 150
28666
- }
28667
- },
28668
- tokensUsed: 1500,
28669
- summary: `Generated ${docType} documentation (150 words)`
28670
- };
28671
- }
28672
- async simulatePRDAssistantAgent(context) {
28673
- const { prdPath: _prdPath, prdContent: _prdContent } = context.data;
28674
- await this.delay(1500);
28675
- return {
28676
- output: {
28677
- suggestions: [
28678
- "Consider existing MCP integration patterns",
28679
- "Reference user-settings.json structure",
28680
- "Check CLI command naming conventions"
28681
- ],
28682
- conflicts: [],
28683
- similarTasks: ["user-management-prd.md"],
28684
- architectureImpact: "May need new tools/ folder"
28685
- },
28686
- tokensUsed: 1200,
28687
- summary: `Analyzed PRD: 3 suggestions, 1 similar task found`
28688
- };
28689
- }
28690
- async simulateDeltaAgent(context) {
28691
- const { fromCommit, toCommit: _toCommit } = context.data;
28692
- await this.delay(1e3);
28693
- return {
28694
- output: {
28695
- filesChanged: ["src/tools/documentation/", "src/hooks/use-input-handler.ts"],
28696
- architectureChanges: true,
28697
- newFeatures: ["documentation system"],
28698
- impact: "Major feature addition - documentation generation"
28699
- },
28700
- tokensUsed: 800,
28701
- summary: `Analyzed changes from ${fromCommit}: 2 files, architecture changes detected`
28702
- };
28703
- }
28704
- async simulateTokenOptimizerAgent(context) {
28705
- const { currentTokens, targetReduction: _targetReduction } = context.data;
28706
- await this.delay(500);
28707
- return {
28708
- output: {
28709
- currentUsage: currentTokens,
28710
- optimizedUsage: Math.floor(currentTokens * 0.3),
28711
- reduction: Math.floor(currentTokens * 0.7),
28712
- suggestions: [
28713
- "Compress conversation history",
28714
- "Archive old tool results",
28715
- "Summarize repeated patterns"
28716
- ]
28717
- },
28718
- tokensUsed: 300,
28719
- summary: `Token optimization: ${Math.floor(currentTokens * 0.7)} tokens can be saved (70% reduction)`
28720
- };
28721
- }
28722
- async simulateSummarizerAgent(context) {
28723
- const { content, compressionTarget } = context.data;
28724
- await this.delay(2500);
28725
- const originalLength = content.length;
28726
- const targetLength = Math.floor(originalLength * (compressionTarget || 0.3));
28727
- return {
28728
- output: {
28729
- originalLength,
28730
- compressedLength: targetLength,
28731
- compressionRatio: 1 - (compressionTarget || 0.3),
28732
- summary: content.substring(0, targetLength) + "...",
28733
- keyPoints: [
28734
- "Main objectives completed",
28735
- "Documentation system implemented",
28736
- "Multiple commands added"
28737
- ]
28738
- },
28739
- tokensUsed: 1800,
28740
- summary: `Compressed content from ${originalLength} to ${targetLength} chars (${Math.round((1 - (compressionTarget || 0.3)) * 100)}% reduction)`
28741
- };
28742
- }
28743
- async simulateSentinelAgent(context) {
28744
- const { errorLogs: _errorLogs, recentCommands: _recentCommands } = context.data;
28745
- await this.delay(800);
28746
- return {
28747
- output: {
28748
- errorsDetected: 0,
28749
- patternsFound: [],
28750
- recommendations: ["System running normally"],
28751
- alertLevel: "green"
28752
- },
28753
- tokensUsed: 400,
28754
- summary: "System monitoring: No issues detected"
28755
- };
28756
- }
28757
- async simulateRegressionHunterAgent(context) {
28758
- const { proposedChanges: _proposedChanges, knownFailures: _knownFailures } = context.data;
28759
- await this.delay(1200);
28760
- return {
28761
- output: {
28762
- riskLevel: "low",
28763
- potentialIssues: [],
28764
- recommendations: ["Changes appear safe to proceed"],
28765
- testsSuggested: []
28766
- },
28767
- tokensUsed: 900,
28768
- summary: "Regression analysis: Low risk, no conflicts with known failures"
28769
- };
28770
- }
28771
- async simulateGuardrailAgent(context) {
28772
- const { planDescription: _planDescription, rules: _rules } = context.data;
28773
- await this.delay(600);
28774
- return {
28775
- output: {
28776
- violationsFound: [],
28777
- warnings: [],
28778
- compliance: "passed",
28779
- newRuleSuggestions: []
28780
- },
28781
- tokensUsed: 350,
28782
- summary: "Guardrail check: All rules satisfied"
28783
- };
28784
- }
28785
- delay(ms) {
28786
- return new Promise((resolve8) => setTimeout(resolve8, ms));
28787
- }
28788
- generateTaskId() {
28789
- return `task_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
28790
- }
28791
- generateContextId() {
28792
- return `ctx_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
28793
- }
28794
- generatePromptForType(type, input) {
28795
- const prompts = {
28796
- "docgen": `Generate documentation for the provided project. Focus on clarity and completeness. Input: ${JSON.stringify(input)}`,
28797
- "prd-assistant": `Analyze this PRD for potential issues, suggestions, and conflicts with existing project context. Input: ${JSON.stringify(input)}`,
28798
- "delta": `Analyze the changes between commits and summarize the impact. Input: ${JSON.stringify(input)}`,
28799
- "token-optimizer": `Analyze token usage and suggest optimizations. Input: ${JSON.stringify(input)}`,
28800
- "summarizer": `Summarize and compress the provided content while preserving key information. Input: ${JSON.stringify(input)}`,
28801
- "sentinel": `Monitor for errors and patterns in the provided logs/commands. Input: ${JSON.stringify(input)}`,
28802
- "regression-hunter": `Check proposed changes against known failure patterns. Input: ${JSON.stringify(input)}`,
28803
- "guardrail": `Validate the plan against established rules and constraints. Input: ${JSON.stringify(input)}`
28804
- };
28805
- return prompts[type];
28806
- }
28807
- setResult(taskId, result) {
28808
- this.results.set(taskId, result);
28809
- }
28810
- async getResult(taskId) {
28811
- return this.results.get(taskId) || null;
28812
- }
28813
- async waitForResult(taskId, timeoutMs = 3e4) {
28814
- const startTime = Date.now();
28815
- while (Date.now() - startTime < timeoutMs) {
28816
- const result = await this.getResult(taskId);
28817
- if (result) {
28818
- return result;
28819
- }
28820
- await this.delay(100);
28821
- }
28822
- throw new Error(`Subagent task ${taskId} timed out after ${timeoutMs}ms`);
28823
- }
28824
- getActiveTaskCount() {
28825
- return this.activeTasks.size;
28826
- }
28827
- getCompletedTaskCount() {
28828
- return this.results.size;
28829
- }
28830
- getPerformanceMetrics() {
28831
- const results = Array.from(this.results.values());
28832
- const avgExecTime = results.length > 0 ? results.reduce((sum, r) => sum + r.executionTime, 0) / results.length : 0;
28833
- const totalTokens = results.reduce((sum, r) => sum + r.tokensUsed, 0);
28834
- return {
28835
- totalTasks: this.activeTasks.size + this.results.size,
28836
- activeTasks: this.activeTasks.size,
28837
- completedTasks: this.results.size,
28838
- averageExecutionTime: Math.round(avgExecTime),
28839
- totalTokensUsed: totalTokens
28840
- };
28841
- }
28842
- clearOldResults(maxAge = 36e5) {
28843
- const now = Date.now();
28844
- for (const [taskId, result] of this.results.entries()) {
28845
- if (now - result.executionTime > maxAge) {
28846
- this.results.delete(taskId);
28847
- }
28848
- }
28849
- }
28850
- };
28851
- }
28852
- });
28853
29201
  var SelfHealingSystem;
28854
29202
  var init_self_healing_system = __esm({
28855
29203
  "src/tools/documentation/self-healing-system.ts"() {
@@ -29280,7 +29628,7 @@ var init_package = __esm({
29280
29628
  package_default = {
29281
29629
  type: "module",
29282
29630
  name: "@xagent/one-shot",
29283
- version: "1.2.14",
29631
+ version: "1.2.16",
29284
29632
  description: "An open-source AI agent that brings advanced AI capabilities directly into your terminal with automatic documentation updates.",
29285
29633
  main: "dist/index.js",
29286
29634
  module: "dist/index.js",
@@ -35293,7 +35641,7 @@ var require_package = __commonJS({
35293
35641
  module.exports = {
35294
35642
  type: "module",
35295
35643
  name: "@xagent/one-shot",
35296
- version: "1.2.14",
35644
+ version: "1.2.16",
35297
35645
  description: "An open-source AI agent that brings advanced AI capabilities directly into your terminal with automatic documentation updates.",
35298
35646
  main: "dist/index.js",
35299
35647
  module: "dist/index.js",