-
Notifications
You must be signed in to change notification settings - Fork 132
Expand file tree
/
Copy pathconfig.ts
More file actions
394 lines (352 loc) · 12.4 KB
/
config.ts
File metadata and controls
394 lines (352 loc) · 12.4 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
import { join, isAbsolute } from "path";
import { mkdir } from "fs/promises";
import { existsSync } from "fs";
import { normalizeTimezoneName, resolveTimezoneOffsetMinutes } from "./timezone";
const HEARTBEAT_DIR = join(process.cwd(), ".claude", "claudeclaw");
const SETTINGS_FILE = join(HEARTBEAT_DIR, "settings.json");
const JOBS_DIR = join(HEARTBEAT_DIR, "jobs");
const LOGS_DIR = join(HEARTBEAT_DIR, "logs");
const DEFAULT_SETTINGS: Settings = {
model: "",
api: "",
fallback: {
model: "",
api: "",
},
agentic: {
enabled: false,
defaultMode: "implementation",
modes: [
{
name: "planning",
model: "opus",
keywords: [
"plan", "design", "architect", "strategy", "approach",
"research", "investigate", "analyze", "explore", "understand",
"think", "consider", "evaluate", "assess", "review",
"system design", "trade-off", "decision", "choose", "compare",
"brainstorm", "ideate", "concept", "proposal",
],
phrases: [
"how to implement", "how should i", "what's the best way to",
"should i", "which approach", "help me decide", "help me understand",
],
},
{
name: "implementation",
model: "sonnet",
keywords: [
"implement", "code", "write", "create", "build", "add",
"fix", "debug", "refactor", "update", "modify", "change",
"deploy", "run", "execute", "install", "configure",
"test", "commit", "push", "merge", "release",
"generate", "scaffold", "setup", "initialize",
],
},
],
},
timezone: "UTC",
timezoneOffsetMinutes: 0,
heartbeat: {
enabled: false,
interval: 15,
prompt: "",
excludeWindows: [],
forwardToTelegram: true,
},
telegram: { token: "", allowedUserIds: [] },
discord: { token: "", allowedUserIds: [], listenChannels: [] },
security: { level: "moderate", allowedTools: [], disallowedTools: [] },
web: { enabled: false, host: "127.0.0.1", port: 4632 },
stt: { baseUrl: "", model: "" },
session: { autoRotate: true, maxMessages: 50, maxAgeHours: 24, summaryPath: "" },
};
export interface HeartbeatExcludeWindow {
days?: number[];
start: string;
end: string;
}
export interface HeartbeatConfig {
enabled: boolean;
interval: number;
prompt: string;
excludeWindows: HeartbeatExcludeWindow[];
forwardToTelegram: boolean;
}
export interface TelegramConfig {
token: string;
allowedUserIds: number[];
}
export interface DiscordConfig {
token: string;
allowedUserIds: string[]; // Discord snowflake IDs exceed Number.MAX_SAFE_INTEGER
listenChannels: string[]; // Channel IDs where bot responds to all messages (no mention needed)
}
export type SecurityLevel =
| "locked"
| "strict"
| "moderate"
| "unrestricted";
export interface SecurityConfig {
level: SecurityLevel;
allowedTools: string[];
disallowedTools: string[];
}
export interface Settings {
model: string;
api: string;
fallback: ModelConfig;
agentic: AgenticConfig;
timezone: string;
timezoneOffsetMinutes: number;
heartbeat: HeartbeatConfig;
telegram: TelegramConfig;
discord: DiscordConfig;
security: SecurityConfig;
web: WebConfig;
stt: SttConfig;
session: SessionConfig;
}
export interface AgenticMode {
name: string;
model: string;
keywords: string[];
phrases?: string[];
}
export interface AgenticConfig {
enabled: boolean;
defaultMode: string;
modes: AgenticMode[];
}
export interface ModelConfig {
model: string;
api: string;
}
export interface WebConfig {
enabled: boolean;
host: string;
port: number;
}
export interface SttConfig {
/** Base URL of an OpenAI-compatible STT API, e.g. "http://127.0.0.1:8000".
* When set, claudeclaw routes voice transcription through this API instead
* of the bundled whisper.cpp binary. */
baseUrl: string;
/** Model name passed to the API (default: "Systran/faster-whisper-large-v3") */
model: string;
}
export interface SessionConfig {
autoRotate: boolean;
maxMessages: number;
maxAgeHours: number;
summaryPath: string;
}
let cached: Settings | null = null;
export async function initConfig(): Promise<void> {
await mkdir(HEARTBEAT_DIR, { recursive: true });
await mkdir(JOBS_DIR, { recursive: true });
await mkdir(LOGS_DIR, { recursive: true });
if (!existsSync(SETTINGS_FILE)) {
await Bun.write(SETTINGS_FILE, JSON.stringify(DEFAULT_SETTINGS, null, 2) + "\n");
}
}
const VALID_LEVELS = new Set<SecurityLevel>([
"locked",
"strict",
"moderate",
"unrestricted",
]);
function parseAgenticMode(raw: any): AgenticMode | null {
if (!raw || typeof raw !== "object") return null;
const name = typeof raw.name === "string" ? raw.name.trim() : "";
const model = typeof raw.model === "string" ? raw.model.trim() : "";
if (!name || !model) return null;
const keywords = Array.isArray(raw.keywords)
? raw.keywords.filter((k: unknown) => typeof k === "string").map((k: string) => k.toLowerCase().trim())
: [];
const phrases = Array.isArray(raw.phrases)
? raw.phrases.filter((p: unknown) => typeof p === "string").map((p: string) => p.toLowerCase().trim())
: undefined;
return { name, model, keywords, ...(phrases && phrases.length > 0 ? { phrases } : {}) };
}
function parseAgenticConfig(raw: any): AgenticConfig {
const defaults = DEFAULT_SETTINGS.agentic;
if (!raw || typeof raw !== "object") return defaults;
const enabled = raw.enabled ?? false;
// Backward compat: old planningModel/implementationModel format
if (!Array.isArray(raw.modes) && ("planningModel" in raw || "implementationModel" in raw)) {
const planningModel = typeof raw.planningModel === "string" ? raw.planningModel.trim() : "opus";
const implModel = typeof raw.implementationModel === "string" ? raw.implementationModel.trim() : "sonnet";
return {
enabled,
defaultMode: "implementation",
modes: [
{ ...defaults.modes[0], model: planningModel },
{ ...defaults.modes[1], model: implModel },
],
};
}
// New modes format
const modes: AgenticMode[] = [];
if (Array.isArray(raw.modes)) {
for (const m of raw.modes) {
const parsed = parseAgenticMode(m);
if (parsed) modes.push(parsed);
}
}
return {
enabled,
defaultMode: typeof raw.defaultMode === "string" ? raw.defaultMode.trim() : "implementation",
modes: modes.length > 0 ? modes : defaults.modes,
};
}
function parseSettings(raw: Record<string, any>): Settings {
const rawLevel = raw.security?.level;
const level: SecurityLevel =
typeof rawLevel === "string" && VALID_LEVELS.has(rawLevel as SecurityLevel)
? (rawLevel as SecurityLevel)
: "moderate";
const parsedTimezone = parseTimezone(raw.timezone);
return {
model: typeof raw.model === "string" ? raw.model.trim() : "",
api: typeof raw.api === "string" ? raw.api.trim() : "",
fallback: {
model: typeof raw.fallback?.model === "string" ? raw.fallback.model.trim() : "",
api: typeof raw.fallback?.api === "string" ? raw.fallback.api.trim() : "",
},
agentic: parseAgenticConfig(raw.agentic),
timezone: parsedTimezone,
timezoneOffsetMinutes: parseTimezoneOffsetMinutes(raw.timezoneOffsetMinutes, parsedTimezone),
heartbeat: {
enabled: raw.heartbeat?.enabled ?? false,
interval: raw.heartbeat?.interval ?? 15,
prompt: raw.heartbeat?.prompt ?? "",
excludeWindows: parseExcludeWindows(raw.heartbeat?.excludeWindows),
forwardToTelegram: raw.heartbeat?.forwardToTelegram ?? false,
},
telegram: {
token: raw.telegram?.token ?? "",
allowedUserIds: raw.telegram?.allowedUserIds ?? [],
},
discord: {
token: typeof raw.discord?.token === "string" ? raw.discord.token.trim() : "",
allowedUserIds: discordUserIds && discordUserIds.length > 0
? discordUserIds
: Array.isArray(raw.discord?.allowedUserIds)
? raw.discord.allowedUserIds.map(String)
: [],
listenChannels: Array.isArray(raw.discord?.listenChannels)
? raw.discord.listenChannels.map(String)
: [],
},
security: {
level,
allowedTools: Array.isArray(raw.security?.allowedTools)
? raw.security.allowedTools
: [],
disallowedTools: Array.isArray(raw.security?.disallowedTools)
? raw.security.disallowedTools
: [],
},
web: {
enabled: raw.web?.enabled ?? false,
host: raw.web?.host ?? "127.0.0.1",
port: Number.isFinite(raw.web?.port) ? Number(raw.web.port) : 4632,
},
stt: {
baseUrl: typeof raw.stt?.baseUrl === "string" ? raw.stt.baseUrl.trim() : "",
model: typeof raw.stt?.model === "string" ? raw.stt.model.trim() : "",
},
session: {
autoRotate: raw.session?.autoRotate ?? true,
maxMessages: Number.isFinite(raw.session?.maxMessages) ? Number(raw.session.maxMessages) : 50,
maxAgeHours: Number.isFinite(raw.session?.maxAgeHours) ? Number(raw.session.maxAgeHours) : 24,
summaryPath: typeof raw.session?.summaryPath === "string" ? raw.session.summaryPath.trim() : "",
},
};
}
const TIME_RE = /^([01]\d|2[0-3]):([0-5]\d)$/;
const ALL_DAYS = [0, 1, 2, 3, 4, 5, 6];
function parseTimezone(value: unknown): string {
return normalizeTimezoneName(value);
}
function parseExcludeWindows(value: unknown): HeartbeatExcludeWindow[] {
if (!Array.isArray(value)) return [];
const out: HeartbeatExcludeWindow[] = [];
for (const entry of value) {
if (!entry || typeof entry !== "object") continue;
const start = typeof (entry as any).start === "string" ? (entry as any).start.trim() : "";
const end = typeof (entry as any).end === "string" ? (entry as any).end.trim() : "";
if (!TIME_RE.test(start) || !TIME_RE.test(end)) continue;
const rawDays = Array.isArray((entry as any).days) ? (entry as any).days : [];
const parsedDays = rawDays
.map((d: unknown) => Number(d))
.filter((d: number) => Number.isInteger(d) && d >= 0 && d <= 6);
const uniqueDays = Array.from(new Set<number>(parsedDays)).sort((a: number, b: number) => a - b);
out.push({
start,
end,
days: uniqueDays.length > 0 ? uniqueDays : [...ALL_DAYS],
});
}
return out;
}
function parseTimezoneOffsetMinutes(value: unknown, timezoneFallback?: string): number {
return resolveTimezoneOffsetMinutes(value, timezoneFallback);
}
/**
* Extract discord.allowedUserIds as raw strings from the JSON text.
* JSON.parse destroys precision on large numeric snowflakes (>2^53),
* so we regex them out of the raw text first.
*/
function extractDiscordUserIds(rawText: string): string[] {
// Match the "discord" object's "allowedUserIds" array values
const discordBlock = rawText.match(/"discord"\s*:\s*\{[\s\S]*?\}/);
if (!discordBlock) return [];
const arrayMatch = discordBlock[0].match(/"allowedUserIds"\s*:\s*\[([\s\S]*?)\]/);
if (!arrayMatch) return [];
const items: string[] = [];
// Match both quoted strings and bare numbers
for (const m of arrayMatch[1].matchAll(/("(\d+)"|(\d+))/g)) {
items.push(m[2] ?? m[3]);
}
return items;
}
export async function loadSettings(): Promise<Settings> {
if (cached) return cached;
const rawText = await Bun.file(SETTINGS_FILE).text();
const raw = JSON.parse(rawText);
cached = parseSettings(raw, extractDiscordUserIds(rawText));
return cached;
}
/** Re-read settings from disk, bypassing cache. */
export async function reloadSettings(): Promise<Settings> {
const rawText = await Bun.file(SETTINGS_FILE).text();
const raw = JSON.parse(rawText);
cached = parseSettings(raw, extractDiscordUserIds(rawText));
return cached;
}
export function getSettings(): Settings {
if (!cached) throw new Error("Settings not loaded. Call loadSettings() first.");
return cached;
}
const PROMPT_EXTENSIONS = [".md", ".txt", ".prompt"];
/**
* If the prompt string looks like a file path (ends with .md, .txt, or .prompt),
* read and return the file contents. Otherwise return the string as-is.
* Relative paths are resolved from the project root (cwd).
*/
export async function resolvePrompt(prompt: string): Promise<string> {
const trimmed = prompt.trim();
if (!trimmed) return trimmed;
const isPath = PROMPT_EXTENSIONS.some((ext) => trimmed.endsWith(ext));
if (!isPath) return trimmed;
const resolved = isAbsolute(trimmed) ? trimmed : join(process.cwd(), trimmed);
try {
const content = await Bun.file(resolved).text();
return content.trim();
} catch {
console.warn(`[config] Prompt path "${trimmed}" not found, using as literal string`);
return trimmed;
}
}