@northflare/runner 0.0.1

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 (154) hide show
  1. package/DEBUG_LOGGING.md +60 -0
  2. package/LICENSE +21 -0
  3. package/MIGRATION_PLAN.md +52 -0
  4. package/README.md +220 -0
  5. package/SDK_IMPLEMENTATION_GUIDE.md +1036 -0
  6. package/bin/northflare-runner +367 -0
  7. package/coverage/base.css +224 -0
  8. package/coverage/block-navigation.js +87 -0
  9. package/coverage/coverage-final.json +12 -0
  10. package/coverage/favicon.png +0 -0
  11. package/coverage/index.html +176 -0
  12. package/coverage/lib/index.html +116 -0
  13. package/coverage/lib/preload-script.js.html +964 -0
  14. package/coverage/prettify.css +1 -0
  15. package/coverage/prettify.js +2 -0
  16. package/coverage/sort-arrow-sprite.png +0 -0
  17. package/coverage/sorter.js +196 -0
  18. package/coverage/src/collections/index.html +116 -0
  19. package/coverage/src/collections/runner-messages.ts.html +312 -0
  20. package/coverage/src/components/claude-manager.ts.html +1290 -0
  21. package/coverage/src/components/index.html +146 -0
  22. package/coverage/src/components/message-handler.ts.html +730 -0
  23. package/coverage/src/components/repository-manager.ts.html +841 -0
  24. package/coverage/src/index.html +131 -0
  25. package/coverage/src/index.ts.html +448 -0
  26. package/coverage/src/runner.ts.html +1239 -0
  27. package/coverage/src/utils/config.ts.html +780 -0
  28. package/coverage/src/utils/console.ts.html +121 -0
  29. package/coverage/src/utils/index.html +161 -0
  30. package/coverage/src/utils/logger.ts.html +475 -0
  31. package/coverage/src/utils/status-line.ts.html +445 -0
  32. package/dist/collections/runner-messages.d.ts +52 -0
  33. package/dist/collections/runner-messages.d.ts.map +1 -0
  34. package/dist/collections/runner-messages.js +161 -0
  35. package/dist/collections/runner-messages.js.map +1 -0
  36. package/dist/components/claude-manager.d.ts +39 -0
  37. package/dist/components/claude-manager.d.ts.map +1 -0
  38. package/dist/components/claude-manager.js +783 -0
  39. package/dist/components/claude-manager.js.map +1 -0
  40. package/dist/components/claude-sdk-manager.d.ts +47 -0
  41. package/dist/components/claude-sdk-manager.d.ts.map +1 -0
  42. package/dist/components/claude-sdk-manager.js +1088 -0
  43. package/dist/components/claude-sdk-manager.js.map +1 -0
  44. package/dist/components/enhanced-repository-manager.d.ts +134 -0
  45. package/dist/components/enhanced-repository-manager.d.ts.map +1 -0
  46. package/dist/components/enhanced-repository-manager.js +602 -0
  47. package/dist/components/enhanced-repository-manager.js.map +1 -0
  48. package/dist/components/message-handler-sse.d.ts +46 -0
  49. package/dist/components/message-handler-sse.d.ts.map +1 -0
  50. package/dist/components/message-handler-sse.js +734 -0
  51. package/dist/components/message-handler-sse.js.map +1 -0
  52. package/dist/components/message-handler.d.ts +35 -0
  53. package/dist/components/message-handler.d.ts.map +1 -0
  54. package/dist/components/message-handler.js +689 -0
  55. package/dist/components/message-handler.js.map +1 -0
  56. package/dist/components/repository-manager.d.ts +51 -0
  57. package/dist/components/repository-manager.d.ts.map +1 -0
  58. package/dist/components/repository-manager.js +295 -0
  59. package/dist/components/repository-manager.js.map +1 -0
  60. package/dist/index.d.ts +9 -0
  61. package/dist/index.d.ts.map +1 -0
  62. package/dist/index.js +166 -0
  63. package/dist/index.js.map +1 -0
  64. package/dist/runner-sse.d.ts +57 -0
  65. package/dist/runner-sse.d.ts.map +1 -0
  66. package/dist/runner-sse.js +698 -0
  67. package/dist/runner-sse.js.map +1 -0
  68. package/dist/runner.d.ts +51 -0
  69. package/dist/runner.d.ts.map +1 -0
  70. package/dist/runner.js +530 -0
  71. package/dist/runner.js.map +1 -0
  72. package/dist/services/RunnerAPIClient.d.ts +30 -0
  73. package/dist/services/RunnerAPIClient.d.ts.map +1 -0
  74. package/dist/services/RunnerAPIClient.js +112 -0
  75. package/dist/services/RunnerAPIClient.js.map +1 -0
  76. package/dist/services/SSEClient.d.ts +60 -0
  77. package/dist/services/SSEClient.d.ts.map +1 -0
  78. package/dist/services/SSEClient.js +204 -0
  79. package/dist/services/SSEClient.js.map +1 -0
  80. package/dist/types/claude.d.ts +45 -0
  81. package/dist/types/claude.d.ts.map +1 -0
  82. package/dist/types/claude.js +6 -0
  83. package/dist/types/claude.js.map +1 -0
  84. package/dist/types/index.d.ts +47 -0
  85. package/dist/types/index.d.ts.map +1 -0
  86. package/dist/types/index.js +23 -0
  87. package/dist/types/index.js.map +1 -0
  88. package/dist/types/messages.d.ts +31 -0
  89. package/dist/types/messages.d.ts.map +1 -0
  90. package/dist/types/messages.js +6 -0
  91. package/dist/types/messages.js.map +1 -0
  92. package/dist/types/runner-interface.d.ts +24 -0
  93. package/dist/types/runner-interface.d.ts.map +1 -0
  94. package/dist/types/runner-interface.js +6 -0
  95. package/dist/types/runner-interface.js.map +1 -0
  96. package/dist/utils/StateManager.d.ts +52 -0
  97. package/dist/utils/StateManager.d.ts.map +1 -0
  98. package/dist/utils/StateManager.js +162 -0
  99. package/dist/utils/StateManager.js.map +1 -0
  100. package/dist/utils/config.d.ts +41 -0
  101. package/dist/utils/config.d.ts.map +1 -0
  102. package/dist/utils/config.js +250 -0
  103. package/dist/utils/config.js.map +1 -0
  104. package/dist/utils/console.d.ts +11 -0
  105. package/dist/utils/console.d.ts.map +1 -0
  106. package/dist/utils/console.js +15 -0
  107. package/dist/utils/console.js.map +1 -0
  108. package/dist/utils/expand-env.d.ts +2 -0
  109. package/dist/utils/expand-env.d.ts.map +1 -0
  110. package/dist/utils/expand-env.js +20 -0
  111. package/dist/utils/expand-env.js.map +1 -0
  112. package/dist/utils/logger.d.ts +9 -0
  113. package/dist/utils/logger.d.ts.map +1 -0
  114. package/dist/utils/logger.js +108 -0
  115. package/dist/utils/logger.js.map +1 -0
  116. package/dist/utils/status-line.d.ts +37 -0
  117. package/dist/utils/status-line.d.ts.map +1 -0
  118. package/dist/utils/status-line.js +113 -0
  119. package/dist/utils/status-line.js.map +1 -0
  120. package/docs/claude-manager.md +91 -0
  121. package/exceptions.log +22 -0
  122. package/lib/preload-script.js +293 -0
  123. package/package.json +55 -0
  124. package/rejections.log +63 -0
  125. package/runner.log +488 -0
  126. package/src/components/claude-sdk-manager.ts +1354 -0
  127. package/src/components/enhanced-repository-manager.ts +823 -0
  128. package/src/components/message-handler-sse.ts +1011 -0
  129. package/src/components/repository-manager.ts +337 -0
  130. package/src/index.ts +166 -0
  131. package/src/runner-sse.ts +847 -0
  132. package/src/services/RunnerAPIClient.ts +135 -0
  133. package/src/services/SSEClient.ts +258 -0
  134. package/src/types/claude.ts +55 -0
  135. package/src/types/computer-name.d.ts +4 -0
  136. package/src/types/index.ts +63 -0
  137. package/src/types/messages.ts +39 -0
  138. package/src/types/runner-interface.ts +34 -0
  139. package/src/utils/StateManager.ts +187 -0
  140. package/src/utils/codex-sdk.js +448 -0
  141. package/src/utils/config.ts +315 -0
  142. package/src/utils/console.ts +13 -0
  143. package/src/utils/expand-env.ts +22 -0
  144. package/src/utils/logger.ts +131 -0
  145. package/src/utils/sdk-demo.js +34 -0
  146. package/src/utils/status-line.ts +121 -0
  147. package/test-debug.sh +26 -0
  148. package/tests/retry-strategies.test.ts +410 -0
  149. package/tests/sdk-integration.test.ts +329 -0
  150. package/tests/sdk-streaming.test.ts +1180 -0
  151. package/tests/setup.ts +5 -0
  152. package/tests/test-claude-manager.ts +120 -0
  153. package/tsconfig.json +36 -0
  154. package/vitest.config.ts +27 -0
@@ -0,0 +1,1011 @@
1
+ /**
2
+ * MessageHandler - Processes incoming JSONRPC messages from SSE events
3
+ */
4
+
5
+ import { IRunnerApp } from "../types/runner-interface";
6
+ import { RunnerMessage, MethodHandler, ConversationContext } from "../types";
7
+ import { SSEClient, SSEEvent } from "../services/SSEClient";
8
+ import { RunnerAPIClient } from "../services/RunnerAPIClient";
9
+ import { statusLineManager } from "../utils/status-line";
10
+ import { console } from "../utils/console";
11
+ import { createLogger } from "../utils/logger";
12
+
13
+ const logger = createLogger("MessageHandler");
14
+
15
+ export class MessageHandler {
16
+ private methodHandlers: Map<string, MethodHandler>;
17
+ private runner: IRunnerApp;
18
+ private processedMessages: Set<string> = new Set();
19
+ private sseClient: SSEClient | null = null;
20
+ private apiClient: RunnerAPIClient;
21
+ private isProcessing: boolean = false;
22
+
23
+ constructor(runner: IRunnerApp) {
24
+ this.runner = runner;
25
+ this.methodHandlers = new Map();
26
+ this.apiClient = new RunnerAPIClient(runner.config_);
27
+ this.registerHandlers();
28
+ }
29
+
30
+ async startProcessing(): Promise<void> {
31
+ console.log("MessageHandler: Starting message processing with SSE...");
32
+
33
+ if (this.isProcessing) {
34
+ logger.warn("Message processing already started");
35
+ return;
36
+ }
37
+
38
+ this.isProcessing = true;
39
+
40
+ // Update API client with runner ID if available
41
+ const runnerId = this.runner.getRunnerId();
42
+ if (runnerId) {
43
+ this.apiClient.setRunnerId(runnerId);
44
+ }
45
+
46
+ // Catch up on missed messages first
47
+ await this.catchUpMissedMessages();
48
+
49
+ // Start SSE connection
50
+ await this.connectSSE();
51
+ }
52
+
53
+ async stopProcessing(): Promise<void> {
54
+ console.log("MessageHandler: Stopping message processing...");
55
+
56
+ this.isProcessing = false;
57
+
58
+ // Stop SSE client
59
+ if (this.sseClient) {
60
+ this.sseClient.stop();
61
+ this.sseClient = null;
62
+ }
63
+
64
+ // Clear processed messages tracking
65
+ this.processedMessages.clear();
66
+ }
67
+
68
+ /**
69
+ * Catch up on missed messages since lastProcessedAt
70
+ */
71
+ private async catchUpMissedMessages(): Promise<void> {
72
+ const lastProcessedAt = this.runner.getLastProcessedAt();
73
+
74
+ if (!lastProcessedAt) {
75
+ logger.debug("No lastProcessedAt timestamp, skipping catch-up");
76
+ return;
77
+ }
78
+
79
+ console.log(
80
+ `MessageHandler: Catching up on messages since ${lastProcessedAt.toISOString()}`
81
+ );
82
+
83
+ try {
84
+ const messages = await this.apiClient.fetchMissedMessages({
85
+ since: lastProcessedAt,
86
+ limit: 1000,
87
+ });
88
+
89
+ if (messages.length > 0) {
90
+ console.log(
91
+ `MessageHandler: Processing ${messages.length} missed messages`
92
+ );
93
+
94
+ // Process messages in order
95
+ for (const message of messages) {
96
+ await this.processMessage(message);
97
+ }
98
+ } else {
99
+ console.log("MessageHandler: No missed messages to process");
100
+ }
101
+ } catch (error) {
102
+ logger.error("Failed to catch up on missed messages:", error);
103
+ // Continue anyway - SSE connection might still work
104
+ }
105
+ }
106
+
107
+ /**
108
+ * Connect to SSE endpoint
109
+ */
110
+ private async connectSSE(): Promise<void> {
111
+ const runnerId = this.runner.getRunnerId();
112
+ if (!runnerId) {
113
+ throw new Error("Cannot connect to SSE without runner ID");
114
+ }
115
+
116
+ const token = process.env["NORTHFLARE_RUNNER_TOKEN"];
117
+ if (!token) {
118
+ throw new Error("Missing NORTHFLARE_RUNNER_TOKEN");
119
+ }
120
+
121
+ console.log("MessageHandler: Connecting to SSE endpoint...");
122
+
123
+ this.sseClient = new SSEClient({
124
+ url: `${this.runner.config_.orchestratorUrl}/api/runner-events`,
125
+ runnerId,
126
+ token,
127
+ onMessage: this.handleSSEEvent.bind(this),
128
+ onError: (error) => {
129
+ logger.error("SSE connection error:", error);
130
+ },
131
+ onConnect: () => {
132
+ console.log("MessageHandler: SSE connection established");
133
+ },
134
+ onDisconnect: () => {
135
+ console.log("MessageHandler: SSE connection closed");
136
+ },
137
+ reconnectInterval: 1000,
138
+ maxReconnectInterval: 30000,
139
+ reconnectMultiplier: 2,
140
+ });
141
+
142
+ // Connect with lastProcessedAt for server-side filtering
143
+ const lastProcessedAt = this.runner.getLastProcessedAt();
144
+ await this.sseClient.connect(lastProcessedAt?.toISOString());
145
+ }
146
+
147
+ /**
148
+ * Handle SSE event
149
+ */
150
+ private async handleSSEEvent(event: SSEEvent): Promise<void> {
151
+ if (event.type === "runner.message") {
152
+ const message = event.data as RunnerMessage;
153
+
154
+ if (process.env["DEBUG"] === "true") {
155
+ logger.debug("Received SSE event", {
156
+ eventId: event.id,
157
+ type: event.type,
158
+ messageId: message?.id,
159
+ method: message?.payload?.method,
160
+ createdAt: message?.createdAt,
161
+ });
162
+ }
163
+
164
+ try {
165
+ // Process the message
166
+ await this.processMessage(message);
167
+ } catch (err) {
168
+ const msg = err instanceof Error ? err.message : String(err);
169
+ logger.error("Failed to process runner.message:", msg);
170
+ // Do not crash the runner on a single bad message
171
+ return;
172
+ }
173
+ } else if (event.type === "connection.established") {
174
+ logger.debug("SSE connection established", event.data);
175
+ } else {
176
+ logger.debug(`Received event type: ${event.type}`, event.data);
177
+ }
178
+ }
179
+
180
+ private async processMessage(message: RunnerMessage): Promise<void> {
181
+ if (process.env["DEBUG"] === "true") {
182
+ logger.debug("processMessage called", {
183
+ messageId: message.id,
184
+ method: message.payload?.method,
185
+ direction: message.direction,
186
+ createdAt: message.createdAt,
187
+ });
188
+ }
189
+
190
+ // Skip if already processed
191
+ if (this.processedMessages.has(message.id)) {
192
+ return;
193
+ }
194
+
195
+ // Check if we should process this message based on ownership
196
+ if (!this.shouldProcessMessage(message)) {
197
+ return;
198
+ }
199
+
200
+ const { method, params } = message.payload;
201
+
202
+ if (!method) {
203
+ await this.sendError(message, "Missing method in message payload");
204
+ return;
205
+ }
206
+
207
+ const handler = this.methodHandlers.get(method);
208
+
209
+ if (!handler) {
210
+ await this.sendError(message, `Unknown method: ${method}`);
211
+ return;
212
+ }
213
+
214
+ if (process.env["DEBUG"] === "true") {
215
+ logger.debug("Processing message", {
216
+ messageId: message.id,
217
+ method: method,
218
+ taskId: message.taskId,
219
+ isActionMessage: this.isActionMessage(message),
220
+ });
221
+ }
222
+
223
+ try {
224
+ await handler(params, message);
225
+ await this.markProcessed(message);
226
+
227
+ // Acknowledge ALL messages to update lastProcessedAt
228
+ await this.acknowledgeMessage(message);
229
+
230
+ if (process.env["DEBUG"] === "true") {
231
+ logger.debug("Message acknowledged", {
232
+ messageId: message.id,
233
+ method: method,
234
+ timestamp: message.createdAt,
235
+ wasActionMessage: this.isActionMessage(message),
236
+ });
237
+ }
238
+ } catch (error) {
239
+ if (process.env["DEBUG"] === "true") {
240
+ logger.debug("Message processing error", {
241
+ messageId: message.id,
242
+ method: method,
243
+ error: error instanceof Error ? error.message : String(error),
244
+ });
245
+ }
246
+ await this.handleError(message, error);
247
+ }
248
+ }
249
+
250
+ private shouldProcessMessage(message: RunnerMessage): boolean {
251
+ const decision = (() => {
252
+ // Always process our own responses going to orchestrator
253
+ if (message.direction === "to_orchestrator") {
254
+ return { shouldProcess: true, reason: "own response to orchestrator" };
255
+ }
256
+
257
+ // Filter by lastProcessedAt first (before checking active status)
258
+ const lastProcessedAt = this.runner.getLastProcessedAt();
259
+ if (lastProcessedAt && message.createdAt) {
260
+ const messageTime = new Date(message.createdAt);
261
+ if (messageTime <= lastProcessedAt) {
262
+ return {
263
+ shouldProcess: false,
264
+ reason: "message before lastProcessedAt",
265
+ };
266
+ }
267
+ }
268
+
269
+ // Always process UID change messages (after time check)
270
+ if (message.payload?.method === "runner.uid.changed") {
271
+ return { shouldProcess: true, reason: "UID change message" };
272
+ }
273
+
274
+ // If we're not the active runner
275
+ if (!this.runner.getIsActiveRunner()) {
276
+ // Only process if it's for a pre-handoff conversation by conversationId
277
+ const cid =
278
+ message.conversationId || message.payload?.params?.conversationId;
279
+ if (cid && this.runner.getPreHandoffConversations().has(cid)) {
280
+ return {
281
+ shouldProcess: true,
282
+ reason: "pre-handoff conversation (by conversationId)",
283
+ };
284
+ }
285
+ return { shouldProcess: false, reason: "not active runner" };
286
+ }
287
+
288
+ // We're active and message is after lastProcessedAt
289
+ return {
290
+ shouldProcess: true,
291
+ reason: "active runner, message after watermark",
292
+ };
293
+ })();
294
+
295
+ if (process.env["DEBUG"] === "true") {
296
+ logger.debug("Message processing decision", {
297
+ messageId: message.id,
298
+ method: message.payload?.method,
299
+ shouldProcess: decision.shouldProcess,
300
+ reason: decision.reason,
301
+ runnerUid: this.runner.getRunnerUid(),
302
+ isActiveRunner: this.runner.getIsActiveRunner(),
303
+ lastProcessedAt:
304
+ this.runner.getLastProcessedAt()?.toISOString() || "null",
305
+ messageCreatedAt: message.createdAt,
306
+ });
307
+ }
308
+
309
+ return decision.shouldProcess;
310
+ }
311
+
312
+ private isActionMessage(message: RunnerMessage): boolean {
313
+ const actionMethods = [
314
+ "conversation.start",
315
+ "conversation.stop",
316
+ "conversation.resume",
317
+ "conversation.config",
318
+ "message.user",
319
+ ];
320
+ return actionMethods.includes(message.payload?.method || "");
321
+ }
322
+
323
+ private async acknowledgeMessage(message: RunnerMessage): Promise<void> {
324
+ const runnerId = this.runner.getRunnerId();
325
+ console.log(`[MessageHandler] Sending message.acknowledge:`, {
326
+ runnerId,
327
+ messageTimestamp: message.createdAt,
328
+ messageId: message.id,
329
+ method: message.payload?.method,
330
+ });
331
+
332
+ try {
333
+ await this.apiClient.acknowledgeMessage(message.createdAt);
334
+
335
+ // Update local lastProcessedAt
336
+ await this.runner.updateLastProcessedAt!(new Date(message.createdAt));
337
+
338
+ console.log(`[MessageHandler] ✅ message.acknowledge sent successfully`);
339
+ } catch (error) {
340
+ logger.error("Failed to acknowledge message:", error);
341
+ // Continue processing even if acknowledgment fails
342
+ }
343
+ }
344
+
345
+ private async markProcessed(message: RunnerMessage): Promise<void> {
346
+ // Track processed messages internally
347
+ this.processedMessages.add(message.id);
348
+ }
349
+
350
+ private async sendError(
351
+ message: RunnerMessage,
352
+ errorMessage: string
353
+ ): Promise<void> {
354
+ // Send error report with conversation object info if available
355
+ const conversationObjectType =
356
+ message.conversationObjectType || (message.taskId ? "Task" : undefined);
357
+ const conversationObjectId = message.conversationObjectId || message.taskId;
358
+
359
+ if (!conversationObjectId) {
360
+ console.error(
361
+ `[MessageHandler] Cannot send error report - no conversationObjectId available. Error: ${errorMessage}`
362
+ );
363
+ if (process.env["DEBUG"] === "true") {
364
+ logger.debug("Error without conversationObjectId", {
365
+ messageId: message.id,
366
+ method: message.payload?.method,
367
+ error: errorMessage,
368
+ runnerId: message.runnerId,
369
+ });
370
+ }
371
+ return;
372
+ }
373
+
374
+ await this.runner.notify("error.report", {
375
+ conversationObjectType,
376
+ conversationObjectId,
377
+ messageId: message.id,
378
+ errorType: "method_error",
379
+ message: errorMessage,
380
+ details: {
381
+ originalMessage: message,
382
+ timestamp: new Date(),
383
+ },
384
+ });
385
+ }
386
+
387
+ private async handleError(message: RunnerMessage, error: any): Promise<void> {
388
+ const errorMessage = error instanceof Error ? error.message : String(error);
389
+ const errorStack = error instanceof Error ? error.stack : undefined;
390
+
391
+ // Send error report with conversation object info if available
392
+ const conversationObjectType =
393
+ message.conversationObjectType || (message.taskId ? "Task" : undefined);
394
+ const conversationObjectId = message.conversationObjectId || message.taskId;
395
+
396
+ if (!conversationObjectId) {
397
+ console.error(
398
+ `[MessageHandler] Cannot send error report - no conversationObjectId available. Processing error: ${errorMessage}`
399
+ );
400
+ if (process.env["DEBUG"] === "true") {
401
+ logger.debug("Processing error without conversationObjectId", {
402
+ messageId: message.id,
403
+ method: message.payload?.method,
404
+ error: errorMessage,
405
+ stack: errorStack,
406
+ runnerId: message.runnerId,
407
+ });
408
+ }
409
+ return;
410
+ }
411
+
412
+ await this.runner.notify("error.report", {
413
+ conversationObjectType,
414
+ conversationObjectId,
415
+ messageId: message.id,
416
+ errorType: "processing_error",
417
+ message: errorMessage,
418
+ details: {
419
+ stack: errorStack,
420
+ originalMessage: message,
421
+ timestamp: new Date(),
422
+ },
423
+ });
424
+ }
425
+
426
+ private registerHandlers(): void {
427
+ console.log("MessageHandler: Registering handlers...");
428
+
429
+ this.methodHandlers = new Map([
430
+ ["conversation.start", this.handleConversationStart.bind(this)],
431
+ ["conversation.stop", this.handleConversationStop.bind(this)],
432
+ ["conversation.resume", this.handleConversationResume.bind(this)],
433
+ ["conversation.config", this.handleConversationConfig.bind(this)],
434
+ ["message.user", this.handleUserMessage.bind(this)],
435
+ ["runner.uid.changed", this.handleUidChanged.bind(this)],
436
+ ["git.operation", this.handleGitOperation.bind(this)],
437
+ ["git.cleanup", this.handleGitCleanup.bind(this)],
438
+ ]);
439
+ }
440
+
441
+ // All the handler methods remain the same as in the original file
442
+ // Just copy them from the original message-handler.ts starting from line 386
443
+
444
+ private async handleConversationStart(
445
+ params: any,
446
+ message: RunnerMessage
447
+ ): Promise<void> {
448
+ const {
449
+ conversationObjectType = message.conversationObjectType || "Task",
450
+ conversationObjectId = message.conversationObjectId ||
451
+ params.conversation?.objectId,
452
+ config,
453
+ initialMessages,
454
+ conversation,
455
+ } = params;
456
+
457
+ // Validate required parameters
458
+ if (!config) {
459
+ throw new Error("Missing required parameter: config");
460
+ }
461
+
462
+ // Require a conversation object
463
+ const conversationData = conversation;
464
+ if (!conversationData) {
465
+ throw new Error(
466
+ "Missing required parameter: conversation object must be provided"
467
+ );
468
+ }
469
+
470
+ const finalObjectType =
471
+ conversationObjectType || conversationData.objectType;
472
+ const finalObjectId = conversationObjectId || conversationData.objectId;
473
+ if (!finalObjectId) {
474
+ throw new Error("Missing conversationObjectId");
475
+ }
476
+
477
+ // Debug log the config
478
+ console.log(`[MessageHandler] conversation.start config:`, {
479
+ conversationObjectId,
480
+ hasConfig: !!config,
481
+ hasRepository: !!config?.repository,
482
+ repositoryType: config?.repository?.type,
483
+ repositoryUrl: config?.repository?.url,
484
+ workspaceId: config?.workspaceId,
485
+ fullConfig: JSON.stringify(config, null, 2),
486
+ });
487
+
488
+ // Start the conversation with the provided/loaded conversation details
489
+ await this.runner.claudeManager_.startConversation(
490
+ finalObjectType,
491
+ finalObjectId,
492
+ config,
493
+ initialMessages || [],
494
+ conversationData
495
+ );
496
+
497
+ // Update status line
498
+ statusLineManager.updateActiveCount(this.runner.activeConversations_.size);
499
+ }
500
+
501
+ private async handleConversationStop(
502
+ params: any,
503
+ message: RunnerMessage
504
+ ): Promise<void> {
505
+ // Require conversationId (present at message level); do not fall back to agentSessionId/taskId
506
+ const { conversationId = message.conversationId, reason } = params;
507
+
508
+ console.log(`[MessageHandler] handleConversationStop called with:`, {
509
+ conversationId,
510
+ messageConversationId: message.conversationId,
511
+ agentSessionId: params?.agentSessionId,
512
+ taskId: params?.taskId,
513
+ params: JSON.stringify(params),
514
+ activeConversations: this.runner.activeConversations_.size,
515
+ conversationIds: Array.from(this.runner.activeConversations_.keys()),
516
+ });
517
+
518
+ // Lookup strictly by conversationId
519
+ let context: ConversationContext | undefined;
520
+ let targetConversationId: string | undefined;
521
+ if (conversationId) {
522
+ context = this.runner.getConversationContext(conversationId);
523
+ targetConversationId = conversationId;
524
+ }
525
+
526
+ console.log(`[MessageHandler] handleConversationStop lookup result:`, {
527
+ contextFound: !!context,
528
+ targetConversationId,
529
+ contextTaskId: context?.taskId,
530
+ contextAgentSessionId: context?.agentSessionId,
531
+ });
532
+
533
+ // Check if we have any identifier to work with
534
+ if (!conversationId) {
535
+ throw new Error("Missing required parameter: conversationId");
536
+ }
537
+
538
+ if (context && targetConversationId) {
539
+ context.status = "stopping";
540
+ await this.runner.claudeManager_.stopConversation(
541
+ context.agentSessionId,
542
+ context,
543
+ false, // Not a runner shutdown
544
+ reason // Pass the reason through
545
+ );
546
+ context.status = "stopped";
547
+ this.runner.activeConversations_.delete(targetConversationId);
548
+
549
+ // Update status line
550
+ statusLineManager.updateActiveCount(
551
+ this.runner.activeConversations_.size
552
+ );
553
+ } else {
554
+ // No conversation found - this is expected as conversations may have already ended
555
+ // or been cleaned up. Just log it and update status line.
556
+ console.log(
557
+ `Conversation stop requested for ${conversationId} - conversation not found or already cleaned up`
558
+ );
559
+
560
+ // If we have a targetConversationId, ensure it's removed from tracking
561
+ if (targetConversationId) {
562
+ this.runner.activeConversations_.delete(targetConversationId);
563
+ }
564
+
565
+ statusLineManager.updateActiveCount(
566
+ this.runner.activeConversations_.size
567
+ );
568
+ }
569
+ }
570
+
571
+ private async handleConversationResume(
572
+ params: any,
573
+ message: RunnerMessage
574
+ ): Promise<void> {
575
+ const {
576
+ conversationId = message.conversationId,
577
+ conversation: resumeConversation,
578
+ config,
579
+ message: resumeMessage,
580
+ } = params;
581
+
582
+ const cid = params.conversationId || conversationId;
583
+ if (!cid) {
584
+ throw new Error("Missing required parameter: conversationId");
585
+ }
586
+
587
+ // Require conversation details
588
+ const conversationData = resumeConversation;
589
+ if (!conversationData) {
590
+ throw new Error(
591
+ "Missing required parameter: conversation object must be provided"
592
+ );
593
+ }
594
+
595
+ const agentSessionId = conversationData.agentSessionId;
596
+ if (!agentSessionId) {
597
+ throw new Error("Cannot resume conversation without agentSessionId");
598
+ }
599
+
600
+ await this.runner.claudeManager_.resumeConversation(
601
+ conversationData.objectType,
602
+ conversationData.objectId,
603
+ agentSessionId,
604
+ config,
605
+ conversationData,
606
+ resumeMessage
607
+ );
608
+ }
609
+
610
+ private async handleConversationConfig(
611
+ params: any,
612
+ message: RunnerMessage
613
+ ): Promise<void> {
614
+ const { conversationId, model, permissionsMode, config } = params;
615
+
616
+ console.log(`[MessageHandler] handleConversationConfig called with:`, {
617
+ conversationId,
618
+ model,
619
+ permissionsMode,
620
+ hasConfig: !!config,
621
+ });
622
+
623
+ // Find the active conversation by conversationId only
624
+ let context: ConversationContext | undefined;
625
+ if (conversationId) {
626
+ context = this.runner.getConversationContext(conversationId);
627
+ }
628
+
629
+ if (!context) {
630
+ throw new Error(
631
+ `No active conversation found for conversationId: ${conversationId}`
632
+ );
633
+ }
634
+
635
+ // Validate required parameters
636
+ if (!model && !permissionsMode) {
637
+ throw new Error(
638
+ "At least one of model or permissionsMode must be provided"
639
+ );
640
+ }
641
+
642
+ // Update the config with new values
643
+ const newConfig = {
644
+ ...context.config,
645
+ ...(model && { model }),
646
+ ...(permissionsMode && { permissionsMode }),
647
+ ...config, // Allow full config overrides if provided
648
+ };
649
+
650
+ console.log(
651
+ `[MessageHandler] Stopping conversation ${context.conversationId} to apply new config`
652
+ );
653
+
654
+ // Stop the current conversation
655
+ await this.runner.claudeManager_.stopConversation(
656
+ context.agentSessionId,
657
+ context,
658
+ false // Not a runner shutdown, just updating config
659
+ );
660
+
661
+ // Remove from active conversations
662
+ this.runner.activeConversations_.delete(context.conversationId);
663
+
664
+ console.log(
665
+ `[MessageHandler] Resuming conversation ${context.conversationId} with new config`
666
+ );
667
+
668
+ // Resume with new config
669
+ await this.runner.claudeManager_.resumeConversation(
670
+ context.conversationObjectType,
671
+ context.conversationObjectId,
672
+ context.agentSessionId,
673
+ newConfig,
674
+ {
675
+ id: context.conversationId,
676
+ objectType: context.conversationObjectType,
677
+ objectId: context.conversationObjectId,
678
+ model: newConfig.model,
679
+ globalInstructions: context.globalInstructions,
680
+ workspaceInstructions: context.workspaceInstructions,
681
+ permissionsMode: newConfig.permissionsMode,
682
+ agentSessionId: context.agentSessionId,
683
+ },
684
+ "<system-instructions>Configuration updated. Please continue with the new settings.</system-instructions>"
685
+ );
686
+
687
+ // Update status line
688
+ statusLineManager.updateActiveCount(this.runner.activeConversations_.size);
689
+
690
+ console.log(
691
+ `[MessageHandler] Conversation ${context.conversationId} config updated successfully`
692
+ );
693
+ }
694
+
695
+ private async handleUserMessage(
696
+ params: any,
697
+ message: RunnerMessage
698
+ ): Promise<void> {
699
+ const {
700
+ conversationId,
701
+ content,
702
+ config,
703
+ conversationObjectType = message.conversationObjectType || "Task",
704
+ conversationObjectId = message.conversationObjectId,
705
+ conversation,
706
+ } = params;
707
+
708
+ // Validate required parameters
709
+ if (!conversationId) {
710
+ throw new Error("Missing required parameter: conversationId");
711
+ }
712
+
713
+ if (!content) {
714
+ throw new Error("Missing required parameter: content");
715
+ }
716
+
717
+ await this.runner.claudeManager_.sendUserMessage(
718
+ conversationId,
719
+ content,
720
+ config,
721
+ conversationObjectType,
722
+ conversationObjectId,
723
+ conversation
724
+ );
725
+ }
726
+
727
+ private async handleUidChanged(
728
+ params: any,
729
+ _message: RunnerMessage
730
+ ): Promise<void> {
731
+ const { runnerUid, lastProcessedAt } = params;
732
+
733
+ console.log(
734
+ `MessageHandler: Handling UID change notification - new UID: ${runnerUid}, lastProcessedAt: ${lastProcessedAt}`
735
+ );
736
+
737
+ if (process.env["DEBUG"] === "true") {
738
+ logger.debug("UID change notification received", {
739
+ newUid: runnerUid,
740
+ currentUid: this.runner.getRunnerUid(),
741
+ newLastProcessedAt: lastProcessedAt,
742
+ currentLastProcessedAt:
743
+ this.runner.getLastProcessedAt()?.toISOString() || "null",
744
+ wasActiveRunner: this.runner.getIsActiveRunner(),
745
+ activeConversations: this.runner.activeConversations_.size,
746
+ });
747
+ }
748
+
749
+ // Check if the UID matches ours FIRST, before checking timestamps
750
+ // This ensures we activate even if we received the message during catch-up
751
+ if (runnerUid === this.runner.getRunnerUid()) {
752
+ // This is our UID - we're the active runner
753
+ console.log("MessageHandler: We are now the active runner");
754
+ this.runner.setIsActiveRunner(true);
755
+ await this.runner.updateLastProcessedAt!(
756
+ lastProcessedAt ? new Date(lastProcessedAt) : null
757
+ );
758
+
759
+ if (process.env["DEBUG"] === "true") {
760
+ logger.debug("Runner activated as primary", {
761
+ runnerUid: runnerUid,
762
+ lastProcessedAt: lastProcessedAt,
763
+ orchestratorUrl: this.runner.config_.orchestratorUrl,
764
+ });
765
+ }
766
+
767
+ // Emit activation notification - wrap in try/catch to handle failures gracefully
768
+ try {
769
+ await this.runner.notify("runner.activate", {
770
+ runnerId: this.runner.getRunnerId(),
771
+ runnerUid: runnerUid,
772
+ });
773
+ } catch (error) {
774
+ console.error("Failed to send activation notification:", error);
775
+ if (process.env["DEBUG"] === "true") {
776
+ logger.debug("Activation notification failed", {
777
+ error: error instanceof Error ? error.message : String(error),
778
+ });
779
+ }
780
+ }
781
+
782
+ // Start processing messages from the lastProcessedAt point
783
+ console.log(
784
+ `MessageHandler: Will process messages after ${
785
+ lastProcessedAt || "beginning"
786
+ }`
787
+ );
788
+ } else {
789
+ // Different UID - check if this is an old UID change that we should ignore
790
+ const currentLastProcessedAt = this.runner.getLastProcessedAt();
791
+ if (currentLastProcessedAt && lastProcessedAt) {
792
+ const newTime = new Date(lastProcessedAt);
793
+ if (newTime < currentLastProcessedAt) {
794
+ console.log(
795
+ `MessageHandler: Ignoring old UID change (${lastProcessedAt} < ${currentLastProcessedAt.toISOString()})`
796
+ );
797
+ if (process.env["DEBUG"] === "true") {
798
+ logger.debug("Ignoring old UID change", {
799
+ newUid: runnerUid,
800
+ newLastProcessedAt: lastProcessedAt,
801
+ currentLastProcessedAt: currentLastProcessedAt.toISOString(),
802
+ });
803
+ }
804
+ return;
805
+ }
806
+ }
807
+
808
+ // Different UID - we're being replaced
809
+ console.log(
810
+ `MessageHandler: We are being replaced by runner with UID ${runnerUid}`
811
+ );
812
+ this.runner.setIsActiveRunner(false);
813
+
814
+ // Remember which conversations were active before handoff (by conversationId)
815
+ for (const [conversationId, context] of this.runner
816
+ .activeConversations_) {
817
+ if (context.status === "active") {
818
+ this.runner.getPreHandoffConversations().add(conversationId);
819
+ }
820
+ }
821
+
822
+ if (process.env["DEBUG"] === "true") {
823
+ logger.debug("Runner deactivated - being replaced", {
824
+ newRunnerUid: runnerUid,
825
+ ourUid: this.runner.getRunnerUid(),
826
+ preHandoffConversations: Array.from(
827
+ this.runner.getPreHandoffConversations()
828
+ ),
829
+ activeConversationsCount:
830
+ this.runner.getPreHandoffConversations().size,
831
+ });
832
+ }
833
+
834
+ console.log(
835
+ `MessageHandler: Will complete ${
836
+ this.runner.getPreHandoffConversations().size
837
+ } active conversations`
838
+ );
839
+
840
+ // Emit deactivation notification - wrap in try/catch to handle failures gracefully
841
+ try {
842
+ await this.runner.notify("runner.deactivate", {
843
+ runnerId: this.runner.getRunnerId(),
844
+ runnerUid: this.runner.getRunnerUid(),
845
+ activeConversations: this.runner.getPreHandoffConversations().size,
846
+ });
847
+ } catch (error) {
848
+ console.error("Failed to send deactivation notification:", error);
849
+ if (process.env["DEBUG"] === "true") {
850
+ logger.debug("Deactivation notification failed", {
851
+ error: error instanceof Error ? error.message : String(error),
852
+ });
853
+ }
854
+ }
855
+ }
856
+ }
857
+
858
+ private async handleGitOperation(
859
+ params: any,
860
+ message: RunnerMessage
861
+ ): Promise<void> {
862
+ const { taskId, operation, params: opParams } = params;
863
+
864
+ if (!taskId || !operation) {
865
+ throw new Error("Missing required parameters: taskId and operation");
866
+ }
867
+
868
+ console.log(
869
+ `MessageHandler: Handling Git operation ${operation} for task ${taskId}`
870
+ );
871
+
872
+ const repoManager = this.runner.repositoryManager_;
873
+
874
+ try {
875
+ switch (operation) {
876
+ case "stage":
877
+ await repoManager.stageAll(taskId);
878
+ await this.sendGitStateUpdate(taskId);
879
+ break;
880
+
881
+ case "commit":
882
+ if (!opParams?.message) {
883
+ throw new Error("Commit message is required");
884
+ }
885
+ const commitHash = await repoManager.commit(
886
+ taskId,
887
+ opParams.message,
888
+ opParams.author
889
+ );
890
+ await this.recordGitOperation(taskId, "commit", "succeeded", {
891
+ commitHash,
892
+ });
893
+ await this.sendGitStateUpdate(taskId);
894
+ break;
895
+
896
+ case "push":
897
+ // TODO: Implement push operation
898
+ console.log("Push operation not yet implemented");
899
+ break;
900
+
901
+ case "rebase":
902
+ if (!opParams?.targetBranch) {
903
+ throw new Error("Target branch is required for rebase");
904
+ }
905
+ const rebaseResult = await repoManager.rebaseTask(
906
+ taskId,
907
+ opParams.targetBranch
908
+ );
909
+ await this.recordGitOperation(
910
+ taskId,
911
+ "rebase",
912
+ rebaseResult.success ? "succeeded" : "failed",
913
+ rebaseResult
914
+ );
915
+ await this.sendGitStateUpdate(taskId);
916
+ break;
917
+
918
+ case "merge":
919
+ if (!opParams?.targetBranch) {
920
+ throw new Error("Target branch is required for merge");
921
+ }
922
+ const mergeResult = await repoManager.mergeTask(
923
+ taskId,
924
+ opParams.targetBranch,
925
+ opParams.mode
926
+ );
927
+ await this.recordGitOperation(
928
+ taskId,
929
+ "merge",
930
+ mergeResult.success ? "succeeded" : "failed",
931
+ mergeResult
932
+ );
933
+ await this.sendGitStateUpdate(taskId);
934
+ break;
935
+
936
+ default:
937
+ throw new Error(`Unknown Git operation: ${operation}`);
938
+ }
939
+ } catch (error) {
940
+ console.error(
941
+ `Git operation ${operation} failed for task ${taskId}:`,
942
+ error
943
+ );
944
+ await this.recordGitOperation(taskId, operation, "failed", {
945
+ error: error instanceof Error ? error.message : String(error),
946
+ });
947
+ throw error;
948
+ }
949
+ }
950
+
951
+ private async handleGitCleanup(
952
+ params: any,
953
+ message: RunnerMessage
954
+ ): Promise<void> {
955
+ const { taskId, preserveBranch = false } = params;
956
+
957
+ if (!taskId) {
958
+ throw new Error("Missing required parameter: taskId");
959
+ }
960
+
961
+ console.log(`MessageHandler: Cleaning up Git worktree for task ${taskId}`);
962
+
963
+ const repoManager = this.runner.repositoryManager_;
964
+
965
+ try {
966
+ await repoManager.removeTaskWorktree(taskId, { preserveBranch });
967
+ console.log(`Successfully cleaned up worktree for task ${taskId}`);
968
+ } catch (error) {
969
+ console.error(`Failed to clean up worktree for task ${taskId}:`, error);
970
+ throw error;
971
+ }
972
+ }
973
+
974
+ private async sendGitStateUpdate(taskId: string): Promise<void> {
975
+ const repoManager = this.runner.repositoryManager_;
976
+ const gitState = await repoManager.getTaskState(taskId);
977
+
978
+ if (!gitState) {
979
+ console.error(`No Git state found for task ${taskId}`);
980
+ return;
981
+ }
982
+
983
+ // Send state update to orchestrator
984
+ await this.runner.notify("git.state.update", {
985
+ taskId,
986
+ state: {
987
+ branch: gitState.branch,
988
+ commit: gitState.lastCommit || "",
989
+ isDirty: false, // TODO: Check actual dirty state
990
+ ahead: 0, // TODO: Calculate ahead/behind
991
+ behind: 0,
992
+ },
993
+ });
994
+ }
995
+
996
+ private async recordGitOperation(
997
+ taskId: string,
998
+ operation: string,
999
+ status: string,
1000
+ details: any
1001
+ ): Promise<void> {
1002
+ // Send operation record to orchestrator
1003
+ await this.runner.notify("git.operation.record", {
1004
+ taskId,
1005
+ operation,
1006
+ status,
1007
+ details,
1008
+ timestamp: new Date(),
1009
+ });
1010
+ }
1011
+ }