-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathindex.ts
More file actions
339 lines (306 loc) · 12.7 KB
/
Copy pathindex.ts
File metadata and controls
339 lines (306 loc) · 12.7 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
#!/usr/bin/env bun
import { readFileSync, existsSync } from "node:fs"
import { resolve } from "node:path"
import { setPendingCommand, flushHistorySync } from "./src/cli/history"
const _rawArgs = process.argv.slice(2)
// ── Auto-load .env file ─────────────────────────────────────────────
// Loads .env from project root if it exists (before any other imports).
// Checks multiple paths for compatibility across run modes:
// 1. Script directory (import.meta.dir)
// 2. Current working directory (process.cwd())
// Supports both KEY=value and export KEY=value formats.
// Does NOT override already-set environment variables.
function loadDotEnv(): void {
// Hermetic mode: skip loading any .env / vault files. Used by CI and the
// CLI smoke tests so zero-key guards can be exercised deterministically.
if (process.env["AEGIS_NO_DOTENV"] === "1") return
const candidates = [
import.meta.dir ? resolve(import.meta.dir, ".env") : null,
resolve(process.cwd(), ".env"),
].filter(Boolean) as string[]
const envPath = candidates.find((p) => existsSync(p))
if (envPath) {
try {
const content = readFileSync(envPath, "utf-8")
for (const line of content.split("\n")) {
const trimmed = line.trim()
if (!trimmed || trimmed.startsWith("#")) continue
// Strip optional 'export ' prefix
const cleaned = trimmed.startsWith("export ") ? trimmed.slice(7) : trimmed
const eqIdx = cleaned.indexOf("=")
if (eqIdx <= 0) continue
const key = cleaned.slice(0, eqIdx).trim()
let value = cleaned.slice(eqIdx + 1).trim()
// Strip surrounding quotes if present
if ((value.startsWith('"') && value.endsWith('"')) ||
(value.startsWith("'") && value.endsWith("'"))) {
value = value.slice(1, -1)
}
if (key && !process.env[key]) {
process.env[key] = value
}
}
} catch {
// .env loading is best-effort
}
}
// ── Load vault agent.env (keys from `aegis setup-keys`) ──────────
const homeDir = process.env.HOME || process.env.USERPROFILE
if (homeDir) {
const vaultEnvPath = resolve(homeDir, ".aegis", "agent.env")
if (existsSync(vaultEnvPath)) {
try {
const content = readFileSync(vaultEnvPath, "utf-8")
for (const line of content.split("\n")) {
const trimmed = line.trim()
if (!trimmed || trimmed.startsWith("#")) continue
const eqIdx = trimmed.indexOf("=")
if (eqIdx > 0) {
const key = trimmed.slice(0, eqIdx).trim()
let value = trimmed.slice(eqIdx + 1).trim()
if (key && !process.env[key]) {
process.env[key] = value
}
}
}
} catch {
// agent.env loading is best-effort
}
}
}
// ── Warn if no keys are set at all ───────────────────────────────
// Skip warning for setup-keys and doctor commands since users expect to configure keys there
if (!envPath && !_rawArgs.includes("setup-keys") && !_rawArgs.includes("doctor")) {
const hasAnyKey = [
"AEGIS_AI_API_KEY", "ANTHROPIC_API_KEY", "OPENAI_API_KEY",
"OPENROUTER_API_KEY", "DEEPSEEK_API_KEY", "GEMINI_API_KEY",
"GOOGLE_GENERATIVE_AI_API_KEY", "GROQ_API_KEY", "MISTRAL_API_KEY",
"AZURE_OPENAI_API_KEY", "TOGETHERAI_API_KEY", "XAI_API_KEY",
"COHERE_API_KEY", "PERPLEXITY_API_KEY", "NVIDIA_API_KEY", "CUSTOM_API_KEY",
].some((k) => process.env[k])
if (!hasAnyKey) {
// Warning will be shown after banner by provider-guard if needed
}
}
}
loadDotEnv()
// ── Fast path: --version (skip all heavy module loading) ──────────────
// Static imports are hoisted in ES modules, so we must detect --version
// before any heavy imports are even loaded. We keep only lightweight
// imports (fs, path, history) at the top and defer everything else.
if (_rawArgs.includes("--version") || _rawArgs.includes("-V")) {
let version = "0.0.0"
try {
const dir = import.meta.dir ?? process.cwd()
const pkg = JSON.parse(readFileSync(resolve(dir, "package.json"), "utf-8"))
version = String(pkg.version || "0.0.0")
} catch {
// fallback
}
console.log(version)
process.exit(0)
}
// ── Heavy imports (deferred so --version never loads them) ────────────
// These are loaded lazily via dynamic import() so the --version fast path
// above never pays the ~5s cost of transpiling 100K+ lines of TypeScript.
const { Command } = await import("commander")
const { showBanner } = await import("./src/cli/banner")
const { getVersion } = await import("./src/version")
const { registerAllCommands } = await import("./src/cli/commands")
const { runWakeup } = await import("./src/cli/wakeup")
const { registerErrorBoundaries } = await import("./src/cli/guard")
const { createLogger } = await import("./src/cli/logger")
const { agentManager } = await import("./src/agent/manager")
const { recordCommand, flushOnExit } = await import("./src/telemetry")
const { sessionStore, getProjectSessionStore } = await import("./src/memory/session-persistence")
const { getActiveProject } = await import("./src/project/context")
// ── Auto-register self-improvement system ────────────────────────────
// Wires the ImprovementScheduler cron triggers and the autonomous
// pipeline trigger on startup so self-improvement runs automatically
// without manual CLI invocation.
let _selfImprovementRegistered = false
async function autoRegisterSelfImprovement(): Promise<void> {
if (_selfImprovementRegistered) return
_selfImprovementRegistered = true
try {
const { ImprovementScheduler } = await import("./src/improve/scheduler")
const scheduler = new ImprovementScheduler()
if (!scheduler.hasDefaults()) {
const ids = scheduler.registerDefaults()
log.info(`Auto-registered ${ids.length} self-improvement cron trigger(s)`)
}
// Also register the autonomous pipeline trigger if not already present
const { triggerEngine } = await import("./src/triggers/registry")
const existing = triggerEngine.list({ tag: "auto-improve" })
if (existing.length === 0) {
try {
const { AutoImprovePipeline } = await import("./src/improve/pipeline")
const pipeline = new AutoImprovePipeline()
pipeline.registerAutoTrigger()
log.info("Auto-registered autonomous pipeline cron trigger (every 12h)")
} catch {
// non-critical
}
}
} catch (err) {
// Self-improvement registration is best-effort
log.debug("Failed to register self-improvement triggers", { error: String(err) })
}
}
const log = createLogger("cli")
// Track whether we've already restored sessions (avoid spam on every command)
let sessionsRestored = false
// ── Restore sessions from SQLite on startup ───────────────────────
function restoreRecentSessions(): void {
try {
const project = getActiveProject()
const store = project ? getProjectSessionStore(project) : sessionStore
const recent = store.restoreRecentSessions(5)
if (recent.length > 0) {
const active = recent.filter((s) => s.status === "active")
const lines = [`📂 Restored ${recent.length} session(s) from database`]
for (const s of recent) {
const status = s.status === "active" ? "🟢" : s.status === "failed" ? "🔴" : "⚪"
lines.push(` ${status} ${s.name.slice(0, 40)} — ${s.goal.slice(0, 60) || "(no goal)"}`)
}
if (active.length > 0) {
lines.push(` ${active.length} session(s) still active — use \`aegis session resume <id>\` to continue`)
}
log.info(lines.join("\n"))
}
} catch {
// Session restoration is best-effort
}
}
// ── Graceful Shutdown ─────────────────────────────────────────────────
async function gracefulShutdown(code = 0): Promise<void> {
log.info("Shutting down gracefully...")
// Flush any pending telemetry events
await flushOnExit()
// Kill all running agents with a reasonable timeout
const agentCount = agentManager.agents.size
if (agentCount > 0) {
log.info(`Stopping ${agentCount} agent(s)...`)
try {
await agentManager.destroy()
} catch (err) {
log.error("Error during agent cleanup", { error: String(err) })
}
}
log.info("Shutdown complete")
process.exit(code)
}
// Register signal handlers
process.on("SIGINT", () => {
if ((program as any)._interactive) return
// In child processes spawned from the wakeup menu, skip gracefulShutdown
// (heavy agent/telemetry cleanup) but still exit so the process doesn't
// hang. Give command-specific handlers (telegram, serve, etc.) a chance
// to run their cleanup first via a short delay.
if (process.env.AEGIS_SPAWNED) {
log.debug("SIGINT in spawned child — exiting (command handler may also fire)")
setTimeout(() => process.exit(0), 100)
return
}
log.debug("Received SIGINT")
// eslint-disable-next-line @typescript-eslint/no-floating-promises
gracefulShutdown(0)
})
process.on("SIGTERM", () => {
log.debug("Received SIGTERM")
// eslint-disable-next-line @typescript-eslint/no-floating-promises
gracefulShutdown(0)
})
// Register error boundaries (unhandledRejection, uncaughtException)
registerErrorBoundaries((code: number) => {
if ((program as any)._interactive) {
log.error("Error in interactive mode, returning to menu...")
return
}
return gracefulShutdown(code)
})
// ── CLI Setup ─────────────────────────────────────────────────────────
const program = new Command()
program
.name("Aegis")
.description("The Operating System for Autonomous AI Agents")
.version(getVersion())
registerAllCommands(program)
// Show banner before any command except --help/--version or interactive mode
program.hook("preAction", () => {
if ((program as any)._interactive) return
const args = process.argv.slice(2)
if (
!args.includes("--help") &&
!args.includes("-h") &&
!args.includes("--version") &&
!args.includes("-V")
) {
showBanner()
// Restore recent sessions from SQLite once per process invocation
if (!sessionsRestored) {
sessionsRestored = true
restoreRecentSessions()
}
// Auto-register self-improvement cron triggers on first CLI invocation
autoRegisterSelfImprovement().catch(() => {
// best-effort
})
}
})
// If no args, launch interactive picker
const noArgs = _rawArgs.length === 0
if (noArgs) {
await runWakeup(program)
} else {
// compat alias
program
.command("build [sub]")
.description("Build subcommands (e.g. 'build wakeup')")
.allowUnknownOption()
.action(async (sub?: string) => {
if (sub === "wakeup") {
await runWakeup(program)
} else {
console.log("usage: aegis build wakeup")
}
})
// ── Record command history ──────────────────────────────────────────
// Writes to ~/.aegis/command-history.json for the /history command
// Uses process.on("exit") via setPendingCommand() so history is flushed
// even when signal handlers call process.exit() (skipping the finally block).
const commandName = _rawArgs
.filter((a) => !a.startsWith("-"))
.slice(0, 2)
.map((a) => a.replace(/[^a-zA-Z0-9_-]/g, ""))
.filter(Boolean)
.join(" ") || "(interactive)"
const startTime = Date.now()
let exitCode = 0
let historyWritten = false
setPendingCommand({
command: commandName,
timestamp: new Date().toISOString(),
args: _rawArgs.length > 1 ? _rawArgs.slice(1).join(" ").slice(0, 100) : undefined,
})
// Called both from finally (normal exit) and process 'exit' handler (early
// exit via process.exit() in signal handlers). The flag prevents double-writes.
function writeCommandHistory(code: number): void {
if (historyWritten) return
historyWritten = true
flushHistorySync()
recordCommand(commandName, code === 0, Date.now() - startTime)
}
// 'exit' fires synchronously even when process.exit() is called directly
// (e.g. from adapter SIGINT handlers), ensuring history is always recorded.
process.on("exit", writeCommandHistory)
try {
await program.parseAsync(process.argv)
exitCode = 0
} catch (err) {
exitCode = 1
throw err
} finally {
writeCommandHistory(exitCode)
}
}