@ptkl/toolkit 0.11.0 → 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.
- package/README.md +101 -0
- package/dist/bin/toolkit.js +0 -0
- package/dist/commands/forge.js +582 -28
- package/dist/commands/index.js +4 -0
- package/dist/commands/kortex.js +106 -0
- package/dist/commands/logs.js +109 -0
- package/dist/lib/kortex/bridge.js +113 -0
- package/dist/lib/kortex/config.js +21 -0
- package/dist/lib/kortex/conversations.js +84 -0
- package/dist/lib/kortex/mcp.js +193 -0
- package/dist/lib/kortex/session.js +759 -0
- package/dist/lib/kortex/tools.js +406 -0
- package/dist/lib/kortex/ui/App.js +455 -0
- package/dist/lib/kortex/ui/SelectAgent.js +23 -0
- package/package.json +11 -2
package/dist/commands/index.js
CHANGED
|
@@ -11,6 +11,8 @@ import component from "./component.js";
|
|
|
11
11
|
import workflow from "./workflow.js";
|
|
12
12
|
import generateTypes from "./generate-types.js";
|
|
13
13
|
import validateIDL from "./validate-idl.js";
|
|
14
|
+
import kortex from "./kortex.js";
|
|
15
|
+
import logs from "./logs.js";
|
|
14
16
|
export const commands = [
|
|
15
17
|
profile.register(),
|
|
16
18
|
users.register(),
|
|
@@ -22,6 +24,8 @@ export const commands = [
|
|
|
22
24
|
workflow.register(),
|
|
23
25
|
generateTypes.register(),
|
|
24
26
|
validateIDL.register(),
|
|
27
|
+
logs.register(),
|
|
28
|
+
kortex.register(),
|
|
25
29
|
new Command('init')
|
|
26
30
|
.description("Init protokol toolkit")
|
|
27
31
|
.action(Util.init)
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { Command } from "commander";
|
|
2
|
+
import axios from "axios";
|
|
3
|
+
import util from "../lib/util.js";
|
|
4
|
+
import { UIBridge } from "../lib/kortex/bridge.js";
|
|
5
|
+
import Session from "../lib/kortex/session.js";
|
|
6
|
+
import { loadKortexConfig } from "../lib/kortex/config.js";
|
|
7
|
+
const PLATFORM_AGENT_NAMES = {
|
|
8
|
+
'protokol-bot': 'ProtokolBot',
|
|
9
|
+
'proka': 'Proka',
|
|
10
|
+
'prota': 'Prota',
|
|
11
|
+
};
|
|
12
|
+
class KortexCommand {
|
|
13
|
+
register() {
|
|
14
|
+
return new Command('kortex')
|
|
15
|
+
.description('Interactive AI coding assistant powered by Kortex')
|
|
16
|
+
.argument('[prompt...]', 'Optional initial prompt')
|
|
17
|
+
.option('-a, --agent <uuid>', 'Agent UUID to use')
|
|
18
|
+
.option('-c, --conversation <uuid>', 'Resume a conversation (local or cloud)')
|
|
19
|
+
.option('--cloud', 'Save conversation on the platform (default: local only)')
|
|
20
|
+
.action(this.run);
|
|
21
|
+
}
|
|
22
|
+
async run(promptParts, opts) {
|
|
23
|
+
let profile;
|
|
24
|
+
try {
|
|
25
|
+
profile = util.getCurrentProfile();
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
let profiles = [];
|
|
29
|
+
try {
|
|
30
|
+
profiles = util.getProfiles() ?? [];
|
|
31
|
+
}
|
|
32
|
+
catch { /* no profiles file */ }
|
|
33
|
+
if (profiles.length === 0) {
|
|
34
|
+
console.error('No profiles found. Run `ptkl init` and then `ptkl profile new` to create one.');
|
|
35
|
+
process.exit(1);
|
|
36
|
+
}
|
|
37
|
+
console.error('No active profile. Available profiles:');
|
|
38
|
+
for (const p of profiles) {
|
|
39
|
+
console.error(` ${p.name}`);
|
|
40
|
+
}
|
|
41
|
+
console.error(`\nRun \`ptkl profile use <name>\` or use \`ptkl --profile <name> kortex\``);
|
|
42
|
+
process.exit(1);
|
|
43
|
+
}
|
|
44
|
+
const client = axios.create({
|
|
45
|
+
baseURL: profile.host || 'https://lemon.protokol.io',
|
|
46
|
+
timeout: 30_000,
|
|
47
|
+
headers: {
|
|
48
|
+
'Authorization': `Bearer ${profile.token}`,
|
|
49
|
+
'Content-Type': 'application/json',
|
|
50
|
+
},
|
|
51
|
+
});
|
|
52
|
+
// Resolve agent: CLI flag → persisted last used → ProtokolBot
|
|
53
|
+
const config = loadKortexConfig();
|
|
54
|
+
const agentUUID = opts.agent ?? config.lastAgentUUID ?? 'protokol-bot';
|
|
55
|
+
let agentName = PLATFORM_AGENT_NAMES[agentUUID] ?? 'Kortex';
|
|
56
|
+
if (!PLATFORM_AGENT_NAMES[agentUUID]) {
|
|
57
|
+
try {
|
|
58
|
+
const resp = await client.get(`/luma/kortex/v1/agents/${agentUUID}`);
|
|
59
|
+
agentName = resp.data?.name ?? agentName;
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
// Unknown agent, fall back to ProtokolBot
|
|
63
|
+
agentName = 'ProtokolBot';
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
const isLocal = !opts.cloud;
|
|
67
|
+
const initialPrompt = promptParts.length > 0 ? promptParts.join(' ') : undefined;
|
|
68
|
+
const bridge = new UIBridge({
|
|
69
|
+
agentUUID,
|
|
70
|
+
agentName,
|
|
71
|
+
cwd: process.cwd(),
|
|
72
|
+
isLocal,
|
|
73
|
+
profileName: profile.name,
|
|
74
|
+
});
|
|
75
|
+
// Force color support before marked-terminal's bundled chalk initializes
|
|
76
|
+
process.env.FORCE_COLOR = '3';
|
|
77
|
+
// Enter alternate screen buffer (fullscreen takeover)
|
|
78
|
+
process.stdout.write('\x1b[?1049h\x1b[2J\x1b[H');
|
|
79
|
+
const exitAltScreen = () => { process.stdout.write('\x1b[?1049l'); };
|
|
80
|
+
process.once('SIGTERM', () => { exitAltScreen(); process.exit(0); });
|
|
81
|
+
const [{ render }, React, { App }] = await Promise.all([
|
|
82
|
+
import('ink'),
|
|
83
|
+
import('react'),
|
|
84
|
+
import('../lib/kortex/ui/App.js'),
|
|
85
|
+
]);
|
|
86
|
+
const { waitUntilExit } = render(React.createElement(App, { bridge }));
|
|
87
|
+
const session = new Session({
|
|
88
|
+
token: profile.token,
|
|
89
|
+
host: profile.host,
|
|
90
|
+
agentUUID,
|
|
91
|
+
agentName,
|
|
92
|
+
cwd: process.cwd(),
|
|
93
|
+
conversationUUID: opts.conversation,
|
|
94
|
+
initialPrompt,
|
|
95
|
+
cloud: !!opts.cloud,
|
|
96
|
+
bridge,
|
|
97
|
+
});
|
|
98
|
+
session.start().catch((err) => {
|
|
99
|
+
bridge.showError(err?.message || String(err));
|
|
100
|
+
bridge.quit();
|
|
101
|
+
});
|
|
102
|
+
await waitUntilExit();
|
|
103
|
+
exitAltScreen();
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
export default new KortexCommand();
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import axios from "axios";
|
|
2
|
+
import { Command } from "commander";
|
|
3
|
+
import util from "../lib/util.js";
|
|
4
|
+
class LogsCommand {
|
|
5
|
+
register() {
|
|
6
|
+
return new Command("logs")
|
|
7
|
+
.description("Query or tail Timber logs for the current project")
|
|
8
|
+
.option("--source <source>", "Filter by source: system | user")
|
|
9
|
+
.option("--level <level>", "Filter by level: debug | info | warn | error")
|
|
10
|
+
.option("--action <action>", "Filter by action")
|
|
11
|
+
.option("--resource-type <type>", "Filter by resource type")
|
|
12
|
+
.option("-s, --search <text>", "Search message, actor, or resource")
|
|
13
|
+
.option("-l, --limit <limit>", "Number of logs to fetch", "50")
|
|
14
|
+
.option("-t, --tail", "Poll Timber and print new logs")
|
|
15
|
+
.option("--interval <seconds>", "Tail polling interval", "3")
|
|
16
|
+
.option("--json", "Print newline-delimited JSON")
|
|
17
|
+
.action(this.run);
|
|
18
|
+
}
|
|
19
|
+
async run(opts) {
|
|
20
|
+
const profile = util.getCurrentProfile();
|
|
21
|
+
const client = LogsCommand.client(profile);
|
|
22
|
+
const seen = new Set();
|
|
23
|
+
const fetch = async () => {
|
|
24
|
+
const { data } = await client.get("/v1/timber/logs", {
|
|
25
|
+
params: LogsCommand.params(opts),
|
|
26
|
+
});
|
|
27
|
+
return data.data || [];
|
|
28
|
+
};
|
|
29
|
+
const print = (events) => {
|
|
30
|
+
events.reverse().forEach((event) => {
|
|
31
|
+
const key = event.id || `${event.timestamp}:${event.service}:${event.resource_id}:${event.message}`;
|
|
32
|
+
if (seen.has(key)) {
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
seen.add(key);
|
|
36
|
+
if (opts.json) {
|
|
37
|
+
console.log(JSON.stringify(event));
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
console.log(LogsCommand.format(event));
|
|
41
|
+
});
|
|
42
|
+
};
|
|
43
|
+
print(await fetch());
|
|
44
|
+
if (!opts.tail) {
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
const interval = Math.max(1, Number(opts.interval || 3)) * 1000;
|
|
48
|
+
setInterval(async () => {
|
|
49
|
+
try {
|
|
50
|
+
print(await fetch());
|
|
51
|
+
}
|
|
52
|
+
catch (err) {
|
|
53
|
+
console.error(`Timber tail failed: ${err.message}`);
|
|
54
|
+
}
|
|
55
|
+
}, interval);
|
|
56
|
+
}
|
|
57
|
+
static client(profile) {
|
|
58
|
+
return axios.create({
|
|
59
|
+
baseURL: `${profile.host.replace(/\/$/, "")}/luma/integrations`,
|
|
60
|
+
timeout: 30000,
|
|
61
|
+
headers: {
|
|
62
|
+
Authorization: `Bearer ${profile.token}`,
|
|
63
|
+
"X-Project-Uuid": profile.project,
|
|
64
|
+
},
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
static params(opts) {
|
|
68
|
+
const params = {
|
|
69
|
+
limit: Number(opts.limit || 50),
|
|
70
|
+
};
|
|
71
|
+
if (opts.source)
|
|
72
|
+
params.source = opts.source;
|
|
73
|
+
if (opts.level)
|
|
74
|
+
params.level = opts.level;
|
|
75
|
+
if (opts.action)
|
|
76
|
+
params.action = opts.action;
|
|
77
|
+
if (opts.resourceType)
|
|
78
|
+
params.resource_type = opts.resourceType;
|
|
79
|
+
if (opts.search)
|
|
80
|
+
params.search = opts.search;
|
|
81
|
+
return params;
|
|
82
|
+
}
|
|
83
|
+
static format(event) {
|
|
84
|
+
const time = event.timestamp ? new Date(event.timestamp).toISOString() : "-";
|
|
85
|
+
const level = (event.level || "info").toUpperCase().padEnd(5);
|
|
86
|
+
const service = (event.service || "-").padEnd(12);
|
|
87
|
+
const action = event.action || "-";
|
|
88
|
+
const resource = event.resource_name || event.resource_id || event.resource_type || "-";
|
|
89
|
+
const message = event.message || `${action} ${resource}`;
|
|
90
|
+
const actor = event.actor
|
|
91
|
+
? event.actor.name || event.actor.id || "-"
|
|
92
|
+
: "-";
|
|
93
|
+
let line = `${time} ${level} ${service} ${message}`;
|
|
94
|
+
if (action !== "-")
|
|
95
|
+
line += ` action=${action}`;
|
|
96
|
+
if (resource !== "-")
|
|
97
|
+
line += ` resource=${resource}`;
|
|
98
|
+
if (actor !== "-")
|
|
99
|
+
line += ` actor=${actor}`;
|
|
100
|
+
if (event.attributes && Object.keys(event.attributes).length) {
|
|
101
|
+
const attrs = Object.entries(event.attributes)
|
|
102
|
+
.map(([k, v]) => `${k}=${typeof v === "object" ? JSON.stringify(v) : v}`)
|
|
103
|
+
.join(" ");
|
|
104
|
+
line += ` ${attrs}`;
|
|
105
|
+
}
|
|
106
|
+
return line;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
export default new LogsCommand();
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { EventEmitter } from 'node:events';
|
|
2
|
+
export class UIBridge extends EventEmitter {
|
|
3
|
+
cwd;
|
|
4
|
+
isLocal;
|
|
5
|
+
profileName;
|
|
6
|
+
_inputResolve = null;
|
|
7
|
+
_consentResolve = null;
|
|
8
|
+
_agentPickerResolve = null;
|
|
9
|
+
_convPickerResolve = null;
|
|
10
|
+
_lastThinkingContent = '';
|
|
11
|
+
_thinkingStart = 0;
|
|
12
|
+
agentName;
|
|
13
|
+
agentUUID;
|
|
14
|
+
constructor(opts) {
|
|
15
|
+
super();
|
|
16
|
+
this.agentUUID = opts.agentUUID;
|
|
17
|
+
this.agentName = opts.agentName;
|
|
18
|
+
this.cwd = opts.cwd;
|
|
19
|
+
this.isLocal = opts.isLocal;
|
|
20
|
+
this.profileName = opts.profileName;
|
|
21
|
+
}
|
|
22
|
+
// --- Input (session awaits, Ink resolves) ---
|
|
23
|
+
getInput() {
|
|
24
|
+
this.emit('input_ready');
|
|
25
|
+
return new Promise((resolve) => {
|
|
26
|
+
this._inputResolve = resolve;
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
submitInput(value) {
|
|
30
|
+
const resolve = this._inputResolve;
|
|
31
|
+
this._inputResolve = null;
|
|
32
|
+
resolve?.(value);
|
|
33
|
+
}
|
|
34
|
+
// --- Consent (session awaits, Ink resolves) ---
|
|
35
|
+
requestConsent(name, summary) {
|
|
36
|
+
this.emit('consent_request', { name, summary });
|
|
37
|
+
return new Promise((resolve) => {
|
|
38
|
+
this._consentResolve = resolve;
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
resolveConsent(answer) {
|
|
42
|
+
const resolve = this._consentResolve;
|
|
43
|
+
this._consentResolve = null;
|
|
44
|
+
resolve?.(answer);
|
|
45
|
+
}
|
|
46
|
+
// --- Session → UI: stream ---
|
|
47
|
+
startStream() { this.emit('stream_start'); }
|
|
48
|
+
appendDelta(text) { this.emit('delta', text); }
|
|
49
|
+
finalizeStream(content) { this.emit('stream_end', content); }
|
|
50
|
+
setStreamAgentLabel(name) { this.emit('agent_label', name); }
|
|
51
|
+
// --- Session → UI: thinking ---
|
|
52
|
+
startThinking() {
|
|
53
|
+
this._thinkingStart = Date.now();
|
|
54
|
+
this._lastThinkingContent = '';
|
|
55
|
+
this.emit('thinking_start');
|
|
56
|
+
}
|
|
57
|
+
appendThinkingDelta(text) {
|
|
58
|
+
this._lastThinkingContent += text;
|
|
59
|
+
}
|
|
60
|
+
finalizeThinking() {
|
|
61
|
+
const elapsed = ((Date.now() - this._thinkingStart) / 1000).toFixed(1);
|
|
62
|
+
this.emit('thinking_end', elapsed);
|
|
63
|
+
}
|
|
64
|
+
getLastThinking() { return this._lastThinkingContent; }
|
|
65
|
+
// --- Session → UI: messages ---
|
|
66
|
+
addUserMessage(content) { this.emit('user_message', content); }
|
|
67
|
+
addToolCall(name, summary) { this.emit('tool_call', { name, summary }); }
|
|
68
|
+
addToolResult(name, success, error) {
|
|
69
|
+
this.emit('tool_result', { name, success, error });
|
|
70
|
+
}
|
|
71
|
+
setTokenUsage(prompt, completion) {
|
|
72
|
+
this.emit('token_usage', { prompt, completion });
|
|
73
|
+
}
|
|
74
|
+
showError(message) { this.emit('error', message); }
|
|
75
|
+
showSystem(content) { this.emit('system', content); }
|
|
76
|
+
showMCPStatus(servers) { this.emit('mcp_status', servers); }
|
|
77
|
+
setProcessing(active) { this.emit('processing', active); }
|
|
78
|
+
setContextUsage(used, limit) { this.emit('context_usage', { used, limit }); }
|
|
79
|
+
clearMessages() { this.emit('clear'); }
|
|
80
|
+
// --- Agent picker (session awaits, Ink resolves) ---
|
|
81
|
+
showAgentPicker(agents) {
|
|
82
|
+
this.emit('show_agent_picker', agents);
|
|
83
|
+
return new Promise((resolve) => {
|
|
84
|
+
this._agentPickerResolve = resolve;
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
resolveAgentPicker(agent) {
|
|
88
|
+
const resolve = this._agentPickerResolve;
|
|
89
|
+
this._agentPickerResolve = null;
|
|
90
|
+
resolve?.(agent);
|
|
91
|
+
}
|
|
92
|
+
setActiveAgent(uuid, name) {
|
|
93
|
+
this.agentUUID = uuid;
|
|
94
|
+
this.agentName = name;
|
|
95
|
+
this.emit('active_agent_changed', { uuid, name });
|
|
96
|
+
}
|
|
97
|
+
// --- Conversation picker (session awaits, Ink resolves) ---
|
|
98
|
+
showConversationPicker(conversations) {
|
|
99
|
+
this.emit('show_conv_picker', conversations);
|
|
100
|
+
return new Promise((resolve) => {
|
|
101
|
+
this._convPickerResolve = resolve;
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
resolveConversationPicker(conv) {
|
|
105
|
+
const resolve = this._convPickerResolve;
|
|
106
|
+
this._convPickerResolve = null;
|
|
107
|
+
resolve?.(conv);
|
|
108
|
+
}
|
|
109
|
+
replayMessages(messages) {
|
|
110
|
+
this.emit('replay_messages', messages);
|
|
111
|
+
}
|
|
112
|
+
quit() { this.emit('quit'); }
|
|
113
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
const CONFIG_DIR = join(process.env.HOME ?? '~', '.ptkl');
|
|
4
|
+
const CONFIG_FILE = join(CONFIG_DIR, 'kortex.json');
|
|
5
|
+
export function loadKortexConfig() {
|
|
6
|
+
try {
|
|
7
|
+
if (existsSync(CONFIG_FILE)) {
|
|
8
|
+
return JSON.parse(readFileSync(CONFIG_FILE, 'utf-8'));
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
catch { /* ignore malformed file */ }
|
|
12
|
+
return {};
|
|
13
|
+
}
|
|
14
|
+
export function saveKortexConfig(config) {
|
|
15
|
+
try {
|
|
16
|
+
if (!existsSync(CONFIG_DIR))
|
|
17
|
+
mkdirSync(CONFIG_DIR, { recursive: true });
|
|
18
|
+
writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2));
|
|
19
|
+
}
|
|
20
|
+
catch { /* ignore write errors */ }
|
|
21
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { readFileSync, writeFileSync, mkdirSync, existsSync, readdirSync, unlinkSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
const CONV_DIR = join(process.env.HOME ?? '~', '.ptkl', 'kortex', 'conversations');
|
|
5
|
+
function ensureDir() {
|
|
6
|
+
if (!existsSync(CONV_DIR))
|
|
7
|
+
mkdirSync(CONV_DIR, { recursive: true });
|
|
8
|
+
}
|
|
9
|
+
function filePath(uuid) {
|
|
10
|
+
return join(CONV_DIR, `${uuid}.json`);
|
|
11
|
+
}
|
|
12
|
+
function deriveTitle(messages) {
|
|
13
|
+
const first = messages.find(m => m.role === 'user');
|
|
14
|
+
if (!first)
|
|
15
|
+
return 'New conversation';
|
|
16
|
+
const text = first.content.trim();
|
|
17
|
+
return text.length > 60 ? text.slice(0, 57) + '...' : text;
|
|
18
|
+
}
|
|
19
|
+
export function createConversation(agentUUID, agentName, cwd) {
|
|
20
|
+
const now = new Date().toISOString();
|
|
21
|
+
return {
|
|
22
|
+
meta: {
|
|
23
|
+
uuid: randomUUID(),
|
|
24
|
+
title: 'New conversation',
|
|
25
|
+
agentUUID,
|
|
26
|
+
agentName,
|
|
27
|
+
cwd,
|
|
28
|
+
createdAt: now,
|
|
29
|
+
updatedAt: now,
|
|
30
|
+
messageCount: 0,
|
|
31
|
+
},
|
|
32
|
+
messages: [],
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
export function saveConversation(conv) {
|
|
36
|
+
try {
|
|
37
|
+
ensureDir();
|
|
38
|
+
conv.meta.updatedAt = new Date().toISOString();
|
|
39
|
+
conv.meta.messageCount = conv.messages.filter(m => m.role === 'user' || m.role === 'assistant').length;
|
|
40
|
+
conv.meta.title = deriveTitle(conv.messages);
|
|
41
|
+
writeFileSync(filePath(conv.meta.uuid), JSON.stringify(conv, null, 2));
|
|
42
|
+
}
|
|
43
|
+
catch { /* ignore write errors */ }
|
|
44
|
+
}
|
|
45
|
+
export function loadConversation(uuid) {
|
|
46
|
+
try {
|
|
47
|
+
const data = readFileSync(filePath(uuid), 'utf-8');
|
|
48
|
+
return JSON.parse(data);
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
export function listConversations() {
|
|
55
|
+
try {
|
|
56
|
+
ensureDir();
|
|
57
|
+
const files = readdirSync(CONV_DIR).filter(f => f.endsWith('.json'));
|
|
58
|
+
const metas = [];
|
|
59
|
+
for (const file of files) {
|
|
60
|
+
try {
|
|
61
|
+
const data = JSON.parse(readFileSync(join(CONV_DIR, file), 'utf-8'));
|
|
62
|
+
if (data.meta)
|
|
63
|
+
metas.push(data.meta);
|
|
64
|
+
}
|
|
65
|
+
catch { /* skip corrupt files */ }
|
|
66
|
+
}
|
|
67
|
+
metas.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
|
|
68
|
+
return metas;
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
return [];
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
export function deleteConversation(uuid) {
|
|
75
|
+
try {
|
|
76
|
+
const path = filePath(uuid);
|
|
77
|
+
if (existsSync(path)) {
|
|
78
|
+
unlinkSync(path);
|
|
79
|
+
return true;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
catch { /* ignore */ }
|
|
83
|
+
return false;
|
|
84
|
+
}
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { readFileSync, existsSync } from 'node:fs';
|
|
3
|
+
import { resolve } from 'node:path';
|
|
4
|
+
class MCPConnection {
|
|
5
|
+
process;
|
|
6
|
+
buffer = '';
|
|
7
|
+
nextId = 1;
|
|
8
|
+
pending = new Map();
|
|
9
|
+
serverName;
|
|
10
|
+
constructor(serverName, config) {
|
|
11
|
+
this.serverName = serverName;
|
|
12
|
+
const env = { ...process.env, ...config.env };
|
|
13
|
+
this.process = spawn(config.command, config.args || [], {
|
|
14
|
+
env,
|
|
15
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
16
|
+
});
|
|
17
|
+
this.process.stdout.on('data', (chunk) => {
|
|
18
|
+
this.buffer += chunk.toString();
|
|
19
|
+
this.processBuffer();
|
|
20
|
+
});
|
|
21
|
+
this.process.stderr.on('data', (chunk) => {
|
|
22
|
+
// MCP servers may log to stderr — ignore
|
|
23
|
+
});
|
|
24
|
+
this.process.on('error', (err) => {
|
|
25
|
+
for (const [, p] of this.pending) {
|
|
26
|
+
p.reject(new Error(`MCP server "${serverName}" process error: ${err.message}`));
|
|
27
|
+
}
|
|
28
|
+
this.pending.clear();
|
|
29
|
+
});
|
|
30
|
+
this.process.on('exit', () => {
|
|
31
|
+
for (const [, p] of this.pending) {
|
|
32
|
+
p.reject(new Error(`MCP server "${serverName}" exited unexpectedly`));
|
|
33
|
+
}
|
|
34
|
+
this.pending.clear();
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
processBuffer() {
|
|
38
|
+
const lines = this.buffer.split('\n');
|
|
39
|
+
this.buffer = lines.pop() || '';
|
|
40
|
+
for (const line of lines) {
|
|
41
|
+
const trimmed = line.trim();
|
|
42
|
+
if (!trimmed)
|
|
43
|
+
continue;
|
|
44
|
+
try {
|
|
45
|
+
const msg = JSON.parse(trimmed);
|
|
46
|
+
if (msg.id !== undefined && this.pending.has(msg.id)) {
|
|
47
|
+
const p = this.pending.get(msg.id);
|
|
48
|
+
this.pending.delete(msg.id);
|
|
49
|
+
if (msg.error) {
|
|
50
|
+
p.reject(new Error(msg.error.message));
|
|
51
|
+
}
|
|
52
|
+
else {
|
|
53
|
+
p.resolve(msg.result);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
// Not valid JSON — skip
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
send(method, params) {
|
|
63
|
+
return new Promise((resolve, reject) => {
|
|
64
|
+
const id = this.nextId++;
|
|
65
|
+
const req = { jsonrpc: '2.0', id, method, params };
|
|
66
|
+
this.pending.set(id, { resolve, reject });
|
|
67
|
+
this.process.stdin.write(JSON.stringify(req) + '\n');
|
|
68
|
+
setTimeout(() => {
|
|
69
|
+
if (this.pending.has(id)) {
|
|
70
|
+
this.pending.delete(id);
|
|
71
|
+
reject(new Error(`MCP server "${this.serverName}" timed out on ${method}`));
|
|
72
|
+
}
|
|
73
|
+
}, 30_000);
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
async initialize() {
|
|
77
|
+
await this.send('initialize', {
|
|
78
|
+
protocolVersion: '2024-11-05',
|
|
79
|
+
capabilities: {},
|
|
80
|
+
clientInfo: { name: 'ptkl-kortex', version: '1.0.0' },
|
|
81
|
+
});
|
|
82
|
+
await this.send('notifications/initialized');
|
|
83
|
+
}
|
|
84
|
+
async listTools() {
|
|
85
|
+
const result = await this.send('tools/list');
|
|
86
|
+
return result?.tools || [];
|
|
87
|
+
}
|
|
88
|
+
async callTool(name, args) {
|
|
89
|
+
const result = await this.send('tools/call', { name, arguments: args });
|
|
90
|
+
if (result?.content) {
|
|
91
|
+
return result.content
|
|
92
|
+
.map((c) => c.text || JSON.stringify(c))
|
|
93
|
+
.join('\n');
|
|
94
|
+
}
|
|
95
|
+
return JSON.stringify(result);
|
|
96
|
+
}
|
|
97
|
+
close() {
|
|
98
|
+
this.process.kill();
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
export class MCPManager {
|
|
102
|
+
connections = new Map();
|
|
103
|
+
toolToServer = new Map();
|
|
104
|
+
async loadConfig(cwd) {
|
|
105
|
+
const configPaths = [
|
|
106
|
+
resolve(cwd, '.kortex.json'),
|
|
107
|
+
resolve(cwd, '.ptkl/kortex.json'),
|
|
108
|
+
resolve(process.env.HOME || '', '.ptkl/kortex.json'),
|
|
109
|
+
];
|
|
110
|
+
let config = null;
|
|
111
|
+
for (const p of configPaths) {
|
|
112
|
+
if (existsSync(p)) {
|
|
113
|
+
try {
|
|
114
|
+
config = JSON.parse(readFileSync(p, 'utf-8'));
|
|
115
|
+
break;
|
|
116
|
+
}
|
|
117
|
+
catch {
|
|
118
|
+
// Skip invalid config
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
if (!config?.mcp_servers)
|
|
123
|
+
return;
|
|
124
|
+
for (const [name, serverConfig] of Object.entries(config.mcp_servers)) {
|
|
125
|
+
try {
|
|
126
|
+
const conn = new MCPConnection(name, serverConfig);
|
|
127
|
+
await conn.initialize();
|
|
128
|
+
this.connections.set(name, conn);
|
|
129
|
+
}
|
|
130
|
+
catch (err) {
|
|
131
|
+
console.error(` MCP "${name}": failed to connect — ${err.message}`);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
async discoverTools() {
|
|
136
|
+
const tools = [];
|
|
137
|
+
for (const [serverName, conn] of this.connections) {
|
|
138
|
+
try {
|
|
139
|
+
const mcpTools = await conn.listTools();
|
|
140
|
+
for (const t of mcpTools) {
|
|
141
|
+
const qualifiedName = `mcp_${serverName}_${t.name}`;
|
|
142
|
+
this.toolToServer.set(qualifiedName, serverName);
|
|
143
|
+
tools.push({
|
|
144
|
+
type: 'function',
|
|
145
|
+
function: {
|
|
146
|
+
name: qualifiedName,
|
|
147
|
+
description: `[MCP: ${serverName}] ${t.description || t.name}`,
|
|
148
|
+
parameters: t.inputSchema || { type: 'object', properties: {}, required: [] },
|
|
149
|
+
},
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
catch (err) {
|
|
154
|
+
console.error(` MCP "${serverName}": failed to list tools — ${err.message}`);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
return tools;
|
|
158
|
+
}
|
|
159
|
+
canHandle(toolName) {
|
|
160
|
+
return this.toolToServer.has(toolName);
|
|
161
|
+
}
|
|
162
|
+
async executeTool(callId, toolName, args) {
|
|
163
|
+
const serverName = this.toolToServer.get(toolName);
|
|
164
|
+
if (!serverName) {
|
|
165
|
+
return { tool_call_id: callId, name: toolName, content: `Error: no MCP server for tool "${toolName}"` };
|
|
166
|
+
}
|
|
167
|
+
const conn = this.connections.get(serverName);
|
|
168
|
+
if (!conn) {
|
|
169
|
+
return { tool_call_id: callId, name: toolName, content: `Error: MCP server "${serverName}" not connected` };
|
|
170
|
+
}
|
|
171
|
+
// Strip the mcp_{server}_ prefix to get the original tool name
|
|
172
|
+
const originalName = toolName.replace(`mcp_${serverName}_`, '');
|
|
173
|
+
try {
|
|
174
|
+
const content = await conn.callTool(originalName, args);
|
|
175
|
+
return { tool_call_id: callId, name: toolName, content };
|
|
176
|
+
}
|
|
177
|
+
catch (err) {
|
|
178
|
+
return { tool_call_id: callId, name: toolName, content: `Error: ${err.message}` };
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
get serverCount() {
|
|
182
|
+
return this.connections.size;
|
|
183
|
+
}
|
|
184
|
+
get serverNames() {
|
|
185
|
+
return Array.from(this.connections.keys());
|
|
186
|
+
}
|
|
187
|
+
close() {
|
|
188
|
+
for (const conn of this.connections.values()) {
|
|
189
|
+
conn.close();
|
|
190
|
+
}
|
|
191
|
+
this.connections.clear();
|
|
192
|
+
}
|
|
193
|
+
}
|