@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,734 @@
1
+ "use strict";
2
+ /**
3
+ * MessageHandler - Processes incoming JSONRPC messages from SSE events
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.MessageHandler = void 0;
7
+ const SSEClient_1 = require("../services/SSEClient");
8
+ const RunnerAPIClient_1 = require("../services/RunnerAPIClient");
9
+ const status_line_1 = require("../utils/status-line");
10
+ const console_1 = require("../utils/console");
11
+ const logger_1 = require("../utils/logger");
12
+ const logger = (0, logger_1.createLogger)("MessageHandler");
13
+ class MessageHandler {
14
+ methodHandlers;
15
+ runner;
16
+ processedMessages = new Set();
17
+ sseClient = null;
18
+ apiClient;
19
+ isProcessing = false;
20
+ constructor(runner) {
21
+ this.runner = runner;
22
+ this.methodHandlers = new Map();
23
+ this.apiClient = new RunnerAPIClient_1.RunnerAPIClient(runner.config_);
24
+ this.registerHandlers();
25
+ }
26
+ async startProcessing() {
27
+ console_1.console.log("MessageHandler: Starting message processing with SSE...");
28
+ if (this.isProcessing) {
29
+ logger.warn("Message processing already started");
30
+ return;
31
+ }
32
+ this.isProcessing = true;
33
+ // Update API client with runner ID if available
34
+ const runnerId = this.runner.getRunnerId();
35
+ if (runnerId) {
36
+ this.apiClient.setRunnerId(runnerId);
37
+ }
38
+ // Catch up on missed messages first
39
+ await this.catchUpMissedMessages();
40
+ // Start SSE connection
41
+ await this.connectSSE();
42
+ }
43
+ async stopProcessing() {
44
+ console_1.console.log("MessageHandler: Stopping message processing...");
45
+ this.isProcessing = false;
46
+ // Stop SSE client
47
+ if (this.sseClient) {
48
+ this.sseClient.stop();
49
+ this.sseClient = null;
50
+ }
51
+ // Clear processed messages tracking
52
+ this.processedMessages.clear();
53
+ }
54
+ /**
55
+ * Catch up on missed messages since lastProcessedAt
56
+ */
57
+ async catchUpMissedMessages() {
58
+ const lastProcessedAt = this.runner.getLastProcessedAt();
59
+ if (!lastProcessedAt) {
60
+ logger.debug("No lastProcessedAt timestamp, skipping catch-up");
61
+ return;
62
+ }
63
+ console_1.console.log(`MessageHandler: Catching up on messages since ${lastProcessedAt.toISOString()}`);
64
+ try {
65
+ const messages = await this.apiClient.fetchMissedMessages({
66
+ since: lastProcessedAt,
67
+ limit: 1000,
68
+ });
69
+ if (messages.length > 0) {
70
+ console_1.console.log(`MessageHandler: Processing ${messages.length} missed messages`);
71
+ // Process messages in order
72
+ for (const message of messages) {
73
+ await this.processMessage(message);
74
+ }
75
+ }
76
+ else {
77
+ console_1.console.log("MessageHandler: No missed messages to process");
78
+ }
79
+ }
80
+ catch (error) {
81
+ logger.error("Failed to catch up on missed messages:", error);
82
+ // Continue anyway - SSE connection might still work
83
+ }
84
+ }
85
+ /**
86
+ * Connect to SSE endpoint
87
+ */
88
+ async connectSSE() {
89
+ const runnerId = this.runner.getRunnerId();
90
+ if (!runnerId) {
91
+ throw new Error("Cannot connect to SSE without runner ID");
92
+ }
93
+ const token = process.env["NORTHFLARE_RUNNER_TOKEN"];
94
+ if (!token) {
95
+ throw new Error("Missing NORTHFLARE_RUNNER_TOKEN");
96
+ }
97
+ console_1.console.log("MessageHandler: Connecting to SSE endpoint...");
98
+ this.sseClient = new SSEClient_1.SSEClient({
99
+ url: `${this.runner.config_.orchestratorUrl}/api/runner-events`,
100
+ runnerId,
101
+ token,
102
+ onMessage: this.handleSSEEvent.bind(this),
103
+ onError: (error) => {
104
+ logger.error("SSE connection error:", error);
105
+ },
106
+ onConnect: () => {
107
+ console_1.console.log("MessageHandler: SSE connection established");
108
+ },
109
+ onDisconnect: () => {
110
+ console_1.console.log("MessageHandler: SSE connection closed");
111
+ },
112
+ reconnectInterval: 1000,
113
+ maxReconnectInterval: 30000,
114
+ reconnectMultiplier: 2,
115
+ });
116
+ // Connect with lastProcessedAt for server-side filtering
117
+ const lastProcessedAt = this.runner.getLastProcessedAt();
118
+ await this.sseClient.connect(lastProcessedAt?.toISOString());
119
+ }
120
+ /**
121
+ * Handle SSE event
122
+ */
123
+ async handleSSEEvent(event) {
124
+ if (event.type === "runner.message") {
125
+ const message = event.data;
126
+ if (process.env["DEBUG"] === "true") {
127
+ logger.debug("Received SSE event", {
128
+ eventId: event.id,
129
+ type: event.type,
130
+ messageId: message?.id,
131
+ method: message?.payload?.method,
132
+ createdAt: message?.createdAt,
133
+ });
134
+ }
135
+ try {
136
+ // Process the message
137
+ await this.processMessage(message);
138
+ }
139
+ catch (err) {
140
+ const msg = err instanceof Error ? err.message : String(err);
141
+ logger.error("Failed to process runner.message:", msg);
142
+ // Do not crash the runner on a single bad message
143
+ return;
144
+ }
145
+ }
146
+ else if (event.type === "connection.established") {
147
+ logger.debug("SSE connection established", event.data);
148
+ }
149
+ else {
150
+ logger.debug(`Received event type: ${event.type}`, event.data);
151
+ }
152
+ }
153
+ async processMessage(message) {
154
+ if (process.env["DEBUG"] === "true") {
155
+ logger.debug("processMessage called", {
156
+ messageId: message.id,
157
+ method: message.payload?.method,
158
+ direction: message.direction,
159
+ createdAt: message.createdAt,
160
+ });
161
+ }
162
+ // Skip if already processed
163
+ if (this.processedMessages.has(message.id)) {
164
+ return;
165
+ }
166
+ // Check if we should process this message based on ownership
167
+ if (!this.shouldProcessMessage(message)) {
168
+ return;
169
+ }
170
+ const { method, params } = message.payload;
171
+ if (!method) {
172
+ await this.sendError(message, "Missing method in message payload");
173
+ return;
174
+ }
175
+ const handler = this.methodHandlers.get(method);
176
+ if (!handler) {
177
+ await this.sendError(message, `Unknown method: ${method}`);
178
+ return;
179
+ }
180
+ if (process.env["DEBUG"] === "true") {
181
+ logger.debug("Processing message", {
182
+ messageId: message.id,
183
+ method: method,
184
+ taskId: message.taskId,
185
+ isActionMessage: this.isActionMessage(message),
186
+ });
187
+ }
188
+ try {
189
+ await handler(params, message);
190
+ await this.markProcessed(message);
191
+ // Acknowledge ALL messages to update lastProcessedAt
192
+ await this.acknowledgeMessage(message);
193
+ if (process.env["DEBUG"] === "true") {
194
+ logger.debug("Message acknowledged", {
195
+ messageId: message.id,
196
+ method: method,
197
+ timestamp: message.createdAt,
198
+ wasActionMessage: this.isActionMessage(message),
199
+ });
200
+ }
201
+ }
202
+ catch (error) {
203
+ if (process.env["DEBUG"] === "true") {
204
+ logger.debug("Message processing error", {
205
+ messageId: message.id,
206
+ method: method,
207
+ error: error instanceof Error ? error.message : String(error),
208
+ });
209
+ }
210
+ await this.handleError(message, error);
211
+ }
212
+ }
213
+ shouldProcessMessage(message) {
214
+ const decision = (() => {
215
+ // Always process our own responses going to orchestrator
216
+ if (message.direction === "to_orchestrator") {
217
+ return { shouldProcess: true, reason: "own response to orchestrator" };
218
+ }
219
+ // Filter by lastProcessedAt first (before checking active status)
220
+ const lastProcessedAt = this.runner.getLastProcessedAt();
221
+ if (lastProcessedAt && message.createdAt) {
222
+ const messageTime = new Date(message.createdAt);
223
+ if (messageTime <= lastProcessedAt) {
224
+ return {
225
+ shouldProcess: false,
226
+ reason: "message before lastProcessedAt",
227
+ };
228
+ }
229
+ }
230
+ // Always process UID change messages (after time check)
231
+ if (message.payload?.method === "runner.uid.changed") {
232
+ return { shouldProcess: true, reason: "UID change message" };
233
+ }
234
+ // If we're not the active runner
235
+ if (!this.runner.getIsActiveRunner()) {
236
+ // Only process if it's for a pre-handoff conversation by conversationId
237
+ const cid = message.conversationId || message.payload?.params?.conversationId;
238
+ if (cid && this.runner.getPreHandoffConversations().has(cid)) {
239
+ return {
240
+ shouldProcess: true,
241
+ reason: "pre-handoff conversation (by conversationId)",
242
+ };
243
+ }
244
+ return { shouldProcess: false, reason: "not active runner" };
245
+ }
246
+ // We're active and message is after lastProcessedAt
247
+ return {
248
+ shouldProcess: true,
249
+ reason: "active runner, message after watermark",
250
+ };
251
+ })();
252
+ if (process.env["DEBUG"] === "true") {
253
+ logger.debug("Message processing decision", {
254
+ messageId: message.id,
255
+ method: message.payload?.method,
256
+ shouldProcess: decision.shouldProcess,
257
+ reason: decision.reason,
258
+ runnerUid: this.runner.getRunnerUid(),
259
+ isActiveRunner: this.runner.getIsActiveRunner(),
260
+ lastProcessedAt: this.runner.getLastProcessedAt()?.toISOString() || "null",
261
+ messageCreatedAt: message.createdAt,
262
+ });
263
+ }
264
+ return decision.shouldProcess;
265
+ }
266
+ isActionMessage(message) {
267
+ const actionMethods = [
268
+ "conversation.start",
269
+ "conversation.stop",
270
+ "conversation.resume",
271
+ "conversation.config",
272
+ "message.user",
273
+ ];
274
+ return actionMethods.includes(message.payload?.method || "");
275
+ }
276
+ async acknowledgeMessage(message) {
277
+ const runnerId = this.runner.getRunnerId();
278
+ console_1.console.log(`[MessageHandler] Sending message.acknowledge:`, {
279
+ runnerId,
280
+ messageTimestamp: message.createdAt,
281
+ messageId: message.id,
282
+ method: message.payload?.method,
283
+ });
284
+ try {
285
+ await this.apiClient.acknowledgeMessage(message.createdAt);
286
+ // Update local lastProcessedAt
287
+ await this.runner.updateLastProcessedAt(new Date(message.createdAt));
288
+ console_1.console.log(`[MessageHandler] ✅ message.acknowledge sent successfully`);
289
+ }
290
+ catch (error) {
291
+ logger.error("Failed to acknowledge message:", error);
292
+ // Continue processing even if acknowledgment fails
293
+ }
294
+ }
295
+ async markProcessed(message) {
296
+ // Track processed messages internally
297
+ this.processedMessages.add(message.id);
298
+ }
299
+ async sendError(message, errorMessage) {
300
+ // Send error report with conversation object info if available
301
+ const conversationObjectType = message.conversationObjectType || (message.taskId ? "Task" : undefined);
302
+ const conversationObjectId = message.conversationObjectId || message.taskId;
303
+ if (!conversationObjectId) {
304
+ console_1.console.error(`[MessageHandler] Cannot send error report - no conversationObjectId available. Error: ${errorMessage}`);
305
+ if (process.env["DEBUG"] === "true") {
306
+ logger.debug("Error without conversationObjectId", {
307
+ messageId: message.id,
308
+ method: message.payload?.method,
309
+ error: errorMessage,
310
+ runnerId: message.runnerId,
311
+ });
312
+ }
313
+ return;
314
+ }
315
+ await this.runner.notify("error.report", {
316
+ conversationObjectType,
317
+ conversationObjectId,
318
+ messageId: message.id,
319
+ errorType: "method_error",
320
+ message: errorMessage,
321
+ details: {
322
+ originalMessage: message,
323
+ timestamp: new Date(),
324
+ },
325
+ });
326
+ }
327
+ async handleError(message, error) {
328
+ const errorMessage = error instanceof Error ? error.message : String(error);
329
+ const errorStack = error instanceof Error ? error.stack : undefined;
330
+ // Send error report with conversation object info if available
331
+ const conversationObjectType = message.conversationObjectType || (message.taskId ? "Task" : undefined);
332
+ const conversationObjectId = message.conversationObjectId || message.taskId;
333
+ if (!conversationObjectId) {
334
+ console_1.console.error(`[MessageHandler] Cannot send error report - no conversationObjectId available. Processing error: ${errorMessage}`);
335
+ if (process.env["DEBUG"] === "true") {
336
+ logger.debug("Processing error without conversationObjectId", {
337
+ messageId: message.id,
338
+ method: message.payload?.method,
339
+ error: errorMessage,
340
+ stack: errorStack,
341
+ runnerId: message.runnerId,
342
+ });
343
+ }
344
+ return;
345
+ }
346
+ await this.runner.notify("error.report", {
347
+ conversationObjectType,
348
+ conversationObjectId,
349
+ messageId: message.id,
350
+ errorType: "processing_error",
351
+ message: errorMessage,
352
+ details: {
353
+ stack: errorStack,
354
+ originalMessage: message,
355
+ timestamp: new Date(),
356
+ },
357
+ });
358
+ }
359
+ registerHandlers() {
360
+ console_1.console.log("MessageHandler: Registering handlers...");
361
+ this.methodHandlers = new Map([
362
+ ["conversation.start", this.handleConversationStart.bind(this)],
363
+ ["conversation.stop", this.handleConversationStop.bind(this)],
364
+ ["conversation.resume", this.handleConversationResume.bind(this)],
365
+ ["conversation.config", this.handleConversationConfig.bind(this)],
366
+ ["message.user", this.handleUserMessage.bind(this)],
367
+ ["runner.uid.changed", this.handleUidChanged.bind(this)],
368
+ ["git.operation", this.handleGitOperation.bind(this)],
369
+ ["git.cleanup", this.handleGitCleanup.bind(this)],
370
+ ]);
371
+ }
372
+ // All the handler methods remain the same as in the original file
373
+ // Just copy them from the original message-handler.ts starting from line 386
374
+ async handleConversationStart(params, message) {
375
+ const { conversationObjectType = message.conversationObjectType || "Task", conversationObjectId = message.conversationObjectId ||
376
+ params.conversation?.objectId, config, initialMessages, conversation, } = params;
377
+ // Validate required parameters
378
+ if (!config) {
379
+ throw new Error("Missing required parameter: config");
380
+ }
381
+ // Require a conversation object
382
+ const conversationData = conversation;
383
+ if (!conversationData) {
384
+ throw new Error("Missing required parameter: conversation object must be provided");
385
+ }
386
+ const finalObjectType = conversationObjectType || conversationData.objectType;
387
+ const finalObjectId = conversationObjectId || conversationData.objectId;
388
+ if (!finalObjectId) {
389
+ throw new Error("Missing conversationObjectId");
390
+ }
391
+ // Debug log the config
392
+ console_1.console.log(`[MessageHandler] conversation.start config:`, {
393
+ conversationObjectId,
394
+ hasConfig: !!config,
395
+ hasRepository: !!config?.repository,
396
+ repositoryType: config?.repository?.type,
397
+ repositoryUrl: config?.repository?.url,
398
+ workspaceId: config?.workspaceId,
399
+ fullConfig: JSON.stringify(config, null, 2),
400
+ });
401
+ // Start the conversation with the provided/loaded conversation details
402
+ await this.runner.claudeManager_.startConversation(finalObjectType, finalObjectId, config, initialMessages || [], conversationData);
403
+ // Update status line
404
+ status_line_1.statusLineManager.updateActiveCount(this.runner.activeConversations_.size);
405
+ }
406
+ async handleConversationStop(params, message) {
407
+ // Require conversationId (present at message level); do not fall back to agentSessionId/taskId
408
+ const { conversationId = message.conversationId, reason } = params;
409
+ console_1.console.log(`[MessageHandler] handleConversationStop called with:`, {
410
+ conversationId,
411
+ messageConversationId: message.conversationId,
412
+ agentSessionId: params?.agentSessionId,
413
+ taskId: params?.taskId,
414
+ params: JSON.stringify(params),
415
+ activeConversations: this.runner.activeConversations_.size,
416
+ conversationIds: Array.from(this.runner.activeConversations_.keys()),
417
+ });
418
+ // Lookup strictly by conversationId
419
+ let context;
420
+ let targetConversationId;
421
+ if (conversationId) {
422
+ context = this.runner.getConversationContext(conversationId);
423
+ targetConversationId = conversationId;
424
+ }
425
+ console_1.console.log(`[MessageHandler] handleConversationStop lookup result:`, {
426
+ contextFound: !!context,
427
+ targetConversationId,
428
+ contextTaskId: context?.taskId,
429
+ contextAgentSessionId: context?.agentSessionId,
430
+ });
431
+ // Check if we have any identifier to work with
432
+ if (!conversationId) {
433
+ throw new Error("Missing required parameter: conversationId");
434
+ }
435
+ if (context && targetConversationId) {
436
+ context.status = "stopping";
437
+ await this.runner.claudeManager_.stopConversation(context.agentSessionId, context, false, // Not a runner shutdown
438
+ reason // Pass the reason through
439
+ );
440
+ context.status = "stopped";
441
+ this.runner.activeConversations_.delete(targetConversationId);
442
+ // Update status line
443
+ status_line_1.statusLineManager.updateActiveCount(this.runner.activeConversations_.size);
444
+ }
445
+ else {
446
+ // No conversation found - this is expected as conversations may have already ended
447
+ // or been cleaned up. Just log it and update status line.
448
+ console_1.console.log(`Conversation stop requested for ${conversationId} - conversation not found or already cleaned up`);
449
+ // If we have a targetConversationId, ensure it's removed from tracking
450
+ if (targetConversationId) {
451
+ this.runner.activeConversations_.delete(targetConversationId);
452
+ }
453
+ status_line_1.statusLineManager.updateActiveCount(this.runner.activeConversations_.size);
454
+ }
455
+ }
456
+ async handleConversationResume(params, message) {
457
+ const { conversationId = message.conversationId, conversation: resumeConversation, config, message: resumeMessage, } = params;
458
+ const cid = params.conversationId || conversationId;
459
+ if (!cid) {
460
+ throw new Error("Missing required parameter: conversationId");
461
+ }
462
+ // Require conversation details
463
+ const conversationData = resumeConversation;
464
+ if (!conversationData) {
465
+ throw new Error("Missing required parameter: conversation object must be provided");
466
+ }
467
+ const agentSessionId = conversationData.agentSessionId;
468
+ if (!agentSessionId) {
469
+ throw new Error("Cannot resume conversation without agentSessionId");
470
+ }
471
+ await this.runner.claudeManager_.resumeConversation(conversationData.objectType, conversationData.objectId, agentSessionId, config, conversationData, resumeMessage);
472
+ }
473
+ async handleConversationConfig(params, message) {
474
+ const { conversationId, model, permissionsMode, config } = params;
475
+ console_1.console.log(`[MessageHandler] handleConversationConfig called with:`, {
476
+ conversationId,
477
+ model,
478
+ permissionsMode,
479
+ hasConfig: !!config,
480
+ });
481
+ // Find the active conversation by conversationId only
482
+ let context;
483
+ if (conversationId) {
484
+ context = this.runner.getConversationContext(conversationId);
485
+ }
486
+ if (!context) {
487
+ throw new Error(`No active conversation found for conversationId: ${conversationId}`);
488
+ }
489
+ // Validate required parameters
490
+ if (!model && !permissionsMode) {
491
+ throw new Error("At least one of model or permissionsMode must be provided");
492
+ }
493
+ // Update the config with new values
494
+ const newConfig = {
495
+ ...context.config,
496
+ ...(model && { model }),
497
+ ...(permissionsMode && { permissionsMode }),
498
+ ...config, // Allow full config overrides if provided
499
+ };
500
+ console_1.console.log(`[MessageHandler] Stopping conversation ${context.conversationId} to apply new config`);
501
+ // Stop the current conversation
502
+ await this.runner.claudeManager_.stopConversation(context.agentSessionId, context, false // Not a runner shutdown, just updating config
503
+ );
504
+ // Remove from active conversations
505
+ this.runner.activeConversations_.delete(context.conversationId);
506
+ console_1.console.log(`[MessageHandler] Resuming conversation ${context.conversationId} with new config`);
507
+ // Resume with new config
508
+ await this.runner.claudeManager_.resumeConversation(context.conversationObjectType, context.conversationObjectId, context.agentSessionId, newConfig, {
509
+ id: context.conversationId,
510
+ objectType: context.conversationObjectType,
511
+ objectId: context.conversationObjectId,
512
+ model: newConfig.model,
513
+ globalInstructions: context.globalInstructions,
514
+ workspaceInstructions: context.workspaceInstructions,
515
+ permissionsMode: newConfig.permissionsMode,
516
+ agentSessionId: context.agentSessionId,
517
+ }, "<system-instructions>Configuration updated. Please continue with the new settings.</system-instructions>");
518
+ // Update status line
519
+ status_line_1.statusLineManager.updateActiveCount(this.runner.activeConversations_.size);
520
+ console_1.console.log(`[MessageHandler] Conversation ${context.conversationId} config updated successfully`);
521
+ }
522
+ async handleUserMessage(params, message) {
523
+ const { conversationId, content, config, conversationObjectType = message.conversationObjectType || "Task", conversationObjectId = message.conversationObjectId, conversation, } = params;
524
+ // Validate required parameters
525
+ if (!conversationId) {
526
+ throw new Error("Missing required parameter: conversationId");
527
+ }
528
+ if (!content) {
529
+ throw new Error("Missing required parameter: content");
530
+ }
531
+ await this.runner.claudeManager_.sendUserMessage(conversationId, content, config, conversationObjectType, conversationObjectId, conversation);
532
+ }
533
+ async handleUidChanged(params, _message) {
534
+ const { runnerUid, lastProcessedAt } = params;
535
+ console_1.console.log(`MessageHandler: Handling UID change notification - new UID: ${runnerUid}, lastProcessedAt: ${lastProcessedAt}`);
536
+ if (process.env["DEBUG"] === "true") {
537
+ logger.debug("UID change notification received", {
538
+ newUid: runnerUid,
539
+ currentUid: this.runner.getRunnerUid(),
540
+ newLastProcessedAt: lastProcessedAt,
541
+ currentLastProcessedAt: this.runner.getLastProcessedAt()?.toISOString() || "null",
542
+ wasActiveRunner: this.runner.getIsActiveRunner(),
543
+ activeConversations: this.runner.activeConversations_.size,
544
+ });
545
+ }
546
+ // Check if the UID matches ours FIRST, before checking timestamps
547
+ // This ensures we activate even if we received the message during catch-up
548
+ if (runnerUid === this.runner.getRunnerUid()) {
549
+ // This is our UID - we're the active runner
550
+ console_1.console.log("MessageHandler: We are now the active runner");
551
+ this.runner.setIsActiveRunner(true);
552
+ await this.runner.updateLastProcessedAt(lastProcessedAt ? new Date(lastProcessedAt) : null);
553
+ if (process.env["DEBUG"] === "true") {
554
+ logger.debug("Runner activated as primary", {
555
+ runnerUid: runnerUid,
556
+ lastProcessedAt: lastProcessedAt,
557
+ orchestratorUrl: this.runner.config_.orchestratorUrl,
558
+ });
559
+ }
560
+ // Emit activation notification - wrap in try/catch to handle failures gracefully
561
+ try {
562
+ await this.runner.notify("runner.activate", {
563
+ runnerId: this.runner.getRunnerId(),
564
+ runnerUid: runnerUid,
565
+ });
566
+ }
567
+ catch (error) {
568
+ console_1.console.error("Failed to send activation notification:", error);
569
+ if (process.env["DEBUG"] === "true") {
570
+ logger.debug("Activation notification failed", {
571
+ error: error instanceof Error ? error.message : String(error),
572
+ });
573
+ }
574
+ }
575
+ // Start processing messages from the lastProcessedAt point
576
+ console_1.console.log(`MessageHandler: Will process messages after ${lastProcessedAt || "beginning"}`);
577
+ }
578
+ else {
579
+ // Different UID - check if this is an old UID change that we should ignore
580
+ const currentLastProcessedAt = this.runner.getLastProcessedAt();
581
+ if (currentLastProcessedAt && lastProcessedAt) {
582
+ const newTime = new Date(lastProcessedAt);
583
+ if (newTime < currentLastProcessedAt) {
584
+ console_1.console.log(`MessageHandler: Ignoring old UID change (${lastProcessedAt} < ${currentLastProcessedAt.toISOString()})`);
585
+ if (process.env["DEBUG"] === "true") {
586
+ logger.debug("Ignoring old UID change", {
587
+ newUid: runnerUid,
588
+ newLastProcessedAt: lastProcessedAt,
589
+ currentLastProcessedAt: currentLastProcessedAt.toISOString(),
590
+ });
591
+ }
592
+ return;
593
+ }
594
+ }
595
+ // Different UID - we're being replaced
596
+ console_1.console.log(`MessageHandler: We are being replaced by runner with UID ${runnerUid}`);
597
+ this.runner.setIsActiveRunner(false);
598
+ // Remember which conversations were active before handoff (by conversationId)
599
+ for (const [conversationId, context] of this.runner
600
+ .activeConversations_) {
601
+ if (context.status === "active") {
602
+ this.runner.getPreHandoffConversations().add(conversationId);
603
+ }
604
+ }
605
+ if (process.env["DEBUG"] === "true") {
606
+ logger.debug("Runner deactivated - being replaced", {
607
+ newRunnerUid: runnerUid,
608
+ ourUid: this.runner.getRunnerUid(),
609
+ preHandoffConversations: Array.from(this.runner.getPreHandoffConversations()),
610
+ activeConversationsCount: this.runner.getPreHandoffConversations().size,
611
+ });
612
+ }
613
+ console_1.console.log(`MessageHandler: Will complete ${this.runner.getPreHandoffConversations().size} active conversations`);
614
+ // Emit deactivation notification - wrap in try/catch to handle failures gracefully
615
+ try {
616
+ await this.runner.notify("runner.deactivate", {
617
+ runnerId: this.runner.getRunnerId(),
618
+ runnerUid: this.runner.getRunnerUid(),
619
+ activeConversations: this.runner.getPreHandoffConversations().size,
620
+ });
621
+ }
622
+ catch (error) {
623
+ console_1.console.error("Failed to send deactivation notification:", error);
624
+ if (process.env["DEBUG"] === "true") {
625
+ logger.debug("Deactivation notification failed", {
626
+ error: error instanceof Error ? error.message : String(error),
627
+ });
628
+ }
629
+ }
630
+ }
631
+ }
632
+ async handleGitOperation(params, message) {
633
+ const { taskId, operation, params: opParams } = params;
634
+ if (!taskId || !operation) {
635
+ throw new Error("Missing required parameters: taskId and operation");
636
+ }
637
+ console_1.console.log(`MessageHandler: Handling Git operation ${operation} for task ${taskId}`);
638
+ const repoManager = this.runner.repositoryManager_;
639
+ try {
640
+ switch (operation) {
641
+ case "stage":
642
+ await repoManager.stageAll(taskId);
643
+ await this.sendGitStateUpdate(taskId);
644
+ break;
645
+ case "commit":
646
+ if (!opParams?.message) {
647
+ throw new Error("Commit message is required");
648
+ }
649
+ const commitHash = await repoManager.commit(taskId, opParams.message, opParams.author);
650
+ await this.recordGitOperation(taskId, "commit", "succeeded", {
651
+ commitHash,
652
+ });
653
+ await this.sendGitStateUpdate(taskId);
654
+ break;
655
+ case "push":
656
+ // TODO: Implement push operation
657
+ console_1.console.log("Push operation not yet implemented");
658
+ break;
659
+ case "rebase":
660
+ if (!opParams?.targetBranch) {
661
+ throw new Error("Target branch is required for rebase");
662
+ }
663
+ const rebaseResult = await repoManager.rebaseTask(taskId, opParams.targetBranch);
664
+ await this.recordGitOperation(taskId, "rebase", rebaseResult.success ? "succeeded" : "failed", rebaseResult);
665
+ await this.sendGitStateUpdate(taskId);
666
+ break;
667
+ case "merge":
668
+ if (!opParams?.targetBranch) {
669
+ throw new Error("Target branch is required for merge");
670
+ }
671
+ const mergeResult = await repoManager.mergeTask(taskId, opParams.targetBranch, opParams.mode);
672
+ await this.recordGitOperation(taskId, "merge", mergeResult.success ? "succeeded" : "failed", mergeResult);
673
+ await this.sendGitStateUpdate(taskId);
674
+ break;
675
+ default:
676
+ throw new Error(`Unknown Git operation: ${operation}`);
677
+ }
678
+ }
679
+ catch (error) {
680
+ console_1.console.error(`Git operation ${operation} failed for task ${taskId}:`, error);
681
+ await this.recordGitOperation(taskId, operation, "failed", {
682
+ error: error instanceof Error ? error.message : String(error),
683
+ });
684
+ throw error;
685
+ }
686
+ }
687
+ async handleGitCleanup(params, message) {
688
+ const { taskId, preserveBranch = false } = params;
689
+ if (!taskId) {
690
+ throw new Error("Missing required parameter: taskId");
691
+ }
692
+ console_1.console.log(`MessageHandler: Cleaning up Git worktree for task ${taskId}`);
693
+ const repoManager = this.runner.repositoryManager_;
694
+ try {
695
+ await repoManager.removeTaskWorktree(taskId, { preserveBranch });
696
+ console_1.console.log(`Successfully cleaned up worktree for task ${taskId}`);
697
+ }
698
+ catch (error) {
699
+ console_1.console.error(`Failed to clean up worktree for task ${taskId}:`, error);
700
+ throw error;
701
+ }
702
+ }
703
+ async sendGitStateUpdate(taskId) {
704
+ const repoManager = this.runner.repositoryManager_;
705
+ const gitState = await repoManager.getTaskState(taskId);
706
+ if (!gitState) {
707
+ console_1.console.error(`No Git state found for task ${taskId}`);
708
+ return;
709
+ }
710
+ // Send state update to orchestrator
711
+ await this.runner.notify("git.state.update", {
712
+ taskId,
713
+ state: {
714
+ branch: gitState.branch,
715
+ commit: gitState.lastCommit || "",
716
+ isDirty: false, // TODO: Check actual dirty state
717
+ ahead: 0, // TODO: Calculate ahead/behind
718
+ behind: 0,
719
+ },
720
+ });
721
+ }
722
+ async recordGitOperation(taskId, operation, status, details) {
723
+ // Send operation record to orchestrator
724
+ await this.runner.notify("git.operation.record", {
725
+ taskId,
726
+ operation,
727
+ status,
728
+ details,
729
+ timestamp: new Date(),
730
+ });
731
+ }
732
+ }
733
+ exports.MessageHandler = MessageHandler;
734
+ //# sourceMappingURL=message-handler-sse.js.map