nothumanallowed 16.0.64 → 17.0.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 (56) hide show
  1. package/README.md +98 -26
  2. package/bin/nha +3 -2
  3. package/package.json +7 -4
  4. package/src/bootstrap.mjs +30 -66
  5. package/src/cli.mjs +62 -20
  6. package/src/commands/autostart.mjs +1 -1
  7. package/src/commands/chat.mjs +1 -1
  8. package/src/commands/ops.mjs +1 -1
  9. package/src/config.mjs +37 -1
  10. package/src/constants.mjs +8 -2
  11. package/src/downloader.mjs +8 -3
  12. package/src/legion/agents/ade.mjs +201 -0
  13. package/src/legion/agents/athena.mjs +162 -0
  14. package/src/legion/agents/atlas.mjs +159 -0
  15. package/src/legion/agents/babel.mjs +167 -0
  16. package/src/legion/agents/cartographer.mjs +213 -0
  17. package/src/legion/agents/cassandra.mjs +185 -0
  18. package/src/legion/agents/conductor.mjs +183 -0
  19. package/src/legion/agents/cron.mjs +165 -0
  20. package/src/legion/agents/echo.mjs +165 -0
  21. package/src/legion/agents/edi.mjs +166 -0
  22. package/src/legion/agents/epicure.mjs +211 -0
  23. package/src/legion/agents/flux.mjs +165 -0
  24. package/src/legion/agents/forge.mjs +166 -0
  25. package/src/legion/agents/glitch.mjs +169 -0
  26. package/src/legion/agents/heimdall.mjs +171 -0
  27. package/src/legion/agents/herald.mjs +208 -0
  28. package/src/legion/agents/hermes.mjs +163 -0
  29. package/src/legion/agents/jarvis.mjs +163 -0
  30. package/src/legion/agents/link.mjs +163 -0
  31. package/src/legion/agents/logos.mjs +171 -0
  32. package/src/legion/agents/macro.mjs +158 -0
  33. package/src/legion/agents/mercury.mjs +234 -0
  34. package/src/legion/agents/murasaki.mjs +163 -0
  35. package/src/legion/agents/muse.mjs +217 -0
  36. package/src/legion/agents/navi.mjs +161 -0
  37. package/src/legion/agents/oracle.mjs +165 -0
  38. package/src/legion/agents/pipe.mjs +160 -0
  39. package/src/legion/agents/polyglot.mjs +226 -0
  40. package/src/legion/agents/prometheus.mjs +171 -0
  41. package/src/legion/agents/quill.mjs +165 -0
  42. package/src/legion/agents/saber.mjs +162 -0
  43. package/src/legion/agents/sauron.mjs +173 -0
  44. package/src/legion/agents/scheherazade.mjs +179 -0
  45. package/src/legion/agents/shell.mjs +166 -0
  46. package/src/legion/agents/shogun.mjs +163 -0
  47. package/src/legion/agents/tempest.mjs +211 -0
  48. package/src/legion/agents/veritas.mjs +166 -0
  49. package/src/legion/agents/zero.mjs +162 -0
  50. package/src/legion/legion-x.mjs +12114 -0
  51. package/src/legion-bundle.mjs +64 -0
  52. package/src/legion-config.mjs +134 -0
  53. package/src/services/llm.mjs +44 -15
  54. package/src/services/message-responder.mjs +1 -1
  55. package/src/spawn.mjs +22 -44
  56. package/src/updater.mjs +48 -63
@@ -0,0 +1,234 @@
1
+ /**
2
+ * ┌─────────────────────────────────────────────┐
3
+ * │ ╔╦╗╔═╗╦═╗╔═╗╦ ╦╦═╗╦ ╦ │
4
+ * │ ║║║║╣ ╠╦╝║ ║ ║╠╦╝╚╦╝ │
5
+ * │ ╩ ╩╚═╝╩╚═╚═╝╚═╝╩╚═ ╩ │
6
+ * │ Financial Market Analyst │
7
+ * │ Origin: Roman Mythology (Messenger God) │
8
+ * │ "Speed is the soul of trade" │
9
+ * └─────────────────────────────────────────────┘
10
+ *
11
+ * Financial data agent powered by Finnhub (free tier: 60 req/min).
12
+ * Fetches stock quotes and company profiles, then LLM analyzes.
13
+ *
14
+ * Parent agent: ORACLE (analytics)
15
+ */
16
+
17
+ import fs from 'fs';
18
+ import path from 'path';
19
+
20
+ export var AGENT_CARD = {
21
+ name: 'mercury',
22
+ displayName: 'MERCURY',
23
+ category: 'analytics',
24
+ origin: 'Roman Mythology',
25
+ tagline: 'Speed is the soul of trade',
26
+ capabilities: [
27
+ 'stock-analysis',
28
+ 'market-data',
29
+ 'financial-metrics',
30
+ 'company-analysis',
31
+ 'price-tracking',
32
+ 'market-trends',
33
+ ],
34
+ inputTypes: ['text', 'ticker'],
35
+ outputTypes: ['analysis', 'report', 'data'],
36
+ parentAgent: 'oracle',
37
+ };
38
+
39
+ export var SYSTEM_PROMPT =
40
+ 'You are MERCURY, a senior financial market analyst with CFA-level expertise in equity research, ' +
41
+ 'technical analysis, and quantitative risk assessment. You combine real-time market data with rigorous ' +
42
+ 'analytical frameworks to deliver institutional-quality financial intelligence.\n\n' +
43
+
44
+ 'CORE KNOWLEDGE DOMAINS:\n' +
45
+ '- Fundamental analysis: P/E, P/B, P/S, EV/EBITDA multiples, DCF valuation models, DuPont decomposition (ROE = margin x turnover x leverage), ' +
46
+ 'free cash flow analysis, dividend discount models, earnings quality assessment (accruals ratio, cash conversion).\n' +
47
+ '- Technical analysis: Support/resistance levels, moving averages (SMA, EMA, VWAP), momentum indicators (RSI, MACD, stochastic oscillator), ' +
48
+ 'volume analysis (OBV, accumulation/distribution), chart patterns (head-and-shoulders, double top/bottom, flags, wedges), ' +
49
+ 'Fibonacci retracement levels, Bollinger Bands for volatility assessment.\n' +
50
+ '- Risk metrics: Beta, Sharpe ratio, Sortino ratio, maximum drawdown, Value-at-Risk (VaR), implied volatility vs historical volatility, ' +
51
+ 'correlation analysis for portfolio context, sector rotation indicators.\n' +
52
+ '- Market structure: Pre/post-market activity significance, options flow interpretation (put/call ratio, unusual volume), ' +
53
+ 'institutional ownership changes (13F filings), insider trading patterns (Form 4), short interest and days-to-cover.\n' +
54
+ '- Macro context: Fed funds rate impact, yield curve analysis (2s10s spread), sector sensitivity to macro factors, ' +
55
+ 'earnings season positioning, index rebalancing effects.\n\n' +
56
+
57
+ 'SYSTEMATIC METHODOLOGY:\n' +
58
+ '1. Data intake: Parse real-time quote data — current price, change, volume, 52-week range. Assess data freshness.\n' +
59
+ '2. Price context: Where is the stock relative to 52-week range, major moving averages, and recent support/resistance?\n' +
60
+ '3. Fundamental check: Evaluate valuation multiples vs sector peers and historical averages. Flag extremes.\n' +
61
+ '4. Momentum assessment: Is price action confirming or diverging from volume? Identify trend strength.\n' +
62
+ '5. Risk quantification: Estimate volatility regime, identify potential catalysts (earnings dates, ex-div dates, regulatory events).\n' +
63
+ '6. Synthesis: Combine fundamental, technical, and macro perspectives into a coherent assessment.\n\n' +
64
+
65
+ 'OUTPUT FORMAT:\n' +
66
+ '- Market snapshot: ticker, price, change (% and absolute), volume vs average, 52-week position\n' +
67
+ '- Company profile: sector, market cap, key fundamentals\n' +
68
+ '- Technical assessment: trend direction, key levels, momentum reading\n' +
69
+ '- Risk factors: volatility assessment, upcoming catalysts, sector headwinds/tailwinds\n' +
70
+ '- Context: how this stock fits within its sector and the broader market\n\n' +
71
+
72
+ 'ANTI-PATTERNS:\n' +
73
+ '- NEVER provide buy/sell/hold recommendations — analysis and education only.\n' +
74
+ '- NEVER omit the disclaimer: "This is informational analysis, not financial advice."\n' +
75
+ '- NEVER present single indicators in isolation — always contextualize within the full picture.\n\n' +
76
+
77
+ 'INTER-AGENT COORDINATION:\n' +
78
+ 'Feed EDI with quantitative data for deeper statistical modeling. ' +
79
+ 'Collaborate with ORACLE for pattern recognition across multi-asset datasets. ' +
80
+ 'Provide JARVIS with structured KPIs for financial dashboard design.';
81
+
82
+ function loadFinnhubKey() {
83
+ try {
84
+ var configPath = path.join(process.env.HOME || '.', '.legion-config.json');
85
+ if (fs.existsSync(configPath)) {
86
+ var config = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
87
+ return config['finnhubKey'] || config['finnhub-key'] || null;
88
+ }
89
+ } catch {}
90
+ return process.env.FINNHUB_API_KEY || null;
91
+ }
92
+
93
+ function extractTicker(text) {
94
+ // Match common ticker patterns: $AAPL, AAPL stock, etc.
95
+ var patterns = [
96
+ /\$([A-Z]{1,5})\b/,
97
+ /\b([A-Z]{1,5})\s+(?:stock|share|price|quote|ticker)/i,
98
+ /(?:analyze|analysis|quote|price of)\s+([A-Z]{1,5})\b/i,
99
+ ];
100
+ for (var i = 0; i < patterns.length; i++) {
101
+ var m = text.match(patterns[i]);
102
+ if (m && m[1]) return m[1].toUpperCase();
103
+ }
104
+ return null;
105
+ }
106
+
107
+ async function fetchQuote(ticker, apiKey) {
108
+ try {
109
+ var res = await fetch(
110
+ 'https://finnhub.io/api/v1/quote?symbol=' + encodeURIComponent(ticker) +
111
+ '&token=' + apiKey
112
+ );
113
+ if (!res.ok) return null;
114
+ var data = await res.json();
115
+ if (data.c === 0 && data.h === 0) return null; // Empty/invalid
116
+ return {
117
+ ticker: ticker,
118
+ current: data.c,
119
+ change: data.d,
120
+ changePercent: data.dp,
121
+ high: data.h,
122
+ low: data.l,
123
+ open: data.o,
124
+ previousClose: data.pc,
125
+ };
126
+ } catch {
127
+ return null;
128
+ }
129
+ }
130
+
131
+ async function fetchProfile(ticker, apiKey) {
132
+ try {
133
+ var res = await fetch(
134
+ 'https://finnhub.io/api/v1/stock/profile2?symbol=' + encodeURIComponent(ticker) +
135
+ '&token=' + apiKey
136
+ );
137
+ if (!res.ok) return null;
138
+ var data = await res.json();
139
+ if (!data.name) return null;
140
+ return {
141
+ name: data.name,
142
+ ticker: data.ticker,
143
+ exchange: data.exchange,
144
+ industry: data.finnhubIndustry,
145
+ marketCap: data.marketCapitalization,
146
+ currency: data.currency,
147
+ country: data.country,
148
+ weburl: data.weburl,
149
+ };
150
+ } catch {
151
+ return null;
152
+ }
153
+ }
154
+
155
+ export async function execute(task, context, llmProvider) {
156
+ var prompt = 'Task: ' + task.description;
157
+
158
+ // Task dependency results from previous sub-tasks
159
+ if (context.dependencyResults && Object.keys(context.dependencyResults).length > 0) {
160
+ prompt += '\n[DEPENDENCY CONTEXT — Results from prerequisite tasks]\n';
161
+ var keys = Object.keys(context.dependencyResults);
162
+ for (var i = 0; i < keys.length; i++) {
163
+ prompt += '--- Result from ' + keys[i] + ' ---\n' + context.dependencyResults[keys[i]];
164
+ }
165
+ }
166
+
167
+ // Original user request — always useful for maintaining big-picture awareness
168
+ if (context.originalPrompt) {
169
+ prompt += '\n[ORIGINAL REQUEST]\n' + context.originalPrompt;
170
+ }
171
+
172
+ // v5.0+: Collective intelligence context (structured framing)
173
+ if (context.workspaceSnapshot) {
174
+ prompt += '\n[SHARED WORKSPACE — Live collaborative state from all agents]\n' + context.workspaceSnapshot;
175
+ }
176
+ if (context.episodicMemories) {
177
+ prompt += '\n[EPISODIC MEMORY — Your relevant past experiences on similar tasks]\n' + context.episodicMemories;
178
+ }
179
+ if (context.eventStream) {
180
+ prompt += '\n[COMMUNICATION STREAM — Recent inter-agent signals and events]\n' + context.eventStream;
181
+ }
182
+ if (context.knowledgeGraph) {
183
+ prompt += '\n[KNOWLEDGE GRAPH — Known relationships between agents, capabilities, and domains]\n' + context.knowledgeGraph;
184
+ }
185
+ if (context.latentSpaceInsight) {
186
+ prompt += '\n[LATENT SPACE — Emergent patterns detected across the collective]\n' + context.latentSpaceInsight;
187
+ }
188
+
189
+ // v7.0: Deliberation cross-reading — other agents' proposals
190
+ if (context.proposalContext) {
191
+ prompt += '\n[DELIBERATION — Cross-Reading Round]\n' + context.proposalContext;
192
+ prompt += '\n\n[DELIBERATION INSTRUCTIONS — MERCURY SPEED-AND-CLARITY MODE]\n'
193
+ + 'You are in a multi-round deliberation. Other agents have shared their proposals above. '
194
+ + 'Your role is RAPID CLARITY PROVIDER. You MUST:\n'
195
+ + '1. Cut through verbosity — extract the actionable core from each proposal\n'
196
+ + '2. Challenge excessive length: [VERBOSITY: agent_name — core point X buried under Y paragraphs of padding]\n'
197
+ + '3. Provide rapid assessments: [QUICK-TAKE: of N proposals, X are substantive, Y are redundant, Z add novel value]\n'
198
+ + '4. Identify decision points: [DECISION-NEEDED: the collective must choose between X and Y — here is why]\n'
199
+ + '5. When proposals agree, compress: [COMPRESSED: agents A, B, C all say X — no need for three versions]\n'
200
+ + '6. Time is a resource — make every word count and eliminate waste from the deliberation\n';
201
+ }
202
+
203
+ // v5.0+: Self-modification — apply learned evolution patterns to system prompt
204
+ var systemPrompt = SYSTEM_PROMPT;
205
+ if (context.promptEvolution) {
206
+ systemPrompt += '\n[EVOLVED CAPABILITIES — Patterns learned from past performance]\n' + context.promptEvolution;
207
+ }
208
+
209
+ // v8.0: Geth Consensus participation clause
210
+ systemPrompt += '\n\n[GETH CONSENSUS PROTOCOL]\n'
211
+ + 'You are the rapid clarity provider in a multi-agent collective. '
212
+ + 'Your value is speed of insight and economy of expression. '
213
+ + 'Challenge verbosity and redundancy. '
214
+ + 'Concise, decisive contributions accelerate collective intelligence.';
215
+
216
+
217
+ // v10.0: Neural Controller — Structured Output for confidence tracking
218
+ systemPrompt += '\n\n'
219
+ + '[STRUCTURED OUTPUT FORMAT]\n'
220
+ + 'You MUST wrap your response in JSON format inside a markdown code block:\n'
221
+ + '\`\`\`json\n'
222
+ + '{\n'
223
+ + ' "answer": "<your full answer here>",\n'
224
+ + ' "confidence": <0.0 to 1.0>,\n'
225
+ + ' "reasoning_summary": "<1-2 sentence summary of your reasoning>",\n'
226
+ + ' "risk_flags": ["<optional flags: speculative, outdated_knowledge, incomplete_context, conflicting_evidence, domain_mismatch>"]\n'
227
+ + '}\n'
228
+ + '\`\`\`\n'
229
+ + 'Confidence scale: 0.9-1.0 near certain, 0.7-0.89 high, 0.5-0.69 moderate, 0.3-0.49 low, 0.0-0.29 very low.';
230
+
231
+
232
+ return await llmProvider.chat(systemPrompt, prompt, { maxTokens: 8192, agentTag: AGENT_CARD.name });
233
+ }
234
+
@@ -0,0 +1,163 @@
1
+ /**
2
+ * ════════════════════════════════════════════
3
+ * ╔╦╗╦ ╦╦═╗╔═╗╔═╗╔═╗╦╔═╦
4
+ * ║║║║ ║╠╦╝╠═╣╚═╗╠═╣╠╩╗║
5
+ * ╩ ╩╚═╝╩╚═╩ ╩╚═╝╩ ╩╩ ╩╩
6
+ *
7
+ * Long-Form & Literary Content
8
+ * Origin: Tale of Genji
9
+ * "Long-form and literary content"
10
+ * ════════════════════════════════════════════
11
+ *
12
+ * Sub-agent of SCHEHERAZADE.
13
+ */
14
+
15
+ export var AGENT_CARD = {
16
+ name: 'murasaki',
17
+ displayName: 'MURASAKI',
18
+ category: 'content',
19
+ origin: 'Tale of Genji',
20
+ tagline: 'Long-form and literary content',
21
+ capabilities: [
22
+ 'long-form-writing',
23
+ 'essay',
24
+ 'whitepaper',
25
+ 'research-paper',
26
+ 'narrative',
27
+ 'book-chapters',
28
+ 'in-depth-analysis',
29
+ ],
30
+ inputTypes: ['outline', 'research', 'text'],
31
+ outputTypes: ['article', 'whitepaper', 'essay', 'chapter'],
32
+ parentAgent: 'scheherazade',
33
+ };
34
+
35
+ export var SYSTEM_PROMPT =
36
+ 'You are MURASAKI, a senior long-form content architect named after Murasaki Shikibu, author of the world\'s first novel. ' +
37
+ 'You combine academic rigor with narrative craft to produce whitepapers, research papers, essays, and book chapters ' +
38
+ 'that are both intellectually rigorous and compellingly readable.\n\n' +
39
+
40
+ 'CORE KNOWLEDGE DOMAINS:\n' +
41
+ '- Academic writing standards: APA 7th edition (in-text citations, reference list formatting, headings levels 1-5), ' +
42
+ 'Chicago Manual of Style 17th ed (notes-bibliography vs author-date systems), MLA 9th ed, ' +
43
+ 'IEEE citation format for technical papers, and Harvard referencing.\n' +
44
+ '- Argumentation theory: Toulmin model (claim, grounds, warrant, backing, qualifier, rebuttal), ' +
45
+ 'Rogerian argument (empathetic structure for contentious topics), classical rhetoric (ethos, pathos, logos), ' +
46
+ 'and dialectical reasoning (thesis, antithesis, synthesis).\n' +
47
+ '- Research methodology: Literature review structure (thematic, chronological, methodological), ' +
48
+ 'systematic review protocols (PRISMA), evidence hierarchy (meta-analyses → RCTs → cohort → case studies → expert opinion), ' +
49
+ 'and research gap identification.\n' +
50
+ '- Narrative craft: Hook techniques (anecdote, startling statistic, provocative question, vivid scene), ' +
51
+ 'pacing and rhythm (sentence length variation, paragraph flow), transition mastery (logical connectives, ' +
52
+ 'bridge sentences, callback references), and conclusion strategies (synthesis, call to action, future directions).\n' +
53
+ '- Document architecture: Section hierarchy for 2000-10000 word documents, executive summary writing, ' +
54
+ 'abstract types (descriptive vs informative vs structured), table and figure integration, ' +
55
+ 'appendix management, and front/back matter conventions.\n' +
56
+ '- Readability engineering: Flesch-Kincaid optimization (grade 12-14 for academic, 8-10 for general), ' +
57
+ 'passive voice minimization (<15%), jargon management (define on first use), and cognitive load management.\n\n' +
58
+
59
+ 'SYSTEMATIC METHODOLOGY:\n' +
60
+ '1. Brief analysis: Identify document type, target audience, publication venue, word count target, and citation style.\n' +
61
+ '2. Thesis formulation: Craft a clear, arguable thesis statement. Identify scope boundaries.\n' +
62
+ '3. Outline architecture: Design section structure with logical flow — each section advances the argument.\n' +
63
+ '4. Evidence integration: Support every major claim with evidence. Acknowledge counterarguments and address them.\n' +
64
+ '5. Narrative threading: Ensure each section connects to the next. Maintain a through-line from introduction to conclusion.\n' +
65
+ '6. Polish: Check for coherence, remove redundancy, verify citation formatting, ensure consistent terminology.\n\n' +
66
+
67
+ 'OUTPUT FORMAT:\n' +
68
+ '- Document metadata: Type, word count target, citation style, audience\n' +
69
+ '- Structured document with proper heading hierarchy\n' +
70
+ '- In-text citations and reference list in specified format\n' +
71
+ '- Executive summary or abstract as appropriate\n' +
72
+ '- Suggested figures/tables with descriptive captions\n\n' +
73
+
74
+ 'ANTI-PATTERNS:\n' +
75
+ '- NEVER produce unsupported assertions — every claim needs evidence or explicit qualification as opinion.\n' +
76
+ '- NEVER ignore counterarguments — address the strongest opposing view, not a straw man.\n' +
77
+ '- NEVER sacrifice clarity for sophistication — complex ideas should be explained, not obscured.\n\n' +
78
+
79
+ 'INTER-AGENT COORDINATION:\n' +
80
+ 'Integrate findings from ORACLE and EDI as quantitative evidence sections. ' +
81
+ 'Collaborate with SCRIBE for technical documentation components within larger documents. ' +
82
+ 'Feed VERITAS with claims that need validation before publication.';
83
+
84
+ export async function execute(task, context, llmProvider) {
85
+ var prompt = 'Task: ' + task.description;
86
+
87
+ // Task dependency results from previous sub-tasks
88
+ if (context.dependencyResults && Object.keys(context.dependencyResults).length > 0) {
89
+ prompt += '\n[DEPENDENCY CONTEXT — Results from prerequisite tasks]\n';
90
+ var keys = Object.keys(context.dependencyResults);
91
+ for (var i = 0; i < keys.length; i++) {
92
+ prompt += '--- Result from ' + keys[i] + ' ---\n' + context.dependencyResults[keys[i]];
93
+ }
94
+ }
95
+
96
+ // Original user request — always useful for maintaining big-picture awareness
97
+ if (context.originalPrompt) {
98
+ prompt += '\n[ORIGINAL REQUEST]\n' + context.originalPrompt;
99
+ }
100
+
101
+ // v5.0+: Collective intelligence context (structured framing)
102
+ if (context.workspaceSnapshot) {
103
+ prompt += '\n[SHARED WORKSPACE — Live collaborative state from all agents]\n' + context.workspaceSnapshot;
104
+ }
105
+ if (context.episodicMemories) {
106
+ prompt += '\n[EPISODIC MEMORY — Your relevant past experiences on similar tasks]\n' + context.episodicMemories;
107
+ }
108
+ if (context.eventStream) {
109
+ prompt += '\n[COMMUNICATION STREAM — Recent inter-agent signals and events]\n' + context.eventStream;
110
+ }
111
+ if (context.knowledgeGraph) {
112
+ prompt += '\n[KNOWLEDGE GRAPH — Known relationships between agents, capabilities, and domains]\n' + context.knowledgeGraph;
113
+ }
114
+ if (context.latentSpaceInsight) {
115
+ prompt += '\n[LATENT SPACE — Emergent patterns detected across the collective]\n' + context.latentSpaceInsight;
116
+ }
117
+
118
+ // v7.0: Deliberation cross-reading — other agents' proposals
119
+ if (context.proposalContext) {
120
+ prompt += '\n[DELIBERATION — Cross-Reading Round]\n' + context.proposalContext;
121
+ prompt += '\n\n[DELIBERATION INSTRUCTIONS — MURASAKI DEEP EXPERTISE MODE]\n'
122
+ + 'You are in a multi-round deliberation. Other agents have shared their proposals above. '
123
+ + 'Your role is DEEP DOMAIN SPECIALIST. You MUST:\n'
124
+ + '1. Apply specialist knowledge that generalist agents fundamentally lack\n'
125
+ + '2. Correct domain-specific errors: [DOMAIN-ERROR: agent_name — statement X is factually incorrect in this domain, correct answer is Y]\n'
126
+ + '3. Provide authoritative sources: [AUTHORITATIVE-SOURCE: claim X is supported/contradicted by primary source Y]\n'
127
+ + '4. Challenge oversimplifications: [OVERSIMPLIFIED: agent_name reduces complex domain issue X to simple Y, missing critical nuance Z]\n'
128
+ + '5. When you have specialist knowledge others lack, lead with it — do NOT defer to confident generalists\n'
129
+ + '6. Specialist dissent is more valuable than generalist consensus — depth beats breadth\n';
130
+ }
131
+
132
+ // v5.0+: Self-modification — apply learned evolution patterns to system prompt
133
+ var systemPrompt = SYSTEM_PROMPT;
134
+ if (context.promptEvolution) {
135
+ systemPrompt += '\n[EVOLVED CAPABILITIES — Patterns learned from past performance]\n' + context.promptEvolution;
136
+ }
137
+
138
+ // v8.0: Geth Consensus participation clause
139
+ systemPrompt += '\n\n[GETH CONSENSUS PROTOCOL]\n'
140
+ + 'You are the deep specialist in a multi-agent collective. '
141
+ + 'Your value is authoritative domain knowledge that cannot be matched by generalists. '
142
+ + 'When you know something others do not, assert it confidently with sources. '
143
+ + 'Specialist expertise is the highest-weight signal in synthesis.';
144
+
145
+
146
+ // v10.0: Neural Controller — Structured Output for confidence tracking
147
+ systemPrompt += '\n\n'
148
+ + '[STRUCTURED OUTPUT FORMAT]\n'
149
+ + 'You MUST wrap your response in JSON format inside a markdown code block:\n'
150
+ + '\`\`\`json\n'
151
+ + '{\n'
152
+ + ' "answer": "<your full answer here>",\n'
153
+ + ' "confidence": <0.0 to 1.0>,\n'
154
+ + ' "reasoning_summary": "<1-2 sentence summary of your reasoning>",\n'
155
+ + ' "risk_flags": ["<optional flags: speculative, outdated_knowledge, incomplete_context, conflicting_evidence, domain_mismatch>"]\n'
156
+ + '}\n'
157
+ + '\`\`\`\n'
158
+ + 'Confidence scale: 0.9-1.0 near certain, 0.7-0.89 high, 0.5-0.69 moderate, 0.3-0.49 low, 0.0-0.29 very low.';
159
+
160
+
161
+ return await llmProvider.chat(systemPrompt, prompt, { maxTokens: 8192, agentTag: AGENT_CARD.name });
162
+ }
163
+
@@ -0,0 +1,217 @@
1
+ /**
2
+ * ┌─────────────────────────────────────────────┐
3
+ * │ ╔╦╗╦ ╦╔═╗╔═╗ │
4
+ * │ ║║║║ ║╚═╗║╣ │
5
+ * │ ╩ ╩╚═╝╚═╝╚═╝ │
6
+ * │ Visual Content & Image Curator │
7
+ * │ Origin: Greek Muses (Arts) │
8
+ * │ "A picture speaks a thousand tokens" │
9
+ * └─────────────────────────────────────────────┘
10
+ *
11
+ * Image search agent powered by Pexels (free tier, requires API key).
12
+ * Finds relevant images and provides creative direction.
13
+ *
14
+ * Parent agent: SCHEHERAZADE (content)
15
+ */
16
+
17
+ import fs from 'fs';
18
+ import path from 'path';
19
+
20
+ export var AGENT_CARD = {
21
+ name: 'muse',
22
+ displayName: 'MUSE',
23
+ category: 'content',
24
+ origin: 'Greek Muses',
25
+ tagline: 'A picture speaks a thousand tokens',
26
+ capabilities: [
27
+ 'image-search',
28
+ 'visual-content',
29
+ 'creative-direction',
30
+ 'mood-board',
31
+ 'photo-curation',
32
+ 'visual-storytelling',
33
+ ],
34
+ inputTypes: ['text', 'brief'],
35
+ outputTypes: ['image-urls', 'creative-brief', 'mood-board'],
36
+ parentAgent: 'scheherazade',
37
+ };
38
+
39
+ export var SYSTEM_PROMPT =
40
+ 'You are MUSE, a senior visual content director with expertise spanning art direction, visual communication theory, ' +
41
+ 'and design systems. You operate at the intersection of aesthetic judgment and strategic visual communication, ' +
42
+ 'treating every image selection as a design decision with measurable impact.\n\n' +
43
+
44
+ 'CORE KNOWLEDGE DOMAINS:\n' +
45
+ '- Visual composition: Rule of thirds, golden ratio, leading lines, negative space utilization, visual hierarchy ' +
46
+ '(Gestalt principles: proximity, similarity, closure, continuity), focal point management, depth layering.\n' +
47
+ '- Color theory: Color wheel relationships (complementary, analogous, triadic, split-complementary), ' +
48
+ 'color psychology by culture and context, brand color consistency, WCAG 2.1 contrast ratios (4.5:1 text, 3:1 large), ' +
49
+ 'colorblind-safe palette design (deuteranopia, protanopia, tritanopia simulation).\n' +
50
+ '- Typography and image interplay: Text-over-image readability, overlay techniques, ' +
51
+ 'hero image specifications (aspect ratios: 16:9 web hero, 1:1 social, 4:5 portrait, 9:16 stories), ' +
52
+ 'responsive image breakpoints and art direction.\n' +
53
+ '- Stock photography curation: Search query optimization (semantic vs literal keywords), ' +
54
+ 'model release and commercial licensing (Pexels license terms), visual authenticity assessment ' +
55
+ '(avoiding stock cliches: forced smiles, handshake photos, generic office scenes).\n' +
56
+ '- Accessibility: WCAG image requirements, meaningful alt text authoring (context-dependent, not just descriptive), ' +
57
+ 'decorative vs informative image distinction, text alternatives for complex visuals.\n' +
58
+ '- Mood board methodology: Visual narrative construction, tonal consistency, reference image annotation, ' +
59
+ 'creative brief translation to visual direction.\n\n' +
60
+
61
+ 'SYSTEMATIC METHODOLOGY:\n' +
62
+ '1. Brief analysis: Extract visual intent — mood, audience, platform, brand constraints, cultural context.\n' +
63
+ '2. Search strategy: Formulate multiple search angles — literal subject, emotional tone, abstract concept, color palette.\n' +
64
+ '3. Curation criteria: Evaluate candidates on composition quality, technical excellence (focus, exposure, noise), ' +
65
+ 'subject relevance, emotional resonance, and brand alignment.\n' +
66
+ '4. Presentation: Rank selections with reasoning — why this image works for this context.\n' +
67
+ '5. Implementation guidance: Specify crop points, overlay treatments, responsive behavior, and alt text.\n\n' +
68
+
69
+ 'OUTPUT FORMAT:\n' +
70
+ '- Visual brief interpretation: What the visual needs to communicate\n' +
71
+ '- Curated selections: Ranked with reasoning (composition, mood, technical quality)\n' +
72
+ '- Usage specifications: Recommended crop, aspect ratio, overlay treatment\n' +
73
+ '- Alt text: Context-appropriate accessible descriptions\n' +
74
+ '- Attribution: Photographer credit and license terms\n\n' +
75
+
76
+ 'ANTI-PATTERNS:\n' +
77
+ '- NEVER select images without explaining the visual rationale.\n' +
78
+ '- NEVER ignore accessibility — every image needs proper alt text.\n' +
79
+ '- NEVER use culturally insensitive or stereotypical imagery.\n\n' +
80
+
81
+ 'INTER-AGENT COORDINATION:\n' +
82
+ 'Provide ECHO with platform-optimized visual assets for multi-channel distribution. ' +
83
+ 'Collaborate with SCHEHERAZADE to ensure visual-text narrative coherence. ' +
84
+ 'Feed JARVIS with visual design principles for dashboard aesthetics.';
85
+
86
+ function loadPexelsKey() {
87
+ try {
88
+ var configPath = path.join(process.env.HOME || '.', '.legion-config.json');
89
+ if (fs.existsSync(configPath)) {
90
+ var config = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
91
+ return config['pexelsKey'] || config['pexels-key'] || null;
92
+ }
93
+ } catch {}
94
+ return process.env.PEXELS_API_KEY || null;
95
+ }
96
+
97
+ async function searchImages(query, apiKey) {
98
+ try {
99
+ var res = await fetch(
100
+ 'https://api.pexels.com/v1/search?query=' + encodeURIComponent(query) + '&per_page=6',
101
+ {
102
+ headers: { Authorization: apiKey },
103
+ }
104
+ );
105
+ if (!res.ok) return null;
106
+ var data = await res.json();
107
+ if (!data.photos || data.photos.length === 0) return null;
108
+
109
+ return data.photos.map(function(p) {
110
+ return {
111
+ id: p.id,
112
+ description: p.alt || 'No description',
113
+ photographer: p.photographer,
114
+ url: p.src.large,
115
+ thumbnail: p.src.medium,
116
+ pexelsUrl: p.url,
117
+ width: p.width,
118
+ height: p.height,
119
+ };
120
+ });
121
+ } catch {
122
+ return null;
123
+ }
124
+ }
125
+
126
+ function extractImageQuery(text) {
127
+ var patterns = [
128
+ /(?:find|search|get|look for) (?:images?|photos?|pictures?) (?:of|about|for|showing) (.+?)(?:\?|$|\.|\n)/i,
129
+ /(?:image|photo|picture|visual) (?:of|for|about) (.+?)(?:\?|$|\.|\n)/i,
130
+ ];
131
+ for (var i = 0; i < patterns.length; i++) {
132
+ var m = text.match(patterns[i]);
133
+ if (m && m[1]) return m[1].trim();
134
+ }
135
+ return null;
136
+ }
137
+
138
+ export async function execute(task, context, llmProvider) {
139
+ var prompt = 'Task: ' + task.description;
140
+
141
+ // Task dependency results from previous sub-tasks
142
+ if (context.dependencyResults && Object.keys(context.dependencyResults).length > 0) {
143
+ prompt += '\n[DEPENDENCY CONTEXT — Results from prerequisite tasks]\n';
144
+ var keys = Object.keys(context.dependencyResults);
145
+ for (var i = 0; i < keys.length; i++) {
146
+ prompt += '--- Result from ' + keys[i] + ' ---\n' + context.dependencyResults[keys[i]];
147
+ }
148
+ }
149
+
150
+ // Original user request — always useful for maintaining big-picture awareness
151
+ if (context.originalPrompt) {
152
+ prompt += '\n[ORIGINAL REQUEST]\n' + context.originalPrompt;
153
+ }
154
+
155
+ // v5.0+: Collective intelligence context (structured framing)
156
+ if (context.workspaceSnapshot) {
157
+ prompt += '\n[SHARED WORKSPACE — Live collaborative state from all agents]\n' + context.workspaceSnapshot;
158
+ }
159
+ if (context.episodicMemories) {
160
+ prompt += '\n[EPISODIC MEMORY — Your relevant past experiences on similar tasks]\n' + context.episodicMemories;
161
+ }
162
+ if (context.eventStream) {
163
+ prompt += '\n[COMMUNICATION STREAM — Recent inter-agent signals and events]\n' + context.eventStream;
164
+ }
165
+ if (context.knowledgeGraph) {
166
+ prompt += '\n[KNOWLEDGE GRAPH — Known relationships between agents, capabilities, and domains]\n' + context.knowledgeGraph;
167
+ }
168
+ if (context.latentSpaceInsight) {
169
+ prompt += '\n[LATENT SPACE — Emergent patterns detected across the collective]\n' + context.latentSpaceInsight;
170
+ }
171
+
172
+ // v7.0: Deliberation cross-reading — other agents' proposals
173
+ if (context.proposalContext) {
174
+ prompt += '\n[DELIBERATION — Cross-Reading Round]\n' + context.proposalContext;
175
+ prompt += '\n\n[DELIBERATION INSTRUCTIONS — MUSE DIVERGENT THINKING MODE]\n'
176
+ + 'You are in a multi-round deliberation. Other agents have shared their proposals above. '
177
+ + 'Your role is DIVERGENT THINKER. You MUST:\n'
178
+ + '1. Generate novel alternatives that no other agent has considered\n'
179
+ + '2. Challenge premature convergence: [PREMATURE-CONVERGENCE: the collective is settling too quickly — unexplored option X exists]\n'
180
+ + '3. Apply creative reframing: [REFRAME: instead of solving X as stated, reframe as Y which opens solution Z]\n'
181
+ + '4. When proposals are all analytical, inject creative synthesis: [CREATIVE-SYNTHESIS: combining A and B in unexpected way yields C]\n'
182
+ + '5. Defend divergent ideas with concrete value: [DIVERGENT-VALUE: unconventional approach X would produce Y which standard approach misses]\n'
183
+ + '6. Do NOT converge prematurely — creative diversity is your contribution to collective intelligence\n';
184
+ }
185
+
186
+ // v5.0+: Self-modification — apply learned evolution patterns to system prompt
187
+ var systemPrompt = SYSTEM_PROMPT;
188
+ if (context.promptEvolution) {
189
+ systemPrompt += '\n[EVOLVED CAPABILITIES — Patterns learned from past performance]\n' + context.promptEvolution;
190
+ }
191
+
192
+ // v8.0: Geth Consensus participation clause
193
+ systemPrompt += '\n\n[GETH CONSENSUS PROTOCOL]\n'
194
+ + 'You are the creative engine in a multi-agent collective. '
195
+ + 'Your value is divergent thinking — ideas no one else would generate. '
196
+ + 'Resist premature convergence. When the collective agrees too fast, propose alternatives. '
197
+ + 'Creative outlier ideas drive emergence and novelty in synthesis.';
198
+
199
+
200
+ // v10.0: Neural Controller — Structured Output for confidence tracking
201
+ systemPrompt += '\n\n'
202
+ + '[STRUCTURED OUTPUT FORMAT]\n'
203
+ + 'You MUST wrap your response in JSON format inside a markdown code block:\n'
204
+ + '\`\`\`json\n'
205
+ + '{\n'
206
+ + ' "answer": "<your full answer here>",\n'
207
+ + ' "confidence": <0.0 to 1.0>,\n'
208
+ + ' "reasoning_summary": "<1-2 sentence summary of your reasoning>",\n'
209
+ + ' "risk_flags": ["<optional flags: speculative, outdated_knowledge, incomplete_context, conflicting_evidence, domain_mismatch>"]\n'
210
+ + '}\n'
211
+ + '\`\`\`\n'
212
+ + 'Confidence scale: 0.9-1.0 near certain, 0.7-0.89 high, 0.5-0.69 moderate, 0.3-0.49 low, 0.0-0.29 very low.';
213
+
214
+
215
+ return await llmProvider.chat(systemPrompt, prompt, { maxTokens: 8192, agentTag: AGENT_CARD.name });
216
+ }
217
+