agentix-cli 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +192 -107
  2. package/dist/agent-K2YOEOJ5.js +2 -0
  3. package/dist/chunk-4YCH6IZV.js +2 -0
  4. package/dist/chunk-AIBBZF4E.js +41 -0
  5. package/dist/chunk-AIBBZF4E.js.map +1 -0
  6. package/dist/chunk-F73GPYCO.js +106 -0
  7. package/dist/chunk-F73GPYCO.js.map +1 -0
  8. package/dist/chunk-M7HKBG3V.js +2 -0
  9. package/dist/chunk-M7HKBG3V.js.map +1 -0
  10. package/dist/chunk-MGMZNJCE.js +46 -0
  11. package/dist/chunk-MGMZNJCE.js.map +1 -0
  12. package/dist/{chunk-6PVFYFUE.js → chunk-X7UN6JAA.js} +2 -2
  13. package/dist/{chunk-6PVFYFUE.js.map → chunk-X7UN6JAA.js.map} +1 -1
  14. package/dist/chunk-Z4GC5D6D.js +12 -0
  15. package/dist/chunk-Z4GC5D6D.js.map +1 -0
  16. package/dist/cli.js +9 -155
  17. package/dist/cli.js.map +1 -1
  18. package/dist/heal-UV5A6B5T.js +2 -0
  19. package/dist/index.d.ts +265 -11
  20. package/dist/index.js +85 -1
  21. package/dist/index.js.map +1 -1
  22. package/dist/loader-6VSM6FSY.js +2 -0
  23. package/dist/providers-AVYG63KK.js +2 -0
  24. package/dist/providers-AVYG63KK.js.map +1 -0
  25. package/package.json +3 -1
  26. package/dist/agent-AI6DUEPU.js +0 -2
  27. package/dist/chunk-FUYKPFUV.js +0 -46
  28. package/dist/chunk-FUYKPFUV.js.map +0 -1
  29. package/dist/chunk-NZ6W33BD.js +0 -116
  30. package/dist/chunk-NZ6W33BD.js.map +0 -1
  31. package/dist/chunk-THMHQELC.js +0 -106
  32. package/dist/chunk-THMHQELC.js.map +0 -1
  33. package/dist/heal-MJLBETRV.js +0 -2
  34. package/dist/loader-PHU6STSZ.js +0 -2
  35. package/dist/providers-MPYTYJVB.js +0 -2
  36. /package/dist/{agent-AI6DUEPU.js.map → agent-K2YOEOJ5.js.map} +0 -0
  37. /package/dist/{heal-MJLBETRV.js.map → chunk-4YCH6IZV.js.map} +0 -0
  38. /package/dist/{loader-PHU6STSZ.js.map → heal-UV5A6B5T.js.map} +0 -0
  39. /package/dist/{providers-MPYTYJVB.js.map → loader-6VSM6FSY.js.map} +0 -0
package/dist/index.d.ts CHANGED
@@ -1444,15 +1444,54 @@ declare const daemonConfigSchema: z.ZodObject<{
1444
1444
  whatsapp: z.ZodDefault<z.ZodObject<{
1445
1445
  enabled: z.ZodDefault<z.ZodBoolean>;
1446
1446
  sessionDir: z.ZodDefault<z.ZodString>;
1447
- agentBinding: z.ZodOptional<z.ZodString>;
1447
+ defaultAgent: z.ZodOptional<z.ZodString>;
1448
+ allowFrom: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
1449
+ routes: z.ZodDefault<z.ZodArray<z.ZodObject<{
1450
+ contact: z.ZodOptional<z.ZodString>;
1451
+ group: z.ZodOptional<z.ZodString>;
1452
+ agent: z.ZodString;
1453
+ }, "strip", z.ZodTypeAny, {
1454
+ agent: string;
1455
+ group?: string | undefined;
1456
+ contact?: string | undefined;
1457
+ }, {
1458
+ agent: string;
1459
+ group?: string | undefined;
1460
+ contact?: string | undefined;
1461
+ }>, "many">>;
1448
1462
  }, "strip", z.ZodTypeAny, {
1449
1463
  enabled: boolean;
1450
1464
  sessionDir: string;
1465
+ routes: {
1466
+ agent: string;
1467
+ group?: string | undefined;
1468
+ contact?: string | undefined;
1469
+ }[];
1470
+ defaultAgent?: string | undefined;
1471
+ allowFrom?: string[] | undefined;
1472
+ }, {
1473
+ enabled?: boolean | undefined;
1474
+ sessionDir?: string | undefined;
1475
+ defaultAgent?: string | undefined;
1476
+ allowFrom?: string[] | undefined;
1477
+ routes?: {
1478
+ agent: string;
1479
+ group?: string | undefined;
1480
+ contact?: string | undefined;
1481
+ }[] | undefined;
1482
+ }>>;
1483
+ discord: z.ZodDefault<z.ZodObject<{
1484
+ enabled: z.ZodDefault<z.ZodBoolean>;
1485
+ token: z.ZodOptional<z.ZodString>;
1486
+ agentBinding: z.ZodOptional<z.ZodString>;
1487
+ }, "strip", z.ZodTypeAny, {
1488
+ enabled: boolean;
1489
+ token?: string | undefined;
1451
1490
  agentBinding?: string | undefined;
1452
1491
  }, {
1453
1492
  enabled?: boolean | undefined;
1493
+ token?: string | undefined;
1454
1494
  agentBinding?: string | undefined;
1455
- sessionDir?: string | undefined;
1456
1495
  }>>;
1457
1496
  }, "strip", z.ZodTypeAny, {
1458
1497
  telegram: {
@@ -1469,6 +1508,17 @@ declare const daemonConfigSchema: z.ZodObject<{
1469
1508
  whatsapp: {
1470
1509
  enabled: boolean;
1471
1510
  sessionDir: string;
1511
+ routes: {
1512
+ agent: string;
1513
+ group?: string | undefined;
1514
+ contact?: string | undefined;
1515
+ }[];
1516
+ defaultAgent?: string | undefined;
1517
+ allowFrom?: string[] | undefined;
1518
+ };
1519
+ discord: {
1520
+ enabled: boolean;
1521
+ token?: string | undefined;
1472
1522
  agentBinding?: string | undefined;
1473
1523
  };
1474
1524
  }, {
@@ -1485,8 +1535,19 @@ declare const daemonConfigSchema: z.ZodObject<{
1485
1535
  } | undefined;
1486
1536
  whatsapp?: {
1487
1537
  enabled?: boolean | undefined;
1488
- agentBinding?: string | undefined;
1489
1538
  sessionDir?: string | undefined;
1539
+ defaultAgent?: string | undefined;
1540
+ allowFrom?: string[] | undefined;
1541
+ routes?: {
1542
+ agent: string;
1543
+ group?: string | undefined;
1544
+ contact?: string | undefined;
1545
+ }[] | undefined;
1546
+ } | undefined;
1547
+ discord?: {
1548
+ enabled?: boolean | undefined;
1549
+ token?: string | undefined;
1550
+ agentBinding?: string | undefined;
1490
1551
  } | undefined;
1491
1552
  }>>;
1492
1553
  crons: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodObject<{
@@ -1605,6 +1666,17 @@ declare const daemonConfigSchema: z.ZodObject<{
1605
1666
  whatsapp: {
1606
1667
  enabled: boolean;
1607
1668
  sessionDir: string;
1669
+ routes: {
1670
+ agent: string;
1671
+ group?: string | undefined;
1672
+ contact?: string | undefined;
1673
+ }[];
1674
+ defaultAgent?: string | undefined;
1675
+ allowFrom?: string[] | undefined;
1676
+ };
1677
+ discord: {
1678
+ enabled: boolean;
1679
+ token?: string | undefined;
1608
1680
  agentBinding?: string | undefined;
1609
1681
  };
1610
1682
  };
@@ -1667,8 +1739,19 @@ declare const daemonConfigSchema: z.ZodObject<{
1667
1739
  } | undefined;
1668
1740
  whatsapp?: {
1669
1741
  enabled?: boolean | undefined;
1670
- agentBinding?: string | undefined;
1671
1742
  sessionDir?: string | undefined;
1743
+ defaultAgent?: string | undefined;
1744
+ allowFrom?: string[] | undefined;
1745
+ routes?: {
1746
+ agent: string;
1747
+ group?: string | undefined;
1748
+ contact?: string | undefined;
1749
+ }[] | undefined;
1750
+ } | undefined;
1751
+ discord?: {
1752
+ enabled?: boolean | undefined;
1753
+ token?: string | undefined;
1754
+ agentBinding?: string | undefined;
1672
1755
  } | undefined;
1673
1756
  } | undefined;
1674
1757
  crons?: Record<string, {
@@ -1785,6 +1868,11 @@ interface AgentTask {
1785
1868
  channel?: string;
1786
1869
  sender?: string;
1787
1870
  group?: string;
1871
+ /** Attached media file (image, audio, video, document) */
1872
+ mediaPath?: string;
1873
+ mediaType?: string;
1874
+ /** Text of the message being replied to */
1875
+ replyToText?: string;
1788
1876
  conversationHistory?: Array<{
1789
1877
  role: string;
1790
1878
  content: string;
@@ -1829,6 +1917,7 @@ declare class AgentRegistry {
1829
1917
  private config;
1830
1918
  private providers;
1831
1919
  private sessions;
1920
+ private wiki;
1832
1921
  private log;
1833
1922
  constructor(config: DaemonConfig, log?: (...args: unknown[]) => void);
1834
1923
  /**
@@ -1886,8 +1975,15 @@ interface IncomingMessage {
1886
1975
  };
1887
1976
  text: string;
1888
1977
  replyTo?: string;
1978
+ replyToText?: string;
1889
1979
  timestamp: Date;
1980
+ media?: {
1981
+ path: string;
1982
+ type: string;
1983
+ fileName?: string;
1984
+ };
1890
1985
  raw?: unknown;
1986
+ resolvedAgent?: string;
1891
1987
  }
1892
1988
  interface OutgoingMessage {
1893
1989
  channel: string;
@@ -1919,21 +2015,40 @@ declare class MessageRouter {
1919
2015
  private config;
1920
2016
  private channels;
1921
2017
  private hooks?;
2018
+ private mesh?;
2019
+ private groupLogs;
1922
2020
  private log;
1923
2021
  constructor(registry: AgentRegistry, config: DaemonConfig, hooks?: HookRegistry, log?: (...args: unknown[]) => void);
2022
+ setMesh(mesh: A2AMesh): void;
1924
2023
  addChannel(adapter: ChannelAdapter): void;
1925
2024
  startAll(): Promise<void>;
1926
2025
  stopAll(): Promise<void>;
1927
2026
  private handleMessage;
2027
+ private static readonly MAX_BOT_CHAIN_DEPTH;
1928
2028
  /**
1929
- * Check if an agent's response mentions another agent.
1930
- * If so, route the response as a new task to that agent.
2029
+ * Bot-to-bot conversation chain.
2030
+ * When an agent's response mentions another agent, route it and continue
2031
+ * the chain if the target agent also mentions someone (up to MAX depth).
1931
2032
  */
1932
- private handleBotToBotMentions;
2033
+ private handleBotToBotChain;
1933
2034
  private adapterSend;
1934
2035
  private adapterEdit;
1935
2036
  private adapterReact;
1936
2037
  private startTypingLoop;
2038
+ /**
2039
+ * Handle a message by routing to a mesh peer's agent.
2040
+ * Searches peer agent cards for mention matches.
2041
+ */
2042
+ private handleViaMesh;
2043
+ /**
2044
+ * Log a message in the group conversation history.
2045
+ */
2046
+ private logGroupMessage;
2047
+ /**
2048
+ * Build group conversation context for an agent.
2049
+ * Returns recent messages from the group so the agent knows what's been discussed.
2050
+ */
2051
+ private buildGroupContext;
1937
2052
  private getAccountForAgent;
1938
2053
  private resolveAgent;
1939
2054
  }
@@ -1990,20 +2105,38 @@ declare class TelegramAdapter implements ChannelAdapter {
1990
2105
  private apiCall;
1991
2106
  }
1992
2107
 
2108
+ interface WhatsAppRoute {
2109
+ contact?: string;
2110
+ group?: string;
2111
+ agent: string;
2112
+ }
1993
2113
  declare class WhatsAppAdapter implements ChannelAdapter {
1994
2114
  readonly name = "whatsapp";
1995
2115
  private sessionDir;
1996
- private agentBinding?;
2116
+ private defaultAgent?;
2117
+ private allowFrom?;
2118
+ private routes;
1997
2119
  private handler?;
2120
+ private sock;
2121
+ private sentMessageIds;
1998
2122
  private log;
1999
2123
  constructor(config: {
2000
2124
  sessionDir: string;
2001
- agentBinding?: string;
2125
+ defaultAgent?: string;
2126
+ allowFrom?: string[];
2127
+ routes?: WhatsAppRoute[];
2002
2128
  }, log?: (...args: unknown[]) => void);
2129
+ /**
2130
+ * Resolve which agent handles a message based on routes.
2131
+ */
2132
+ resolveAgent(senderPhone: string, groupName?: string, groupJid?: string): string | undefined;
2003
2133
  onMessage(handler: (msg: IncomingMessage) => Promise<void>): void;
2004
2134
  start(): Promise<void>;
2005
2135
  stop(): Promise<void>;
2006
- send(msg: OutgoingMessage): Promise<void>;
2136
+ send(msg: OutgoingMessage): Promise<string>;
2137
+ editMessage(chatId: string, messageId: string, text: string): Promise<boolean>;
2138
+ sendTyping(chatId: string): Promise<void>;
2139
+ react(chatId: string, messageId: string, emoji?: string): Promise<void>;
2007
2140
  }
2008
2141
 
2009
2142
  interface CronJobState {
@@ -2051,6 +2184,127 @@ declare class CronScheduler {
2051
2184
  list(): CronJobState[];
2052
2185
  }
2053
2186
 
2187
+ /**
2188
+ * Access levels for wiki articles:
2189
+ * - private: only the owning agent can read/write
2190
+ * - shared: specific agents listed in `sharedWith` can read, owner can write
2191
+ * - public: all agents on this node can read, owner can write
2192
+ */
2193
+ type WikiAccess = "private" | "shared" | "public";
2194
+ interface WikiArticleMeta {
2195
+ title: string;
2196
+ type: string;
2197
+ owner: string;
2198
+ access: WikiAccess;
2199
+ sharedWith?: string[];
2200
+ created: string;
2201
+ lastUpdated: string;
2202
+ related: string[];
2203
+ sources: string[];
2204
+ tags?: string[];
2205
+ }
2206
+ interface WikiArticle {
2207
+ meta: WikiArticleMeta;
2208
+ content: string;
2209
+ path: string;
2210
+ }
2211
+ interface WikiEntry {
2212
+ id: string;
2213
+ date: string;
2214
+ agentId: string;
2215
+ source: string;
2216
+ sourceContext?: string;
2217
+ content: string;
2218
+ meta?: Record<string, unknown>;
2219
+ }
2220
+ interface WikiIndex {
2221
+ articles: Array<{
2222
+ path: string;
2223
+ title: string;
2224
+ type: string;
2225
+ owner: string;
2226
+ access: WikiAccess;
2227
+ sharedWith?: string[];
2228
+ aliases: string[];
2229
+ backlinks: number;
2230
+ }>;
2231
+ lastRebuilt: string;
2232
+ }
2233
+
2234
+ declare class WikiStore {
2235
+ private baseDir;
2236
+ private rawDir;
2237
+ private log;
2238
+ constructor(baseDir?: string, log?: (...args: unknown[]) => void);
2239
+ /**
2240
+ * Check if an agent can read an article.
2241
+ */
2242
+ canRead(article: WikiArticleMeta, agentId: string): boolean;
2243
+ /**
2244
+ * Check if an agent can write an article.
2245
+ */
2246
+ canWrite(article: WikiArticleMeta, agentId: string): boolean;
2247
+ /**
2248
+ * Add a raw entry (from a conversation, cron result, etc.)
2249
+ */
2250
+ addEntry(entry: WikiEntry): string;
2251
+ /**
2252
+ * List raw entries, optionally filtered by agent or date range.
2253
+ */
2254
+ listEntries(filter?: {
2255
+ agentId?: string;
2256
+ after?: string;
2257
+ before?: string;
2258
+ }): WikiEntry[];
2259
+ private parseEntry;
2260
+ /**
2261
+ * Write or update a wiki article.
2262
+ */
2263
+ writeArticle(path: string, meta: WikiArticleMeta, content: string, agentId: string): boolean;
2264
+ /**
2265
+ * Read an article. Returns null if not found.
2266
+ */
2267
+ readArticle(path: string): WikiArticle | null;
2268
+ /**
2269
+ * Read an article with permission check.
2270
+ */
2271
+ readArticleAs(path: string, agentId: string): WikiArticle | null;
2272
+ private parseArticle;
2273
+ /**
2274
+ * List all articles accessible to an agent.
2275
+ */
2276
+ listArticles(agentId: string): WikiArticle[];
2277
+ /**
2278
+ * Search articles by keyword. Returns articles the agent can read.
2279
+ */
2280
+ search(query: string, agentId: string, maxResults?: number): WikiArticle[];
2281
+ /**
2282
+ * Find articles relevant to a message (for context injection).
2283
+ * Extracts keywords from the message and searches the wiki.
2284
+ */
2285
+ findRelevant(message: string, agentId: string, maxArticles?: number): WikiArticle[];
2286
+ /**
2287
+ * Build context string from relevant wiki articles for prompt injection.
2288
+ * Token-efficient: includes title + first ~500 chars of each article.
2289
+ */
2290
+ buildContext(articles: WikiArticle[], maxChars?: number): string;
2291
+ /**
2292
+ * Rebuild the master index.
2293
+ */
2294
+ rebuildIndex(): WikiIndex;
2295
+ /**
2296
+ * Get wiki stats.
2297
+ */
2298
+ stats(): {
2299
+ totalArticles: number;
2300
+ totalEntries: number;
2301
+ articlesByType: Record<string, number>;
2302
+ articlesByAccess: Record<string, number>;
2303
+ articlesByOwner: Record<string, number>;
2304
+ };
2305
+ private walkDir;
2306
+ }
2307
+
2054
2308
  interface ProviderCapabilities {
2055
2309
  streaming: boolean;
2056
2310
  tools: boolean;
@@ -2102,4 +2356,4 @@ declare function handleError(error: unknown): void;
2102
2356
 
2103
2357
  declare function getPackageInfo(): PackageJson;
2104
2358
 
2105
- export { A2AClient, A2AMesh, A2AServer, A2AServerConfig, ALL_TOOL_NAMES, AgentCard, AgentConfig, AgentContext, AgentDef, AgentProvider, AgentRegistry, AgentResponse, AgentTask, AgentXDaemon, AgentXRuntime, AnthropicMessage, AuthConfig, BLOCKING_EVENTS, ChannelAdapter, ClaudeCodeProvider, ClaudeProvider, ContentBlock, ContextBuilder, CronJobDef, CronJobState, CronRunResult, CronScheduler, DaemonConfig, EnhanceConfig, EnhanceEngine, EnhanceResult, GenerateOptions, GenerateResult, GenerateStreamEvent, GeneratedFile, GenerationMessage, GenerationResult, GitCommitResult, GitDiffFile, GitLogEntry, GitManager, GitStatus, HOOK_EVENTS, HealConfig, HealEngine, HealResult, HookContext, HookDefinition, HookEvent, HookHandler, HookRegistry, HookResult, IncomingMessage, Memory, MemoryEntry, MemoryHierarchy, MemoryStore, MeshPeer, MessageRouter, MiddlewareFn, ModelUsage, OUTPUT_CONFIGS, OUTPUT_TYPES, OutgoingMessage, OutputConfig, OutputType, PERMISSION_MODES, PROVIDER_CAPABILITIES, PermissionAction, PermissionConfig, PermissionManager, PermissionMode, PermissionRule, Pipeline, PipelineRequest, PipelineResponse, ProjectSchemas, ProviderCapabilities, ProviderName, ProviderOptions, RawGenerationResult, ReplEngine, ReplOptions, RuntimeConfig, Session, StepUsage, StreamEvent, Task, TaskArtifact, TaskMessage, TaskState, TaskStatusUpdate, TechStack, TelegramAdapter, ToolCallInput, ToolExecutor, ToolExecutorOptions, ToolResult, UsageSummary, UsageTracker, WhatsAppAdapter, agentConfigSchema$1 as agentConfigSchema, checkCapabilities, createAgentContext, createProvider, createSession, daemonConfigSchema, debug, detectSchemas, detectTechStack, ensureCredentials, executeClaudeCode, executeOrchestrator, executeSdk, executeTask, exportSession, formatSchemas, formatTechStack, formatToolsForSystemPrompt, gatherContext7Docs, generate, generateSkill, generateSkillMd, generateStream, getAnthropicTools, getCommand, getLegacyTools, getPackageInfo, globalHooks, globalPermissions, globalTracker, handleError, installSkillPackage, isCommand, isDebug, listInstalledSkills, listSessions, loadAuthConfig, loadDaemonConfig, loadHooks, loadLatestSession, loadLocalSkills, loadProjectInstructions, loadSession, logger, matchSkillsToTask, outputTypeDescriptions, parseCommand, parseSkillContent, parseSkillFile, permissionConfigSchema, permissionModeSchema, registerCommand, resolveAtImports, resolveOutputType, resolveToken, runModelSetup, saveAuthConfig, saveSession, setDebug, startMcpServer, validateWorkspaces };
2359
+ export { A2AClient, A2AMesh, A2AServer, A2AServerConfig, ALL_TOOL_NAMES, AgentCard, AgentConfig, AgentContext, AgentDef, AgentProvider, AgentRegistry, AgentResponse, AgentTask, AgentXDaemon, AgentXRuntime, AnthropicMessage, AuthConfig, BLOCKING_EVENTS, ChannelAdapter, ClaudeCodeProvider, ClaudeProvider, ContentBlock, ContextBuilder, CronJobDef, CronJobState, CronRunResult, CronScheduler, DaemonConfig, EnhanceConfig, EnhanceEngine, EnhanceResult, GenerateOptions, GenerateResult, GenerateStreamEvent, GeneratedFile, GenerationMessage, GenerationResult, GitCommitResult, GitDiffFile, GitLogEntry, GitManager, GitStatus, HOOK_EVENTS, HealConfig, HealEngine, HealResult, HookContext, HookDefinition, HookEvent, HookHandler, HookRegistry, HookResult, IncomingMessage, Memory, MemoryEntry, MemoryHierarchy, MemoryStore, MeshPeer, MessageRouter, MiddlewareFn, ModelUsage, OUTPUT_CONFIGS, OUTPUT_TYPES, OutgoingMessage, OutputConfig, OutputType, PERMISSION_MODES, PROVIDER_CAPABILITIES, PermissionAction, PermissionConfig, PermissionManager, PermissionMode, PermissionRule, Pipeline, PipelineRequest, PipelineResponse, ProjectSchemas, ProviderCapabilities, ProviderName, ProviderOptions, RawGenerationResult, ReplEngine, ReplOptions, RuntimeConfig, Session, StepUsage, StreamEvent, Task, TaskArtifact, TaskMessage, TaskState, TaskStatusUpdate, TechStack, TelegramAdapter, ToolCallInput, ToolExecutor, ToolExecutorOptions, ToolResult, UsageSummary, UsageTracker, WhatsAppAdapter, WikiAccess, WikiArticle, WikiArticleMeta, WikiEntry, WikiIndex, WikiStore, agentConfigSchema$1 as agentConfigSchema, checkCapabilities, createAgentContext, createProvider, createSession, daemonConfigSchema, debug, detectSchemas, detectTechStack, ensureCredentials, executeClaudeCode, executeOrchestrator, executeSdk, executeTask, exportSession, formatSchemas, formatTechStack, formatToolsForSystemPrompt, gatherContext7Docs, generate, generateSkill, generateSkillMd, generateStream, getAnthropicTools, getCommand, getLegacyTools, getPackageInfo, globalHooks, globalPermissions, globalTracker, handleError, installSkillPackage, isCommand, isDebug, listInstalledSkills, listSessions, loadAuthConfig, loadDaemonConfig, loadHooks, loadLatestSession, loadLocalSkills, loadProjectInstructions, loadSession, logger, matchSkillsToTask, outputTypeDescriptions, parseCommand, parseSkillContent, parseSkillFile, permissionConfigSchema, permissionModeSchema, registerCommand, resolveAtImports, resolveOutputType, resolveToken, runModelSetup, saveAuthConfig, saveSession, setDebug, startMcpServer, validateWorkspaces };
package/dist/index.js CHANGED
@@ -1,2 +1,86 @@
1
- import{A as _e,B as De,C as Ge,D as He,E as Le,F as Ue,G as we,H as Be,I as Fe,J as Ne,K as Ve,a as se,b as ae,c as pe,d as le,e as me,f as ge,g as fe,h as xe,i as ce,j as ue,k as de,l as Ce,m as ye,n as Se,o as ke,p as he,q as Ae,r as Te,s as Pe,t as ve,u as Re,v as Ee,w as Me,x as be,y as Oe,z as Ie}from"./chunk-THMHQELC.js";import{a as oe}from"./chunk-6PVFYFUE.js";import{A as Z,B as ee,C as te,D as re,E as ne,F as ie,a,b as p,c as l,d as v,e as R,f as E,g as _,h as D,i as G,j as H,k as L,l as U,m as w,n as B,o as F,p as N,q as V,r as j,s as $,t as J,u as K,v as W,w as X,x as Y,y as z,z as Q}from"./chunk-NZ6W33BD.js";import{a as M,b,c as O,d as I}from"./chunk-FRFR27IN.js";import{a as T,b as P,c as q}from"./chunk-SFQUP3BP.js";import{a as m,b as g,c as f,d as x,e as c,f as u,g as d,h as C,i as y,j as S,k,l as h,m as A}from"./chunk-FUYKPFUV.js";var s={"claude-code":{streaming:!0,tools:!0,vision:!0,thinking:!0,maxContext:1e6},claude:{streaming:!0,tools:!0,vision:!0,thinking:!0,maxContext:1e6},openai:{streaming:!0,tools:!0,vision:!0,thinking:!1,maxContext:128e3},ollama:{streaming:!0,tools:!1,vision:!1,thinking:!1,maxContext:32e3}};function je(e,n){let t=s[e];if(!t)return[`Unknown provider "${e}" \u2014 capabilities unknown`];if(!n?.length)return[];let i=[],o=[];for(let r of n)r in t&&!t[r]&&o.push(r);return o.length&&i.push(`Provider "${e}" lacks: ${o.join(", ")}. Some features will be degraded.`),i}export{Re as A2AClient,Ee as A2AMesh,ve as A2AServer,S as ALL_TOOL_NAMES,He as AgentRegistry,Fe as AgentXDaemon,fe as AgentXRuntime,H as BLOCKING_EVENTS,h as ClaudeCodeProvider,k as ClaudeProvider,ee as ContextBuilder,Be as CronScheduler,me as EnhanceEngine,ce as GitManager,G as HOOK_EVENTS,oe as HealEngine,V as HookRegistry,q as Memory,z as MemoryHierarchy,Le as MessageRouter,_ as OUTPUT_CONFIGS,p as OUTPUT_TYPES,J as PERMISSION_MODES,s as PROVIDER_CAPABILITIES,X as PermissionManager,ge as Pipeline,Pe as ReplEngine,Ue as TelegramAdapter,te as ToolExecutor,L as UsageTracker,we as WhatsAppAdapter,a as agentConfigSchema,je as checkCapabilities,re as createAgentContext,A as createProvider,ue as createSession,Me as daemonConfigSchema,F as debug,v as detectSchemas,T as detectTechStack,u as ensureCredentials,Ie as executeClaudeCode,De as executeOrchestrator,_e as executeSdk,Ge as executeTask,N as exportSession,R as formatSchemas,P as formatTechStack,y as formatToolsForSystemPrompt,E as gatherContext7Docs,ne as generate,le as generateSkill,ae as generateSkillMd,ie as generateStream,d as getAnthropicTools,he as getCommand,C as getLegacyTools,Ve as getPackageInfo,$ as globalHooks,Y as globalPermissions,U as globalTracker,Ne as handleError,se as installSkillPackage,Ae as isCommand,B as isDebug,pe as listInstalledSkills,Se as listSessions,g as loadAuthConfig,be as loadDaemonConfig,j as loadHooks,ye as loadLatestSession,M as loadLocalSkills,Z as loadProjectInstructions,Ce as loadSession,m as logger,I as matchSkillsToTask,l as outputTypeDescriptions,Te as parseCommand,O as parseSkillContent,b as parseSkillFile,W as permissionConfigSchema,K as permissionModeSchema,ke as registerCommand,Q as resolveAtImports,D as resolveOutputType,x as resolveToken,c as runModelSetup,f as saveAuthConfig,de as saveSession,w as setDebug,xe as startMcpServer,Oe as validateWorkspaces};
1
+ import{a as de,b as pe,c as pt,d as gt,e as mt,f as ut,g as ft,h as ht,i as yt,j as kt,k as wt,l as St,m as vt,n as xt,o as bt,p as Ct,q as Pt}from"./chunk-AIBBZF4E.js";import{a as H}from"./chunk-X7UN6JAA.js";import{a as Me,b as Ee,c as Oe,d as Ke,e as Be,f as We,g as ze,h as te,i as J,j as ot,k as rt,l as it,m as R,n as ne,o as at,p as ct,q as lt,r as dt,s as T,t as b,u as j}from"./chunk-F73GPYCO.js";import{a as Ve,b as Ye,c as Xe,d as F,e as Qe,f as Ze,g as et,h as se,i as tt,j as st,k as nt}from"./chunk-Z4GC5D6D.js";import{a as Z,b as qe,c as _,d as ee}from"./chunk-FRFR27IN.js";import{a as Q,b as x,c as U}from"./chunk-SFQUP3BP.js";import{a as Ne,b as _e,c as Fe,d as Je,e as Ue,f as He,g as G}from"./chunk-MGMZNJCE.js";import{a as m,b as Ie,c as Ge,d as je,e as Le,f as De}from"./chunk-M7HKBG3V.js";import"./chunk-4YCH6IZV.js";import{execa as $t}from"execa";import{existsSync as ge,promises as oe}from"fs";import C from"path";import fe from"node-fetch";async function Rt(o,e){let t=o.split("/");if(t.length<2)throw new Error(`Invalid skill package ID: ${o}. Expected format: owner/repo`);let s=t[0],r=t[1],n=t[2];try{let a=n?`${s}/${r}/${n}`:`${s}/${r}`;await $t("npx",["-y","skills","add",a],{cwd:e,stdio:"pipe"}),m.success(`Installed skill package: ${o}`);let i=C.resolve(e,".skills",`${s}_${r}`);if(ge(i))return await ue(i,o);let c=C.resolve(e,".skills");return ge(c)?await ue(c,o):[]}catch{return m.info(`Fetching skills directly from GitHub: ${s}/${r}`),await Tt(s,r,n,e)}}async function Tt(o,e,t,s){let r=[];try{let n=`https://api.github.com/repos/${o}/${e}/git/trees/main?recursive=1`,a=await fe(n);if(!a.ok)throw new Error(`GitHub API error: ${a.status}`);let c=(await a.json()).tree.filter(l=>l.type==="blob"&&l.path.endsWith("SKILL.md"));if(t){let l=c.find(g=>g.path.includes(`/${t}/`)||g.path===`${t}/SKILL.md`);if(l){let g=await me(o,e,l.path,s);g&&r.push(g)}}else for(let l of c){let g=await me(o,e,l.path,s);g&&r.push(g)}}catch(n){m.error(`Failed to fetch skills from GitHub: ${n.message}`)}return r}async function me(o,e,t,s){try{let r=`https://raw.githubusercontent.com/${o}/${e}/main/${t}`,n=await fe(r);if(!n.ok)return null;let a=await n.text(),i=_(a);if(i){i.source="remote",i.packageId=`${o}/${e}`;let c=C.dirname(t),l=C.resolve(s,".skills",`${o}_${e}`,c);await oe.mkdir(l,{recursive:!0}),await oe.writeFile(C.resolve(l,"SKILL.md"),a),i.path=C.resolve(l,"SKILL.md")}return i}catch{return null}}async function ue(o,e){let t=[],{default:s}=await import("fast-glob"),r=await s.glob("**/SKILL.md",{cwd:o,deep:5});for(let n of r)try{let a=C.resolve(o,n),i=await oe.readFile(a,"utf8"),c=_(i);c&&(c.source="remote",c.path=a,c.packageId=e,t.push(c))}catch{}return t}async function At(o,e,t,s,r){let n=["---",`name: ${o}`,`description: ${e}`];if(s?.length){n.push("tags:");for(let a of s)n.push(` - ${a}`)}if(r?.length){n.push("globs:");for(let a of r)n.push(` - ${a}`)}return n.push("---"),`${n.join(`
2
+ `)}
3
+
4
+ ${t}`}async function Mt(o){let{loadLocalSkills:e}=await import("./loader-6VSM6FSY.js");return e(o)}async function Et(o,e,t,s,r){let a=[{role:"system",content:`You are a skill author for the Agent Skills ecosystem (skills.sh).
5
+ You create high-quality SKILL.md files that provide reusable instructions for AI coding agents.
6
+
7
+ A skill is a markdown document with YAML frontmatter that teaches an agent how to perform a specific task.
8
+ Skills should be:
9
+ - Clear and actionable
10
+ - Tech-stack aware (use the right patterns for the project)
11
+ - Complete but concise
12
+ - Include examples where helpful
13
+ - Follow the Agent Skills specification
14
+
15
+ The project's tech stack:
16
+ ${x(s)}
17
+
18
+ Output ONLY the SKILL.md content (frontmatter + markdown instructions). Do not wrap in code fences.`},{role:"user",content:`Create a skill called "${e}" with this description: "${t}"${r?.tags?.length?`
19
+ Tags: ${r.tags.join(", ")}`:""}${r?.outputType?`
20
+ Primary output type: ${r.outputType}`:""}
21
+
22
+ The skill should contain detailed instructions for an AI agent to follow when performing this task in a project with the above tech stack. Include:
23
+ 1. Step-by-step instructions
24
+ 2. Code patterns and conventions to follow
25
+ 3. Common pitfalls to avoid
26
+ 4. Examples where helpful`}],c=(await o.generate(a,{temperature:.7,maxTokens:4096})).content.trim(),l={frontmatter:{name:e,description:t},instructions:c,source:"generated"},g=c.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);return g&&(l.instructions=g[2].trim()),{skill:l,content:c}}import{existsSync as Ot,promises as he}from"fs";import re from"path";var It={enabled:!0,autoSkills:!0,minFrequency:3,provider:"claude-code"},A=class{constructor(e,t,s){this.cwd=e;this.memory=t;this.config={...It,...s}}config;async enhance(){if(!this.config.enabled)return{skillsCreated:[],skillsUpdated:[],insights:[]};let e={skillsCreated:[],skillsUpdated:[],insights:[]};if(this.config.autoSkills){let r=await this.createSkillsFromPatterns();e.skillsCreated.push(...r)}let t=this.analyzeFailures();e.insights.push(...t);let s=this.analyzePreferences();return e.insights.push(...s),e}async createSkillsFromPatterns(){let t=this.memory.getPatterns().filter(n=>n.frequency>=this.config.minFrequency);if(!t.length)return[];let s=[],r=re.resolve(this.cwd,".skills","_auto");for(let n of t.slice(0,3)){let a=Gt(n),i=re.resolve(r,a,"SKILL.md");if(!Ot(i))try{let c=await this.generateSkillFromPattern(n);c&&(await he.mkdir(re.dirname(i),{recursive:!0}),await he.writeFile(i,c,"utf8"),s.push(a))}catch{}}return s}async generateSkillFromPattern(e){let t=this.memory.getRecentGenerations(20).filter(i=>i.success&&i.userFeedback!=="negative").slice(0,3);if(!t.length)return null;let s=G(this.config.provider,this.config.apiKey),r=await Q(this.cwd),n=[{role:"system",content:`You are a skill author. Create a SKILL.md file that captures a successful pattern.
27
+ Tech stack: ${x(r)}
28
+ Output ONLY the SKILL.md content with YAML frontmatter. No code fences.`},{role:"user",content:`Create a skill from this recurring pattern:
29
+
30
+ Pattern: ${e.description}
31
+ Frequency: used ${e.frequency} times
32
+ Tech stack: ${e.techStack.join(", ")||"general"}
33
+
34
+ Successful examples:
35
+ ${t.map(i=>`- "${i.task}" \u2192 ${i.files.join(", ")}`).join(`
36
+ `)}
37
+
38
+ Create a concise, reusable skill that captures what worked.`}];return(await s.generate(n,{maxTokens:2048,temperature:.7})).content.trim()||null}analyzeFailures(){let e=[],t=this.memory.getFailedGenerations(20);if(t.length<2)return e;let s=new Map;for(let n of t){let a=(n.error||"unknown").split(`
39
+ `)[0].slice(0,80),i=s.get(a)||[];i.push(n),s.set(a,i)}for(let[n,a]of s)a.length>=2&&e.push(`Recurring error (${a.length}x): "${n}" \u2014 consider creating a skill to prevent this`);let r=this.memory.getStats();return r.successRate<.7&&r.totalGenerations>5&&e.push(`Success rate is ${(r.successRate*100).toFixed(0)}% \u2014 review recent failures and update skills`),e}analyzePreferences(){let e=[],s=this.memory.getPreferences().filter(r=>r.confidence>.8);return s.length&&e.push(`Strong preferences detected: ${s.map(r=>`${r.key}=${r.value}`).join(", ")}`),e}};function Gt(o){return o.description.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").slice(0,40).replace(/-+$/,"")}var M=class{middleware=[];use(e,t){return this.middleware.push({name:e,fn:t}),this}async execute(e){let t={id:e.id,success:!1,files:[],content:"",outputType:e.outputType||"auto",duration:0},s={startTime:Date.now()},r=0,n=async()=>{if(r>=this.middleware.length)return;await this.middleware[r++].fn(e,t,s,n)};try{await n(),t.duration=Date.now()-s.startTime}catch(a){t.success=!1,t.error=a.message,t.duration=Date.now()-s.startTime}return t}getMiddlewareNames(){return this.middleware.map(e=>e.name)}};import{createServer as jt}from"http";var Lt={port:3170,host:"0.0.0.0",provider:"claude-code",cwd:process.cwd(),memory:{enabled:!0},heal:{enabled:!0},enhance:{enabled:!0,autoSkills:!0},cors:!0},K=class{config;memory;healEngine;enhanceEngine;pipeline;requestCount=0;log;constructor(e){this.config={...Lt,...e},this.memory=new U(this.config.cwd),this.healEngine=new H(this.config.cwd,{enabled:this.config.heal.enabled,testCommand:this.config.heal.testCommand,buildCommand:this.config.heal.buildCommand,provider:this.config.provider,model:this.config.model,apiKey:this.config.apiKey}),this.enhanceEngine=new A(this.config.cwd,this.memory,{enabled:this.config.enhance.enabled,autoSkills:this.config.enhance.autoSkills,provider:this.config.provider,model:this.config.model,apiKey:this.config.apiKey}),this.pipeline=this.buildPipeline(),this.log=console.error.bind(console,"[agentx]")}buildPipeline(){let e=new M;return e.use("memory",this.memoryMiddleware()),e.use("context",this.contextMiddleware()),e.use("generate",this.generateMiddleware()),e.use("heal",this.healMiddleware()),e.use("record",this.recordMiddleware()),e.use("enhance",this.enhanceMiddleware()),e}async start(){await this.memory.load(),jt(async(t,s)=>{if(this.config.cors&&(s.setHeader("Access-Control-Allow-Origin","*"),s.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),s.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),t.method==="OPTIONS")){s.writeHead(204),s.end();return}await this.handleRequest(t,s)}).listen(this.config.port,this.config.host,()=>{this.log(`
40
+ agentx runtime v0.1.0`),this.log(` Listening on http://${this.config.host}:${this.config.port}`),this.log(` Provider: ${this.config.provider}`),this.log(` Memory: ${this.config.memory.enabled?"enabled":"disabled"}`),this.log(` Auto-heal: ${this.config.heal.enabled?"enabled":"disabled"}`),this.log(` Self-enhance: ${this.config.enhance.enabled?"enabled":"disabled"}`),this.log(` Pipeline: ${this.pipeline.getMiddlewareNames().join(" \u2192 ")}`),this.log(` Working dir: ${this.config.cwd}`),this.log(""),this.log(" Endpoints:"),this.log(" POST /generate \u2014 generate code/content"),this.log(" POST /evolve \u2014 transform existing code"),this.log(" GET /inspect \u2014 project analysis"),this.log(" GET /memory \u2014 view learning history"),this.log(" POST /feedback \u2014 provide feedback on a generation"),this.log(" GET /health \u2014 health check"),this.log(" POST /enhance \u2014 trigger self-enhancement"),this.log("")})}async handleRequest(e,t){let s=new URL(e.url||"/",`http://${e.headers.host||"localhost"}`),r=e.method||"GET",n=s.pathname;this.log(`${r} ${n}`);try{switch(`${r} ${n}`){case"POST /generate":await this.handleGenerate(e,t);break;case"POST /evolve":await this.handleEvolve(e,t);break;case"GET /inspect":await this.handleInspect(t);break;case"GET /memory":await this.handleMemory(t);break;case"POST /feedback":await this.handleFeedback(e,t);break;case"GET /health":this.sendJson(t,200,{status:"ok",uptime:process.uptime(),requests:this.requestCount,stats:this.memory.getStats(),pipeline:this.pipeline.getMiddlewareNames()});break;case"POST /enhance":await this.handleEnhance(t);break;default:this.sendJson(t,404,{error:"Not found",endpoints:["POST /generate","POST /evolve","GET /inspect","GET /memory","POST /feedback","GET /health","POST /enhance"]})}}catch(a){this.log("Error:",a.message),this.sendJson(t,500,{error:a.message})}this.requestCount++}async handleGenerate(e,t){let s=await ie(e);if(!s.task){this.sendJson(t,400,{error:"Missing required field: task"});return}let r={id:`req-${Date.now().toString(36)}`,task:s.task,outputType:s.type||s.outputType||"auto",outputDir:s.outputDir||s.output_dir,provider:s.provider||this.config.provider,model:s.model||this.config.model,apiKey:s.apiKey||s.api_key||this.config.apiKey,cwd:this.config.cwd,overwrite:s.overwrite??!0,metadata:s.metadata},n=await this.pipeline.execute(r);this.sendJson(t,n.success?200:500,n)}async handleEvolve(e,t){let s=await ie(e);if(!s.task||!s.glob){this.sendJson(t,400,{error:"Missing required fields: task, glob"});return}this.sendJson(t,200,{message:'Use the CLI for evolve: agentx evolve "'+s.task+'" --glob "'+s.glob+'"',hint:"The evolve endpoint requires interactive diff review. Use the CLI for full functionality."})}async handleInspect(e){let t=await T(this.config.cwd,"inspect",{context7:{enabled:!1}});this.sendJson(e,200,{techStack:{languages:t.techStack.languages,frameworks:t.techStack.frameworks,packageManager:t.techStack.packageManager,databases:t.techStack.databases,styling:t.techStack.styling,testing:t.techStack.testing,deployment:t.techStack.deployment,monorepo:t.techStack.monorepo},schemas:{database:t.schemas.database?{type:t.schemas.database.type,tables:t.schemas.database.tables}:null,api:t.schemas.api?{type:t.schemas.api.type}:null,env:t.schemas.env,models:t.schemas.models?.map(s=>({path:s.path,type:s.type}))},skills:t.skills.map(s=>({name:s.frontmatter.name,description:s.frontmatter.description,source:s.source,tags:s.frontmatter.tags})),dependencies:Object.keys(t.techStack.dependencies).length,devDependencies:Object.keys(t.techStack.devDependencies).length})}async handleMemory(e){this.sendJson(e,200,{stats:this.memory.getStats(),recent:this.memory.getRecentGenerations(10),patterns:this.memory.getPatterns().slice(0,10),preferences:this.memory.getPreferences()})}async handleFeedback(e,t){let s=await ie(e);if(!s.entryId||!s.feedback){this.sendJson(t,400,{error:"Missing required fields: entryId, feedback (positive/negative/neutral)"});return}await this.memory.recordFeedback(s.entryId,s.feedback),this.sendJson(t,200,{recorded:!0})}async handleEnhance(e){let t=await this.enhanceEngine.enhance();this.sendJson(e,200,t)}memoryMiddleware(){let e=this.memory;return async(t,s,r,n)=>{r.memory=e;let a=e.buildMemoryContext(t.task);a&&(r.memoryContext=a),await n()}}contextMiddleware(){return async(e,t,s,r)=>{s.agentContext=await T(e.cwd,e.task,{provider:e.provider,context7:{enabled:!0}}),await r()}}generateMiddleware(){return async(e,t,s,r)=>{let n=await b({task:s.memoryContext?`${e.task}
41
+
42
+ ${s.memoryContext}`:e.task,outputType:e.outputType,outputDir:e.outputDir,overwrite:e.overwrite??!0,cwd:e.cwd,provider:e.provider||this.config.provider,model:e.model||this.config.model,apiKey:e.apiKey||this.config.apiKey,context7:!0,interactive:!1,maxSteps:5});t.success=n.files.errors.length===0,t.files=n.files.written.map(a=>({path:a})),t.content=n.content,t.outputType=n.outputType,t.tokensUsed=n.tokensUsed,await r()}}healMiddleware(){let e=this.healEngine;return async(t,s,r,n)=>{if(this.config.heal.enabled&&s.files.length>0){let a=await e.detectAndHeal(s.files.map(i=>i.path),t.task,s.memoryEntryId);a.attempts>0&&(s.healed=a.healed,s.healAttempts=a.attempts,a.healed&&(s.success=!0))}await n()}}recordMiddleware(){let e=this.memory;return async(t,s,r,n)=>{if(this.config.memory.enabled){let a=await e.recordGeneration({task:t.task,outputType:s.outputType,files:s.files.map(i=>i.path),success:s.success,error:s.error,context:{techStack:r.agentContext?.techStack.languages.map(i=>i.name),frameworks:r.agentContext?.techStack.frameworks.map(i=>i.name)}});s.memoryEntryId=a,t.outputType&&t.outputType!=="auto"&&await e.learnPreference("preferred-output-type",t.outputType,`generation request: ${t.task.slice(0,50)}`)}await n()}}enhanceMiddleware(){let e=this.enhanceEngine;return async(t,s,r,n)=>{this.config.enhance.enabled&&this.requestCount%10===0&&this.requestCount>0&&e.enhance().then(a=>{if(a.skillsCreated.length&&this.log(`Auto-created ${a.skillsCreated.length} skill(s): ${a.skillsCreated.join(", ")}`),a.insights.length)for(let i of a.insights)this.log(`Insight: ${i}`)}).catch(()=>{}),await n()}}sendJson(e,t,s){e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify(s,null,2))}};async function ie(o){return new Promise((e,t)=>{let s="";o.on("data",r=>s+=r),o.on("end",()=>{try{e(s?JSON.parse(s):{})}catch{e({})}}),o.on("error",t)})}var Dt={name:"agentx",version:"0.1.0"},Nt="2024-11-05",_t={tools:{}},Ft=[{name:"agentx_generate",description:"Generate code, components, pages, APIs, documents, tests, workflows, schemas, emails, diagrams, and more using AI. Understands the project's tech stack, schemas, and skills automatically.",inputSchema:{type:"object",properties:{task:{type:"string",description:"Describe what to generate (e.g., 'a responsive pricing card', 'REST API for users', 'GitHub Actions CI pipeline')"},type:{type:"string",description:"Output type: component, page, api, website, document, script, config, skill, media, report, test, workflow, schema, email, diagram, auto",default:"auto"},output_dir:{type:"string",description:"Optional output directory (relative to project root)"},cwd:{type:"string",description:"Project working directory (defaults to current directory)"}},required:["task"]}},{name:"agentx_inspect",description:"Analyze a project and return its tech stack, frameworks, databases, schemas, installed skills, and dependencies. Use this to understand a project before generating code.",inputSchema:{type:"object",properties:{cwd:{type:"string",description:"Project working directory (defaults to current directory)"}}}},{name:"agentx_skill_match",description:"Find installed skills that are relevant to a given task description. Returns matched skills with relevance scores.",inputSchema:{type:"object",properties:{task:{type:"string",description:"The task to match skills against"},cwd:{type:"string",description:"Project working directory"}},required:["task"]}},{name:"agentx_detect_output_type",description:"Auto-detect the best output type for a given task description based on keyword analysis.",inputSchema:{type:"object",properties:{task:{type:"string",description:"The task description to analyze"}},required:["task"]}}];async function Jt(o,e){let t=e.cwd||process.cwd();switch(o){case"agentx_generate":{let s=e.task,r=e.type||"auto",n=e.output_dir,a=await b({task:s,outputType:r,outputDir:n,cwd:t,overwrite:!0,dryRun:!1,context7:!0,interactive:!1,maxSteps:5}),i=[];return a.content&&i.push(a.content),a.files.written.length&&i.push(`
43
+ Created ${a.files.written.length} file(s):
44
+ ${a.files.written.map(c=>` - ${c}`).join(`
45
+ `)}`),a.files.skipped.length&&i.push(`
46
+ Skipped ${a.files.skipped.length} existing file(s):
47
+ ${a.files.skipped.map(c=>` - ${c}`).join(`
48
+ `)}`),a.followUp&&i.push(`
49
+ Needs clarification: ${a.followUp}`),{content:[{type:"text",text:i.join(`
50
+ `)||"Generation complete."}]}}case"agentx_inspect":{let s=await T(t,"inspect",{context7:{enabled:!1}}),r={languages:s.techStack.languages,frameworks:s.techStack.frameworks,packageManager:s.techStack.packageManager,databases:s.techStack.databases,styling:s.techStack.styling,testing:s.techStack.testing,deployment:s.techStack.deployment,monorepo:s.techStack.monorepo,srcDir:s.techStack.srcDir,dependencyCount:Object.keys(s.techStack.dependencies).length,devDependencyCount:Object.keys(s.techStack.devDependencies).length,schemas:{database:s.schemas.database?{type:s.schemas.database.type,tables:s.schemas.database.tables}:null,api:s.schemas.api?{type:s.schemas.api.type}:null,env:s.schemas.env?{variableCount:s.schemas.env.variables.length}:null,models:s.schemas.models?.map(n=>n.path)||[]},skills:s.skills.map(n=>({name:n.frontmatter.name,description:n.frontmatter.description,source:n.source}))};return{content:[{type:"text",text:`Project analysis:
51
+
52
+ ${x(s.techStack)}
53
+
54
+ ${JSON.stringify(r,null,2)}`}]}}case"agentx_skill_match":{let s=e.task,r=await Z(t),n=ee(r,s);return n.length?{content:[{type:"text",text:`Matching skills:
55
+
56
+ ${n.map(i=>`- **${i.skill.frontmatter.name}** (relevance: ${(i.relevance*100).toFixed(0)}%)
57
+ ${i.skill.frontmatter.description}
58
+ Match: ${i.matchReason}`).join(`
59
+
60
+ `)}`}]}:{content:[{type:"text",text:"No matching skills found. Install skills with: agentx skill install <owner/repo>"}]}}case"agentx_detect_output_type":{let s=e.task;return{content:[{type:"text",text:`Detected output type: ${te(void 0,s)}`}]}}default:throw new Error(`Unknown tool: ${o}`)}}async function Ut(){let o=(...t)=>console.error("[agentx-mcp]",...t);o("Starting MCP server (stdio transport)...");let e="";process.stdin.setEncoding("utf8"),process.stdin.on("data",t=>{for(e+=t;;){let s=e.indexOf(`\r
61
+ \r
62
+ `);if(s===-1)break;let n=e.slice(0,s).match(/Content-Length:\s*(\d+)/);if(!n){let g=e.indexOf(`
63
+ `);if(g===-1)break;let f=e.slice(0,g).trim();if(e=e.slice(g+1),f)try{let y=JSON.parse(f);ye(y,o).catch($=>o("Error:",$))}catch{}continue}let a=parseInt(n[1],10),i=s+4,c=i+a;if(e.length<c)break;let l=e.slice(i,c);e=e.slice(c);try{let g=JSON.parse(l);ye(g,o).catch(f=>o("Error:",f))}catch(g){o("Failed to parse message:",g)}}}),process.stdin.on("end",()=>{o("stdin closed, shutting down."),process.exit(0)})}function E(o){let e=JSON.stringify(o),t=`Content-Length: ${Buffer.byteLength(e)}\r
64
+ \r
65
+ `;process.stdout.write(t+e)}async function ye(o,e){let{method:t,id:s,params:r}=o;switch(e(`Received: ${t}`),t){case"initialize":{E({jsonrpc:"2.0",id:s,result:{protocolVersion:Nt,capabilities:_t,serverInfo:Dt}});break}case"notifications/initialized":{e("Client initialized.");break}case"tools/list":{E({jsonrpc:"2.0",id:s,result:{tools:Ft}});break}case"tools/call":{let n=r?.name,a=r?.arguments||{};try{let i=await Jt(n,a);E({jsonrpc:"2.0",id:s,result:i})}catch(i){E({jsonrpc:"2.0",id:s,result:{content:[{type:"text",text:`Error: ${i.message}`}],isError:!0}})}break}case"ping":{E({jsonrpc:"2.0",id:s,result:{}});break}default:s!==void 0&&E({jsonrpc:"2.0",id:s,error:{code:-32601,message:`Method not found: ${t}`}})}}import{execa as h}from"execa";var w=class{constructor(e){this.cwd=e}async isRepo(){try{return await h("git",["rev-parse","--is-inside-work-tree"],{cwd:this.cwd,reject:!1}),!0}catch{return!1}}async status(){let t=(await h("git",["status","--porcelain","-b"],{cwd:this.cwd,reject:!1})).stdout.trim().split(`
66
+ `).filter(Boolean),s="unknown",r=[],n=[],a=[],i=[];for(let c of t){if(c.startsWith("## ")){s=c.slice(3).split("...")[0];continue}let l=c[0],g=c[1],f=c.slice(3).trim();(l==="A"||l==="M"||l==="R")&&r.push(f),l==="D"&&(i.push(f),r.push(f)),g==="M"&&n.push(f),g==="D"&&i.push(f),l==="?"&&g==="?"&&a.push(f)}return{staged:r,modified:n,untracked:a,deleted:[...new Set(i)],branch:s,isClean:r.length===0&&n.length===0&&a.length===0}}async diff(e=!1){return(await h("git",e?["diff","--cached"]:["diff"],{cwd:this.cwd,reject:!1})).stdout}async diffStat(e=!1){let s=await h("git",e?["diff","--cached","--numstat"]:["diff","--numstat"],{cwd:this.cwd,reject:!1}),r=[];for(let n of s.stdout.trim().split(`
67
+ `).filter(Boolean)){let[a,i,c]=n.split(" ");if(!c)continue;let l="modified";a==="-"&&i==="-"&&(l="renamed"),r.push({path:c,status:l,additions:parseInt(a)||0,deletions:parseInt(i)||0})}return r}async log(e=10){let t=await h("git",["log",`--max-count=${e}`,"--format=%H|%h|%s|%an|%ai"],{cwd:this.cwd,reject:!1});return t.stdout.trim()?t.stdout.trim().split(`
68
+ `).filter(Boolean).map(s=>{let[r,n,a,i,c]=s.split("|");return{hash:r,shortHash:n,message:a,author:i,date:c}}):[]}async add(e){e.length&&await h("git",["add",...e],{cwd:this.cwd})}async addAll(){await h("git",["add","-A"],{cwd:this.cwd})}async commit(e){let t=await h("git",["commit","-m",e],{cwd:this.cwd,reject:!1});if(t.exitCode!==0)throw new Error(t.stderr||t.stdout||"Git commit failed");let r=t.stdout.match(/\[[\w/.-]+\s+(\w+)\]/)?.[1]||"unknown",n=t.stdout.match(/(\d+)\s+files?\s+changed/),a=parseInt(n?.[1]||"0");return{hash:r,message:e,filesChanged:a}}async currentBranch(){return(await h("git",["branch","--show-current"],{cwd:this.cwd,reject:!1})).stdout.trim()}async createBranch(e){await h("git",["checkout","-b",e],{cwd:this.cwd})}async checkout(e){await h("git",["checkout",e],{cwd:this.cwd})}async stash(e){let t=["stash","push"];e&&t.push("-m",e),await h("git",t,{cwd:this.cwd})}async stashPop(){await h("git",["stash","pop"],{cwd:this.cwd})}async generateCommitMessage(e){let t=await this.diff(!0);if(!t.trim())throw new Error("No staged changes to commit");return e?(await e.generate([{role:"system",content:`You are a git commit message generator. Generate a conventional commit message (type(scope): subject) from the given diff.
69
+ Rules:
70
+ - Use conventional commit format: feat|fix|refactor|docs|test|chore|style(scope): message
71
+ - Keep the subject line under 72 characters
72
+ - Be specific about what changed
73
+ - Output ONLY the commit message, nothing else`},{role:"user",content:`Generate a commit message for this diff:
74
+
75
+ ${t.slice(0,4e3)}`}])).content.trim().split(`
76
+ `)[0]:this.fallbackCommitMessage(t)}fallbackCommitMessage(e){let t=e.split(`
77
+ `),s=[];for(let r of t)if(r.startsWith("diff --git")){let n=r.match(/b\/(.+)$/);n&&s.push(n[1])}return s.length===0?"chore: update files":s.length===1?`chore: update ${s[0]}`:`chore: update ${s.length} files`}};import{createInterface as Yt}from"readline";import v from"chalk";import Xt from"ora";import{existsSync as ke,mkdirSync as Ht,readFileSync as ae,readdirSync as we,writeFileSync as Kt}from"fs";import L from"path";import Bt from"os";var S=L.join(Bt.homedir(),".agentx","sessions");function ce(){ke(S)||Ht(S,{recursive:!0})}function O(o){return{id:Wt(),createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),cwd:o,messages:[],tokensUsed:0,filesGenerated:[]}}function I(o){ce();let e=L.join(S,`${o.id}.json`);o.updatedAt=new Date().toISOString(),Kt(e,JSON.stringify(o,null,2),"utf8")}function P(o){let e=L.join(S,`${o}.json`);if(!ke(e))return null;try{return JSON.parse(ae(e,"utf8"))}catch{return null}}function B(){ce();let o=we(S).filter(t=>t.endsWith(".json")).map(t=>({name:t,path:L.join(S,t)}));if(!o.length)return null;let e=null;for(let t of o)try{let s=JSON.parse(ae(t.path,"utf8"));(!e||s.updatedAt>e.session.updatedAt)&&(e={name:t.name,session:s})}catch{}return e?.session??null}function W(){ce();let o=we(S).filter(t=>t.endsWith(".json")),e=[];for(let t of o)try{let s=JSON.parse(ae(L.join(S,t),"utf8"));e.push(s)}catch{}return e.sort((t,s)=>s.updatedAt.localeCompare(t.updatedAt)),e}function Wt(){return Math.random().toString(36).slice(2,10)+Date.now().toString(36).slice(-4)}import p from"chalk";import{writeFileSync as qt}from"fs";import zt from"path";import d from"chalk";function Se(o,e){console.log(),console.log(d.bold.cyan(" agentx")+d.dim(` v${o}`)),console.log(d.dim(` Session: ${e}`)),console.log(d.dim(" Type /help for commands, /quit to exit")),console.log()}function ve(o){if(o.written.length){console.log(),console.log(d.green(` Created ${o.written.length} file(s):`));for(let e of o.written)console.log(` ${d.green("+")} ${e}`)}if(o.skipped.length){console.log(),console.log(d.yellow(` Skipped ${o.skipped.length} file(s):`));for(let e of o.skipped)console.log(` ${d.yellow("~")} ${e}`)}if(o.errors.length){console.log(),console.log(d.red(` Failed ${o.errors.length} file(s):`));for(let e of o.errors)console.log(` ${d.red("x")} ${e}`)}}function D(o){let e=o/1e6*9;console.log(),console.log(d.dim(` Tokens: ${o.toLocaleString()} | Est. cost: $${e.toFixed(4)}`))}function xe(o){process.stdout.write(o)}function be(){console.log(),console.log(d.bold(" Commands:")),console.log(),console.log(` ${d.cyan("/help")} Show this help`),console.log(` ${d.cyan("/clear")} Clear conversation history`),console.log(` ${d.cyan("/save")} Save current session`),console.log(` ${d.cyan("/load")} Load a saved session`),console.log(` ${d.cyan("/undo")} Undo last generation`),console.log(` ${d.cyan("/cost")} Show token usage and cost breakdown`),console.log(` ${d.cyan("/export")} Export session as markdown`),console.log(` ${d.cyan("/files")} List generated files`),console.log(` ${d.cyan("/context")} Show session context info`),console.log(` ${d.cyan("/memory")} Show memory stats and preferences`),console.log(` ${d.cyan("/mode")} Switch permission mode`),console.log(` ${d.cyan("/commit")} Commit generated files with AI message`),console.log(` ${d.cyan("/diff")} Show git diff`),console.log(` ${d.cyan("/status")} Show git status`),console.log(` ${d.cyan("/quit")} Exit the REPL`),console.log()}function Ce(o){if(console.log(),console.log(d.dim(` Branch: ${o.branch}`)),o.isClean){console.log(d.green(" Working tree clean"));return}o.staged.length&&console.log(d.green(` Staged: ${o.staged.length}`)),o.modified.length&&console.log(d.yellow(` Modified: ${o.modified.length}`)),o.untracked.length&&console.log(d.dim(` Untracked: ${o.untracked.length}`)),console.log()}function Pe(o){if(console.log(),console.log(d.bold(" Cost Breakdown")),console.log(),console.log(d.dim(` Total: ${o.totalTokens.toLocaleString()} tokens ($${o.totalCost.toFixed(4)})`)),console.log(d.dim(` Input: ${o.totalInputTokens.toLocaleString()} | Output: ${o.totalOutputTokens.toLocaleString()}`)),Object.keys(o.models).length){console.log(),console.log(d.dim(" Per model:"));for(let[e,t]of Object.entries(o.models))console.log(` ${d.cyan(e)}: ${(t.inputTokens+t.outputTokens).toLocaleString()} tokens, $${t.cost.toFixed(4)} (${t.steps} step${t.steps!==1?"s":""})`)}if(o.steps.length>1){console.log(),console.log(d.dim(" Per step:"));for(let e of o.steps)console.log(` Step ${e.step}: ${(e.inputTokens+e.outputTokens).toLocaleString()} tokens ($${e.cost.toFixed(4)})`)}console.log()}function $e(o){console.log(),console.log(d.bold(" Plan Preview")),console.log(d.dim(" No files will be written in plan mode.")),console.log();for(let e of o){let t=e.action==="create"?d.green("+"):d.yellow("~");console.log(` ${t} ${e.path} (${e.action})`)}console.log()}import Vt from"prompts";var Re={};function u(o,e){Re[o]=e}function q(o){return Re[o]}function z(o){return o.startsWith("/")}function V(o){let e=o.trim(),t=e.indexOf(" ");return t===-1?{name:e.slice(1),args:""}:{name:e.slice(1,t),args:e.slice(t+1).trim()}}u("help",async()=>(be(),!0));u("quit",async()=>!1);u("exit",async()=>!1);u("q",async()=>!1);u("clear",async(o,e)=>(e.session.messages=[],console.log(p.dim(" Conversation cleared")),!0));u("save",async(o,e)=>(I(e.session),console.log(p.dim(` Session saved: ${e.session.id}`)),!0));u("load",async(o,e)=>{let t=null;if(o){if(t=P(o),!t)return m.warn(`Session not found: ${o}`),!0}else{let s=W();if(!s.length)return m.info("No saved sessions"),!0;let{sessionId:r}=await Vt({type:"select",name:"sessionId",message:"Select a session",choices:s.slice(0,10).map(n=>({title:`${n.id} \u2014 ${new Date(n.updatedAt).toLocaleDateString()} (${n.messages.length} messages)`,value:n.id}))});if(!r)return!0;t=P(r)}return t&&(e.onSessionChange(t),console.log(p.dim(` Loaded session: ${t.id} (${t.messages.length} messages)`))),!0});u("undo",async(o,e)=>{let t=e.session.messages;return t.length<2?(m.info("Nothing to undo"),!0):(t[t.length-1]?.role==="assistant"&&t.pop(),t[t.length-1]?.role==="user"&&t.pop(),console.log(p.dim(" Undid last exchange")),!0)});u("cost",async(o,e)=>{let t=F.getSummary();return t.steps.length>0?Pe(t):D(e.session.tokensUsed),!0});u("export",async(o,e)=>{let t=F.getSummary(),s=se(e.session,t.steps.length?t:void 0),r=o||`session-${e.session.id}.md`,n=zt.resolve(e.cwd,r);return qt(n,s,"utf8"),m.success(` Session exported to ${n}`),!0});u("files",async(o,e)=>{let t=e.session.filesGenerated;if(!t.length)return m.info("No files generated in this session"),!0;console.log(),console.log(p.dim(` Files generated (${t.length}):`));for(let s of t)console.log(` ${p.green("+")} ${s}`);return console.log(),!0});u("context",async(o,e)=>(console.log(),console.log(p.dim(` Session: ${e.session.id}`)),console.log(p.dim(` CWD: ${e.session.cwd}`)),console.log(p.dim(` Messages: ${e.session.messages.length}`)),console.log(p.dim(` Tokens: ${e.session.tokensUsed.toLocaleString()}`)),console.log(p.dim(` Files: ${e.session.filesGenerated.length}`)),console.log(p.dim(` Created: ${new Date(e.session.createdAt).toLocaleString()}`)),console.log(),!0));u("memory",async(o,e)=>{try{let t=new ne(e.cwd);await t.load();let s=t.getStats(),r=t.getPreferences(),n=t.getPatterns(),a=t.getRecentGenerations(5);if(console.log(),console.log(p.bold(" Memory")),console.log(),console.log(p.dim(" Project:")),console.log(p.dim(` Generations: ${s.project.totalGenerations}`)),console.log(p.dim(` Success rate: ${(s.project.successRate*100).toFixed(0)}%`)),console.log(p.dim(` Heals: ${s.project.totalHeals}`)),console.log(),console.log(p.dim(" Global:")),console.log(p.dim(` Generations: ${s.user.totalGenerations}`)),console.log(p.dim(` Success rate: ${(s.user.successRate*100).toFixed(0)}%`)),r.length){console.log(),console.log(p.dim(" Preferences:"));for(let i of r.slice(0,10))console.log(p.dim(` ${i.key}: ${i.value} (${(i.confidence*100).toFixed(0)}%)`))}if(n.length){console.log(),console.log(p.dim(" Patterns:"));for(let i of n.slice(0,5))console.log(p.dim(` ${i.description} (${i.frequency}x)`))}if(a.length){console.log(),console.log(p.dim(" Recent:"));for(let i of a){let c=i.success?p.green("ok"):p.red("fail");console.log(p.dim(` [${c}] ${i.task.slice(0,60)}`))}}console.log()}catch(t){m.error(` ${t.message}`)}return!0});u("mode",async(o,e)=>{if(o&&J.includes(o))R.setMode(o),m.success(` Permission mode: ${o}`);else if(o)m.warn(` Unknown mode: ${o}. Valid modes: ${J.join(", ")}`);else{let t=R.getMode();console.log(),console.log(p.dim(` Current mode: ${p.bold(t)}`)),console.log(),console.log(p.dim(" Available modes:")),console.log(p.dim(" default \u2014 confirm each file write")),console.log(p.dim(" acceptEdits \u2014 auto-allow writes, confirm destructive ops")),console.log(p.dim(" plan \u2014 show plan without writing")),console.log(p.dim(" yolo \u2014 auto-allow everything")),console.log(),console.log(p.dim(" Usage: /mode <mode>")),console.log()}return!0});u("commit",async(o,e)=>{try{let t=new w(e.cwd);if(!await t.isRepo())return m.warn("Not a git repository"),!0;let s=e.session.filesGenerated.filter(i=>i);if(s.length&&(await t.add(s),console.log(p.dim(` Staged ${s.length} generated file(s)`))),(await t.status()).staged.length===0)return m.warn("Nothing staged to commit"),!0;let n;try{let i=G();n=await t.generateCommitMessage(i)}catch{n=await t.generateCommitMessage()}console.log(p.dim(` Message: ${n}`));let a=await t.commit(n);m.success(` [${a.hash}] ${a.message}`)}catch(t){m.error(` ${t.message}`)}return!0});u("diff",async(o,e)=>{try{let s=await new w(e.cwd).diff();s.trim()?console.log(s):m.info("No changes")}catch(t){m.error(` ${t.message}`)}return!0});u("status",async(o,e)=>{try{let t=new w(e.cwd);if(!await t.isRepo())return m.warn("Not a git repository"),!0;let s=await t.status();Ce(s)}catch(t){m.error(` ${t.message}`)}return!0});var Y=class{rl=null;session;options;running=!1;constructor(e){if(this.options=e,e.sessionId){let t=P(e.sessionId);t?this.session=t:(m.warn(`Session ${e.sessionId} not found, starting new session`),this.session=O(e.cwd))}else if(e.resume){let t=B();t?(this.session=t,m.info(`Resumed session: ${t.id}`)):(m.info("No previous session found, starting new session"),this.session=O(e.cwd))}else this.session=O(e.cwd)}async start(){this.running=!0,Se(this.options.version,this.session.id),this.session.messages.length>0&&(console.log(v.dim(` Resumed with ${this.session.messages.length} messages, ${this.session.tokensUsed.toLocaleString()} tokens`)),console.log()),this.rl=Yt({input:process.stdin,output:process.stdout,prompt:v.cyan("agentx > "),terminal:!0}),this.rl.prompt(),this.rl.on("line",async e=>{let t=e.trim();if(!t){this.rl?.prompt();return}try{if(z(t)){if(!await this.handleCommand(t)){this.stop();return}}else await this.handleGeneration(t)}catch(s){m.error(` Error: ${s.message}`)}this.running&&this.rl?.prompt()}),this.rl.on("close",()=>{this.stop()}),this.rl.on("SIGINT",()=>{console.log(),this.stop()})}stop(){this.running=!1,I(this.session),console.log(),console.log(v.dim(` Session saved: ${this.session.id}`)),D(this.session.tokensUsed),console.log(),this.rl?.close(),process.exit(0)}async handleCommand(e){let{name:t,args:s}=V(e),r=q(t);if(!r)return m.warn(` Unknown command: /${t}. Type /help for available commands.`),!0;let n={session:this.session,cwd:this.options.cwd,onSessionChange:a=>{this.session=a}};return r(s,n)}async handleGeneration(e){let t=Xt({text:"Thinking...",color:"cyan"}).start();try{let s=this.session.messages.filter(i=>i.role!=="system").map(i=>({role:i.role,content:i.content})),r={task:e,cwd:this.options.cwd,provider:this.options.provider||"claude-code",model:this.options.model,apiKey:this.options.apiKey,overwrite:!0,dryRun:!1,interactive:!1,context7:!0,sessionMessages:s},n,a=!1;for await(let i of j(r)){if(i.type==="context_ready"){t.stop(),console.log(),a=!0;continue}if(i.type==="text_delta"){xe(i.text);continue}if(i.type==="done"){console.log();continue}if(i.type==="error")throw new Error(i.error);if(i.type==="step_complete"){i.step>1&&console.log(v.dim(` Step ${i.step}: ${i.filesCount} file(s)`));continue}i.type==="generate_result"&&(n=i.result)}if(a||t.stop(),!n)return;(n.files.written.length||n.files.skipped.length||n.files.errors.length)&&(R.getMode()==="plan"?$e(n.files.written.map(i=>({path:i,action:"create"}))):ve(n.files)),n.tokensUsed&&D(n.tokensUsed),this.session.messages.push({role:"user",content:e}),this.session.messages.push({role:"assistant",content:n.content||""}),this.session.tokensUsed+=n.tokensUsed||0,this.session.filesGenerated.push(...n.files.written),n.followUp&&(console.log(),console.log(v.yellow(` ${n.followUp}`))),n.healResult&&(console.log(),n.healResult.healed?console.log(v.green(` Heal: passed verification${n.healResult.attempts>0?` (fixed in ${n.healResult.attempts} attempt(s))`:""}`)):n.healResult.error&&(console.log(v.red(` Heal: verification failed after ${n.healResult.attempts} attempt(s)`)),console.log(v.dim(` ${n.healResult.error.split(`
78
+ `)[0]}`))))}catch(s){throw t.stop(),s}}};import{createServer as Qt}from"http";var k={TASK_NOT_FOUND:{code:-32001,message:"Task not found"},TASK_NOT_CANCELABLE:{code:-32002,message:"Task cannot be canceled"},INVALID_PARAMS:{code:-32602,message:"Invalid params"},INTERNAL_ERROR:{code:-32603,message:"Internal error"},METHOD_NOT_FOUND:{code:-32601,message:"Method not found"},PARSE_ERROR:{code:-32700,message:"Parse error"}};var Zt={port:3171,host:"0.0.0.0",provider:"claude-code",cwd:process.cwd(),cors:!0},X=class{config;tasks=new Map;activeCancellations=new Set;log;constructor(e){this.config={...Zt,...e},this.log=console.error.bind(console,"[a2a]")}async start(){Qt(async(t,s)=>{if(this.config.cors&&(s.setHeader("Access-Control-Allow-Origin","*"),s.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),s.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),t.method==="OPTIONS")){s.writeHead(204),s.end();return}await this.handleRequest(t,s)}).listen(this.config.port,this.config.host,()=>{this.log(`
79
+ agentx A2A server v0.1.0`),this.log(` Listening on http://${this.config.host}:${this.config.port}`),this.log(` Provider: ${this.config.provider}`),this.log(` Working dir: ${this.config.cwd}`),this.log(""),this.log(" Discovery:"),this.log(" GET /.well-known/agent-card.json"),this.log(""),this.log(" JSON-RPC 2.0 methods:"),this.log(" tasks/send \u2014 synchronous task execution"),this.log(" tasks/sendSubscribe \u2014 streaming task execution (SSE)"),this.log(" tasks/get \u2014 retrieve task state"),this.log(" tasks/cancel \u2014 cancel running task"),this.log("")})}getAgentCard(){return{name:"agentx",description:"AI-powered agentic code generation agent. Generates components, pages, APIs, documents, skills, and more for any tech stack.",url:`http://${this.config.host}:${this.config.port}`,version:"0.1.0",capabilities:{streaming:!0,pushNotifications:!1,stateTransitionHistory:!0},skills:[{id:"generate",name:"Code Generation",description:"Generate code files from natural language descriptions. Supports components, pages, APIs, tests, schemas, and more.",tags:["code-generation","ai","multi-framework"],examples:["Create a React login form with email and password validation","Generate a REST API for user management with CRUD operations","Build a dashboard page with charts and data tables"]},{id:"evolve",name:"Code Transformation",description:"Transform existing code files based on natural language instructions. Applies targeted edits with diff preview.",tags:["code-transformation","refactoring","ai"],examples:["Add dark mode support to this component","Refactor this API to use async/await instead of callbacks"]},{id:"inspect",name:"Project Analysis",description:"Analyze a project's tech stack, schemas, dependencies, and structure.",tags:["analysis","project-inspection"],examples:["What tech stack does this project use?","List all API schemas in the project"]}],defaultInputModes:["text"],defaultOutputModes:["text","file"]}}async handleRequest(e,t){let s=new URL(e.url||"/",`http://${e.headers.host||"localhost"}`),r=e.method||"GET",n=s.pathname;this.log(`${r} ${n}`);try{if(r==="GET"&&n==="/.well-known/agent-card.json"){this.sendJson(t,200,this.getAgentCard());return}if(r==="POST"&&n==="/"){let a=await es(e);await this.handleJsonRpc(a,t);return}this.sendJson(t,404,{error:"Not found",hint:"Use GET /.well-known/agent-card.json for discovery or POST / for JSON-RPC"})}catch(a){this.log("Error:",a.message),this.sendJson(t,500,{error:a.message})}}async handleJsonRpc(e,t){if(e.jsonrpc!=="2.0"||!e.method||!e.id){this.sendJsonRpc(t,{jsonrpc:"2.0",id:e.id||0,error:k.PARSE_ERROR});return}let s=e,r=s.params||{};switch(s.method){case"tasks/send":await this.handleTaskSend(s.id,r,t);break;case"tasks/sendSubscribe":await this.handleTaskSendSubscribe(s.id,r,t);break;case"tasks/get":this.handleTaskGet(s.id,r,t);break;case"tasks/cancel":this.handleTaskCancel(s.id,r,t);break;default:this.sendJsonRpc(t,{jsonrpc:"2.0",id:s.id,error:k.METHOD_NOT_FOUND})}}async handleTaskSend(e,t,s){let r=String(t.id||`task-${Date.now().toString(36)}`),n=t.message;if(!n?.parts?.length){this.sendJsonRpc(s,{jsonrpc:"2.0",id:e,error:{...k.INVALID_PARAMS,data:"message with parts is required"}});return}let i=n.parts.filter(l=>l.type==="text").map(l=>l.text).join(`
80
+ `);if(!i){this.sendJsonRpc(s,{jsonrpc:"2.0",id:e,error:{...k.INVALID_PARAMS,data:"No text content in message parts"}});return}let c={id:r,state:"submitted",messages:[{role:"user",parts:n.parts}],artifacts:[],metadata:t.metadata,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};this.tasks.set(r,c),c.state="working",c.updatedAt=new Date().toISOString();try{let l=await b({task:i,cwd:this.config.cwd,provider:this.config.provider,model:this.config.model,apiKey:this.config.apiKey,overwrite:!0,interactive:!1,context7:!0}),g=l.files.written.map((y,$)=>({name:y,description:"Generated file",parts:[{type:"text",text:y}],index:$})),f={role:"agent",parts:[{type:"text",text:l.content||"Generation complete."}]};l.followUp?(c.state="input-required",f.parts.push({type:"text",text:`
81
+
82
+ Question: ${l.followUp}`})):c.state="completed",c.messages.push(f),c.artifacts=g,c.updatedAt=new Date().toISOString()}catch(l){c.state="failed",c.messages.push({role:"agent",parts:[{type:"text",text:`Error: ${l.message}`}]}),c.updatedAt=new Date().toISOString()}this.sendJsonRpc(s,{jsonrpc:"2.0",id:e,result:c})}async handleTaskSendSubscribe(e,t,s){let r=String(t.id||`task-${Date.now().toString(36)}`),n=t.message;if(!n?.parts?.length){this.sendJsonRpc(s,{jsonrpc:"2.0",id:e,error:{...k.INVALID_PARAMS,data:"message with parts is required"}});return}let i=n.parts.filter(g=>g.type==="text").map(g=>g.text).join(`
83
+ `);if(!i){this.sendJsonRpc(s,{jsonrpc:"2.0",id:e,error:{...k.INVALID_PARAMS,data:"No text content in message parts"}});return}s.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});let c={id:r,state:"submitted",messages:[{role:"user",parts:n.parts}],artifacts:[],metadata:t.metadata,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};this.tasks.set(r,c);let l=g=>{s.write(`data: ${JSON.stringify(g)}
84
+
85
+ `)};l({id:r,state:"submitted",final:!1}),c.state="working",c.updatedAt=new Date().toISOString(),l({id:r,state:"working",final:!1});try{let g="",f=[];for await(let y of j({task:i,cwd:this.config.cwd,provider:this.config.provider,model:this.config.model,apiKey:this.config.apiKey,overwrite:!0,interactive:!1,context7:!0})){if(this.activeCancellations.has(r)){this.activeCancellations.delete(r),c.state="canceled",c.updatedAt=new Date().toISOString(),l({id:r,state:"canceled",final:!0}),s.end();return}if(y.type==="text_delta"&&(g+=y.text,l({id:r,state:"working",message:{role:"agent",parts:[{type:"text",text:y.text}]},final:!1})),y.type==="generate_result"){let $=y.result,le=$.files.written.map((N,Ae)=>({name:N,parts:[{type:"text",text:N}],index:Ae}));f.push(...le);for(let N of le)l({id:r,state:"working",artifact:N,final:!1});$.followUp?c.state="input-required":c.state="completed"}}c.messages.push({role:"agent",parts:[{type:"text",text:g||"Generation complete."}]}),c.artifacts=f,c.updatedAt=new Date().toISOString(),l({id:r,state:c.state,final:!0})}catch(g){c.state="failed",c.messages.push({role:"agent",parts:[{type:"text",text:`Error: ${g.message}`}]}),c.updatedAt=new Date().toISOString(),l({id:r,state:"failed",message:{role:"agent",parts:[{type:"text",text:`Error: ${g.message}`}]},final:!0})}s.end()}handleTaskGet(e,t,s){let r=String(t.id||""),n=this.tasks.get(r);if(!n){this.sendJsonRpc(s,{jsonrpc:"2.0",id:e,error:k.TASK_NOT_FOUND});return}this.sendJsonRpc(s,{jsonrpc:"2.0",id:e,result:n})}handleTaskCancel(e,t,s){let r=String(t.id||""),n=this.tasks.get(r);if(!n){this.sendJsonRpc(s,{jsonrpc:"2.0",id:e,error:k.TASK_NOT_FOUND});return}if(n.state!=="working"&&n.state!=="submitted"){this.sendJsonRpc(s,{jsonrpc:"2.0",id:e,error:k.TASK_NOT_CANCELABLE});return}this.activeCancellations.add(r),n.state="canceled",n.updatedAt=new Date().toISOString(),this.sendJsonRpc(s,{jsonrpc:"2.0",id:e,result:n})}sendJson(e,t,s){e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify(s,null,2))}sendJsonRpc(e,t){e.headersSent||e.writeHead(200,{"Content-Type":"application/json"}),e.end(JSON.stringify(t))}};async function es(o){return new Promise((e,t)=>{let s="";o.on("data",r=>s+=r),o.on("end",()=>{try{e(s?JSON.parse(s):{})}catch{e({})}}),o.on("error",t)})}var Te={"claude-code":{streaming:!0,tools:!0,vision:!0,thinking:!0,maxContext:1e6},claude:{streaming:!0,tools:!0,vision:!0,thinking:!0,maxContext:1e6},openai:{streaming:!0,tools:!0,vision:!0,thinking:!1,maxContext:128e3},ollama:{streaming:!0,tools:!1,vision:!1,thinking:!1,maxContext:32e3}};function ts(o,e){let t=Te[o];if(!t)return[`Unknown provider "${o}" \u2014 capabilities unknown`];if(!e?.length)return[];let s=[],r=[];for(let n of e)n in t&&!t[n]&&r.push(n);return r.length&&s.push(`Provider "${o}" lacks: ${r.join(", ")}. Some features will be degraded.`),s}function ss(o){typeof o=="string"&&(m.error(o),process.exit(1)),o instanceof Error&&(m.error(o.message),process.exit(1)),m.error("Something went wrong. Please try again."),process.exit(1)}export{de as A2AClient,pe as A2AMesh,X as A2AServer,Je as ALL_TOOL_NAMES,wt as AgentRegistry,Ct as AgentXDaemon,K as AgentXRuntime,Ye as BLOCKING_EVENTS,He as ClaudeCodeProvider,Ue as ClaudeProvider,lt as ContextBuilder,bt as CronScheduler,A as EnhanceEngine,w as GitManager,Ve as HOOK_EVENTS,H as HealEngine,tt as HookRegistry,U as Memory,ne as MemoryHierarchy,St as MessageRouter,ze as OUTPUT_CONFIGS,Ee as OUTPUT_TYPES,J as PERMISSION_MODES,Te as PROVIDER_CAPABILITIES,it as PermissionManager,M as Pipeline,Y as ReplEngine,vt as TelegramAdapter,dt as ToolExecutor,Xe as UsageTracker,xt as WhatsAppAdapter,kt as WikiStore,Me as agentConfigSchema,ts as checkCapabilities,T as createAgentContext,G as createProvider,O as createSession,pt as daemonConfigSchema,et as debug,Ke as detectSchemas,Q as detectTechStack,De as ensureCredentials,ut as executeClaudeCode,ht as executeOrchestrator,ft as executeSdk,yt as executeTask,se as exportSession,Be as formatSchemas,x as formatTechStack,Fe as formatToolsForSystemPrompt,We as gatherContext7Docs,b as generate,Et as generateSkill,At as generateSkillMd,j as generateStream,Ne as getAnthropicTools,q as getCommand,_e as getLegacyTools,Pt as getPackageInfo,nt as globalHooks,R as globalPermissions,F as globalTracker,ss as handleError,Rt as installSkillPackage,z as isCommand,Ze as isDebug,Mt as listInstalledSkills,W as listSessions,Ie as loadAuthConfig,gt as loadDaemonConfig,st as loadHooks,B as loadLatestSession,Z as loadLocalSkills,ct as loadProjectInstructions,P as loadSession,m as logger,ee as matchSkillsToTask,Oe as outputTypeDescriptions,V as parseCommand,_ as parseSkillContent,qe as parseSkillFile,rt as permissionConfigSchema,ot as permissionModeSchema,u as registerCommand,at as resolveAtImports,te as resolveOutputType,je as resolveToken,Le as runModelSetup,Ge as saveAuthConfig,I as saveSession,Qe as setDebug,Ut as startMcpServer,mt as validateWorkspaces};
2
86
  //# sourceMappingURL=index.js.map