@gilangranggaid/kilua-agent 1.0.3 → 1.0.5
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/bin/kilua.js +479 -0
- package/bin/kilua.mjs +116 -84
- package/package.json +4 -4
package/bin/kilua.js
ADDED
|
@@ -0,0 +1,479 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import readline from "node:readline";
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import os from "node:os";
|
|
6
|
+
import { execSync } from "node:child_process";
|
|
7
|
+
|
|
8
|
+
// ponytail: single-file agent CLI supporting real-time streaming for 9router, Anthropic & OpenAI proxies.
|
|
9
|
+
const KILUA_DIR = path.join(os.homedir(), ".kilua");
|
|
10
|
+
const SETTINGS_PATH = path.join(KILUA_DIR, "settings.json");
|
|
11
|
+
const CLAUDE_SETTINGS_PATH = path.join(os.homedir(), ".claude", "settings.json");
|
|
12
|
+
|
|
13
|
+
function ensureKiluaDir() {
|
|
14
|
+
if (!fs.existsSync(KILUA_DIR)) fs.mkdirSync(KILUA_DIR, { recursive: true });
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function loadSettings() {
|
|
18
|
+
ensureKiluaDir();
|
|
19
|
+
try { return JSON.parse(fs.readFileSync(SETTINGS_PATH, "utf8")); } catch { return {}; }
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function saveSettings(settings) {
|
|
23
|
+
ensureKiluaDir();
|
|
24
|
+
fs.writeFileSync(SETTINGS_PATH, JSON.stringify(settings, null, 2), "utf8");
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function readClaudeSettings() {
|
|
28
|
+
try {
|
|
29
|
+
const raw = JSON.parse(fs.readFileSync(CLAUDE_SETTINGS_PATH, "utf8"));
|
|
30
|
+
const env = raw.env || {};
|
|
31
|
+
if (env.ANTHROPIC_BASE_URL || env.ANTHROPIC_AUTH_TOKEN) {
|
|
32
|
+
return {
|
|
33
|
+
base_url: env.ANTHROPIC_BASE_URL || "http://127.0.0.1:20128/v1",
|
|
34
|
+
api_key: env.ANTHROPIC_AUTH_TOKEN || "",
|
|
35
|
+
model: env.ANTHROPIC_DEFAULT_OPUS_MODEL || env.ANTHROPIC_DEFAULT_SONNET_MODEL || "harobor",
|
|
36
|
+
provider: "anthropic"
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
} catch {}
|
|
40
|
+
return null;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const TOOLS_OPENAI = [
|
|
44
|
+
{
|
|
45
|
+
type: "function",
|
|
46
|
+
function: {
|
|
47
|
+
name: "read_file",
|
|
48
|
+
description: "Membaca isi file lokal.",
|
|
49
|
+
parameters: { type: "object", properties: { path: { type: "string" } }, required: ["path"] }
|
|
50
|
+
}
|
|
51
|
+
},
|
|
52
|
+
{
|
|
53
|
+
type: "function",
|
|
54
|
+
function: {
|
|
55
|
+
name: "write_file",
|
|
56
|
+
description: "Menulis atau membuat file lokal.",
|
|
57
|
+
parameters: { type: "object", properties: { path: { type: "string" }, content: { type: "string" } }, required: ["path", "content"] }
|
|
58
|
+
}
|
|
59
|
+
},
|
|
60
|
+
{
|
|
61
|
+
type: "function",
|
|
62
|
+
function: {
|
|
63
|
+
name: "edit_file",
|
|
64
|
+
description: "Mengganti teks persis di file lokal.",
|
|
65
|
+
parameters: { type: "object", properties: { path: { type: "string" }, old_string: { type: "string" }, new_string: { type: "string" } }, required: ["path", "old_string", "new_string"] }
|
|
66
|
+
}
|
|
67
|
+
},
|
|
68
|
+
{
|
|
69
|
+
type: "function",
|
|
70
|
+
function: {
|
|
71
|
+
name: "list_dir",
|
|
72
|
+
description: "Melihat daftar file di folder.",
|
|
73
|
+
parameters: { type: "object", properties: { path: { type: "string" } } }
|
|
74
|
+
}
|
|
75
|
+
},
|
|
76
|
+
{
|
|
77
|
+
type: "function",
|
|
78
|
+
function: {
|
|
79
|
+
name: "run_cmd",
|
|
80
|
+
description: "Menjalankan perintah terminal lokal.",
|
|
81
|
+
parameters: { type: "object", properties: { command: { type: "string" } }, required: ["command"] }
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
];
|
|
85
|
+
|
|
86
|
+
const TOOLS_ANTHROPIC = TOOLS_OPENAI.map(t => ({
|
|
87
|
+
name: t.function.name,
|
|
88
|
+
description: t.function.description,
|
|
89
|
+
input_schema: t.function.parameters
|
|
90
|
+
}));
|
|
91
|
+
|
|
92
|
+
function executeLocalTool(name, args) {
|
|
93
|
+
const cwd = process.cwd();
|
|
94
|
+
try {
|
|
95
|
+
if (name === "read_file") {
|
|
96
|
+
const full = path.resolve(cwd, args.path);
|
|
97
|
+
return fs.existsSync(full) ? fs.readFileSync(full, "utf8").slice(0, 40000) : `Error: ${args.path} not found.`;
|
|
98
|
+
}
|
|
99
|
+
if (name === "write_file") {
|
|
100
|
+
const full = path.resolve(cwd, args.path);
|
|
101
|
+
fs.mkdirSync(path.dirname(full), { recursive: true });
|
|
102
|
+
fs.writeFileSync(full, args.content, "utf8");
|
|
103
|
+
return `✓ Written: ${args.path}`;
|
|
104
|
+
}
|
|
105
|
+
if (name === "edit_file") {
|
|
106
|
+
const full = path.resolve(cwd, args.path);
|
|
107
|
+
if (!fs.existsSync(full)) return `Error: ${args.path} not found.`;
|
|
108
|
+
const src = fs.readFileSync(full, "utf8");
|
|
109
|
+
if (!src.includes(args.old_string)) return `Error: old_string not matched in ${args.path}.`;
|
|
110
|
+
fs.writeFileSync(full, src.replace(args.old_string, args.new_string), "utf8");
|
|
111
|
+
return `✓ Edited: ${args.path}`;
|
|
112
|
+
}
|
|
113
|
+
if (name === "list_dir") {
|
|
114
|
+
const target = path.resolve(cwd, args.path || ".");
|
|
115
|
+
return fs.readdirSync(target, { withFileTypes: true }).map(it => `${it.isDirectory() ? "[DIR]" : "[FILE]"} ${it.name}`).join("\n");
|
|
116
|
+
}
|
|
117
|
+
if (name === "run_cmd") {
|
|
118
|
+
const out = execSync(args.command, { cwd, encoding: "utf8", timeout: 60000, stdio: ["pipe", "pipe", "pipe"] });
|
|
119
|
+
return out.trim() || "(Done)";
|
|
120
|
+
}
|
|
121
|
+
} catch (err) {
|
|
122
|
+
return `Error: ${err.stderr || err.message}`;
|
|
123
|
+
}
|
|
124
|
+
return `Error: Unknown tool ${name}`;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function promptQuestion(rl, query) {
|
|
128
|
+
return new Promise(res => rl.question(query, res));
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
async function runInteractiveConfig() {
|
|
132
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
133
|
+
const claudeCfg = readClaudeSettings();
|
|
134
|
+
|
|
135
|
+
console.log("\x1b[35m=== KILUA CONFIG ===\x1b[0m\nPath: " + SETTINGS_PATH);
|
|
136
|
+
console.log("1) 9Router Local / Claude Code Proxy (Port 20128)");
|
|
137
|
+
console.log("2) TokenHarbor / 9Router / OpenRouter (OpenAI-compatible)");
|
|
138
|
+
console.log("3) Google Gemini (AI Studio Key)\n");
|
|
139
|
+
|
|
140
|
+
const choice = (await promptQuestion(rl, "Pilihan [1/2/3] (default 1): ")).trim() || "1";
|
|
141
|
+
let settings = {};
|
|
142
|
+
|
|
143
|
+
if (choice === "1") {
|
|
144
|
+
const defaultUrl = claudeCfg?.base_url || "http://127.0.0.1:20128/v1";
|
|
145
|
+
const defaultKey = claudeCfg?.api_key || "";
|
|
146
|
+
const defaultModel = claudeCfg?.model || "harobor";
|
|
147
|
+
|
|
148
|
+
const baseUrl = (await promptQuestion(rl, `Base URL (${defaultUrl}): `)).trim() || defaultUrl;
|
|
149
|
+
const key = (await promptQuestion(rl, `API Key/Token (${defaultKey ? defaultKey.slice(0, 10) + "..." : "masukkan token"}): `)).trim() || defaultKey;
|
|
150
|
+
const model = (await promptQuestion(rl, `Model (${defaultModel}): `)).trim() || defaultModel;
|
|
151
|
+
|
|
152
|
+
settings = {
|
|
153
|
+
provider: "anthropic",
|
|
154
|
+
base_url: baseUrl.replace(/\/+$/, ""),
|
|
155
|
+
api_key: key,
|
|
156
|
+
model
|
|
157
|
+
};
|
|
158
|
+
} else if (choice === "3") {
|
|
159
|
+
const key = (await promptQuestion(rl, "Masukkan GEMINI_API_KEY: ")).trim();
|
|
160
|
+
const model = (await promptQuestion(rl, "Nama Model (gemini-2.5-flash): ")).trim() || "gemini-2.5-flash";
|
|
161
|
+
settings = {
|
|
162
|
+
provider: "openai",
|
|
163
|
+
base_url: "https://generativelanguage.googleapis.com/v1beta/openai",
|
|
164
|
+
api_key: key,
|
|
165
|
+
model
|
|
166
|
+
};
|
|
167
|
+
} else {
|
|
168
|
+
console.log("Contoh Base URL: https://tokenharbor.ai/v1");
|
|
169
|
+
const baseUrl = (await promptQuestion(rl, "Base URL (https://tokenharbor.ai/v1): ")).trim() || "https://tokenharbor.ai/v1";
|
|
170
|
+
const key = (await promptQuestion(rl, "API Key: ")).trim();
|
|
171
|
+
const model = (await promptQuestion(rl, "Model (deepseek-v4.1-flash:free): ")).trim() || "deepseek-v4.1-flash:free";
|
|
172
|
+
settings = {
|
|
173
|
+
provider: "openai",
|
|
174
|
+
api_key: key,
|
|
175
|
+
base_url: baseUrl.replace(/\/+$/, ""),
|
|
176
|
+
model
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
saveSettings(settings);
|
|
181
|
+
rl.close();
|
|
182
|
+
console.log("\x1b[32m✓ Pengaturan disimpan di " + SETTINGS_PATH + "\x1b[0m\n");
|
|
183
|
+
return settings;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// Stream reader universal untuk SSE (Anthropic & 9router)
|
|
187
|
+
async function readSseStream(res, onChunk) {
|
|
188
|
+
const reader = res.body.getReader();
|
|
189
|
+
const decoder = new TextDecoder("utf-8");
|
|
190
|
+
let buffer = "";
|
|
191
|
+
|
|
192
|
+
while (true) {
|
|
193
|
+
const { done, value } = await reader.read();
|
|
194
|
+
if (done) break;
|
|
195
|
+
buffer += decoder.decode(value, { stream: true });
|
|
196
|
+
const lines = buffer.split("\n");
|
|
197
|
+
buffer = lines.pop() || "";
|
|
198
|
+
|
|
199
|
+
for (const rawLine of lines) {
|
|
200
|
+
const line = rawLine.trim();
|
|
201
|
+
if (!line || line.startsWith("event:") || line.startsWith(":")) continue;
|
|
202
|
+
if (line.startsWith("data:")) {
|
|
203
|
+
const jsonStr = line.slice(5).trim();
|
|
204
|
+
if (!jsonStr || jsonStr === "[DONE]") continue;
|
|
205
|
+
try {
|
|
206
|
+
const parsed = JSON.parse(jsonStr);
|
|
207
|
+
onChunk(parsed);
|
|
208
|
+
} catch {}
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
if (buffer.trim().startsWith("data:")) {
|
|
214
|
+
try {
|
|
215
|
+
const parsed = JSON.parse(buffer.trim().slice(5).trim());
|
|
216
|
+
onChunk(parsed);
|
|
217
|
+
} catch {}
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// Loop untuk Anthropic / 9router local (/v1/messages)
|
|
222
|
+
async function runAnthropicLoop(settings, convo) {
|
|
223
|
+
const SYSTEM = `Kamu KILUA, AI Coding Agent di terminal lokal. Folder: ${process.cwd()}. Gunakan tools (read_file, write_file, edit_file, list_dir, run_cmd) untuk inspeksi dan eksekusi tugas coding mandiri. Respon ringkas to the point.`;
|
|
224
|
+
|
|
225
|
+
let endpoint = settings.base_url.replace(/\/+$/, "");
|
|
226
|
+
if (!endpoint.endsWith("/messages")) endpoint += "/messages";
|
|
227
|
+
|
|
228
|
+
for (let step = 0; step < 12; step++) {
|
|
229
|
+
process.stdout.write("\r\x1b[2K\x1b[35m[KILUA Berpikir...]\x1b[0m ");
|
|
230
|
+
let res;
|
|
231
|
+
try {
|
|
232
|
+
res = await fetch(endpoint, {
|
|
233
|
+
method: "POST",
|
|
234
|
+
headers: {
|
|
235
|
+
"Content-Type": "application/json",
|
|
236
|
+
"x-api-key": settings.api_key,
|
|
237
|
+
Authorization: `Bearer ${settings.api_key}`,
|
|
238
|
+
"anthropic-version": "2023-06-01"
|
|
239
|
+
},
|
|
240
|
+
body: JSON.stringify({
|
|
241
|
+
model: settings.model,
|
|
242
|
+
max_tokens: 4096,
|
|
243
|
+
stream: true,
|
|
244
|
+
system: SYSTEM,
|
|
245
|
+
messages: convo,
|
|
246
|
+
tools: TOOLS_ANTHROPIC
|
|
247
|
+
})
|
|
248
|
+
});
|
|
249
|
+
} catch (e) {
|
|
250
|
+
console.error("\n[!] Connection error:", e.message);
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
if (!res.ok) {
|
|
255
|
+
const errText = await res.text().catch(() => "");
|
|
256
|
+
console.error(`\n[!] Error (${res.status}):`, errText.slice(0, 200));
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
let printedHeader = false;
|
|
261
|
+
let fullText = "";
|
|
262
|
+
const toolBlocks = [];
|
|
263
|
+
|
|
264
|
+
await readSseStream(res, (evt) => {
|
|
265
|
+
// 1. Text deltas
|
|
266
|
+
let deltaText = "";
|
|
267
|
+
if (typeof evt.delta?.text === "string") deltaText = evt.delta.text;
|
|
268
|
+
else if (typeof evt.delta?.content === "string") deltaText = evt.delta.content;
|
|
269
|
+
else if (evt.choices?.[0]?.delta?.content) deltaText = evt.choices[0].delta.content;
|
|
270
|
+
else if (evt.content_block?.text) deltaText = evt.content_block.text;
|
|
271
|
+
|
|
272
|
+
if (deltaText) {
|
|
273
|
+
if (!printedHeader) {
|
|
274
|
+
process.stdout.write("\r\x1b[2KKILUA > ");
|
|
275
|
+
printedHeader = true;
|
|
276
|
+
}
|
|
277
|
+
process.stdout.write(deltaText);
|
|
278
|
+
fullText += deltaText;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// 2. Tool deltas
|
|
282
|
+
if (evt.type === "content_block_start" && evt.content_block?.type === "tool_use") {
|
|
283
|
+
toolBlocks[evt.index] = { ...evt.content_block, _raw_json: "" };
|
|
284
|
+
} else if (evt.delta?.type === "input_json_delta") {
|
|
285
|
+
const idx = evt.index;
|
|
286
|
+
if (toolBlocks[idx]) {
|
|
287
|
+
toolBlocks[idx]._raw_json = (toolBlocks[idx]._raw_json || "") + (evt.delta.partial_json || "");
|
|
288
|
+
}
|
|
289
|
+
} else if (evt.type === "content_block_stop") {
|
|
290
|
+
const idx = evt.index;
|
|
291
|
+
if (toolBlocks[idx]?._raw_json) {
|
|
292
|
+
try { toolBlocks[idx].input = JSON.parse(toolBlocks[idx]._raw_json); } catch {}
|
|
293
|
+
delete toolBlocks[idx]._raw_json;
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
});
|
|
297
|
+
|
|
298
|
+
if (printedHeader) console.log();
|
|
299
|
+
else process.stdout.write("\r\x1b[2K");
|
|
300
|
+
|
|
301
|
+
const activeTools = toolBlocks.filter(Boolean);
|
|
302
|
+
const assistantBlocks = [];
|
|
303
|
+
if (fullText) assistantBlocks.push({ type: "text", text: fullText });
|
|
304
|
+
for (const tb of activeTools) assistantBlocks.push(tb);
|
|
305
|
+
|
|
306
|
+
convo.push({ role: "assistant", content: assistantBlocks.length ? assistantBlocks : fullText });
|
|
307
|
+
|
|
308
|
+
if (!activeTools.length) break;
|
|
309
|
+
|
|
310
|
+
const toolResultContent = [];
|
|
311
|
+
for (const tu of activeTools) {
|
|
312
|
+
const name = tu.name;
|
|
313
|
+
const args = tu.input || {};
|
|
314
|
+
console.log(`\x1b[36m⚡ Tool: ${name}\x1b[0m(${JSON.stringify(args)})`);
|
|
315
|
+
const output = executeLocalTool(name, args);
|
|
316
|
+
console.log(`\x1b[90m↳ ${output.slice(0, 140).replace(/\n/g, " ")}${output.length > 140 ? "..." : ""}\x1b[0m`);
|
|
317
|
+
toolResultContent.push({
|
|
318
|
+
type: "tool_result",
|
|
319
|
+
tool_use_id: tu.id,
|
|
320
|
+
content: output
|
|
321
|
+
});
|
|
322
|
+
}
|
|
323
|
+
convo.push({ role: "user", content: toolResultContent });
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
// Loop untuk OpenAI / TokenHarbor / Gemini OpenAI protocol
|
|
328
|
+
async function runOpenAiLoop(settings, convo) {
|
|
329
|
+
const SYSTEM = `Kamu KILUA, AI Coding Agent di terminal lokal. Folder: ${process.cwd()}. Gunakan tools (read_file, write_file, edit_file, list_dir, run_cmd) untuk inspeksi dan eksekusi tugas coding mandiri. Respon ringkas to the point.`;
|
|
330
|
+
|
|
331
|
+
let endpoint = settings.base_url.replace(/\/+$/, "");
|
|
332
|
+
if (endpoint.includes("generativelanguage.googleapis.com") && !endpoint.includes("/openai")) {
|
|
333
|
+
endpoint += "/openai";
|
|
334
|
+
}
|
|
335
|
+
if (!endpoint.endsWith("/chat/completions")) {
|
|
336
|
+
endpoint += "/chat/completions";
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
for (let step = 0; step < 12; step++) {
|
|
340
|
+
process.stdout.write("\r\x1b[2K\x1b[35m[KILUA Berpikir...]\x1b[0m ");
|
|
341
|
+
let res;
|
|
342
|
+
try {
|
|
343
|
+
res = await fetch(endpoint, {
|
|
344
|
+
method: "POST",
|
|
345
|
+
headers: {
|
|
346
|
+
"Content-Type": "application/json",
|
|
347
|
+
Authorization: `Bearer ${settings.api_key}`,
|
|
348
|
+
"x-goog-api-key": settings.api_key
|
|
349
|
+
},
|
|
350
|
+
body: JSON.stringify({
|
|
351
|
+
model: settings.model,
|
|
352
|
+
stream: true,
|
|
353
|
+
messages: [{ role: "system", content: SYSTEM }, ...convo],
|
|
354
|
+
tools: TOOLS_OPENAI,
|
|
355
|
+
tool_choice: "auto"
|
|
356
|
+
})
|
|
357
|
+
});
|
|
358
|
+
} catch (e) {
|
|
359
|
+
console.error("\n[!] Connection error:", e.message);
|
|
360
|
+
return;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
if (!res.ok) {
|
|
364
|
+
const errText = await res.text().catch(() => "");
|
|
365
|
+
console.error(`\n[!] Error (${res.status}):`, errText.slice(0, 200));
|
|
366
|
+
return;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
let printedHeader = false;
|
|
370
|
+
let fullText = "";
|
|
371
|
+
const toolCallsMap = {};
|
|
372
|
+
|
|
373
|
+
await readSseStream(res, (evt) => {
|
|
374
|
+
const choice = evt.choices?.[0];
|
|
375
|
+
const delta = choice?.delta;
|
|
376
|
+
if (delta?.content) {
|
|
377
|
+
if (!printedHeader) {
|
|
378
|
+
process.stdout.write("\r\x1b[2KKILUA > ");
|
|
379
|
+
printedHeader = true;
|
|
380
|
+
}
|
|
381
|
+
process.stdout.write(delta.content);
|
|
382
|
+
fullText += delta.content;
|
|
383
|
+
}
|
|
384
|
+
if (delta?.tool_calls) {
|
|
385
|
+
for (const tc of delta.tool_calls) {
|
|
386
|
+
const idx = tc.index ?? 0;
|
|
387
|
+
if (!toolCallsMap[idx]) toolCallsMap[idx] = { id: tc.id, function: { name: tc.function?.name || "", arguments: "" } };
|
|
388
|
+
if (tc.function?.name) toolCallsMap[idx].function.name = tc.function.name;
|
|
389
|
+
if (tc.function?.arguments) toolCallsMap[idx].function.arguments += tc.function.arguments;
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
});
|
|
393
|
+
|
|
394
|
+
if (printedHeader) console.log();
|
|
395
|
+
else process.stdout.write("\r\x1b[2K");
|
|
396
|
+
|
|
397
|
+
const toolCalls = Object.values(toolCallsMap);
|
|
398
|
+
convo.push({ role: "assistant", content: fullText, tool_calls: toolCalls.length ? toolCalls : undefined });
|
|
399
|
+
|
|
400
|
+
if (!toolCalls.length) break;
|
|
401
|
+
|
|
402
|
+
for (const tc of toolCalls) {
|
|
403
|
+
const name = tc.function.name;
|
|
404
|
+
let args = {};
|
|
405
|
+
try { args = JSON.parse(tc.function.arguments || "{}"); } catch {}
|
|
406
|
+
console.log(`\x1b[36m⚡ Tool: ${name}\x1b[0m(${JSON.stringify(args)})`);
|
|
407
|
+
const output = executeLocalTool(name, args);
|
|
408
|
+
console.log(`\x1b[90m↳ ${output.slice(0, 140).replace(/\n/g, " ")}${output.length > 140 ? "..." : ""}\x1b[0m`);
|
|
409
|
+
convo.push({ role: "tool", tool_call_id: tc.id, name, content: output });
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
async function runAgent(settings, userPrompt, convo) {
|
|
415
|
+
const isAnthropic = settings.provider === "anthropic" || settings.base_url.includes(":20128") || settings.model === "harobor";
|
|
416
|
+
if (isAnthropic) {
|
|
417
|
+
convo.push({ role: "user", content: userPrompt });
|
|
418
|
+
await runAnthropicLoop(settings, convo);
|
|
419
|
+
} else {
|
|
420
|
+
convo.push({ role: "user", content: userPrompt });
|
|
421
|
+
await runOpenAiLoop(settings, convo);
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
async function main() {
|
|
426
|
+
const args = process.argv.slice(2);
|
|
427
|
+
const oneShot = args.join(" ").trim();
|
|
428
|
+
|
|
429
|
+
if (args[0] === "config" || args[0] === "setup") {
|
|
430
|
+
await runInteractiveConfig();
|
|
431
|
+
process.exit(0);
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
let settings = loadSettings();
|
|
435
|
+
|
|
436
|
+
// Auto-import dari Claude Code jika settings kilua belum ada
|
|
437
|
+
if (!settings.api_key) {
|
|
438
|
+
const claudeCfg = readClaudeSettings();
|
|
439
|
+
if (claudeCfg) {
|
|
440
|
+
settings = claudeCfg;
|
|
441
|
+
saveSettings(settings);
|
|
442
|
+
} else {
|
|
443
|
+
console.log("\x1b[33m[!] Belum ada konfigurasi AI key.\x1b[0m");
|
|
444
|
+
settings = await runInteractiveConfig();
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
const convo = [];
|
|
449
|
+
if (oneShot) {
|
|
450
|
+
await runAgent(settings, oneShot, convo);
|
|
451
|
+
process.exit(0);
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
console.log("\x1b[1m\x1b[35m=== KILUA AI CLI AGENT ===\x1b[0m");
|
|
455
|
+
console.log(`CWD : \x1b[33m${process.cwd()}\x1b[0m`);
|
|
456
|
+
console.log(`Provider: \x1b[32m${settings.base_url}\x1b[0m (${settings.model})`);
|
|
457
|
+
console.log(`Config : \x1b[90m${SETTINGS_PATH}\x1b[0m (ketik 'config' untuk ganti)\n`);
|
|
458
|
+
|
|
459
|
+
let rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
460
|
+
const ask = () => {
|
|
461
|
+
rl.question("\x1b[1mKAMU > \x1b[0m", async input => {
|
|
462
|
+
const q = input.trim();
|
|
463
|
+
if (!q) return ask();
|
|
464
|
+
if (q === "exit" || q === "quit") { rl.close(); process.exit(0); }
|
|
465
|
+
if (q === "config" || q === "/config") {
|
|
466
|
+
rl.close();
|
|
467
|
+
await runInteractiveConfig();
|
|
468
|
+
settings = loadSettings();
|
|
469
|
+
rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
470
|
+
return ask();
|
|
471
|
+
}
|
|
472
|
+
await runAgent(settings, q, convo);
|
|
473
|
+
ask();
|
|
474
|
+
});
|
|
475
|
+
};
|
|
476
|
+
ask();
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
main();
|
package/bin/kilua.mjs
CHANGED
|
@@ -5,7 +5,7 @@ import path from "node:path";
|
|
|
5
5
|
import os from "node:os";
|
|
6
6
|
import { execSync } from "node:child_process";
|
|
7
7
|
|
|
8
|
-
// ponytail: single-file agent CLI
|
|
8
|
+
// ponytail: single-file agent CLI supporting real-time streaming for 9router, Anthropic & OpenAI proxies.
|
|
9
9
|
const KILUA_DIR = path.join(os.homedir(), ".kilua");
|
|
10
10
|
const SETTINGS_PATH = path.join(KILUA_DIR, "settings.json");
|
|
11
11
|
const CLAUDE_SETTINGS_PATH = path.join(os.homedir(), ".claude", "settings.json");
|
|
@@ -165,7 +165,7 @@ async function runInteractiveConfig() {
|
|
|
165
165
|
model
|
|
166
166
|
};
|
|
167
167
|
} else {
|
|
168
|
-
console.log("Contoh Base URL: https://tokenharbor.ai/v1
|
|
168
|
+
console.log("Contoh Base URL: https://tokenharbor.ai/v1");
|
|
169
169
|
const baseUrl = (await promptQuestion(rl, "Base URL (https://tokenharbor.ai/v1): ")).trim() || "https://tokenharbor.ai/v1";
|
|
170
170
|
const key = (await promptQuestion(rl, "API Key: ")).trim();
|
|
171
171
|
const model = (await promptQuestion(rl, "Model (deepseek-v4.1-flash:free): ")).trim() || "deepseek-v4.1-flash:free";
|
|
@@ -183,50 +183,39 @@ async function runInteractiveConfig() {
|
|
|
183
183
|
return settings;
|
|
184
184
|
}
|
|
185
185
|
|
|
186
|
-
//
|
|
187
|
-
async function
|
|
188
|
-
const
|
|
189
|
-
const
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
const blk = { ...evt.content_block };
|
|
210
|
-
if (blk.type === "tool_use") blk._raw_json = "";
|
|
211
|
-
blocks[evt.index] = blk;
|
|
212
|
-
} else if (evt.type === "content_block_delta") {
|
|
213
|
-
const idx = evt.index;
|
|
214
|
-
if (!blocks[idx]) blocks[idx] = { type: "text", text: "" };
|
|
215
|
-
if (evt.delta?.type === "text_delta") {
|
|
216
|
-
blocks[idx].text = (blocks[idx].text || "") + (evt.delta.text || "");
|
|
217
|
-
} else if (evt.delta?.type === "input_json_delta") {
|
|
218
|
-
blocks[idx]._raw_json = (blocks[idx]._raw_json || "") + (evt.delta.partial_json || "");
|
|
219
|
-
}
|
|
220
|
-
} else if (evt.type === "content_block_stop") {
|
|
221
|
-
const idx = evt.index;
|
|
222
|
-
if (blocks[idx]?.type === "tool_use" && blocks[idx]._raw_json) {
|
|
223
|
-
try { blocks[idx].input = JSON.parse(blocks[idx]._raw_json); } catch {}
|
|
224
|
-
delete blocks[idx]._raw_json;
|
|
186
|
+
// Stream reader universal untuk SSE (Anthropic & 9router)
|
|
187
|
+
async function readSseStream(res, onChunk) {
|
|
188
|
+
const reader = res.body.getReader();
|
|
189
|
+
const decoder = new TextDecoder("utf-8");
|
|
190
|
+
let buffer = "";
|
|
191
|
+
|
|
192
|
+
while (true) {
|
|
193
|
+
const { done, value } = await reader.read();
|
|
194
|
+
if (done) break;
|
|
195
|
+
buffer += decoder.decode(value, { stream: true });
|
|
196
|
+
const lines = buffer.split("\n");
|
|
197
|
+
buffer = lines.pop() || "";
|
|
198
|
+
|
|
199
|
+
for (const rawLine of lines) {
|
|
200
|
+
const line = rawLine.trim();
|
|
201
|
+
if (!line || line.startsWith("event:") || line.startsWith(":")) continue;
|
|
202
|
+
if (line.startsWith("data:")) {
|
|
203
|
+
const jsonStr = line.slice(5).trim();
|
|
204
|
+
if (!jsonStr || jsonStr === "[DONE]") continue;
|
|
205
|
+
try {
|
|
206
|
+
const parsed = JSON.parse(jsonStr);
|
|
207
|
+
onChunk(parsed);
|
|
208
|
+
} catch {}
|
|
225
209
|
}
|
|
226
210
|
}
|
|
227
211
|
}
|
|
228
212
|
|
|
229
|
-
|
|
213
|
+
if (buffer.trim().startsWith("data:")) {
|
|
214
|
+
try {
|
|
215
|
+
const parsed = JSON.parse(buffer.trim().slice(5).trim());
|
|
216
|
+
onChunk(parsed);
|
|
217
|
+
} catch {}
|
|
218
|
+
}
|
|
230
219
|
}
|
|
231
220
|
|
|
232
221
|
// Loop untuk Anthropic / 9router local (/v1/messages)
|
|
@@ -251,7 +240,7 @@ async function runAnthropicLoop(settings, convo) {
|
|
|
251
240
|
body: JSON.stringify({
|
|
252
241
|
model: settings.model,
|
|
253
242
|
max_tokens: 4096,
|
|
254
|
-
stream:
|
|
243
|
+
stream: true,
|
|
255
244
|
system: SYSTEM,
|
|
256
245
|
messages: convo,
|
|
257
246
|
tools: TOOLS_ANTHROPIC
|
|
@@ -268,20 +257,58 @@ async function runAnthropicLoop(settings, convo) {
|
|
|
268
257
|
return;
|
|
269
258
|
}
|
|
270
259
|
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
const
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
260
|
+
let printedHeader = false;
|
|
261
|
+
let fullText = "";
|
|
262
|
+
const toolBlocks = [];
|
|
263
|
+
|
|
264
|
+
await readSseStream(res, (evt) => {
|
|
265
|
+
// 1. Text deltas
|
|
266
|
+
let deltaText = "";
|
|
267
|
+
if (typeof evt.delta?.text === "string") deltaText = evt.delta.text;
|
|
268
|
+
else if (typeof evt.delta?.content === "string") deltaText = evt.delta.content;
|
|
269
|
+
else if (evt.choices?.[0]?.delta?.content) deltaText = evt.choices[0].delta.content;
|
|
270
|
+
else if (evt.content_block?.text) deltaText = evt.content_block.text;
|
|
271
|
+
|
|
272
|
+
if (deltaText) {
|
|
273
|
+
if (!printedHeader) {
|
|
274
|
+
process.stdout.write("\r\x1b[2KKILUA > ");
|
|
275
|
+
printedHeader = true;
|
|
276
|
+
}
|
|
277
|
+
process.stdout.write(deltaText);
|
|
278
|
+
fullText += deltaText;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// 2. Tool deltas
|
|
282
|
+
if (evt.type === "content_block_start" && evt.content_block?.type === "tool_use") {
|
|
283
|
+
toolBlocks[evt.index] = { ...evt.content_block, _raw_json: "" };
|
|
284
|
+
} else if (evt.delta?.type === "input_json_delta") {
|
|
285
|
+
const idx = evt.index;
|
|
286
|
+
if (toolBlocks[idx]) {
|
|
287
|
+
toolBlocks[idx]._raw_json = (toolBlocks[idx]._raw_json || "") + (evt.delta.partial_json || "");
|
|
288
|
+
}
|
|
289
|
+
} else if (evt.type === "content_block_stop") {
|
|
290
|
+
const idx = evt.index;
|
|
291
|
+
if (toolBlocks[idx]?._raw_json) {
|
|
292
|
+
try { toolBlocks[idx].input = JSON.parse(toolBlocks[idx]._raw_json); } catch {}
|
|
293
|
+
delete toolBlocks[idx]._raw_json;
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
});
|
|
297
|
+
|
|
298
|
+
if (printedHeader) console.log();
|
|
299
|
+
else process.stdout.write("\r\x1b[2K");
|
|
277
300
|
|
|
278
|
-
|
|
301
|
+
const activeTools = toolBlocks.filter(Boolean);
|
|
302
|
+
const assistantBlocks = [];
|
|
303
|
+
if (fullText) assistantBlocks.push({ type: "text", text: fullText });
|
|
304
|
+
for (const tb of activeTools) assistantBlocks.push(tb);
|
|
279
305
|
|
|
280
|
-
|
|
281
|
-
|
|
306
|
+
convo.push({ role: "assistant", content: assistantBlocks.length ? assistantBlocks : fullText });
|
|
307
|
+
|
|
308
|
+
if (!activeTools.length) break;
|
|
282
309
|
|
|
283
310
|
const toolResultContent = [];
|
|
284
|
-
for (const tu of
|
|
311
|
+
for (const tu of activeTools) {
|
|
285
312
|
const name = tu.name;
|
|
286
313
|
const args = tu.input || {};
|
|
287
314
|
console.log(`\x1b[36m⚡ Tool: ${name}\x1b[0m(${JSON.stringify(args)})`);
|
|
@@ -295,29 +322,6 @@ async function runAnthropicLoop(settings, convo) {
|
|
|
295
322
|
}
|
|
296
323
|
convo.push({ role: "user", content: toolResultContent });
|
|
297
324
|
}
|
|
298
|
-
console.log();
|
|
299
|
-
}
|
|
300
|
-
|
|
301
|
-
// Parser tangguh untuk OpenAI format
|
|
302
|
-
async function parseOpenAiResponse(res) {
|
|
303
|
-
const text = await res.text();
|
|
304
|
-
const trimmed = text.trim();
|
|
305
|
-
if (!trimmed.startsWith("data:")) {
|
|
306
|
-
try { return JSON.parse(trimmed); } catch {}
|
|
307
|
-
}
|
|
308
|
-
let content = "";
|
|
309
|
-
const lines = text.split("\n");
|
|
310
|
-
for (const line of lines) {
|
|
311
|
-
if (!line.startsWith("data:")) continue;
|
|
312
|
-
const jsonStr = line.slice(5).trim();
|
|
313
|
-
if (!jsonStr || jsonStr === "[DONE]") continue;
|
|
314
|
-
try {
|
|
315
|
-
const parsed = JSON.parse(jsonStr);
|
|
316
|
-
const delta = parsed.choices?.[0]?.delta?.content;
|
|
317
|
-
if (delta) content += delta;
|
|
318
|
-
} catch {}
|
|
319
|
-
}
|
|
320
|
-
return { choices: [{ message: { role: "assistant", content } }] };
|
|
321
325
|
}
|
|
322
326
|
|
|
323
327
|
// Loop untuk OpenAI / TokenHarbor / Gemini OpenAI protocol
|
|
@@ -343,7 +347,13 @@ async function runOpenAiLoop(settings, convo) {
|
|
|
343
347
|
Authorization: `Bearer ${settings.api_key}`,
|
|
344
348
|
"x-goog-api-key": settings.api_key
|
|
345
349
|
},
|
|
346
|
-
body: JSON.stringify({
|
|
350
|
+
body: JSON.stringify({
|
|
351
|
+
model: settings.model,
|
|
352
|
+
stream: true,
|
|
353
|
+
messages: [{ role: "system", content: SYSTEM }, ...convo],
|
|
354
|
+
tools: TOOLS_OPENAI,
|
|
355
|
+
tool_choice: "auto"
|
|
356
|
+
})
|
|
347
357
|
});
|
|
348
358
|
} catch (e) {
|
|
349
359
|
console.error("\n[!] Connection error:", e.message);
|
|
@@ -356,14 +366,37 @@ async function runOpenAiLoop(settings, convo) {
|
|
|
356
366
|
return;
|
|
357
367
|
}
|
|
358
368
|
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
369
|
+
let printedHeader = false;
|
|
370
|
+
let fullText = "";
|
|
371
|
+
const toolCallsMap = {};
|
|
372
|
+
|
|
373
|
+
await readSseStream(res, (evt) => {
|
|
374
|
+
const choice = evt.choices?.[0];
|
|
375
|
+
const delta = choice?.delta;
|
|
376
|
+
if (delta?.content) {
|
|
377
|
+
if (!printedHeader) {
|
|
378
|
+
process.stdout.write("\r\x1b[2KKILUA > ");
|
|
379
|
+
printedHeader = true;
|
|
380
|
+
}
|
|
381
|
+
process.stdout.write(delta.content);
|
|
382
|
+
fullText += delta.content;
|
|
383
|
+
}
|
|
384
|
+
if (delta?.tool_calls) {
|
|
385
|
+
for (const tc of delta.tool_calls) {
|
|
386
|
+
const idx = tc.index ?? 0;
|
|
387
|
+
if (!toolCallsMap[idx]) toolCallsMap[idx] = { id: tc.id, function: { name: tc.function?.name || "", arguments: "" } };
|
|
388
|
+
if (tc.function?.name) toolCallsMap[idx].function.name = tc.function.name;
|
|
389
|
+
if (tc.function?.arguments) toolCallsMap[idx].function.arguments += tc.function.arguments;
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
});
|
|
393
|
+
|
|
394
|
+
if (printedHeader) console.log();
|
|
395
|
+
else process.stdout.write("\r\x1b[2K");
|
|
363
396
|
|
|
364
|
-
|
|
397
|
+
const toolCalls = Object.values(toolCallsMap);
|
|
398
|
+
convo.push({ role: "assistant", content: fullText, tool_calls: toolCalls.length ? toolCalls : undefined });
|
|
365
399
|
|
|
366
|
-
const toolCalls = message.tool_calls || [];
|
|
367
400
|
if (!toolCalls.length) break;
|
|
368
401
|
|
|
369
402
|
for (const tc of toolCalls) {
|
|
@@ -376,7 +409,6 @@ async function runOpenAiLoop(settings, convo) {
|
|
|
376
409
|
convo.push({ role: "tool", tool_call_id: tc.id, name, content: output });
|
|
377
410
|
}
|
|
378
411
|
}
|
|
379
|
-
console.log();
|
|
380
412
|
}
|
|
381
413
|
|
|
382
414
|
async function runAgent(settings, userPrompt, convo) {
|
package/package.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@gilangranggaid/kilua-agent",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.5",
|
|
4
4
|
"description": "Autonomous AI Coding Agent for your terminal and VS Code",
|
|
5
5
|
"type": "module",
|
|
6
|
-
"main": "bin/kilua.
|
|
6
|
+
"main": "bin/kilua.js",
|
|
7
7
|
"bin": {
|
|
8
|
-
"kilua": "./bin/kilua.
|
|
9
|
-
"kilua-agent": "./bin/kilua.
|
|
8
|
+
"kilua": "./bin/kilua.js",
|
|
9
|
+
"kilua-agent": "./bin/kilua.js"
|
|
10
10
|
},
|
|
11
11
|
"files": [
|
|
12
12
|
"bin",
|