@ptkl/toolkit 0.10.4 → 0.14.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,759 @@
1
+ import { readFileSync, writeFileSync, existsSync } from 'node:fs';
2
+ import { resolve } from 'node:path';
3
+ import axios from 'axios';
4
+ import { getToolDefinitions, executeTool } from './tools.js';
5
+ import { MCPManager } from './mcp.js';
6
+ import { saveKortexConfig } from './config.js';
7
+ import { createConversation as createLocalConversation, saveConversation, loadConversation, listConversations, } from './conversations.js';
8
+ const PLATFORM_AGENTS = [
9
+ { uuid: 'protokol-bot', name: 'ProtokolBot', description: 'Free tier platform assistant' },
10
+ { uuid: 'proka', name: 'Proka', description: 'Standard tier platform assistant' },
11
+ { uuid: 'prota', name: 'Prota', description: 'Pro tier platform assistant' },
12
+ ];
13
+ const MAX_TOOL_ROUNDS = 25;
14
+ const CONTEXT_LIMIT = 128_000;
15
+ const SLASH_COMMANDS = [
16
+ '/thoughts', '/clear', '/compact', '/undo', '/cost',
17
+ '/files', '/history', '/conversations', '/agents', '/add', '/remove', '/agent', '/profile', '/help', '/quit',
18
+ ];
19
+ function isDangerous(call) {
20
+ switch (call.function.name) {
21
+ case 'bash':
22
+ case 'write_file':
23
+ case 'edit_file':
24
+ case 'git_commit':
25
+ return true;
26
+ case 'git_branch': {
27
+ try {
28
+ const args = JSON.parse(call.function.arguments);
29
+ return args.action === 'create' || args.action === 'switch';
30
+ }
31
+ catch {
32
+ return true;
33
+ }
34
+ }
35
+ default:
36
+ return false;
37
+ }
38
+ }
39
+ function getToolSummary(name, args) {
40
+ try {
41
+ const parsed = JSON.parse(args);
42
+ switch (name) {
43
+ case 'read_file':
44
+ case 'write_file':
45
+ case 'edit_file':
46
+ return parsed.path ?? '';
47
+ case 'list_directory':
48
+ return parsed.path || '.';
49
+ case 'bash':
50
+ return parsed.command?.length > 60
51
+ ? parsed.command.slice(0, 60) + '…'
52
+ : (parsed.command ?? '');
53
+ case 'search_files':
54
+ return `"${parsed.pattern}"` + (parsed.include ? ` in ${parsed.include}` : '');
55
+ default:
56
+ return args.slice(0, 60);
57
+ }
58
+ }
59
+ catch {
60
+ return args.slice(0, 60);
61
+ }
62
+ }
63
+ export default class Session {
64
+ client;
65
+ opts;
66
+ bridge;
67
+ conversationUUID;
68
+ tools = getToolDefinitions();
69
+ mcp = new MCPManager();
70
+ cwd;
71
+ cumulativeTokens = { prompt: 0, completion: 0 };
72
+ messageRounds = 0;
73
+ filesRead = new Set();
74
+ filesWritten = new Set();
75
+ editHistory = [];
76
+ participants = [];
77
+ activeAgentUUID;
78
+ alwaysApprove = false;
79
+ isLocal;
80
+ localMessages = [];
81
+ localConversation = null;
82
+ constructor(opts) {
83
+ this.opts = opts;
84
+ this.bridge = opts.bridge;
85
+ this.cwd = opts.cwd;
86
+ this.conversationUUID = opts.conversationUUID || null;
87
+ this.activeAgentUUID = opts.agentUUID;
88
+ this.participants = [{ agent_uuid: opts.agentUUID, name: opts.agentName }];
89
+ this.isLocal = !(opts.cloud ?? false);
90
+ this.client = axios.create({
91
+ baseURL: opts.host || 'https://lemon.protokol.io',
92
+ timeout: 180_000,
93
+ headers: {
94
+ 'Authorization': `Bearer ${opts.token}`,
95
+ 'Content-Type': 'application/json',
96
+ 'X-Agent-Context': 'cli',
97
+ },
98
+ });
99
+ }
100
+ async start() {
101
+ await this.mcp.loadConfig(this.cwd);
102
+ if (this.mcp.serverCount > 0) {
103
+ const mcpTools = await this.mcp.discoverTools();
104
+ this.tools = [...this.tools, ...mcpTools];
105
+ this.bridge.showMCPStatus(this.mcp.serverNames);
106
+ }
107
+ if (this.isLocal) {
108
+ if (this.opts.conversationUUID) {
109
+ const loaded = loadConversation(this.opts.conversationUUID);
110
+ if (loaded) {
111
+ this.localConversation = loaded;
112
+ this.localMessages = loaded.messages.map(m => ({ ...m }));
113
+ this.replayToUI(loaded);
114
+ }
115
+ else {
116
+ this.bridge.showError(`Conversation ${this.opts.conversationUUID} not found.`);
117
+ this.startNewLocalConversation();
118
+ }
119
+ }
120
+ else {
121
+ this.startNewLocalConversation();
122
+ }
123
+ }
124
+ else if (!this.conversationUUID) {
125
+ await this.createConversation();
126
+ }
127
+ try {
128
+ if (this.opts.initialPrompt) {
129
+ await this.sendAndProcess(this.opts.initialPrompt);
130
+ }
131
+ await this.repl();
132
+ }
133
+ finally {
134
+ this.persistLocal();
135
+ this.mcp.close();
136
+ this.bridge.quit();
137
+ }
138
+ }
139
+ startNewLocalConversation() {
140
+ this.localConversation = createLocalConversation(this.activeAgentUUID, this.opts.agentName, this.cwd);
141
+ this.localMessages = [{ role: 'context', content: `Working directory: ${this.cwd}` }];
142
+ }
143
+ replayToUI(conv) {
144
+ const replay = [];
145
+ for (const msg of conv.messages) {
146
+ if (msg.role === 'user') {
147
+ replay.push({ kind: 'user', content: msg.content });
148
+ }
149
+ else if (msg.role === 'assistant' && msg.content.trim()) {
150
+ replay.push({
151
+ kind: 'assistant',
152
+ content: msg.content,
153
+ meta: { name: conv.meta.agentName },
154
+ });
155
+ }
156
+ }
157
+ if (replay.length > 0) {
158
+ this.bridge.replayMessages(replay);
159
+ this.bridge.showSystem(`Resumed conversation · ${conv.meta.messageCount} messages`);
160
+ }
161
+ }
162
+ persistLocal() {
163
+ if (!this.isLocal || !this.localConversation)
164
+ return;
165
+ this.localConversation.messages = this.localMessages.map(m => ({ ...m }));
166
+ saveConversation(this.localConversation);
167
+ }
168
+ async createConversation() {
169
+ const resp = await this.client.post('/luma/kortex/v1/conversations', {
170
+ title: `CLI session — ${new Date().toISOString().slice(0, 16)}`,
171
+ agent_uuid: this.opts.agentUUID,
172
+ });
173
+ this.conversationUUID = resp.data.uuid;
174
+ await this.injectSessionContext();
175
+ }
176
+ async injectSessionContext() {
177
+ try {
178
+ await this.client.post(`/luma/kortex/v1/conversations/${this.conversationUUID}/messages/inject`, { role: 'context', content: `Working directory: ${this.cwd}` });
179
+ }
180
+ catch {
181
+ // Non-fatal
182
+ }
183
+ }
184
+ async repl() {
185
+ while (true) {
186
+ this.bridge.setProcessing(false);
187
+ const input = await this.bridge.getInput();
188
+ if (input === null)
189
+ break;
190
+ const trimmed = input.trim();
191
+ if (!trimmed)
192
+ continue;
193
+ if (trimmed.startsWith('/')) {
194
+ const done = await this.handleCommand(trimmed);
195
+ if (done === 'quit')
196
+ break;
197
+ continue;
198
+ }
199
+ this.bridge.setProcessing(true);
200
+ try {
201
+ const targetUUID = this.resolveAgentMention(trimmed);
202
+ const content = this.stripMention(trimmed);
203
+ await this.sendAndProcess(content, undefined, targetUUID);
204
+ }
205
+ catch (err) {
206
+ const msg = err?.response?.data?.message || err?.message || String(err);
207
+ this.bridge.showError(msg);
208
+ }
209
+ }
210
+ }
211
+ resolveAgentMention(input) {
212
+ const match = input.match(/^@(\S+)\s/);
213
+ if (!match)
214
+ return this.activeAgentUUID;
215
+ const mention = match[1].toLowerCase();
216
+ const found = this.participants.find(p => p.name.toLowerCase() === mention);
217
+ return found ? found.agent_uuid : this.activeAgentUUID;
218
+ }
219
+ stripMention(input) {
220
+ return input.replace(/^@\S+\s/, '');
221
+ }
222
+ async handleCommand(input) {
223
+ const [cmd, ...args] = input.split(/\s+/);
224
+ switch (cmd) {
225
+ case '/quit':
226
+ case '/exit':
227
+ return 'quit';
228
+ case '/thoughts': {
229
+ const thinking = this.bridge.getLastThinking();
230
+ if (!thinking) {
231
+ this.bridge.showSystem('No thinking content from last response.');
232
+ }
233
+ else {
234
+ this.bridge.showSystem('┌─ Thinking ─────────────────────────\n' +
235
+ thinking.split('\n').map(l => '│ ' + l).join('\n') +
236
+ '\n└─────────────────────────────────────');
237
+ }
238
+ return true;
239
+ }
240
+ case '/clear':
241
+ if (this.isLocal) {
242
+ this.persistLocal();
243
+ this.startNewLocalConversation();
244
+ }
245
+ else {
246
+ await this.createConversation();
247
+ }
248
+ this.messageRounds = 0;
249
+ this.cumulativeTokens = { prompt: 0, completion: 0 };
250
+ this.bridge.clearMessages();
251
+ this.bridge.showSystem('New conversation started.');
252
+ return true;
253
+ case '/compact': {
254
+ this.persistLocal();
255
+ this.bridge.setProcessing(true);
256
+ this.bridge.showSystem('Compacting conversation…');
257
+ const summaryPrompt = 'Summarize our conversation so far for context continuity. ' +
258
+ 'Include: key decisions, code changes made, file paths discussed, current task status, ' +
259
+ 'and important constraints. Be concise — bullet points preferred.';
260
+ try {
261
+ let summary;
262
+ if (this.isLocal) {
263
+ const response = await this.client.post('/luma/kortex/v1/chat', {
264
+ agent_uuid: this.activeAgentUUID,
265
+ messages: [...this.localMessages, { role: 'user', content: summaryPrompt }],
266
+ }, { responseType: 'stream' });
267
+ summary = await this.silentStream(response.data);
268
+ this.localMessages = [
269
+ { role: 'context', content: `Working directory: ${this.cwd}` },
270
+ { role: 'assistant', content: summary },
271
+ ];
272
+ }
273
+ else {
274
+ const response = await this.client.post(`/luma/kortex/v1/conversations/${this.conversationUUID}/messages`, {
275
+ content: summaryPrompt,
276
+ agent_uuid: this.activeAgentUUID,
277
+ stream: true,
278
+ }, { responseType: 'stream' });
279
+ summary = await this.silentStream(response.data);
280
+ await this.createConversation();
281
+ try {
282
+ await this.client.post(`/luma/kortex/v1/conversations/${this.conversationUUID}/messages/inject`, { role: 'context', content: summary });
283
+ }
284
+ catch { /* non-fatal */ }
285
+ }
286
+ this.messageRounds = 0;
287
+ this.persistLocal();
288
+ this.bridge.clearMessages();
289
+ this.bridge.setContextUsage(0, CONTEXT_LIMIT);
290
+ this.bridge.showSystem('─── conversation compacted ───\n\n' + summary);
291
+ }
292
+ catch (err) {
293
+ this.bridge.showError(`Compact failed: ${err?.message || String(err)}`);
294
+ }
295
+ return true;
296
+ }
297
+ case '/undo':
298
+ this.undoLastEdit();
299
+ return true;
300
+ case '/cost':
301
+ this.bridge.showSystem(`Session Usage\n` +
302
+ ` Prompt: ${this.cumulativeTokens.prompt.toLocaleString()} tokens\n` +
303
+ ` Completion: ${this.cumulativeTokens.completion.toLocaleString()} tokens\n` +
304
+ ` Total: ${(this.cumulativeTokens.prompt + this.cumulativeTokens.completion).toLocaleString()} tokens\n` +
305
+ ` Rounds: ${this.messageRounds}`);
306
+ return true;
307
+ case '/files': {
308
+ const lines = ['Files'];
309
+ if (this.filesWritten.size > 0) {
310
+ for (const f of this.filesWritten)
311
+ lines.push(` ✎ ${f}`);
312
+ }
313
+ if (this.filesRead.size > 0) {
314
+ for (const f of this.filesRead)
315
+ lines.push(` ◇ ${f}`);
316
+ }
317
+ if (this.filesRead.size === 0 && this.filesWritten.size === 0) {
318
+ lines.push(' No files accessed this session.');
319
+ }
320
+ this.bridge.showSystem(lines.join('\n'));
321
+ return true;
322
+ }
323
+ case '/history':
324
+ this.bridge.showSystem(`Conversation\n` +
325
+ ` UUID: ${this.localConversation?.meta.uuid ?? this.conversationUUID ?? 'N/A'}\n` +
326
+ ` Messages: ${this.messageRounds * 2}\n` +
327
+ ` Rounds: ${this.messageRounds}`);
328
+ return true;
329
+ case '/conversations': {
330
+ if (!this.isLocal) {
331
+ this.bridge.showSystem('Conversation history is only available in local mode.');
332
+ return true;
333
+ }
334
+ this.persistLocal();
335
+ const convs = listConversations();
336
+ if (convs.length === 0) {
337
+ this.bridge.showSystem('No saved conversations.');
338
+ return true;
339
+ }
340
+ const options = convs.map(c => ({
341
+ uuid: c.uuid,
342
+ title: c.title,
343
+ agentName: c.agentName,
344
+ updatedAt: c.updatedAt,
345
+ messageCount: c.messageCount,
346
+ }));
347
+ const selected = await this.bridge.showConversationPicker(options);
348
+ if (selected) {
349
+ const loaded = loadConversation(selected.uuid);
350
+ if (loaded) {
351
+ this.localConversation = loaded;
352
+ this.localMessages = loaded.messages.map(m => ({ ...m }));
353
+ this.messageRounds = 0;
354
+ this.cumulativeTokens = { prompt: 0, completion: 0 };
355
+ this.bridge.clearMessages();
356
+ this.replayToUI(loaded);
357
+ }
358
+ else {
359
+ this.bridge.showError('Failed to load conversation.');
360
+ }
361
+ }
362
+ return true;
363
+ }
364
+ case '/agents':
365
+ await this.refreshParticipants();
366
+ this.bridge.showSystem('Participants\n' +
367
+ this.participants.map(p => ` ● ${p.name}${p.mode ? ` (${p.mode})` : ''}\n ${p.agent_uuid}`).join('\n'));
368
+ return true;
369
+ case '/add': {
370
+ const name = args.join(' ');
371
+ if (!name) {
372
+ this.bridge.showError('Usage: /add <agent-name-or-uuid>');
373
+ return true;
374
+ }
375
+ await this.addParticipant(name);
376
+ return true;
377
+ }
378
+ case '/remove': {
379
+ const name = args.join(' ');
380
+ if (!name) {
381
+ this.bridge.showError('Usage: /remove <agent-name>');
382
+ return true;
383
+ }
384
+ await this.removeParticipant(name);
385
+ return true;
386
+ }
387
+ case '/agent': {
388
+ const resp = await this.client.get('/luma/kortex/v1/agents', { params: { limit: 50 } }).catch(() => ({ data: { data: [] } }));
389
+ const userAgents = (resp.data?.data ?? []).map((a) => ({
390
+ uuid: a.uuid,
391
+ name: a.name,
392
+ description: a.description,
393
+ }));
394
+ const agents = [...PLATFORM_AGENTS, ...userAgents];
395
+ const selected = await this.bridge.showAgentPicker(agents);
396
+ if (selected) {
397
+ this.activeAgentUUID = selected.uuid;
398
+ this.bridge.setActiveAgent(selected.uuid, selected.name);
399
+ saveKortexConfig({ lastAgentUUID: selected.uuid });
400
+ this.bridge.showSystem(`Switched to ${selected.name}`);
401
+ }
402
+ return true;
403
+ }
404
+ case '/profile':
405
+ this.bridge.showSystem(`Profile: ${this.bridge.profileName}\n` +
406
+ ` Host: ${this.opts.host || 'https://lemon.protokol.io'}\n` +
407
+ ` Mode: ${this.isLocal ? 'local' : 'cloud'}`);
408
+ return true;
409
+ case '/help':
410
+ this.bridge.showSystem('Commands\n' +
411
+ SLASH_COMMANDS.map(c => ` ${c}`).join('\n') +
412
+ '\n\nShortcuts\n Tab Switch agent\n / Open command palette\n PgUp/PgDn Scroll messages');
413
+ return true;
414
+ default:
415
+ return false;
416
+ }
417
+ }
418
+ async askConsent(call) {
419
+ if (this.alwaysApprove || !isDangerous(call))
420
+ return true;
421
+ const summary = getToolSummary(call.function.name, call.function.arguments);
422
+ const answer = await this.bridge.requestConsent(call.function.name, summary);
423
+ if (answer === 'always')
424
+ this.alwaysApprove = true;
425
+ return answer !== 'no';
426
+ }
427
+ undoLastEdit() {
428
+ const last = this.editHistory.pop();
429
+ if (!last) {
430
+ this.bridge.showSystem('No edits to undo.');
431
+ return;
432
+ }
433
+ try {
434
+ writeFileSync(last.path, last.oldContent, 'utf-8');
435
+ this.bridge.showSystem(`Reverted ${last.path}`);
436
+ }
437
+ catch (err) {
438
+ this.bridge.showError(`Failed to undo: ${err.message}`);
439
+ }
440
+ }
441
+ async refreshParticipants() {
442
+ if (!this.conversationUUID)
443
+ return;
444
+ try {
445
+ const resp = await this.client.get(`/luma/kortex/v1/conversations/${this.conversationUUID}`);
446
+ if (resp.data.participants) {
447
+ this.participants = resp.data.participants;
448
+ }
449
+ }
450
+ catch { /* keep current list */ }
451
+ }
452
+ async addParticipant(nameOrUUID) {
453
+ let agentUUID = nameOrUUID;
454
+ let agentName = nameOrUUID;
455
+ const isUUID = /^[0-9a-f-]{36}$/i.test(nameOrUUID);
456
+ if (!isUUID) {
457
+ try {
458
+ const resp = await this.client.get('/luma/kortex/v1/agents', { params: { limit: 50 } });
459
+ const agents = resp.data?.data || [];
460
+ const matches = agents.filter((a) => a.name.toLowerCase().includes(nameOrUUID.toLowerCase()));
461
+ if (matches.length === 0) {
462
+ this.bridge.showError(`No agent found matching "${nameOrUUID}"`);
463
+ return;
464
+ }
465
+ agentUUID = matches[0].uuid;
466
+ agentName = matches[0].name;
467
+ }
468
+ catch (err) {
469
+ this.bridge.showError(`Failed to search agents: ${err.message}`);
470
+ return;
471
+ }
472
+ }
473
+ try {
474
+ await this.client.post(`/luma/kortex/v1/conversations/${this.conversationUUID}/participants`, { agent_uuid: agentUUID, name: agentName });
475
+ this.participants.push({ agent_uuid: agentUUID, name: agentName });
476
+ this.bridge.showSystem(`Added ${agentName} to conversation.`);
477
+ }
478
+ catch (err) {
479
+ this.bridge.showError(`Failed to add participant: ${err?.response?.data?.message || err.message}`);
480
+ }
481
+ }
482
+ async removeParticipant(name) {
483
+ const found = this.participants.find(p => p.name.toLowerCase() === name.toLowerCase());
484
+ if (!found) {
485
+ this.bridge.showError(`No participant named "${name}"`);
486
+ return;
487
+ }
488
+ if (found.agent_uuid === this.opts.agentUUID) {
489
+ this.bridge.showError('Cannot remove the primary agent.');
490
+ return;
491
+ }
492
+ try {
493
+ await this.client.delete(`/luma/kortex/v1/conversations/${this.conversationUUID}/participants/${found.agent_uuid}`);
494
+ this.participants = this.participants.filter(p => p.agent_uuid !== found.agent_uuid);
495
+ this.bridge.showSystem(`Removed ${found.name} from conversation.`);
496
+ }
497
+ catch (err) {
498
+ this.bridge.showError(`Failed to remove participant: ${err?.response?.data?.message || err.message}`);
499
+ }
500
+ }
501
+ async sendAndProcess(content, toolResults, agentUUID) {
502
+ this.messageRounds++;
503
+ if (content)
504
+ this.bridge.addUserMessage(content);
505
+ if (this.isLocal) {
506
+ if (content)
507
+ this.localMessages.push({ role: 'user', content });
508
+ const response = await this.client.post('/luma/kortex/v1/chat', { agent_uuid: agentUUID || this.activeAgentUUID, messages: this.localMessages, tools: this.tools }, { responseType: 'stream' });
509
+ const result = await this.processStream(response.data);
510
+ this.cumulativeTokens.prompt += result.tokenUsage.prompt_tokens;
511
+ this.cumulativeTokens.completion += result.tokenUsage.completion_tokens;
512
+ this.localMessages.push({
513
+ role: 'assistant',
514
+ content: result.content,
515
+ tool_calls: result.toolCalls.length ? result.toolCalls : undefined,
516
+ });
517
+ this.persistLocal();
518
+ if (result.toolCalls.length > 0) {
519
+ await this.executeToolLoop(result.toolCalls, result.tokenUsage, 1, agentUUID);
520
+ }
521
+ return;
522
+ }
523
+ const body = {
524
+ content: toolResults ? '' : content,
525
+ agent_uuid: agentUUID || this.activeAgentUUID,
526
+ stream: true,
527
+ tools: this.tools,
528
+ };
529
+ if (toolResults) {
530
+ body.tool_results = toolResults;
531
+ body.content = '';
532
+ }
533
+ const response = await this.client.post(`/luma/kortex/v1/conversations/${this.conversationUUID}/messages`, body, { responseType: 'stream' });
534
+ const result = await this.processStream(response.data);
535
+ this.cumulativeTokens.prompt += result.tokenUsage.prompt_tokens;
536
+ this.cumulativeTokens.completion += result.tokenUsage.completion_tokens;
537
+ if (result.toolCalls.length > 0) {
538
+ await this.executeToolLoop(result.toolCalls, result.tokenUsage, 1, agentUUID);
539
+ }
540
+ }
541
+ async executeToolLoop(toolCalls, cumulativeUsage, round, agentUUID) {
542
+ if (round > MAX_TOOL_ROUNDS) {
543
+ this.bridge.showError(`Tool loop limit (${MAX_TOOL_ROUNDS}) reached. Stopping.`);
544
+ return;
545
+ }
546
+ const results = [];
547
+ for (const call of toolCalls) {
548
+ const summary = getToolSummary(call.function.name, call.function.arguments);
549
+ this.bridge.addToolCall(call.function.name, summary);
550
+ const approved = await this.askConsent(call);
551
+ if (!approved) {
552
+ this.bridge.addToolResult(call.function.name, false, 'Denied by user.');
553
+ results.push({
554
+ tool_call_id: call.id,
555
+ name: call.function.name,
556
+ content: 'Error: User denied permission to run this tool.',
557
+ });
558
+ continue;
559
+ }
560
+ this.trackFileAccess(call);
561
+ let result;
562
+ if (this.mcp.canHandle(call.function.name)) {
563
+ let args;
564
+ try {
565
+ args = JSON.parse(call.function.arguments);
566
+ }
567
+ catch {
568
+ args = {};
569
+ }
570
+ result = await this.mcp.executeTool(call.id, call.function.name, args);
571
+ }
572
+ else {
573
+ this.recordEditForUndo(call);
574
+ result = executeTool(this.cwd, call);
575
+ }
576
+ const success = !result.content.startsWith('Error:');
577
+ this.bridge.addToolResult(call.function.name, success, success ? undefined : result.content);
578
+ results.push(result);
579
+ }
580
+ if (this.isLocal) {
581
+ for (const r of results) {
582
+ this.localMessages.push({ role: 'tool', content: r.content, tool_call_id: r.tool_call_id });
583
+ }
584
+ const response = await this.client.post('/luma/kortex/v1/chat', { agent_uuid: agentUUID || this.activeAgentUUID, messages: this.localMessages, tools: this.tools }, { responseType: 'stream' });
585
+ const result = await this.processStream(response.data);
586
+ cumulativeUsage.prompt_tokens += result.tokenUsage.prompt_tokens;
587
+ cumulativeUsage.completion_tokens += result.tokenUsage.completion_tokens;
588
+ this.cumulativeTokens.prompt += result.tokenUsage.prompt_tokens;
589
+ this.cumulativeTokens.completion += result.tokenUsage.completion_tokens;
590
+ this.localMessages.push({
591
+ role: 'assistant',
592
+ content: result.content,
593
+ tool_calls: result.toolCalls.length ? result.toolCalls : undefined,
594
+ });
595
+ this.persistLocal();
596
+ if (result.toolCalls.length > 0) {
597
+ await this.executeToolLoop(result.toolCalls, cumulativeUsage, round + 1, agentUUID);
598
+ }
599
+ return;
600
+ }
601
+ const response = await this.client.post(`/luma/kortex/v1/conversations/${this.conversationUUID}/messages`, {
602
+ content: '',
603
+ agent_uuid: agentUUID || this.activeAgentUUID,
604
+ stream: true,
605
+ tools: this.tools,
606
+ tool_results: results,
607
+ }, { responseType: 'stream' });
608
+ const result = await this.processStream(response.data);
609
+ cumulativeUsage.prompt_tokens += result.tokenUsage.prompt_tokens;
610
+ cumulativeUsage.completion_tokens += result.tokenUsage.completion_tokens;
611
+ this.cumulativeTokens.prompt += result.tokenUsage.prompt_tokens;
612
+ this.cumulativeTokens.completion += result.tokenUsage.completion_tokens;
613
+ if (result.toolCalls.length > 0) {
614
+ await this.executeToolLoop(result.toolCalls, cumulativeUsage, round + 1, agentUUID);
615
+ }
616
+ }
617
+ trackFileAccess(call) {
618
+ try {
619
+ const args = JSON.parse(call.function.arguments);
620
+ const name = call.function.name;
621
+ if (name === 'read_file' && args.path) {
622
+ this.filesRead.add(args.path);
623
+ }
624
+ else if ((name === 'write_file' || name === 'edit_file') && args.path) {
625
+ this.filesWritten.add(args.path);
626
+ }
627
+ }
628
+ catch { /* ignore */ }
629
+ }
630
+ recordEditForUndo(call) {
631
+ try {
632
+ const args = JSON.parse(call.function.arguments);
633
+ const name = call.function.name;
634
+ if ((name === 'write_file' || name === 'edit_file') && args.path) {
635
+ const fullPath = resolve(this.cwd, args.path);
636
+ if (existsSync(fullPath)) {
637
+ this.editHistory.push({ path: fullPath, oldContent: readFileSync(fullPath, 'utf-8') });
638
+ }
639
+ }
640
+ }
641
+ catch { /* ignore */ }
642
+ }
643
+ async processStream(stream) {
644
+ const toolCalls = [];
645
+ const tokenUsage = { prompt_tokens: 0, completion_tokens: 0 };
646
+ let fullContent = '';
647
+ let wasThinking = false;
648
+ this.bridge.startStream();
649
+ for await (const event of this.parseSSE(stream)) {
650
+ switch (event.event) {
651
+ case 'content_delta': {
652
+ const { delta } = JSON.parse(event.data);
653
+ if (delta) {
654
+ if (wasThinking) {
655
+ this.bridge.finalizeThinking();
656
+ wasThinking = false;
657
+ }
658
+ fullContent += delta;
659
+ this.bridge.appendDelta(delta);
660
+ }
661
+ break;
662
+ }
663
+ case 'thinking_delta': {
664
+ const { delta } = JSON.parse(event.data);
665
+ if (delta) {
666
+ if (!wasThinking) {
667
+ wasThinking = true;
668
+ this.bridge.startThinking();
669
+ }
670
+ this.bridge.appendThinkingDelta(delta);
671
+ }
672
+ break;
673
+ }
674
+ case 'message_start': {
675
+ const data = JSON.parse(event.data);
676
+ if (data.agent_name) {
677
+ this.bridge.setStreamAgentLabel(data.agent_name);
678
+ }
679
+ break;
680
+ }
681
+ case 'message_complete': {
682
+ if (wasThinking) {
683
+ this.bridge.finalizeThinking();
684
+ wasThinking = false;
685
+ }
686
+ const msg = JSON.parse(event.data);
687
+ if (msg.agent_name)
688
+ this.bridge.setStreamAgentLabel(msg.agent_name);
689
+ if (msg.tool_calls?.length)
690
+ toolCalls.push(...msg.tool_calls);
691
+ if (msg.token_usage) {
692
+ tokenUsage.prompt_tokens += msg.token_usage.prompt_tokens || 0;
693
+ tokenUsage.completion_tokens += msg.token_usage.completion_tokens || 0;
694
+ }
695
+ break;
696
+ }
697
+ case 'error': {
698
+ const { error } = JSON.parse(event.data);
699
+ this.bridge.showError(error || 'Unknown streaming error');
700
+ break;
701
+ }
702
+ }
703
+ }
704
+ this.bridge.finalizeStream(fullContent);
705
+ this.bridge.setTokenUsage(this.cumulativeTokens.prompt + tokenUsage.prompt_tokens, this.cumulativeTokens.completion + tokenUsage.completion_tokens);
706
+ if (tokenUsage.prompt_tokens > 0) {
707
+ this.bridge.setContextUsage(tokenUsage.prompt_tokens, CONTEXT_LIMIT);
708
+ }
709
+ return { content: fullContent, toolCalls, tokenUsage };
710
+ }
711
+ async silentStream(stream) {
712
+ let content = '';
713
+ for await (const event of this.parseSSE(stream)) {
714
+ if (event.event === 'content_delta') {
715
+ try {
716
+ const { delta } = JSON.parse(event.data);
717
+ if (delta)
718
+ content += delta;
719
+ }
720
+ catch { /* ignore */ }
721
+ }
722
+ }
723
+ return content;
724
+ }
725
+ async *parseSSE(stream) {
726
+ let buffer = '';
727
+ for await (const chunk of stream) {
728
+ buffer += chunk.toString();
729
+ const parts = buffer.split('\n\n');
730
+ buffer = parts.pop() || '';
731
+ for (const part of parts) {
732
+ const lines = part.split('\n');
733
+ let event = '';
734
+ let data = '';
735
+ for (const line of lines) {
736
+ if (line.startsWith('event: '))
737
+ event = line.slice(7);
738
+ else if (line.startsWith('data: '))
739
+ data = line.slice(6);
740
+ }
741
+ if (event && data)
742
+ yield { event, data };
743
+ }
744
+ }
745
+ if (buffer.trim()) {
746
+ const lines = buffer.split('\n');
747
+ let event = '';
748
+ let data = '';
749
+ for (const line of lines) {
750
+ if (line.startsWith('event: '))
751
+ event = line.slice(7);
752
+ else if (line.startsWith('data: '))
753
+ data = line.slice(6);
754
+ }
755
+ if (event && data)
756
+ yield { event, data };
757
+ }
758
+ }
759
+ }