juno-code 1.0.47 → 1.0.50

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.
Files changed (60) hide show
  1. package/README.md +455 -205
  2. package/dist/bin/cli.d.mts +17 -0
  3. package/dist/bin/cli.d.ts +17 -0
  4. package/dist/bin/cli.js +6456 -17604
  5. package/dist/bin/cli.js.map +1 -1
  6. package/dist/bin/cli.mjs +6443 -17589
  7. package/dist/bin/cli.mjs.map +1 -1
  8. package/dist/bin/feedback-collector.d.mts +2 -0
  9. package/dist/bin/feedback-collector.d.ts +2 -0
  10. package/dist/bin/feedback-collector.js.map +1 -1
  11. package/dist/bin/feedback-collector.mjs.map +1 -1
  12. package/dist/index.d.mts +2133 -0
  13. package/dist/index.d.ts +2133 -0
  14. package/dist/index.js +3916 -14711
  15. package/dist/index.js.map +1 -1
  16. package/dist/index.mjs +3914 -14516
  17. package/dist/index.mjs.map +1 -1
  18. package/dist/templates/extensions/pi/juno-skill-preprocessor.ts +239 -0
  19. package/dist/templates/scripts/__pycache__/github.cpython-313.pyc +0 -0
  20. package/dist/templates/scripts/__pycache__/parallel_runner.cpython-313.pyc +0 -0
  21. package/dist/templates/scripts/__pycache__/slack_respond.cpython-313.pyc +0 -0
  22. package/dist/templates/scripts/install_requirements.sh +41 -3
  23. package/dist/templates/scripts/kanban.sh +22 -4
  24. package/dist/templates/scripts/parallel_runner.sh +2242 -0
  25. package/dist/templates/services/README.md +61 -1
  26. package/dist/templates/services/__pycache__/claude.cpython-313.pyc +0 -0
  27. package/dist/templates/services/__pycache__/codex.cpython-313.pyc +0 -0
  28. package/dist/templates/services/__pycache__/pi.cpython-313.pyc +0 -0
  29. package/dist/templates/services/claude.py +132 -33
  30. package/dist/templates/services/codex.py +179 -66
  31. package/dist/templates/services/gemini.py +117 -27
  32. package/dist/templates/services/pi.py +2796 -0
  33. package/dist/templates/skills/claude/kanban-workflow/SKILL.md +138 -0
  34. package/dist/templates/skills/claude/plan-kanban-tasks/SKILL.md +15 -8
  35. package/dist/templates/skills/claude/ralph-loop/SKILL.md +18 -22
  36. package/dist/templates/skills/claude/ralph-loop/references/first_check.md +15 -14
  37. package/dist/templates/skills/claude/ralph-loop/references/implement.md +17 -17
  38. package/dist/templates/skills/claude/ralph-loop/scripts/kanban.sh +22 -4
  39. package/dist/templates/skills/claude/understand-project/SKILL.md +15 -8
  40. package/dist/templates/skills/codex/kanban-workflow/SKILL.md +139 -0
  41. package/dist/templates/skills/codex/plan-kanban-tasks/SKILL.md +32 -0
  42. package/dist/templates/skills/codex/ralph-loop/SKILL.md +18 -22
  43. package/dist/templates/skills/codex/ralph-loop/references/first_check.md +15 -14
  44. package/dist/templates/skills/codex/ralph-loop/references/implement.md +17 -17
  45. package/dist/templates/skills/codex/ralph-loop/scripts/kanban.sh +22 -4
  46. package/dist/templates/skills/codex/understand-project/SKILL.md +46 -0
  47. package/dist/templates/skills/pi/.gitkeep +0 -0
  48. package/dist/templates/skills/pi/kanban-workflow/SKILL.md +139 -0
  49. package/dist/templates/skills/pi/plan-kanban-tasks/SKILL.md +32 -0
  50. package/dist/templates/skills/pi/ralph-loop/SKILL.md +43 -0
  51. package/dist/templates/skills/pi/ralph-loop/references/first_check.md +21 -0
  52. package/dist/templates/skills/pi/ralph-loop/references/implement.md +99 -0
  53. package/dist/templates/skills/pi/understand-project/SKILL.md +46 -0
  54. package/package.json +26 -46
  55. package/dist/templates/scripts/__pycache__/attachment_downloader.cpython-38.pyc +0 -0
  56. package/dist/templates/scripts/__pycache__/github.cpython-38.pyc +0 -0
  57. package/dist/templates/scripts/__pycache__/slack_fetch.cpython-38.pyc +0 -0
  58. package/dist/templates/scripts/__pycache__/slack_state.cpython-38.pyc +0 -0
  59. package/dist/templates/services/__pycache__/claude.cpython-38.pyc +0 -0
  60. package/dist/templates/services/__pycache__/codex.cpython-38.pyc +0 -0
@@ -0,0 +1,2133 @@
1
+ import { z } from 'zod';
2
+ import { EventEmitter } from 'node:events';
3
+
4
+ /**
5
+ * Core type definitions for juno-code
6
+ */
7
+ type SubagentType = 'claude' | 'cursor' | 'codex' | 'gemini' | 'pi';
8
+ type BackendType = 'shell';
9
+ type SessionStatus = 'running' | 'completed' | 'failed' | 'cancelled';
10
+ type LogLevel = 'error' | 'warn' | 'info' | 'debug' | 'trace';
11
+ type OnHourlyLimit = 'wait' | 'raise';
12
+ type HookType$1 = 'START_RUN' | 'START_ITERATION' | 'END_ITERATION' | 'END_RUN' | 'ON_STALE';
13
+ interface Hook$1 {
14
+ commands: string[];
15
+ }
16
+ type Hooks = Record<HookType$1, Hook$1>;
17
+ type ProgressEventType$1 = 'tool_start' | 'tool_result' | 'thinking' | 'error' | 'info';
18
+ interface JunoTaskConfig {
19
+ defaultSubagent: SubagentType;
20
+ defaultMaxIterations: number;
21
+ defaultModel?: string;
22
+ defaultBackend: BackendType;
23
+ mainTask?: string;
24
+ logLevel: LogLevel;
25
+ logFile?: string;
26
+ /** Verbosity level: 0=quiet, 1=normal+helping texts (default), 2=debug+hooks */
27
+ verbose: number;
28
+ quiet: boolean;
29
+ mcpTimeout: number;
30
+ mcpRetries: number;
31
+ mcpServerPath?: string;
32
+ mcpServerName?: string;
33
+ hookCommandTimeout?: number;
34
+ onHourlyLimit: OnHourlyLimit;
35
+ interactive: boolean;
36
+ headlessMode: boolean;
37
+ workingDirectory: string;
38
+ sessionDirectory: string;
39
+ /** Path to project env file loaded on startup (relative to workingDirectory or absolute) */
40
+ envFilePath?: string;
41
+ /** Tracks whether the configured env file has been initialized from .env.juno */
42
+ envFileCopied?: boolean;
43
+ hooks?: Hooks;
44
+ skipHooks?: boolean;
45
+ }
46
+ declare global {
47
+ const __VERSION__: string;
48
+ const __DEV__: boolean;
49
+ }
50
+
51
+ /**
52
+ * Core configuration module for juno-code
53
+ *
54
+ * Provides comprehensive configuration management with multi-source loading,
55
+ * validation, and environment variable support.
56
+ *
57
+ * @module core/config
58
+ */
59
+
60
+ /**
61
+ * Environment variable mapping for configuration options
62
+ * All config options can be set via JUNO_CODE_* environment variables
63
+ * Uses JUNO_CODE_* environment variables
64
+ */
65
+ declare const ENV_VAR_MAPPING: {
66
+ readonly JUNO_CODE_DEFAULT_SUBAGENT: "defaultSubagent";
67
+ readonly JUNO_CODE_DEFAULT_BACKEND: "defaultBackend";
68
+ readonly JUNO_CODE_DEFAULT_MAX_ITERATIONS: "defaultMaxIterations";
69
+ readonly JUNO_CODE_DEFAULT_MODEL: "defaultModel";
70
+ readonly JUNO_CODE_LOG_LEVEL: "logLevel";
71
+ readonly JUNO_CODE_LOG_FILE: "logFile";
72
+ readonly JUNO_CODE_VERBOSE: "verbose";
73
+ readonly JUNO_CODE_QUIET: "quiet";
74
+ readonly JUNO_CODE_MCP_TIMEOUT: "mcpTimeout";
75
+ readonly JUNO_CODE_MCP_RETRIES: "mcpRetries";
76
+ readonly JUNO_CODE_MCP_SERVER_PATH: "mcpServerPath";
77
+ readonly JUNO_CODE_MCP_SERVER_NAME: "mcpServerName";
78
+ readonly JUNO_CODE_HOOK_COMMAND_TIMEOUT: "hookCommandTimeout";
79
+ readonly JUNO_CODE_ON_HOURLY_LIMIT: "onHourlyLimit";
80
+ readonly JUNO_CODE_INTERACTIVE: "interactive";
81
+ readonly JUNO_CODE_HEADLESS_MODE: "headlessMode";
82
+ readonly JUNO_CODE_WORKING_DIRECTORY: "workingDirectory";
83
+ readonly JUNO_CODE_SESSION_DIRECTORY: "sessionDirectory";
84
+ };
85
+ /**
86
+ * Zod schema for validating JunoTaskConfig
87
+ * Provides runtime validation with detailed error messages
88
+ */
89
+ declare const JunoTaskConfigSchema: z.ZodObject<{
90
+ defaultSubagent: z.ZodEnum<["claude", "cursor", "codex", "gemini", "pi"]>;
91
+ defaultBackend: z.ZodEnum<["shell"]>;
92
+ defaultMaxIterations: z.ZodNumber;
93
+ defaultModel: z.ZodOptional<z.ZodString>;
94
+ mainTask: z.ZodOptional<z.ZodString>;
95
+ logLevel: z.ZodEnum<["error", "warn", "info", "debug", "trace"]>;
96
+ logFile: z.ZodOptional<z.ZodString>;
97
+ verbose: z.ZodEffects<z.ZodNumber, number, unknown>;
98
+ quiet: z.ZodBoolean;
99
+ mcpTimeout: z.ZodNumber;
100
+ mcpRetries: z.ZodNumber;
101
+ mcpServerPath: z.ZodOptional<z.ZodString>;
102
+ mcpServerName: z.ZodOptional<z.ZodString>;
103
+ hookCommandTimeout: z.ZodOptional<z.ZodNumber>;
104
+ onHourlyLimit: z.ZodEnum<["wait", "raise"]>;
105
+ interactive: z.ZodBoolean;
106
+ headlessMode: z.ZodBoolean;
107
+ workingDirectory: z.ZodString;
108
+ sessionDirectory: z.ZodString;
109
+ envFilePath: z.ZodOptional<z.ZodString>;
110
+ envFileCopied: z.ZodOptional<z.ZodBoolean>;
111
+ hooks: z.ZodOptional<z.ZodRecord<z.ZodEnum<["START_RUN", "START_ITERATION", "END_ITERATION", "END_RUN", "ON_STALE"]>, z.ZodObject<{
112
+ commands: z.ZodArray<z.ZodString, "many">;
113
+ }, "strip", z.ZodTypeAny, {
114
+ commands?: string[];
115
+ }, {
116
+ commands?: string[];
117
+ }>>>;
118
+ skipHooks: z.ZodOptional<z.ZodBoolean>;
119
+ }, "strict", z.ZodTypeAny, {
120
+ defaultSubagent?: "claude" | "cursor" | "codex" | "gemini" | "pi";
121
+ defaultBackend?: "shell";
122
+ defaultMaxIterations?: number;
123
+ defaultModel?: string;
124
+ logLevel?: "error" | "warn" | "info" | "debug" | "trace";
125
+ logFile?: string;
126
+ verbose?: number;
127
+ quiet?: boolean;
128
+ mcpTimeout?: number;
129
+ mcpRetries?: number;
130
+ mcpServerPath?: string;
131
+ mcpServerName?: string;
132
+ hookCommandTimeout?: number;
133
+ onHourlyLimit?: "wait" | "raise";
134
+ interactive?: boolean;
135
+ headlessMode?: boolean;
136
+ workingDirectory?: string;
137
+ sessionDirectory?: string;
138
+ mainTask?: string;
139
+ envFilePath?: string;
140
+ envFileCopied?: boolean;
141
+ hooks?: Partial<Record<"START_RUN" | "START_ITERATION" | "END_ITERATION" | "END_RUN" | "ON_STALE", {
142
+ commands?: string[];
143
+ }>>;
144
+ skipHooks?: boolean;
145
+ }, {
146
+ defaultSubagent?: "claude" | "cursor" | "codex" | "gemini" | "pi";
147
+ defaultBackend?: "shell";
148
+ defaultMaxIterations?: number;
149
+ defaultModel?: string;
150
+ logLevel?: "error" | "warn" | "info" | "debug" | "trace";
151
+ logFile?: string;
152
+ verbose?: unknown;
153
+ quiet?: boolean;
154
+ mcpTimeout?: number;
155
+ mcpRetries?: number;
156
+ mcpServerPath?: string;
157
+ mcpServerName?: string;
158
+ hookCommandTimeout?: number;
159
+ onHourlyLimit?: "wait" | "raise";
160
+ interactive?: boolean;
161
+ headlessMode?: boolean;
162
+ workingDirectory?: string;
163
+ sessionDirectory?: string;
164
+ mainTask?: string;
165
+ envFilePath?: string;
166
+ envFileCopied?: boolean;
167
+ hooks?: Partial<Record<"START_RUN" | "START_ITERATION" | "END_ITERATION" | "END_RUN" | "ON_STALE", {
168
+ commands?: string[];
169
+ }>>;
170
+ skipHooks?: boolean;
171
+ }>;
172
+ /**
173
+ * Default configuration values
174
+ * These are used as fallbacks when no other configuration is provided
175
+ */
176
+ declare const DEFAULT_CONFIG: JunoTaskConfig;
177
+ /**
178
+ * ConfigLoader class for multi-source configuration loading
179
+ *
180
+ * Implements configuration precedence: CLI args > Environment Variables > Project Config > Global Config Files > Profile > Defaults
181
+ */
182
+ declare class ConfigLoader {
183
+ private baseDir;
184
+ private configSources;
185
+ /**
186
+ * Create a new ConfigLoader instance
187
+ *
188
+ * @param baseDir - Base directory for relative path resolution
189
+ */
190
+ constructor(baseDir?: string);
191
+ /**
192
+ * Load configuration from environment variables
193
+ *
194
+ * @returns This ConfigLoader instance for method chaining
195
+ */
196
+ fromEnvironment(): this;
197
+ /**
198
+ * Load configuration from a specific file
199
+ *
200
+ * @param filePath - Path to configuration file
201
+ * @returns This ConfigLoader instance for method chaining
202
+ */
203
+ fromFile(filePath: string): Promise<this>;
204
+ /**
205
+ * Load configuration from project-specific config file
206
+ * Loads from .juno_task/config.json with highest precedence for project settings
207
+ *
208
+ * @returns This ConfigLoader instance for method chaining
209
+ */
210
+ fromProjectConfig(): Promise<this>;
211
+ /**
212
+ * Automatically discover and load configuration files
213
+ * Searches for both project-specific and global config files in the base directory
214
+ * Project-specific config (.juno_task/config.json) takes precedence over global configs
215
+ *
216
+ * @returns This ConfigLoader instance for method chaining
217
+ */
218
+ autoDiscoverFile(): Promise<this>;
219
+ /**
220
+ * Load configuration from CLI arguments
221
+ *
222
+ * @param cliConfig - Configuration object from CLI argument parsing
223
+ * @returns This ConfigLoader instance for method chaining
224
+ */
225
+ fromCli(cliConfig: Partial<JunoTaskConfig>): this;
226
+ /**
227
+ * Merge all configuration sources according to precedence
228
+ * CLI args > Environment Variables > Project Config > Global Config Files > Defaults
229
+ *
230
+ * @returns Merged configuration object
231
+ */
232
+ merge(): JunoTaskConfig;
233
+ /**
234
+ * Load and merge configuration from all sources
235
+ * Convenience method that performs auto-discovery and returns validated config
236
+ *
237
+ * @param cliConfig - Optional CLI configuration
238
+ * @returns Promise resolving to validated configuration
239
+ */
240
+ loadAll(cliConfig?: Partial<JunoTaskConfig>): Promise<JunoTaskConfig>;
241
+ }
242
+ /**
243
+ * Validate configuration object against schema
244
+ *
245
+ * @param config - Configuration object to validate
246
+ * @returns Validated configuration object
247
+ * @throws Error if validation fails
248
+ */
249
+ declare function validateConfig(config: unknown): JunoTaskConfig;
250
+ /**
251
+ * Load and validate configuration from all sources
252
+ *
253
+ * This is the main entry point for configuration loading.
254
+ * It performs auto-discovery, merging, and validation.
255
+ *
256
+ * @param options - Configuration loading options
257
+ * @param options.baseDir - Base directory for relative path resolution
258
+ * @param options.configFile - Specific configuration file to load
259
+ * @param options.cliConfig - CLI configuration override
260
+ * @returns Promise resolving to validated configuration
261
+ *
262
+ * @example
263
+ * ```typescript
264
+ * // Load with auto-discovery
265
+ * const config = await loadConfig();
266
+ *
267
+ * // Load with specific file
268
+ * const config = await loadConfig({
269
+ * configFile: './my-config.json'
270
+ * });
271
+ *
272
+ * // Load with CLI overrides
273
+ * const config = await loadConfig({
274
+ * cliConfig: { verbose: true, logLevel: 'debug' }
275
+ * });
276
+ * ```
277
+ */
278
+ declare function loadConfig(options?: {
279
+ baseDir?: string;
280
+ configFile?: string;
281
+ cliConfig?: Partial<JunoTaskConfig>;
282
+ }): Promise<JunoTaskConfig>;
283
+ /**
284
+ * Type export for configuration loading options
285
+ */
286
+ type ConfigLoadOptions = Parameters<typeof loadConfig>[0];
287
+ /**
288
+ * Type export for environment variable mapping
289
+ */
290
+ type EnvVarMapping = typeof ENV_VAR_MAPPING;
291
+
292
+ /**
293
+ * Default hooks template configuration
294
+ *
295
+ * This module provides default hook commands that are shipped with juno-code.
296
+ * These hooks are automatically configured during project initialization (init command).
297
+ *
298
+ * Hook Types:
299
+ * - START_RUN: Executes at the beginning of a run (before all iterations)
300
+ * - START_ITERATION: Executes at the start of each iteration
301
+ * - END_ITERATION: Executes at the end of each iteration
302
+ * - END_RUN: Executes at the end of a run (after all iterations)
303
+ *
304
+ * To modify default hooks:
305
+ * 1. Update the commands in this file
306
+ * 2. Rebuild the project (npm run build)
307
+ * 3. New installations will use the updated defaults
308
+ *
309
+ * @module templates/default-hooks
310
+ */
311
+
312
+ /**
313
+ * Default hooks configuration template
314
+ *
315
+ * All hook types are included so users can see available hooks without reading documentation.
316
+ * Empty command arrays indicate hooks that are available but not configured by default.
317
+ *
318
+ * These hooks provide useful default behaviors:
319
+ * - File size monitoring for CLAUDE.md, AGENTS.md, .juno_task/plan.md, .juno_task/tasks.md
320
+ * - Alerts via juno-kanban when documentation/task files become too large
321
+ *
322
+ * Users can customize these hooks by editing .juno_task/config.json after initialization
323
+ */
324
+ declare const DEFAULT_HOOKS: Hooks;
325
+ /**
326
+ * Get default hooks configuration
327
+ *
328
+ * Returns a copy of the default hooks to prevent mutation of the template.
329
+ * This function can be used during initialization to populate the config.json file.
330
+ *
331
+ * @returns A copy of the default hooks configuration
332
+ */
333
+ declare function getDefaultHooks(): Hooks;
334
+ /**
335
+ * Get default hooks as formatted JSON string for config.json
336
+ *
337
+ * @param indent - Number of spaces for indentation (default: 2)
338
+ * @returns Formatted JSON string of default hooks
339
+ */
340
+ declare function getDefaultHooksJson(indent?: number): string;
341
+
342
+ /**
343
+ * Execution error definitions for juno-task-ts
344
+ *
345
+ * Provides comprehensive error classes and utilities for execution operations,
346
+ * including error codes, context tracking, recovery suggestions, and
347
+ * specialized error types for different failure scenarios.
348
+ *
349
+ * Originally migrated from the MCP error module. The MCP system has been
350
+ * removed; these are now the canonical execution error definitions.
351
+ * Deprecated MCP-prefixed aliases are retained below for backward compatibility.
352
+ *
353
+ * @module core/errors
354
+ * @version 2.0.0
355
+ */
356
+ /**
357
+ * Execution error categories for targeted error handling
358
+ */
359
+ declare enum ExecutionErrorType {
360
+ CONNECTION = "connection",
361
+ TIMEOUT = "timeout",
362
+ RATE_LIMIT = "rate_limit",
363
+ TOOL_EXECUTION = "tool_execution",
364
+ VALIDATION = "validation",
365
+ SERVER_NOT_FOUND = "server_not_found",
366
+ PROTOCOL = "protocol",
367
+ AUTHENTICATION = "authentication"
368
+ }
369
+ /**
370
+ * Error codes for specific error conditions
371
+ */
372
+ declare enum ExecutionErrorCode {
373
+ CONNECTION_FAILED = "MCP_CONNECTION_FAILED",
374
+ CONNECTION_TIMEOUT = "MCP_CONNECTION_TIMEOUT",
375
+ CONNECTION_REFUSED = "MCP_CONNECTION_REFUSED",
376
+ CONNECTION_LOST = "MCP_CONNECTION_LOST",
377
+ RECONNECTION_FAILED = "MCP_RECONNECTION_FAILED",
378
+ TOOL_NOT_FOUND = "MCP_TOOL_NOT_FOUND",
379
+ TOOL_EXECUTION_FAILED = "MCP_TOOL_EXECUTION_FAILED",
380
+ TOOL_TIMEOUT = "MCP_TOOL_TIMEOUT",
381
+ TOOL_INVALID_ARGUMENTS = "MCP_TOOL_INVALID_ARGUMENTS",
382
+ RATE_LIMIT_EXCEEDED = "MCP_RATE_LIMIT_EXCEEDED",
383
+ RATE_LIMIT_HOURLY = "MCP_RATE_LIMIT_HOURLY",
384
+ RATE_LIMIT_DAILY = "MCP_RATE_LIMIT_DAILY",
385
+ VALIDATION_FAILED = "MCP_VALIDATION_FAILED",
386
+ INVALID_REQUEST = "MCP_INVALID_REQUEST",
387
+ MISSING_PARAMETERS = "MCP_MISSING_PARAMETERS",
388
+ INVALID_PARAMETERS = "MCP_INVALID_PARAMETERS",
389
+ SERVER_NOT_FOUND = "MCP_SERVER_NOT_FOUND",
390
+ SERVER_NOT_EXECUTABLE = "MCP_SERVER_NOT_EXECUTABLE",
391
+ SERVER_STARTUP_FAILED = "MCP_SERVER_STARTUP_FAILED",
392
+ SERVER_CRASHED = "MCP_SERVER_CRASHED",
393
+ PROTOCOL_ERROR = "MCP_PROTOCOL_ERROR",
394
+ INVALID_RESPONSE = "MCP_INVALID_RESPONSE",
395
+ VERSION_MISMATCH = "MCP_VERSION_MISMATCH",
396
+ AUTHENTICATION_FAILED = "MCP_AUTHENTICATION_FAILED",
397
+ UNAUTHORIZED = "MCP_UNAUTHORIZED",
398
+ TOKEN_EXPIRED = "MCP_TOKEN_EXPIRED"
399
+ }
400
+ /**
401
+ * Base error options for execution errors
402
+ */
403
+ interface ExecutionErrorOptions {
404
+ /** Error code for programmatic handling */
405
+ readonly code?: ExecutionErrorCode | undefined;
406
+ /** Operation context when error occurred */
407
+ readonly context?: string | undefined;
408
+ /** Retry information */
409
+ readonly retryInfo?: RetryInfo | undefined;
410
+ /** Recovery suggestions for the user */
411
+ readonly recoverySuggestions?: readonly string[] | undefined;
412
+ /** Cause error for error chaining */
413
+ readonly cause?: Error | undefined;
414
+ /** Additional metadata */
415
+ readonly metadata?: Readonly<Record<string, unknown>> | undefined;
416
+ }
417
+ /**
418
+ * Retry information for error context
419
+ */
420
+ interface RetryInfo {
421
+ /** Current attempt number */
422
+ readonly attempt: number;
423
+ /** Maximum attempts allowed */
424
+ readonly maxAttempts: number;
425
+ /** Next retry time */
426
+ readonly nextRetryTime?: Date;
427
+ /** Retry strategy used */
428
+ readonly strategy: string;
429
+ /** Backoff delay in milliseconds */
430
+ readonly backoffDelay?: number;
431
+ }
432
+ /**
433
+ * Base execution error class with enhanced context and recovery information
434
+ */
435
+ declare abstract class ExecutionError extends Error {
436
+ /** Error type classification */
437
+ readonly type: ExecutionErrorType;
438
+ /** Error code for programmatic handling */
439
+ readonly code: ExecutionErrorCode;
440
+ /** Error timestamp */
441
+ readonly timestamp: Date;
442
+ /** Operation context */
443
+ readonly context?: string | undefined;
444
+ /** Retry information */
445
+ readonly retryInfo?: RetryInfo | undefined;
446
+ /** Recovery suggestions */
447
+ readonly recoverySuggestions?: readonly string[] | undefined;
448
+ /** Additional metadata */
449
+ readonly metadata?: Readonly<Record<string, unknown>> | undefined;
450
+ /** Cause error for error chaining */
451
+ readonly cause?: Error | undefined;
452
+ constructor(message: string, type: ExecutionErrorType, code: ExecutionErrorCode, options?: ExecutionErrorOptions);
453
+ /**
454
+ * Get user-friendly error message
455
+ */
456
+ getUserMessage(): string;
457
+ /**
458
+ * Get technical error details
459
+ */
460
+ getTechnicalDetails(): string;
461
+ /**
462
+ * Check if error is retryable
463
+ */
464
+ isRetryable(): boolean;
465
+ /**
466
+ * Get time until next retry
467
+ */
468
+ getRetryDelay(): number;
469
+ /**
470
+ * Serialize error to JSON
471
+ */
472
+ toJSON(): Record<string, unknown>;
473
+ }
474
+
475
+ /**
476
+ * Progress event types from Roundtable server format
477
+ */
478
+ declare enum ProgressEventType {
479
+ TOOL_START = "tool_start",
480
+ TOOL_RESULT = "tool_result",
481
+ THINKING = "thinking",
482
+ ERROR = "error",
483
+ INFO = "info",
484
+ DEBUG = "debug"
485
+ }
486
+ /**
487
+ * Tool execution status for tracking
488
+ */
489
+ declare enum ToolExecutionStatus {
490
+ PENDING = "pending",
491
+ RUNNING = "running",
492
+ COMPLETED = "completed",
493
+ FAILED = "failed",
494
+ CANCELLED = "cancelled",
495
+ TIMEOUT = "timeout"
496
+ }
497
+ /**
498
+ * Progress event interface matching Roundtable server format
499
+ * Format: "Backend #count: event_type => content"
500
+ *
501
+ * @example
502
+ * ```typescript
503
+ * const progressEvent: ProgressEvent = {
504
+ * sessionId: 'session-123',
505
+ * timestamp: new Date(),
506
+ * backend: 'claude',
507
+ * count: 1,
508
+ * type: ProgressEventType.TOOL_START,
509
+ * content: 'Starting code analysis...',
510
+ * toolId: 'claude_1',
511
+ * metadata: {
512
+ * duration: 150,
513
+ * tokens: 1024
514
+ * }
515
+ * };
516
+ * ```
517
+ */
518
+ interface ProgressEvent {
519
+ /** Unique session identifier for correlation */
520
+ readonly sessionId: string;
521
+ /** Event timestamp */
522
+ readonly timestamp: Date;
523
+ /** Subagent backend name (claude, cursor, codex, gemini) */
524
+ readonly backend: string;
525
+ /** Sequential event number within session */
526
+ readonly count: number;
527
+ /** Progress event classification */
528
+ readonly type: ProgressEventType;
529
+ /** Event content/message from subagent */
530
+ readonly content: string;
531
+ /** Generated tool correlation ID for tracking */
532
+ readonly toolId: string;
533
+ /** Additional event metadata */
534
+ readonly metadata?: Readonly<Record<string, unknown>>;
535
+ /** Parent event ID for nested operations */
536
+ readonly parentId?: string;
537
+ /** Event priority level */
538
+ readonly priority?: 'low' | 'normal' | 'high';
539
+ }
540
+ /**
541
+ * Progress callback function signature
542
+ * Callbacks must never throw errors to avoid breaking execution flow
543
+ *
544
+ * @param event - The progress event to handle
545
+ * @returns Promise<void> - Should handle errors internally
546
+ */
547
+ type ProgressCallback = (event: ProgressEvent) => Promise<void> | void;
548
+ /**
549
+ * Tool call request structure
550
+ *
551
+ * @example
552
+ * ```typescript
553
+ * const request: ToolCallRequest = {
554
+ * toolName: 'claude_subagent',
555
+ * arguments: {
556
+ * instruction: 'Analyze this code',
557
+ * project_path: '/path/to/project',
558
+ * model: 'sonnet-4'
559
+ * },
560
+ * timeout: 30000,
561
+ * priority: 'high',
562
+ * metadata: {
563
+ * userId: 'user-123',
564
+ * sessionId: 'session-456'
565
+ * }
566
+ * };
567
+ * ```
568
+ */
569
+ interface ToolCallRequest {
570
+ /** Tool name (mapped from subagent name) */
571
+ readonly toolName: string;
572
+ /** Tool arguments object */
573
+ readonly arguments: Readonly<Record<string, unknown>>;
574
+ /** Request timeout in milliseconds */
575
+ readonly timeout?: number;
576
+ /** Request priority level */
577
+ readonly priority?: 'low' | 'normal' | 'high';
578
+ /** Additional request metadata */
579
+ readonly metadata?: Readonly<Record<string, unknown>>;
580
+ /** Callback for progress events */
581
+ readonly progressCallback?: ProgressCallback;
582
+ /** Unique request identifier */
583
+ readonly requestId?: string;
584
+ }
585
+ /**
586
+ * Tool call result structure
587
+ */
588
+ interface ToolCallResult {
589
+ /** Tool execution result content */
590
+ readonly content: string;
591
+ /** Execution status */
592
+ readonly status: ToolExecutionStatus;
593
+ /** Execution start time */
594
+ readonly startTime: Date;
595
+ /** Execution end time */
596
+ readonly endTime: Date;
597
+ /** Total execution duration in milliseconds */
598
+ readonly duration: number;
599
+ /** Any error that occurred during execution */
600
+ readonly error?: Error;
601
+ /** Progress events generated during execution */
602
+ readonly progressEvents: readonly ProgressEvent[];
603
+ /** Tool execution metadata */
604
+ readonly metadata?: ToolExecutionMetadata;
605
+ /** Request that generated this result */
606
+ readonly request: ToolCallRequest;
607
+ }
608
+ /**
609
+ * Tool execution metadata
610
+ */
611
+ interface ToolExecutionMetadata {
612
+ /** Number of tokens used */
613
+ readonly tokensUsed?: number;
614
+ /** Estimated cost */
615
+ readonly estimatedCost?: number;
616
+ /** Model used for execution */
617
+ readonly model?: string;
618
+ /** Server version */
619
+ readonly serverVersion?: string;
620
+ /** Performance metrics */
621
+ readonly performanceMetrics?: ToolPerformanceMetrics;
622
+ /** Raw subagent response payload (for programmatic capture / session resume) */
623
+ readonly subAgentResponse?: any;
624
+ /** Indicates the content string is structured (e.g., JSON) and safe to parse */
625
+ readonly structuredOutput?: boolean;
626
+ /** Content type for the tool output (e.g., application/json) */
627
+ readonly contentType?: string;
628
+ /** Original raw output emitted by the tool (pre-structuring) */
629
+ readonly rawOutput?: string;
630
+ /** Quota limit information detected during execution */
631
+ readonly quotaLimitInfo?: any;
632
+ }
633
+ /**
634
+ * Tool performance metrics
635
+ */
636
+ interface ToolPerformanceMetrics {
637
+ /** CPU usage during execution */
638
+ readonly cpuUsage: number;
639
+ /** Memory usage during execution */
640
+ readonly memoryUsage: number;
641
+ /** Network usage in bytes */
642
+ readonly networkUsage: number;
643
+ /** Processing time breakdown */
644
+ readonly timingBreakdown: Record<string, number>;
645
+ }
646
+ /**
647
+ * Session context (renamed from MCPSessionContext)
648
+ */
649
+ interface SessionContext {
650
+ /** Unique session identifier */
651
+ readonly sessionId: string;
652
+ /** Session start time */
653
+ readonly startTime: Date;
654
+ /** User identifier */
655
+ readonly userId?: string;
656
+ /** Session metadata */
657
+ readonly metadata: Readonly<Record<string, unknown>>;
658
+ /** Active tool calls */
659
+ readonly activeToolCalls: readonly string[];
660
+ /** Session state */
661
+ readonly state: SessionState;
662
+ /** Last activity time */
663
+ readonly lastActivity: Date;
664
+ }
665
+ /**
666
+ * Session state
667
+ */
668
+ declare enum SessionState {
669
+ INITIALIZING = "initializing",
670
+ ACTIVE = "active",
671
+ IDLE = "idle",
672
+ SUSPENDED = "suspended",
673
+ COMPLETED = "completed",
674
+ FAILED = "failed"
675
+ }
676
+
677
+ /**
678
+ * Core execution engine module for juno-task-ts
679
+ *
680
+ * This module provides the main execution orchestration engine that manages
681
+ * the entire workflow for AI task execution, including session management,
682
+ * backend integration, progress tracking, error handling, and cancellation.
683
+ *
684
+ * The implementation closely matches the Python budi-cli execution patterns,
685
+ * including rate limit handling, iteration logic, and progress tracking.
686
+ *
687
+ * @module core/engine
688
+ * @since 1.0.0
689
+ */
690
+
691
+ /**
692
+ * Execution request interface for starting task execution
693
+ */
694
+ interface ExecutionRequest {
695
+ /** Unique request identifier */
696
+ readonly requestId: string;
697
+ /** Task instruction or prompt text */
698
+ readonly instruction: string;
699
+ /** Subagent to use for execution */
700
+ readonly subagent: SubagentType;
701
+ /** Backend to use for execution */
702
+ readonly backend: BackendType;
703
+ /** Working directory for execution */
704
+ readonly workingDirectory: string;
705
+ /** Maximum number of iterations (-1 for unlimited) */
706
+ readonly maxIterations: number;
707
+ /** Optional specific model to use */
708
+ readonly model?: string;
709
+ /** Optional timeout in milliseconds (overrides config) */
710
+ readonly timeoutMs?: number;
711
+ /** Session metadata */
712
+ readonly sessionMetadata?: Record<string, unknown>;
713
+ /** Custom progress callbacks */
714
+ readonly progressCallbacks?: ProgressCallback[];
715
+ /** Request priority level */
716
+ readonly priority?: 'low' | 'normal' | 'high';
717
+ /** MCP server name (for MCP backend) */
718
+ readonly mcpServerName?: string;
719
+ /** Available tools from built-in set (only works with --print mode, forwarded to shell backend) */
720
+ readonly tools?: string[];
721
+ /** Permission-based filtering of specific tool instances (forwarded to shell backend) */
722
+ readonly allowedTools?: string[];
723
+ /** Disallowed tools (forwarded to shell backend) */
724
+ readonly disallowedTools?: string[];
725
+ /** Append tools to default allowed-tools list (forwarded to shell backend) */
726
+ readonly appendAllowedTools?: string[];
727
+ /** Agents configuration (forwarded to shell backend) */
728
+ readonly agents?: string;
729
+ /** Resume a conversation by session ID (forwarded to shell backend) */
730
+ readonly resume?: string;
731
+ /** Continue the most recent conversation (forwarded to shell backend) */
732
+ readonly continueConversation?: boolean;
733
+ /** Extended thinking level (forwarded to shell backend --thinking flag) */
734
+ readonly thinking?: string;
735
+ }
736
+ /**
737
+ * Execution result interface for completed executions
738
+ */
739
+ interface ExecutionResult {
740
+ /** Request that generated this result */
741
+ readonly request: ExecutionRequest;
742
+ /** Execution status */
743
+ readonly status: ExecutionStatus;
744
+ /** Execution start time */
745
+ readonly startTime: Date;
746
+ /** Execution end time */
747
+ readonly endTime: Date;
748
+ /** Total execution duration in milliseconds */
749
+ readonly duration: number;
750
+ /** All iteration results */
751
+ readonly iterations: readonly IterationResult[];
752
+ /** Final execution statistics */
753
+ readonly statistics: ExecutionStatistics;
754
+ /** Any error that terminated execution */
755
+ readonly error?: ExecutionError;
756
+ /** Session context information */
757
+ readonly sessionContext: SessionContext;
758
+ /** All progress events captured during execution */
759
+ readonly progressEvents: readonly ProgressEvent[];
760
+ }
761
+ /**
762
+ * Individual iteration result
763
+ */
764
+ interface IterationResult {
765
+ /** Iteration number (1-based) */
766
+ readonly iterationNumber: number;
767
+ /** Iteration success status */
768
+ readonly success: boolean;
769
+ /** Iteration start time */
770
+ readonly startTime: Date;
771
+ /** Iteration end time */
772
+ readonly endTime: Date;
773
+ /** Iteration duration in milliseconds */
774
+ readonly duration: number;
775
+ /** Tool call result */
776
+ readonly toolResult: ToolCallResult;
777
+ /** Iteration-specific progress events */
778
+ readonly progressEvents: readonly ProgressEvent[];
779
+ /** Any error that occurred during iteration */
780
+ readonly error?: Error;
781
+ }
782
+ /**
783
+ * Execution status enumeration
784
+ */
785
+ declare enum ExecutionStatus {
786
+ PENDING = "pending",
787
+ RUNNING = "running",
788
+ COMPLETED = "completed",
789
+ FAILED = "failed",
790
+ CANCELLED = "cancelled",
791
+ TIMEOUT = "timeout",
792
+ RATE_LIMITED = "rate_limited"
793
+ }
794
+ /**
795
+ * Execution statistics for performance tracking
796
+ */
797
+ interface ExecutionStatistics {
798
+ /** Total iterations attempted */
799
+ totalIterations: number;
800
+ /** Number of successful iterations */
801
+ successfulIterations: number;
802
+ /** Number of failed iterations */
803
+ failedIterations: number;
804
+ /** Average iteration duration in milliseconds */
805
+ averageIterationDuration: number;
806
+ /** Total tool calls made */
807
+ totalToolCalls: number;
808
+ /** Total progress events processed */
809
+ totalProgressEvents: number;
810
+ /** Rate limit encounters */
811
+ rateLimitEncounters: number;
812
+ /** Total rate limit wait time in milliseconds */
813
+ rateLimitWaitTime: number;
814
+ /** Quota limit encounters (Claude-specific) */
815
+ quotaLimitEncounters: number;
816
+ /** Total quota limit wait time in milliseconds */
817
+ quotaLimitWaitTime: number;
818
+ /** Error breakdown by type */
819
+ errorBreakdown: Record<string, number>;
820
+ /** Performance metrics */
821
+ performanceMetrics: PerformanceMetrics;
822
+ }
823
+ /**
824
+ * Performance metrics for detailed analysis
825
+ */
826
+ interface PerformanceMetrics {
827
+ /** CPU usage percentage during execution */
828
+ cpuUsage: number;
829
+ /** Memory usage in bytes */
830
+ memoryUsage: number;
831
+ /** Network requests made */
832
+ networkRequests: number;
833
+ /** File system operations */
834
+ fileSystemOperations: number;
835
+ /** Throughput metrics */
836
+ throughput: ThroughputMetrics;
837
+ }
838
+ /**
839
+ * Throughput metrics
840
+ */
841
+ interface ThroughputMetrics {
842
+ /** Iterations per minute */
843
+ iterationsPerMinute: number;
844
+ /** Progress events per second */
845
+ progressEventsPerSecond: number;
846
+ /** Tool calls per minute */
847
+ toolCallsPerMinute: number;
848
+ }
849
+ /**
850
+ * Rate limit information for handling
851
+ */
852
+ interface RateLimitInfo {
853
+ /** Whether currently rate limited */
854
+ readonly isRateLimited: boolean;
855
+ /** Rate limit reset time */
856
+ readonly resetTime?: Date;
857
+ /** Remaining requests in current window */
858
+ readonly remaining: number;
859
+ /** Time to wait before next request in milliseconds */
860
+ readonly waitTimeMs: number;
861
+ /** Rate limit tier/category */
862
+ readonly tier?: string;
863
+ }
864
+ /**
865
+ * Error recovery strategy configuration
866
+ */
867
+ interface ErrorRecoveryConfig {
868
+ /** Maximum recovery attempts per error type */
869
+ readonly maxAttempts: Record<string, number>;
870
+ /** Retry delays by error type in milliseconds */
871
+ readonly retryDelays: Record<string, number>;
872
+ /** Whether to continue on specific error types */
873
+ readonly continueOnError: Record<string, boolean>;
874
+ /** Custom recovery strategies */
875
+ readonly customStrategies: Record<string, (error: ExecutionError) => Promise<boolean>>;
876
+ }
877
+ /**
878
+ * Execution engine configuration
879
+ */
880
+ interface ExecutionEngineConfig {
881
+ /** Base configuration */
882
+ readonly config: JunoTaskConfig;
883
+ /** No longer uses BackendManager; engine creates ShellBackend directly */
884
+ /** Error recovery configuration */
885
+ readonly errorRecovery: ErrorRecoveryConfig;
886
+ /** Rate limit handling configuration */
887
+ readonly rateLimitConfig: RateLimitHandlingConfig;
888
+ /** Progress tracking configuration */
889
+ readonly progressConfig: ProgressTrackingConfig;
890
+ }
891
+ /**
892
+ * Rate limit handling configuration
893
+ */
894
+ interface RateLimitHandlingConfig {
895
+ /** Enable automatic rate limit handling */
896
+ readonly enabled: boolean;
897
+ /** Maximum wait time for rate limits in milliseconds */
898
+ readonly maxWaitTimeMs: number;
899
+ /** Rate limit detection patterns */
900
+ readonly detectionPatterns: readonly RegExp[];
901
+ /** Custom rate limit parsers */
902
+ readonly customParsers: readonly RateLimitParser[];
903
+ }
904
+ /**
905
+ * Rate limit parser interface
906
+ */
907
+ interface RateLimitParser {
908
+ /** Pattern to match rate limit messages */
909
+ readonly pattern: RegExp;
910
+ /** Parse function to extract reset time */
911
+ readonly parse: (message: string) => Date | null;
912
+ }
913
+ /**
914
+ * Progress tracking configuration
915
+ */
916
+ interface ProgressTrackingConfig {
917
+ /** Enable progress tracking */
918
+ readonly enabled: boolean;
919
+ /** Buffer size for progress events */
920
+ readonly bufferSize: number;
921
+ /** Progress event filters */
922
+ readonly filters: readonly ProgressEventFilter[];
923
+ /** Custom progress processors */
924
+ readonly processors: readonly ProgressEventProcessor[];
925
+ }
926
+ /**
927
+ * Progress event filter
928
+ */
929
+ interface ProgressEventFilter {
930
+ /** Filter type */
931
+ readonly type: ProgressEventType$1 | 'custom';
932
+ /** Filter predicate */
933
+ readonly predicate: (event: ProgressEvent) => boolean;
934
+ }
935
+ /**
936
+ * Progress event processor
937
+ */
938
+ interface ProgressEventProcessor {
939
+ /** Processor name */
940
+ readonly name: string;
941
+ /** Process function */
942
+ readonly process: (event: ProgressEvent) => Promise<void>;
943
+ }
944
+ /**
945
+ * Default error recovery configuration
946
+ */
947
+ declare const DEFAULT_ERROR_RECOVERY_CONFIG: ErrorRecoveryConfig;
948
+ /**
949
+ * Default rate limit handling configuration
950
+ */
951
+ declare const DEFAULT_RATE_LIMIT_CONFIG: RateLimitHandlingConfig;
952
+ /**
953
+ * Default progress tracking configuration
954
+ */
955
+ declare const DEFAULT_PROGRESS_CONFIG: ProgressTrackingConfig;
956
+ /**
957
+ * Main execution engine class for orchestrating AI task execution
958
+ *
959
+ * This class manages the complete execution lifecycle including:
960
+ * - Session creation and management
961
+ * - Iteration loop with rate limit handling
962
+ * - Progress tracking and statistics collection
963
+ * - Error handling with recovery strategies
964
+ * - Cancellation and cleanup
965
+ *
966
+ * @example
967
+ * ```typescript
968
+ * const engine = createExecutionEngine(await loadConfig());
969
+ *
970
+ * const request: ExecutionRequest = {
971
+ * requestId: 'req-123',
972
+ * instruction: 'Implement a new feature',
973
+ * subagent: 'claude',
974
+ * workingDirectory: '/path/to/project',
975
+ * maxIterations: 10,
976
+ * };
977
+ *
978
+ * const result = await engine.execute(request);
979
+ * ```
980
+ */
981
+ declare class ExecutionEngine extends EventEmitter {
982
+ private readonly engineConfig;
983
+ private readonly activeExecutions;
984
+ private readonly progressCallbacks;
985
+ private readonly cleanupTasks;
986
+ private isShuttingDown;
987
+ private currentBackend;
988
+ /**
989
+ * Create a new ExecutionEngine instance
990
+ *
991
+ * @param config - Engine configuration
992
+ */
993
+ constructor(config: ExecutionEngineConfig);
994
+ /**
995
+ * Execute a task request with comprehensive orchestration
996
+ *
997
+ * @param request - Execution request parameters
998
+ * @param abortSignal - Optional abort signal for cancellation
999
+ * @returns Promise resolving to execution result
1000
+ */
1001
+ execute(request: ExecutionRequest, abortSignal?: AbortSignal): Promise<ExecutionResult>;
1002
+ /**
1003
+ * Add a progress callback for all executions
1004
+ *
1005
+ * @param callback - Progress callback function
1006
+ * @returns Cleanup function to remove the callback
1007
+ */
1008
+ onProgress(callback: ProgressCallback): () => void;
1009
+ /**
1010
+ * Get current rate limit information
1011
+ *
1012
+ * @returns Current rate limit status
1013
+ */
1014
+ getRateLimitInfo(): Promise<RateLimitInfo>;
1015
+ /**
1016
+ * Cancel all active executions and shutdown gracefully
1017
+ *
1018
+ * @param timeoutMs - Maximum time to wait for cleanup
1019
+ */
1020
+ shutdown(timeoutMs?: number): Promise<void>;
1021
+ /**
1022
+ * Get statistics for all executions
1023
+ *
1024
+ * @returns Aggregate execution statistics
1025
+ */
1026
+ getExecutionStatistics(): ExecutionStatistics;
1027
+ /**
1028
+ * Setup error handling for the engine
1029
+ */
1030
+ private setupErrorHandling;
1031
+ /**
1032
+ * Setup progress tracking for the engine
1033
+ */
1034
+ private setupProgressTracking;
1035
+ /**
1036
+ * Display hook execution output to stderr at verbose level 2 (debug+hooks).
1037
+ * At level 2: shows hook name, command stdout/stderr output.
1038
+ * At level 0-1: output is suppressed (hooks still execute).
1039
+ */
1040
+ private displayHookOutput;
1041
+ /**
1042
+ * Initialize backend for execution request.
1043
+ * Directly creates and configures a ShellBackend (no factory indirection).
1044
+ */
1045
+ private initializeBackend;
1046
+ /**
1047
+ * Validate execution request parameters
1048
+ */
1049
+ private validateRequest;
1050
+ /**
1051
+ * Create execution context for a request
1052
+ */
1053
+ private createExecutionContext;
1054
+ /**
1055
+ * Create initial statistics object
1056
+ */
1057
+ private createInitialStatistics;
1058
+ /**
1059
+ * Create session context for execution
1060
+ */
1061
+ private createSessionContext;
1062
+ /**
1063
+ * Internal execution implementation
1064
+ */
1065
+ private executeInternal;
1066
+ /**
1067
+ * Run the main iteration loop
1068
+ */
1069
+ private runIterationLoop;
1070
+ /**
1071
+ * Execute a single iteration
1072
+ * @returns QuotaLimitInfo if a quota limit was detected, null otherwise
1073
+ */
1074
+ private executeIteration;
1075
+ /**
1076
+ * Handle rate limit errors with automatic retry
1077
+ */
1078
+ private handleRateLimit;
1079
+ /**
1080
+ * Calculate wait time for rate limit reset
1081
+ */
1082
+ private calculateRateLimitWaitTime;
1083
+ /**
1084
+ * Handle Claude quota limit with automatic sleep and retry
1085
+ * @returns true if we should retry the iteration, false otherwise
1086
+ */
1087
+ private handleQuotaLimit;
1088
+ /**
1089
+ * Sleep with periodic progress updates
1090
+ */
1091
+ private sleepWithProgress;
1092
+ /**
1093
+ * Check if tool result indicates a quota limit error
1094
+ */
1095
+ private extractQuotaLimitInfo;
1096
+ /**
1097
+ * Handle iteration errors with recovery strategies
1098
+ */
1099
+ private handleIterationError;
1100
+ /**
1101
+ * Process individual progress events
1102
+ */
1103
+ private processProgressEvent;
1104
+ /**
1105
+ * Update execution statistics
1106
+ */
1107
+ private updateStatistics;
1108
+ /**
1109
+ * Update performance metrics
1110
+ */
1111
+ private updatePerformanceMetrics;
1112
+ /**
1113
+ * Check if iteration loop should stop
1114
+ */
1115
+ private shouldStopIterating;
1116
+ /**
1117
+ * Check abort signal and throw if aborted
1118
+ */
1119
+ private checkAbortSignal;
1120
+ /**
1121
+ * Get tool name for subagent
1122
+ */
1123
+ private getToolNameForSubagent;
1124
+ /**
1125
+ * Wrap unknown errors as execution errors
1126
+ */
1127
+ private wrapError;
1128
+ /**
1129
+ * Determine execution status from error
1130
+ */
1131
+ private determineErrorStatus;
1132
+ /**
1133
+ * Create final execution result
1134
+ */
1135
+ private createExecutionResult;
1136
+ /**
1137
+ * Cancel an execution
1138
+ */
1139
+ private cancelExecution;
1140
+ /**
1141
+ * Cleanup execution resources
1142
+ */
1143
+ private cleanupExecution;
1144
+ /**
1145
+ * Calculate average iteration duration across contexts
1146
+ */
1147
+ private calculateAverageIterationDuration;
1148
+ /**
1149
+ * Aggregate error breakdown across contexts
1150
+ */
1151
+ private aggregateErrorBreakdown;
1152
+ /**
1153
+ * Calculate performance metrics across contexts
1154
+ */
1155
+ private calculatePerformanceMetrics;
1156
+ /**
1157
+ * Sleep utility for delays
1158
+ */
1159
+ private sleep;
1160
+ }
1161
+ /**
1162
+ * Create an execution engine with default configuration
1163
+ *
1164
+ * @param config - Base juno-task configuration
1165
+ * @returns Configured execution engine
1166
+ */
1167
+ declare function createExecutionEngine(config: JunoTaskConfig): ExecutionEngine;
1168
+ /**
1169
+ * Create an execution request with defaults
1170
+ *
1171
+ * @param options - Request options
1172
+ * @returns Execution request
1173
+ */
1174
+ declare function createExecutionRequest(options: {
1175
+ instruction: string;
1176
+ subagent?: SubagentType;
1177
+ backend?: BackendType;
1178
+ workingDirectory?: string;
1179
+ maxIterations?: number;
1180
+ model?: string;
1181
+ agents?: string;
1182
+ tools?: string[];
1183
+ allowedTools?: string[];
1184
+ appendAllowedTools?: string[];
1185
+ disallowedTools?: string[];
1186
+ requestId?: string;
1187
+ mcpServerName?: string;
1188
+ resume?: string;
1189
+ continueConversation?: boolean;
1190
+ thinking?: string;
1191
+ }): ExecutionRequest;
1192
+
1193
+ /** Session metadata */
1194
+ interface SessionInfo {
1195
+ id: string;
1196
+ name?: string;
1197
+ status: SessionStatus;
1198
+ subagent: SubagentType;
1199
+ createdAt: Date;
1200
+ updatedAt: Date;
1201
+ completedAt?: Date;
1202
+ workingDirectory: string;
1203
+ config: Partial<JunoTaskConfig>;
1204
+ tags: string[];
1205
+ metadata: Record<string, any>;
1206
+ }
1207
+ /** Session statistics - essential counters only */
1208
+ interface SessionStatistics {
1209
+ duration: number;
1210
+ iterations: number;
1211
+ toolCalls: number;
1212
+ errorCount: number;
1213
+ }
1214
+ /** Complete session state */
1215
+ interface Session {
1216
+ info: SessionInfo;
1217
+ context: {
1218
+ workingDirectory: string;
1219
+ config: JunoTaskConfig;
1220
+ };
1221
+ statistics: SessionStatistics;
1222
+ history: SessionHistoryEntry[];
1223
+ result?: {
1224
+ success: boolean;
1225
+ output?: string;
1226
+ error?: string;
1227
+ finalState?: any;
1228
+ };
1229
+ }
1230
+ /** History entry for conversation tracking */
1231
+ interface SessionHistoryEntry {
1232
+ id: string;
1233
+ timestamp: Date;
1234
+ type: 'prompt' | 'response' | 'tool_call' | 'error' | 'system';
1235
+ content: string;
1236
+ data?: any;
1237
+ duration?: number;
1238
+ iteration?: number;
1239
+ }
1240
+ /** Persistence layer abstraction */
1241
+ interface SessionStorage {
1242
+ saveSession(session: Session): Promise<void>;
1243
+ loadSession(sessionId: string): Promise<Session | null>;
1244
+ listSessions(filter?: SessionListFilter): Promise<SessionInfo[]>;
1245
+ removeSession(sessionId: string): Promise<void>;
1246
+ sessionExists(sessionId: string): Promise<boolean>;
1247
+ cleanup(options: CleanupOptions): Promise<void>;
1248
+ }
1249
+ /** Filter criteria for listing sessions */
1250
+ interface SessionListFilter {
1251
+ status?: SessionStatus[];
1252
+ subagent?: SubagentType[];
1253
+ dateRange?: {
1254
+ start?: Date;
1255
+ end?: Date;
1256
+ };
1257
+ tags?: string[];
1258
+ limit?: number;
1259
+ offset?: number;
1260
+ sortBy?: 'createdAt' | 'updatedAt' | 'name';
1261
+ sortOrder?: 'asc' | 'desc';
1262
+ }
1263
+ /** Options for storage cleanup */
1264
+ interface CleanupOptions {
1265
+ removeEmpty?: boolean;
1266
+ removeOlderThanDays?: number;
1267
+ removeStatus?: SessionStatus[];
1268
+ dryRun?: boolean;
1269
+ }
1270
+ /** File-based session storage implementation */
1271
+ declare class FileSessionStorage implements SessionStorage {
1272
+ private readonly baseDir;
1273
+ private readonly sessionsDir;
1274
+ constructor(baseDir: string);
1275
+ initialize(): Promise<void>;
1276
+ private getSessionPath;
1277
+ saveSession(session: Session): Promise<void>;
1278
+ loadSession(sessionId: string): Promise<Session | null>;
1279
+ listSessions(filter?: SessionListFilter): Promise<SessionInfo[]>;
1280
+ removeSession(sessionId: string): Promise<void>;
1281
+ sessionExists(sessionId: string): Promise<boolean>;
1282
+ cleanup(options: CleanupOptions): Promise<void>;
1283
+ }
1284
+ /** Session manager - plain class for session lifecycle management */
1285
+ declare class SessionManager {
1286
+ private storage;
1287
+ private activeSessions;
1288
+ constructor(storage: SessionStorage);
1289
+ createSession(options: {
1290
+ name?: string;
1291
+ subagent: SubagentType;
1292
+ config: JunoTaskConfig;
1293
+ tags?: string[];
1294
+ metadata?: Record<string, any>;
1295
+ }): Promise<Session>;
1296
+ updateSession(sessionId: string, updates: {
1297
+ status?: SessionStatus;
1298
+ name?: string;
1299
+ tags?: string[];
1300
+ metadata?: Record<string, any>;
1301
+ statistics?: Partial<SessionStatistics>;
1302
+ result?: Session['result'];
1303
+ }): Promise<void>;
1304
+ completeSession(sessionId: string, result: {
1305
+ success: boolean;
1306
+ output?: string;
1307
+ error?: string;
1308
+ finalState?: any;
1309
+ }): Promise<void>;
1310
+ cancelSession(sessionId: string): Promise<void>;
1311
+ getSession(sessionId: string): Promise<Session | null>;
1312
+ listSessions(filter?: SessionListFilter): Promise<SessionInfo[]>;
1313
+ removeSession(sessionId: string): Promise<void>;
1314
+ cleanupSessions(options: CleanupOptions): Promise<void>;
1315
+ addHistoryEntry(sessionId: string, entry: Omit<SessionHistoryEntry, 'id' | 'timestamp'>): Promise<void>;
1316
+ updateStatistics(sessionId: string, stats: Partial<SessionStatistics>): Promise<void>;
1317
+ recordToolCall(sessionId: string, toolCall: {
1318
+ name: string;
1319
+ duration: number;
1320
+ success: boolean;
1321
+ }): Promise<void>;
1322
+ getSessionContext(sessionId: string, options?: {
1323
+ includeHistory?: boolean;
1324
+ includeStats?: boolean;
1325
+ maxHistoryEntries?: number;
1326
+ }): Promise<string>;
1327
+ getSessionSummary(sessionId: string): Promise<{
1328
+ info: SessionInfo;
1329
+ statistics: SessionStatistics;
1330
+ summary: {
1331
+ totalDuration: string;
1332
+ iterationsPerMinute: number;
1333
+ toolCallsPerIteration: number;
1334
+ errorRate: number;
1335
+ };
1336
+ } | null>;
1337
+ private formatDuration;
1338
+ }
1339
+ /** Create a session manager with file storage */
1340
+ declare function createSessionManager(config: JunoTaskConfig): Promise<SessionManager>;
1341
+
1342
+ /**
1343
+ * Environment Utilities Module for juno-task-ts
1344
+ *
1345
+ * Provides comprehensive environment variable handling and detection utilities
1346
+ * for the juno-task-ts CLI tool. This module includes environment detection,
1347
+ * terminal capabilities, platform information, configuration directories,
1348
+ * and MCP server path detection.
1349
+ *
1350
+ * @module utils/environment
1351
+ */
1352
+ /**
1353
+ * Color support levels for terminal output
1354
+ */
1355
+ type ColorSupport = 'none' | 'basic' | '256' | 'truecolor';
1356
+ /**
1357
+ * Node.js environment types
1358
+ */
1359
+ type NodeEnvironment = 'development' | 'production' | 'test';
1360
+ /**
1361
+ * Operating system platforms
1362
+ */
1363
+ type Platform = 'win32' | 'darwin' | 'linux' | 'freebsd' | 'openbsd' | 'sunos' | 'aix';
1364
+ /**
1365
+ * System architectures
1366
+ */
1367
+ type Architecture = 'arm' | 'arm64' | 'ia32' | 'mips' | 'mipsel' | 'ppc' | 'ppc64' | 's390' | 's390x' | 'x64';
1368
+ /**
1369
+ * Shell types
1370
+ */
1371
+ type ShellType = 'bash' | 'zsh' | 'fish' | 'cmd' | 'powershell' | 'unknown';
1372
+ /**
1373
+ * Process information interface
1374
+ */
1375
+ interface ProcessInfo {
1376
+ pid: number;
1377
+ ppid: number;
1378
+ platform: Platform;
1379
+ arch: Architecture;
1380
+ nodeVersion: string;
1381
+ uptime: number;
1382
+ cwd: string;
1383
+ execPath: string;
1384
+ argv: string[];
1385
+ env: Record<string, string | undefined>;
1386
+ }
1387
+ /**
1388
+ * Memory usage information
1389
+ */
1390
+ interface MemoryUsage {
1391
+ rss: number;
1392
+ heapTotal: number;
1393
+ heapUsed: number;
1394
+ external: number;
1395
+ arrayBuffers: number;
1396
+ }
1397
+ /**
1398
+ * CPU usage information
1399
+ */
1400
+ interface CpuUsage {
1401
+ user: number;
1402
+ system: number;
1403
+ }
1404
+ /**
1405
+ * MCP server environment configuration
1406
+ */
1407
+ interface MCPServerEnvironment {
1408
+ PATH: string;
1409
+ NODE_ENV: string;
1410
+ [key: string]: string;
1411
+ }
1412
+ /**
1413
+ * Detect if running in a headless/CI environment where interactive prompts should be avoided.
1414
+ * Based on the Python implementation patterns from budi-cli.
1415
+ *
1416
+ * @returns True if running in headless/CI environment
1417
+ *
1418
+ * @example
1419
+ * ```typescript
1420
+ * if (isHeadlessEnvironment()) {
1421
+ * console.log('Using non-interactive mode');
1422
+ * }
1423
+ * ```
1424
+ */
1425
+ declare function isHeadlessEnvironment(): boolean;
1426
+ /**
1427
+ * Detect if running in a continuous integration environment.
1428
+ *
1429
+ * @returns True if running in CI environment
1430
+ *
1431
+ * @example
1432
+ * ```typescript
1433
+ * if (isCIEnvironment()) {
1434
+ * console.log('Running in CI environment');
1435
+ * }
1436
+ * ```
1437
+ */
1438
+ declare function isCIEnvironment(): boolean;
1439
+ /**
1440
+ * Check if terminal supports interactive input/output.
1441
+ *
1442
+ * @returns True if terminal supports interaction
1443
+ *
1444
+ * @example
1445
+ * ```typescript
1446
+ * if (isInteractiveTerminal()) {
1447
+ * // Show interactive prompts
1448
+ * }
1449
+ * ```
1450
+ */
1451
+ declare function isInteractiveTerminal(): boolean;
1452
+ /**
1453
+ * Detect if running in development mode.
1454
+ *
1455
+ * @returns True if in development mode
1456
+ *
1457
+ * @example
1458
+ * ```typescript
1459
+ * if (isDevelopmentMode()) {
1460
+ * console.log('Debug logging enabled');
1461
+ * }
1462
+ * ```
1463
+ */
1464
+ declare function isDevelopmentMode(): boolean;
1465
+ /**
1466
+ * Get Node.js environment type.
1467
+ *
1468
+ * @returns The Node.js environment type
1469
+ *
1470
+ * @example
1471
+ * ```typescript
1472
+ * const env = getNodeEnvironment();
1473
+ * console.log(`Running in ${env} mode`);
1474
+ * ```
1475
+ */
1476
+ declare function getNodeEnvironment(): NodeEnvironment;
1477
+ /**
1478
+ * Get environment variable with optional type conversion.
1479
+ *
1480
+ * @param key - Environment variable name
1481
+ * @param defaultValue - Default value if variable is not set
1482
+ * @returns Environment variable value or default
1483
+ *
1484
+ * @example
1485
+ * ```typescript
1486
+ * const port = getEnvVar('PORT', '3000');
1487
+ * const timeout = getEnvVar('TIMEOUT', '30');
1488
+ * ```
1489
+ */
1490
+ declare function getEnvVar(key: string, defaultValue?: string): string | undefined;
1491
+ /**
1492
+ * Get environment variable with fallback value.
1493
+ *
1494
+ * @param key - Environment variable name
1495
+ * @param defaultValue - Default value if variable is not set
1496
+ * @returns Environment variable value or default
1497
+ *
1498
+ * @example
1499
+ * ```typescript
1500
+ * const logLevel = getEnvVarWithDefault('LOG_LEVEL', 'info');
1501
+ * ```
1502
+ */
1503
+ declare function getEnvVarWithDefault(key: string, defaultValue: string): string;
1504
+ /**
1505
+ * Set environment variable safely.
1506
+ *
1507
+ * @param key - Environment variable name
1508
+ * @param value - Value to set
1509
+ *
1510
+ * @example
1511
+ * ```typescript
1512
+ * setEnvVar('DEBUG', 'true');
1513
+ * ```
1514
+ */
1515
+ declare function setEnvVar(key: string, value: string): void;
1516
+ /**
1517
+ * Parse boolean value from environment variable string.
1518
+ *
1519
+ * @param value - Environment variable value
1520
+ * @param defaultValue - Default boolean value
1521
+ * @returns Parsed boolean value
1522
+ *
1523
+ * @example
1524
+ * ```typescript
1525
+ * const isVerbose = parseEnvBoolean(process.env.VERBOSE, false);
1526
+ * const isEnabled = parseEnvBoolean('true'); // returns true
1527
+ * ```
1528
+ */
1529
+ declare function parseEnvBoolean(value: string | undefined, defaultValue?: boolean): boolean;
1530
+ /**
1531
+ * Parse number value from environment variable string.
1532
+ *
1533
+ * @param value - Environment variable value
1534
+ * @param defaultValue - Default number value
1535
+ * @returns Parsed number value
1536
+ *
1537
+ * @example
1538
+ * ```typescript
1539
+ * const port = parseEnvNumber(process.env.PORT, 3000);
1540
+ * const timeout = parseEnvNumber('30'); // returns 30
1541
+ * ```
1542
+ */
1543
+ declare function parseEnvNumber(value: string | undefined, defaultValue?: number): number;
1544
+ /**
1545
+ * Parse array from delimited environment variable string.
1546
+ *
1547
+ * @param value - Environment variable value
1548
+ * @param delimiter - Delimiter to split on
1549
+ * @param defaultValue - Default array value
1550
+ * @returns Parsed array
1551
+ *
1552
+ * @example
1553
+ * ```typescript
1554
+ * const paths = parseEnvArray(process.env.SEARCH_PATHS, ':', []);
1555
+ * const hosts = parseEnvArray('host1,host2,host3', ','); // returns ['host1', 'host2', 'host3']
1556
+ * ```
1557
+ */
1558
+ declare function parseEnvArray(value: string | undefined, delimiter?: string, defaultValue?: string[]): string[];
1559
+ /**
1560
+ * Get terminal width for formatting output.
1561
+ *
1562
+ * @returns Terminal width in columns
1563
+ *
1564
+ * @example
1565
+ * ```typescript
1566
+ * const width = getTerminalWidth();
1567
+ * console.log(`Terminal width: ${width} columns`);
1568
+ * ```
1569
+ */
1570
+ declare function getTerminalWidth(): number;
1571
+ /**
1572
+ * Get terminal height for formatting output.
1573
+ *
1574
+ * @returns Terminal height in rows
1575
+ *
1576
+ * @example
1577
+ * ```typescript
1578
+ * const height = getTerminalHeight();
1579
+ * console.log(`Terminal height: ${height} rows`);
1580
+ * ```
1581
+ */
1582
+ declare function getTerminalHeight(): number;
1583
+ /**
1584
+ * Check if terminal supports color output.
1585
+ *
1586
+ * @returns True if terminal supports colors
1587
+ *
1588
+ * @example
1589
+ * ```typescript
1590
+ * if (supportsColor()) {
1591
+ * console.log('\x1b[32mGreen text\x1b[0m');
1592
+ * }
1593
+ * ```
1594
+ */
1595
+ declare function supportsColor(): boolean;
1596
+ /**
1597
+ * Get color capability level of the terminal.
1598
+ *
1599
+ * @returns Color support level
1600
+ *
1601
+ * @example
1602
+ * ```typescript
1603
+ * const colorSupport = getColorSupport();
1604
+ * if (colorSupport === 'truecolor') {
1605
+ * // Use RGB colors
1606
+ * }
1607
+ * ```
1608
+ */
1609
+ declare function getColorSupport(): ColorSupport;
1610
+ /**
1611
+ * Detect if running inside a Docker container.
1612
+ *
1613
+ * @returns True if running in Docker
1614
+ *
1615
+ * @example
1616
+ * ```typescript
1617
+ * if (isInDocker()) {
1618
+ * console.log('Running in Docker container');
1619
+ * }
1620
+ * ```
1621
+ */
1622
+ declare function isInDocker(): boolean;
1623
+ /**
1624
+ * Get operating system platform information.
1625
+ *
1626
+ * @returns Platform information
1627
+ *
1628
+ * @example
1629
+ * ```typescript
1630
+ * const platform = getPlatform();
1631
+ * console.log(`Running on ${platform}`);
1632
+ * ```
1633
+ */
1634
+ declare function getPlatform(): Platform;
1635
+ /**
1636
+ * Get system architecture information.
1637
+ *
1638
+ * @returns System architecture
1639
+ *
1640
+ * @example
1641
+ * ```typescript
1642
+ * const arch = getArchitecture();
1643
+ * console.log(`System architecture: ${arch}`);
1644
+ * ```
1645
+ */
1646
+ declare function getArchitecture(): Architecture;
1647
+ /**
1648
+ * Detect user's shell (bash, zsh, fish, etc.).
1649
+ *
1650
+ * @returns Detected shell type
1651
+ *
1652
+ * @example
1653
+ * ```typescript
1654
+ * const shell = getShell();
1655
+ * console.log(`User shell: ${shell}`);
1656
+ * ```
1657
+ */
1658
+ declare function getShell(): ShellType;
1659
+ /**
1660
+ * Get user home directory path.
1661
+ *
1662
+ * @returns User home directory path
1663
+ *
1664
+ * @example
1665
+ * ```typescript
1666
+ * const home = getHomeDirectory();
1667
+ * console.log(`Home directory: ${home}`);
1668
+ * ```
1669
+ */
1670
+ declare function getHomeDirectory(): string;
1671
+ /**
1672
+ * Get system temporary directory path.
1673
+ *
1674
+ * @returns System temp directory path
1675
+ *
1676
+ * @example
1677
+ * ```typescript
1678
+ * const temp = getTempDirectory();
1679
+ * console.log(`Temp directory: ${temp}`);
1680
+ * ```
1681
+ */
1682
+ declare function getTempDirectory(): string;
1683
+ /**
1684
+ * Get user configuration directory path.
1685
+ * Follows XDG Base Directory specification on Unix systems.
1686
+ *
1687
+ * @param appName - Application name for subdirectory
1688
+ * @returns Configuration directory path
1689
+ *
1690
+ * @example
1691
+ * ```typescript
1692
+ * const configDir = getConfigDirectory('juno-task');
1693
+ * // Returns: ~/.config/juno-task (Linux), ~/Library/Application Support/juno-task (macOS), etc.
1694
+ * ```
1695
+ */
1696
+ declare function getConfigDirectory(appName?: string): string;
1697
+ /**
1698
+ * Get user data directory path.
1699
+ *
1700
+ * @param appName - Application name for subdirectory
1701
+ * @returns Data directory path
1702
+ *
1703
+ * @example
1704
+ * ```typescript
1705
+ * const dataDir = getDataDirectory('juno-task');
1706
+ * ```
1707
+ */
1708
+ declare function getDataDirectory(appName?: string): string;
1709
+ /**
1710
+ * Get user cache directory path.
1711
+ *
1712
+ * @param appName - Application name for subdirectory
1713
+ * @returns Cache directory path
1714
+ *
1715
+ * @example
1716
+ * ```typescript
1717
+ * const cacheDir = getCacheDirectory('juno-task');
1718
+ * ```
1719
+ */
1720
+ declare function getCacheDirectory(appName?: string): string;
1721
+ /**
1722
+ * Create directory if it doesn't exist.
1723
+ *
1724
+ * @param dirPath - Directory path to create
1725
+ * @returns Promise that resolves when directory is created
1726
+ *
1727
+ * @example
1728
+ * ```typescript
1729
+ * await createDirectoryIfNotExists('/path/to/config');
1730
+ * ```
1731
+ */
1732
+ declare function createDirectoryIfNotExists(dirPath: string): Promise<void>;
1733
+ /**
1734
+ * Get current process information.
1735
+ *
1736
+ * @returns Process information object
1737
+ *
1738
+ * @example
1739
+ * ```typescript
1740
+ * const info = getProcessInfo();
1741
+ * console.log(`Process ID: ${info.pid}`);
1742
+ * ```
1743
+ */
1744
+ declare function getProcessInfo(): ProcessInfo;
1745
+ /**
1746
+ * Check if running with root/administrator privileges.
1747
+ *
1748
+ * @returns True if running as root
1749
+ *
1750
+ * @example
1751
+ * ```typescript
1752
+ * if (isRunningAsRoot()) {
1753
+ * console.warn('Running with elevated privileges');
1754
+ * }
1755
+ * ```
1756
+ */
1757
+ declare function isRunningAsRoot(): boolean;
1758
+ /**
1759
+ * Get process memory usage information.
1760
+ *
1761
+ * @returns Memory usage information
1762
+ *
1763
+ * @example
1764
+ * ```typescript
1765
+ * const memory = getMemoryUsage();
1766
+ * console.log(`Heap used: ${(memory.heapUsed / 1024 / 1024).toFixed(2)} MB`);
1767
+ * ```
1768
+ */
1769
+ declare function getMemoryUsage(): MemoryUsage;
1770
+ /**
1771
+ * Get CPU usage information.
1772
+ *
1773
+ * @returns CPU usage information
1774
+ *
1775
+ * @example
1776
+ * ```typescript
1777
+ * const cpu = getCpuUsage();
1778
+ * console.log(`User CPU time: ${cpu.user}μs`);
1779
+ * ```
1780
+ */
1781
+ declare function getCpuUsage(): CpuUsage;
1782
+ /**
1783
+ * Auto-discover MCP server location.
1784
+ * Searches common installation paths and PATH environment variable.
1785
+ *
1786
+ * @param serverName - MCP server executable name
1787
+ * @returns Promise that resolves to server path or null if not found
1788
+ *
1789
+ * @example
1790
+ * ```typescript
1791
+ * const serverPath = await findMCPServerPath('mcp-server');
1792
+ * if (serverPath) {
1793
+ * console.log(`Found MCP server at: ${serverPath}`);
1794
+ * }
1795
+ * ```
1796
+ */
1797
+ declare function findMCPServerPath(serverName?: string): Promise<string | null>;
1798
+ /**
1799
+ * Verify MCP server path is executable.
1800
+ *
1801
+ * @param serverPath - Path to MCP server executable
1802
+ * @returns Promise that resolves to true if valid and executable
1803
+ *
1804
+ * @example
1805
+ * ```typescript
1806
+ * const isValid = await validateMCPServerPath('/usr/local/bin/mcp-server');
1807
+ * if (isValid) {
1808
+ * console.log('MCP server is valid and executable');
1809
+ * }
1810
+ * ```
1811
+ */
1812
+ declare function validateMCPServerPath(serverPath: string): Promise<boolean>;
1813
+ /**
1814
+ * Get environment configuration for MCP server.
1815
+ *
1816
+ * @param additionalEnv - Additional environment variables
1817
+ * @returns MCP server environment configuration
1818
+ *
1819
+ * @example
1820
+ * ```typescript
1821
+ * const env = getMCPServerEnvironment({ DEBUG: 'true' });
1822
+ * console.log('MCP server environment:', env);
1823
+ * ```
1824
+ */
1825
+ declare function getMCPServerEnvironment(additionalEnv?: Record<string, string>): MCPServerEnvironment;
1826
+
1827
+ declare enum LogContext {
1828
+ CLI = "CLI",
1829
+ MCP = "MCP",
1830
+ ENGINE = "ENGINE",
1831
+ SESSION = "SESSION",
1832
+ TEMPLATE = "TEMPLATE",
1833
+ CONFIG = "CONFIG",
1834
+ PERFORMANCE = "PERFORMANCE",
1835
+ SYSTEM = "SYSTEM"
1836
+ }
1837
+
1838
+ /**
1839
+ * Hook execution utility module for juno-task-ts
1840
+ *
1841
+ * Provides robust hook execution functionality with comprehensive logging,
1842
+ * error handling, and execution context tracking.
1843
+ *
1844
+ * @module utils/hooks
1845
+ */
1846
+
1847
+ /**
1848
+ * Supported hook types for lifecycle execution
1849
+ */
1850
+ type HookType = 'START_RUN' | 'START_ITERATION' | 'END_ITERATION' | 'END_RUN' | 'ON_STALE';
1851
+ /**
1852
+ * Hook configuration interface
1853
+ */
1854
+ interface Hook {
1855
+ /** List of bash commands to execute for this hook */
1856
+ commands: string[];
1857
+ }
1858
+ /**
1859
+ * Complete hooks configuration mapping hook types to their configurations
1860
+ */
1861
+ interface HooksConfig {
1862
+ [key: string]: Hook;
1863
+ }
1864
+ /**
1865
+ * Execution context for hooks - provides information about the current execution state
1866
+ */
1867
+ interface HookExecutionContext {
1868
+ /** Current iteration number (for iteration-based hooks) */
1869
+ iteration?: number;
1870
+ /** Session ID for tracking */
1871
+ sessionId?: string;
1872
+ /** Working directory for command execution */
1873
+ workingDirectory?: string;
1874
+ /** Additional metadata */
1875
+ metadata?: Record<string, any>;
1876
+ /** Run ID for tracking across hooks */
1877
+ runId?: string;
1878
+ /** Total iterations planned */
1879
+ totalIterations?: number;
1880
+ }
1881
+ /**
1882
+ * Result of a single command execution within a hook
1883
+ */
1884
+ interface CommandExecutionResult {
1885
+ /** The command that was executed */
1886
+ command: string;
1887
+ /** Exit code (0 for success) */
1888
+ exitCode: number;
1889
+ /** Standard output */
1890
+ stdout: string;
1891
+ /** Standard error output */
1892
+ stderr: string;
1893
+ /** Execution duration in milliseconds */
1894
+ duration: number;
1895
+ /** Whether the command succeeded */
1896
+ success: boolean;
1897
+ /** Error if execution failed */
1898
+ error?: Error;
1899
+ }
1900
+ /**
1901
+ * Result of executing all commands in a hook
1902
+ */
1903
+ interface HookExecutionResult {
1904
+ /** Hook type that was executed */
1905
+ hookType: HookType;
1906
+ /** Total execution duration for all commands */
1907
+ totalDuration: number;
1908
+ /** Results for each command */
1909
+ commandResults: CommandExecutionResult[];
1910
+ /** Overall success (true if all commands succeeded) */
1911
+ success: boolean;
1912
+ /** Number of commands executed */
1913
+ commandsExecuted: number;
1914
+ /** Number of commands that failed */
1915
+ commandsFailed: number;
1916
+ }
1917
+ /**
1918
+ * Hook execution options
1919
+ */
1920
+ interface HookExecutionOptions {
1921
+ /** Maximum timeout per command in milliseconds (default: 300000 = 5 minutes) */
1922
+ commandTimeout?: number | undefined;
1923
+ /** Environment variables to pass to commands */
1924
+ env?: Record<string, string> | undefined;
1925
+ /** Whether to continue executing commands if one fails (default: true) */
1926
+ continueOnError?: boolean | undefined;
1927
+ /** Custom logger context (default: 'SYSTEM') */
1928
+ logContext?: LogContext | undefined;
1929
+ }
1930
+ /**
1931
+ * Execute a specific hook type with the provided context
1932
+ *
1933
+ * This is the main entry point for hook execution. It handles:
1934
+ * - Hook existence validation
1935
+ * - Sequential command execution
1936
+ * - Comprehensive logging with execution context
1937
+ * - Robust error handling (log but don't throw)
1938
+ * - Performance tracking
1939
+ *
1940
+ * @param hookType - The type of hook to execute
1941
+ * @param hooks - The complete hooks configuration
1942
+ * @param context - Execution context with iteration, session info, etc.
1943
+ * @param options - Additional execution options
1944
+ * @returns Promise that resolves when all commands complete (never throws)
1945
+ *
1946
+ * @example
1947
+ * ```typescript
1948
+ * const hooks = {
1949
+ * START_ITERATION: {
1950
+ * commands: ['echo "Starting iteration $ITERATION"', 'npm test']
1951
+ * }
1952
+ * };
1953
+ *
1954
+ * const context = {
1955
+ * iteration: 1,
1956
+ * sessionId: 'session-123',
1957
+ * workingDirectory: '/path/to/project'
1958
+ * };
1959
+ *
1960
+ * await executeHook('START_ITERATION', hooks, context);
1961
+ * ```
1962
+ */
1963
+ declare function executeHook(hookType: HookType, hooks: HooksConfig, context?: HookExecutionContext, options?: HookExecutionOptions): Promise<HookExecutionResult>;
1964
+ /**
1965
+ * Execute multiple hooks in sequence
1966
+ *
1967
+ * Convenience function for executing multiple hooks with the same context.
1968
+ * Each hook is executed independently - failure of one hook does not stop
1969
+ * execution of subsequent hooks.
1970
+ *
1971
+ * @param hookTypes - Array of hook types to execute
1972
+ * @param hooks - The complete hooks configuration
1973
+ * @param context - Execution context
1974
+ * @param options - Execution options
1975
+ * @returns Promise resolving to array of hook execution results
1976
+ */
1977
+ declare function executeHooks(hookTypes: HookType[], hooks: HooksConfig, context?: HookExecutionContext, options?: HookExecutionOptions): Promise<HookExecutionResult[]>;
1978
+ /**
1979
+ * Validate hooks configuration
1980
+ *
1981
+ * Checks that all hook configurations are valid and provides warnings
1982
+ * for common issues.
1983
+ *
1984
+ * @param hooks - Hooks configuration to validate
1985
+ * @returns Validation result with any issues found
1986
+ */
1987
+ declare function validateHooksConfig(hooks: HooksConfig): {
1988
+ valid: boolean;
1989
+ issues: string[];
1990
+ warnings: string[];
1991
+ };
1992
+
1993
+ /**
1994
+ * Validation Utilities Module for juno-code
1995
+ *
1996
+ * Provides Zod-based validation for configuration values.
1997
+ *
1998
+ * @module utils/validation
1999
+ */
2000
+
2001
+ /**
2002
+ * Schema for validating subagent types with alias support
2003
+ */
2004
+ declare const SubagentSchema: z.ZodEffects<z.ZodEffects<z.ZodString, "claude" | "cursor" | "codex" | "gemini" | "pi", string>, SubagentType, string>;
2005
+ /**
2006
+ * Schema for validating log levels
2007
+ */
2008
+ declare const LogLevelSchema: z.ZodEnum<["error", "warn", "info", "debug", "trace"]>;
2009
+ /**
2010
+ * Schema for validating session status
2011
+ */
2012
+ declare const SessionStatusSchema: z.ZodEnum<["running", "completed", "failed", "cancelled"]>;
2013
+ /**
2014
+ * Schema for validating iteration counts
2015
+ */
2016
+ declare const IterationsSchema: z.ZodEffects<z.ZodEffects<z.ZodNumber, number, number>, number, number>;
2017
+ /**
2018
+ * Schema for validating model names (subagent-specific)
2019
+ */
2020
+ declare const ModelSchema: z.ZodEffects<z.ZodString, string, string>;
2021
+ /**
2022
+ * Schema for runtime configuration validation
2023
+ */
2024
+ declare const ConfigValidationSchema: z.ZodObject<{
2025
+ defaultSubagent: z.ZodEnum<["claude", "cursor", "codex", "gemini", "pi"]>;
2026
+ defaultBackend: z.ZodEnum<["shell"]>;
2027
+ defaultMaxIterations: z.ZodNumber;
2028
+ defaultModel: z.ZodOptional<z.ZodString>;
2029
+ mainTask: z.ZodOptional<z.ZodString>;
2030
+ logLevel: z.ZodEnum<["error", "warn", "info", "debug", "trace"]>;
2031
+ logFile: z.ZodOptional<z.ZodString>;
2032
+ verbose: z.ZodEffects<z.ZodNumber, number, unknown>;
2033
+ quiet: z.ZodBoolean;
2034
+ mcpTimeout: z.ZodNumber;
2035
+ mcpRetries: z.ZodNumber;
2036
+ mcpServerPath: z.ZodOptional<z.ZodString>;
2037
+ mcpServerName: z.ZodOptional<z.ZodString>;
2038
+ hookCommandTimeout: z.ZodOptional<z.ZodNumber>;
2039
+ onHourlyLimit: z.ZodEnum<["wait", "raise"]>;
2040
+ interactive: z.ZodBoolean;
2041
+ headlessMode: z.ZodBoolean;
2042
+ workingDirectory: z.ZodString;
2043
+ sessionDirectory: z.ZodString;
2044
+ envFilePath: z.ZodOptional<z.ZodString>;
2045
+ envFileCopied: z.ZodOptional<z.ZodBoolean>;
2046
+ hooks: z.ZodOptional<z.ZodRecord<z.ZodEnum<["START_RUN", "START_ITERATION", "END_ITERATION", "END_RUN", "ON_STALE"]>, z.ZodObject<{
2047
+ commands: z.ZodArray<z.ZodString, "many">;
2048
+ }, "strip", z.ZodTypeAny, {
2049
+ commands?: string[];
2050
+ }, {
2051
+ commands?: string[];
2052
+ }>>>;
2053
+ skipHooks: z.ZodOptional<z.ZodBoolean>;
2054
+ }, "strict", z.ZodTypeAny, {
2055
+ defaultSubagent?: "claude" | "cursor" | "codex" | "gemini" | "pi";
2056
+ defaultBackend?: "shell";
2057
+ defaultMaxIterations?: number;
2058
+ defaultModel?: string;
2059
+ logLevel?: "error" | "warn" | "info" | "debug" | "trace";
2060
+ logFile?: string;
2061
+ verbose?: number;
2062
+ quiet?: boolean;
2063
+ mcpTimeout?: number;
2064
+ mcpRetries?: number;
2065
+ mcpServerPath?: string;
2066
+ mcpServerName?: string;
2067
+ hookCommandTimeout?: number;
2068
+ onHourlyLimit?: "wait" | "raise";
2069
+ interactive?: boolean;
2070
+ headlessMode?: boolean;
2071
+ workingDirectory?: string;
2072
+ sessionDirectory?: string;
2073
+ mainTask?: string;
2074
+ envFilePath?: string;
2075
+ envFileCopied?: boolean;
2076
+ hooks?: Partial<Record<"START_RUN" | "START_ITERATION" | "END_ITERATION" | "END_RUN" | "ON_STALE", {
2077
+ commands?: string[];
2078
+ }>>;
2079
+ skipHooks?: boolean;
2080
+ }, {
2081
+ defaultSubagent?: "claude" | "cursor" | "codex" | "gemini" | "pi";
2082
+ defaultBackend?: "shell";
2083
+ defaultMaxIterations?: number;
2084
+ defaultModel?: string;
2085
+ logLevel?: "error" | "warn" | "info" | "debug" | "trace";
2086
+ logFile?: string;
2087
+ verbose?: unknown;
2088
+ quiet?: boolean;
2089
+ mcpTimeout?: number;
2090
+ mcpRetries?: number;
2091
+ mcpServerPath?: string;
2092
+ mcpServerName?: string;
2093
+ hookCommandTimeout?: number;
2094
+ onHourlyLimit?: "wait" | "raise";
2095
+ interactive?: boolean;
2096
+ headlessMode?: boolean;
2097
+ workingDirectory?: string;
2098
+ sessionDirectory?: string;
2099
+ mainTask?: string;
2100
+ envFilePath?: string;
2101
+ envFileCopied?: boolean;
2102
+ hooks?: Partial<Record<"START_RUN" | "START_ITERATION" | "END_ITERATION" | "END_RUN" | "ON_STALE", {
2103
+ commands?: string[];
2104
+ }>>;
2105
+ skipHooks?: boolean;
2106
+ }>;
2107
+ /**
2108
+ * Validate and normalize subagent names including aliases
2109
+ */
2110
+ declare function validateSubagent(subagent: string): SubagentType;
2111
+ /**
2112
+ * Validate model names for specific subagents
2113
+ */
2114
+ declare function validateModel(model: string, _subagent?: SubagentType): string;
2115
+ /**
2116
+ * Validate iteration counts (positive integers or -1 for infinite)
2117
+ */
2118
+ declare function validateIterations(iterations: number): number;
2119
+ /**
2120
+ * Validate log level strings
2121
+ */
2122
+ declare function validateLogLevel(logLevel: string): LogLevel;
2123
+ /**
2124
+ * Environment variable validation
2125
+ */
2126
+ declare function validateEnvironmentVars(envVars: Record<string, string | undefined>): Partial<JunoTaskConfig>;
2127
+
2128
+ /**
2129
+ * Version information for juno-task-ts
2130
+ */
2131
+ declare const version: string;
2132
+
2133
+ export { type Architecture, type BackendType, type CleanupOptions, type ColorSupport, type CommandExecutionResult, type ConfigLoadOptions, ConfigLoader, ConfigValidationSchema, type CpuUsage, DEFAULT_CONFIG, DEFAULT_ERROR_RECOVERY_CONFIG, DEFAULT_HOOKS, DEFAULT_PROGRESS_CONFIG, DEFAULT_RATE_LIMIT_CONFIG, ENV_VAR_MAPPING, type EnvVarMapping, type ErrorRecoveryConfig, ExecutionEngine, type ExecutionEngineConfig, type ExecutionRequest, type ExecutionResult, type ExecutionStatistics, ExecutionStatus, FileSessionStorage, type Hook$1 as Hook, type HookExecutionContext, type HookExecutionOptions, type HookExecutionResult, type HookType$1 as HookType, type Hooks, type HooksConfig, type IterationResult, IterationsSchema, type JunoTaskConfig, JunoTaskConfigSchema, type LogLevel, LogLevelSchema, type MCPServerEnvironment, type MemoryUsage, ModelSchema, type NodeEnvironment, type OnHourlyLimit, type PerformanceMetrics, type Platform, type ProcessInfo, type ProgressEventFilter, type ProgressEventProcessor, type ProgressEventType$1 as ProgressEventType, type ProgressTrackingConfig, type RateLimitHandlingConfig, type RateLimitInfo, type RateLimitParser, type Session, type SessionHistoryEntry, type SessionInfo, type SessionListFilter, SessionManager, type SessionStatistics, type SessionStatus, SessionStatusSchema, type SessionStorage, type ShellType, SubagentSchema, type SubagentType, type ThroughputMetrics, createDirectoryIfNotExists, createExecutionEngine, createExecutionRequest, createSessionManager, executeHook, executeHooks, findMCPServerPath, getArchitecture, getCacheDirectory, getColorSupport, getConfigDirectory, getCpuUsage, getDataDirectory, getDefaultHooks, getDefaultHooksJson, getEnvVar, getEnvVarWithDefault, getHomeDirectory, getMCPServerEnvironment, getMemoryUsage, getNodeEnvironment, getPlatform, getProcessInfo, getShell, getTempDirectory, getTerminalHeight, getTerminalWidth, isCIEnvironment, isDevelopmentMode, isHeadlessEnvironment, isInDocker, isInteractiveTerminal, isRunningAsRoot, loadConfig, parseEnvArray, parseEnvBoolean, parseEnvNumber, setEnvVar, supportsColor, validateConfig, validateEnvironmentVars, validateHooksConfig, validateIterations, validateLogLevel, validateMCPServerPath, validateModel, validateSubagent, version };