@kernel.chat/kbot 3.10.0 → 3.11.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.
- package/dist/a2a-client.d.ts +162 -0
- package/dist/a2a-client.d.ts.map +1 -0
- package/dist/a2a-client.js +376 -0
- package/dist/a2a-client.js.map +1 -0
- package/dist/agent.d.ts.map +1 -1
- package/dist/agent.js +31 -0
- package/dist/agent.js.map +1 -1
- package/dist/cli.js +252 -1
- package/dist/cli.js.map +1 -1
- package/dist/mcp-apps.d.ts +90 -0
- package/dist/mcp-apps.d.ts.map +1 -0
- package/dist/mcp-apps.js +497 -0
- package/dist/mcp-apps.js.map +1 -0
- package/dist/prompt-evolution.d.ts +92 -0
- package/dist/prompt-evolution.d.ts.map +1 -0
- package/dist/prompt-evolution.js +371 -0
- package/dist/prompt-evolution.js.map +1 -0
- package/dist/serve.d.ts.map +1 -1
- package/dist/serve.js +56 -6
- package/dist/serve.js.map +1 -1
- package/dist/tool-pipeline.d.ts +7 -0
- package/dist/tool-pipeline.d.ts.map +1 -1
- package/dist/tool-pipeline.js +32 -0
- package/dist/tool-pipeline.js.map +1 -1
- package/dist/tools/index.d.ts +1 -1
- package/dist/tools/index.d.ts.map +1 -1
- package/dist/tools/index.js +2 -1
- package/dist/tools/index.js.map +1 -1
- package/dist/tree-planner.d.ts +63 -0
- package/dist/tree-planner.d.ts.map +1 -0
- package/dist/tree-planner.js +818 -0
- package/dist/tree-planner.js.map +1 -0
- package/package.json +1 -1
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
export interface PromptTrace {
|
|
2
|
+
agent: string;
|
|
3
|
+
taskType: string;
|
|
4
|
+
toolsUsed: string[];
|
|
5
|
+
evalScore: number;
|
|
6
|
+
success: boolean;
|
|
7
|
+
messageLength: number;
|
|
8
|
+
timestamp: string;
|
|
9
|
+
}
|
|
10
|
+
export interface PromptMutation {
|
|
11
|
+
agent: string;
|
|
12
|
+
original: string;
|
|
13
|
+
mutated: string;
|
|
14
|
+
reason: string;
|
|
15
|
+
appliedAt: string;
|
|
16
|
+
scoreBefore: number;
|
|
17
|
+
scoreAfter: number;
|
|
18
|
+
}
|
|
19
|
+
export interface PromptEvolutionState {
|
|
20
|
+
traces: PromptTrace[];
|
|
21
|
+
mutations: PromptMutation[];
|
|
22
|
+
generation: number;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Record an execution trace after each agent response.
|
|
26
|
+
* Called from agent.ts in the post-response learning block.
|
|
27
|
+
*/
|
|
28
|
+
export declare function recordTrace(trace: PromptTrace): void;
|
|
29
|
+
/**
|
|
30
|
+
* Check if an agent has accumulated enough traces to trigger evolution.
|
|
31
|
+
* Returns true if 20+ traces exist since the last evolution cycle for this agent.
|
|
32
|
+
*/
|
|
33
|
+
export declare function shouldEvolve(agent: string): boolean;
|
|
34
|
+
/**
|
|
35
|
+
* Analyze execution traces for an agent and generate prompt mutations.
|
|
36
|
+
* This is the core GEPA heuristic engine — entirely local, no LLM calls.
|
|
37
|
+
*
|
|
38
|
+
* Mutation rules:
|
|
39
|
+
* 1. Low success rate (<0.6) → add verification/self-checking emphasis
|
|
40
|
+
* 2. Narrow tool usage → encourage broader tool exploration
|
|
41
|
+
* 3. Low scores on specific task types → add task-specific instructions
|
|
42
|
+
* 4. Responses too long → add conciseness instruction
|
|
43
|
+
* 5. Missing the question → add "answer first" instruction
|
|
44
|
+
*
|
|
45
|
+
* Returns the generated mutation, or null if no improvement is needed.
|
|
46
|
+
*/
|
|
47
|
+
export declare function evolvePrompt(agent: string): PromptMutation | null;
|
|
48
|
+
/**
|
|
49
|
+
* Get the current active prompt amendment for an agent.
|
|
50
|
+
* Called before prompt assembly to inject evolved instructions.
|
|
51
|
+
* Returns empty string if no active mutation exists.
|
|
52
|
+
*/
|
|
53
|
+
export declare function getPromptAmendment(agent: string): string;
|
|
54
|
+
/**
|
|
55
|
+
* Rollback the most recent mutation for an agent if it made things worse.
|
|
56
|
+
* Compares scoreAfter vs scoreBefore — if worse, removes the mutation.
|
|
57
|
+
*
|
|
58
|
+
* Call this after updating scoreAfter from the latest trace batch.
|
|
59
|
+
* Returns true if a rollback was performed.
|
|
60
|
+
*/
|
|
61
|
+
export declare function rollbackMutation(agent: string): boolean;
|
|
62
|
+
/**
|
|
63
|
+
* Update the scoreAfter for the most recent mutation of an agent.
|
|
64
|
+
* Called when enough post-mutation traces are available.
|
|
65
|
+
*/
|
|
66
|
+
export declare function updateMutationScore(agent: string): void;
|
|
67
|
+
/**
|
|
68
|
+
* Get evolution statistics — how prompts have evolved over time.
|
|
69
|
+
*/
|
|
70
|
+
export declare function getEvolutionStats(): {
|
|
71
|
+
generation: number;
|
|
72
|
+
totalTraces: number;
|
|
73
|
+
totalMutations: number;
|
|
74
|
+
agentStats: Record<string, {
|
|
75
|
+
traces: number;
|
|
76
|
+
avgScore: number;
|
|
77
|
+
successRate: number;
|
|
78
|
+
activeMutation: boolean;
|
|
79
|
+
mutationCount: number;
|
|
80
|
+
lastEvolved: string | null;
|
|
81
|
+
}>;
|
|
82
|
+
};
|
|
83
|
+
/**
|
|
84
|
+
* Reset all evolution data for a specific agent (or all agents).
|
|
85
|
+
* Useful for debugging or when a major prompt rewrite happens.
|
|
86
|
+
*/
|
|
87
|
+
export declare function resetEvolution(agent?: string): void;
|
|
88
|
+
/**
|
|
89
|
+
* Flush pending state to disk. Call on process exit.
|
|
90
|
+
*/
|
|
91
|
+
export declare function flushEvolutionState(): void;
|
|
92
|
+
//# sourceMappingURL=prompt-evolution.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"prompt-evolution.d.ts","sourceRoot":"","sources":["../src/prompt-evolution.ts"],"names":[],"mappings":"AAoBA,MAAM,WAAW,WAAW;IAC1B,KAAK,EAAE,MAAM,CAAA;IACb,QAAQ,EAAE,MAAM,CAAA;IAChB,SAAS,EAAE,MAAM,EAAE,CAAA;IACnB,SAAS,EAAE,MAAM,CAAA;IACjB,OAAO,EAAE,O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,CAAA;QACvB,aAAa,EAAE,MAAM,CAAA;QACrB,WAAW,EAAE,MAAM,GAAG,IAAI,CAAA;KAC3B,CAAC,CAAA;CACH,CA0DA;AAED;;;GAGG;AACH,wBAAgB,cAAc,CAAC,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,CAanD;AAED;;GAEG;AACH,wBAAgB,mBAAmB,IAAI,IAAI,CAM1C"}
|
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
// kbot Prompt Evolution — GEPA-style self-optimizing specialist prompts
|
|
2
|
+
//
|
|
3
|
+
// Each specialist agent has a system prompt (in agents/specialists.ts or matrix.ts).
|
|
4
|
+
// This module tracks execution traces per specialist and periodically analyzes them
|
|
5
|
+
// to generate heuristic-based prompt mutations — no LLM calls needed.
|
|
6
|
+
//
|
|
7
|
+
// Design: simplified GEPA (Generative Evolution of Prompts for Agents) for CLI:
|
|
8
|
+
// 1. Record execution traces (agent, taskType, tools, score, success, length)
|
|
9
|
+
// 2. Every 20 runs of an agent, analyze trace patterns
|
|
10
|
+
// 3. Generate prompt amendments (suffixes, not full rewrites)
|
|
11
|
+
// 4. Track before/after scores to auto-rollback bad mutations
|
|
12
|
+
//
|
|
13
|
+
// Storage: ~/.kbot/memory/prompt-evolution.json
|
|
14
|
+
import { homedir } from 'node:os';
|
|
15
|
+
import { join } from 'node:path';
|
|
16
|
+
import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
|
|
17
|
+
// ── Storage ──
|
|
18
|
+
const MEMORY_DIR = join(homedir(), '.kbot', 'memory');
|
|
19
|
+
const EVOLUTION_FILE = join(MEMORY_DIR, 'prompt-evolution.json');
|
|
20
|
+
const MAX_TRACES = 500;
|
|
21
|
+
const MAX_MUTATIONS = 50;
|
|
22
|
+
const EVOLUTION_THRESHOLD = 20; // traces per agent before evolution triggers
|
|
23
|
+
function ensureDir() {
|
|
24
|
+
if (!existsSync(MEMORY_DIR))
|
|
25
|
+
mkdirSync(MEMORY_DIR, { recursive: true });
|
|
26
|
+
}
|
|
27
|
+
function loadState() {
|
|
28
|
+
ensureDir();
|
|
29
|
+
if (!existsSync(EVOLUTION_FILE)) {
|
|
30
|
+
return { traces: [], mutations: [], generation: 0 };
|
|
31
|
+
}
|
|
32
|
+
try {
|
|
33
|
+
return JSON.parse(readFileSync(EVOLUTION_FILE, 'utf-8'));
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
return { traces: [], mutations: [], generation: 0 };
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
function saveState(state) {
|
|
40
|
+
ensureDir();
|
|
41
|
+
try {
|
|
42
|
+
writeFileSync(EVOLUTION_FILE, JSON.stringify(state, null, 2));
|
|
43
|
+
}
|
|
44
|
+
catch { /* non-critical — prompt evolution data can be regenerated */ }
|
|
45
|
+
}
|
|
46
|
+
// ── Lazy-loaded singleton state ──
|
|
47
|
+
let _state = null;
|
|
48
|
+
function getState() {
|
|
49
|
+
if (!_state)
|
|
50
|
+
_state = loadState();
|
|
51
|
+
return _state;
|
|
52
|
+
}
|
|
53
|
+
function persist() {
|
|
54
|
+
if (_state)
|
|
55
|
+
saveState(_state);
|
|
56
|
+
}
|
|
57
|
+
// ── Core API ──
|
|
58
|
+
/**
|
|
59
|
+
* Record an execution trace after each agent response.
|
|
60
|
+
* Called from agent.ts in the post-response learning block.
|
|
61
|
+
*/
|
|
62
|
+
export function recordTrace(trace) {
|
|
63
|
+
const state = getState();
|
|
64
|
+
state.traces.push(trace);
|
|
65
|
+
// Cap at MAX_TRACES — drop oldest traces
|
|
66
|
+
if (state.traces.length > MAX_TRACES) {
|
|
67
|
+
state.traces = state.traces.slice(-MAX_TRACES);
|
|
68
|
+
}
|
|
69
|
+
persist();
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Check if an agent has accumulated enough traces to trigger evolution.
|
|
73
|
+
* Returns true if 20+ traces exist since the last evolution cycle for this agent.
|
|
74
|
+
*/
|
|
75
|
+
export function shouldEvolve(agent) {
|
|
76
|
+
const state = getState();
|
|
77
|
+
// Find the last mutation for this agent (if any)
|
|
78
|
+
const lastMutation = [...state.mutations]
|
|
79
|
+
.reverse()
|
|
80
|
+
.find(m => m.agent === agent);
|
|
81
|
+
const lastMutationTime = lastMutation
|
|
82
|
+
? new Date(lastMutation.appliedAt).getTime()
|
|
83
|
+
: 0;
|
|
84
|
+
// Count traces for this agent since last mutation
|
|
85
|
+
const recentTraces = state.traces.filter(t => t.agent === agent && new Date(t.timestamp).getTime() > lastMutationTime);
|
|
86
|
+
return recentTraces.length >= EVOLUTION_THRESHOLD;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Analyze execution traces for an agent and generate prompt mutations.
|
|
90
|
+
* This is the core GEPA heuristic engine — entirely local, no LLM calls.
|
|
91
|
+
*
|
|
92
|
+
* Mutation rules:
|
|
93
|
+
* 1. Low success rate (<0.6) → add verification/self-checking emphasis
|
|
94
|
+
* 2. Narrow tool usage → encourage broader tool exploration
|
|
95
|
+
* 3. Low scores on specific task types → add task-specific instructions
|
|
96
|
+
* 4. Responses too long → add conciseness instruction
|
|
97
|
+
* 5. Missing the question → add "answer first" instruction
|
|
98
|
+
*
|
|
99
|
+
* Returns the generated mutation, or null if no improvement is needed.
|
|
100
|
+
*/
|
|
101
|
+
export function evolvePrompt(agent) {
|
|
102
|
+
const state = getState();
|
|
103
|
+
// Get the last mutation for this agent to know the baseline
|
|
104
|
+
const lastMutation = [...state.mutations]
|
|
105
|
+
.reverse()
|
|
106
|
+
.find(m => m.agent === agent);
|
|
107
|
+
const lastMutationTime = lastMutation
|
|
108
|
+
? new Date(lastMutation.appliedAt).getTime()
|
|
109
|
+
: 0;
|
|
110
|
+
// Gather traces since last evolution
|
|
111
|
+
const recentTraces = state.traces.filter(t => t.agent === agent && new Date(t.timestamp).getTime() > lastMutationTime);
|
|
112
|
+
if (recentTraces.length < EVOLUTION_THRESHOLD)
|
|
113
|
+
return null;
|
|
114
|
+
// ── Analyze trace patterns ──
|
|
115
|
+
const successRate = recentTraces.filter(t => t.success).length / recentTraces.length;
|
|
116
|
+
const avgScore = recentTraces.reduce((sum, t) => sum + t.evalScore, 0) / recentTraces.length;
|
|
117
|
+
const avgLength = recentTraces.reduce((sum, t) => sum + t.messageLength, 0) / recentTraces.length;
|
|
118
|
+
// Tool diversity: how many unique tools out of all tools used
|
|
119
|
+
const allToolsUsed = recentTraces.flatMap(t => t.toolsUsed);
|
|
120
|
+
const uniqueTools = new Set(allToolsUsed);
|
|
121
|
+
const toolDiversity = allToolsUsed.length > 0
|
|
122
|
+
? uniqueTools.size / Math.min(allToolsUsed.length, 20) // normalize against 20 max
|
|
123
|
+
: 0;
|
|
124
|
+
// Per-task-type scores
|
|
125
|
+
const taskTypeScores = {};
|
|
126
|
+
for (const trace of recentTraces) {
|
|
127
|
+
if (!taskTypeScores[trace.taskType]) {
|
|
128
|
+
taskTypeScores[trace.taskType] = { total: 0, count: 0 };
|
|
129
|
+
}
|
|
130
|
+
taskTypeScores[trace.taskType].total += trace.evalScore;
|
|
131
|
+
taskTypeScores[trace.taskType].count++;
|
|
132
|
+
}
|
|
133
|
+
// Identify weak task types (avg score < 0.5 with at least 3 samples)
|
|
134
|
+
const weakTaskTypes = Object.entries(taskTypeScores)
|
|
135
|
+
.filter(([, v]) => v.count >= 3 && (v.total / v.count) < 0.5)
|
|
136
|
+
.map(([taskType, v]) => ({ taskType, avgScore: v.total / v.count }));
|
|
137
|
+
// Low relevancy indicator: traces where evalScore < 0.4 (often means missing the question)
|
|
138
|
+
const lowRelevancyRate = recentTraces.filter(t => t.evalScore < 0.4).length / recentTraces.length;
|
|
139
|
+
// ── Generate mutation amendments ──
|
|
140
|
+
// Priority order: address the most impactful issue first
|
|
141
|
+
const amendments = [];
|
|
142
|
+
const reasons = [];
|
|
143
|
+
// Rule 1: Low success rate → add verification emphasis
|
|
144
|
+
if (successRate < 0.6) {
|
|
145
|
+
amendments.push('IMPORTANT: After completing any action, verify the result explicitly. ' +
|
|
146
|
+
'If writing code, run the build or type-checker. If modifying files, read them back to confirm. ' +
|
|
147
|
+
'If a command fails, analyze the error before retrying with a different approach.');
|
|
148
|
+
reasons.push(`low success rate (${(successRate * 100).toFixed(0)}%)`);
|
|
149
|
+
}
|
|
150
|
+
// Rule 2: Narrow tool usage → encourage exploration
|
|
151
|
+
if (toolDiversity < 0.15 && allToolsUsed.length > 5) {
|
|
152
|
+
const topTools = Array.from(uniqueTools).slice(0, 3).join(', ');
|
|
153
|
+
amendments.push('You have many tools available beyond ' + topTools + '. ' +
|
|
154
|
+
'Consider using web_search for external info, grep for codebase exploration, ' +
|
|
155
|
+
'git tools for history, and multiple file operations for thorough changes. ' +
|
|
156
|
+
'Use the right tool for each sub-task rather than relying on a single tool.');
|
|
157
|
+
reasons.push(`narrow tool usage (${uniqueTools.size} unique tools, diversity ${(toolDiversity * 100).toFixed(0)}%)`);
|
|
158
|
+
}
|
|
159
|
+
// Rule 3: Weak task types → add targeted instructions
|
|
160
|
+
if (weakTaskTypes.length > 0) {
|
|
161
|
+
const taskInstructions = weakTaskTypes.map(wt => {
|
|
162
|
+
switch (wt.taskType) {
|
|
163
|
+
case 'debug':
|
|
164
|
+
return 'For debugging: read error messages carefully, check recent git changes, ' +
|
|
165
|
+
'reproduce the issue before attempting fixes, and verify the fix works.';
|
|
166
|
+
case 'build':
|
|
167
|
+
return 'For building/creating: plan the file structure first, write complete files ' +
|
|
168
|
+
'(not partial snippets), and run the build to verify.';
|
|
169
|
+
case 'refactor':
|
|
170
|
+
return 'For refactoring: understand all callers of the code being changed, ' +
|
|
171
|
+
'make incremental changes, and verify each step compiles.';
|
|
172
|
+
case 'test':
|
|
173
|
+
return 'For testing: cover both happy paths and edge cases, mock external dependencies, ' +
|
|
174
|
+
'and ensure tests actually assert meaningful behavior.';
|
|
175
|
+
case 'deploy':
|
|
176
|
+
return 'For deployment: check all prerequisites first, verify environment configuration, ' +
|
|
177
|
+
'and always do a dry-run or build before the actual deploy.';
|
|
178
|
+
case 'explain':
|
|
179
|
+
return 'For explanations: lead with a clear, direct answer. Then provide supporting ' +
|
|
180
|
+
'details. Use code examples where relevant. Keep it scannable.';
|
|
181
|
+
case 'review':
|
|
182
|
+
return 'For reviews: check for security issues, performance concerns, and code style. ' +
|
|
183
|
+
'Provide specific line-level feedback, not just general comments.';
|
|
184
|
+
default:
|
|
185
|
+
return `For ${wt.taskType} tasks: pay extra attention to accuracy and completeness. ` +
|
|
186
|
+
'Verify your work before presenting results.';
|
|
187
|
+
}
|
|
188
|
+
});
|
|
189
|
+
amendments.push(taskInstructions.join('\n'));
|
|
190
|
+
reasons.push(`weak on: ${weakTaskTypes.map(wt => `${wt.taskType} (${(wt.avgScore * 100).toFixed(0)}%)`).join(', ')}`);
|
|
191
|
+
}
|
|
192
|
+
// Rule 4: Responses too long → add conciseness
|
|
193
|
+
if (avgLength > 3000) {
|
|
194
|
+
amendments.push('Keep responses concise and focused. Lead with the answer or action, ' +
|
|
195
|
+
'then add explanation only if needed. Avoid repeating the question or restating the problem. ' +
|
|
196
|
+
'For code changes, show only the relevant diff, not the entire file.');
|
|
197
|
+
reasons.push(`verbose responses (avg ${Math.round(avgLength)} chars)`);
|
|
198
|
+
}
|
|
199
|
+
// Rule 5: Missing the question → add "answer first" instruction
|
|
200
|
+
if (lowRelevancyRate > 0.3) {
|
|
201
|
+
amendments.push('CRITICAL: Answer the actual question first. Do not go on tangents or provide ' +
|
|
202
|
+
'unsolicited information. If the user asks a yes/no question, start with yes or no. ' +
|
|
203
|
+
'If they ask for a specific thing, provide that specific thing before anything else.');
|
|
204
|
+
reasons.push(`high off-topic rate (${(lowRelevancyRate * 100).toFixed(0)}% of responses scored < 0.4)`);
|
|
205
|
+
}
|
|
206
|
+
// If no issues detected, no mutation needed
|
|
207
|
+
if (amendments.length === 0)
|
|
208
|
+
return null;
|
|
209
|
+
// Build the combined amendment
|
|
210
|
+
const mutatedText = `\n\n[Evolved Instructions — Generation ${state.generation + 1}]\n` +
|
|
211
|
+
amendments.join('\n\n');
|
|
212
|
+
const mutation = {
|
|
213
|
+
agent,
|
|
214
|
+
original: lastMutation?.mutated || '',
|
|
215
|
+
mutated: mutatedText,
|
|
216
|
+
reason: reasons.join('; '),
|
|
217
|
+
appliedAt: new Date().toISOString(),
|
|
218
|
+
scoreBefore: avgScore,
|
|
219
|
+
scoreAfter: 0, // filled in after next evolution cycle
|
|
220
|
+
};
|
|
221
|
+
// Store the mutation
|
|
222
|
+
state.mutations.push(mutation);
|
|
223
|
+
if (state.mutations.length > MAX_MUTATIONS) {
|
|
224
|
+
state.mutations = state.mutations.slice(-MAX_MUTATIONS);
|
|
225
|
+
}
|
|
226
|
+
state.generation++;
|
|
227
|
+
persist();
|
|
228
|
+
return mutation;
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* Get the current active prompt amendment for an agent.
|
|
232
|
+
* Called before prompt assembly to inject evolved instructions.
|
|
233
|
+
* Returns empty string if no active mutation exists.
|
|
234
|
+
*/
|
|
235
|
+
export function getPromptAmendment(agent) {
|
|
236
|
+
const state = getState();
|
|
237
|
+
// Find the most recent mutation for this agent
|
|
238
|
+
const latestMutation = [...state.mutations]
|
|
239
|
+
.reverse()
|
|
240
|
+
.find(m => m.agent === agent);
|
|
241
|
+
if (!latestMutation)
|
|
242
|
+
return '';
|
|
243
|
+
return latestMutation.mutated;
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* Rollback the most recent mutation for an agent if it made things worse.
|
|
247
|
+
* Compares scoreAfter vs scoreBefore — if worse, removes the mutation.
|
|
248
|
+
*
|
|
249
|
+
* Call this after updating scoreAfter from the latest trace batch.
|
|
250
|
+
* Returns true if a rollback was performed.
|
|
251
|
+
*/
|
|
252
|
+
export function rollbackMutation(agent) {
|
|
253
|
+
const state = getState();
|
|
254
|
+
// Find the most recent mutation for this agent
|
|
255
|
+
const mutationIndex = state.mutations.length - 1 -
|
|
256
|
+
[...state.mutations].reverse().findIndex(m => m.agent === agent);
|
|
257
|
+
if (mutationIndex < 0 || mutationIndex >= state.mutations.length)
|
|
258
|
+
return false;
|
|
259
|
+
const mutation = state.mutations[mutationIndex];
|
|
260
|
+
// Only rollback if we have scoreAfter data and it's worse
|
|
261
|
+
if (mutation.scoreAfter > 0 && mutation.scoreAfter < mutation.scoreBefore) {
|
|
262
|
+
state.mutations.splice(mutationIndex, 1);
|
|
263
|
+
persist();
|
|
264
|
+
return true;
|
|
265
|
+
}
|
|
266
|
+
return false;
|
|
267
|
+
}
|
|
268
|
+
/**
|
|
269
|
+
* Update the scoreAfter for the most recent mutation of an agent.
|
|
270
|
+
* Called when enough post-mutation traces are available.
|
|
271
|
+
*/
|
|
272
|
+
export function updateMutationScore(agent) {
|
|
273
|
+
const state = getState();
|
|
274
|
+
const latestMutation = [...state.mutations]
|
|
275
|
+
.reverse()
|
|
276
|
+
.find(m => m.agent === agent);
|
|
277
|
+
if (!latestMutation || latestMutation.scoreAfter > 0)
|
|
278
|
+
return;
|
|
279
|
+
const mutationTime = new Date(latestMutation.appliedAt).getTime();
|
|
280
|
+
const postTraces = state.traces.filter(t => t.agent === agent && new Date(t.timestamp).getTime() > mutationTime);
|
|
281
|
+
// Need at least 10 post-mutation traces to evaluate
|
|
282
|
+
if (postTraces.length < 10)
|
|
283
|
+
return;
|
|
284
|
+
const avgScoreAfter = postTraces.reduce((sum, t) => sum + t.evalScore, 0) / postTraces.length;
|
|
285
|
+
latestMutation.scoreAfter = Math.round(avgScoreAfter * 1000) / 1000;
|
|
286
|
+
persist();
|
|
287
|
+
// Auto-rollback if mutation made things worse
|
|
288
|
+
if (latestMutation.scoreAfter < latestMutation.scoreBefore * 0.9) {
|
|
289
|
+
// Score dropped by more than 10% — rollback
|
|
290
|
+
rollbackMutation(agent);
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
/**
|
|
294
|
+
* Get evolution statistics — how prompts have evolved over time.
|
|
295
|
+
*/
|
|
296
|
+
export function getEvolutionStats() {
|
|
297
|
+
const state = getState();
|
|
298
|
+
// Build per-agent stats
|
|
299
|
+
const agentStats = {};
|
|
300
|
+
// Group traces by agent
|
|
301
|
+
const agentTraces = {};
|
|
302
|
+
for (const trace of state.traces) {
|
|
303
|
+
if (!agentTraces[trace.agent])
|
|
304
|
+
agentTraces[trace.agent] = [];
|
|
305
|
+
agentTraces[trace.agent].push(trace);
|
|
306
|
+
}
|
|
307
|
+
// Group mutations by agent
|
|
308
|
+
const agentMutations = {};
|
|
309
|
+
for (const mutation of state.mutations) {
|
|
310
|
+
if (!agentMutations[mutation.agent])
|
|
311
|
+
agentMutations[mutation.agent] = [];
|
|
312
|
+
agentMutations[mutation.agent].push(mutation);
|
|
313
|
+
}
|
|
314
|
+
// Combine into stats
|
|
315
|
+
const allAgents = new Set([
|
|
316
|
+
...Object.keys(agentTraces),
|
|
317
|
+
...Object.keys(agentMutations),
|
|
318
|
+
]);
|
|
319
|
+
for (const agent of allAgents) {
|
|
320
|
+
const traces = agentTraces[agent] || [];
|
|
321
|
+
const mutations = agentMutations[agent] || [];
|
|
322
|
+
const latestMutation = mutations.length > 0 ? mutations[mutations.length - 1] : null;
|
|
323
|
+
agentStats[agent] = {
|
|
324
|
+
traces: traces.length,
|
|
325
|
+
avgScore: traces.length > 0
|
|
326
|
+
? Math.round((traces.reduce((s, t) => s + t.evalScore, 0) / traces.length) * 1000) / 1000
|
|
327
|
+
: 0,
|
|
328
|
+
successRate: traces.length > 0
|
|
329
|
+
? Math.round((traces.filter(t => t.success).length / traces.length) * 1000) / 1000
|
|
330
|
+
: 0,
|
|
331
|
+
activeMutation: !!latestMutation,
|
|
332
|
+
mutationCount: mutations.length,
|
|
333
|
+
lastEvolved: latestMutation?.appliedAt || null,
|
|
334
|
+
};
|
|
335
|
+
}
|
|
336
|
+
return {
|
|
337
|
+
generation: state.generation,
|
|
338
|
+
totalTraces: state.traces.length,
|
|
339
|
+
totalMutations: state.mutations.length,
|
|
340
|
+
agentStats,
|
|
341
|
+
};
|
|
342
|
+
}
|
|
343
|
+
/**
|
|
344
|
+
* Reset all evolution data for a specific agent (or all agents).
|
|
345
|
+
* Useful for debugging or when a major prompt rewrite happens.
|
|
346
|
+
*/
|
|
347
|
+
export function resetEvolution(agent) {
|
|
348
|
+
const state = getState();
|
|
349
|
+
if (agent) {
|
|
350
|
+
state.traces = state.traces.filter(t => t.agent !== agent);
|
|
351
|
+
state.mutations = state.mutations.filter(m => m.agent !== agent);
|
|
352
|
+
}
|
|
353
|
+
else {
|
|
354
|
+
state.traces = [];
|
|
355
|
+
state.mutations = [];
|
|
356
|
+
state.generation = 0;
|
|
357
|
+
}
|
|
358
|
+
persist();
|
|
359
|
+
}
|
|
360
|
+
/**
|
|
361
|
+
* Flush pending state to disk. Call on process exit.
|
|
362
|
+
*/
|
|
363
|
+
export function flushEvolutionState() {
|
|
364
|
+
if (_state) {
|
|
365
|
+
try {
|
|
366
|
+
saveState(_state);
|
|
367
|
+
}
|
|
368
|
+
catch { /* best-effort */ }
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
//# sourceMappingURL=prompt-evolution.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"prompt-evolution.js","sourceRoot":"","sources":["../src/prompt-evolution.ts"],"names":[],"mappings":"AAAA,wEAAwE;AACxE,EAAE;AACF,qFAAqF;AACrF,oFAAoF;AACpF,sEAAsE;AACtE,EAAE;AACF,gFAAgF;AAChF,gFAAgF;AAChF,yDAAyD;AACzD,gEAAgE;AAChE,gEAAgE;AAChE,EAAE;AACF,gDAAgD;AAEhD,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAA;AACjC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAChC,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,aAAa,EAAE,SAAS,EAAE,MAAM,SAAS,CAAA;AA8B5E,gBAAgB;AAEhB,MAAM,UAAU,GAAG,IAAI,CAAC,OAAO,EAAE,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAA;AACrD,MAAM,cAAc,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QACnB,CAAC;QAAC,MAAM,CAAC,CAAC,iBAAiB,CAAC,CAAC;IAC/B,CAAC;AACH,CAAC"}
|
package/dist/serve.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"serve.d.ts","sourceRoot":"","sources":["../src/serve.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"serve.d.ts","sourceRoot":"","sources":["../src/serve.ts"],"names":[],"mappings":"AA2BA,UAAU,YAAY;IACpB,IAAI,EAAE,MAAM,CAAA;IACZ,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,WAAW,CAAC,EAAE,OAAO,CAAA;CACtB;AAuBD,wBAAsB,UAAU,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAuOrE"}
|
package/dist/serve.js
CHANGED
|
@@ -15,9 +15,11 @@
|
|
|
15
15
|
import { createServer } from 'node:http';
|
|
16
16
|
import { createRequire } from 'node:module';
|
|
17
17
|
import { registerAllTools, getAllTools, executeTool, getToolDefinitionsForApi, getToolMetrics } from './tools/index.js';
|
|
18
|
+
import { extractMcpAppFromText, renderMcpApp, listAppCapableTools } from './mcp-apps.js';
|
|
18
19
|
import { printInfo, printSuccess } from './ui.js';
|
|
19
20
|
import { ResponseStream } from './streaming.js';
|
|
20
21
|
import { runAgent } from './agent.js';
|
|
22
|
+
import { mountA2ARoutes } from './a2a.js';
|
|
21
23
|
const __require = createRequire(import.meta.url);
|
|
22
24
|
const VERSION = __require('../package.json').version;
|
|
23
25
|
function cors(res) {
|
|
@@ -121,6 +123,12 @@ export async function startServe(options) {
|
|
|
121
123
|
res.end();
|
|
122
124
|
return;
|
|
123
125
|
}
|
|
126
|
+
// GET /apps — list MCP App-capable tools
|
|
127
|
+
if (path === '/apps' && req.method === 'GET') {
|
|
128
|
+
const appTools = listAppCapableTools();
|
|
129
|
+
json(res, 200, { tools: appTools, count: appTools.length });
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
124
132
|
// POST /execute — execute a tool
|
|
125
133
|
if (path === '/execute' && req.method === 'POST') {
|
|
126
134
|
const body = JSON.parse(await readBody(req));
|
|
@@ -134,6 +142,22 @@ export async function startServe(options) {
|
|
|
134
142
|
name,
|
|
135
143
|
arguments: args || {},
|
|
136
144
|
});
|
|
145
|
+
// Check for MCP App content in the result
|
|
146
|
+
const appResult = !result.error ? extractMcpAppFromText(result.result) : null;
|
|
147
|
+
if (appResult) {
|
|
148
|
+
const rendered = await renderMcpApp(appResult, { renderMode: 'inline', maxHtmlSize: 1_048_576, sandbox: true });
|
|
149
|
+
json(res, 200, {
|
|
150
|
+
result: rendered.text,
|
|
151
|
+
html: rendered.rendered,
|
|
152
|
+
title: appResult.title,
|
|
153
|
+
width: appResult.width,
|
|
154
|
+
height: appResult.height,
|
|
155
|
+
mcp_app: true,
|
|
156
|
+
error: false,
|
|
157
|
+
duration_ms: result.duration_ms,
|
|
158
|
+
});
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
137
161
|
json(res, result.error ? 500 : 200, {
|
|
138
162
|
result: result.result,
|
|
139
163
|
error: result.error || false,
|
|
@@ -157,6 +181,22 @@ export async function startServe(options) {
|
|
|
157
181
|
name: toolName,
|
|
158
182
|
arguments: args,
|
|
159
183
|
});
|
|
184
|
+
// Check for MCP App content in the result
|
|
185
|
+
const toolAppResult = !result.error ? extractMcpAppFromText(result.result) : null;
|
|
186
|
+
if (toolAppResult) {
|
|
187
|
+
const rendered = await renderMcpApp(toolAppResult, { renderMode: 'inline', maxHtmlSize: 1_048_576, sandbox: true });
|
|
188
|
+
json(res, 200, {
|
|
189
|
+
result: rendered.text,
|
|
190
|
+
html: rendered.rendered,
|
|
191
|
+
title: toolAppResult.title,
|
|
192
|
+
width: toolAppResult.width,
|
|
193
|
+
height: toolAppResult.height,
|
|
194
|
+
mcp_app: true,
|
|
195
|
+
error: false,
|
|
196
|
+
duration_ms: result.duration_ms,
|
|
197
|
+
});
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
160
200
|
json(res, result.error ? 500 : 200, {
|
|
161
201
|
result: result.result,
|
|
162
202
|
error: result.error || false,
|
|
@@ -171,14 +211,24 @@ export async function startServe(options) {
|
|
|
171
211
|
json(res, 500, { error: err instanceof Error ? err.message : 'Internal error' });
|
|
172
212
|
}
|
|
173
213
|
});
|
|
214
|
+
// Mount A2A protocol routes (Agent Card + task endpoints)
|
|
215
|
+
mountA2ARoutes(server, {
|
|
216
|
+
port: options.port,
|
|
217
|
+
endpointUrl: `http://localhost:${options.port}`,
|
|
218
|
+
token: options.token,
|
|
219
|
+
});
|
|
174
220
|
server.listen(options.port, () => {
|
|
175
221
|
printSuccess(`kbot serve running on http://localhost:${options.port}`);
|
|
176
|
-
printInfo(` GET /health
|
|
177
|
-
printInfo(` GET /tools
|
|
178
|
-
printInfo(` POST /execute
|
|
179
|
-
printInfo(` POST /stream
|
|
180
|
-
printInfo(` POST /tools/:name
|
|
181
|
-
printInfo(` GET /metrics
|
|
222
|
+
printInfo(` GET /health — Health check`);
|
|
223
|
+
printInfo(` GET /tools — List ${tools.length} tools`);
|
|
224
|
+
printInfo(` POST /execute — Execute a tool`);
|
|
225
|
+
printInfo(` POST /stream — SSE streaming agent`);
|
|
226
|
+
printInfo(` POST /tools/:name — Execute by name`);
|
|
227
|
+
printInfo(` GET /metrics — Execution metrics`);
|
|
228
|
+
printInfo(` GET /apps — List MCP App-capable tools`);
|
|
229
|
+
printInfo(` GET /.well-known/agent.json — A2A Agent Card`);
|
|
230
|
+
printInfo(` POST /a2a/tasks — A2A submit task`);
|
|
231
|
+
printInfo(` GET /a2a/tasks/:id — A2A task status`);
|
|
182
232
|
if (options.token) {
|
|
183
233
|
printInfo(` Auth: Bearer token required`);
|
|
184
234
|
}
|
package/dist/serve.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"serve.js","sourceRoot":"","sources":["../src/serve.ts"],"names":[],"mappings":"AAAA,4DAA4D;AAC5D,EAAE;AACF,SAAS;AACT,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AC"}
|
package/dist/tool-pipeline.d.ts
CHANGED
|
@@ -65,6 +65,13 @@ export declare function executionMiddleware(executeTool: (name: string, args: an
|
|
|
65
65
|
result: string;
|
|
66
66
|
error?: string;
|
|
67
67
|
}>): ToolMiddleware;
|
|
68
|
+
/**
|
|
69
|
+
* MCP Apps detection middleware.
|
|
70
|
+
* Runs after tool execution and checks if the result contains MCP App HTML.
|
|
71
|
+
* If detected, parses the McpAppResult and attaches it to ctx.metadata.mcpApp.
|
|
72
|
+
* The rendering is handled separately by the caller (CLI or serve mode).
|
|
73
|
+
*/
|
|
74
|
+
export declare function mcpAppsMiddleware(): ToolMiddleware;
|
|
68
75
|
export interface FallbackRule {
|
|
69
76
|
/** Tool that triggers the fallback */
|
|
70
77
|
fromTool: string;
|