-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.js
More file actions
537 lines (465 loc) · 16.2 KB
/
Copy pathcli.js
File metadata and controls
537 lines (465 loc) · 16.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
#!/usr/bin/env node
const { askBrain } = require('./core/brain');
const { buildTemplate } = require('./core/builder');
const { printDoctor, runDoctor } = require('./core/doctor');
const { printJson, printScan, printSearch, printToolResult } = require('./core/format');
const { createGoal, loadGoal, listGoals, runApprovedGoal } = require('./core/goal-manager');
const { runChat } = require('./core/chat');
const { runMenu } = require('./core/menu');
const { loadMemory, setMemoryValue } = require('./core/memory');
const { checkProvider, listOllamaModels } = require('./core/provider-health');
const { listProviders, providerStatus, setupProvider } = require('./core/providers');
const { runSetup } = require('./core/setup');
const { getSkill, listSkills, searchSkills } = require('./core/skills');
const { readRecentToolEvents } = require('./core/tool-log');
const { buildContextIndex, searchContextIndex } = require('./core/context-index');
const { getTool, listTools } = require('./core/tools');
const { applyFilePatch, makeDir, previewPatch, readTextFile, runReviewedCommand, scanProject, searchFiles, zipPath } = require('./core/workspace-tools');
function parseArgs(argv) {
const args = [];
const flags = {};
for (let index = 0; index < argv.length; index += 1) {
const value = argv[index];
if (value.startsWith('--')) {
const key = value.slice(2);
const next = argv[index + 1];
if (!next || next.startsWith('--')) {
flags[key] = true;
} else {
flags[key] = next;
index += 1;
}
} else {
args.push(value);
}
}
return { args, flags };
}
function printHelp() {
console.log([
'Kairos Agent 0.1',
'',
'Commands:',
' (no args) opens the Kairos menu',
' start',
' chat',
' setup [--yes] [--provider offline|ollama|openai|anthropic|gemini|kimi|openrouter|codex]',
' doctor',
' brain setup|status|list|check',
' brain ask "<prompt>"',
' ollama models',
' run "<powershell command>"',
' scan [path]',
' search <query> [path]',
' read <path>',
' mkdir <path>',
' zip <sourcePath> <zipPath>',
' build <node-cli|discord-bot> <targetPath> [--force]',
' /goal "<goal>" [--budget cheap|balanced|best] [--approval step|auto-safe|manual]',
' approve <goal-id>',
' status [goal-id]',
' skills list',
' skills search "<query>"',
' skills show <category:skill-name>',
' tools list',
' logs [limit]',
' providers list',
' providers status [provider]',
' providers setup [--provider offline|ollama|openai|anthropic|gemini|kimi|openrouter|codex]',
' memory show',
' memory set <name|style|note|key> <value>',
' --help',
'',
'Examples:',
' npm.cmd run kairos',
' npm.cmd run kairos -- setup',
' npm.cmd run kairos -- doctor',
' npm.cmd run kairos -- brain setup',
' npm.cmd run kairos -- brain status',
' npm.cmd run kairos -- brain check',
' npm.cmd run kairos -- brain check --all',
' npm.cmd run kairos -- brain ask "explain this repo"',
' npm.cmd run kairos -- ollama models',
' npm.cmd run kairos -- scan',
' npm.cmd run kairos -- search discord poseidon-bot',
' npm.cmd run kairos -- read README.md',
' npm.cmd run kairos -- mkdir apps/demo',
' npm.cmd run kairos -- zip poseidon-bot packages/poseidon-bot.zip',
' npm.cmd run kairos -- build discord-bot apps/client-bot',
' npm.cmd run kairos -- /goal "Build a Discord ticket bot template" --budget cheap --approval step',
' npm.cmd run kairos -- approve goal_20260531_001',
' npm.cmd run kairos -- skills list',
' npm.cmd run kairos -- skills search "model selector"',
' npm.cmd run kairos -- skills show 01-coding:code-reviewer',
' npm.cmd run kairos -- tools list',
' npm.cmd run kairos -- logs 10',
' npm.cmd run kairos -- providers status',
' npm.cmd run kairos -- providers setup',
' npm.cmd run kairos -- providers setup --provider ollama --yes',
' npm.cmd run kairos -- providers setup --provider openai'
].join('\n'));
}
function printGoal(goal) {
printJson(goal);
}
async function main() {
const { args, flags } = parseArgs(process.argv.slice(2));
const command = args[0];
if (command === '--help' || flags.help) {
printHelp();
return;
}
if (!command || command === 'start') {
await runMenu();
return;
}
if (command === 'chat') {
await runChat();
return;
}
if (command === 'setup') {
const result = await runSetup(flags);
if (!result.completed) {
console.log(result.message);
return;
}
console.log('Setup complete.');
console.log(`Provider: ${result.provider.id}`);
console.log(`Memory: ${result.memoryPath}`);
if (result.health) {
console.log(`Brain check: ${result.health.ok ? 'OK' : 'NOT READY'} - ${result.health.message}`);
}
if (result.provider.id !== 'offline' && result.health?.ok) {
console.log('Starting chat...');
await runChat();
}
return;
}
if (command === 'doctor') {
const report = await runDoctor();
flags.json ? printGoal(report) : printDoctor(report);
return;
}
if (command === '/goal') {
const title = args.slice(1).join(' ').trim();
if (!title) {
throw new Error('Missing goal text. Example: /goal "Build a Discord ticket bot template"');
}
const goal = createGoal({
title,
budgetMode: flags.budget || 'cheap',
approvalMode: flags.approval || 'step'
});
console.log(goal.warning);
console.log('');
console.log(`Goal saved: ${goal.id}`);
console.log(`Approve with: npm.cmd run kairos -- approve ${goal.id}`);
return;
}
if (command === 'approve') {
const goalId = args[1];
if (!goalId) throw new Error('Missing goal id. Example: approve goal_20260531_001');
const result = runApprovedGoal(goalId);
printGoal(result);
return;
}
if (command === 'status') {
const goalId = args[1];
if (goalId) {
printGoal(loadGoal(goalId));
return;
}
const goals = listGoals();
if (goals.length === 0) {
console.log('No Kairos goals yet.');
return;
}
for (const goal of goals) {
console.log(`${goal.id} | ${goal.status} | ${goal.title}`);
}
return;
}
if (command === 'skills') {
const subcommand = args[1] || 'list';
if (subcommand === 'list') {
const result = listSkills();
if (result.warning) {
console.log(result.warning);
return;
}
console.log(`Skills root: ${result.rootDir}`);
for (const skill of result.skills) {
console.log(`${skill.id} | ${skill.title}`);
}
return;
}
if (subcommand === 'show') {
const skillId = args[2];
if (!skillId) throw new Error('Missing skill id. Example: skills show 01-coding:code-reviewer');
const skill = getSkill(skillId);
console.log([
`${skill.id} | ${skill.title}`,
`Path: ${skill.path}`,
'',
skill.content
].join('\n'));
return;
}
if (subcommand === 'search') {
const query = args.slice(2).join(' ').trim();
if (!query) throw new Error('Missing search query. Example: skills search "model selector"');
const results = searchSkills(query);
if (results.length === 0) {
console.log(`No skills matched: ${query}`);
return;
}
for (const skill of results) {
console.log(`${skill.id} | score=${skill.score} | ${skill.title}`);
}
return;
}
throw new Error(`Unknown skills command: ${subcommand}`);
}
if (command === 'tools') {
const subcommand = args[1] || 'list';
if (subcommand === 'list') {
for (const tool of listTools()) {
console.log(`${tool.id} | ${tool.status} | ${tool.description}`);
}
return;
}
if (subcommand === 'run') {
const toolId = args[2];
if (!toolId) throw new Error('Usage: tools run <id> --json \'{"key":"value"}\'');
const tool = getTool(toolId);
if (!tool) throw new Error(`Unknown tool: ${toolId}`);
if (typeof tool.handler !== 'function') {
throw new Error(`Tool has no runnable handler yet: ${toolId} (status: ${tool.status})`);
}
let params = {};
if (flags.json && flags.json !== true) {
try {
params = JSON.parse(flags.json);
} catch {
throw new Error('Invalid --json payload for tools run.');
}
}
const result = await tool.handler(params);
flags.json ? printJson(result) : printToolResult(result);
return;
}
throw new Error(`Unknown tools command: ${subcommand}`);
}
if (command === 'context') {
const subcommand = args[1] || 'build';
if (subcommand === 'build') {
const result = buildContextIndex({
project: !flags['no-project'],
compact: Boolean(flags.compact),
incremental: Boolean(flags.incremental)
});
flags.json ? printJson(result) : printGoal(result);
return;
}
if (subcommand === 'search') {
const query = args.slice(2).join(' ').trim();
if (!query) throw new Error('Usage: context search "<query>"');
const results = searchContextIndex(query, {});
if (flags.json) {
printJson(results);
return;
}
if (results.length === 0) {
console.log('No matching context found. Try: kairos context build');
return;
}
for (const doc of results) {
console.log(`[${doc.type}] ${doc.title || doc.sourcePath || doc.path}`);
console.log(doc.content.slice(0, 200));
console.log('');
}
return;
}
throw new Error(`Unknown context command: ${subcommand}`);
}
if (command === 'logs') {
const limit = Number.parseInt(args[1] || '25', 10);
printGoal(readRecentToolEvents(Number.isInteger(limit) ? limit : 25));
return;
}
if (command === 'providers') {
const subcommand = args[1] || 'status';
if (subcommand === 'list') {
for (const provider of listProviders()) {
console.log(`${provider.id} | ${provider.status.configured ? 'configured' : 'needs setup'} | ${provider.label} | ${provider.description}`);
}
return;
}
if (subcommand === 'status') {
const providerId = args[2];
printGoal(providerStatus(providerId));
return;
}
if (subcommand === 'setup') {
const providerId = flags.provider;
const result = await setupProvider(providerId, flags);
console.log(`Saved provider config to: ${result.envPath}`);
printGoal(result.status);
return;
}
throw new Error(`Unknown providers command: ${subcommand}`);
}
if (command === 'brain') {
const subcommand = args[1] || 'status';
if (subcommand === 'list') {
for (const provider of listProviders()) {
console.log(`${provider.id} | ${provider.status.configured ? 'configured' : 'needs setup'} | ${provider.label} | ${provider.description}`);
}
return;
}
if (subcommand === 'status') {
printGoal(providerStatus(args[2]));
return;
}
if (subcommand === 'setup' || subcommand === 'change') {
const result = await setupProvider(flags.provider, flags);
console.log('Brain updated.');
console.log(`Provider: ${result.status.id}`);
console.log(`Status: ${result.status.configured ? 'configured' : 'needs setup'}`);
const health = await checkProvider(result.status.id);
console.log(`Brain check: ${health.ok ? 'OK' : 'NOT READY'} - ${health.message}`);
return;
}
if (subcommand === 'check') {
if (flags.all) {
for (const provider of listProviders()) {
const health = await checkProvider(provider.id);
console.log(`${provider.id} | ${health.ok ? 'OK' : 'NOT READY'} | ${health.message}`);
}
return;
}
printGoal(await checkProvider(args[2] || providerStatus().id));
return;
}
if (subcommand === 'ask') {
const prompt = args.slice(2).join(' ').trim();
if (!prompt) throw new Error('Usage: brain ask "<prompt>"');
console.log(await askBrain(prompt));
return;
}
throw new Error(`Unknown brain command: ${subcommand}`);
}
if (command === 'ollama') {
const subcommand = args[1] || 'models';
if (subcommand === 'models') {
const result = await listOllamaModels();
if (!result.ok) {
console.log(result.message);
if (result.detail) console.log(result.detail);
return;
}
if (result.models.length === 0) {
console.log('Ollama is running, but no models are installed.');
console.log('Try: ollama pull llama3.1');
return;
}
console.log('Ollama models:');
for (const model of result.models) console.log(`- ${model}`);
return;
}
throw new Error(`Unknown ollama command: ${subcommand}`);
}
if (command === 'run') {
const shellCommand = args.slice(1).join(' ').trim();
if (!shellCommand) throw new Error('Usage: run "<powershell command>"');
const result = await runReviewedCommand(shellCommand, flags);
flags.json ? printJson(result) : printToolResult(result);
return;
}
if (command === 'scan') {
const result = scanProject(args[1] || '.');
flags.json ? printJson(result) : printScan(result);
return;
}
if (command === 'search') {
const query = args[1];
if (!query) throw new Error('Usage: search <query> [path]');
const result = searchFiles(query, args[2] || '.');
flags.json ? printJson(result) : printSearch(result);
return;
}
if (command === 'files') {
const subcommand = args[1];
if (subcommand === 'patch') {
const targetPath = args[2];
if (!targetPath) throw new Error('Usage: files patch <path> --old <text> --new <text> [--yes]');
const oldText = flags.old;
const newText = flags.new;
if (typeof oldText !== 'string' || typeof newText !== 'string') {
throw new Error('Usage: files patch <path> --old <text> --new <text> [--yes]');
}
const current = readTextFile(targetPath).content;
if (!current.includes(oldText)) {
throw new Error(`Text not found in file: ${JSON.stringify(oldText)}`);
}
const updated = current.replace(oldText, newText);
previewPatch(targetPath, updated);
const result = await applyFilePatch(targetPath, flags);
flags.json ? printJson(result) : printToolResult(result);
return;
}
throw new Error(`Unknown files command: ${subcommand}`);
}
if (command === 'read') {
const targetPath = args[1];
if (!targetPath) throw new Error('Usage: read <path>');
const result = readTextFile(targetPath);
console.log(result.content);
return;
}
if (command === 'mkdir') {
const targetPath = args[1];
if (!targetPath) throw new Error('Usage: mkdir <path>');
const result = await makeDir(targetPath, flags);
flags.json ? printJson(result) : printToolResult(result);
return;
}
if (command === 'zip') {
const sourcePath = args[1];
const outPath = args[2];
if (!sourcePath || !outPath) throw new Error('Usage: zip <sourcePath> <zipPath>');
const result = await zipPath(sourcePath, outPath, flags);
flags.json ? printJson(result) : printToolResult(result);
return;
}
if (command === 'build') {
const type = args[1];
const targetPath = args[2];
if (!type || !targetPath) throw new Error('Usage: build <node-cli|discord-bot> <targetPath> [--force]');
const result = await buildTemplate({ type, targetPath, flags });
flags.json ? printJson(result) : printToolResult(result);
return;
}
if (command === 'memory') {
const subcommand = args[1] || 'show';
if (subcommand === 'show') {
printGoal(loadMemory());
return;
}
if (subcommand === 'set') {
const key = args[2];
const value = args.slice(3).join(' ').trim();
if (!key || !value) {
throw new Error('Usage: memory set <name|style|note|key> <value>');
}
printGoal(setMemoryValue(key, value));
return;
}
throw new Error(`Unknown memory command: ${subcommand}`);
}
throw new Error(`Unknown command: ${command}`);
}
main().catch((error) => {
console.error(`Kairos error: ${error.message}`);
process.exitCode = 1;
});