@axplusb/kepler 1.0.5 → 1.0.9

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.
@@ -1,147 +1,252 @@
1
1
  /**
2
- * Skills Loader loads skills from .claude/skills/{name}/SKILL.md
2
+ * Portable Agent Skills loader.
3
3
  *
4
- * Skills are invoked via /skill-name in REPL or the Skill tool.
5
- * Each skill has a SKILL.md that defines:
6
- * - name, description, trigger conditions
7
- * - The prompt to inject when the skill is invoked
4
+ * Discovers standard <root>/<skill>/SKILL.md bundles from Kepler and Claude
5
+ * locations. Only metadata is exposed eagerly; instructions and resources are
6
+ * loaded on demand through view().
8
7
  */
9
8
 
10
- import fs from 'fs';
11
- import path from 'path';
9
+ import crypto from 'node:crypto';
10
+ import fs from 'node:fs';
11
+ import os from 'node:os';
12
+ import path from 'node:path';
13
+
14
+ const DEFAULT_MAX_CHARS = 12_000;
15
+
16
+ function isWithin(root, candidate) {
17
+ const relative = path.relative(root, candidate);
18
+ return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));
19
+ }
20
+
21
+ function parseScalar(value) {
22
+ const trimmed = value.trim();
23
+ if (
24
+ (trimmed.startsWith('"') && trimmed.endsWith('"'))
25
+ || (trimmed.startsWith("'") && trimmed.endsWith("'"))
26
+ ) {
27
+ return trimmed.slice(1, -1);
28
+ }
29
+ if (trimmed.startsWith('[') && trimmed.endsWith(']')) {
30
+ return trimmed.slice(1, -1).split(',').map(item => parseScalar(item)).filter(Boolean);
31
+ }
32
+ if (trimmed === 'true') return true;
33
+ if (trimmed === 'false') return false;
34
+ return trimmed;
35
+ }
36
+
37
+ export function parseSkill(content, fallbackName) {
38
+ const match = content.match(/^---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*\r?\n?/);
39
+ if (!match) throw new Error('SKILL.md requires YAML frontmatter');
40
+
41
+ const metadata = {};
42
+ let activeList = null;
43
+ for (const rawLine of match[1].split(/\r?\n/)) {
44
+ if (!rawLine.trim() || rawLine.trimStart().startsWith('#')) continue;
45
+ const listMatch = rawLine.match(/^\s*-\s+(.+)$/);
46
+ if (listMatch && activeList) {
47
+ metadata[activeList].push(parseScalar(listMatch[1]));
48
+ continue;
49
+ }
50
+ const fieldMatch = rawLine.match(/^([A-Za-z0-9_-]+):\s*(.*)$/);
51
+ if (!fieldMatch) continue;
52
+ const [, key, rawValue] = fieldMatch;
53
+ if (!rawValue.trim()) {
54
+ metadata[key] = [];
55
+ activeList = key;
56
+ } else {
57
+ metadata[key] = parseScalar(rawValue);
58
+ activeList = null;
59
+ }
60
+ }
61
+
62
+ const name = String(metadata.name || fallbackName || '').trim();
63
+ const description = String(metadata.description || '').trim();
64
+ const instructions = content.slice(match[0].length).trim();
65
+ if (!name) throw new Error("SKILL.md requires non-empty 'name'");
66
+ if (!description) throw new Error("SKILL.md requires non-empty 'description'");
67
+ if (!instructions) throw new Error('SKILL.md requires instruction content');
68
+
69
+ return {
70
+ name,
71
+ description,
72
+ aliases: Array.isArray(metadata.aliases) ? metadata.aliases : [],
73
+ compatibility: Array.isArray(metadata.compatibility) ? metadata.compatibility : [],
74
+ metadata,
75
+ instructions,
76
+ prompt: instructions,
77
+ };
78
+ }
79
+
80
+ export function discoverSkillDirectories(root) {
81
+ if (!root || !fs.existsSync(root)) return [];
82
+ const resolved = fs.realpathSync(root);
83
+ if (fs.existsSync(path.join(resolved, 'SKILL.md'))) return [resolved];
84
+ return fs.readdirSync(resolved, { withFileTypes: true })
85
+ .filter(entry => entry.isDirectory() && !entry.isSymbolicLink())
86
+ .map(entry => path.join(resolved, entry.name))
87
+ .filter(dir => fs.existsSync(path.join(dir, 'SKILL.md')))
88
+ .sort();
89
+ }
90
+
91
+ function walkFiles(root) {
92
+ const files = [];
93
+ const queue = [root];
94
+ while (queue.length) {
95
+ const current = queue.shift();
96
+ for (const entry of fs.readdirSync(current, { withFileTypes: true })) {
97
+ const fullPath = path.join(current, entry.name);
98
+ if (entry.isSymbolicLink()) continue;
99
+ if (entry.isDirectory()) queue.push(fullPath);
100
+ else if (entry.isFile()) files.push(fullPath);
101
+ }
102
+ }
103
+ return files.sort((a, b) => a.localeCompare(b));
104
+ }
105
+
106
+ function contentHash(root) {
107
+ const digest = crypto.createHash('sha256');
108
+ for (const filePath of walkFiles(root)) {
109
+ digest.update(path.relative(root, filePath).split(path.sep).join('/'));
110
+ digest.update('\0');
111
+ digest.update(fs.readFileSync(filePath));
112
+ digest.update('\0');
113
+ }
114
+ return `sha256:${digest.digest('hex')}`;
115
+ }
116
+
117
+ function bounded(content, maxChars) {
118
+ if (content.length <= maxChars) return content;
119
+ const head = Math.floor(maxChars * 0.7);
120
+ const tail = maxChars - head;
121
+ return `${content.slice(0, head)}\n\n[... skill content truncated ...]\n\n${content.slice(-tail)}`;
122
+ }
12
123
 
13
124
  export class SkillsLoader {
14
- constructor() {
125
+ constructor({ homeDir = os.homedir() } = {}) {
126
+ this.homeDir = homeDir;
15
127
  this.skills = new Map();
128
+ this.versions = new Map();
16
129
  this.searchPaths = [];
17
130
  }
18
131
 
19
- /**
20
- * Load skills from standard directories.
21
- * @param {string} [cwd] - project working directory
22
- */
23
132
  load(cwd = process.cwd()) {
133
+ this.skills.clear();
134
+ this.versions.clear();
135
+ const project = path.resolve(cwd);
24
136
  this.searchPaths = [
25
- path.join(cwd, '.claude', 'skills'),
26
- path.join(process.env.HOME || '', '.claude', 'skills'),
137
+ { dir: path.join(project, '.kepler', 'skills'), source: 'kepler-project', scope: 'project', priority: 500 },
138
+ { dir: path.join(project, '.claude', 'skills'), source: 'claude-project', scope: 'project', priority: 400 },
139
+ { dir: path.join(this.homeDir, '.kepler', 'skills'), source: 'kepler-global', scope: 'global', priority: 300 },
140
+ { dir: path.join(this.homeDir, '.claude', 'skills'), source: 'claude-global', scope: 'global', priority: 200 },
27
141
  ];
28
142
 
29
- for (const dir of this.searchPaths) {
30
- this._loadFromDir(dir);
31
- }
32
-
143
+ for (const config of this.searchPaths) this._loadFromDir(config);
33
144
  return this;
34
145
  }
35
146
 
36
- _loadFromDir(dir) {
37
- try {
38
- const entries = fs.readdirSync(dir, { withFileTypes: true });
39
- for (const entry of entries) {
40
- if (!entry.isDirectory()) continue;
41
-
42
- const skillFile = path.join(dir, entry.name, 'SKILL.md');
43
- try {
44
- const content = fs.readFileSync(skillFile, 'utf-8');
45
- const skill = parseSkill(content, entry.name);
46
- if (skill) {
47
- skill.source = skillFile;
48
- this.skills.set(skill.name, skill);
49
- }
50
- } catch {
51
- // Skill directory without SKILL.md, skip
52
- }
147
+ _loadFromDir(config) {
148
+ for (const skillDir of discoverSkillDirectories(config.dir)) {
149
+ try {
150
+ const skillFile = path.join(skillDir, 'SKILL.md');
151
+ if (fs.lstatSync(skillFile).isSymbolicLink()) continue;
152
+ const parsed = parseSkill(fs.readFileSync(skillFile, 'utf-8'), path.basename(skillDir));
153
+ const skill = {
154
+ ...parsed,
155
+ root: skillDir,
156
+ source: config.source,
157
+ source_id: `${config.source}:${parsed.name}`,
158
+ scope: config.scope,
159
+ priority: config.priority,
160
+ content_hash: contentHash(skillDir),
161
+ };
162
+ const versions = this.versions.get(skill.name) || [];
163
+ versions.push(skill);
164
+ versions.sort((a, b) => b.priority - a.priority || a.source.localeCompare(b.source));
165
+ this.versions.set(skill.name, versions);
166
+ this.skills.set(skill.name, versions[0]);
167
+ } catch {
168
+ // Invalid third-party bundles are ignored during discovery.
53
169
  }
54
- } catch {
55
- // Directory does not exist
56
170
  }
57
171
  }
58
172
 
59
- /**
60
- * Get a skill by name.
61
- * @param {string} name
62
- * @returns {object|null}
63
- */
64
- get(name) {
65
- // Try exact match, then prefix match
173
+ get(name, sourceId = null) {
174
+ if (sourceId) {
175
+ return (this.versions.get(name) || []).find(skill => skill.source_id === sourceId) || null;
176
+ }
66
177
  if (this.skills.has(name)) return this.skills.get(name);
67
- for (const [key, skill] of this.skills) {
68
- if (key.startsWith(name) || skill.aliases?.includes(name)) {
69
- return skill;
70
- }
178
+ for (const skill of this.skills.values()) {
179
+ if (skill.name.startsWith(name) || skill.aliases.includes(name)) return skill;
71
180
  }
72
181
  return null;
73
182
  }
74
183
 
75
- /**
76
- * List all loaded skills.
77
- * @returns {Array<object>}
78
- */
79
- list() {
80
- return [...this.skills.values()];
184
+ list({ query = '', source = '', scope = '' } = {}) {
185
+ const needle = query.toLowerCase();
186
+ return [...this.skills.values()]
187
+ .filter(skill => !source || skill.source === source)
188
+ .filter(skill => !scope || skill.scope === scope)
189
+ .filter(skill => !needle || `${skill.name} ${skill.description}`.toLowerCase().includes(needle))
190
+ .sort((a, b) => a.name.localeCompare(b.name))
191
+ .map(skill => ({
192
+ name: skill.name,
193
+ description: skill.description,
194
+ source: skill.source,
195
+ source_id: skill.source_id,
196
+ scope: skill.scope,
197
+ content_hash: skill.content_hash,
198
+ compatibility: skill.compatibility,
199
+ shadowed_sources: (this.versions.get(skill.name) || []).slice(1).map(item => item.source_id),
200
+ }));
81
201
  }
82
202
 
83
- /**
84
- * Run a skill, returning its prompt for injection into the conversation.
85
- * @param {string} name - skill name
86
- * @param {string} [args] - optional arguments
87
- * @returns {string} skill prompt
88
- */
89
- async run(name, args) {
90
- const skill = this.get(name);
91
- if (!skill) {
92
- throw new Error(`Unknown skill: ${name}`);
93
- }
94
-
95
- let prompt = skill.prompt;
96
- if (args) {
97
- prompt = prompt.replace('$ARGUMENTS', args);
98
- prompt += `\n\nArguments: ${args}`;
203
+ view(name, resourcePath = null, { sourceId = null, maxChars = DEFAULT_MAX_CHARS } = {}) {
204
+ const skill = this.get(name, sourceId);
205
+ if (!skill) throw new Error(`Unknown skill: ${name}`);
206
+ if (!resourcePath) {
207
+ return {
208
+ name: skill.name,
209
+ description: skill.description,
210
+ source: skill.source,
211
+ source_id: skill.source_id,
212
+ scope: skill.scope,
213
+ content_hash: skill.content_hash,
214
+ compatibility: skill.compatibility,
215
+ shadowed_sources: (this.versions.get(skill.name) || [])
216
+ .filter(item => item.source_id !== skill.source_id)
217
+ .map(item => item.source_id),
218
+ instructions: bounded(skill.instructions, maxChars),
219
+ resources: walkFiles(skill.root)
220
+ .map(file => path.relative(skill.root, file).split(path.sep).join('/'))
221
+ .filter(file => file !== 'SKILL.md'),
222
+ metadata: skill.metadata,
223
+ };
99
224
  }
100
225
 
101
- return `[Skill: ${skill.name}]\n${prompt}`;
102
- }
103
- }
104
-
105
- /**
106
- * Parse a SKILL.md file into a skill definition.
107
- */
108
- function parseSkill(content, dirName) {
109
- const lines = content.split('\n');
110
- const skill = {
111
- name: dirName,
112
- description: '',
113
- aliases: [],
114
- trigger: null,
115
- prompt: content,
116
- };
117
-
118
- // Parse YAML frontmatter if present
119
- if (lines[0]?.trim() === '---') {
120
- const endIdx = lines.indexOf('---', 1);
121
- if (endIdx > 0) {
122
- const frontmatter = lines.slice(1, endIdx).join('\n');
123
- for (const line of frontmatter.split('\n')) {
124
- const colonIdx = line.indexOf(':');
125
- if (colonIdx === -1) continue;
126
- const key = line.slice(0, colonIdx).trim();
127
- const value = line.slice(colonIdx + 1).trim();
128
-
129
- if (key === 'name') skill.name = value;
130
- else if (key === 'description') skill.description = value;
131
- else if (key === 'trigger') skill.trigger = value;
132
- else if (key === 'aliases') {
133
- skill.aliases = value.replace(/[\[\]]/g, '').split(',').map(s => s.trim());
134
- }
135
- }
136
- skill.prompt = lines.slice(endIdx + 1).join('\n').trim();
226
+ if (path.isAbsolute(resourcePath)) throw new Error('Skill resource path must be relative');
227
+ const candidate = path.resolve(skill.root, resourcePath);
228
+ if (!isWithin(skill.root, candidate)) throw new Error('Skill resource escapes its bundle');
229
+ const relativeParts = path.relative(skill.root, candidate).split(path.sep);
230
+ let cursor = skill.root;
231
+ for (const part of relativeParts) {
232
+ cursor = path.join(cursor, part);
233
+ if (!fs.existsSync(cursor)) throw new Error(`Skill resource not found: ${resourcePath}`);
234
+ if (fs.lstatSync(cursor).isSymbolicLink()) throw new Error('Symlinked skill resources are not allowed');
137
235
  }
236
+ if (!fs.statSync(candidate).isFile()) throw new Error(`Skill resource not found: ${resourcePath}`);
237
+ return {
238
+ name: skill.name,
239
+ source_id: skill.source_id,
240
+ path: resourcePath,
241
+ content: bounded(fs.readFileSync(candidate, 'utf-8'), maxChars),
242
+ };
138
243
  }
139
244
 
140
- // Extract description from first paragraph if not in frontmatter
141
- if (!skill.description && skill.prompt) {
142
- const firstLine = skill.prompt.split('\n').find(l => l.trim() && !l.startsWith('#'));
143
- if (firstLine) skill.description = firstLine.trim().slice(0, 100);
245
+ async run(name, args) {
246
+ const skill = this.get(name);
247
+ if (!skill) throw new Error(`Unknown skill: ${name}`);
248
+ let prompt = skill.instructions;
249
+ if (args) prompt = prompt.replace(/\$ARGUMENTS/g, args);
250
+ return `[Skill: ${skill.name}]\n${prompt}${args ? `\n\nArguments: ${args}` : ''}`;
144
251
  }
145
-
146
- return skill;
147
252
  }
@@ -47,6 +47,17 @@ async function main() {
47
47
  return;
48
48
  }
49
49
 
50
+ if (subcommand === 'skills' || subcommand === 'skill') {
51
+ const { runSkillsCommand } = await import('./skills.mjs');
52
+ try {
53
+ await runSkillsCommand(subcommandArgs);
54
+ } catch (err) {
55
+ process.stderr.write(`\x1b[31m✗ Skills command failed: ${err.message}\x1b[0m\n`);
56
+ process.exitCode = 1;
57
+ }
58
+ return;
59
+ }
60
+
50
61
  if (subcommand === 'login') {
51
62
  const { TarangAuth } = await import('../auth/tarang-auth.mjs');
52
63
  const auth = new TarangAuth();
@@ -99,6 +110,13 @@ async function main() {
99
110
  kepler stats Show aggregate local session stats
100
111
  kepler history Show recent prompt history
101
112
 
113
+ \x1b[1mSkills:\x1b[0m
114
+ kepler skills list [--all|--project]
115
+ kepler skills view <name> [resource]
116
+ kepler skills install <path-or-git-url> [--project] [--force]
117
+ kepler skills update <name> [--project]
118
+ kepler skills remove <name> [--project]
119
+
102
120
  \x1b[1mREPL Commands:\x1b[0m
103
121
  /help Show available commands
104
122
  /stats Session metrics (tokens, cost, tools)
@@ -17,17 +17,17 @@
17
17
 
18
18
  import * as readline from 'node:readline';
19
19
  import * as path from 'node:path';
20
+ import * as fs from 'node:fs';
20
21
  import { c, progressBar, spinner, inPlace, renderMarkdown, renderDiff, formatElapsed, formatCost, stripAnsi } from './ansi.mjs';
21
22
  import { calculateCost, formatCostValue, formatTokens } from '../core/pricing.mjs';
22
23
  import { TarangStreamClient, EVENT_TYPES } from '../core/stream-client.mjs';
23
24
  import { JsonlWriter } from '../core/jsonl-writer.mjs';
24
25
  import { createToolExecutor } from '../core/tool-executor.mjs';
26
+ import { persistProjectArtifacts } from '../core/project-artifacts.mjs';
25
27
  import { TarangAuth } from '../auth/tarang-auth.mjs';
26
28
  import { ApprovalManager } from '../core/approval.mjs';
27
29
  import { resolveBackendUrl } from '../core/backend-url.mjs';
28
30
  import { BUILTIN_AGENTS, runAgent } from './agents.mjs';
29
- import { ContextRetriever } from '../context/retriever.mjs';
30
- import { buildProjectSkeleton } from '../context/skeleton.mjs';
31
31
  import { SessionManager } from '../core/session-manager.mjs';
32
32
  import { parseArgs } from '../config/cli-args.mjs';
33
33
  import { formatShellCommand, toolDisplayLabel, toolDisplaySummary } from './tool-display.mjs';
@@ -621,6 +621,16 @@ function renderEvent(event) {
621
621
  break;
622
622
  }
623
623
 
624
+ case 'plan_created': {
625
+ process.stderr.write(` ${c.dim('project plan prepared')}\n`);
626
+ break;
627
+ }
628
+
629
+ case 'goal_created': {
630
+ process.stderr.write(` ${c.dim('project goal prepared')}\n`);
631
+ break;
632
+ }
633
+
624
634
  case 'session_info': {
625
635
  if (data?.session_id) {
626
636
  session.id = data.session_id;
@@ -1122,9 +1132,8 @@ export async function startTerminalRepl() {
1122
1132
  const cliArgs = parseArgs(process.argv.slice(2));
1123
1133
  const auth = new TarangAuth();
1124
1134
 
1125
- // BM25 retriever indexes project files for search_code tool
1126
- const retriever = new ContextRetriever(safeCwd());
1127
- const toolExecutor = createToolExecutor({ retriever });
1135
+ // Projects are registered and indexed on demand through get_project_overview.
1136
+ const toolExecutor = createToolExecutor();
1128
1137
  const skipPerms = cliArgs.freeswim;
1129
1138
  const approval = new ApprovalManager({ autoApprove: skipPerms });
1130
1139
 
@@ -1142,51 +1151,13 @@ export async function startTerminalRepl() {
1142
1151
 
1143
1152
  printBanner(auth);
1144
1153
 
1145
- // ── Initialization with progress ──
1146
- // BM25 indexing is CPU-bound and blocks the event loop, so setInterval
1147
- // spinners won't tick during it. Instead, show a static "Initializing..."
1148
- // message, then yield to the event loop between phases so the spinner runs.
1149
- let projectSkeleton = '';
1150
-
1151
- // Phase 1: Show immediate feedback
1154
+ // ── Initialization ──
1152
1155
  process.stderr.write(` ${c.brand('⠋')} ${c.dim('Initializing...')}\r`);
1153
-
1154
- // Fetch user in parallel (network I/O, won't block event loop)
1155
- const userPromise = fetchUser(ctx);
1156
-
1157
- // Phase 2: BM25 index — CPU-bound, blocks event loop.
1158
- // Wrap in a microtask break so the initial message renders first.
1159
- const indexResult = await new Promise((resolve) => {
1160
- // Let the event loop flush stderr before blocking
1161
- setImmediate(async () => {
1162
- try {
1163
- process.stderr.write(`\r ${c.brand('⠹')} ${c.dim('Indexing project files...')}${' '.repeat(20)}\r`);
1164
- const result = await retriever.buildIndex();
1165
- resolve(result);
1166
- } catch {
1167
- resolve({ fileCount: 0, chunkCount: 0 });
1168
- }
1169
- });
1170
- });
1171
-
1172
- // Phase 3: Build skeleton (fast, synchronous)
1173
- process.stderr.write(`\r ${c.brand('⠼')} ${c.dim('Building project skeleton...')}${' '.repeat(20)}\r`);
1174
- await new Promise(r => setImmediate(r)); // yield so message renders
1175
- projectSkeleton = buildProjectSkeleton(safeCwd());
1176
-
1177
- // Wait for user fetch
1178
- await userPromise;
1156
+ await fetchUser(ctx);
1179
1157
 
1180
1158
  // Clear the spinner line
1181
1159
  process.stderr.write(`\r${' '.repeat(60)}\r`);
1182
-
1183
- // Show init summary
1184
- if (indexResult.fileCount > 0) {
1185
- process.stderr.write(` ${c.green('✓')} ${c.dim(`Indexed ${indexResult.fileCount} files (${indexResult.chunkCount} chunks)`)}\n`);
1186
- }
1187
- if (projectSkeleton) {
1188
- process.stderr.write(` ${c.green('✓')} ${c.dim('Project skeleton ready')}\n`);
1189
- }
1160
+ process.stderr.write(` ${c.green('✓')} ${c.dim('Ready; projects will be indexed on demand')}\n`);
1190
1161
  if (session.user) {
1191
1162
  process.stderr.write(` ${c.green('✓')} ${c.dim(`Logged in as ${session.user.github_username || session.user.email || 'user'}`)}\n`);
1192
1163
  }
@@ -1367,9 +1338,17 @@ export async function startTerminalRepl() {
1367
1338
 
1368
1339
  const execContext = { cwd: safeCwd() };
1369
1340
  if (skipPerms) execContext.freeswim = true;
1370
- if (projectSkeleton) execContext.project_skeleton = projectSkeleton;
1341
+ execContext.project_resources = toolExecutor.getProjectResources();
1342
+ execContext.agent_context = toolExecutor.getAgentContext();
1371
1343
 
1372
1344
  for await (const event of client.execute(input, execContext, session.history)) {
1345
+ if (event.type === 'plan_created' || event.type === 'goal_created') {
1346
+ persistProjectArtifacts(
1347
+ event.data,
1348
+ toolExecutor.getProjectResources(),
1349
+ message => process.stderr.write(` ${c.dim(message)}\n`),
1350
+ );
1351
+ }
1373
1352
  renderEvent(event);
1374
1353
 
1375
1354
  if (event.type === 'content_partial') {
@@ -0,0 +1,54 @@
1
+ import { SkillInstaller } from '../skills/installer.mjs';
2
+ import { SkillsLoader } from '../skills/loader.mjs';
3
+
4
+ function has(args, flag) {
5
+ return args.includes(flag);
6
+ }
7
+
8
+ function scopeFrom(args) {
9
+ return has(args, '--project') ? 'project' : 'global';
10
+ }
11
+
12
+ function print(value) {
13
+ process.stdout.write(typeof value === 'string' ? `${value}\n` : `${JSON.stringify(value, null, 2)}\n`);
14
+ }
15
+
16
+ export async function runSkillsCommand(args, { cwd = process.cwd() } = {}) {
17
+ const action = args[0] || 'list';
18
+ const rest = args.slice(1);
19
+ const scope = scopeFrom(rest);
20
+ const installer = new SkillInstaller({ cwd });
21
+ const loader = new SkillsLoader().load(cwd);
22
+
23
+ if (action === 'list') {
24
+ const rows = loader.list({ scope: has(rest, '--all') ? '' : scope });
25
+ if (has(rest, '--json')) print(rows);
26
+ else if (!rows.length) print('No skills found.');
27
+ else for (const row of rows) print(`${row.name}\t${row.scope}\t${row.source}\t${row.description}`);
28
+ return;
29
+ }
30
+ if (action === 'view') {
31
+ const name = rest.find(arg => !arg.startsWith('--'));
32
+ if (!name) throw new Error('Usage: kepler skills view <name> [resource-path]');
33
+ const nameIndex = rest.indexOf(name);
34
+ const resource = rest.slice(nameIndex + 1).find(arg => !arg.startsWith('--')) || null;
35
+ print(loader.view(name, resource));
36
+ return;
37
+ }
38
+ if (action === 'install') {
39
+ const source = rest.find(arg => !arg.startsWith('--'));
40
+ print(installer.install(source, { scope, force: has(rest, '--force') }));
41
+ return;
42
+ }
43
+ if (action === 'remove') {
44
+ const name = rest.find(arg => !arg.startsWith('--'));
45
+ print(installer.remove(name, { scope }));
46
+ return;
47
+ }
48
+ if (action === 'update') {
49
+ const name = rest.find(arg => !arg.startsWith('--'));
50
+ print(installer.update(name, { scope }));
51
+ return;
52
+ }
53
+ throw new Error(`Unknown skills command: ${action}`);
54
+ }
@@ -27,6 +27,7 @@ export const BashTool = {
27
27
  command: { type: 'string', description: 'The command to execute' },
28
28
  timeout: { type: 'number', description: 'Timeout in ms (max 600000)', default: 120000 },
29
29
  description: { type: 'string', description: 'Description of what this command does' },
30
+ cwd: { type: 'string', description: 'Working directory for the command' },
30
31
  run_in_background: { type: 'boolean', description: 'Run in background', default: false },
31
32
  },
32
33
  required: ['command'],
@@ -40,7 +41,7 @@ export const BashTool = {
40
41
  const timeout = Math.min(input.timeout || 120000, 600000);
41
42
 
42
43
  if (input.run_in_background) {
43
- return runBackground(input.command);
44
+ return runBackground(input.command, input.cwd);
44
45
  }
45
46
 
46
47
  return new Promise((resolve) => {
@@ -50,6 +51,7 @@ export const BashTool = {
50
51
  let exitCode = null;
51
52
 
52
53
  const proc = spawn('bash', ['-c', input.command], {
54
+ cwd: input.cwd,
53
55
  env: { ...process.env },
54
56
  stdio: ['pipe', 'pipe', 'pipe'],
55
57
  timeout: 0, // we handle timeout ourselves
@@ -120,9 +122,10 @@ export const BashTool = {
120
122
  const backgroundJobs = new Map();
121
123
  let bgJobId = 0;
122
124
 
123
- function runBackground(command) {
125
+ function runBackground(command, cwd) {
124
126
  const id = ++bgJobId;
125
127
  const proc = spawn('bash', ['-c', command], {
128
+ cwd,
126
129
  detached: true,
127
130
  stdio: ['ignore', 'pipe', 'pipe'],
128
131
  });