@axplusb/kepler 2.0.7 → 2.2.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.
@@ -9,12 +9,13 @@
9
9
  */
10
10
 
11
11
  import { createToolRegistry } from '../tools/registry.mjs';
12
- import { filterOutput } from './output-filter.mjs';
12
+ import { detectCommandType, filterOutput } from './output-filter.mjs';
13
13
  import { validatePath, validateDelete, validateShellCommand, validateWrite } from './safety.mjs';
14
14
  import { classifyCommand, isExitCodeError } from '../permissions/command-classifier.mjs';
15
15
  import { analyzeCode } from '../context/ast-parser.mjs';
16
16
  import { ProjectRegistry } from '../tools/project-overview.mjs';
17
17
  import { SkillsLoader } from '../skills/loader.mjs';
18
+ import { HookRunner } from '../config/hook-runner.mjs';
18
19
  import * as fs from 'node:fs';
19
20
  import * as path from 'node:path';
20
21
  import { execSync } from 'node:child_process';
@@ -29,6 +30,7 @@ export function createToolExecutor({
29
30
  projectRegistry = new ProjectRegistry(),
30
31
  skillsLoader = new SkillsLoader().load(process.cwd()),
31
32
  checkpoints = null,
33
+ hookRunner = null,
32
34
  } = {}) {
33
35
  const occRegistry = createToolRegistry();
34
36
  const skillTool = occRegistry.get('Skill');
@@ -49,6 +51,43 @@ export function createToolExecutor({
49
51
  return resolvePath(args.cwd || null, args);
50
52
  }
51
53
 
54
+ function longRunningObservationTimeoutMs() {
55
+ const configured = Number(process.env.KEPLER_LONG_RUNNING_TIMEOUT_MS);
56
+ return Number.isFinite(configured) && configured > 0 ? configured : 15_000;
57
+ }
58
+
59
+ function isLikelyLongRunningCommand(command) {
60
+ const cmd = String(command || '').trim();
61
+ if (!cmd) return false;
62
+ if (/^(?:timeout|gtimeout)\s+\S+\s+/i.test(cmd)) return false;
63
+ if (/(?:^|[;&|]\s*)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:dev|start|serve|preview)\b/i.test(cmd)) return true;
64
+ if (/(?:^|[;&|]\s*)(?:vite|next|nuxt|astro|webpack-dev-server)\b/i.test(cmd)) return true;
65
+ if (/\b(?:uvicorn|gunicorn|flask\s+run|rails\s+server|bin\/rails\s+server|django-admin\s+runserver|manage\.py\s+runserver)\b/i.test(cmd)) return true;
66
+ if (/\b(?:python|python3)\s+-m\s+http\.server\b/i.test(cmd)) return true;
67
+ if (/\bnode\b[\s\S]*(?:setInterval|\.listen\s*\(|createServer\s*\()/i.test(cmd)) return true;
68
+ if (/\b(?:docker\s+compose|docker-compose)\s+up\b(?![\s\S]*\s-d\b)/i.test(cmd)) return true;
69
+ if (/\btail\s+-f\b/i.test(cmd)) return true;
70
+ if (/\b(?:--watch|watch)\b/i.test(cmd)) return true;
71
+ return false;
72
+ }
73
+
74
+ function limitTail(text, maxChars = 8000) {
75
+ const value = String(text || '');
76
+ if (value.length <= maxChars) return value;
77
+ return `... (tail truncated)\n${value.slice(value.length - maxChars)}`;
78
+ }
79
+
80
+ function formatObservationTimeoutOutput(rawOutput, timeoutMs) {
81
+ const tail = String(rawOutput || '')
82
+ .replace(/^Error:\s*Command timed out after \d+ms\s*/i, '')
83
+ .trim();
84
+ const body = tail || '(no output captured before timeout)';
85
+ return limitTail(
86
+ `Observation timeout after ${timeoutMs}ms for a likely long-running command. ` +
87
+ `The process was stopped after collecting the output tail.\n${body}`
88
+ );
89
+ }
90
+
52
91
  function updateProjectIndex(filePath) {
53
92
  try {
54
93
  projectRegistry.projectForPath(filePath)?.retriever.updateFile(filePath);
@@ -215,20 +254,31 @@ export function createToolExecutor({
215
254
  }
216
255
  }
217
256
 
257
+ const observationTimeout = args.timeout == null && isLikelyLongRunningCommand(args.command);
258
+ const effectiveTimeout = observationTimeout ? longRunningObservationTimeoutMs() : args.timeout;
218
259
  const result = await occRegistry.call('Bash', {
219
260
  command: args.command,
220
- timeout: args.timeout,
261
+ timeout: effectiveTimeout,
221
262
  description: args.description || `Run: ${(args.command || '').slice(0, 50)}`,
222
263
  cwd,
223
264
  });
224
265
  const rawOutput = typeof result === 'string' ? result : String(result);
266
+ const timedOut = /^Error:\s*Command timed out after \d+ms/i.test(rawOutput);
225
267
  const exitMatch = rawOutput.match(/Exit code: (\d+)/);
226
- const exitCode = exitMatch ? parseInt(exitMatch[1]) : 0;
268
+ const exitCode = timedOut ? 124 : (exitMatch ? parseInt(exitMatch[1]) : 0);
227
269
  // Semantic exit code: grep returns 1 for "no matches" (not an error)
228
- const success = !isExitCodeError(args.command, exitCode);
270
+ const success = observationTimeout && timedOut ? true : (!timedOut && !isExitCodeError(args.command, exitCode));
229
271
 
230
272
  // Apply smart filtering based on command type
231
- const filtered = filterOutput(rawOutput, args.command, success);
273
+ const filtered = observationTimeout && timedOut
274
+ ? {
275
+ output: formatObservationTimeoutOutput(rawOutput, effectiveTimeout),
276
+ commandType: detectCommandType(args.command),
277
+ truncated: false,
278
+ originalLines: rawOutput.split('\n').length,
279
+ filteredLines: rawOutput.split('\n').length,
280
+ }
281
+ : filterOutput(rawOutput, args.command, success);
232
282
 
233
283
  return {
234
284
  success,
@@ -238,6 +288,9 @@ export function createToolExecutor({
238
288
  _classification: args._classification,
239
289
  _commandType: filtered.commandType,
240
290
  _filtered: filtered.truncated || filtered.originalLines !== filtered.filteredLines,
291
+ _timed_out: timedOut,
292
+ _observation_timeout: observationTimeout && timedOut,
293
+ _observation_timeout_ms: observationTimeout && timedOut ? effectiveTimeout : undefined,
241
294
  };
242
295
  },
243
296
 
@@ -875,8 +928,21 @@ print('OK: replaced')
875
928
  if (!handler) {
876
929
  return { success: false, output: `Unknown tool: ${name}`, _tool: name };
877
930
  }
931
+ const hooks = hookRunner || new HookRunner({ cwd: process.cwd() });
878
932
  try {
879
- return await handler(args);
933
+ const pre = await hooks.run('PreToolUse', { toolName: name, input: args || {} });
934
+ if (pre.blocked) {
935
+ return { success: false, output: `BLOCKED by hook: ${pre.message}`, _tool: name, _blocked: true };
936
+ }
937
+ let result = await handler(args);
938
+ const post = await hooks.run('PostToolUse', { toolName: name, input: args || {}, result });
939
+ for (const item of post.results || []) {
940
+ if (item.parsed?.modifiedResult !== undefined) result = item.parsed.modifiedResult;
941
+ if (item.parsed?.feedback && result && typeof result === 'object') {
942
+ result.output = `${result.output || ''}\n\n--- Hook Feedback ---\n${item.parsed.feedback}`.trim();
943
+ }
944
+ }
945
+ return result;
880
946
  } catch (err) {
881
947
  return { success: false, output: `Tool error (${name}): ${err.message}`, _tool: name };
882
948
  }
@@ -0,0 +1,158 @@
1
+ import * as crypto from 'node:crypto';
2
+ import * as fs from 'node:fs';
3
+ import * as path from 'node:path';
4
+ import { TIERS } from './risk-tier.mjs';
5
+
6
+ function trustPath(cwd) {
7
+ return path.join(cwd, '.kepler', 'trust.json');
8
+ }
9
+
10
+ function nowIso() {
11
+ return new Date().toISOString();
12
+ }
13
+
14
+ function commandShape(command) {
15
+ const parts = String(command || '').trim().split(/\s+/).filter(Boolean);
16
+ return parts.slice(0, 2).join(' ');
17
+ }
18
+
19
+ function shellPattern(args) {
20
+ const shape = commandShape(args?.command);
21
+ return shape ? `${shape}*` : '*';
22
+ }
23
+
24
+ function pathPattern(args) {
25
+ const p = String(args?.file_path || args?.path || '').trim();
26
+ if (!p) return '*';
27
+ const dir = path.dirname(p);
28
+ return dir === '.' ? p : path.join(dir, '**');
29
+ }
30
+
31
+ export function patternFor(tool, args = {}) {
32
+ if (tool === 'shell') return shellPattern(args);
33
+ return pathPattern(args);
34
+ }
35
+
36
+ function matches(pattern, value) {
37
+ if (!pattern || pattern === '*') return true;
38
+ if (pattern.endsWith('*')) return String(value || '').startsWith(pattern.slice(0, -1));
39
+ if (pattern.endsWith('/**')) return String(value || '').startsWith(pattern.slice(0, -3));
40
+ return pattern === value;
41
+ }
42
+
43
+ function valueFor(tool, args = {}) {
44
+ if (tool === 'shell') return String(args.command || '');
45
+ return String(args.file_path || args.path || '');
46
+ }
47
+
48
+ export class TrustStore {
49
+ constructor({ cwd = process.cwd(), policy = {} } = {}) {
50
+ this.cwd = cwd;
51
+ this.policy = policy;
52
+ this.sessionRules = [];
53
+ }
54
+
55
+ loadProjectRules() {
56
+ try {
57
+ const file = trustPath(this.cwd);
58
+ if (!fs.existsSync(file)) return [];
59
+ const data = JSON.parse(fs.readFileSync(file, 'utf-8'));
60
+ return Array.isArray(data.rules) ? data.rules : [];
61
+ } catch {
62
+ return [];
63
+ }
64
+ }
65
+
66
+ saveProjectRules(rules) {
67
+ const file = trustPath(this.cwd);
68
+ fs.mkdirSync(path.dirname(file), { recursive: true });
69
+ fs.writeFileSync(file, JSON.stringify({ version: 1, rules }, null, 2) + '\n');
70
+ }
71
+
72
+ allRules() {
73
+ return [...this.sessionRules, ...this.loadProjectRules()];
74
+ }
75
+
76
+ find(tool, args = {}, tier = '') {
77
+ const value = valueFor(tool, args);
78
+ const rules = this.allRules().filter(rule => rule.tool === tool && matches(rule.pattern, value));
79
+ const deny = rules.find(rule => rule.decision === 'deny');
80
+ if (deny) return { decision: 'deny', rule: deny };
81
+ const allow = rules.find(rule => rule.decision === 'allow');
82
+ if (!allow) return null;
83
+
84
+ const reask = this.shouldReask(allow, args, tier);
85
+ if (reask) return { decision: 'reask', rule: allow, reason: reask };
86
+ return { decision: 'allow', rule: allow };
87
+ }
88
+
89
+ shouldReask(rule, args = {}, tier = '') {
90
+ const reask = rule.reask || {};
91
+ const after = reask.after_minutes ?? this.policy.hitl?.reaskAfterMinutes;
92
+ if (after && rule.created_at) {
93
+ const ageMs = Date.now() - Date.parse(rule.created_at);
94
+ if (Number.isFinite(ageMs) && ageMs > after * 60 * 1000) {
95
+ return `approval expired after ${after}m`;
96
+ }
97
+ }
98
+ if ((reask.on_risk_increase ?? this.policy.hitl?.reaskOnRiskIncrease) && rule.tier && tier) {
99
+ const order = [TIERS.READ, TIERS.SHELL_SAFE, TIERS.LOCAL_EDIT, TIERS.SHELL_MEDIUM, TIERS.NETWORK, TIERS.SHELL_DANGEROUS, TIERS.DESTRUCTIVE];
100
+ if (order.indexOf(tier) > order.indexOf(rule.tier)) return 'risk tier increased';
101
+ }
102
+ if ((this.policy.hitl?.alwaysAskForDangerous ?? true) && (tier === TIERS.SHELL_DANGEROUS || tier === TIERS.DESTRUCTIVE)) {
103
+ return 'dangerous tier requires fresh approval';
104
+ }
105
+ if ((reask.on_command_shape_change ?? this.policy.hitl?.reaskOnCommandShapeChange) && rule.command_shape && args.command) {
106
+ if (rule.command_shape !== commandShape(args.command)) return 'command shape changed';
107
+ }
108
+ return '';
109
+ }
110
+
111
+ add({ tool, args = {}, tier, scope = 'SESSION', decision = 'allow' }) {
112
+ const normalizedScope = String(scope || 'SESSION').toUpperCase();
113
+ const pattern = patternFor(tool, args);
114
+ const id = `${tool}-${crypto.createHash('sha1').update(pattern + normalizedScope).digest('hex').slice(0, 10)}`;
115
+ const ttl = this.policy.hitl?.reaskAfterMinutes ?? 30;
116
+ const rule = {
117
+ id,
118
+ tool,
119
+ pattern,
120
+ scope: normalizedScope,
121
+ decision,
122
+ tier,
123
+ command_shape: tool === 'shell' ? commandShape(args.command) : undefined,
124
+ created_at: nowIso(),
125
+ expires_at: normalizedScope === 'SESSION'
126
+ ? new Date(Date.now() + ttl * 60 * 1000).toISOString()
127
+ : undefined,
128
+ reask: {
129
+ after_minutes: ttl,
130
+ on_command_shape_change: this.policy.hitl?.reaskOnCommandShapeChange ?? true,
131
+ on_risk_increase: this.policy.hitl?.reaskOnRiskIncrease ?? true,
132
+ on_path_boundary_change: this.policy.hitl?.reaskOnPathBoundaryChange ?? true,
133
+ },
134
+ };
135
+ if (normalizedScope === 'PROJECT') {
136
+ const rules = this.loadProjectRules().filter(r => r.id !== id);
137
+ rules.push(rule);
138
+ this.saveProjectRules(rules);
139
+ } else {
140
+ this.sessionRules = this.sessionRules.filter(r => r.id !== id);
141
+ this.sessionRules.push(rule);
142
+ }
143
+ return rule;
144
+ }
145
+
146
+ revoke() {
147
+ const active = this.sessionRules.length > 0;
148
+ this.sessionRules = [];
149
+ return active;
150
+ }
151
+
152
+ summary() {
153
+ return {
154
+ sessionRules: this.sessionRules.length,
155
+ projectRules: this.loadProjectRules().length,
156
+ };
157
+ }
158
+ }
@@ -30,6 +30,7 @@ import { URL } from 'node:url';
30
30
  import { paint } from '../ui/palette.mjs';
31
31
  import { icons } from '../ui/icons.mjs';
32
32
  import { term } from '../ui/term.mjs';
33
+ import { formatMessageWindow, lowWindowStatus } from '../core/rate-limit-display.mjs';
33
34
 
34
35
  const OK = (s) => `${paint.state.success('[✓]')} ${s}`;
35
36
  const WARN = (s) => `${paint.state.warn('[⚠]')} ${s}`;
@@ -37,18 +38,22 @@ const FAIL = (s) => `${paint.state.danger('[✗]')} ${s}`;
37
38
 
38
39
  // ── Individual checks (each returns { status, label, hint? }) ──────────
39
40
 
40
- async function checkAuthAndBackend(auth, { timeoutMs = 2500 } = {}) {
41
+ export async function checkAuthAndBackend(auth, { timeoutMs } = {}) {
41
42
  const creds = auth.loadCredentials();
42
43
  const hasToken = !!creds.token;
43
44
  const url = creds.backendUrl;
45
+ // Local Docker backends round-trip Supabase and often take 2–4s. Give them
46
+ // more headroom so preflight doesn't falsely report Offline.
47
+ const isLocal = /^https?:\/\/(127\.0\.0\.1|localhost)(:|$|\/)/i.test(url || '');
48
+ timeoutMs = timeoutMs ?? (isLocal ? 8000 : 2500);
44
49
 
45
50
  // No token: just probe whether the backend is reachable so we can hint
46
51
  // /login when it makes sense.
47
52
  if (!hasToken) {
48
53
  const reachable = url ? await ping(url, timeoutMs).catch(() => false) : false;
49
54
  return reachable
50
- ? { status: 'warn', label: 'Not signed in · backend ready', hint: '/login to sign in' }
51
- : { status: 'warn', label: 'Not signed in · backend offline', hint: '/login once the network is back' };
55
+ ? { status: 'warn', label: 'Online', hint: '/login to sign in' }
56
+ : { status: 'warn', label: 'Offline' };
52
57
  }
53
58
 
54
59
  // Token present: real authenticated round-trip against /api/user/me.
@@ -66,15 +71,14 @@ async function checkAuthAndBackend(auth, { timeoutMs = 2500 } = {}) {
66
71
 
67
72
  if (resp.ok) {
68
73
  const user = await resp.json().catch(() => null);
69
- const who = user?.github_username || user?.email || 'user';
70
- return { status: 'ok', label: `Signed in as ${who} · connected`, user };
74
+ return { status: 'ok', label: 'Online', user };
71
75
  }
72
76
  if (resp.status === 401 || resp.status === 403) {
73
- return { status: 'warn', label: 'Token expired · connected', hint: '/login again to refresh' };
77
+ return { status: 'warn', label: 'Online', hint: '/login again to refresh' };
74
78
  }
75
- return { status: 'warn', label: `Backend returned ${resp.status}`, hint: 'try again shortly' };
79
+ return { status: 'warn', label: 'Offline' };
76
80
  } catch {
77
- return { status: 'warn', label: 'Signed in · backend offline', hint: 'check network or try again shortly' };
81
+ return { status: 'warn', label: 'Offline' };
78
82
  }
79
83
  }
80
84
 
@@ -86,7 +90,7 @@ async function checkAuthAndBackend(auth, { timeoutMs = 2500 } = {}) {
86
90
  * { status, label } — shown as a preflight row
87
91
  * null — silent (e.g. BYOK or no signal)
88
92
  */
89
- async function checkCreditsAndPlan(auth, { timeoutMs = 2000 } = {}) {
93
+ export async function checkCreditsAndPlan(auth, { timeoutMs = 2000 } = {}) {
90
94
  const creds = auth.loadCredentials();
91
95
  if (!creds.token || !creds.backendUrl) return null;
92
96
  try {
@@ -103,10 +107,22 @@ async function checkCreditsAndPlan(auth, { timeoutMs = 2000 } = {}) {
103
107
  const data = await resp.json().catch(() => null);
104
108
  if (!data) return null;
105
109
 
110
+ const tier = (data.tier || 'free').toUpperCase();
111
+ const windowLabel = formatMessageWindow(data.rate_limit);
112
+ if (windowLabel) {
113
+ const status = lowWindowStatus(data.rate_limit);
114
+ if (status === 'exhausted') {
115
+ return { status: 'fail', label: windowLabel, hint: 'message window exhausted — try again after reset' };
116
+ }
117
+ if (status === 'low') {
118
+ return { status: 'warn', label: windowLabel, hint: 'low message window — codekepler.ai/pricing' };
119
+ }
120
+ return { status: 'ok', label: windowLabel };
121
+ }
122
+
106
123
  if (data.byok_enabled) {
107
- return { status: 'ok', label: `Plan: ${(data.tier || 'byok').toUpperCase()} · billed by your provider` };
124
+ return { status: 'ok', label: `Plan: ${tier || 'BYOK'} · billed by your provider` };
108
125
  }
109
- const tier = (data.tier || 'free').toUpperCase();
110
126
  const remaining = data.balance?.total;
111
127
  if (typeof remaining !== 'number') {
112
128
  return { status: 'ok', label: `Plan: ${tier}` };
@@ -144,6 +144,41 @@ function containsCommandSubstitution(command) {
144
144
  return false;
145
145
  }
146
146
 
147
+ function isQuotedMessage(text) {
148
+ const value = String(text || '').trim();
149
+ return /^echo\s+(?:"[^"]*"|'[^']*'|[A-Za-z0-9_ .:-]+)$/.test(value);
150
+ }
151
+
152
+ function isNumericKillCommand(command) {
153
+ const trimmed = String(command || '').trim();
154
+ return /^kill\s+(?:-(?:\d+|[A-Z]+)\s+)?\d+(?:\s+\d+)*\s*(?:2>\s*\/dev\/null)?$/.test(trimmed);
155
+ }
156
+
157
+ function isPortLsofKillSubstitution(command) {
158
+ const trimmed = String(command || '').trim();
159
+ return /^kill\s+(?:-(?:\d+|[A-Z]+)\s+)?\$\(\s*lsof\s+-ti:?\d+\s*\)\s*(?:2>\s*\/dev\/null)?$/.test(trimmed);
160
+ }
161
+
162
+ function isPortLsofXargsKill(command) {
163
+ const trimmed = String(command || '').trim();
164
+ return /^lsof\s+-ti:?\d+\s*\|\s*xargs\s+kill(?:\s+-(?:\d+|[A-Z]+))?\s*(?:2>\s*\/dev\/null)?(?:\s*;\s*echo\s+(?:"[^"]*"|'[^']*'|[A-Za-z0-9_ .:-]+))?$/.test(trimmed);
165
+ }
166
+
167
+ function isApprovedProcessCleanupCommand(command) {
168
+ const trimmed = String(command || '').trim();
169
+ if (!trimmed) return false;
170
+ if (isPortLsofXargsKill(trimmed)) return true;
171
+ const segments = splitCommand(trimmed);
172
+ if (segments.length === 0) return false;
173
+ return segments.every(segment => {
174
+ const sub = segment.trim();
175
+ return isNumericKillCommand(sub) ||
176
+ isPortLsofKillSubstitution(sub) ||
177
+ isPortLsofXargsKill(sub) ||
178
+ isQuotedMessage(sub);
179
+ });
180
+ }
181
+
147
182
  // ═══════════════════════════════════════════════════════════════════
148
183
  // Section 3: Read-Only Command Allowlist
149
184
  // ═══════════════════════════════════════════════════════════════════
@@ -207,6 +242,10 @@ const COMMAND_ALLOWLIST = {
207
242
  find: { flags: { '-name': 'string', '-iname': 'string', '-path': 'string', '-ipath': 'string', '-type': 'string', '-maxdepth': 'number', '-mindepth': 'number', '-newer': 'string', '-size': 'string', '-mtime': 'string', '-atime': 'string', '-ctime': 'string', '-perm': 'string', '-user': 'string', '-group': 'string', '-not': 'none', '!': 'none', '-or': 'none', '-o': 'none', '-and': 'none', '-a': 'none', '-print': 'none', '-print0': 'none', '-empty': 'none', '-readable': 'none', '-writable': 'none', '-executable': 'none', '-follow': 'none', '-L': 'none', '-P': 'none', '-H': 'none', '-xdev': 'none', '-mount': 'none', '-daystart': 'none', '-regextype': 'string', '-regex': 'string', '-iregex': 'string' },
208
243
  blocked: ['-exec', '-execdir', '-ok', '-okdir', '-delete', '-fprint', '-fprint0', '-fls', '-fprintf'] },
209
244
 
245
+ // ── sed (read-only subset — NO -i/--in-place) ──
246
+ sed: { flags: { '-n': 'none', '--quiet': 'none', '--silent': 'none', '-E': 'none', '-r': 'none', '--regexp-extended': 'none', '-e': 'string', '--expression': 'string', '-f': 'string', '--file': 'string', '-l': 'number', '--line-length': 'number', '-u': 'none', '--unbuffered': 'none' },
247
+ blocked: ['-i', '--in-place', '-z', '--null-data', '-s', '--separate'] },
248
+
210
249
  // ── ls ──
211
250
  ls: { flags: { '-l': 'none', '-a': 'none', '-A': 'none', '-h': 'none', '--human-readable': 'none', '-R': 'none', '--recursive': 'none', '-S': 'none', '-t': 'none', '-r': 'none', '--reverse': 'none', '-1': 'none', '-d': 'none', '--directory': 'none', '-F': 'none', '--classify': 'none', '-i': 'none', '--inode': 'none', '-s': 'none', '--size': 'none', '--color': 'string', '--sort': 'string', '--time': 'string', '--group-directories-first': 'none', '-p': 'none', '-G': 'none', '-n': 'none', '--numeric-uid-gid': 'none' } },
212
251
 
@@ -295,6 +334,7 @@ const BLOCKED_PATTERNS = [
295
334
  /curl.*\|\s*(ba)?sh/, // pipe curl to shell
296
335
  /wget.*\|\s*(ba)?sh/, // pipe wget to shell
297
336
  /eval\s*\$\(/, // eval command substitution
337
+ /\bfind\s+\/(?:\s|$)/, // find / scans the whole VM
298
338
  /find\s.*-exec/, // find with -exec (code execution)
299
339
  /find\s.*-delete/, // find with -delete
300
340
  ];
@@ -349,6 +389,7 @@ function validateFlags(tokens, startIdx, config) {
349
389
  if (blocked) {
350
390
  for (const b of blocked) {
351
391
  if (token === b || token.startsWith(b + '=')) return false;
392
+ if (/^-[A-Za-z]$/.test(b) && token.startsWith(b) && token.length > b.length) return false;
352
393
  }
353
394
  }
354
395
 
@@ -449,6 +490,14 @@ export function classifyCommand(command) {
449
490
 
450
491
  const trimmed = command.trim();
451
492
 
493
+ if (isApprovedProcessCleanupCommand(trimmed)) {
494
+ return {
495
+ classification: 'contained',
496
+ reason: 'Process cleanup by numeric PID or lsof port lookup; requires approval',
497
+ highRisk: true,
498
+ };
499
+ }
500
+
452
501
  // ── Step 1: Check for always-blocked patterns ──
453
502
  for (const pattern of BLOCKED_PATTERNS) {
454
503
  if (pattern.test(trimmed)) {
@@ -461,6 +510,10 @@ export function classifyCommand(command) {
461
510
  return { classification: 'blocked', reason: 'Contains command substitution (backticks or $())' };
462
511
  }
463
512
 
513
+ if (containsUnsafeOutputRedirection(trimmed)) {
514
+ return { classification: 'contained', reason: 'Writes shell output via redirection' };
515
+ }
516
+
464
517
  // ── Step 3: Split compound commands and classify each ──
465
518
  const subcommands = splitCommand(trimmed);
466
519
 
@@ -500,6 +553,31 @@ export function classifyCommand(command) {
500
553
  };
501
554
  }
502
555
 
556
+ function containsUnsafeOutputRedirection(command) {
557
+ let inSingle = false;
558
+ let inDouble = false;
559
+ let escaped = false;
560
+ for (let i = 0; i < command.length; i++) {
561
+ const ch = command[i];
562
+ if (escaped) { escaped = false; continue; }
563
+ if (ch === '\\' && !inSingle) { escaped = true; continue; }
564
+ if (ch === "'" && !inDouble) { inSingle = !inSingle; continue; }
565
+ if (ch === '"' && !inSingle) { inDouble = !inDouble; continue; }
566
+ if (inSingle || inDouble || ch !== '>') continue;
567
+
568
+ const prev = command[i - 1] || '';
569
+ const next = command[i + 1] || '';
570
+ if (next === '&') continue;
571
+ let cursor = next === '>' ? i + 2 : i + 1;
572
+ while (/\s/.test(command[cursor] || '')) cursor++;
573
+ const target = command.slice(cursor).match(/^[^\s;&|]+/)?.[0] || '';
574
+ if (target === '/dev/null') continue;
575
+ if (prev === '2' && target === '/dev/null') continue;
576
+ return true;
577
+ }
578
+ return false;
579
+ }
580
+
503
581
  /**
504
582
  * Classify a single (non-compound) command.
505
583
  */
@@ -0,0 +1,145 @@
1
+ import * as fs from 'node:fs';
2
+ import * as path from 'node:path';
3
+
4
+ const FILES = {
5
+ 'README.md': `# .kepler/ - project agent context
6
+
7
+ Kepler reads and writes here to keep state between sessions.
8
+
9
+ ## Files Kepler writes
10
+ - \`plan.md\` - current agent plan
11
+ - \`goal.md\` - durable session goal
12
+ - \`tasks/\` - task list
13
+ - \`reports/*.md\` - end-of-turn mission reports
14
+ - \`sessions/*.jsonl\` - turn transcripts
15
+ - \`commands.log\` - command executions
16
+ - \`approvals.log\` - HITL decisions
17
+ - \`trust.json\` - approved patterns
18
+
19
+ ## Files you can write
20
+ - \`config.json\` - project policy
21
+ - \`project.md\` - durable project context
22
+ - \`style.md\` - codebase conventions
23
+ - \`hitl.md\` - approval guidance
24
+ - \`skills/<name>/SKILL.md\` - reusable domain skills
25
+
26
+ Format v1. Markdown files are intentionally hand-editable.
27
+ `,
28
+ 'config.json': JSON.stringify({
29
+ version: 1,
30
+ context: {
31
+ loadEveryTurn: ['KEPLER.md', 'project.md', 'style.md', 'goal.md', 'plan.md', 'tasks/*.md'],
32
+ showReloadNotice: true,
33
+ },
34
+ planning: { owner: 'auto', onUserEditedPlan: 'prefer_user_plan' },
35
+ tasks: { storage: 'project_markdown', syncTodoWrite: true, resumePrompt: true },
36
+ hitl: {
37
+ defaultScope: 'once',
38
+ allowSessionTrust: true,
39
+ allowProjectTrust: false,
40
+ reaskAfterMinutes: 30,
41
+ },
42
+ commands: {
43
+ enabled: ['map', 'probe', 'footprint', 'heal', 'align', 'distill', 'brief', 'rewind'],
44
+ dryRunDefault: false,
45
+ },
46
+ }, null, 2) + '\n',
47
+ 'settings.json': JSON.stringify({
48
+ env: {},
49
+ permissions: {
50
+ shellAllowlist: ['git', 'npm', 'pnpm'],
51
+ editDenylist: ['**/*.env', 'secrets/**'],
52
+ },
53
+ hooks: {
54
+ UserPromptSubmit: [],
55
+ PreToolUse: [],
56
+ PostToolUse: [],
57
+ Stop: [],
58
+ },
59
+ }, null, 2) + '\n',
60
+ 'KEPLER.md': `# Project
61
+
62
+ ## Quick Facts
63
+ - Stack:
64
+ - Test command:
65
+ - Lint command:
66
+ - Build command:
67
+
68
+ ## Key Directories
69
+
70
+ ## Code Style
71
+
72
+ ## Critical Rules
73
+ `,
74
+ 'project.md': '# Project Context\n\nAdd durable project context here.\n',
75
+ 'style.md': '# Style\n\nAdd code and communication conventions here.\n',
76
+ 'hitl.md': '# HITL Guidance\n\nAdd project-specific approval guidance here.\n',
77
+ 'trust.json': JSON.stringify({ version: 1, rules: [] }, null, 2) + '\n',
78
+ 'tasks/README.md': `# Kepler Tasks
79
+
80
+ Checklist files are read every turn.
81
+
82
+ - \`backlog.md\` - pending tasks
83
+ - \`active.md\` - current task
84
+ - \`done.md\` - completed tasks
85
+ - \`blocked.md\` - waiting on input
86
+ `,
87
+ 'tasks/backlog.md': '# Backlog\n\n',
88
+ 'tasks/active.md': '# Active\n\n',
89
+ 'tasks/done.md': '# Done\n\n',
90
+ 'tasks/blocked.md': '# Blocked\n\n',
91
+ 'skills/starter/SKILL.md': `---
92
+ name: starter
93
+ description: Project-specific conventions and setup notes. Use when onboarding to this repo.
94
+ ---
95
+
96
+ # Starter Skill
97
+
98
+ Add reusable project knowledge here.
99
+ `,
100
+ 'commands/onboard.md': `---
101
+ name: onboard
102
+ description: Explore the project and record onboarding notes.
103
+ ---
104
+
105
+ # Onboard
106
+
107
+ Context:
108
+ $ARGUMENTS
109
+
110
+ Explore the codebase, ask clarifying questions, and record useful notes in .kepler/tasks/active.md.
111
+ `,
112
+ };
113
+
114
+ export function scaffoldKeplerProject({ cwd = process.cwd(), force = false } = {}) {
115
+ const root = path.join(cwd, '.kepler');
116
+ const written = [];
117
+ const skipped = [];
118
+ for (const [rel, content] of Object.entries(FILES)) {
119
+ const filePath = path.join(root, rel);
120
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
121
+ if (fs.existsSync(filePath) && !force) {
122
+ skipped.push(filePath);
123
+ continue;
124
+ }
125
+ fs.writeFileSync(filePath, content);
126
+ written.push(filePath);
127
+ }
128
+
129
+ const gitignore = path.join(root, '.gitignore');
130
+ if (!fs.existsSync(gitignore) || force) {
131
+ fs.writeFileSync(gitignore, 'settings.local.json\nsessions/\nreports/\n*.log\n');
132
+ written.push(gitignore);
133
+ }
134
+
135
+ return { root, written, skipped };
136
+ }
137
+
138
+ export async function runInitCommand(args = [], { cwd = process.cwd() } = {}) {
139
+ const force = args.includes('--force');
140
+ const result = scaffoldKeplerProject({ cwd, force });
141
+ process.stderr.write(`\x1b[32m✓\x1b[0m Initialized .kepler at ${result.root}\n`);
142
+ process.stderr.write(` wrote ${result.written.length} files`);
143
+ if (result.skipped.length) process.stderr.write(`, skipped ${result.skipped.length} existing files`);
144
+ process.stderr.write('\n');
145
+ }
@@ -47,6 +47,12 @@ async function main() {
47
47
  return;
48
48
  }
49
49
 
50
+ if (subcommand === 'init') {
51
+ const { runInitCommand } = await import('./init.mjs');
52
+ await runInitCommand(subcommandArgs);
53
+ return;
54
+ }
55
+
50
56
  if (subcommand === 'skills' || subcommand === 'skill') {
51
57
  const { runSkillsCommand } = await import('./skills.mjs');
52
58
  try {
@@ -103,6 +109,7 @@ async function main() {
103
109
  kepler dashboard Open Kepler Pulse analytics dashboard
104
110
  kepler login Sign in via browser
105
111
  kepler logout Sign out and clear credentials
112
+ kepler init Scaffold .kepler config, memory, hooks, tasks
106
113
  kepler version Show version
107
114
 
108
115
  \x1b[1mAnalytics:\x1b[0m