@agent-relay/wrapper 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/dist/__fixtures__/claude-outputs.d.ts +49 -0
  2. package/dist/__fixtures__/claude-outputs.d.ts.map +1 -0
  3. package/dist/__fixtures__/claude-outputs.js +443 -0
  4. package/dist/__fixtures__/claude-outputs.js.map +1 -0
  5. package/dist/__fixtures__/codex-outputs.d.ts +9 -0
  6. package/dist/__fixtures__/codex-outputs.d.ts.map +1 -0
  7. package/dist/__fixtures__/codex-outputs.js +94 -0
  8. package/dist/__fixtures__/codex-outputs.js.map +1 -0
  9. package/dist/__fixtures__/gemini-outputs.d.ts +19 -0
  10. package/dist/__fixtures__/gemini-outputs.d.ts.map +1 -0
  11. package/dist/__fixtures__/gemini-outputs.js +144 -0
  12. package/dist/__fixtures__/gemini-outputs.js.map +1 -0
  13. package/dist/__fixtures__/index.d.ts +68 -0
  14. package/dist/__fixtures__/index.d.ts.map +1 -0
  15. package/dist/__fixtures__/index.js +44 -0
  16. package/dist/__fixtures__/index.js.map +1 -0
  17. package/dist/auth-detection.d.ts +49 -0
  18. package/dist/auth-detection.d.ts.map +1 -0
  19. package/dist/auth-detection.js +199 -0
  20. package/dist/auth-detection.js.map +1 -0
  21. package/dist/base-wrapper.d.ts +225 -0
  22. package/dist/base-wrapper.d.ts.map +1 -0
  23. package/dist/base-wrapper.js +572 -0
  24. package/dist/base-wrapper.js.map +1 -0
  25. package/dist/client.d.ts +254 -0
  26. package/dist/client.d.ts.map +1 -0
  27. package/dist/client.js +801 -0
  28. package/dist/client.js.map +1 -0
  29. package/dist/id-generator.d.ts +35 -0
  30. package/dist/id-generator.d.ts.map +1 -0
  31. package/dist/id-generator.js +60 -0
  32. package/dist/id-generator.js.map +1 -0
  33. package/dist/idle-detector.d.ts +110 -0
  34. package/dist/idle-detector.d.ts.map +1 -0
  35. package/dist/idle-detector.js +304 -0
  36. package/dist/idle-detector.js.map +1 -0
  37. package/dist/inbox.d.ts +37 -0
  38. package/dist/inbox.d.ts.map +1 -0
  39. package/dist/inbox.js +73 -0
  40. package/dist/inbox.js.map +1 -0
  41. package/dist/index.d.ts +37 -0
  42. package/dist/index.d.ts.map +1 -0
  43. package/dist/index.js +47 -0
  44. package/dist/index.js.map +1 -0
  45. package/dist/parser.d.ts +236 -0
  46. package/dist/parser.d.ts.map +1 -0
  47. package/dist/parser.js +1238 -0
  48. package/dist/parser.js.map +1 -0
  49. package/dist/prompt-composer.d.ts +67 -0
  50. package/dist/prompt-composer.d.ts.map +1 -0
  51. package/dist/prompt-composer.js +168 -0
  52. package/dist/prompt-composer.js.map +1 -0
  53. package/dist/relay-pty-orchestrator.d.ts +407 -0
  54. package/dist/relay-pty-orchestrator.d.ts.map +1 -0
  55. package/dist/relay-pty-orchestrator.js +1885 -0
  56. package/dist/relay-pty-orchestrator.js.map +1 -0
  57. package/dist/shared.d.ts +201 -0
  58. package/dist/shared.d.ts.map +1 -0
  59. package/dist/shared.js +341 -0
  60. package/dist/shared.js.map +1 -0
  61. package/dist/stuck-detector.d.ts +161 -0
  62. package/dist/stuck-detector.d.ts.map +1 -0
  63. package/dist/stuck-detector.js +402 -0
  64. package/dist/stuck-detector.js.map +1 -0
  65. package/dist/tmux-resolver.d.ts +55 -0
  66. package/dist/tmux-resolver.d.ts.map +1 -0
  67. package/dist/tmux-resolver.js +175 -0
  68. package/dist/tmux-resolver.js.map +1 -0
  69. package/dist/tmux-wrapper.d.ts +345 -0
  70. package/dist/tmux-wrapper.d.ts.map +1 -0
  71. package/dist/tmux-wrapper.js +1747 -0
  72. package/dist/tmux-wrapper.js.map +1 -0
  73. package/dist/trajectory-integration.d.ts +292 -0
  74. package/dist/trajectory-integration.d.ts.map +1 -0
  75. package/dist/trajectory-integration.js +979 -0
  76. package/dist/trajectory-integration.js.map +1 -0
  77. package/dist/wrapper-types.d.ts +41 -0
  78. package/dist/wrapper-types.d.ts.map +1 -0
  79. package/dist/wrapper-types.js +7 -0
  80. package/dist/wrapper-types.js.map +1 -0
  81. package/package.json +63 -0
  82. package/src/__fixtures__/claude-outputs.ts +471 -0
  83. package/src/__fixtures__/codex-outputs.ts +99 -0
  84. package/src/__fixtures__/gemini-outputs.ts +151 -0
  85. package/src/__fixtures__/index.ts +47 -0
  86. package/src/auth-detection.ts +244 -0
  87. package/src/base-wrapper.test.ts +540 -0
  88. package/src/base-wrapper.ts +741 -0
  89. package/src/client.test.ts +262 -0
  90. package/src/client.ts +984 -0
  91. package/src/id-generator.test.ts +71 -0
  92. package/src/id-generator.ts +69 -0
  93. package/src/idle-detector.test.ts +390 -0
  94. package/src/idle-detector.ts +370 -0
  95. package/src/inbox.test.ts +233 -0
  96. package/src/inbox.ts +89 -0
  97. package/src/index.ts +170 -0
  98. package/src/parser.regression.test.ts +251 -0
  99. package/src/parser.test.ts +1359 -0
  100. package/src/parser.ts +1477 -0
  101. package/src/prompt-composer.test.ts +219 -0
  102. package/src/prompt-composer.ts +231 -0
  103. package/src/relay-pty-orchestrator.test.ts +1027 -0
  104. package/src/relay-pty-orchestrator.ts +2270 -0
  105. package/src/shared.test.ts +221 -0
  106. package/src/shared.ts +454 -0
  107. package/src/stuck-detector.test.ts +303 -0
  108. package/src/stuck-detector.ts +511 -0
  109. package/src/tmux-resolver.test.ts +104 -0
  110. package/src/tmux-resolver.ts +207 -0
  111. package/src/tmux-wrapper.test.ts +316 -0
  112. package/src/tmux-wrapper.ts +2010 -0
  113. package/src/trajectory-detection.test.ts +151 -0
  114. package/src/trajectory-integration.ts +1261 -0
  115. package/src/wrapper-types.ts +45 -0
@@ -0,0 +1,1747 @@
1
+ /**
2
+ * TmuxWrapper - Attach-based tmux wrapper
3
+ *
4
+ * Architecture:
5
+ * 1. Start agent in detached tmux session
6
+ * 2. Attach user to tmux (they see real terminal)
7
+ * 3. Background: poll capture-pane silently (no stdout writes)
8
+ * 4. Background: parse ->relay commands, send to daemon
9
+ * 5. Background: inject messages via send-keys
10
+ *
11
+ * The key insight: user sees the REAL tmux session, not a proxy.
12
+ * We just do background parsing and injection.
13
+ */
14
+ import { exec, execSync, spawn } from 'node:child_process';
15
+ import crypto from 'node:crypto';
16
+ import { promisify } from 'node:util';
17
+ import { BaseWrapper } from './base-wrapper.js';
18
+ import { OutputParser, parseSummaryWithDetails, parseSessionEndFromOutput } from './parser.js';
19
+ import { hasContinuityCommand, parseContinuityCommand, } from '@agent-relay/continuity';
20
+ import { InboxManager } from './inbox.js';
21
+ import { SqliteStorageAdapter } from '@agent-relay/storage/sqlite-adapter';
22
+ import { getProjectPaths } from '@agent-relay/config/project-namespace';
23
+ import { getTmuxPath } from '@agent-relay/wrapper';
24
+ import { findAgentConfig } from '@agent-relay/config/agent-config';
25
+ import { getTrajectoryIntegration, detectPhaseFromContent, detectToolCalls, detectErrors, getCompactTrailInstructions, getTrailEnvVars, } from '@agent-relay/wrapper';
26
+ import { escapeForShell } from '@agent-relay/config/bridge-utils';
27
+ import { detectProviderAuthRevocation } from './auth-detection.js';
28
+ import { stripAnsi, sleep, getDefaultRelayPrefix, buildInjectionString, injectWithRetry as sharedInjectWithRetry, INJECTION_CONSTANTS, CLI_QUIRKS, AdaptiveThrottle, } from './shared.js';
29
+ import { getTmuxPanePid } from './idle-detector.js';
30
+ import { DEFAULT_TMUX_WRAPPER_CONFIG } from '@agent-relay/config/relay-config';
31
+ const execAsync = promisify(exec);
32
+ // Constants for cursor stability detection in waitForClearInput
33
+ /** Number of consecutive polls with stable cursor before assuming input is clear */
34
+ const STABLE_CURSOR_THRESHOLD = 3;
35
+ /** Maximum cursor X position that indicates a prompt (typical prompts are 1-4 chars) */
36
+ const MAX_PROMPT_CURSOR_POSITION = 4;
37
+ /** Maximum characters to show in debug log truncation */
38
+ const DEBUG_LOG_TRUNCATE_LENGTH = 40;
39
+ /** Maximum characters to show in relay command log truncation */
40
+ const RELAY_LOG_TRUNCATE_LENGTH = 50;
41
+ /**
42
+ * Get the default relay prefix for a given CLI type.
43
+ * All agents now use '->relay:' as the unified prefix.
44
+ * @deprecated Use getDefaultRelayPrefix() from shared.js instead
45
+ */
46
+ export function getDefaultPrefix(_cliType) {
47
+ return getDefaultRelayPrefix();
48
+ }
49
+ export class TmuxWrapper extends BaseWrapper {
50
+ config;
51
+ sessionName;
52
+ parser;
53
+ inbox;
54
+ storage;
55
+ storageReady; // Resolves true if storage initialized, false if failed
56
+ pollTimer;
57
+ attachProcess;
58
+ lastCapturedOutput = '';
59
+ lastOutputTime = 0;
60
+ lastActivityTime = Date.now();
61
+ activityState = 'disconnected';
62
+ recentlySentMessages = new Map();
63
+ // Track processed output to avoid re-parsing
64
+ processedOutputLength = 0;
65
+ lastLoggedLength = 0; // Track length for incremental log streaming
66
+ lastDebugLog = 0;
67
+ lastSummaryHash = ''; // Dedup summary saves
68
+ pendingRelayCommands = [];
69
+ queuedMessageHashes = new Set(); // For offline queue dedup
70
+ MAX_PENDING_RELAY_COMMANDS = 50;
71
+ receivedMessageIdSet = new Set();
72
+ receivedMessageIdOrder = [];
73
+ MAX_RECEIVED_MESSAGES = 2000;
74
+ tmuxPath; // Resolved path to tmux binary (system or bundled)
75
+ trajectory; // Trajectory tracking via trail
76
+ lastDetectedPhase; // Track last auto-detected PDERO phase
77
+ seenToolCalls = new Set(); // Dedup tool call trajectory events
78
+ seenErrors = new Set(); // Dedup error trajectory events
79
+ authRevoked = false; // Track if auth has been revoked
80
+ lastAuthCheck = 0; // Timestamp of last auth check (throttle)
81
+ AUTH_CHECK_INTERVAL = 5000; // Check auth status every 5 seconds max
82
+ // Adaptive throttle for message queue - adjusts delay based on success/failure
83
+ throttle = new AdaptiveThrottle();
84
+ constructor(config) {
85
+ // Merge defaults with config
86
+ const mergedConfig = {
87
+ cols: process.stdout.columns || 120,
88
+ rows: process.stdout.rows || 40,
89
+ ...DEFAULT_TMUX_WRAPPER_CONFIG,
90
+ ...config,
91
+ };
92
+ // Call parent constructor (initializes client, cliType, relayPrefix, continuity)
93
+ super(mergedConfig);
94
+ this.config = mergedConfig;
95
+ // Session name (one agent per name - starting a duplicate kills the existing one)
96
+ this.sessionName = `relay-${config.name}`;
97
+ // Resolve tmux path early so we fail fast if tmux isn't available
98
+ this.tmuxPath = getTmuxPath();
99
+ // Auto-detect agent role from .claude/agents/ or .openagents/ if task not provided
100
+ let detectedTask = this.config.task;
101
+ if (!detectedTask) {
102
+ const agentConfig = findAgentConfig(config.name, this.config.cwd);
103
+ if (agentConfig?.description) {
104
+ detectedTask = agentConfig.description;
105
+ this.logStderr(`Auto-detected role: ${detectedTask.substring(0, 60)}...`, true);
106
+ }
107
+ }
108
+ this.parser = new OutputParser({ prefix: this.relayPrefix });
109
+ // Initialize inbox if using file-based messaging
110
+ if (config.useInbox) {
111
+ this.inbox = new InboxManager({
112
+ agentName: config.name,
113
+ inboxDir: config.inboxDir,
114
+ });
115
+ }
116
+ // Initialize storage for session/summary persistence
117
+ const projectPaths = getProjectPaths();
118
+ this.storage = new SqliteStorageAdapter({ dbPath: projectPaths.dbPath });
119
+ // Initialize asynchronously (don't block constructor) - methods await storageReady
120
+ this.storageReady = this.storage.init().then(() => true).catch(err => {
121
+ this.logStderr(`Failed to initialize storage: ${err.message}`, true);
122
+ this.storage = undefined;
123
+ return false;
124
+ });
125
+ // Initialize trajectory tracking via trail CLI
126
+ this.trajectory = getTrajectoryIntegration(projectPaths.projectId, config.name);
127
+ this.client.onStateChange = (state) => {
128
+ // Only log to stderr, never stdout (user is in tmux)
129
+ if (state === 'READY') {
130
+ this.logStderr('Connected to relay daemon');
131
+ this.flushQueuedRelayCommands();
132
+ }
133
+ else if (state === 'BACKOFF') {
134
+ this.logStderr('Relay unavailable, will retry (backoff)');
135
+ }
136
+ else if (state === 'DISCONNECTED') {
137
+ this.logStderr('Relay disconnected (offline mode)');
138
+ }
139
+ else if (state === 'CONNECTING') {
140
+ this.logStderr('Connecting to relay daemon...');
141
+ }
142
+ };
143
+ }
144
+ // =========================================================================
145
+ // Abstract method implementations
146
+ // =========================================================================
147
+ /**
148
+ * Inject content into the tmux session via paste
149
+ */
150
+ async performInjection(content) {
151
+ await this.pasteLiteral(content);
152
+ }
153
+ /**
154
+ * Get cleaned output for parsing (strip ANSI codes)
155
+ */
156
+ getCleanOutput() {
157
+ return stripAnsi(this.lastCapturedOutput);
158
+ }
159
+ /**
160
+ * Log to stderr (safe - doesn't interfere with tmux display)
161
+ */
162
+ logStderr(msg, force = false) {
163
+ if (!force && !this.config.debug)
164
+ return;
165
+ const now = Date.now();
166
+ if (!force && this.config.debugLogIntervalMs && this.config.debugLogIntervalMs > 0) {
167
+ if (now - this.lastDebugLog < this.config.debugLogIntervalMs) {
168
+ return;
169
+ }
170
+ this.lastDebugLog = now;
171
+ }
172
+ // Prefix with newline to avoid corrupting tmux status line
173
+ process.stderr.write(`\r[relay:${this.config.name}] ${msg}\n`);
174
+ }
175
+ /**
176
+ * Detect PDERO phase from output content and auto-transition if needed.
177
+ * Also detects tool calls and errors, recording them to the trajectory.
178
+ */
179
+ detectAndTransitionPhase(content) {
180
+ if (!this.trajectory)
181
+ return;
182
+ // Detect phase transitions
183
+ const detectedPhase = detectPhaseFromContent(content);
184
+ if (detectedPhase && detectedPhase !== this.lastDetectedPhase) {
185
+ const currentPhase = this.trajectory.getPhase();
186
+ if (detectedPhase !== currentPhase) {
187
+ this.trajectory.transition(detectedPhase, 'Auto-detected from output');
188
+ this.lastDetectedPhase = detectedPhase;
189
+ this.logStderr(`Phase transition: ${currentPhase || 'none'} → ${detectedPhase}`);
190
+ }
191
+ }
192
+ // Detect and record tool calls
193
+ // Note: We deduplicate by tool+status to record each unique tool type once per session
194
+ // (e.g., "Read" started, "Read" completed). This provides a summary of tools used
195
+ // without flooding the trajectory with every individual invocation.
196
+ const tools = detectToolCalls(content);
197
+ for (const tool of tools) {
198
+ const key = `${tool.tool}:${tool.status || 'started'}`;
199
+ if (!this.seenToolCalls.has(key)) {
200
+ this.seenToolCalls.add(key);
201
+ const statusLabel = tool.status === 'completed' ? ' (completed)' : '';
202
+ this.trajectory.event(`Tool: ${tool.tool}${statusLabel}`, 'tool_call');
203
+ }
204
+ }
205
+ // Detect and record errors
206
+ const errors = detectErrors(content);
207
+ for (const error of errors) {
208
+ if (!this.seenErrors.has(error.message)) {
209
+ this.seenErrors.add(error.message);
210
+ const prefix = error.type === 'warning' ? 'Warning' : 'Error';
211
+ this.trajectory.event(`${prefix}: ${error.message}`, 'error');
212
+ }
213
+ }
214
+ }
215
+ /**
216
+ * Build the full command with proper quoting
217
+ * Args containing spaces need to be quoted
218
+ */
219
+ buildCommand() {
220
+ if (!this.config.args || this.config.args.length === 0) {
221
+ return this.config.command;
222
+ }
223
+ // Quote any argument that contains spaces, quotes, or shell special chars
224
+ // Must handle: spaces, quotes, $, <, >, |, &, ;, (, ), `, etc.
225
+ const quotedArgs = this.config.args.map(arg => {
226
+ if (/[\s"'$<>|&;()`,!\\]/.test(arg)) {
227
+ // Use double quotes and escape internal quotes and special chars
228
+ const escaped = arg
229
+ .replace(/\\/g, '\\\\')
230
+ .replace(/"/g, '\\"')
231
+ .replace(/\$/g, '\\$')
232
+ .replace(/`/g, '\\`')
233
+ .replace(/!/g, '\\!');
234
+ return `"${escaped}"`;
235
+ }
236
+ return arg;
237
+ });
238
+ return `${this.config.command} ${quotedArgs.join(' ')}`;
239
+ }
240
+ /**
241
+ * Check if tmux session exists
242
+ */
243
+ async sessionExists() {
244
+ try {
245
+ await execAsync(`"${this.tmuxPath}" has-session -t ${this.sessionName} 2>/dev/null`);
246
+ return true;
247
+ }
248
+ catch {
249
+ return false;
250
+ }
251
+ }
252
+ /**
253
+ * Start the wrapped agent process
254
+ */
255
+ async start() {
256
+ if (this.running)
257
+ return;
258
+ // Initialize inbox if enabled
259
+ if (this.inbox) {
260
+ this.inbox.init();
261
+ }
262
+ // Connect to relay daemon (in background, don't block)
263
+ this.client.connect()
264
+ .then(() => {
265
+ this.logStderr(`Relay connected (state: ${this.client.state})`, true);
266
+ })
267
+ .catch((err) => {
268
+ // Connection failures will retry via client backoff; surface once to stderr.
269
+ this.logStderr(`Relay connect failed: ${err.message}. Will retry if enabled.`, true);
270
+ this.logStderr(`Relay client state: ${this.client.state}`, true);
271
+ });
272
+ // Kill any existing session with this name
273
+ try {
274
+ execSync(`"${this.tmuxPath}" kill-session -t ${this.sessionName} 2>/dev/null`);
275
+ }
276
+ catch {
277
+ // Session doesn't exist, that's fine
278
+ }
279
+ // Build the command - properly quote args that contain spaces
280
+ const fullCommand = this.buildCommand();
281
+ this.logStderr(`Command: ${fullCommand}`);
282
+ this.logStderr(`Prefix: ${this.relayPrefix} (use ${this.relayPrefix}AgentName to send)`);
283
+ // Create tmux session
284
+ try {
285
+ execSync(`"${this.tmuxPath}" new-session -d -s ${this.sessionName} -x ${this.config.cols} -y ${this.config.rows}`, {
286
+ cwd: this.config.cwd ?? process.cwd(),
287
+ stdio: 'pipe',
288
+ });
289
+ // Configure tmux for seamless scrolling
290
+ // Mouse mode passes scroll events to the application when in alternate screen
291
+ const tmuxSettings = [
292
+ 'set -g set-clipboard on', // Enable clipboard
293
+ 'set -g history-limit 50000', // Large scrollback for when needed
294
+ 'setw -g alternate-screen on', // Ensure alternate screen works
295
+ // Pass through mouse scroll to application in alternate screen mode
296
+ 'set -ga terminal-overrides ",xterm*:Tc"',
297
+ 'set -g status-left-length 100', // Provide ample space for agent name in status bar
298
+ 'set -g mode-keys vi', // Predictable key table (avoid copy-mode surprises)
299
+ ];
300
+ // Add mouse mode if enabled (allows scroll passthrough to CLI apps)
301
+ if (this.config.mouseMode) {
302
+ tmuxSettings.unshift('set -g mouse on');
303
+ this.logStderr('Mouse mode enabled (scroll should work in app)');
304
+ }
305
+ for (const setting of tmuxSettings) {
306
+ try {
307
+ execSync(`"${this.tmuxPath}" ${setting}`, { stdio: 'pipe' });
308
+ }
309
+ catch {
310
+ // Some settings may not be available in older tmux versions
311
+ }
312
+ }
313
+ // Mouse scroll should work for both TUIs (alternate screen) and plain shells.
314
+ // If the pane is in alternate screen, pass scroll to the app; otherwise enter copy-mode and scroll tmux history.
315
+ const tmuxMouseBindings = [
316
+ 'unbind -T root WheelUpPane',
317
+ 'unbind -T root WheelDownPane',
318
+ 'unbind -T root MouseDrag1Pane',
319
+ 'bind -T root WheelUpPane if-shell -F "#{alternate_on}" "send-keys -M" "copy-mode -e; send-keys -X scroll-up"',
320
+ 'bind -T root WheelDownPane if-shell -F "#{alternate_on}" "send-keys -M" "send-keys -X scroll-down"',
321
+ 'bind -T root MouseDrag1Pane if-shell -F "#{alternate_on}" "send-keys -M" "copy-mode -e"',
322
+ ];
323
+ for (const setting of tmuxMouseBindings) {
324
+ try {
325
+ execSync(`"${this.tmuxPath}" ${setting}`, { stdio: 'pipe' });
326
+ }
327
+ catch {
328
+ // Ignore on older tmux versions lacking these key tables
329
+ }
330
+ }
331
+ // Set environment variables including trail/trajectory vars
332
+ const projectPaths = getProjectPaths();
333
+ const trailEnvVars = getTrailEnvVars(projectPaths.projectId, this.config.name, projectPaths.dataDir);
334
+ for (const [key, value] of Object.entries({
335
+ ...this.config.env,
336
+ ...trailEnvVars,
337
+ AGENT_RELAY_NAME: this.config.name,
338
+ TERM: 'xterm-256color',
339
+ })) {
340
+ // Use proper shell escaping to prevent command injection via env var values
341
+ const escaped = escapeForShell(value);
342
+ execSync(`"${this.tmuxPath}" setenv -t ${this.sessionName} ${key} "${escaped}"`);
343
+ }
344
+ // Wait for shell to be ready (look for prompt)
345
+ await this.waitForShellReady();
346
+ // Send the command to run
347
+ this.logStderr('Sending command to tmux...');
348
+ await this.sendKeysLiteral(fullCommand);
349
+ await sleep(300); // Give shell time to process the command literal
350
+ this.logStderr('Sending Enter...');
351
+ await this.sendKeys('Enter');
352
+ await sleep(500); // Ensure Enter is processed and command starts before we continue
353
+ this.logStderr('Command sent');
354
+ }
355
+ catch (err) {
356
+ throw new Error(`Failed to create tmux session: ${err.message}`);
357
+ }
358
+ // Wait for session to be ready
359
+ await this.waitForSession();
360
+ this.running = true;
361
+ this.lastActivityTime = Date.now();
362
+ this.activityState = 'active';
363
+ // Initialize trajectory tracking (auto-start if task provided)
364
+ this.initializeTrajectory();
365
+ // Initialize continuity and get/create agentId
366
+ this.initializeAgentId();
367
+ // Start background polling (silent - no stdout writes)
368
+ this.startSilentPolling();
369
+ // Initialize idle detector with the tmux pane PID for process state inspection
370
+ this.initializeIdleDetectorPid();
371
+ this.startStuckDetection();
372
+ // Wait for agent to be ready, then inject instructions
373
+ // This replaces the fixed 3-second delay with actual readiness detection
374
+ this.waitForAgentReady().then(() => {
375
+ this.injectInstructions();
376
+ }).catch(err => {
377
+ this.logStderr(`Failed to wait for agent ready: ${err.message}`, true);
378
+ // Fall back to injecting after a delay
379
+ setTimeout(() => this.injectInstructions(), 3000);
380
+ });
381
+ // Attach user to tmux session
382
+ // This takes over stdin/stdout - user sees the real terminal
383
+ this.attachToSession();
384
+ }
385
+ /**
386
+ * Initialize trajectory tracking
387
+ * Auto-starts a trajectory if task is provided in config
388
+ */
389
+ async initializeTrajectory() {
390
+ if (!this.trajectory)
391
+ return;
392
+ // Auto-start trajectory if task is provided
393
+ if (this.config.task) {
394
+ const success = await this.trajectory.initialize(this.config.task);
395
+ if (success) {
396
+ this.logStderr(`Trajectory started for task: ${this.config.task}`);
397
+ }
398
+ }
399
+ else {
400
+ // Just initialize without starting a trajectory
401
+ await this.trajectory.initialize();
402
+ }
403
+ }
404
+ /**
405
+ * Initialize agent ID for continuity/resume functionality (uses logStderr for tmux)
406
+ */
407
+ async initializeAgentId() {
408
+ if (!this.continuity)
409
+ return;
410
+ try {
411
+ let ledger;
412
+ // If resuming from a previous agent ID, try to find that ledger
413
+ if (this.config.resumeAgentId) {
414
+ ledger = await this.continuity.findLedgerByAgentId(this.config.resumeAgentId);
415
+ if (ledger) {
416
+ this.logStderr(`Resuming agent ID: ${ledger.agentId} (from previous session)`);
417
+ }
418
+ else {
419
+ this.logStderr(`Resume agent ID ${this.config.resumeAgentId} not found, creating new`, true);
420
+ }
421
+ }
422
+ // If not resuming or resume ID not found, get or create ledger
423
+ if (!ledger) {
424
+ ledger = await this.continuity.getOrCreateLedger(this.config.name, this.cliType);
425
+ this.logStderr(`Agent ID: ${ledger.agentId} (use this to resume if agent dies)`);
426
+ }
427
+ this.agentId = ledger.agentId;
428
+ }
429
+ catch (err) {
430
+ this.logStderr(`Failed to initialize agent ID: ${err.message}`, true);
431
+ }
432
+ }
433
+ /**
434
+ * Initialize the idle detector with the tmux pane PID.
435
+ * This enables process state inspection on Linux for more reliable idle detection.
436
+ */
437
+ async initializeIdleDetectorPid() {
438
+ try {
439
+ const pid = await getTmuxPanePid(this.tmuxPath, this.sessionName);
440
+ if (pid) {
441
+ this.setIdleDetectorPid(pid);
442
+ this.logStderr(`Idle detector initialized with PID ${pid}`);
443
+ }
444
+ else {
445
+ this.logStderr('Could not get pane PID for idle detection (will use output analysis)');
446
+ }
447
+ }
448
+ catch (err) {
449
+ this.logStderr(`Failed to initialize idle detector PID: ${err.message}`);
450
+ }
451
+ }
452
+ /**
453
+ * Wait for the agent to be ready for input.
454
+ * Uses idle detection instead of a fixed delay.
455
+ */
456
+ async waitForAgentReady() {
457
+ // Minimum wait to ensure the CLI process has started
458
+ await sleep(500);
459
+ // Wait for agent to become idle (CLI fully initialized)
460
+ const result = await this.waitForIdleState(10000, 200);
461
+ if (result.isIdle) {
462
+ this.logStderr(`Agent ready (confidence: ${(result.confidence * 100).toFixed(0)}%)`);
463
+ }
464
+ else {
465
+ this.logStderr('Agent readiness timeout, proceeding anyway');
466
+ }
467
+ }
468
+ /**
469
+ * Inject usage instructions for the agent including persistence protocol
470
+ */
471
+ async injectInstructions() {
472
+ if (!this.running)
473
+ return;
474
+ if (this.config.skipInstructions)
475
+ return;
476
+ // Use escaped prefix (\->relay:) in examples to prevent parser from treating them as real commands
477
+ const escapedPrefix = '\\' + this.relayPrefix;
478
+ // Build instructions including relay and trail
479
+ const relayInstructions = [
480
+ `[Agent Relay] You are "${this.config.name}" - connected for real-time messaging.`,
481
+ `SEND: ${escapedPrefix}AgentName message`,
482
+ `MULTI-LINE: ${escapedPrefix}AgentName <<<(newline)content(newline)>>> - ALWAYS end with >>> on its own line!`,
483
+ `IMPORTANT: Do NOT include self-identification or preamble in messages. Start with your actual response content.`,
484
+ `PERSIST: Output [[SUMMARY]]{"currentTask":"...","context":"..."}[[/SUMMARY]] after major work.`,
485
+ `END: Output [[SESSION_END]]{"summary":"..."}[[/SESSION_END]] when session complete.`,
486
+ ].join(' | ');
487
+ // Add trail instructions if available
488
+ const trailInstructions = getCompactTrailInstructions();
489
+ try {
490
+ await this.sendKeysLiteral(relayInstructions);
491
+ await sleep(50);
492
+ await this.sendKeys('Enter');
493
+ // Inject trail instructions
494
+ if (this.trajectory?.isTrailInstalledSync()) {
495
+ await sleep(100);
496
+ await this.sendKeysLiteral(trailInstructions);
497
+ await sleep(50);
498
+ await this.sendKeys('Enter');
499
+ }
500
+ // Inject continuity context from previous session
501
+ await this.injectContinuityContext();
502
+ }
503
+ catch {
504
+ // Silent fail - instructions are nice-to-have
505
+ }
506
+ }
507
+ /**
508
+ * Inject continuity context from previous session
509
+ */
510
+ async injectContinuityContext() {
511
+ if (!this.continuity || !this.running)
512
+ return;
513
+ try {
514
+ const context = await this.continuity.getStartupContext(this.config.name);
515
+ if (context && context.formatted) {
516
+ // Inject a brief notification about loaded context
517
+ const notification = `[Continuity] Previous session context loaded. ${context.ledger ? `Task: ${context.ledger.currentTask?.slice(0, 50) || 'unknown'}` : ''}${context.handoff ? ` | Last handoff: ${context.handoff.createdAt.toISOString().split('T')[0]}` : ''}`;
518
+ await sleep(200);
519
+ await this.sendKeysLiteral(notification);
520
+ await sleep(50);
521
+ await this.sendKeys('Enter');
522
+ // Queue the full context for injection when agent is ready
523
+ this.messageQueue.push({
524
+ from: 'system',
525
+ body: context.formatted,
526
+ messageId: `continuity-startup-${Date.now()}`,
527
+ });
528
+ this.checkForInjectionOpportunity();
529
+ if (this.config.debug) {
530
+ this.logStderr(`[CONTINUITY] Loaded context for ${this.config.name}`);
531
+ }
532
+ }
533
+ }
534
+ catch (err) {
535
+ this.logStderr(`[CONTINUITY] Failed to load context: ${err.message}`, true);
536
+ }
537
+ }
538
+ /**
539
+ * Wait for tmux session to be ready
540
+ */
541
+ async waitForSession(maxWaitMs = 5000) {
542
+ const startTime = Date.now();
543
+ while (Date.now() - startTime < maxWaitMs) {
544
+ if (await this.sessionExists()) {
545
+ await new Promise(r => setTimeout(r, 200));
546
+ return;
547
+ }
548
+ await new Promise(r => setTimeout(r, 100));
549
+ }
550
+ throw new Error('Timeout waiting for tmux session');
551
+ }
552
+ /**
553
+ * Wait for shell prompt to appear (shell is ready for input)
554
+ */
555
+ async waitForShellReady(maxWaitMs = 10000) {
556
+ const startTime = Date.now();
557
+ // Common prompt endings: $, %, >, ➜, #
558
+ const promptPatterns = /[$%>#➜]\s*$/;
559
+ this.logStderr('Waiting for shell to initialize...');
560
+ while (Date.now() - startTime < maxWaitMs) {
561
+ try {
562
+ const { stdout } = await execAsync(
563
+ // -J joins wrapped lines so long prompts/messages stay intact
564
+ `"${this.tmuxPath}" capture-pane -t ${this.sessionName} -p -J 2>/dev/null`);
565
+ // Check if the last non-empty line looks like a prompt
566
+ const lines = stdout.split('\n').filter(l => l.trim());
567
+ const lastLine = lines[lines.length - 1] || '';
568
+ if (promptPatterns.test(lastLine)) {
569
+ this.logStderr('Shell ready');
570
+ // Extra delay to ensure shell is fully ready
571
+ await sleep(200);
572
+ return;
573
+ }
574
+ }
575
+ catch {
576
+ // Session might not be ready yet
577
+ }
578
+ await sleep(200);
579
+ }
580
+ // Fallback: proceed anyway after timeout
581
+ this.logStderr('Shell ready timeout, proceeding anyway');
582
+ }
583
+ /**
584
+ * Attach user to tmux session
585
+ * This spawns tmux attach and lets it take over stdin/stdout
586
+ */
587
+ attachToSession() {
588
+ this.attachProcess = spawn(this.tmuxPath, ['attach-session', '-t', this.sessionName], {
589
+ stdio: 'inherit', // User's terminal connects directly to tmux
590
+ });
591
+ this.attachProcess.on('exit', (code) => {
592
+ this.logStderr(`Session ended (code: ${code})`, true);
593
+ this.stop();
594
+ process.exit(code ?? 0);
595
+ });
596
+ this.attachProcess.on('error', (err) => {
597
+ this.logStderr(`Attach error: ${err.message}`, true);
598
+ this.stop();
599
+ process.exit(1);
600
+ });
601
+ // Handle signals
602
+ const cleanup = () => {
603
+ this.stop();
604
+ };
605
+ process.on('SIGINT', cleanup);
606
+ process.on('SIGTERM', cleanup);
607
+ }
608
+ /**
609
+ * Start silent polling for ->relay commands
610
+ * Does NOT write to stdout - just parses and sends to daemon
611
+ */
612
+ startSilentPolling() {
613
+ this.pollTimer = setInterval(() => {
614
+ this.pollForRelayCommands().catch(() => {
615
+ // Ignore poll errors
616
+ });
617
+ }, this.config.pollInterval);
618
+ }
619
+ /**
620
+ * Poll for ->relay commands in output (silent)
621
+ */
622
+ async pollForRelayCommands() {
623
+ if (!this.running)
624
+ return;
625
+ try {
626
+ // Capture scrollback
627
+ const { stdout } = await execAsync(
628
+ // -J joins wrapped lines to avoid truncating ->relay commands mid-line
629
+ `"${this.tmuxPath}" capture-pane -t ${this.sessionName} -p -J -S - 2>/dev/null`);
630
+ // Always parse the FULL capture for ->relay commands
631
+ // This handles terminal UIs that rewrite content in place
632
+ const cleanContent = stripAnsi(stdout);
633
+ // Join continuation lines that TUIs split across multiple lines
634
+ const joinedContent = this.joinContinuationLines(cleanContent);
635
+ const { commands, output: filteredOutput } = this.parser.parse(joinedContent);
636
+ // Debug: log relay commands being parsed
637
+ if (commands.length > 0 && this.config.debug) {
638
+ for (const cmd of commands) {
639
+ const bodyPreview = cmd.body.substring(0, 80).replace(/\n/g, '\\n');
640
+ this.logStderr(`[RELAY_PARSED] to=${cmd.to}, body="${bodyPreview}...", lines=${cmd.body.split('\n').length}`);
641
+ }
642
+ }
643
+ // Track last output time for injection timing
644
+ if (stdout.length !== this.processedOutputLength) {
645
+ this.lastOutputTime = Date.now();
646
+ this.markActivity();
647
+ // Feed new output to idle detector for more robust idle detection
648
+ const newOutput = stdout.substring(this.processedOutputLength);
649
+ this.feedIdleDetectorOutput(newOutput);
650
+ this.processedOutputLength = stdout.length;
651
+ // Stream new output to daemon for dashboard log viewing
652
+ // Use filtered output to exclude thinking blocks and relay commands
653
+ if (this.config.streamLogs && this.client.state === 'READY') {
654
+ // Send incremental filtered output since last log
655
+ const newContent = filteredOutput.substring(this.lastLoggedLength);
656
+ if (newContent.length > 0) {
657
+ this.client.sendLog(newContent);
658
+ this.lastLoggedLength = filteredOutput.length;
659
+ }
660
+ }
661
+ }
662
+ // Send any commands found (deduplication handles repeats)
663
+ for (const cmd of commands) {
664
+ this.sendRelayCommand(cmd);
665
+ }
666
+ // Check for [[SUMMARY]] blocks and save to storage
667
+ this.parseSummaryAndSave(cleanContent);
668
+ // Detect PDERO phase transitions from output content
669
+ this.detectAndTransitionPhase(cleanContent);
670
+ // Parse and handle continuity commands (->continuity:save, ->continuity:load, etc.)
671
+ await this.parseContinuityCommands(joinedContent);
672
+ // Check for [[SESSION_END]] blocks to explicitly close session
673
+ this.parseSessionEndAndClose(cleanContent);
674
+ // Check for ->relay:spawn and ->relay:release commands (any agent can spawn)
675
+ // Use joinedContent to handle multi-line output from TUIs like Claude Code
676
+ this.parseSpawnReleaseCommands(joinedContent);
677
+ // Check for auth revocation (limited sessions scenario)
678
+ this.checkAuthRevocation(cleanContent);
679
+ this.updateActivityState();
680
+ // Also check for injection opportunity
681
+ this.checkForInjectionOpportunity();
682
+ }
683
+ catch (err) {
684
+ if (err.message?.includes('no such session')) {
685
+ this.stop();
686
+ }
687
+ }
688
+ }
689
+ /**
690
+ * Record recent activity and transition back to active if needed.
691
+ */
692
+ markActivity() {
693
+ this.lastActivityTime = Date.now();
694
+ if (this.activityState === 'idle') {
695
+ this.activityState = 'active';
696
+ this.logStderr('Session active');
697
+ }
698
+ }
699
+ /**
700
+ * Update activity state based on idle threshold and trigger injections when idle.
701
+ */
702
+ updateActivityState() {
703
+ if (this.activityState === 'disconnected')
704
+ return;
705
+ const now = Date.now();
706
+ const idleThreshold = this.config.activityIdleThresholdMs ?? 30000;
707
+ const timeSinceActivity = now - this.lastActivityTime;
708
+ if (timeSinceActivity > idleThreshold && this.activityState === 'active') {
709
+ this.activityState = 'idle';
710
+ this.logStderr('Session went idle');
711
+ this.checkForInjectionOpportunity();
712
+ }
713
+ else if (timeSinceActivity <= idleThreshold && this.activityState === 'idle') {
714
+ this.activityState = 'active';
715
+ this.logStderr('Session active');
716
+ }
717
+ }
718
+ /**
719
+ * Check if the CLI output indicates auth has been revoked.
720
+ * This can happen when the user authenticates elsewhere (limited sessions).
721
+ */
722
+ checkAuthRevocation(output) {
723
+ // Don't check if already revoked or if we checked recently
724
+ if (this.authRevoked)
725
+ return;
726
+ const now = Date.now();
727
+ if (now - this.lastAuthCheck < this.AUTH_CHECK_INTERVAL)
728
+ return;
729
+ this.lastAuthCheck = now;
730
+ // Get the CLI type/provider from config
731
+ const provider = this.config.program || this.cliType || 'claude';
732
+ // Check for auth revocation patterns in recent output
733
+ const result = detectProviderAuthRevocation(output, provider);
734
+ if (result.detected && result.confidence !== 'low') {
735
+ this.authRevoked = true;
736
+ this.logStderr(`[AUTH] Auth revocation detected (${result.confidence} confidence): ${result.message}`);
737
+ // Send auth status message to daemon
738
+ if (this.client.state === 'READY') {
739
+ const authPayload = JSON.stringify({
740
+ type: 'auth_revoked',
741
+ agent: this.config.name,
742
+ provider,
743
+ message: result.message,
744
+ confidence: result.confidence,
745
+ timestamp: new Date().toISOString(),
746
+ });
747
+ this.client.sendMessage('#system', authPayload, 'message');
748
+ }
749
+ // Emit event for listeners
750
+ this.emit('auth_revoked', {
751
+ agent: this.config.name,
752
+ provider,
753
+ message: result.message,
754
+ confidence: result.confidence,
755
+ });
756
+ }
757
+ }
758
+ /**
759
+ * Reset auth revocation state (called after successful re-authentication)
760
+ */
761
+ resetAuthState() {
762
+ this.authRevoked = false;
763
+ this.lastAuthCheck = 0;
764
+ this.logStderr('[AUTH] Auth state reset');
765
+ }
766
+ /**
767
+ * Check if auth has been revoked
768
+ */
769
+ isAuthRevoked() {
770
+ return this.authRevoked;
771
+ }
772
+ /**
773
+ * Send relay command to daemon (overrides BaseWrapper for offline queue support)
774
+ */
775
+ sendRelayCommand(cmd) {
776
+ const msgHash = `${cmd.to}:${cmd.body}`;
777
+ // Permanent dedup - never send the same message twice
778
+ if (this.sentMessageHashes.has(msgHash)) {
779
+ this.logStderr(`[DEDUP] Skipped duplicate message to ${cmd.to} (hash already sent)`);
780
+ return;
781
+ }
782
+ // If client not ready, queue for later and return
783
+ if (this.client.state !== 'READY') {
784
+ if (this.queuedMessageHashes.has(msgHash)) {
785
+ return; // Already queued
786
+ }
787
+ if (this.pendingRelayCommands.length >= this.MAX_PENDING_RELAY_COMMANDS) {
788
+ this.logStderr('Relay offline queue full, dropping oldest');
789
+ const dropped = this.pendingRelayCommands.shift();
790
+ if (dropped) {
791
+ this.queuedMessageHashes.delete(`${dropped.to}:${dropped.body}`);
792
+ }
793
+ }
794
+ this.pendingRelayCommands.push(cmd);
795
+ this.queuedMessageHashes.add(msgHash);
796
+ this.logStderr(`Relay offline; queued message to ${cmd.to}`);
797
+ return;
798
+ }
799
+ // Convert ParsedMessageMetadata to SendMeta if present
800
+ let sendMeta;
801
+ if (cmd.meta) {
802
+ sendMeta = {
803
+ importance: cmd.meta.importance,
804
+ replyTo: cmd.meta.replyTo,
805
+ requires_ack: cmd.meta.ackRequired,
806
+ };
807
+ }
808
+ if (cmd.sync?.blocking) {
809
+ this.client.sendAndWait(cmd.to, cmd.body, {
810
+ timeoutMs: cmd.sync.timeoutMs,
811
+ kind: cmd.kind,
812
+ data: cmd.data,
813
+ thread: cmd.thread,
814
+ }).then(() => {
815
+ this.sentMessageHashes.add(msgHash);
816
+ this.queuedMessageHashes.delete(msgHash);
817
+ }).catch((err) => {
818
+ this.logStderr(`sendAndWait failed for ${cmd.to}: ${err.message}`, true);
819
+ });
820
+ return;
821
+ }
822
+ const success = this.client.sendMessage(cmd.to, cmd.body, cmd.kind, cmd.data, cmd.thread, sendMeta);
823
+ if (success) {
824
+ this.sentMessageHashes.add(msgHash);
825
+ this.queuedMessageHashes.delete(msgHash);
826
+ const truncatedBody = cmd.body.substring(0, Math.min(RELAY_LOG_TRUNCATE_LENGTH, cmd.body.length));
827
+ this.logStderr(`→ ${cmd.to}: ${truncatedBody}...`);
828
+ // Record in trajectory via trail
829
+ this.trajectory?.message('sent', this.config.name, cmd.to, cmd.body);
830
+ }
831
+ else if (this.client.state !== 'READY') {
832
+ // Only log failure once per state change
833
+ this.logStderr(`Send failed (client ${this.client.state})`);
834
+ }
835
+ }
836
+ /**
837
+ * Flush any queued relay commands when the client reconnects.
838
+ */
839
+ flushQueuedRelayCommands() {
840
+ if (this.pendingRelayCommands.length === 0)
841
+ return;
842
+ const queued = [...this.pendingRelayCommands];
843
+ this.pendingRelayCommands = [];
844
+ this.queuedMessageHashes.clear();
845
+ for (const cmd of queued) {
846
+ this.sendRelayCommand(cmd);
847
+ }
848
+ }
849
+ /**
850
+ * Parse [[SUMMARY]] blocks from output and save to storage.
851
+ * Agents can output summaries to maintain running context:
852
+ *
853
+ * [[SUMMARY]]
854
+ * {"currentTask": "Implementing auth", "context": "Completed login flow"}
855
+ * [[/SUMMARY]]
856
+ */
857
+ parseSummaryAndSave(content) {
858
+ const result = parseSummaryWithDetails(content);
859
+ // No SUMMARY block found
860
+ if (!result.found)
861
+ return;
862
+ // Dedup based on raw content - prevents repeated error logging for same invalid JSON
863
+ if (result.rawContent === this.lastSummaryRawContent)
864
+ return;
865
+ this.lastSummaryRawContent = result.rawContent || '';
866
+ // Invalid JSON - log error once (deduped above)
867
+ if (!result.valid) {
868
+ this.logStderr('[parser] Invalid JSON in SUMMARY block');
869
+ return;
870
+ }
871
+ const summary = result.summary;
872
+ // Dedup valid summaries - don't save same summary twice
873
+ const summaryHash = JSON.stringify(summary);
874
+ if (summaryHash === this.lastSummaryHash)
875
+ return;
876
+ this.lastSummaryHash = summaryHash;
877
+ // Save to continuity ledger for session recovery
878
+ // This ensures the ledger has actual data instead of placeholders
879
+ if (this.continuity) {
880
+ this.saveSummaryToLedger(summary).catch(err => {
881
+ this.logStderr(`Failed to save summary to ledger: ${err.message}`, true);
882
+ });
883
+ }
884
+ // Wait for storage to be ready before saving to project storage
885
+ this.storageReady.then(ready => {
886
+ if (!ready || !this.storage) {
887
+ this.logStderr('Cannot save summary: storage not initialized');
888
+ return;
889
+ }
890
+ const projectPaths = getProjectPaths();
891
+ this.storage.saveAgentSummary({
892
+ agentName: this.config.name,
893
+ projectId: projectPaths.projectId,
894
+ currentTask: summary.currentTask,
895
+ completedTasks: summary.completedTasks,
896
+ decisions: summary.decisions,
897
+ context: summary.context,
898
+ files: summary.files,
899
+ }).then(() => {
900
+ this.logStderr(`Saved agent summary: ${summary.currentTask || 'updated context'}`);
901
+ }).catch(err => {
902
+ this.logStderr(`Failed to save summary: ${err.message}`, true);
903
+ });
904
+ });
905
+ }
906
+ /**
907
+ * Save a parsed summary to the continuity ledger (uses logStderr for tmux).
908
+ * Maps summary fields to ledger fields for session recovery.
909
+ */
910
+ async saveSummaryToLedger(summary) {
911
+ if (!this.continuity)
912
+ return;
913
+ const updates = {};
914
+ // Map summary fields to ledger fields
915
+ if (summary.currentTask) {
916
+ updates.currentTask = summary.currentTask;
917
+ }
918
+ if (summary.completedTasks && summary.completedTasks.length > 0) {
919
+ updates.completed = summary.completedTasks;
920
+ }
921
+ if (summary.context) {
922
+ // Store context in inProgress as "next steps" hint
923
+ updates.inProgress = [summary.context];
924
+ }
925
+ if (summary.files && summary.files.length > 0) {
926
+ updates.fileContext = summary.files.map((f) => ({ path: f }));
927
+ }
928
+ // Only save if we have meaningful updates
929
+ if (Object.keys(updates).length > 0) {
930
+ await this.continuity.saveLedger(this.config.name, updates);
931
+ this.logStderr('Saved summary to continuity ledger');
932
+ }
933
+ }
934
+ /**
935
+ * Parse ->continuity: commands from output and handle them.
936
+ * Supported commands:
937
+ * ->continuity:save <<<...>>> - Save session state to ledger
938
+ * ->continuity:load - Request context injection
939
+ * ->continuity:search "query" - Search past handoffs
940
+ * ->continuity:uncertain "..." - Mark item as uncertain
941
+ * ->continuity:handoff <<<...>>> - Create explicit handoff
942
+ */
943
+ async parseContinuityCommands(content) {
944
+ if (!this.continuity)
945
+ return;
946
+ if (!hasContinuityCommand(content))
947
+ return;
948
+ const command = parseContinuityCommand(content);
949
+ if (!command)
950
+ return;
951
+ // Create a hash for deduplication
952
+ // For commands with content (save, handoff, uncertain), use content hash
953
+ // For commands without content (load, search), allow each unique call
954
+ const hasContent = command.content || command.query || command.item;
955
+ const cmdHash = hasContent
956
+ ? `${command.type}:${command.content || command.query || command.item}`
957
+ : `${command.type}:${Date.now()}`; // Allow load/search to run each time
958
+ if (hasContent && this.processedContinuityCommands.has(cmdHash))
959
+ return;
960
+ this.processedContinuityCommands.add(cmdHash);
961
+ // Limit dedup set size
962
+ if (this.processedContinuityCommands.size > 100) {
963
+ const oldest = this.processedContinuityCommands.values().next().value;
964
+ if (oldest)
965
+ this.processedContinuityCommands.delete(oldest);
966
+ }
967
+ try {
968
+ if (this.config.debug) {
969
+ this.logStderr(`[CONTINUITY] Processing ${command.type} command`);
970
+ }
971
+ const response = await this.continuity.handleCommand(this.config.name, command);
972
+ // If there's a response (e.g., from load or search), inject it
973
+ if (response) {
974
+ this.messageQueue.push({
975
+ from: 'system',
976
+ body: response,
977
+ messageId: `continuity-${Date.now()}`,
978
+ });
979
+ this.checkForInjectionOpportunity();
980
+ }
981
+ }
982
+ catch (err) {
983
+ this.logStderr(`[CONTINUITY] Error: ${err.message}`, true);
984
+ }
985
+ }
986
+ /**
987
+ * Parse [[SESSION_END]] blocks from output and close session explicitly.
988
+ * Agents output this to mark their work session as complete:
989
+ *
990
+ * [[SESSION_END]]
991
+ * {"summary": "Completed auth module", "completedTasks": ["login", "logout"]}
992
+ * [[/SESSION_END]]
993
+ *
994
+ * Also stores the data for use in autoSave to populate handoff (fixes empty handoff issue).
995
+ */
996
+ parseSessionEndAndClose(content) {
997
+ if (this.sessionEndProcessed)
998
+ return; // Only process once per session
999
+ const sessionEnd = parseSessionEndFromOutput(content);
1000
+ if (!sessionEnd)
1001
+ return;
1002
+ // Store SESSION_END data for use in autoSave (fixes empty handoff issue)
1003
+ this.sessionEndData = sessionEnd;
1004
+ // Get session ID from client connection - if not available yet, don't set flag
1005
+ // so we can retry when sessionId becomes available
1006
+ const sessionId = this.client.currentSessionId;
1007
+ if (!sessionId) {
1008
+ this.logStderr('Cannot close session: no session ID yet, will retry');
1009
+ return;
1010
+ }
1011
+ this.sessionEndProcessed = true;
1012
+ // Wait for storage to be ready before attempting to close session
1013
+ this.storageReady.then(ready => {
1014
+ if (!ready || !this.storage) {
1015
+ this.logStderr('Cannot close session: storage not initialized');
1016
+ return;
1017
+ }
1018
+ this.storage.endSession(sessionId, {
1019
+ summary: sessionEnd.summary,
1020
+ closedBy: 'agent',
1021
+ }).then(() => {
1022
+ this.logStderr(`Session closed by agent: ${sessionEnd.summary || 'complete'}`);
1023
+ }).catch(err => {
1024
+ this.logStderr(`Failed to close session: ${err.message}`, true);
1025
+ });
1026
+ });
1027
+ }
1028
+ /**
1029
+ * Execute spawn via API (if dashboardPort set) or callback.
1030
+ * After spawning, waits for the agent to come online and sends the task via relay.
1031
+ */
1032
+ async executeSpawn(name, cli, task) {
1033
+ let spawned = false;
1034
+ if (this.config.dashboardPort) {
1035
+ // Use dashboard API for spawning (works from any context, no terminal required)
1036
+ try {
1037
+ const response = await fetch(`http://localhost:${this.config.dashboardPort}/api/spawn`, {
1038
+ method: 'POST',
1039
+ headers: { 'Content-Type': 'application/json' },
1040
+ body: JSON.stringify({ name, cli }), // No task - we send it after agent is online
1041
+ });
1042
+ const result = await response.json();
1043
+ if (result.success) {
1044
+ this.logStderr(`Spawned ${name} via API`);
1045
+ spawned = true;
1046
+ }
1047
+ else {
1048
+ this.logStderr(`Spawn failed: ${result.error}`, true);
1049
+ }
1050
+ }
1051
+ catch (err) {
1052
+ this.logStderr(`Spawn API call failed: ${err.message}`, true);
1053
+ }
1054
+ }
1055
+ else if (this.config.onSpawn) {
1056
+ // Fall back to callback
1057
+ try {
1058
+ await this.config.onSpawn(name, cli, task);
1059
+ spawned = true;
1060
+ }
1061
+ catch (err) {
1062
+ this.logStderr(`Spawn failed: ${err.message}`, true);
1063
+ }
1064
+ }
1065
+ // If spawn succeeded and we have a task, wait for agent to come online and send it
1066
+ if (spawned && task && task.trim() && this.config.dashboardPort) {
1067
+ await this.waitAndSendTask(name, task);
1068
+ }
1069
+ }
1070
+ /**
1071
+ * Wait for a spawned agent to come online, then send the task via relay.
1072
+ * Uses the wrapper's own relay client so the message comes "from" this agent,
1073
+ * not from the dashboard's relay client.
1074
+ */
1075
+ async waitAndSendTask(agentName, task) {
1076
+ const maxWaitMs = 30000;
1077
+ const pollIntervalMs = 500;
1078
+ const startTime = Date.now();
1079
+ this.logStderr(`Waiting for ${agentName} to come online...`);
1080
+ // Poll for agent to be online using dedicated status endpoint
1081
+ while (Date.now() - startTime < maxWaitMs) {
1082
+ try {
1083
+ const response = await fetch(`http://localhost:${this.config.dashboardPort}/api/agents/${encodeURIComponent(agentName)}/online`);
1084
+ const data = await response.json();
1085
+ if (data.online) {
1086
+ this.logStderr(`${agentName} is online, sending task...`);
1087
+ // Send task directly via our relay client (not dashboard API)
1088
+ // This ensures the message comes "from" this agent, not from _DashboardUI
1089
+ if (this.client.state === 'READY') {
1090
+ const sent = this.client.sendMessage(agentName, task, 'message');
1091
+ if (sent) {
1092
+ this.logStderr(`Task sent to ${agentName}`);
1093
+ }
1094
+ else {
1095
+ this.logStderr(`Failed to send task to ${agentName}: sendMessage returned false`, true);
1096
+ }
1097
+ }
1098
+ else {
1099
+ this.logStderr(`Failed to send task to ${agentName}: relay client not ready (state: ${this.client.state})`, true);
1100
+ }
1101
+ return;
1102
+ }
1103
+ }
1104
+ catch (_err) {
1105
+ // Ignore poll errors, keep trying
1106
+ }
1107
+ await sleep(pollIntervalMs);
1108
+ }
1109
+ this.logStderr(`Timeout waiting for ${agentName} to come online`, true);
1110
+ }
1111
+ /**
1112
+ * Execute release via API (if dashboardPort set) or callback
1113
+ */
1114
+ async executeRelease(name) {
1115
+ if (this.config.dashboardPort) {
1116
+ // Use dashboard API for release (works from any context, no terminal required)
1117
+ try {
1118
+ const response = await fetch(`http://localhost:${this.config.dashboardPort}/api/spawned/${encodeURIComponent(name)}`, {
1119
+ method: 'DELETE',
1120
+ });
1121
+ const result = await response.json();
1122
+ if (result.success) {
1123
+ this.logStderr(`Released ${name} via API`);
1124
+ }
1125
+ else {
1126
+ this.logStderr(`Release failed: ${result.error}`, true);
1127
+ }
1128
+ }
1129
+ catch (err) {
1130
+ this.logStderr(`Release API call failed: ${err.message}`, true);
1131
+ }
1132
+ }
1133
+ else if (this.config.onRelease) {
1134
+ // Fall back to callback
1135
+ try {
1136
+ await this.config.onRelease(name);
1137
+ }
1138
+ catch (err) {
1139
+ this.logStderr(`Release failed: ${err.message}`, true);
1140
+ }
1141
+ }
1142
+ }
1143
+ /**
1144
+ * Parse ->relay:spawn and ->relay:release commands from output.
1145
+ * Supports two formats:
1146
+ * Single-line: ->relay:spawn WorkerName cli "task description"
1147
+ * Multi-line (fenced): ->relay:spawn WorkerName cli <<<
1148
+ * task description here
1149
+ * can span multiple lines>>>
1150
+ * ->relay:release WorkerName
1151
+ */
1152
+ parseSpawnReleaseCommands(content) {
1153
+ // Only process if we have API or callbacks configured
1154
+ const canSpawn = this.config.dashboardPort || this.config.onSpawn;
1155
+ const canRelease = this.config.dashboardPort || this.config.onRelease;
1156
+ // Debug: Log spawn capability status
1157
+ if (content.includes('->relay:spawn')) {
1158
+ this.logStderr(`[spawn-debug] canSpawn=${!!canSpawn} dashboardPort=${this.config.dashboardPort} hasOnSpawn=${!!this.config.onSpawn}`);
1159
+ }
1160
+ if (!canSpawn && !canRelease)
1161
+ return;
1162
+ const lines = content.split('\n');
1163
+ // Pattern to strip common line prefixes (bullets, prompts, etc.)
1164
+ // Must include ● (U+25CF BLACK CIRCLE) used by Claude's TUI
1165
+ const linePrefixPattern = /^(?:[>$%#→➜›»●•◦‣⁃\-*⏺◆◇○□■│┃┆┇┊┋╎╏✦]\s*)+/;
1166
+ for (const line of lines) {
1167
+ let trimmed = line.trim();
1168
+ // Strip common line prefixes (bullets, prompts) before checking for commands
1169
+ trimmed = trimmed.replace(linePrefixPattern, '');
1170
+ // Fix for over-stripping: the linePrefixPattern includes - and > characters,
1171
+ // which can accidentally strip the -> from ->relay:spawn, leaving just relay:spawn.
1172
+ // If we detect this happened, restore the -> prefix.
1173
+ if (/^(relay|thinking|continuity):/.test(trimmed)) {
1174
+ trimmed = '->' + trimmed;
1175
+ }
1176
+ // If we're in fenced spawn mode, accumulate lines until we see >>>
1177
+ if (this.pendingFencedSpawn) {
1178
+ // Check for fence close (>>> at end of line or on its own line)
1179
+ const closeIdx = trimmed.indexOf('>>>');
1180
+ if (closeIdx !== -1) {
1181
+ // Add content before >>> to task
1182
+ const contentBeforeClose = trimmed.substring(0, closeIdx);
1183
+ if (contentBeforeClose) {
1184
+ this.pendingFencedSpawn.taskLines.push(contentBeforeClose);
1185
+ }
1186
+ // Execute the spawn with accumulated task
1187
+ const { name, cli, taskLines } = this.pendingFencedSpawn;
1188
+ const taskStr = taskLines.join('\n').trim();
1189
+ const spawnKey = `${name}:${cli}`;
1190
+ if (!this.processedSpawnCommands.has(spawnKey)) {
1191
+ this.processedSpawnCommands.add(spawnKey);
1192
+ if (taskStr) {
1193
+ this.logStderr(`Spawn command (fenced): ${name} (${cli}) - "${taskStr.substring(0, 50)}..."`);
1194
+ }
1195
+ else {
1196
+ this.logStderr(`Spawn command (fenced): ${name} (${cli}) - no task`);
1197
+ }
1198
+ this.executeSpawn(name, cli, taskStr);
1199
+ }
1200
+ this.pendingFencedSpawn = null;
1201
+ }
1202
+ else {
1203
+ // Accumulate line as part of task
1204
+ this.pendingFencedSpawn.taskLines.push(line);
1205
+ }
1206
+ continue;
1207
+ }
1208
+ // Check for fenced spawn start: ->relay:spawn Name [cli] <<< (CLI optional, defaults to 'claude')
1209
+ // Prefixes are stripped above, so we just look for the command at start of line
1210
+ const fencedSpawnMatch = trimmed.match(/^->relay:spawn\s+(\S+)(?:\s+(\S+))?\s+<<<(.*)$/);
1211
+ if (fencedSpawnMatch && canSpawn) {
1212
+ const [, name, cliOrUndefined, inlineContent] = fencedSpawnMatch;
1213
+ const cli = cliOrUndefined || 'claude';
1214
+ // Validate name
1215
+ if (name.length < 2) {
1216
+ this.logStderr(`Fenced spawn has invalid name, skipping: name=${name}`);
1217
+ continue;
1218
+ }
1219
+ // Check if fence closes on same line (e.g., ->relay:spawn Worker cli <<<task>>>)
1220
+ const inlineCloseIdx = inlineContent.indexOf('>>>');
1221
+ if (inlineCloseIdx !== -1) {
1222
+ // Single line fenced: extract task between <<< and >>>
1223
+ const taskStr = inlineContent.substring(0, inlineCloseIdx).trim();
1224
+ const spawnKey = `${name}:${cli}`;
1225
+ if (!this.processedSpawnCommands.has(spawnKey)) {
1226
+ this.processedSpawnCommands.add(spawnKey);
1227
+ if (taskStr) {
1228
+ this.logStderr(`Spawn command: ${name} (${cli}) - "${taskStr.substring(0, 50)}..."`);
1229
+ }
1230
+ else {
1231
+ this.logStderr(`Spawn command: ${name} (${cli}) - no task`);
1232
+ }
1233
+ this.executeSpawn(name, cli, taskStr);
1234
+ }
1235
+ }
1236
+ else {
1237
+ // Start multi-line fenced mode
1238
+ this.pendingFencedSpawn = {
1239
+ name,
1240
+ cli,
1241
+ taskLines: inlineContent.trim() ? [inlineContent.trim()] : [],
1242
+ };
1243
+ this.logStderr(`Starting fenced spawn capture: ${name} (${cli})`);
1244
+ }
1245
+ continue;
1246
+ }
1247
+ // Match single-line spawn: ->relay:spawn WorkerName [cli] ["task"]
1248
+ // CLI is optional - defaults to 'claude'. Task is also optional.
1249
+ // Prefixes are stripped above, so we just look for the command at start of line
1250
+ const spawnMatch = trimmed.match(/^->relay:spawn\s+(\S+)(?:\s+(\S+))?(?:\s+["'](.+?)["'])?\s*$/);
1251
+ if (spawnMatch && canSpawn) {
1252
+ const [, name, cliOrUndefined, task] = spawnMatch;
1253
+ const cli = cliOrUndefined || 'claude';
1254
+ // Validate the parsed values
1255
+ if (cli === '<<<' || cli === '>>>' || name === '<<<' || name === '>>>') {
1256
+ this.logStderr(`Invalid spawn command (fence markers), skipping: name=${name}, cli=${cli}`);
1257
+ continue;
1258
+ }
1259
+ if (name.length < 2) {
1260
+ this.logStderr(`Spawn command has suspiciously short name, skipping: name=${name}`);
1261
+ continue;
1262
+ }
1263
+ const taskStr = task || '';
1264
+ const spawnKey = `${name}:${cli}`;
1265
+ if (!this.processedSpawnCommands.has(spawnKey)) {
1266
+ this.processedSpawnCommands.add(spawnKey);
1267
+ if (taskStr) {
1268
+ this.logStderr(`Spawn command: ${name} (${cli}) - "${taskStr.substring(0, 50)}..."`);
1269
+ }
1270
+ else {
1271
+ this.logStderr(`Spawn command: ${name} (${cli}) - no task`);
1272
+ }
1273
+ this.executeSpawn(name, cli, taskStr);
1274
+ }
1275
+ continue;
1276
+ }
1277
+ // Match ->relay:release WorkerName
1278
+ // Prefixes are stripped above, so we just look for the command at start of line
1279
+ const releaseMatch = trimmed.match(/^->relay:release\s+(\S+)\s*$/);
1280
+ if (releaseMatch && canRelease) {
1281
+ const [, name] = releaseMatch;
1282
+ if (!this.processedReleaseCommands.has(name)) {
1283
+ this.processedReleaseCommands.add(name);
1284
+ this.logStderr(`Release command: ${name}`);
1285
+ this.executeRelease(name);
1286
+ }
1287
+ }
1288
+ }
1289
+ }
1290
+ /**
1291
+ * Handle incoming message from relay
1292
+ * @param originalTo - The original 'to' field from sender. '*' indicates this was a broadcast message.
1293
+ * Agents should reply to originalTo to maintain channel routing (e.g., respond to #general, not DM).
1294
+ */
1295
+ handleIncomingMessage(from, payload, messageId, meta, originalTo) {
1296
+ if (this.hasSeenIncoming(messageId)) {
1297
+ this.logStderr(`← ${from}: duplicate delivery (${messageId.substring(0, 8)})`);
1298
+ return;
1299
+ }
1300
+ const truncatedBody = payload.body.substring(0, Math.min(DEBUG_LOG_TRUNCATE_LENGTH, payload.body.length));
1301
+ const channelInfo = originalTo === '*' ? ' [broadcast]' : '';
1302
+ this.logStderr(`← ${from}${channelInfo}: ${truncatedBody}...`);
1303
+ // Record in trajectory via trail
1304
+ this.trajectory?.message('received', from, this.config.name, payload.body);
1305
+ // Queue for injection - include originalTo so we can inform the agent how to route responses
1306
+ this.messageQueue.push({
1307
+ from,
1308
+ body: payload.body,
1309
+ messageId,
1310
+ thread: payload.thread,
1311
+ importance: meta?.importance,
1312
+ data: payload.data,
1313
+ sync: meta?.sync,
1314
+ originalTo,
1315
+ });
1316
+ // Write to inbox if enabled
1317
+ if (this.inbox) {
1318
+ this.inbox.addMessage(from, payload.body);
1319
+ }
1320
+ // Try to inject
1321
+ this.checkForInjectionOpportunity();
1322
+ }
1323
+ /**
1324
+ * Handle incoming channel message from relay.
1325
+ * Channel messages include a channel indicator so the agent knows to reply to the channel.
1326
+ */
1327
+ handleIncomingChannelMessage(from, channel, body, envelope) {
1328
+ const messageId = envelope.id;
1329
+ if (this.hasSeenIncoming(messageId)) {
1330
+ this.logStderr(`← ${from} [${channel}]: duplicate delivery (${messageId.substring(0, 8)})`);
1331
+ return;
1332
+ }
1333
+ const truncatedBody = body.substring(0, Math.min(DEBUG_LOG_TRUNCATE_LENGTH, body.length));
1334
+ this.logStderr(`← ${from} [${channel}]: ${truncatedBody}...`);
1335
+ // Record in trajectory via trail
1336
+ this.trajectory?.message('received', from, this.config.name, body);
1337
+ // Queue for injection - include channel as originalTo so we can inform the agent how to route responses
1338
+ this.messageQueue.push({
1339
+ from,
1340
+ body,
1341
+ messageId,
1342
+ thread: envelope.payload.thread,
1343
+ data: {
1344
+ _isChannelMessage: true,
1345
+ _channel: channel,
1346
+ _mentions: envelope.payload.mentions,
1347
+ },
1348
+ originalTo: channel, // Set channel as the reply target
1349
+ });
1350
+ // Write to inbox if enabled
1351
+ if (this.inbox) {
1352
+ this.inbox.addMessage(from, body);
1353
+ }
1354
+ // Try to inject
1355
+ this.checkForInjectionOpportunity();
1356
+ }
1357
+ /**
1358
+ * Check if we should inject a message.
1359
+ * Uses UniversalIdleDetector (from BaseWrapper) for robust cross-CLI idle detection.
1360
+ */
1361
+ checkForInjectionOpportunity() {
1362
+ if (this.messageQueue.length === 0)
1363
+ return;
1364
+ if (this.isInjecting)
1365
+ return;
1366
+ if (!this.running)
1367
+ return;
1368
+ // Use universal idle detector for more reliable detection (inherited from BaseWrapper)
1369
+ const idleResult = this.checkIdleForInjection();
1370
+ if (!idleResult.isIdle) {
1371
+ // Not idle yet, retry later
1372
+ const retryMs = this.config.injectRetryMs ?? 500;
1373
+ setTimeout(() => this.checkForInjectionOpportunity(), retryMs);
1374
+ return;
1375
+ }
1376
+ this.injectNextMessage();
1377
+ }
1378
+ /**
1379
+ * Inject message via tmux send-keys.
1380
+ * Uses shared injection logic with tmux-specific callbacks.
1381
+ */
1382
+ async injectNextMessage() {
1383
+ const msg = this.messageQueue.shift();
1384
+ if (!msg)
1385
+ return;
1386
+ this.isInjecting = true;
1387
+ try {
1388
+ const shortId = msg.messageId.substring(0, 8);
1389
+ // Wait for input to be clear before injecting
1390
+ // If input is not clear (human typing), re-queue and try later - never clear forcefully!
1391
+ const waitTimeoutMs = this.config.inputWaitTimeoutMs ?? 5000;
1392
+ const waitPollMs = this.config.inputWaitPollMs ?? 200;
1393
+ const inputClear = await this.waitForClearInput(waitTimeoutMs, waitPollMs);
1394
+ if (!inputClear) {
1395
+ // Input still has text after timeout - DON'T clear forcefully, re-queue instead
1396
+ this.logStderr('Input not clear, re-queuing injection');
1397
+ this.messageQueue.unshift(msg);
1398
+ this.isInjecting = false;
1399
+ setTimeout(() => this.checkForInjectionOpportunity(), this.config.injectRetryMs ?? 1000);
1400
+ return;
1401
+ }
1402
+ // Ensure pane output is stable to avoid interleaving with active generation
1403
+ const stablePane = await this.waitForStablePane(this.config.outputStabilityTimeoutMs ?? 2000, this.config.outputStabilityPollMs ?? 200);
1404
+ if (!stablePane) {
1405
+ this.logStderr('Output still active, re-queuing injection');
1406
+ this.messageQueue.unshift(msg);
1407
+ this.isInjecting = false;
1408
+ setTimeout(() => this.checkForInjectionOpportunity(), this.config.injectRetryMs ?? 500);
1409
+ return;
1410
+ }
1411
+ // For Gemini: check if we're at a shell prompt ($) vs chat prompt (>)
1412
+ // If at shell prompt, skip injection to avoid shell command execution
1413
+ if (this.cliType === 'gemini') {
1414
+ const lastLine = await this.getLastLine();
1415
+ const cleanLine = stripAnsi(lastLine).trim();
1416
+ if (CLI_QUIRKS.isShellPrompt(cleanLine)) {
1417
+ this.logStderr('Gemini at shell prompt, skipping injection to avoid shell execution');
1418
+ // Re-queue the message for later
1419
+ this.messageQueue.unshift(msg);
1420
+ this.isInjecting = false;
1421
+ setTimeout(() => this.checkForInjectionOpportunity(), 2000);
1422
+ return;
1423
+ }
1424
+ }
1425
+ // Build injection string using shared utility
1426
+ let injection = buildInjectionString(msg);
1427
+ // Gemini-specific: wrap body in backticks to prevent shell keyword interpretation
1428
+ if (this.cliType === 'gemini') {
1429
+ const colonIdx = injection.indexOf(': ');
1430
+ if (colonIdx > 0) {
1431
+ const prefix = injection.substring(0, colonIdx + 2);
1432
+ const body = injection.substring(colonIdx + 2);
1433
+ injection = prefix + CLI_QUIRKS.wrapForGemini(body);
1434
+ }
1435
+ }
1436
+ // Create callbacks for shared injection logic
1437
+ const callbacks = {
1438
+ getOutput: async () => {
1439
+ try {
1440
+ const { stdout } = await execAsync(`"${this.tmuxPath}" capture-pane -t ${this.sessionName} -p -S - 2>/dev/null`);
1441
+ return stdout;
1442
+ }
1443
+ catch {
1444
+ return '';
1445
+ }
1446
+ },
1447
+ performInjection: async (inj) => {
1448
+ // Use send-keys -l (literal) instead of paste-buffer
1449
+ // paste-buffer causes issues where Claude shows "[Pasted text]" but content doesn't appear
1450
+ await this.sendKeysLiteral(inj);
1451
+ await sleep(INJECTION_CONSTANTS.ENTER_DELAY_MS);
1452
+ await this.sendKeys('Enter');
1453
+ },
1454
+ log: (message) => this.logStderr(message),
1455
+ logError: (message) => this.logStderr(message, true),
1456
+ getMetrics: () => this.injectionMetrics,
1457
+ };
1458
+ // Inject with retry and verification using shared logic
1459
+ const result = await sharedInjectWithRetry(injection, shortId, msg.from, callbacks);
1460
+ if (result.success) {
1461
+ this.logStderr(`Injection complete (attempt ${result.attempts})`);
1462
+ // Record success for adaptive throttling
1463
+ this.throttle.recordSuccess();
1464
+ this.sendSyncAck(msg.messageId, msg.sync, 'OK');
1465
+ }
1466
+ else {
1467
+ // All retries failed - log and optionally fall back to inbox
1468
+ this.logStderr(`Message delivery failed after ${result.attempts} attempts: from=${msg.from} id=${shortId}`, true);
1469
+ // Record failure for adaptive throttling
1470
+ this.throttle.recordFailure();
1471
+ // Write to inbox as fallback if enabled
1472
+ if (this.inbox) {
1473
+ this.inbox.addMessage(msg.from, msg.body);
1474
+ this.logStderr('Wrote message to inbox as fallback');
1475
+ }
1476
+ this.sendSyncAck(msg.messageId, msg.sync, 'ERROR', { error: 'injection_failed' });
1477
+ }
1478
+ }
1479
+ catch (err) {
1480
+ this.logStderr(`Injection failed: ${err.message}`, true);
1481
+ // Record failure for adaptive throttling
1482
+ this.throttle.recordFailure();
1483
+ this.sendSyncAck(msg.messageId, msg.sync, 'ERROR', { error: err.message });
1484
+ }
1485
+ finally {
1486
+ this.isInjecting = false;
1487
+ // Process next message after adaptive delay (faster when healthy, slower under stress)
1488
+ if (this.messageQueue.length > 0) {
1489
+ const delay = this.throttle.getDelay();
1490
+ setTimeout(() => this.checkForInjectionOpportunity(), delay);
1491
+ }
1492
+ }
1493
+ }
1494
+ hasSeenIncoming(messageId) {
1495
+ if (this.receivedMessageIdSet.has(messageId)) {
1496
+ return true;
1497
+ }
1498
+ this.receivedMessageIdSet.add(messageId);
1499
+ this.receivedMessageIdOrder.push(messageId);
1500
+ if (this.receivedMessageIdOrder.length > this.MAX_RECEIVED_MESSAGES) {
1501
+ const oldest = this.receivedMessageIdOrder.shift();
1502
+ if (oldest) {
1503
+ this.receivedMessageIdSet.delete(oldest);
1504
+ }
1505
+ }
1506
+ return false;
1507
+ }
1508
+ /**
1509
+ * Send special keys to tmux
1510
+ */
1511
+ async sendKeys(keys) {
1512
+ const cmd = `"${this.tmuxPath}" send-keys -t ${this.sessionName} ${keys}`;
1513
+ try {
1514
+ await execAsync(cmd);
1515
+ this.logStderr(`[sendKeys] Sent: ${keys}`);
1516
+ }
1517
+ catch (err) {
1518
+ this.logStderr(`[sendKeys] Failed to send ${keys}: ${err.message}`, true);
1519
+ throw err;
1520
+ }
1521
+ }
1522
+ /**
1523
+ * Send literal text to tmux
1524
+ */
1525
+ async sendKeysLiteral(text) {
1526
+ // Escape for shell and use -l for literal
1527
+ // Must escape: \ " $ ` ! and remove any newlines
1528
+ const escaped = text
1529
+ .replace(/[\r\n]+/g, ' ') // Remove any newlines first
1530
+ .replace(/\\/g, '\\\\')
1531
+ .replace(/"/g, '\\"')
1532
+ .replace(/\$/g, '\\$')
1533
+ .replace(/`/g, '\\`')
1534
+ .replace(/!/g, '\\!');
1535
+ try {
1536
+ await execAsync(`"${this.tmuxPath}" send-keys -t ${this.sessionName} -l "${escaped}"`);
1537
+ this.logStderr(`[sendKeysLiteral] Sent ${text.length} chars`);
1538
+ }
1539
+ catch (err) {
1540
+ this.logStderr(`[sendKeysLiteral] Failed: ${err.message}`, true);
1541
+ throw err;
1542
+ }
1543
+ }
1544
+ /**
1545
+ * Paste text using tmux buffer with optional bracketed paste to avoid interleaving with ongoing output.
1546
+ * Some CLIs (like droid) don't handle bracketed paste sequences properly, so we skip -p for them.
1547
+ */
1548
+ async pasteLiteral(text) {
1549
+ // Sanitize newlines to keep injection single-line inside paste buffer
1550
+ const sanitized = text.replace(/[\r\n]+/g, ' ');
1551
+ const escaped = sanitized
1552
+ .replace(/\\/g, '\\\\')
1553
+ .replace(/"/g, '\\"')
1554
+ .replace(/\$/g, '\\$')
1555
+ .replace(/`/g, '\\`')
1556
+ .replace(/!/g, '\\!');
1557
+ // Set tmux buffer then paste
1558
+ const setBufferCmd = `"${this.tmuxPath}" set-buffer -- "${escaped}"`;
1559
+ await execAsync(setBufferCmd);
1560
+ await execAsync(`"${this.tmuxPath}" paste-buffer -t ${this.sessionName}`);
1561
+ }
1562
+ /**
1563
+ * Reset session-specific state for wrapper reuse.
1564
+ * Call this when starting a new session with the same wrapper instance.
1565
+ */
1566
+ resetSessionState() {
1567
+ super.resetSessionState();
1568
+ // TmuxWrapper-specific state
1569
+ this.lastSummaryHash = '';
1570
+ }
1571
+ /**
1572
+ * Get the prompt pattern for the current CLI type.
1573
+ */
1574
+ getPromptPattern() {
1575
+ return CLI_QUIRKS.getPromptPattern(this.cliType);
1576
+ }
1577
+ /**
1578
+ * Capture the last non-empty line from the tmux pane.
1579
+ */
1580
+ async getLastLine() {
1581
+ try {
1582
+ const { stdout } = await execAsync(`"${this.tmuxPath}" capture-pane -t ${this.sessionName} -p -J 2>/dev/null`);
1583
+ const lines = stdout.split('\n').filter(l => l.length > 0);
1584
+ return lines[lines.length - 1] || '';
1585
+ }
1586
+ catch {
1587
+ return '';
1588
+ }
1589
+ }
1590
+ /**
1591
+ * Detect if the provided line contains visible user input (beyond the prompt).
1592
+ */
1593
+ hasVisibleInput(line) {
1594
+ const cleanLine = stripAnsi(line).trimEnd();
1595
+ if (cleanLine === '')
1596
+ return false;
1597
+ return !this.getPromptPattern().test(cleanLine);
1598
+ }
1599
+ /**
1600
+ * Check if the input line is clear (no user-typed text after the prompt).
1601
+ * Returns true if the last visible line appears to be just a prompt.
1602
+ */
1603
+ async isInputClear(lastLine) {
1604
+ try {
1605
+ const lineToCheck = lastLine ?? await this.getLastLine();
1606
+ const cleanLine = stripAnsi(lineToCheck).trimEnd();
1607
+ const isClear = this.getPromptPattern().test(cleanLine);
1608
+ if (this.config.debug) {
1609
+ const truncatedLine = cleanLine.substring(0, Math.min(DEBUG_LOG_TRUNCATE_LENGTH, cleanLine.length));
1610
+ this.logStderr(`isInputClear: lastLine="${truncatedLine}", clear=${isClear}`);
1611
+ }
1612
+ return isClear;
1613
+ }
1614
+ catch {
1615
+ // If we can't capture, assume not clear (safer)
1616
+ return false;
1617
+ }
1618
+ }
1619
+ /**
1620
+ * Get cursor X position to detect input length.
1621
+ * Returns the cursor column (0-indexed).
1622
+ */
1623
+ async getCursorX() {
1624
+ try {
1625
+ const { stdout } = await execAsync(`"${this.tmuxPath}" display-message -t ${this.sessionName} -p "#{cursor_x}" 2>/dev/null`);
1626
+ return parseInt(stdout.trim(), 10) || 0;
1627
+ }
1628
+ catch {
1629
+ return 0;
1630
+ }
1631
+ }
1632
+ /**
1633
+ * Wait for the input line to be clear before injecting.
1634
+ * Polls until the input appears empty or timeout is reached.
1635
+ *
1636
+ * @param maxWaitMs Maximum time to wait (default 5000ms)
1637
+ * @param pollIntervalMs How often to check (default 200ms)
1638
+ * @returns true if input became clear, false if timed out
1639
+ */
1640
+ async waitForClearInput(maxWaitMs = 5000, pollIntervalMs = 200) {
1641
+ const startTime = Date.now();
1642
+ let lastCursorX = -1;
1643
+ let stableCursorCount = 0;
1644
+ while (Date.now() - startTime < maxWaitMs) {
1645
+ const lastLine = await this.getLastLine();
1646
+ // Check if input line is just a prompt
1647
+ if (await this.isInputClear(lastLine)) {
1648
+ return true;
1649
+ }
1650
+ const hasInput = this.hasVisibleInput(lastLine);
1651
+ // Also check cursor stability - if cursor is moving, agent is typing
1652
+ const cursorX = await this.getCursorX();
1653
+ if (!hasInput && cursorX === lastCursorX) {
1654
+ stableCursorCount++;
1655
+ // If cursor has been stable for enough polls and at typical prompt position,
1656
+ // the agent might be done but we just can't match the prompt pattern
1657
+ if (stableCursorCount >= STABLE_CURSOR_THRESHOLD && cursorX <= MAX_PROMPT_CURSOR_POSITION) {
1658
+ this.logStderr(`waitForClearInput: cursor stable at x=${cursorX}, assuming clear`);
1659
+ return true;
1660
+ }
1661
+ }
1662
+ else {
1663
+ stableCursorCount = 0;
1664
+ lastCursorX = cursorX;
1665
+ }
1666
+ await sleep(pollIntervalMs);
1667
+ }
1668
+ this.logStderr(`waitForClearInput: timed out after ${maxWaitMs}ms`);
1669
+ return false;
1670
+ }
1671
+ /**
1672
+ * Capture a signature of the current pane content for stability checks.
1673
+ * Uses hash+length to cheaply detect changes without storing full content.
1674
+ */
1675
+ async capturePaneSignature() {
1676
+ try {
1677
+ const { stdout } = await execAsync(`"${this.tmuxPath}" capture-pane -t ${this.sessionName} -p -J -S - 2>/dev/null`);
1678
+ const hash = crypto.createHash('sha1').update(stdout).digest('hex');
1679
+ return `${stdout.length}:${hash}`;
1680
+ }
1681
+ catch {
1682
+ return null;
1683
+ }
1684
+ }
1685
+ /**
1686
+ * Wait for pane output to stabilize before injecting to avoid interleaving with ongoing output.
1687
+ */
1688
+ async waitForStablePane(maxWaitMs = 2000, pollIntervalMs = 200, requiredStablePolls = 2) {
1689
+ const start = Date.now();
1690
+ let lastSig = await this.capturePaneSignature();
1691
+ if (!lastSig)
1692
+ return false;
1693
+ let stableCount = 0;
1694
+ while (Date.now() - start < maxWaitMs) {
1695
+ await sleep(pollIntervalMs);
1696
+ const sig = await this.capturePaneSignature();
1697
+ if (!sig)
1698
+ continue;
1699
+ if (sig === lastSig) {
1700
+ stableCount++;
1701
+ if (stableCount >= requiredStablePolls) {
1702
+ return true;
1703
+ }
1704
+ }
1705
+ else {
1706
+ stableCount = 0;
1707
+ lastSig = sig;
1708
+ }
1709
+ }
1710
+ this.logStderr(`waitForStablePane: timed out after ${maxWaitMs}ms`);
1711
+ return false;
1712
+ }
1713
+ /**
1714
+ * Stop and cleanup
1715
+ */
1716
+ stop() {
1717
+ if (!this.running)
1718
+ return;
1719
+ this.running = false;
1720
+ this.activityState = 'disconnected';
1721
+ this.stopStuckDetection();
1722
+ // Auto-save continuity state before shutdown (fire and forget)
1723
+ // Pass sessionEndData to populate handoff (fixes empty handoff issue)
1724
+ if (this.continuity) {
1725
+ this.continuity.autoSave(this.config.name, 'session_end', this.sessionEndData).catch((err) => {
1726
+ this.logStderr(`[CONTINUITY] Auto-save failed: ${err.message}`, true);
1727
+ });
1728
+ }
1729
+ // Reset session state for potential reuse
1730
+ this.resetSessionState();
1731
+ // Stop polling
1732
+ if (this.pollTimer) {
1733
+ clearInterval(this.pollTimer);
1734
+ this.pollTimer = undefined;
1735
+ }
1736
+ // Kill tmux session
1737
+ try {
1738
+ execSync(`"${this.tmuxPath}" kill-session -t ${this.sessionName} 2>/dev/null`);
1739
+ }
1740
+ catch {
1741
+ // Ignore
1742
+ }
1743
+ // Disconnect relay
1744
+ this.client.destroy();
1745
+ }
1746
+ }
1747
+ //# sourceMappingURL=tmux-wrapper.js.map