karajan-code 1.2.3 → 1.4.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.
package/README.md CHANGED
@@ -36,7 +36,9 @@ Instead of running one AI agent and manually reviewing its output, `kj` chains a
36
36
  - **Review profiles** — standard, strict, relaxed, paranoid
37
37
  - **Budget tracking** — per-session token and cost monitoring with `--trace`
38
38
  - **Git automation** — auto-commit, auto-push, auto-PR after approval
39
- - **Session management** — pause/resume with fail-fast detection
39
+ - **Session management** — pause/resume with fail-fast detection and automatic cleanup of expired sessions
40
+ - **Plugin system** — extend with custom agents via `.karajan/plugins/`
41
+ - **Retry with backoff** — automatic recovery from transient API errors (429, 5xx) with exponential backoff and jitter
40
42
  - **Planning Game integration** — optionally pair with [Planning Game](https://github.com/AgenteIA-Geniova/planning-game) for agile project management (tasks, sprints, estimation) — like Jira, but open-source and XP-native
41
43
 
42
44
  > **Best with MCP** — Karajan Code is designed to be used as an MCP server inside your AI agent (Claude, Codex, etc.). The agent sends tasks to `kj_run`, gets real-time progress notifications, and receives structured results — no copy-pasting needed.
@@ -428,7 +430,7 @@ Use `kj roles show <role>` to inspect any template. Create a project override to
428
430
  git clone https://github.com/manufosela/karajan-code.git
429
431
  cd karajan-code
430
432
  npm install
431
- npm test # Run 761+ tests with Vitest
433
+ npm test # Run 899+ tests with Vitest
432
434
  npm run test:watch # Watch mode
433
435
  npm run validate # Lint + test
434
436
  ```
@@ -439,6 +441,7 @@ npm run validate # Lint + test
439
441
 
440
442
  ## Links
441
443
 
444
+ - [Website](https://karajancode.com) (also [kj-code.com](https://kj-code.com))
442
445
  - [Changelog](CHANGELOG.md)
443
446
  - [Security Policy](SECURITY.md)
444
447
  - [License (AGPL-3.0)](LICENSE)
package/docs/README.es.md CHANGED
@@ -36,7 +36,9 @@ En lugar de ejecutar un agente de IA y revisar manualmente su output, `kj` encad
36
36
  - **Perfiles de revision** — standard, strict, relaxed, paranoid
37
37
  - **Tracking de presupuesto** — monitorizacion de tokens y costes por sesion con `--trace`
38
38
  - **Automatizacion Git** — auto-commit, auto-push, auto-PR tras aprobacion
39
- - **Gestion de sesiones** — pausa/reanudacion con deteccion fail-fast
39
+ - **Gestion de sesiones** — pausa/reanudacion con deteccion fail-fast y limpieza automatica de sesiones expiradas
40
+ - **Sistema de plugins** — extiende con agentes custom via `.karajan/plugins/`
41
+ - **Retry con backoff** — recuperacion automatica ante errores transitorios de API (429, 5xx) con backoff exponencial y jitter
40
42
  - **Integracion con Planning Game** — combina opcionalmente con [Planning Game](https://github.com/AgenteIA-Geniova/planning-game) para gestion agil de proyectos (tareas, sprints, estimacion) — como Jira, pero open-source y nativo XP
41
43
 
42
44
  > **Mejor con MCP** — Karajan Code esta disenado para usarse como servidor MCP dentro de tu agente de IA (Claude, Codex, etc.). El agente envia tareas a `kj_run`, recibe notificaciones de progreso en tiempo real, y obtiene resultados estructurados — sin copiar y pegar.
@@ -227,7 +229,7 @@ Usa `kj roles show <rol>` para inspeccionar cualquier template. Crea un override
227
229
  git clone https://github.com/manufosela/karajan-code.git
228
230
  cd karajan-code
229
231
  npm install
230
- npm test # Ejecutar 761+ tests con Vitest
232
+ npm test # Ejecutar 899+ tests con Vitest
231
233
  npm run test:watch # Modo watch
232
234
  npm run validate # Lint + test
233
235
  ```
@@ -238,6 +240,7 @@ npm run validate # Lint + test
238
240
 
239
241
  ## Enlaces
240
242
 
243
+ - [Web](https://karajancode.com) (tambien [kj-code.com](https://kj-code.com))
241
244
  - [Changelog](../CHANGELOG.md)
242
245
  - [Politica de seguridad](../SECURITY.md)
243
246
  - [Licencia (AGPL-3.0)](../LICENSE)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "karajan-code",
3
- "version": "1.2.3",
3
+ "version": "1.4.0",
4
4
  "description": "Local multi-agent coding orchestrator with TDD, SonarQube, and code review pipeline",
5
5
  "type": "module",
6
6
  "license": "AGPL-3.0",
package/src/cli.js CHANGED
@@ -71,6 +71,7 @@ program
71
71
  .option("--max-total-minutes <n>")
72
72
  .option("--base-branch <name>")
73
73
  .option("--base-ref <ref>")
74
+ .option("--coder-fallback <name>")
74
75
  .option("--reviewer-fallback <name>")
75
76
  .option("--reviewer-retries <n>")
76
77
  .option("--auto-commit")
package/src/config.js CHANGED
@@ -33,7 +33,7 @@ const DEFAULTS = {
33
33
  review_rules: "./review-rules.md",
34
34
  coder_rules: "./coder-rules.md",
35
35
  base_branch: "main",
36
- coder_options: { model: null, auto_approve: true },
36
+ coder_options: { model: null, auto_approve: true, fallback_coder: null },
37
37
  reviewer_options: {
38
38
  output_format: "json",
39
39
  require_schema: true,
@@ -114,10 +114,18 @@ const DEFAULTS = {
114
114
  max_sonar_retries: 3,
115
115
  max_reviewer_retries: 3,
116
116
  max_tester_retries: 1,
117
- max_security_retries: 1
117
+ max_security_retries: 1,
118
+ expiry_days: 30
118
119
  },
119
120
  failFast: {
120
121
  repeatThreshold: 2
122
+ },
123
+ retry: {
124
+ max_attempts: 3,
125
+ initial_backoff_ms: 1000,
126
+ max_backoff_ms: 30000,
127
+ backoff_multiplier: 2,
128
+ jitter_factor: 0.1
121
129
  }
122
130
  };
123
131
 
@@ -232,6 +240,7 @@ export function applyRunOverrides(config, flags) {
232
240
  if (flags.maxIterationMinutes) out.session.max_iteration_minutes = Number(flags.maxIterationMinutes);
233
241
  if (flags.maxTotalMinutes) out.session.max_total_minutes = Number(flags.maxTotalMinutes);
234
242
  if (flags.baseBranch) out.base_branch = flags.baseBranch;
243
+ if (flags.coderFallback) out.coder_options.fallback_coder = flags.coderFallback;
235
244
  if (flags.reviewerFallback) out.reviewer_options.fallback_reviewer = flags.reviewerFallback;
236
245
  if (flags.reviewerRetries !== undefined) out.reviewer_options.retries = Number(flags.reviewerRetries);
237
246
  if (flags.autoCommit !== undefined) out.git.auto_commit = Boolean(flags.autoCommit);
@@ -0,0 +1,83 @@
1
+ import { createAgent } from "../agents/index.js";
2
+ import { addCheckpoint } from "../session-store.js";
3
+ import { detectRateLimit } from "../utils/rate-limit-detector.js";
4
+
5
+ /**
6
+ * Run a coder-like role with fallback on rate limit.
7
+ * Tries the primary agent first. If it fails with a rate limit,
8
+ * switches to the fallback agent (if configured).
9
+ * Non-rate-limit failures stop immediately (no fallback).
10
+ *
11
+ * Returns { execResult, attempts, allRateLimited }
12
+ */
13
+ export async function runCoderWithFallback({
14
+ coderName,
15
+ fallbackCoder,
16
+ config,
17
+ logger,
18
+ emitter,
19
+ RoleClass,
20
+ roleInput,
21
+ session,
22
+ iteration,
23
+ onAttemptResult
24
+ }) {
25
+ const candidates = [coderName];
26
+ if (fallbackCoder && fallbackCoder !== coderName) {
27
+ candidates.push(fallbackCoder);
28
+ }
29
+
30
+ const attempts = [];
31
+ let allRateLimited = true;
32
+
33
+ for (const name of candidates) {
34
+ const agentConfig = {
35
+ ...config,
36
+ roles: { ...config.roles, coder: { ...config.roles?.coder, provider: name } }
37
+ };
38
+
39
+ const role = new RoleClass({ config: agentConfig, logger, emitter, createAgentFn: createAgent });
40
+ await role.init();
41
+
42
+ const execResult = await role.execute(roleInput);
43
+
44
+ if (onAttemptResult) {
45
+ await onAttemptResult({ coder: name, result: execResult.result });
46
+ }
47
+
48
+ const rateLimited = !execResult.ok && detectRateLimit({
49
+ stderr: execResult.result?.error || "",
50
+ stdout: execResult.result?.output || ""
51
+ }).isRateLimit;
52
+
53
+ attempts.push({
54
+ coder: name,
55
+ ok: execResult.ok,
56
+ rateLimited,
57
+ result: execResult.result,
58
+ execResult
59
+ });
60
+
61
+ await addCheckpoint(session, {
62
+ stage: "coder-attempt",
63
+ iteration,
64
+ coder: name,
65
+ ok: execResult.ok,
66
+ rateLimited
67
+ });
68
+
69
+ if (execResult.ok) {
70
+ return { execResult, attempts, allRateLimited: false };
71
+ }
72
+
73
+ // Only fallback on rate limit errors
74
+ if (!rateLimited) {
75
+ allRateLimited = false;
76
+ return { execResult: null, attempts, allRateLimited: false };
77
+ }
78
+
79
+ logger.warn(`Agent ${name} hit rate limit, trying fallback...`);
80
+ }
81
+
82
+ return { execResult: null, attempts, allRateLimited };
83
+ }
@@ -1,4 +1,5 @@
1
1
  import { createAgent } from "../agents/index.js";
2
+ import { CoderRole } from "../roles/coder-role.js";
2
3
  import { RefactorerRole } from "../roles/refactorer-role.js";
3
4
  import { SonarRole } from "../roles/sonar-role.js";
4
5
  import { addCheckpoint, markSessionStatus, saveSession, pauseSession } from "../session-store.js";
@@ -7,7 +8,9 @@ import { evaluateTddPolicy } from "../review/tdd-policy.js";
7
8
  import { validateReviewResult } from "../review/schema.js";
8
9
  import { emitProgress, makeEvent } from "../utils/events.js";
9
10
  import { runReviewerWithFallback } from "./reviewer-fallback.js";
11
+ import { runCoderWithFallback } from "./agent-fallback.js";
10
12
  import { invokeSolomon } from "./solomon-escalation.js";
13
+ import { detectRateLimit } from "../utils/rate-limit-detector.js";
11
14
 
12
15
  export async function runCoderStage({ coderRoleInstance, coderRole, config, logger, emitter, eventBase, session, plannedTask, trackBudget, iteration }) {
13
16
  logger.setContext({ iteration, stage: "coder" });
@@ -35,8 +38,70 @@ export async function runCoderStage({ coderRoleInstance, coderRole, config, logg
35
38
  trackBudget({ role: "coder", provider: coderRole.provider, model: coderRole.model, result: coderExecResult.result, duration_ms: Date.now() - coderStart });
36
39
 
37
40
  if (!coderExecResult.ok) {
38
- await markSessionStatus(session, "failed");
39
41
  const details = coderExecResult.result?.error || coderExecResult.summary || "unknown error";
42
+ const rateLimitCheck = detectRateLimit({
43
+ stderr: coderExecResult.result?.error || "",
44
+ stdout: coderExecResult.result?.output || ""
45
+ });
46
+
47
+ if (rateLimitCheck.isRateLimit) {
48
+ // Try fallback agent if configured
49
+ const fallbackCoder = config.coder_options?.fallback_coder;
50
+ if (fallbackCoder && fallbackCoder !== coderRole.provider) {
51
+ logger.warn(`Coder ${coderRole.provider} hit rate limit, falling back to ${fallbackCoder}`);
52
+ emitProgress(
53
+ emitter,
54
+ makeEvent("coder:fallback", { ...eventBase, stage: "coder" }, {
55
+ message: `Coder ${coderRole.provider} rate-limited, switching to ${fallbackCoder}`,
56
+ detail: { primary: coderRole.provider, fallback: fallbackCoder }
57
+ })
58
+ );
59
+
60
+ const fallbackResult = await runCoderWithFallback({
61
+ coderName: fallbackCoder,
62
+ fallbackCoder: null,
63
+ config,
64
+ logger,
65
+ emitter,
66
+ RoleClass: CoderRole,
67
+ roleInput: { task: plannedTask, reviewerFeedback: session.last_reviewer_feedback, sonarSummary: session.last_sonar_summary, onOutput: coderOnOutput },
68
+ session,
69
+ iteration,
70
+ onAttemptResult: ({ coder, result }) => {
71
+ trackBudget({ role: "coder", provider: coder, model: coderRole.model, result, duration_ms: Date.now() - coderStart });
72
+ }
73
+ });
74
+
75
+ if (fallbackResult.execResult?.ok) {
76
+ await addCheckpoint(session, { stage: "coder", iteration, note: `Coder completed via fallback (${fallbackCoder})` });
77
+ emitProgress(
78
+ emitter,
79
+ makeEvent("coder:end", { ...eventBase, stage: "coder" }, {
80
+ message: `Coder completed (fallback: ${fallbackCoder})`
81
+ })
82
+ );
83
+ return;
84
+ }
85
+ }
86
+
87
+ // No fallback or fallback also failed — pause
88
+ const question = `Agent ${coderRole.provider} hit a rate limit: ${rateLimitCheck.message}. Session paused until the token window resets.`;
89
+ await pauseSession(session, {
90
+ question,
91
+ context: { iteration, stage: "coder", reason: "rate_limit", agent: coderRole.provider, detail: rateLimitCheck.message }
92
+ });
93
+ emitProgress(
94
+ emitter,
95
+ makeEvent("coder:rate_limit", { ...eventBase, stage: "coder" }, {
96
+ status: "paused",
97
+ message: question,
98
+ detail: { agent: coderRole.provider, rateLimitMessage: rateLimitCheck.message, sessionId: session.id }
99
+ })
100
+ );
101
+ return { action: "pause", result: { paused: true, sessionId: session.id, question, context: "rate_limit" } };
102
+ }
103
+
104
+ await markSessionStatus(session, "failed");
40
105
  emitProgress(
41
106
  emitter,
42
107
  makeEvent("coder:end", { ...eventBase, stage: "coder" }, {
@@ -71,8 +136,30 @@ export async function runRefactorerStage({ refactorerRole, config, logger, emitt
71
136
  const refResult = await refRole.execute(plannedTask);
72
137
  trackBudget({ role: "refactorer", provider: refactorerRole.provider, model: refactorerRole.model, result: refResult.result, duration_ms: Date.now() - refactorerStart });
73
138
  if (!refResult.ok) {
74
- await markSessionStatus(session, "failed");
75
139
  const details = refResult.result?.error || refResult.summary || "unknown error";
140
+ const rateLimitCheck = detectRateLimit({
141
+ stderr: refResult.result?.error || "",
142
+ stdout: refResult.result?.output || ""
143
+ });
144
+
145
+ if (rateLimitCheck.isRateLimit) {
146
+ const question = `Agent ${refactorerRole.provider} hit a rate limit: ${rateLimitCheck.message}. Session paused until the token window resets.`;
147
+ await pauseSession(session, {
148
+ question,
149
+ context: { iteration, stage: "refactorer", reason: "rate_limit", agent: refactorerRole.provider, detail: rateLimitCheck.message }
150
+ });
151
+ emitProgress(
152
+ emitter,
153
+ makeEvent("refactorer:rate_limit", { ...eventBase, stage: "refactorer" }, {
154
+ status: "paused",
155
+ message: question,
156
+ detail: { agent: refactorerRole.provider, rateLimitMessage: rateLimitCheck.message, sessionId: session.id }
157
+ })
158
+ );
159
+ return { action: "pause", result: { paused: true, sessionId: session.id, question, context: "rate_limit" } };
160
+ }
161
+
162
+ await markSessionStatus(session, "failed");
76
163
  emitProgress(
77
164
  emitter,
78
165
  makeEvent("refactorer:end", { ...eventBase, stage: "refactorer" }, {
@@ -318,12 +405,35 @@ export async function runReviewerStage({ reviewerRole, config, logger, emitter,
318
405
  });
319
406
 
320
407
  if (!reviewerExec.execResult || !reviewerExec.execResult.ok) {
321
- await markSessionStatus(session, "failed");
322
408
  const lastAttempt = reviewerExec.attempts.at(-1);
323
409
  const details =
324
410
  lastAttempt?.result?.error ||
325
411
  lastAttempt?.execResult?.summary ||
326
412
  `reviewer=${lastAttempt?.reviewer || "unknown"}`;
413
+
414
+ const rateLimitCheck = detectRateLimit({
415
+ stderr: lastAttempt?.result?.error || "",
416
+ stdout: lastAttempt?.result?.output || ""
417
+ });
418
+
419
+ if (rateLimitCheck.isRateLimit) {
420
+ const question = `Reviewer ${reviewerRole.provider} hit a rate limit: ${rateLimitCheck.message}. Session paused until the token window resets.`;
421
+ await pauseSession(session, {
422
+ question,
423
+ context: { iteration, stage: "reviewer", reason: "rate_limit", agent: reviewerRole.provider, detail: rateLimitCheck.message }
424
+ });
425
+ emitProgress(
426
+ emitter,
427
+ makeEvent("reviewer:rate_limit", { ...eventBase, stage: "reviewer" }, {
428
+ status: "paused",
429
+ message: question,
430
+ detail: { agent: reviewerRole.provider, rateLimitMessage: rateLimitCheck.message, sessionId: session.id }
431
+ })
432
+ );
433
+ return { action: "pause", result: { paused: true, sessionId: session.id, question, context: "rate_limit" } };
434
+ }
435
+
436
+ await markSessionStatus(session, "failed");
327
437
  emitProgress(
328
438
  emitter,
329
439
  makeEvent("reviewer:end", { ...eventBase, stage: "reviewer" }, {
@@ -255,11 +255,17 @@ export async function runFlow({ task, config, logger, flags = {}, emitter = null
255
255
  logger.info(`Iteration ${i}/${config.max_iterations}`);
256
256
 
257
257
  // --- Coder ---
258
- await runCoderStage({ coderRoleInstance, coderRole, config, logger, emitter, eventBase, session, plannedTask, trackBudget, iteration: i });
258
+ const coderResult = await runCoderStage({ coderRoleInstance, coderRole, config, logger, emitter, eventBase, session, plannedTask, trackBudget, iteration: i });
259
+ if (coderResult?.action === "pause") {
260
+ return coderResult.result;
261
+ }
259
262
 
260
263
  // --- Refactorer ---
261
264
  if (refactorerEnabled) {
262
- await runRefactorerStage({ refactorerRole, config, logger, emitter, eventBase, session, plannedTask, trackBudget, iteration: i });
265
+ const refResult = await runRefactorerStage({ refactorerRole, config, logger, emitter, eventBase, session, plannedTask, trackBudget, iteration: i });
266
+ if (refResult?.action === "pause") {
267
+ return refResult.result;
268
+ }
263
269
  }
264
270
 
265
271
  // --- TDD Policy ---
@@ -302,6 +308,9 @@ export async function runFlow({ task, config, logger, flags = {}, emitter = null
302
308
  reviewerRole, config, logger, emitter, eventBase, session, trackBudget,
303
309
  iteration: i, reviewRules, task, repeatDetector, budgetSummary
304
310
  });
311
+ if (reviewerResult.action === "pause") {
312
+ return reviewerResult.result;
313
+ }
305
314
  review = reviewerResult.review;
306
315
  if (reviewerResult.stalled) {
307
316
  return reviewerResult.stalledResult;
@@ -9,6 +9,8 @@
9
9
  * Requires planning_game.api_url in config or PG_API_URL env var.
10
10
  */
11
11
 
12
+ import { withRetry, isTransientError } from "../utils/retry.js";
13
+
12
14
  const DEFAULT_API_URL = "http://localhost:3000/api";
13
15
  const DEFAULT_TIMEOUT_MS = 10000;
14
16
 
@@ -20,10 +22,20 @@ async function fetchWithTimeout(url, options = {}, timeoutMs = DEFAULT_TIMEOUT_M
20
22
  const controller = new AbortController();
21
23
  const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
22
24
  try {
23
- return await fetch(url, { ...options, signal: controller.signal });
25
+ const response = await fetch(url, { ...options, signal: controller.signal });
26
+ if (!response.ok) {
27
+ const err = new Error(`Planning Game API error: ${response.status} ${response.statusText}`);
28
+ err.httpStatus = response.status;
29
+ err.retryAfter = response.headers?.get?.("retry-after") || null;
30
+ throw err;
31
+ }
32
+ return response;
24
33
  } catch (error) {
34
+ if (error?.httpStatus) throw error;
25
35
  if (error?.name === "AbortError") {
26
- throw new Error(`Planning Game API timeout after ${timeoutMs}ms`);
36
+ const err = new Error(`Planning Game API timeout after ${timeoutMs}ms`);
37
+ err.httpStatus = 408;
38
+ throw err;
27
39
  }
28
40
  throw new Error(`Planning Game network error: ${error?.message || "unknown error"}`);
29
41
  } finally {
@@ -31,6 +43,13 @@ async function fetchWithTimeout(url, options = {}, timeoutMs = DEFAULT_TIMEOUT_M
31
43
  }
32
44
  }
33
45
 
46
+ async function fetchWithRetry(url, options = {}, timeoutMs = DEFAULT_TIMEOUT_MS, retryOpts = {}) {
47
+ return withRetry(
48
+ () => fetchWithTimeout(url, options, timeoutMs),
49
+ { maxAttempts: 3, initialBackoffMs: 1000, ...retryOpts }
50
+ );
51
+ }
52
+
34
53
  async function parseJsonResponse(response) {
35
54
  try {
36
55
  return await response.json();
@@ -41,10 +60,7 @@ async function parseJsonResponse(response) {
41
60
 
42
61
  export async function fetchCard({ projectId, cardId, timeoutMs = DEFAULT_TIMEOUT_MS }) {
43
62
  const url = `${getApiUrl()}/projects/${encodeURIComponent(projectId)}/cards/${encodeURIComponent(cardId)}`;
44
- const response = await fetchWithTimeout(url, {}, timeoutMs);
45
- if (!response.ok) {
46
- throw new Error(`Planning Game API error: ${response.status} ${response.statusText}`);
47
- }
63
+ const response = await fetchWithRetry(url, {}, timeoutMs);
48
64
  const data = await parseJsonResponse(response);
49
65
  return data?.card || data;
50
66
  }
@@ -55,27 +71,21 @@ export async function getCard({ projectId, cardId, timeoutMs = DEFAULT_TIMEOUT_M
55
71
 
56
72
  export async function listCards({ projectId, timeoutMs = DEFAULT_TIMEOUT_MS }) {
57
73
  const url = `${getApiUrl()}/projects/${encodeURIComponent(projectId)}/cards`;
58
- const response = await fetchWithTimeout(url, {}, timeoutMs);
59
- if (!response.ok) {
60
- throw new Error(`Planning Game API error: ${response.status} ${response.statusText}`);
61
- }
74
+ const response = await fetchWithRetry(url, {}, timeoutMs);
62
75
  const data = await parseJsonResponse(response);
63
76
  return data?.cards || data;
64
77
  }
65
78
 
66
79
  export async function updateCard({ projectId, cardId, firebaseId, updates, timeoutMs = DEFAULT_TIMEOUT_MS }) {
67
80
  const url = `${getApiUrl()}/projects/${encodeURIComponent(projectId)}/cards/${encodeURIComponent(firebaseId)}`;
68
- const response = await fetchWithTimeout(
81
+ const response = await fetchWithRetry(
69
82
  url,
70
83
  {
71
- method: "PATCH",
72
- headers: { "Content-Type": "application/json" },
73
- body: JSON.stringify({ updates })
84
+ method: "PATCH",
85
+ headers: { "Content-Type": "application/json" },
86
+ body: JSON.stringify({ updates })
74
87
  },
75
88
  timeoutMs
76
89
  );
77
- if (!response.ok) {
78
- throw new Error(`Planning Game API error: ${response.status} ${response.statusText}`);
79
- }
80
90
  return parseJsonResponse(response);
81
91
  }
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Plugin loader: discovers and loads plugins from .karajan/plugins/ directories.
3
+ *
4
+ * Plugins are JS files that export a `register(api)` function.
5
+ * The `api` object provides: registerAgent, registerModel.
6
+ *
7
+ * Discovery order (all are loaded, not first-wins):
8
+ * 1. <project>/.karajan/plugins/*.js
9
+ * 2. ~/.karajan/plugins/*.js
10
+ */
11
+
12
+ import path from "node:path";
13
+ import { pathToFileURL } from "node:url";
14
+ import { getKarajanHome } from "../utils/paths.js";
15
+ import { registerAgent } from "../agents/index.js";
16
+
17
+ async function listPluginFiles(dir) {
18
+ try {
19
+ const { readdir } = await import("node:fs/promises");
20
+ const entries = await readdir(dir, { withFileTypes: true });
21
+ return entries
22
+ .filter((e) => e.isFile() && e.name.endsWith(".js"))
23
+ .map((e) => path.join(dir, e.name));
24
+ } catch {
25
+ return [];
26
+ }
27
+ }
28
+
29
+ async function loadPlugin(filePath, api, logger) {
30
+ try {
31
+ const mod = await import(pathToFileURL(filePath).href);
32
+ const registerFn = mod.register || mod.default?.register;
33
+ if (typeof registerFn !== "function") {
34
+ logger?.warn?.(`Plugin ${filePath}: no register() export found, skipping`);
35
+ return null;
36
+ }
37
+ const meta = registerFn(api);
38
+ const name = meta?.name || path.basename(filePath, ".js");
39
+ logger?.debug?.(`Plugin loaded: ${name} (${filePath})`);
40
+ return { name, path: filePath, meta };
41
+ } catch (error) {
42
+ logger?.warn?.(`Plugin ${filePath} failed to load: ${error.message}`);
43
+ return null;
44
+ }
45
+ }
46
+
47
+ export async function loadPlugins({ projectDir, logger } = {}) {
48
+ const dirs = [];
49
+
50
+ if (projectDir) {
51
+ dirs.push(path.join(projectDir, ".karajan", "plugins"));
52
+ }
53
+ dirs.push(path.join(getKarajanHome(), "plugins"));
54
+
55
+ const api = { registerAgent };
56
+
57
+ const loaded = [];
58
+ for (const dir of dirs) {
59
+ const files = await listPluginFiles(dir);
60
+ for (const file of files) {
61
+ const result = await loadPlugin(file, api, logger);
62
+ if (result) loaded.push(result);
63
+ }
64
+ }
65
+
66
+ return loaded;
67
+ }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Automatic cleanup of expired sessions.
3
+ * Removes session directories older than session.expiry_days (default: 30).
4
+ */
5
+
6
+ import fs from "node:fs/promises";
7
+ import path from "node:path";
8
+ import { getSessionRoot } from "./utils/paths.js";
9
+
10
+ const DEFAULT_EXPIRY_DAYS = 30;
11
+
12
+ export async function cleanupExpiredSessions({ config, logger } = {}) {
13
+ const expiryDays = config?.session?.expiry_days ?? DEFAULT_EXPIRY_DAYS;
14
+ if (expiryDays <= 0) return { removed: 0, errors: [] };
15
+
16
+ const sessionRoot = getSessionRoot();
17
+ const cutoff = Date.now() - expiryDays * 24 * 60 * 60 * 1000;
18
+
19
+ let entries;
20
+ try {
21
+ entries = await fs.readdir(sessionRoot, { withFileTypes: true });
22
+ } catch {
23
+ return { removed: 0, errors: [] };
24
+ }
25
+
26
+ const dirs = entries.filter((e) => e.isDirectory() && e.name.startsWith("s_"));
27
+ const removed = [];
28
+ const errors = [];
29
+
30
+ for (const dir of dirs) {
31
+ const sessionDir = path.join(sessionRoot, dir.name);
32
+ const sessionFile = path.join(sessionDir, "session.json");
33
+
34
+ try {
35
+ const raw = await fs.readFile(sessionFile, "utf8");
36
+ const session = JSON.parse(raw);
37
+ const updatedAt = new Date(session.updated_at || session.created_at).getTime();
38
+
39
+ if (updatedAt < cutoff) {
40
+ await fs.rm(sessionDir, { recursive: true, force: true });
41
+ removed.push(dir.name);
42
+ logger?.debug?.(`Session expired and removed: ${dir.name}`);
43
+ }
44
+ } catch (error) {
45
+ const stat = await fs.stat(sessionDir).catch(() => null);
46
+ if (stat && stat.mtimeMs < cutoff) {
47
+ try {
48
+ await fs.rm(sessionDir, { recursive: true, force: true });
49
+ removed.push(dir.name);
50
+ logger?.debug?.(`Orphan session dir removed: ${dir.name}`);
51
+ } catch (rmErr) {
52
+ errors.push({ session: dir.name, error: rmErr.message });
53
+ }
54
+ }
55
+ }
56
+ }
57
+
58
+ if (removed.length > 0) {
59
+ logger?.info?.(`Cleaned up ${removed.length} expired session(s)`);
60
+ }
61
+
62
+ return { removed: removed.length, errors };
63
+ }
package/src/sonar/api.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { runCommand } from "../utils/process.js";
2
+ import { withRetry } from "../utils/retry.js";
2
3
  import { resolveSonarProjectKey } from "./project-key.js";
3
4
 
4
5
  export class SonarApiError extends Error {
@@ -22,16 +23,18 @@ function parseHttpResponse(stdout) {
22
23
  return { httpCode, body };
23
24
  }
24
25
 
25
- async function sonarFetch(config, urlPath) {
26
+ async function sonarFetchOnce(config, urlPath) {
26
27
  const token = tokenFromConfig(config);
27
28
  const url = `${config.sonarqube.host}${urlPath}`;
28
29
  const res = await runCommand("curl", ["-s", "-w", "\n%{http_code}", "-u", `${token}:`, url]);
29
30
 
30
31
  if (res.exitCode !== 0) {
31
- throw new SonarApiError(
32
+ const err = new SonarApiError(
32
33
  `SonarQube is not reachable at ${config.sonarqube.host}. Check that SonarQube is running ('kj sonar start').`,
33
34
  { url, hint: "Run 'kj sonar start' or verify Docker is running." }
34
35
  );
36
+ err.httpStatus = 503;
37
+ throw err;
35
38
  }
36
39
 
37
40
  const { httpCode, body } = parseHttpResponse(res.stdout);
@@ -44,15 +47,25 @@ async function sonarFetch(config, urlPath) {
44
47
  }
45
48
 
46
49
  if (httpCode >= 400) {
47
- throw new SonarApiError(
50
+ const err = new SonarApiError(
48
51
  `SonarQube API returned HTTP ${httpCode} for ${url}.`,
49
52
  { url, httpStatus: httpCode }
50
53
  );
54
+ err.httpStatus = httpCode;
55
+ throw err;
51
56
  }
52
57
 
53
58
  return body;
54
59
  }
55
60
 
61
+ async function sonarFetch(config, urlPath) {
62
+ const maxAttempts = config.sonarqube?.max_scan_retries ?? 3;
63
+ return withRetry(
64
+ () => sonarFetchOnce(config, urlPath),
65
+ { maxAttempts, initialBackoffMs: 2000, maxBackoffMs: 15000 }
66
+ );
67
+ }
68
+
56
69
  export async function getQualityGateStatus(config, projectKey = null) {
57
70
  const effectiveProjectKey = await resolveSonarProjectKey(config, { projectKey });
58
71
  const body = await sonarFetch(config, `/api/qualitygates/project_status?projectKey=${effectiveProjectKey}`);
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Detects rate limit / usage cap messages from CLI agent output.
3
+ * Returns { isRateLimit, agent, message } where agent is the best guess
4
+ * of which CLI triggered it (or "unknown").
5
+ */
6
+
7
+ const RATE_LIMIT_PATTERNS = [
8
+ // Claude CLI
9
+ { pattern: /usage limit/i, agent: "claude" },
10
+ { pattern: /plan's usage limit/i, agent: "claude" },
11
+ { pattern: /Claude Pro usage limit/i, agent: "claude" },
12
+
13
+ // OpenAI / Codex CLI
14
+ { pattern: /exceeded your current quota/i, agent: "codex" },
15
+
16
+ // Gemini CLI
17
+ { pattern: /resource exhausted/i, agent: "gemini" },
18
+ { pattern: /quota exceeded/i, agent: "gemini" },
19
+
20
+ // Generic (match any agent)
21
+ { pattern: /rate limit/i, agent: "unknown" },
22
+ { pattern: /token limit reached/i, agent: "unknown" },
23
+ { pattern: /\b429\b/, agent: "unknown" },
24
+ { pattern: /too many requests/i, agent: "unknown" },
25
+ { pattern: /throttl/i, agent: "unknown" },
26
+ ];
27
+
28
+ export function detectRateLimit({ stderr = "", stdout = "" }) {
29
+ const combined = `${stderr}\n${stdout}`;
30
+
31
+ for (const { pattern, agent } of RATE_LIMIT_PATTERNS) {
32
+ if (pattern.test(combined)) {
33
+ const matchedLine = combined.split("\n").find((l) => pattern.test(l)) || combined.trim();
34
+ return {
35
+ isRateLimit: true,
36
+ agent,
37
+ message: matchedLine.trim()
38
+ };
39
+ }
40
+ }
41
+
42
+ return { isRateLimit: false, agent: "", message: "" };
43
+ }
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Generic retry utility with exponential backoff and jitter.
3
+ * Handles transient errors (429, 502, 503, timeouts) automatically.
4
+ */
5
+
6
+ const TRANSIENT_HTTP_CODES = new Set([408, 429, 500, 502, 503, 504]);
7
+
8
+ const TRANSIENT_ERROR_PATTERNS = [
9
+ "ETIMEDOUT", "ECONNREFUSED", "ECONNRESET", "EPIPE",
10
+ "ENETUNREACH", "EAI_AGAIN", "EHOSTUNREACH",
11
+ "socket hang up", "network error", "fetch failed"
12
+ ];
13
+
14
+ const DEFAULT_OPTIONS = {
15
+ maxAttempts: 3,
16
+ initialBackoffMs: 1000,
17
+ maxBackoffMs: 30000,
18
+ backoffMultiplier: 2,
19
+ jitterFactor: 0.1,
20
+ onRetry: null
21
+ };
22
+
23
+ export function isTransientError(error) {
24
+ if (!error) return false;
25
+
26
+ if (error.httpStatus && TRANSIENT_HTTP_CODES.has(error.httpStatus)) return true;
27
+ if (error.status && TRANSIENT_HTTP_CODES.has(error.status)) return true;
28
+
29
+ const msg = (error.message || String(error)).toLowerCase();
30
+ return TRANSIENT_ERROR_PATTERNS.some((p) => msg.includes(p.toLowerCase()));
31
+ }
32
+
33
+ export function parseRetryAfter(headerValue) {
34
+ if (!headerValue) return null;
35
+ const seconds = Number(headerValue);
36
+ if (!Number.isNaN(seconds) && seconds > 0) return seconds * 1000;
37
+
38
+ const date = Date.parse(headerValue);
39
+ if (!Number.isNaN(date)) {
40
+ const delayMs = date - Date.now();
41
+ return delayMs > 0 ? delayMs : null;
42
+ }
43
+ return null;
44
+ }
45
+
46
+ export function calculateBackoff(attempt, options = {}) {
47
+ const { initialBackoffMs = 1000, maxBackoffMs = 30000, backoffMultiplier = 2, jitterFactor = 0.1 } = options;
48
+
49
+ const base = initialBackoffMs * Math.pow(backoffMultiplier, attempt);
50
+ const capped = Math.min(base, maxBackoffMs);
51
+ const jitter = capped * jitterFactor * (Math.random() * 2 - 1);
52
+ return Math.max(0, Math.round(capped + jitter));
53
+ }
54
+
55
+ function sleep(ms) {
56
+ return new Promise((resolve) => setTimeout(resolve, ms));
57
+ }
58
+
59
+ export async function withRetry(fn, options = {}) {
60
+ const opts = { ...DEFAULT_OPTIONS, ...options };
61
+ let lastError;
62
+
63
+ for (let attempt = 0; attempt < opts.maxAttempts; attempt++) {
64
+ try {
65
+ return await fn(attempt);
66
+ } catch (error) {
67
+ lastError = error;
68
+
69
+ if (attempt >= opts.maxAttempts - 1) break;
70
+ if (!isTransientError(error)) break;
71
+
72
+ let delayMs = calculateBackoff(attempt, opts);
73
+
74
+ const retryAfterMs = parseRetryAfter(error.retryAfter || error.headers?.get?.("retry-after"));
75
+ if (retryAfterMs) {
76
+ delayMs = Math.min(retryAfterMs, opts.maxBackoffMs);
77
+ }
78
+
79
+ if (opts.onRetry) {
80
+ opts.onRetry({ attempt, error, delayMs, maxAttempts: opts.maxAttempts });
81
+ }
82
+
83
+ await sleep(delayMs);
84
+ }
85
+ }
86
+
87
+ throw lastError;
88
+ }