@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.
@@ -0,0 +1,162 @@
1
+ import { delegateTask, listRemoteAgents, removeRemoteAgent, findAgentBySkill, type AgentCard, type A2ATask, type A2ATaskStatus, type A2AMessage, type A2APart, type RemoteAgent } from './a2a.js';
2
+ export type { AgentCard, A2ATask, A2ATaskStatus, A2AMessage, A2APart, RemoteAgent, };
3
+ interface TaskHistoryEntry {
4
+ id: string;
5
+ agentUrl: string;
6
+ agentName?: string;
7
+ prompt: string;
8
+ status: A2ATaskStatus['state'];
9
+ result?: string;
10
+ createdAt: string;
11
+ completedAt?: string;
12
+ metadata?: Record<string, unknown>;
13
+ }
14
+ /**
15
+ * Generate kbot's Agent Card JSON with all specialists as skills.
16
+ *
17
+ * @param endpointUrl - The URL where this kbot instance is reachable.
18
+ * Defaults to http://localhost:7437.
19
+ * @returns A fully populated AgentCard per the A2A v0.3 spec.
20
+ */
21
+ export declare function generateAgentCard(endpointUrl?: string): AgentCard;
22
+ /**
23
+ * Discover a remote A2A agent by fetching its Agent Card from
24
+ * `<url>/.well-known/agent.json`.
25
+ *
26
+ * The discovered agent is persisted in the local registry at
27
+ * `~/.kbot/a2a-registry.json` for future lookups.
28
+ *
29
+ * @param url - Base URL of the remote agent (e.g. "http://other-agent:8080")
30
+ * @returns The agent's card, or null if discovery fails.
31
+ */
32
+ export declare function discoverAgent(url: string): Promise<AgentCard | null>;
33
+ export interface SendTaskOptions {
34
+ /** Hint which specialist agent should handle the task */
35
+ agent?: string;
36
+ /** Additional metadata to attach to the task */
37
+ metadata?: Record<string, unknown>;
38
+ /** Auth token for the remote agent (Bearer) */
39
+ token?: string;
40
+ /** Whether to wait for completion (sync) or return immediately (async).
41
+ * Defaults to true (synchronous). */
42
+ sync?: boolean;
43
+ /** Timeout in milliseconds. Defaults to 120_000 (2 min). */
44
+ timeoutMs?: number;
45
+ }
46
+ /**
47
+ * Send a task to a remote A2A agent.
48
+ *
49
+ * By default this is synchronous — it waits for the remote agent to complete
50
+ * the task and returns the result. Set `options.sync = false` to submit
51
+ * asynchronously (returns immediately with a submitted-state task).
52
+ *
53
+ * @param agentUrl - Base URL of the remote agent
54
+ * @param task - The prompt text or a structured A2AMessage
55
+ * @param options - Execution options
56
+ * @returns The task result, including id, status, and response text
57
+ */
58
+ export declare function sendTask(agentUrl: string, task: string | {
59
+ prompt: string;
60
+ }, options?: SendTaskOptions): Promise<{
61
+ id: string;
62
+ status: A2ATaskStatus['state'];
63
+ text: string | null;
64
+ metadata: Record<string, unknown>;
65
+ }>;
66
+ /**
67
+ * Check the status and result of a previously submitted task.
68
+ *
69
+ * @param agentUrl - Base URL of the remote agent
70
+ * @param taskId - The task ID returned by sendTask
71
+ * @param options - Optional auth token
72
+ * @returns Current task state and any available result
73
+ */
74
+ export declare function getTaskStatus(agentUrl: string, taskId: string, options?: {
75
+ token?: string;
76
+ }): Promise<{
77
+ id: string;
78
+ status: A2ATaskStatus['state'];
79
+ message?: string;
80
+ text: string | null;
81
+ metadata: Record<string, unknown>;
82
+ }>;
83
+ /**
84
+ * Cancel a running task on a remote agent.
85
+ *
86
+ * @param agentUrl - Base URL of the remote agent
87
+ * @param taskId - The task ID to cancel
88
+ * @param options - Optional auth token
89
+ * @returns true if the task was canceled, false if it was already terminal
90
+ */
91
+ export declare function cancelTask(agentUrl: string, taskId: string, options?: {
92
+ token?: string;
93
+ }): Promise<boolean>;
94
+ /**
95
+ * Handle an incoming A2A task received by this kbot instance.
96
+ *
97
+ * Routes the task to the appropriate specialist agent based on metadata
98
+ * hints or automatic intent classification, executes it through kbot's
99
+ * agent system, and returns the completed task.
100
+ *
101
+ * This is used internally by the A2A server but is exported for
102
+ * programmatic use (e.g., SDK consumers, custom servers).
103
+ *
104
+ * @param task - The incoming task with a user message
105
+ * @returns The task with result populated and status set to completed/failed
106
+ */
107
+ export declare function handleIncomingTask(task: {
108
+ message: A2AMessage;
109
+ metadata?: Record<string, unknown>;
110
+ }): Promise<{
111
+ id: string;
112
+ status: A2ATaskStatus['state'];
113
+ text: string | null;
114
+ metadata: Record<string, unknown>;
115
+ }>;
116
+ /**
117
+ * List all discovered remote agents from the local registry.
118
+ */
119
+ export { listRemoteAgents, removeRemoteAgent, findAgentBySkill };
120
+ /**
121
+ * Delegate a task to a remote agent (convenience wrapper around sendTask
122
+ * that matches the existing delegateTask signature in a2a.ts).
123
+ */
124
+ export { delegateTask };
125
+ /**
126
+ * Get the local task history (tasks sent to remote agents).
127
+ */
128
+ export declare function getTaskHistory(): TaskHistoryEntry[];
129
+ /**
130
+ * Clear the local task history.
131
+ */
132
+ export declare function clearTaskHistory(): void;
133
+ export interface CollaborationPlan {
134
+ steps: {
135
+ agentUrl: string;
136
+ agentName?: string;
137
+ prompt: string;
138
+ dependsOn?: number[];
139
+ }[];
140
+ }
141
+ /**
142
+ * Execute a multi-step collaboration plan across multiple A2A agents.
143
+ *
144
+ * Steps without dependencies run in parallel. Steps with `dependsOn`
145
+ * wait for their dependencies to complete and inject their results
146
+ * into the prompt using `{{step:N}}` placeholders.
147
+ *
148
+ * @param plan - The collaboration plan
149
+ * @param options - Auth tokens keyed by agent URL
150
+ * @returns Results for each step
151
+ */
152
+ export declare function collaborate(plan: CollaborationPlan, options?: {
153
+ tokens?: Record<string, string>;
154
+ }): Promise<{
155
+ results: {
156
+ stepIndex: number;
157
+ agentUrl: string;
158
+ status: A2ATaskStatus['state'];
159
+ text: string | null;
160
+ }[];
161
+ }>;
162
+ //# sourceMappingURL=a2a-client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"a2a-client.d.ts","sourceRoot":"","sources":["../src/a2a-client.ts"],"names":[],"mappings":"AAcA,OAAO,EAGL,YAAY,EACZ,gBAAgB,EAChB,iBAAiB,EACjB,gBAAgB,EAChB,KAAK,SAAS,EACd,KAAK,OAAO,EACZ,KAAK,aAAa,EAClB,KAAK,UAAU,EACf,KAAK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AGG;AACH,OAAO,EAAE,YAAY,EAAE,CAAA;AAEvB;;GAEG;AACH,wBAAgB,cAAc,IAAI,gBAAgB,EAAE,CAEnD;AAED;;GAEG;AACH,wBAAgB,gBAAgB,IAAI,IAAI,CAIvC;AAID,MAAM,WAAW,iBAAiB;IAChC,KAAK,EAAE;QACL,QAAQ,EAAE,MAAM,CAAA;QAChB,SAAS,CAAC,EAAE,MAAM,CAAA;QAClB,MAAM,EAAE,MAAM,CAAA;QACd,SAAS,CAAC,EAAE,MAAM,EAAE,CAAA;KACrB,EAAE,CAAA;CACJ;AAED;;;;;;;;;;GAUG;AACH,wBAAsB,WAAW,CAC/B,IAAI,EAAE,iBAAiB,EACvB,OAAO,GAAE;IAAE,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;CAAO,GAChD,OAAO,CAAC;IACT,OAAO,EAAE;QACP,SAAS,EAAE,MAAM,CAAA;QACjB,QAAQ,EAAE,MAAM,CAAA;QAChB,MAAM,EAAE,aAAa,CAAC,OAAO,CAAC,CAAA;QAC9B,IAAI,EAAE,MAAM,GAAG,IAAI,CAAA;KACpB,EAAE,CAAA;CACJ,CAAC,CA6DD"}
@@ -0,0 +1,376 @@
1
+ // kbot A2A Client — Agent-to-Agent protocol client (v0.3)
2
+ //
3
+ // Discovers remote A2A agents, sends tasks, tracks lifecycle, cancels work.
4
+ // Complements a2a.ts which provides the server side + Agent Card generation.
5
+ //
6
+ // Usage:
7
+ // import { discoverAgent, sendTask, getTaskStatus, cancelTask } from './a2a-client.js'
8
+ // const card = await discoverAgent('http://other-agent:8080')
9
+ // const task = await sendTask('http://other-agent:8080', { prompt: 'Summarize this repo' })
10
+ // const status = await getTaskStatus('http://other-agent:8080', task.id)
11
+ import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';
12
+ import { join } from 'node:path';
13
+ import { homedir } from 'node:os';
14
+ import { buildAgentCard, discoverAgent as discoverAgentCore, delegateTask, listRemoteAgents, removeRemoteAgent, findAgentBySkill, } from './a2a.js';
15
+ // ── Constants ──
16
+ const KBOT_DIR = join(homedir(), '.kbot');
17
+ const TASK_HISTORY_PATH = join(KBOT_DIR, 'a2a-task-history.json');
18
+ const DEFAULT_TIMEOUT_MS = 120_000; // 2 minutes
19
+ const DISCOVERY_TIMEOUT_MS = 10_000; // 10 seconds
20
+ function loadTaskHistory() {
21
+ try {
22
+ if (!existsSync(TASK_HISTORY_PATH))
23
+ return [];
24
+ return JSON.parse(readFileSync(TASK_HISTORY_PATH, 'utf-8'));
25
+ }
26
+ catch {
27
+ return [];
28
+ }
29
+ }
30
+ function saveTaskHistory(history) {
31
+ if (!existsSync(KBOT_DIR))
32
+ mkdirSync(KBOT_DIR, { recursive: true });
33
+ // Keep last 500 entries
34
+ const trimmed = history.slice(-500);
35
+ writeFileSync(TASK_HISTORY_PATH, JSON.stringify(trimmed, null, 2));
36
+ }
37
+ function recordTask(entry) {
38
+ const history = loadTaskHistory();
39
+ // Update existing or append
40
+ const idx = history.findIndex(h => h.id === entry.id);
41
+ if (idx >= 0) {
42
+ history[idx] = entry;
43
+ }
44
+ else {
45
+ history.push(entry);
46
+ }
47
+ saveTaskHistory(history);
48
+ }
49
+ // ── Agent Card Generator ──
50
+ /**
51
+ * Generate kbot's Agent Card JSON with all specialists as skills.
52
+ *
53
+ * @param endpointUrl - The URL where this kbot instance is reachable.
54
+ * Defaults to http://localhost:7437.
55
+ * @returns A fully populated AgentCard per the A2A v0.3 spec.
56
+ */
57
+ export function generateAgentCard(endpointUrl) {
58
+ return buildAgentCard(endpointUrl);
59
+ }
60
+ // ── Discovery ──
61
+ /**
62
+ * Discover a remote A2A agent by fetching its Agent Card from
63
+ * `<url>/.well-known/agent.json`.
64
+ *
65
+ * The discovered agent is persisted in the local registry at
66
+ * `~/.kbot/a2a-registry.json` for future lookups.
67
+ *
68
+ * @param url - Base URL of the remote agent (e.g. "http://other-agent:8080")
69
+ * @returns The agent's card, or null if discovery fails.
70
+ */
71
+ export async function discoverAgent(url) {
72
+ return discoverAgentCore(url);
73
+ }
74
+ /**
75
+ * Send a task to a remote A2A agent.
76
+ *
77
+ * By default this is synchronous — it waits for the remote agent to complete
78
+ * the task and returns the result. Set `options.sync = false` to submit
79
+ * asynchronously (returns immediately with a submitted-state task).
80
+ *
81
+ * @param agentUrl - Base URL of the remote agent
82
+ * @param task - The prompt text or a structured A2AMessage
83
+ * @param options - Execution options
84
+ * @returns The task result, including id, status, and response text
85
+ */
86
+ export async function sendTask(agentUrl, task, options = {}) {
87
+ const prompt = typeof task === 'string' ? task : task.prompt;
88
+ const sync = options.sync !== false;
89
+ const timeout = options.timeoutMs || DEFAULT_TIMEOUT_MS;
90
+ const baseUrl = agentUrl.replace(/\/$/, '');
91
+ const taskUrl = `${baseUrl}/a2a/tasks${sync ? '?sync=true' : ''}`;
92
+ const body = {
93
+ message: {
94
+ role: 'user',
95
+ parts: [{ type: 'text', text: prompt }],
96
+ },
97
+ };
98
+ if (options.agent || options.metadata) {
99
+ body.metadata = { ...options.metadata, agent: options.agent };
100
+ }
101
+ const headers = {
102
+ 'Content-Type': 'application/json',
103
+ };
104
+ if (options.token) {
105
+ headers['Authorization'] = `Bearer ${options.token}`;
106
+ }
107
+ const response = await fetch(taskUrl, {
108
+ method: 'POST',
109
+ headers,
110
+ body: JSON.stringify(body),
111
+ signal: AbortSignal.timeout(timeout),
112
+ });
113
+ if (!response.ok) {
114
+ const errText = await response.text().catch(() => 'Unknown error');
115
+ throw new Error(`A2A task submission failed (${response.status}): ${errText}`);
116
+ }
117
+ const result = await response.json();
118
+ const text = result.result?.parts
119
+ ?.filter((p) => p.type === 'text')
120
+ .map(p => p.text)
121
+ .join('\n') ?? null;
122
+ // Record in local history
123
+ recordTask({
124
+ id: result.id,
125
+ agentUrl,
126
+ prompt,
127
+ status: result.status.state,
128
+ result: text ?? undefined,
129
+ createdAt: new Date().toISOString(),
130
+ completedAt: result.status.state === 'completed' ? new Date().toISOString() : undefined,
131
+ metadata: result.metadata,
132
+ });
133
+ return {
134
+ id: result.id,
135
+ status: result.status.state,
136
+ text,
137
+ metadata: result.metadata || {},
138
+ };
139
+ }
140
+ /**
141
+ * Check the status and result of a previously submitted task.
142
+ *
143
+ * @param agentUrl - Base URL of the remote agent
144
+ * @param taskId - The task ID returned by sendTask
145
+ * @param options - Optional auth token
146
+ * @returns Current task state and any available result
147
+ */
148
+ export async function getTaskStatus(agentUrl, taskId, options = {}) {
149
+ const baseUrl = agentUrl.replace(/\/$/, '');
150
+ const url = `${baseUrl}/a2a/tasks/${taskId}`;
151
+ const headers = {
152
+ 'Accept': 'application/json',
153
+ };
154
+ if (options.token) {
155
+ headers['Authorization'] = `Bearer ${options.token}`;
156
+ }
157
+ const response = await fetch(url, {
158
+ headers,
159
+ signal: AbortSignal.timeout(DISCOVERY_TIMEOUT_MS),
160
+ });
161
+ if (!response.ok) {
162
+ if (response.status === 404) {
163
+ throw new Error(`Task ${taskId} not found on ${agentUrl}`);
164
+ }
165
+ throw new Error(`Failed to get task status (${response.status})`);
166
+ }
167
+ const result = await response.json();
168
+ const text = result.result?.parts
169
+ ?.filter((p) => p.type === 'text')
170
+ .map(p => p.text)
171
+ .join('\n') ?? null;
172
+ // Update local history
173
+ recordTask({
174
+ id: result.id,
175
+ agentUrl,
176
+ prompt: '(status check)',
177
+ status: result.status.state,
178
+ result: text ?? undefined,
179
+ createdAt: new Date().toISOString(),
180
+ completedAt: result.status.state === 'completed' ? new Date().toISOString() : undefined,
181
+ metadata: result.metadata,
182
+ });
183
+ return {
184
+ id: result.id,
185
+ status: result.status.state,
186
+ message: result.status.message,
187
+ text,
188
+ metadata: result.metadata || {},
189
+ };
190
+ }
191
+ /**
192
+ * Cancel a running task on a remote agent.
193
+ *
194
+ * @param agentUrl - Base URL of the remote agent
195
+ * @param taskId - The task ID to cancel
196
+ * @param options - Optional auth token
197
+ * @returns true if the task was canceled, false if it was already terminal
198
+ */
199
+ export async function cancelTask(agentUrl, taskId, options = {}) {
200
+ const baseUrl = agentUrl.replace(/\/$/, '');
201
+ const url = `${baseUrl}/a2a/tasks/${taskId}/cancel`;
202
+ const headers = {
203
+ 'Content-Type': 'application/json',
204
+ };
205
+ if (options.token) {
206
+ headers['Authorization'] = `Bearer ${options.token}`;
207
+ }
208
+ const response = await fetch(url, {
209
+ method: 'POST',
210
+ headers,
211
+ signal: AbortSignal.timeout(DISCOVERY_TIMEOUT_MS),
212
+ });
213
+ if (response.status === 409) {
214
+ // Task already in terminal state
215
+ return false;
216
+ }
217
+ if (!response.ok) {
218
+ if (response.status === 404) {
219
+ throw new Error(`Task ${taskId} not found on ${agentUrl}`);
220
+ }
221
+ throw new Error(`Failed to cancel task (${response.status})`);
222
+ }
223
+ return true;
224
+ }
225
+ // ── Incoming Task Handling ──
226
+ /**
227
+ * Handle an incoming A2A task received by this kbot instance.
228
+ *
229
+ * Routes the task to the appropriate specialist agent based on metadata
230
+ * hints or automatic intent classification, executes it through kbot's
231
+ * agent system, and returns the completed task.
232
+ *
233
+ * This is used internally by the A2A server but is exported for
234
+ * programmatic use (e.g., SDK consumers, custom servers).
235
+ *
236
+ * @param task - The incoming task with a user message
237
+ * @returns The task with result populated and status set to completed/failed
238
+ */
239
+ export async function handleIncomingTask(task) {
240
+ const agentModule = await import('./agent.js');
241
+ const runAgent = agentModule.runAgent;
242
+ const text = task.message.parts
243
+ .filter((p) => p.type === 'text')
244
+ .map(p => p.text)
245
+ .join('\n');
246
+ if (!text) {
247
+ return {
248
+ id: 'inline-' + Date.now(),
249
+ status: 'failed',
250
+ text: null,
251
+ metadata: { error: 'No text content in message' },
252
+ };
253
+ }
254
+ const agentOpts = {};
255
+ if (task.metadata?.agent && typeof task.metadata.agent === 'string') {
256
+ agentOpts.agent = task.metadata.agent;
257
+ }
258
+ try {
259
+ const response = await runAgent(text, agentOpts);
260
+ return {
261
+ id: 'inline-' + Date.now(),
262
+ status: 'completed',
263
+ text: response.content,
264
+ metadata: {
265
+ ...task.metadata,
266
+ agentUsed: response.agent,
267
+ model: response.model,
268
+ toolCalls: response.toolCalls,
269
+ usage: response.usage,
270
+ },
271
+ };
272
+ }
273
+ catch (err) {
274
+ return {
275
+ id: 'inline-' + Date.now(),
276
+ status: 'failed',
277
+ text: null,
278
+ metadata: {
279
+ ...task.metadata,
280
+ error: err instanceof Error ? err.message : 'Task execution failed',
281
+ },
282
+ };
283
+ }
284
+ }
285
+ // ── Convenience / Registry ──
286
+ /**
287
+ * List all discovered remote agents from the local registry.
288
+ */
289
+ export { listRemoteAgents, removeRemoteAgent, findAgentBySkill };
290
+ /**
291
+ * Delegate a task to a remote agent (convenience wrapper around sendTask
292
+ * that matches the existing delegateTask signature in a2a.ts).
293
+ */
294
+ export { delegateTask };
295
+ /**
296
+ * Get the local task history (tasks sent to remote agents).
297
+ */
298
+ export function getTaskHistory() {
299
+ return loadTaskHistory();
300
+ }
301
+ /**
302
+ * Clear the local task history.
303
+ */
304
+ export function clearTaskHistory() {
305
+ if (existsSync(TASK_HISTORY_PATH)) {
306
+ writeFileSync(TASK_HISTORY_PATH, '[]');
307
+ }
308
+ }
309
+ /**
310
+ * Execute a multi-step collaboration plan across multiple A2A agents.
311
+ *
312
+ * Steps without dependencies run in parallel. Steps with `dependsOn`
313
+ * wait for their dependencies to complete and inject their results
314
+ * into the prompt using `{{step:N}}` placeholders.
315
+ *
316
+ * @param plan - The collaboration plan
317
+ * @param options - Auth tokens keyed by agent URL
318
+ * @returns Results for each step
319
+ */
320
+ export async function collaborate(plan, options = {}) {
321
+ const results = new Map();
322
+ const pending = new Set(plan.steps.map((_, i) => i));
323
+ while (pending.size > 0) {
324
+ // Find steps whose dependencies are all resolved
325
+ const ready = [];
326
+ for (const idx of pending) {
327
+ const step = plan.steps[idx];
328
+ const deps = step.dependsOn || [];
329
+ if (deps.every(d => results.has(d))) {
330
+ ready.push(idx);
331
+ }
332
+ }
333
+ if (ready.length === 0) {
334
+ // Deadlock — remaining steps have unresolvable dependencies
335
+ for (const idx of pending) {
336
+ results.set(idx, { status: 'failed', text: 'Deadlock: unresolvable dependencies' });
337
+ }
338
+ break;
339
+ }
340
+ // Execute ready steps in parallel
341
+ const executions = ready.map(async (idx) => {
342
+ const step = plan.steps[idx];
343
+ pending.delete(idx);
344
+ // Substitute dependency results into prompt
345
+ let prompt = step.prompt;
346
+ for (const depIdx of step.dependsOn || []) {
347
+ const depResult = results.get(depIdx);
348
+ const placeholder = `{{step:${depIdx}}}`;
349
+ prompt = prompt.replace(placeholder, depResult?.text || '(no result)');
350
+ }
351
+ try {
352
+ const result = await sendTask(step.agentUrl, prompt, {
353
+ token: options.tokens?.[step.agentUrl],
354
+ sync: true,
355
+ });
356
+ results.set(idx, { status: result.status, text: result.text });
357
+ }
358
+ catch (err) {
359
+ results.set(idx, {
360
+ status: 'failed',
361
+ text: err instanceof Error ? err.message : 'Collaboration step failed',
362
+ });
363
+ }
364
+ });
365
+ await Promise.all(executions);
366
+ }
367
+ return {
368
+ results: plan.steps.map((step, idx) => ({
369
+ stepIndex: idx,
370
+ agentUrl: step.agentUrl,
371
+ status: results.get(idx)?.status || 'failed',
372
+ text: results.get(idx)?.text || null,
373
+ })),
374
+ };
375
+ }
376
+ //# sourceMappingURL=a2a-client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"a2a-client.js","sourceRoot":"","sources":["../src/a2a-client.ts"],"names":[],"mappings":"AAAA,0DAA0D;AAC1D,EAAE;AACF,4EAA4E;AAC5E,6EAA6E;AAC7E,EAAE;AACF,SAAS;AACT,yFAAyF;AACzF,gEAAgE;AAChE,8FAA8F;AAC9F,2EAA2E;AAE3E,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,SAAS,CAAA;AAC5E,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAChC,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAA;AACjC,OAAO,EACL,cAAc,EACd,aAAa,IAAI,iBAAiB,EAClC,YAAY,EACZ,gBAAgB,EAChB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AM,CAAA;KAAE,CAAA;CAC1E;AA+qBD,wBAAsB,QAAQ,CAC5B,OAAO,EAAE,MAAM,EACf,OAAO,GAAE,YAAiB,GACzB,OAAO,CAAC,aAAa,CAAC,CA44BxB;AAGD,6CAA6C;AAC7C,wBAAsB,WAAW,CAC/B,OAAO,EAAE,MAAM,EACf,OAAO,GAAE,YAAiB,GACzB,OAAO,CAAC,IAAI,CAAC,CAkEf;AAGD;;;GAGG;AACH,wBAAsB,sBAAsB,CAC1C,UAAU,EAAE,UAAU,EACtB,OAAO,GAAE,YAAiB,GACzB,OAAO,CAAC,aAAa,CAAC,CAgCxB"}
package/dist/agent.js CHANGED
@@ -47,6 +47,7 @@ import { StrangeLoopDetector } from './strange-loops.js';
47
47
  import { IntegrationMeter } from './integrated-information.js';
48
48
  import { generateReflections, getRelevantReflections, formatReflectionsForPrompt, isUserRejection } from './reflection.js';
49
49
  import { getSynthesisContext } from './memory-synthesis.js';
50
+ import { recordTrace, shouldEvolve, evolvePrompt, getPromptAmendment, updateMutationScore } from './prompt-evolution.js';
50
51
  const MAX_TOOL_LOOPS = 75;
51
52
  /** Maximum cumulative cost (USD) before auto-stopping tool loops */
52
53
  const MAX_COST_CEILING = 1.00;
@@ -934,6 +935,12 @@ Always quote file paths that contain spaces. Never reference internal system nam
934
935
  });
935
936
  const provider = byokProvider || 'anthropic';
936
937
  let { text: systemContext } = buildCacheablePrompt(promptSections, provider);
938
+ // Prompt evolution: inject evolved instructions for this agent (GEPA)
939
+ const activeAgent = options.agent || 'kernel';
940
+ const promptAmendment = getPromptAmendment(activeAgent);
941
+ if (promptAmendment) {
942
+ systemContext += promptAmendment;
943
+ }
937
944
  // Plan mode: append read-only instruction to system prompt
938
945
  if (options.plan) {
939
946
  systemContext += '\n\n## PLAN MODE\n\nYou are in PLAN MODE. You can read, search, and analyze — but you CANNOT write files, execute commands, or make changes. Your job is to understand the problem and propose a plan. Output a numbered list of steps.';
@@ -1326,6 +1333,30 @@ Always quote file paths that contain spaces. Never reference internal system nam
1326
1333
  }
1327
1334
  catch { /* silent */ }
1328
1335
  }
1336
+ // ── Prompt Evolution (GEPA): record trace and evolve if threshold met ──
1337
+ try {
1338
+ const traceAgent = lastResponse.agent || 'kernel';
1339
+ recordTrace({
1340
+ agent: traceAgent,
1341
+ taskType: classifyTask(originalMessage),
1342
+ toolsUsed: [...toolSequenceLog],
1343
+ evalScore: selfEvalScore ?? 0.7,
1344
+ success: true,
1345
+ messageLength: content.length,
1346
+ timestamp: new Date().toISOString(),
1347
+ });
1348
+ // Check if we should evolve this agent's prompt
1349
+ if (shouldEvolve(traceAgent)) {
1350
+ const mutation = evolvePrompt(traceAgent);
1351
+ if (mutation) {
1352
+ // Log evolution event (non-blocking, info-level)
1353
+ process.stderr.write(`\n \x1b[2m[prompt-evolution] ${traceAgent} evolved: ${mutation.reason}\x1b[0m\n`);
1354
+ }
1355
+ }
1356
+ // Update scoreAfter for recent mutations (needs 10+ post-mutation traces)
1357
+ updateMutationScore(traceAgent);
1358
+ }
1359
+ catch { /* prompt evolution is non-critical */ }
1329
1360
  // ── Post-execution cognitive updates (v3.6.2) ──
1330
1361
  try {
1331
1362
  // Free energy — update beliefs based on tool results