aicodeman 0.2.8

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 (246) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +403 -0
  3. package/dist/ai-checker-base.d.ts +175 -0
  4. package/dist/ai-checker-base.d.ts.map +1 -0
  5. package/dist/ai-checker-base.js +424 -0
  6. package/dist/ai-checker-base.js.map +1 -0
  7. package/dist/ai-idle-checker.d.ts +53 -0
  8. package/dist/ai-idle-checker.d.ts.map +1 -0
  9. package/dist/ai-idle-checker.js +141 -0
  10. package/dist/ai-idle-checker.js.map +1 -0
  11. package/dist/ai-plan-checker.d.ts +52 -0
  12. package/dist/ai-plan-checker.d.ts.map +1 -0
  13. package/dist/ai-plan-checker.js +103 -0
  14. package/dist/ai-plan-checker.js.map +1 -0
  15. package/dist/bash-tool-parser.d.ts +191 -0
  16. package/dist/bash-tool-parser.d.ts.map +1 -0
  17. package/dist/bash-tool-parser.js +598 -0
  18. package/dist/bash-tool-parser.js.map +1 -0
  19. package/dist/cli.d.ts +12 -0
  20. package/dist/cli.d.ts.map +1 -0
  21. package/dist/cli.js +460 -0
  22. package/dist/cli.js.map +1 -0
  23. package/dist/config/buffer-limits.d.ts +59 -0
  24. package/dist/config/buffer-limits.d.ts.map +1 -0
  25. package/dist/config/buffer-limits.js +74 -0
  26. package/dist/config/buffer-limits.js.map +1 -0
  27. package/dist/config/map-limits.d.ts +40 -0
  28. package/dist/config/map-limits.d.ts.map +1 -0
  29. package/dist/config/map-limits.js +52 -0
  30. package/dist/config/map-limits.js.map +1 -0
  31. package/dist/file-stream-manager.d.ts +148 -0
  32. package/dist/file-stream-manager.d.ts.map +1 -0
  33. package/dist/file-stream-manager.js +351 -0
  34. package/dist/file-stream-manager.js.map +1 -0
  35. package/dist/hooks-config.d.ts +31 -0
  36. package/dist/hooks-config.d.ts.map +1 -0
  37. package/dist/hooks-config.js +115 -0
  38. package/dist/hooks-config.js.map +1 -0
  39. package/dist/image-watcher.d.ts +86 -0
  40. package/dist/image-watcher.d.ts.map +1 -0
  41. package/dist/image-watcher.js +275 -0
  42. package/dist/image-watcher.js.map +1 -0
  43. package/dist/index.d.ts +11 -0
  44. package/dist/index.d.ts.map +1 -0
  45. package/dist/index.js +54 -0
  46. package/dist/index.js.map +1 -0
  47. package/dist/mux-factory.d.ts +13 -0
  48. package/dist/mux-factory.d.ts.map +1 -0
  49. package/dist/mux-factory.js +19 -0
  50. package/dist/mux-factory.js.map +1 -0
  51. package/dist/mux-interface.d.ts +145 -0
  52. package/dist/mux-interface.d.ts.map +1 -0
  53. package/dist/mux-interface.js +9 -0
  54. package/dist/mux-interface.js.map +1 -0
  55. package/dist/plan-orchestrator.d.ts +123 -0
  56. package/dist/plan-orchestrator.d.ts.map +1 -0
  57. package/dist/plan-orchestrator.js +500 -0
  58. package/dist/plan-orchestrator.js.map +1 -0
  59. package/dist/prompts/index.d.ts +9 -0
  60. package/dist/prompts/index.d.ts.map +1 -0
  61. package/dist/prompts/index.js +9 -0
  62. package/dist/prompts/index.js.map +1 -0
  63. package/dist/prompts/planner.d.ts +14 -0
  64. package/dist/prompts/planner.d.ts.map +1 -0
  65. package/dist/prompts/planner.js +83 -0
  66. package/dist/prompts/planner.js.map +1 -0
  67. package/dist/prompts/research-agent.d.ts +10 -0
  68. package/dist/prompts/research-agent.d.ts.map +1 -0
  69. package/dist/prompts/research-agent.js +143 -0
  70. package/dist/prompts/research-agent.js.map +1 -0
  71. package/dist/push-store.d.ts +41 -0
  72. package/dist/push-store.d.ts.map +1 -0
  73. package/dist/push-store.js +168 -0
  74. package/dist/push-store.js.map +1 -0
  75. package/dist/ralph-config.d.ts +67 -0
  76. package/dist/ralph-config.d.ts.map +1 -0
  77. package/dist/ralph-config.js +134 -0
  78. package/dist/ralph-config.js.map +1 -0
  79. package/dist/ralph-loop.d.ts +124 -0
  80. package/dist/ralph-loop.d.ts.map +1 -0
  81. package/dist/ralph-loop.js +418 -0
  82. package/dist/ralph-loop.js.map +1 -0
  83. package/dist/ralph-tracker.d.ts +1081 -0
  84. package/dist/ralph-tracker.d.ts.map +1 -0
  85. package/dist/ralph-tracker.js +3343 -0
  86. package/dist/ralph-tracker.js.map +1 -0
  87. package/dist/respawn-controller.d.ts +1182 -0
  88. package/dist/respawn-controller.d.ts.map +1 -0
  89. package/dist/respawn-controller.js +2754 -0
  90. package/dist/respawn-controller.js.map +1 -0
  91. package/dist/run-summary.d.ts +123 -0
  92. package/dist/run-summary.d.ts.map +1 -0
  93. package/dist/run-summary.js +325 -0
  94. package/dist/run-summary.js.map +1 -0
  95. package/dist/session-lifecycle-log.d.ts +36 -0
  96. package/dist/session-lifecycle-log.d.ts.map +1 -0
  97. package/dist/session-lifecycle-log.js +101 -0
  98. package/dist/session-lifecycle-log.js.map +1 -0
  99. package/dist/session-manager.d.ts +97 -0
  100. package/dist/session-manager.d.ts.map +1 -0
  101. package/dist/session-manager.js +224 -0
  102. package/dist/session-manager.js.map +1 -0
  103. package/dist/session.d.ts +686 -0
  104. package/dist/session.d.ts.map +1 -0
  105. package/dist/session.js +2025 -0
  106. package/dist/session.js.map +1 -0
  107. package/dist/state-store.d.ts +189 -0
  108. package/dist/state-store.d.ts.map +1 -0
  109. package/dist/state-store.js +730 -0
  110. package/dist/state-store.js.map +1 -0
  111. package/dist/subagent-watcher.d.ts +345 -0
  112. package/dist/subagent-watcher.d.ts.map +1 -0
  113. package/dist/subagent-watcher.js +1469 -0
  114. package/dist/subagent-watcher.js.map +1 -0
  115. package/dist/task-queue.d.ts +108 -0
  116. package/dist/task-queue.d.ts.map +1 -0
  117. package/dist/task-queue.js +235 -0
  118. package/dist/task-queue.js.map +1 -0
  119. package/dist/task-tracker.d.ts +306 -0
  120. package/dist/task-tracker.d.ts.map +1 -0
  121. package/dist/task-tracker.js +488 -0
  122. package/dist/task-tracker.js.map +1 -0
  123. package/dist/task.d.ts +73 -0
  124. package/dist/task.d.ts.map +1 -0
  125. package/dist/task.js +177 -0
  126. package/dist/task.js.map +1 -0
  127. package/dist/team-watcher.d.ts +53 -0
  128. package/dist/team-watcher.d.ts.map +1 -0
  129. package/dist/team-watcher.js +313 -0
  130. package/dist/team-watcher.js.map +1 -0
  131. package/dist/templates/case-template.md +461 -0
  132. package/dist/templates/claude-md.d.ts +26 -0
  133. package/dist/templates/claude-md.d.ts.map +1 -0
  134. package/dist/templates/claude-md.js +74 -0
  135. package/dist/templates/claude-md.js.map +1 -0
  136. package/dist/tmux-manager.d.ts +181 -0
  137. package/dist/tmux-manager.d.ts.map +1 -0
  138. package/dist/tmux-manager.js +1405 -0
  139. package/dist/tmux-manager.js.map +1 -0
  140. package/dist/transcript-watcher.d.ts +110 -0
  141. package/dist/transcript-watcher.d.ts.map +1 -0
  142. package/dist/transcript-watcher.js +338 -0
  143. package/dist/transcript-watcher.js.map +1 -0
  144. package/dist/tunnel-manager.d.ts +54 -0
  145. package/dist/tunnel-manager.d.ts.map +1 -0
  146. package/dist/tunnel-manager.js +251 -0
  147. package/dist/tunnel-manager.js.map +1 -0
  148. package/dist/types.d.ts +1139 -0
  149. package/dist/types.d.ts.map +1 -0
  150. package/dist/types.js +215 -0
  151. package/dist/types.js.map +1 -0
  152. package/dist/utils/buffer-accumulator.d.ts +111 -0
  153. package/dist/utils/buffer-accumulator.d.ts.map +1 -0
  154. package/dist/utils/buffer-accumulator.js +172 -0
  155. package/dist/utils/buffer-accumulator.js.map +1 -0
  156. package/dist/utils/claude-cli-resolver.d.ts +26 -0
  157. package/dist/utils/claude-cli-resolver.d.ts.map +1 -0
  158. package/dist/utils/claude-cli-resolver.js +78 -0
  159. package/dist/utils/claude-cli-resolver.js.map +1 -0
  160. package/dist/utils/cleanup-manager.d.ts +165 -0
  161. package/dist/utils/cleanup-manager.d.ts.map +1 -0
  162. package/dist/utils/cleanup-manager.js +274 -0
  163. package/dist/utils/cleanup-manager.js.map +1 -0
  164. package/dist/utils/index.d.ts +19 -0
  165. package/dist/utils/index.d.ts.map +1 -0
  166. package/dist/utils/index.js +19 -0
  167. package/dist/utils/index.js.map +1 -0
  168. package/dist/utils/lru-map.d.ts +140 -0
  169. package/dist/utils/lru-map.d.ts.map +1 -0
  170. package/dist/utils/lru-map.js +234 -0
  171. package/dist/utils/lru-map.js.map +1 -0
  172. package/dist/utils/nice-wrapper.d.ts +13 -0
  173. package/dist/utils/nice-wrapper.d.ts.map +1 -0
  174. package/dist/utils/nice-wrapper.js +17 -0
  175. package/dist/utils/nice-wrapper.js.map +1 -0
  176. package/dist/utils/opencode-cli-resolver.d.ts +21 -0
  177. package/dist/utils/opencode-cli-resolver.d.ts.map +1 -0
  178. package/dist/utils/opencode-cli-resolver.js +67 -0
  179. package/dist/utils/opencode-cli-resolver.js.map +1 -0
  180. package/dist/utils/regex-patterns.d.ts +64 -0
  181. package/dist/utils/regex-patterns.d.ts.map +1 -0
  182. package/dist/utils/regex-patterns.js +74 -0
  183. package/dist/utils/regex-patterns.js.map +1 -0
  184. package/dist/utils/stale-expiration-map.d.ts +159 -0
  185. package/dist/utils/stale-expiration-map.d.ts.map +1 -0
  186. package/dist/utils/stale-expiration-map.js +277 -0
  187. package/dist/utils/stale-expiration-map.js.map +1 -0
  188. package/dist/utils/string-similarity.d.ts +108 -0
  189. package/dist/utils/string-similarity.d.ts.map +1 -0
  190. package/dist/utils/string-similarity.js +189 -0
  191. package/dist/utils/string-similarity.js.map +1 -0
  192. package/dist/utils/token-validation.d.ts +39 -0
  193. package/dist/utils/token-validation.d.ts.map +1 -0
  194. package/dist/utils/token-validation.js +59 -0
  195. package/dist/utils/token-validation.js.map +1 -0
  196. package/dist/utils/type-safety.d.ts +33 -0
  197. package/dist/utils/type-safety.d.ts.map +1 -0
  198. package/dist/utils/type-safety.js +35 -0
  199. package/dist/utils/type-safety.js.map +1 -0
  200. package/dist/web/public/app.js +491 -0
  201. package/dist/web/public/app.js.br +0 -0
  202. package/dist/web/public/app.js.gz +0 -0
  203. package/dist/web/public/index.html +1675 -0
  204. package/dist/web/public/index.html.br +0 -0
  205. package/dist/web/public/index.html.gz +0 -0
  206. package/dist/web/public/manifest.json +8 -0
  207. package/dist/web/public/mobile.css +1 -0
  208. package/dist/web/public/mobile.css.br +0 -0
  209. package/dist/web/public/mobile.css.gz +0 -0
  210. package/dist/web/public/ralph-wizard.js +1037 -0
  211. package/dist/web/public/ralph-wizard.js.br +0 -0
  212. package/dist/web/public/ralph-wizard.js.gz +0 -0
  213. package/dist/web/public/styles.css +1 -0
  214. package/dist/web/public/styles.css.br +0 -0
  215. package/dist/web/public/styles.css.gz +0 -0
  216. package/dist/web/public/sw.js +67 -0
  217. package/dist/web/public/sw.js.br +0 -0
  218. package/dist/web/public/sw.js.gz +0 -0
  219. package/dist/web/public/upload.html +155 -0
  220. package/dist/web/public/upload.html.br +0 -0
  221. package/dist/web/public/upload.html.gz +0 -0
  222. package/dist/web/public/vendor/xterm-addon-fit.min.js +1 -0
  223. package/dist/web/public/vendor/xterm-addon-fit.min.js.br +0 -0
  224. package/dist/web/public/vendor/xterm-addon-fit.min.js.gz +0 -0
  225. package/dist/web/public/vendor/xterm-addon-unicode11.min.js +1 -0
  226. package/dist/web/public/vendor/xterm-addon-unicode11.min.js.br +0 -0
  227. package/dist/web/public/vendor/xterm-addon-unicode11.min.js.gz +0 -0
  228. package/dist/web/public/vendor/xterm-addon-webgl.min.js +2 -0
  229. package/dist/web/public/vendor/xterm-addon-webgl.min.js.br +0 -0
  230. package/dist/web/public/vendor/xterm-addon-webgl.min.js.gz +0 -0
  231. package/dist/web/public/vendor/xterm.css +209 -0
  232. package/dist/web/public/vendor/xterm.css.br +0 -0
  233. package/dist/web/public/vendor/xterm.css.gz +0 -0
  234. package/dist/web/public/vendor/xterm.min.js +9 -0
  235. package/dist/web/public/vendor/xterm.min.js.br +0 -0
  236. package/dist/web/public/vendor/xterm.min.js.gz +0 -0
  237. package/dist/web/schemas.d.ts +479 -0
  238. package/dist/web/schemas.d.ts.map +1 -0
  239. package/dist/web/schemas.js +448 -0
  240. package/dist/web/schemas.js.map +1 -0
  241. package/dist/web/server.d.ts +207 -0
  242. package/dist/web/server.d.ts.map +1 -0
  243. package/dist/web/server.js +5784 -0
  244. package/dist/web/server.js.map +1 -0
  245. package/package.json +110 -0
  246. package/scripts/postinstall.js +390 -0
@@ -0,0 +1,686 @@
1
+ /**
2
+ * @fileoverview Core PTY session wrapper for Claude CLI interactions.
3
+ *
4
+ * This module provides the Session class which manages a PTY (pseudo-terminal)
5
+ * process running the Claude CLI. It supports three operation modes:
6
+ *
7
+ * 1. **One-shot mode** (`runPrompt`): Execute a single prompt and get JSON response
8
+ * 2. **Interactive mode** (`startInteractive`): Start an interactive Claude session
9
+ * 3. **Shell mode**: Run a plain bash shell for debugging/testing
10
+ *
11
+ * The session can optionally run inside a tmux session for persistence across disconnects.
12
+ * It tracks tokens, costs, background tasks, and supports
13
+ * auto-clear/auto-compact functionality when token limits are approached.
14
+ *
15
+ * @module session
16
+ */
17
+ import { EventEmitter } from 'node:events';
18
+ import { SessionState, SessionStatus, SessionConfig, RalphTrackerState, RalphTodoItem, ActiveBashTool, NiceConfig, type ClaudeMode, type SessionMode, type OpenCodeConfig } from './types.js';
19
+ import type { TerminalMultiplexer, MuxSession } from './mux-interface.js';
20
+ import { TaskTracker, type BackgroundTask } from './task-tracker.js';
21
+ import { RalphTracker } from './ralph-tracker.js';
22
+ import { BashToolParser } from './bash-tool-parser.js';
23
+ export type { BackgroundTask } from './task-tracker.js';
24
+ export type { RalphTrackerState, RalphTodoItem, ActiveBashTool } from './types.js';
25
+ /**
26
+ * Represents a JSON message from Claude CLI's stream-json output format.
27
+ * Messages are newline-delimited JSON objects parsed from PTY output.
28
+ */
29
+ export interface ClaudeMessage {
30
+ /** Message type indicating the role or purpose */
31
+ type: 'system' | 'assistant' | 'user' | 'result';
32
+ /** Optional subtype for further classification */
33
+ subtype?: string;
34
+ /** Claude's internal session identifier */
35
+ session_id?: string;
36
+ /** Message content with optional token usage */
37
+ message?: {
38
+ content: Array<{
39
+ type: string;
40
+ text?: string;
41
+ }>;
42
+ usage?: {
43
+ input_tokens: number;
44
+ output_tokens: number;
45
+ };
46
+ };
47
+ /** Final result text (on result messages) */
48
+ result?: string;
49
+ /** Whether this message represents an error */
50
+ is_error?: boolean;
51
+ /** Total cost in USD (on result messages) */
52
+ total_cost_usd?: number;
53
+ /** Total duration in milliseconds (on result messages) */
54
+ duration_ms?: number;
55
+ }
56
+ /**
57
+ * Event signatures emitted by the Session class.
58
+ * Subscribe using `session.on('eventName', handler)`.
59
+ */
60
+ export interface SessionEvents {
61
+ /** Processed text output (ANSI stripped) */
62
+ output: (data: string) => void;
63
+ /** Parsed JSON message from Claude CLI */
64
+ message: (msg: ClaudeMessage) => void;
65
+ /** Error output from the session */
66
+ error: (data: string) => void;
67
+ /** Session process exited */
68
+ exit: (code: number | null) => void;
69
+ /** One-shot prompt completed with result and cost */
70
+ completion: (result: string, cost: number) => void;
71
+ /** Raw terminal data (includes ANSI codes) */
72
+ terminal: (data: string) => void;
73
+ /** Signal to clear terminal display (after mux attach) */
74
+ clearTerminal: () => void;
75
+ /** New background task started */
76
+ taskCreated: (task: BackgroundTask) => void;
77
+ /** Background task status changed */
78
+ taskUpdated: (task: BackgroundTask) => void;
79
+ /** Background task finished successfully */
80
+ taskCompleted: (task: BackgroundTask) => void;
81
+ /** Background task failed with error */
82
+ taskFailed: (task: BackgroundTask, error: string) => void;
83
+ /** Auto-clear triggered due to token threshold */
84
+ autoClear: (data: {
85
+ tokens: number;
86
+ threshold: number;
87
+ }) => void;
88
+ /** Auto-compact triggered due to token threshold */
89
+ autoCompact: (data: {
90
+ tokens: number;
91
+ threshold: number;
92
+ prompt?: string;
93
+ }) => void;
94
+ /** Ralph loop state changed */
95
+ ralphLoopUpdate: (state: RalphTrackerState) => void;
96
+ /** Ralph todo list updated */
97
+ ralphTodoUpdate: (todos: RalphTodoItem[]) => void;
98
+ /** Ralph completion phrase detected */
99
+ ralphCompletionDetected: (phrase: string) => void;
100
+ /** RALPH_STATUS block detected */
101
+ ralphStatusBlockDetected: (block: import('./types.js').RalphStatusBlock) => void;
102
+ /** Circuit breaker state changed */
103
+ ralphCircuitBreakerUpdate: (status: import('./types.js').CircuitBreakerStatus) => void;
104
+ /** Dual-condition exit gate met */
105
+ ralphExitGateMet: (data: {
106
+ completionIndicators: number;
107
+ exitSignal: boolean;
108
+ }) => void;
109
+ /** Bash tool with file paths started */
110
+ bashToolStart: (tool: ActiveBashTool) => void;
111
+ /** Bash tool completed */
112
+ bashToolEnd: (tool: ActiveBashTool) => void;
113
+ /** Active Bash tools list updated */
114
+ bashToolsUpdate: (tools: ActiveBashTool[]) => void;
115
+ /** CLI info (version, model, account) updated */
116
+ cliInfoUpdated: (info: {
117
+ version: string | null;
118
+ model: string | null;
119
+ accountType: string | null;
120
+ latestVersion: string | null;
121
+ }) => void;
122
+ }
123
+ export type { SessionMode } from './types.js';
124
+ /**
125
+ * Core session class that wraps a PTY process running Claude CLI or a shell.
126
+ *
127
+ * @example
128
+ * ```typescript
129
+ * // Create and start an interactive Claude session
130
+ * const session = new Session({
131
+ * workingDir: '/path/to/project',
132
+ * mux: muxManager,
133
+ * useMux: true
134
+ * });
135
+ * await session.startInteractive();
136
+ *
137
+ * // Listen for events
138
+ * session.on('terminal', (data) => console.log(data));
139
+ * session.on('message', (msg) => console.log('Claude:', msg));
140
+ *
141
+ * // Send input
142
+ * session.write('Hello Claude!\r');
143
+ *
144
+ * // Stop when done
145
+ * await session.stop();
146
+ * ```
147
+ *
148
+ * @fires Session#terminal - Raw terminal output
149
+ * @fires Session#message - Parsed Claude JSON message
150
+ * @fires Session#completion - One-shot prompt completed
151
+ * @fires Session#exit - Process exited
152
+ * @fires Session#autoClear - Token threshold reached, clearing context
153
+ * @fires Session#autoCompact - Token threshold reached, compacting context
154
+ */
155
+ export declare class Session extends EventEmitter {
156
+ readonly id: string;
157
+ readonly workingDir: string;
158
+ readonly createdAt: number;
159
+ readonly mode: SessionMode;
160
+ /** Maximum number of task descriptions to keep (LRUMap handles size limit automatically) */
161
+ private static readonly MAX_TASK_DESCRIPTIONS;
162
+ private static readonly TASK_DESCRIPTION_MAX_AGE_MS;
163
+ private _name;
164
+ private ptyProcess;
165
+ private _pid;
166
+ private _status;
167
+ private _currentTaskId;
168
+ private _terminalBuffer;
169
+ private _textOutput;
170
+ private _errorBuffer;
171
+ private _lastActivityAt;
172
+ private _claudeSessionId;
173
+ private _totalCost;
174
+ private _messages;
175
+ private _lineBuffer;
176
+ private _lineBufferFlushTimer;
177
+ private resolvePromise;
178
+ private rejectPromise;
179
+ private _promptResolved;
180
+ private _isWorking;
181
+ private _lastPromptTime;
182
+ private activityTimeout;
183
+ private _awaitingIdleConfirmation;
184
+ private _taskTracker;
185
+ private _totalInputTokens;
186
+ private _totalOutputTokens;
187
+ private _autoClearThreshold;
188
+ private _autoClearEnabled;
189
+ private _isClearing;
190
+ private _autoCompactThreshold;
191
+ private _autoCompactEnabled;
192
+ private _autoCompactPrompt;
193
+ private _isCompacting;
194
+ private _imageWatcherEnabled;
195
+ private _flickerFilterEnabled;
196
+ private _cliVersion;
197
+ private _cliModel;
198
+ private _cliAccountType;
199
+ private _cliLatestVersion;
200
+ private _cliInfoParsed;
201
+ private _autoCompactTimer;
202
+ private _autoClearTimer;
203
+ private _promptCheckInterval;
204
+ private _promptCheckTimeout;
205
+ private _shellIdleTimer;
206
+ private _mux;
207
+ private _muxSession;
208
+ private _useMux;
209
+ private _isStopped;
210
+ private _ralphTracker;
211
+ private _parentAgentId;
212
+ private _childAgentIds;
213
+ private _niceConfig;
214
+ private _model;
215
+ private _claudeMode;
216
+ private _allowedTools;
217
+ private _openCodeConfig;
218
+ private _color;
219
+ private _taskTrackerHandlers;
220
+ private _ralphHandlers;
221
+ private _bashToolParser;
222
+ private _bashToolHandlers;
223
+ private _recentTaskDescriptions;
224
+ private _lastExpensiveProcessTime;
225
+ private _pendingCleanData;
226
+ private _expensiveProcessTimer;
227
+ private static readonly EXPENSIVE_PROCESS_INTERVAL_MS;
228
+ constructor(config: Partial<SessionConfig> & {
229
+ workingDir: string;
230
+ mode?: SessionMode;
231
+ name?: string;
232
+ /** Terminal multiplexer instance (tmux) */
233
+ mux?: TerminalMultiplexer;
234
+ /** Whether to use multiplexer wrapping */
235
+ useMux?: boolean;
236
+ /** Existing mux session for restored sessions */
237
+ muxSession?: MuxSession;
238
+ niceConfig?: NiceConfig;
239
+ /** Claude model override (e.g., 'opus', 'sonnet', 'haiku') */
240
+ model?: string;
241
+ /** Claude CLI startup permission mode */
242
+ claudeMode?: ClaudeMode;
243
+ /** Comma-separated allowed tools (for 'allowedTools' mode) */
244
+ allowedTools?: string;
245
+ /** OpenCode configuration (only for mode === 'opencode') */
246
+ openCodeConfig?: OpenCodeConfig;
247
+ });
248
+ get status(): SessionStatus;
249
+ get currentTaskId(): string | null;
250
+ get pid(): number | null;
251
+ get terminalBuffer(): string;
252
+ get terminalBufferLength(): number;
253
+ get textOutput(): string;
254
+ get errorBuffer(): string;
255
+ get lastActivityAt(): number;
256
+ get claudeSessionId(): string | null;
257
+ get totalCost(): number;
258
+ get messages(): ClaudeMessage[];
259
+ get isWorking(): boolean;
260
+ get lastPromptTime(): number;
261
+ get taskTracker(): TaskTracker;
262
+ get runningTaskCount(): number;
263
+ get taskTree(): BackgroundTask[];
264
+ get taskStats(): {
265
+ total: number;
266
+ running: number;
267
+ completed: number;
268
+ failed: number;
269
+ };
270
+ get ralphTracker(): RalphTracker;
271
+ get ralphLoopState(): RalphTrackerState;
272
+ get ralphTodos(): RalphTodoItem[];
273
+ get ralphTodoStats(): {
274
+ total: number;
275
+ pending: number;
276
+ inProgress: number;
277
+ completed: number;
278
+ };
279
+ get bashToolParser(): BashToolParser;
280
+ get activeTools(): ActiveBashTool[];
281
+ get parentAgentId(): string | null;
282
+ set parentAgentId(value: string | null);
283
+ get childAgentIds(): string[];
284
+ addChildAgentId(agentId: string): void;
285
+ removeChildAgentId(agentId: string): void;
286
+ get niceConfig(): NiceConfig;
287
+ /** Claude CLI startup permission mode */
288
+ get claudeMode(): ClaudeMode;
289
+ /** Allowed tools list (for 'allowedTools' mode) */
290
+ get allowedTools(): string | undefined;
291
+ /**
292
+ * Build Claude CLI permission flags based on the configured mode.
293
+ * Returns an array of args to pass to the CLI.
294
+ */
295
+ private _buildPermissionArgs;
296
+ /**
297
+ * Set CPU priority configuration.
298
+ * Note: This only affects new sessions; existing running processes won't be changed.
299
+ */
300
+ setNice(config: Partial<NiceConfig>): void;
301
+ get color(): import('./types.js').SessionColor;
302
+ setColor(color: import('./types.js').SessionColor): void;
303
+ get totalTokens(): number;
304
+ get inputTokens(): number;
305
+ get outputTokens(): number;
306
+ /**
307
+ * Restore token and cost values from saved state.
308
+ * Called when recovering sessions after server restart.
309
+ */
310
+ restoreTokens(inputTokens: number, outputTokens: number, totalCost: number): void;
311
+ get autoClearThreshold(): number;
312
+ get autoClearEnabled(): boolean;
313
+ get name(): string;
314
+ set name(value: string);
315
+ /** Minimum valid threshold for auto-clear/compact (1000 tokens) */
316
+ private static readonly MIN_AUTO_THRESHOLD;
317
+ /** Maximum valid threshold for auto-clear/compact (500k tokens) */
318
+ private static readonly MAX_AUTO_THRESHOLD;
319
+ /** Default auto-clear threshold when invalid value provided */
320
+ private static readonly DEFAULT_AUTO_CLEAR_THRESHOLD;
321
+ /** Default auto-compact threshold when invalid value provided */
322
+ private static readonly DEFAULT_AUTO_COMPACT_THRESHOLD;
323
+ setAutoClear(enabled: boolean, threshold?: number): void;
324
+ get autoCompactThreshold(): number;
325
+ get autoCompactEnabled(): boolean;
326
+ get autoCompactPrompt(): string;
327
+ setAutoCompact(enabled: boolean, threshold?: number, prompt?: string): void;
328
+ get imageWatcherEnabled(): boolean;
329
+ set imageWatcherEnabled(enabled: boolean);
330
+ get flickerFilterEnabled(): boolean;
331
+ set flickerFilterEnabled(enabled: boolean);
332
+ isIdle(): boolean;
333
+ isBusy(): boolean;
334
+ isRunning(): boolean;
335
+ toState(): SessionState;
336
+ toDetailedState(): {
337
+ textOutput: string;
338
+ terminalBuffer: string;
339
+ name: string;
340
+ mode: SessionMode;
341
+ claudeSessionId: string | null;
342
+ totalCost: number;
343
+ messageCount: number;
344
+ isWorking: boolean;
345
+ lastPromptTime: number;
346
+ bufferStats: {
347
+ terminalBufferSize: number;
348
+ textOutputSize: number;
349
+ messageCount: number;
350
+ maxTerminalBuffer: number;
351
+ maxTextOutput: number;
352
+ maxMessages: number;
353
+ };
354
+ taskStats: {
355
+ total: number;
356
+ running: number;
357
+ completed: number;
358
+ failed: number;
359
+ };
360
+ taskTree: Omit<BackgroundTask, "output">[];
361
+ tokens: {
362
+ input: number;
363
+ output: number;
364
+ total: number;
365
+ };
366
+ autoClear: {
367
+ enabled: boolean;
368
+ threshold: number;
369
+ };
370
+ nice: {
371
+ enabled: boolean;
372
+ niceValue: number;
373
+ };
374
+ ralphLoop: RalphTrackerState;
375
+ ralphTodos: RalphTodoItem[];
376
+ ralphTodoStats: {
377
+ total: number;
378
+ pending: number;
379
+ inProgress: number;
380
+ completed: number;
381
+ };
382
+ id: string;
383
+ pid: number | null;
384
+ status: SessionStatus;
385
+ workingDir: string;
386
+ currentTaskId: string | null;
387
+ createdAt: number;
388
+ lastActivityAt: number;
389
+ autoClearEnabled?: boolean;
390
+ autoClearThreshold?: number;
391
+ autoCompactEnabled?: boolean;
392
+ autoCompactThreshold?: number;
393
+ autoCompactPrompt?: string;
394
+ imageWatcherEnabled?: boolean;
395
+ inputTokens?: number;
396
+ outputTokens?: number;
397
+ respawnEnabled?: boolean;
398
+ respawnConfig?: import("./types.js").RespawnConfig & {
399
+ durationMinutes?: number;
400
+ };
401
+ ralphEnabled?: boolean;
402
+ ralphAutoEnableDisabled?: boolean;
403
+ ralphCompletionPhrase?: string;
404
+ parentAgentId?: string;
405
+ childAgentIds?: string[];
406
+ niceEnabled?: boolean;
407
+ niceValue?: number;
408
+ color?: import("./types.js").SessionColor;
409
+ flickerFilterEnabled?: boolean;
410
+ cliVersion?: string;
411
+ cliModel?: string;
412
+ cliAccountType?: string;
413
+ cliLatestVersion?: string;
414
+ openCodeConfig?: OpenCodeConfig;
415
+ };
416
+ /**
417
+ * Lightweight detailed state that excludes heavy buffers (textOutput, terminalBuffer).
418
+ * Use for SSE session:updated broadcasts where buffers aren't needed.
419
+ * Full buffers are fetched on-demand via /api/sessions/:id/terminal.
420
+ */
421
+ toLightDetailedState(): {
422
+ name: string;
423
+ mode: SessionMode;
424
+ claudeSessionId: string | null;
425
+ totalCost: number;
426
+ messageCount: number;
427
+ isWorking: boolean;
428
+ lastPromptTime: number;
429
+ bufferStats: {
430
+ terminalBufferSize: number;
431
+ textOutputSize: number;
432
+ messageCount: number;
433
+ maxTerminalBuffer: number;
434
+ maxTextOutput: number;
435
+ maxMessages: number;
436
+ };
437
+ taskStats: {
438
+ total: number;
439
+ running: number;
440
+ completed: number;
441
+ failed: number;
442
+ };
443
+ taskTree: Omit<BackgroundTask, "output">[];
444
+ tokens: {
445
+ input: number;
446
+ output: number;
447
+ total: number;
448
+ };
449
+ autoClear: {
450
+ enabled: boolean;
451
+ threshold: number;
452
+ };
453
+ nice: {
454
+ enabled: boolean;
455
+ niceValue: number;
456
+ };
457
+ ralphLoop: RalphTrackerState;
458
+ ralphTodos: RalphTodoItem[];
459
+ ralphTodoStats: {
460
+ total: number;
461
+ pending: number;
462
+ inProgress: number;
463
+ completed: number;
464
+ };
465
+ id: string;
466
+ pid: number | null;
467
+ status: SessionStatus;
468
+ workingDir: string;
469
+ currentTaskId: string | null;
470
+ createdAt: number;
471
+ lastActivityAt: number;
472
+ autoClearEnabled?: boolean;
473
+ autoClearThreshold?: number;
474
+ autoCompactEnabled?: boolean;
475
+ autoCompactThreshold?: number;
476
+ autoCompactPrompt?: string;
477
+ imageWatcherEnabled?: boolean;
478
+ inputTokens?: number;
479
+ outputTokens?: number;
480
+ respawnEnabled?: boolean;
481
+ respawnConfig?: import("./types.js").RespawnConfig & {
482
+ durationMinutes?: number;
483
+ };
484
+ ralphEnabled?: boolean;
485
+ ralphAutoEnableDisabled?: boolean;
486
+ ralphCompletionPhrase?: string;
487
+ parentAgentId?: string;
488
+ childAgentIds?: string[];
489
+ niceEnabled?: boolean;
490
+ niceValue?: number;
491
+ color?: import("./types.js").SessionColor;
492
+ flickerFilterEnabled?: boolean;
493
+ cliVersion?: string;
494
+ cliModel?: string;
495
+ cliAccountType?: string;
496
+ cliLatestVersion?: string;
497
+ openCodeConfig?: OpenCodeConfig;
498
+ };
499
+ /**
500
+ * Starts an interactive Claude CLI session with full terminal support.
501
+ *
502
+ * This spawns Claude CLI in interactive mode with the configured permission
503
+ * mode (default: `--dangerously-skip-permissions`). If mux wrapping is enabled,
504
+ * the session runs inside a tmux session for persistence across disconnects.
505
+ *
506
+ * @throws {Error} If a process is already running in this session
507
+ *
508
+ * @example
509
+ * ```typescript
510
+ * const session = new Session({ workingDir: '/project', useMux: true });
511
+ * await session.startInteractive();
512
+ * session.on('terminal', (data) => process.stdout.write(data));
513
+ * session.write('help me with this code\r');
514
+ * ```
515
+ */
516
+ startInteractive(): Promise<void>;
517
+ /**
518
+ * Process expensive parsers (ANSI strip, Ralph, bash tool, token, CLI info, task descriptions).
519
+ * Called on a throttled schedule (every EXPENSIVE_PROCESS_INTERVAL_MS) instead of on every
520
+ * PTY data chunk. Receives accumulated raw data to process in one batch.
521
+ */
522
+ private _processExpensiveParsers;
523
+ /**
524
+ * Starts a plain shell session (bash/zsh) without Claude CLI.
525
+ *
526
+ * Useful for debugging, testing, or when you just need a terminal.
527
+ * Uses the user's default shell from $SHELL or falls back to /bin/bash.
528
+ *
529
+ * @throws {Error} If a process is already running in this session
530
+ *
531
+ * @example
532
+ * ```typescript
533
+ * const session = new Session({ workingDir: '/project', mode: 'shell' });
534
+ * await session.startShell();
535
+ * session.write('ls -la\r');
536
+ * ```
537
+ */
538
+ startShell(): Promise<void>;
539
+ /**
540
+ * Runs a one-shot prompt and returns the result.
541
+ *
542
+ * This spawns Claude CLI with `--output-format stream-json` to get
543
+ * structured JSON output. The promise resolves when Claude completes
544
+ * the response.
545
+ *
546
+ * @param prompt - The prompt text to send to Claude
547
+ * @param options - Optional configuration
548
+ * @param options.model - Model to use ('opus', 'sonnet', or full model name). Defaults to default model.
549
+ * @param options.onProgress - Callback for progress updates (token count, status)
550
+ * @returns Promise resolving to the result text and total cost in USD
551
+ * @throws {Error} If a process is already running in this session
552
+ *
553
+ * @example
554
+ * ```typescript
555
+ * const session = new Session({ workingDir: '/project' });
556
+ * const { result, cost } = await session.runPrompt('Explain this code', { model: 'opus' });
557
+ * console.log(`Response: ${result}`);
558
+ * console.log(`Cost: $${cost.toFixed(4)}`);
559
+ * ```
560
+ */
561
+ runPrompt(prompt: string, options?: {
562
+ model?: string;
563
+ onProgress?: (info: {
564
+ tokens?: number;
565
+ status?: string;
566
+ }) => void;
567
+ }): Promise<{
568
+ result: string;
569
+ cost: number;
570
+ }>;
571
+ private processOutput;
572
+ /**
573
+ * Parse task descriptions from terminal data (may contain multiple lines).
574
+ * Called from interactive mode's onData handler with ANSI-stripped data.
575
+ * @param cleanData - Terminal data with ANSI codes already stripped
576
+ */
577
+ private parseTaskDescriptionsFromTerminalData;
578
+ /**
579
+ * Parse task descriptions from a pre-cleaned line (no ANSI codes).
580
+ * Used by both processOutput() and parseTaskDescriptionsFromTerminalData().
581
+ */
582
+ private parseTaskDescriptionsDirect;
583
+ /**
584
+ * Remove task descriptions older than TASK_DESCRIPTION_MAX_AGE_MS.
585
+ * Size limit is handled automatically by LRUMap eviction on set().
586
+ */
587
+ private cleanupOldTaskDescriptions;
588
+ /**
589
+ * Get recent task descriptions parsed from terminal output.
590
+ * Returns descriptions sorted by timestamp (most recent first).
591
+ */
592
+ getRecentTaskDescriptions(): Array<{
593
+ timestamp: number;
594
+ description: string;
595
+ }>;
596
+ /**
597
+ * Find a task description that was parsed close to a given timestamp.
598
+ * Used to correlate with SubagentWatcher discoveries.
599
+ *
600
+ * @param subagentStartTime - The timestamp when the subagent was discovered
601
+ * @param maxAgeMs - Maximum age difference to consider (default 10 seconds)
602
+ * @returns The matching description or undefined
603
+ */
604
+ findTaskDescriptionNear(subagentStartTime: number, maxAgeMs?: number): string | undefined;
605
+ private parseTokensFromStatusLine;
606
+ private parseClaudeCodeInfo;
607
+ private checkAutoCompact;
608
+ private checkAutoClear;
609
+ /**
610
+ * Sends input directly to the PTY process.
611
+ *
612
+ * For interactive sessions, this is how you send user input to Claude.
613
+ * Remember to include `\r` (carriage return) to simulate pressing Enter.
614
+ *
615
+ * @param data - The input data to send (text, escape sequences, etc.)
616
+ *
617
+ * @example
618
+ * ```typescript
619
+ * session.write('hello world'); // Text only, no Enter
620
+ * session.write('\r'); // Enter key
621
+ * session.write('ls -la\r'); // Command with Enter
622
+ * ```
623
+ */
624
+ write(data: string): void;
625
+ /**
626
+ * Sends input via the terminal multiplexer's direct input mechanism.
627
+ *
628
+ * More reliable than direct PTY write for programmatic input, especially
629
+ * with Claude CLI which uses Ink (React for terminals).
630
+ * Uses tmux `send-keys -l` to inject text + Enter.
631
+ *
632
+ * @param data - Input data with optional `\r` for Enter
633
+ * @returns true if input was sent, false if no mux session or PTY
634
+ *
635
+ * @example
636
+ * ```typescript
637
+ * session.writeViaMux('/clear\r'); // Send /clear command
638
+ * session.writeViaMux('/init\r'); // Send /init command
639
+ * ```
640
+ */
641
+ writeViaMux(data: string): Promise<boolean>;
642
+ /** Current PTY dimensions — used to skip no-op resizes that trigger Ink redraws */
643
+ private _ptyCols;
644
+ private _ptyRows;
645
+ /**
646
+ * Resizes the PTY terminal dimensions.
647
+ * Skips the resize if dimensions haven't changed to avoid triggering
648
+ * unnecessary Ink full-screen redraws (visible flicker on tab switch).
649
+ *
650
+ * @param cols - Number of columns (width in characters)
651
+ * @param rows - Number of rows (height in lines)
652
+ */
653
+ resize(cols: number, rows: number): void;
654
+ start(): Promise<void>;
655
+ sendInput(input: string): Promise<void>;
656
+ /**
657
+ * Remove event listeners from TaskTracker and RalphTracker.
658
+ * Prevents memory leaks by ensuring handlers don't persist after session stop.
659
+ */
660
+ private cleanupTrackerListeners;
661
+ /**
662
+ * Stops the session and cleans up resources.
663
+ *
664
+ * This kills the PTY process and optionally the associated tmux session.
665
+ * All buffers are cleared and the session is marked as stopped.
666
+ *
667
+ * @param killMux - Whether to also kill the mux session (default: true)
668
+ *
669
+ * @example
670
+ * ```typescript
671
+ * // Stop and kill everything
672
+ * await session.stop();
673
+ *
674
+ * // Stop but keep mux session running for later reattachment
675
+ * await session.stop(false);
676
+ * ```
677
+ */
678
+ stop(killMux?: boolean): Promise<void>;
679
+ assignTask(taskId: string): void;
680
+ clearTask(): void;
681
+ getOutput(): string;
682
+ getError(): string;
683
+ getTerminalBuffer(): string;
684
+ clearBuffers(): void;
685
+ }
686
+ //# sourceMappingURL=session.d.ts.map