@zhigang1992/happy-cli 0.12.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 (47) hide show
  1. package/README.md +60 -0
  2. package/bin/happy-mcp.mjs +32 -0
  3. package/bin/happy.mjs +35 -0
  4. package/dist/codex/happyMcpStdioBridge.cjs +80 -0
  5. package/dist/codex/happyMcpStdioBridge.d.cts +2 -0
  6. package/dist/codex/happyMcpStdioBridge.d.mts +2 -0
  7. package/dist/codex/happyMcpStdioBridge.mjs +78 -0
  8. package/dist/index-BOBrKhX5.cjs +6655 -0
  9. package/dist/index-DsHtmQqP.mjs +6624 -0
  10. package/dist/index.cjs +42 -0
  11. package/dist/index.d.cts +1 -0
  12. package/dist/index.d.mts +1 -0
  13. package/dist/index.mjs +39 -0
  14. package/dist/lib.cjs +31 -0
  15. package/dist/lib.d.cts +817 -0
  16. package/dist/lib.d.mts +817 -0
  17. package/dist/lib.mjs +21 -0
  18. package/dist/list-BW6QBLa1.cjs +328 -0
  19. package/dist/list-hET5tyMc.mjs +326 -0
  20. package/dist/prompt-DXkgjktW.cjs +203 -0
  21. package/dist/prompt-Dz7G8yGx.mjs +201 -0
  22. package/dist/runCodex-CLGYMNs2.mjs +1335 -0
  23. package/dist/runCodex-CylcX5Ug.cjs +1338 -0
  24. package/dist/types-BsjUgWOx.cjs +2264 -0
  25. package/dist/types-CGco5Y-r.mjs +2213 -0
  26. package/package.json +126 -0
  27. package/scripts/claude_local_launcher.cjs +98 -0
  28. package/scripts/claude_remote_launcher.cjs +13 -0
  29. package/scripts/ripgrep_launcher.cjs +33 -0
  30. package/scripts/unpack-tools.cjs +163 -0
  31. package/tools/archives/difftastic-LICENSE +21 -0
  32. package/tools/archives/difftastic-arm64-darwin.tar.gz +0 -0
  33. package/tools/archives/difftastic-arm64-linux.tar.gz +0 -0
  34. package/tools/archives/difftastic-x64-darwin.tar.gz +0 -0
  35. package/tools/archives/difftastic-x64-linux.tar.gz +0 -0
  36. package/tools/archives/difftastic-x64-win32.tar.gz +0 -0
  37. package/tools/archives/ripgrep-LICENSE +3 -0
  38. package/tools/archives/ripgrep-arm64-darwin.tar.gz +0 -0
  39. package/tools/archives/ripgrep-arm64-linux.tar.gz +0 -0
  40. package/tools/archives/ripgrep-x64-darwin.tar.gz +0 -0
  41. package/tools/archives/ripgrep-x64-linux.tar.gz +0 -0
  42. package/tools/archives/ripgrep-x64-win32.tar.gz +0 -0
  43. package/tools/licenses/difftastic-LICENSE +21 -0
  44. package/tools/licenses/ripgrep-LICENSE +3 -0
  45. package/tools/unpacked/difft +0 -0
  46. package/tools/unpacked/rg +0 -0
  47. package/tools/unpacked/ripgrep.node +0 -0
@@ -0,0 +1,1338 @@
1
+ 'use strict';
2
+
3
+ var ink = require('ink');
4
+ var React = require('react');
5
+ var types = require('./types-BsjUgWOx.cjs');
6
+ var index_js = require('@modelcontextprotocol/sdk/client/index.js');
7
+ var stdio_js = require('@modelcontextprotocol/sdk/client/stdio.js');
8
+ var z = require('zod');
9
+ var types_js = require('@modelcontextprotocol/sdk/types.js');
10
+ var child_process = require('child_process');
11
+ var node_crypto = require('node:crypto');
12
+ var index = require('./index-BOBrKhX5.cjs');
13
+ var os = require('node:os');
14
+ var node_path = require('node:path');
15
+ var fs = require('node:fs');
16
+ require('axios');
17
+ require('chalk');
18
+ require('fs');
19
+ require('node:fs/promises');
20
+ require('tweetnacl');
21
+ require('node:events');
22
+ require('socket.io-client');
23
+ require('util');
24
+ require('fs/promises');
25
+ require('crypto');
26
+ require('path');
27
+ require('url');
28
+ require('os');
29
+ require('expo-server-sdk');
30
+ require('node:child_process');
31
+ require('node:readline');
32
+ require('node:url');
33
+ require('ps-list');
34
+ require('cross-spawn');
35
+ require('tmp');
36
+ require('qrcode-terminal');
37
+ require('open');
38
+ require('fastify');
39
+ require('fastify-type-provider-zod');
40
+ require('@modelcontextprotocol/sdk/server/mcp.js');
41
+ require('node:http');
42
+ require('@modelcontextprotocol/sdk/server/streamableHttp.js');
43
+ require('@stablelib/hex');
44
+ require('http');
45
+
46
+ const DEFAULT_TIMEOUT = 14 * 24 * 60 * 60 * 1e3;
47
+ function getCodexMcpCommand() {
48
+ try {
49
+ const version = child_process.execSync("codex --version", { encoding: "utf8" }).trim();
50
+ const match = version.match(/codex-cli\s+(\d+\.\d+\.\d+(?:-alpha\.\d+)?)/);
51
+ if (!match) return "mcp-server";
52
+ const versionStr = match[1];
53
+ const [major, minor, patch] = versionStr.split(/[-.]/).map(Number);
54
+ if (major > 0 || minor > 43) return "mcp-server";
55
+ if (minor === 43 && patch === 0) {
56
+ if (versionStr.includes("-alpha.")) {
57
+ const alphaNum = parseInt(versionStr.split("-alpha.")[1]);
58
+ return alphaNum >= 5 ? "mcp-server" : "mcp";
59
+ }
60
+ return "mcp-server";
61
+ }
62
+ return "mcp";
63
+ } catch (error) {
64
+ types.logger.debug("[CodexMCP] Error detecting codex version, defaulting to mcp-server:", error);
65
+ return "mcp-server";
66
+ }
67
+ }
68
+ class CodexMcpClient {
69
+ client;
70
+ transport = null;
71
+ connected = false;
72
+ sessionId = null;
73
+ conversationId = null;
74
+ handler = null;
75
+ permissionHandler = null;
76
+ constructor() {
77
+ this.client = new index_js.Client(
78
+ { name: "happy-codex-client", version: "1.0.0" },
79
+ { capabilities: { tools: {}, elicitation: {} } }
80
+ );
81
+ this.client.setNotificationHandler(z.z.object({
82
+ method: z.z.literal("codex/event"),
83
+ params: z.z.object({
84
+ msg: z.z.any()
85
+ })
86
+ }).passthrough(), (data) => {
87
+ const msg = data.params.msg;
88
+ this.updateIdentifiersFromEvent(msg);
89
+ this.handler?.(msg);
90
+ });
91
+ }
92
+ setHandler(handler) {
93
+ this.handler = handler;
94
+ }
95
+ /**
96
+ * Set the permission handler for tool approval
97
+ */
98
+ setPermissionHandler(handler) {
99
+ this.permissionHandler = handler;
100
+ }
101
+ async connect() {
102
+ if (this.connected) return;
103
+ const mcpCommand = getCodexMcpCommand();
104
+ types.logger.debug(`[CodexMCP] Connecting to Codex MCP server using command: codex ${mcpCommand}`);
105
+ this.transport = new stdio_js.StdioClientTransport({
106
+ command: "codex",
107
+ args: [mcpCommand],
108
+ env: Object.keys(process.env).reduce((acc, key) => {
109
+ const value = process.env[key];
110
+ if (typeof value === "string") acc[key] = value;
111
+ return acc;
112
+ }, {})
113
+ });
114
+ this.registerPermissionHandlers();
115
+ await this.client.connect(this.transport);
116
+ this.connected = true;
117
+ types.logger.debug("[CodexMCP] Connected to Codex");
118
+ }
119
+ registerPermissionHandlers() {
120
+ this.client.setRequestHandler(
121
+ types_js.ElicitRequestSchema,
122
+ async (request) => {
123
+ console.log("[CodexMCP] Received elicitation request:", request.params);
124
+ const params = request.params;
125
+ const toolName = "CodexBash";
126
+ if (!this.permissionHandler) {
127
+ types.logger.debug("[CodexMCP] No permission handler set, denying by default");
128
+ return {
129
+ decision: "denied"
130
+ };
131
+ }
132
+ try {
133
+ const result = await this.permissionHandler.handleToolCall(
134
+ params.codex_call_id,
135
+ toolName,
136
+ {
137
+ command: params.codex_command,
138
+ cwd: params.codex_cwd
139
+ }
140
+ );
141
+ types.logger.debug("[CodexMCP] Permission result:", result);
142
+ return {
143
+ decision: result.decision
144
+ };
145
+ } catch (error) {
146
+ types.logger.debug("[CodexMCP] Error handling permission request:", error);
147
+ return {
148
+ decision: "denied",
149
+ reason: error instanceof Error ? error.message : "Permission request failed"
150
+ };
151
+ }
152
+ }
153
+ );
154
+ types.logger.debug("[CodexMCP] Permission handlers registered");
155
+ }
156
+ async startSession(config, options) {
157
+ if (!this.connected) await this.connect();
158
+ types.logger.debug("[CodexMCP] Starting Codex session:", config);
159
+ const response = await this.client.callTool({
160
+ name: "codex",
161
+ arguments: config
162
+ }, void 0, {
163
+ signal: options?.signal,
164
+ timeout: DEFAULT_TIMEOUT
165
+ // maxTotalTimeout: 10000000000
166
+ });
167
+ types.logger.debug("[CodexMCP] startSession response:", response);
168
+ this.extractIdentifiers(response);
169
+ return response;
170
+ }
171
+ async continueSession(prompt, options) {
172
+ if (!this.connected) await this.connect();
173
+ if (!this.sessionId) {
174
+ throw new Error("No active session. Call startSession first.");
175
+ }
176
+ if (!this.conversationId) {
177
+ this.conversationId = this.sessionId;
178
+ types.logger.debug("[CodexMCP] conversationId missing, defaulting to sessionId:", this.conversationId);
179
+ }
180
+ const args = { sessionId: this.sessionId, conversationId: this.conversationId, prompt };
181
+ types.logger.debug("[CodexMCP] Continuing Codex session:", args);
182
+ const response = await this.client.callTool({
183
+ name: "codex-reply",
184
+ arguments: args
185
+ }, void 0, {
186
+ signal: options?.signal,
187
+ timeout: DEFAULT_TIMEOUT
188
+ });
189
+ types.logger.debug("[CodexMCP] continueSession response:", response);
190
+ this.extractIdentifiers(response);
191
+ return response;
192
+ }
193
+ updateIdentifiersFromEvent(event) {
194
+ if (!event || typeof event !== "object") {
195
+ return;
196
+ }
197
+ const candidates = [event];
198
+ if (event.data && typeof event.data === "object") {
199
+ candidates.push(event.data);
200
+ }
201
+ for (const candidate of candidates) {
202
+ const sessionId = candidate.session_id ?? candidate.sessionId;
203
+ if (sessionId) {
204
+ this.sessionId = sessionId;
205
+ types.logger.debug("[CodexMCP] Session ID extracted from event:", this.sessionId);
206
+ }
207
+ const conversationId = candidate.conversation_id ?? candidate.conversationId;
208
+ if (conversationId) {
209
+ this.conversationId = conversationId;
210
+ types.logger.debug("[CodexMCP] Conversation ID extracted from event:", this.conversationId);
211
+ }
212
+ }
213
+ }
214
+ extractIdentifiers(response) {
215
+ const meta = response?.meta || {};
216
+ if (meta.sessionId) {
217
+ this.sessionId = meta.sessionId;
218
+ types.logger.debug("[CodexMCP] Session ID extracted:", this.sessionId);
219
+ } else if (response?.sessionId) {
220
+ this.sessionId = response.sessionId;
221
+ types.logger.debug("[CodexMCP] Session ID extracted:", this.sessionId);
222
+ }
223
+ if (meta.conversationId) {
224
+ this.conversationId = meta.conversationId;
225
+ types.logger.debug("[CodexMCP] Conversation ID extracted:", this.conversationId);
226
+ } else if (response?.conversationId) {
227
+ this.conversationId = response.conversationId;
228
+ types.logger.debug("[CodexMCP] Conversation ID extracted:", this.conversationId);
229
+ }
230
+ const content = response?.content;
231
+ if (Array.isArray(content)) {
232
+ for (const item of content) {
233
+ if (!this.sessionId && item?.sessionId) {
234
+ this.sessionId = item.sessionId;
235
+ types.logger.debug("[CodexMCP] Session ID extracted from content:", this.sessionId);
236
+ }
237
+ if (!this.conversationId && item && typeof item === "object" && "conversationId" in item && item.conversationId) {
238
+ this.conversationId = item.conversationId;
239
+ types.logger.debug("[CodexMCP] Conversation ID extracted from content:", this.conversationId);
240
+ }
241
+ }
242
+ }
243
+ }
244
+ getSessionId() {
245
+ return this.sessionId;
246
+ }
247
+ hasActiveSession() {
248
+ return this.sessionId !== null;
249
+ }
250
+ clearSession() {
251
+ const previousSessionId = this.sessionId;
252
+ this.sessionId = null;
253
+ this.conversationId = null;
254
+ types.logger.debug("[CodexMCP] Session cleared, previous sessionId:", previousSessionId);
255
+ }
256
+ /**
257
+ * Store the current session ID without clearing it, useful for abort handling
258
+ */
259
+ storeSessionForResume() {
260
+ types.logger.debug("[CodexMCP] Storing session for potential resume:", this.sessionId);
261
+ return this.sessionId;
262
+ }
263
+ async disconnect() {
264
+ if (!this.connected) return;
265
+ const pid = this.transport?.pid ?? null;
266
+ types.logger.debug(`[CodexMCP] Disconnecting; child pid=${pid ?? "none"}`);
267
+ try {
268
+ types.logger.debug("[CodexMCP] client.close begin");
269
+ await this.client.close();
270
+ types.logger.debug("[CodexMCP] client.close done");
271
+ } catch (e) {
272
+ types.logger.debug("[CodexMCP] Error closing client, attempting transport close directly", e);
273
+ try {
274
+ types.logger.debug("[CodexMCP] transport.close begin");
275
+ await this.transport?.close?.();
276
+ types.logger.debug("[CodexMCP] transport.close done");
277
+ } catch {
278
+ }
279
+ }
280
+ if (pid) {
281
+ try {
282
+ process.kill(pid, 0);
283
+ types.logger.debug("[CodexMCP] Child still alive, sending SIGKILL");
284
+ try {
285
+ process.kill(pid, "SIGKILL");
286
+ } catch {
287
+ }
288
+ } catch {
289
+ }
290
+ }
291
+ this.transport = null;
292
+ this.connected = false;
293
+ this.sessionId = null;
294
+ this.conversationId = null;
295
+ types.logger.debug("[CodexMCP] Disconnected");
296
+ }
297
+ }
298
+
299
+ class CodexPermissionHandler {
300
+ pendingRequests = /* @__PURE__ */ new Map();
301
+ session;
302
+ constructor(session) {
303
+ this.session = session;
304
+ this.setupRpcHandler();
305
+ }
306
+ /**
307
+ * Handle a tool permission request
308
+ * @param toolCallId - The unique ID of the tool call
309
+ * @param toolName - The name of the tool being called
310
+ * @param input - The input parameters for the tool
311
+ * @returns Promise resolving to permission result
312
+ */
313
+ async handleToolCall(toolCallId, toolName, input) {
314
+ return new Promise((resolve, reject) => {
315
+ this.pendingRequests.set(toolCallId, {
316
+ resolve,
317
+ reject,
318
+ toolName,
319
+ input
320
+ });
321
+ this.session.updateAgentState((currentState) => ({
322
+ ...currentState,
323
+ requests: {
324
+ ...currentState.requests,
325
+ [toolCallId]: {
326
+ tool: toolName,
327
+ arguments: input,
328
+ createdAt: Date.now()
329
+ }
330
+ }
331
+ }));
332
+ types.logger.debug(`[Codex] Permission request sent for tool: ${toolName} (${toolCallId})`);
333
+ });
334
+ }
335
+ /**
336
+ * Setup RPC handler for permission responses
337
+ */
338
+ setupRpcHandler() {
339
+ this.session.rpcHandlerManager.registerHandler(
340
+ "permission",
341
+ async (response) => {
342
+ const pending = this.pendingRequests.get(response.id);
343
+ if (!pending) {
344
+ types.logger.debug("[Codex] Permission request not found or already resolved");
345
+ return;
346
+ }
347
+ this.pendingRequests.delete(response.id);
348
+ const result = response.approved ? { decision: response.decision === "approved_for_session" ? "approved_for_session" : "approved" } : { decision: response.decision === "denied" ? "denied" : "abort" };
349
+ pending.resolve(result);
350
+ this.session.updateAgentState((currentState) => {
351
+ const request = currentState.requests?.[response.id];
352
+ if (!request) return currentState;
353
+ const { [response.id]: _, ...remainingRequests } = currentState.requests || {};
354
+ let res = {
355
+ ...currentState,
356
+ requests: remainingRequests,
357
+ completedRequests: {
358
+ ...currentState.completedRequests,
359
+ [response.id]: {
360
+ ...request,
361
+ completedAt: Date.now(),
362
+ status: response.approved ? "approved" : "denied",
363
+ decision: result.decision
364
+ }
365
+ }
366
+ };
367
+ return res;
368
+ });
369
+ types.logger.debug(`[Codex] Permission ${response.approved ? "approved" : "denied"} for ${pending.toolName}`);
370
+ }
371
+ );
372
+ }
373
+ /**
374
+ * Reset state for new sessions
375
+ */
376
+ reset() {
377
+ for (const [id, pending] of this.pendingRequests.entries()) {
378
+ pending.reject(new Error("Session reset"));
379
+ }
380
+ this.pendingRequests.clear();
381
+ this.session.updateAgentState((currentState) => {
382
+ const pendingRequests = currentState.requests || {};
383
+ const completedRequests = { ...currentState.completedRequests };
384
+ for (const [id, request] of Object.entries(pendingRequests)) {
385
+ completedRequests[id] = {
386
+ ...request,
387
+ completedAt: Date.now(),
388
+ status: "canceled",
389
+ reason: "Session reset"
390
+ };
391
+ }
392
+ return {
393
+ ...currentState,
394
+ requests: {},
395
+ completedRequests
396
+ };
397
+ });
398
+ types.logger.debug("[Codex] Permission handler reset");
399
+ }
400
+ }
401
+
402
+ class ReasoningProcessor {
403
+ accumulator = "";
404
+ inTitleCapture = false;
405
+ titleBuffer = "";
406
+ contentBuffer = "";
407
+ hasTitle = false;
408
+ currentCallId = null;
409
+ toolCallStarted = false;
410
+ currentTitle = null;
411
+ onMessage = null;
412
+ constructor(onMessage) {
413
+ this.onMessage = onMessage || null;
414
+ this.reset();
415
+ }
416
+ /**
417
+ * Set the message callback for sending messages directly
418
+ */
419
+ setMessageCallback(callback) {
420
+ this.onMessage = callback;
421
+ }
422
+ /**
423
+ * Process a reasoning section break - indicates a new reasoning section is starting
424
+ */
425
+ handleSectionBreak() {
426
+ this.finishCurrentToolCall("canceled");
427
+ this.resetState();
428
+ types.logger.debug("[ReasoningProcessor] Section break - reset state");
429
+ }
430
+ /**
431
+ * Process a reasoning delta and accumulate content
432
+ */
433
+ processDelta(delta) {
434
+ this.accumulator += delta;
435
+ if (!this.inTitleCapture && !this.hasTitle && !this.contentBuffer) {
436
+ if (this.accumulator.startsWith("**")) {
437
+ this.inTitleCapture = true;
438
+ this.titleBuffer = this.accumulator.substring(2);
439
+ types.logger.debug("[ReasoningProcessor] Started title capture");
440
+ } else if (this.accumulator.length > 0) {
441
+ this.contentBuffer = this.accumulator;
442
+ }
443
+ } else if (this.inTitleCapture) {
444
+ this.titleBuffer = this.accumulator.substring(2);
445
+ const titleEndIndex = this.titleBuffer.indexOf("**");
446
+ if (titleEndIndex !== -1) {
447
+ const title = this.titleBuffer.substring(0, titleEndIndex);
448
+ const afterTitle = this.titleBuffer.substring(titleEndIndex + 2);
449
+ this.hasTitle = true;
450
+ this.inTitleCapture = false;
451
+ this.currentTitle = title;
452
+ this.contentBuffer = afterTitle;
453
+ this.currentCallId = node_crypto.randomUUID();
454
+ types.logger.debug(`[ReasoningProcessor] Title captured: "${title}"`);
455
+ this.sendToolCallStart(title);
456
+ }
457
+ } else if (this.hasTitle) {
458
+ this.contentBuffer = this.accumulator.substring(
459
+ this.accumulator.indexOf("**") + 2 + this.currentTitle.length + 2
460
+ );
461
+ } else {
462
+ this.contentBuffer = this.accumulator;
463
+ }
464
+ }
465
+ /**
466
+ * Send the tool call start message
467
+ */
468
+ sendToolCallStart(title) {
469
+ if (!this.currentCallId || this.toolCallStarted) {
470
+ return;
471
+ }
472
+ const toolCall = {
473
+ type: "tool-call",
474
+ name: "CodexReasoning",
475
+ callId: this.currentCallId,
476
+ input: {
477
+ title
478
+ },
479
+ id: node_crypto.randomUUID()
480
+ };
481
+ types.logger.debug(`[ReasoningProcessor] Sending tool call start for: "${title}"`);
482
+ this.onMessage?.(toolCall);
483
+ this.toolCallStarted = true;
484
+ }
485
+ /**
486
+ * Complete the reasoning section with final text
487
+ */
488
+ complete(fullText) {
489
+ let title;
490
+ let content = fullText;
491
+ if (fullText.startsWith("**")) {
492
+ const titleEndIndex = fullText.indexOf("**", 2);
493
+ if (titleEndIndex !== -1) {
494
+ title = fullText.substring(2, titleEndIndex);
495
+ content = fullText.substring(titleEndIndex + 2).trim();
496
+ }
497
+ }
498
+ types.logger.debug(`[ReasoningProcessor] Complete reasoning - Title: "${title}", Has content: ${content.length > 0}`);
499
+ if (title && !this.toolCallStarted) {
500
+ this.currentCallId = this.currentCallId || node_crypto.randomUUID();
501
+ this.sendToolCallStart(title);
502
+ }
503
+ if (this.toolCallStarted && this.currentCallId) {
504
+ const toolResult = {
505
+ type: "tool-call-result",
506
+ callId: this.currentCallId,
507
+ output: {
508
+ content,
509
+ status: "completed"
510
+ },
511
+ id: node_crypto.randomUUID()
512
+ };
513
+ types.logger.debug("[ReasoningProcessor] Sending tool call result");
514
+ this.onMessage?.(toolResult);
515
+ } else {
516
+ const reasoningMessage = {
517
+ type: "reasoning",
518
+ message: content,
519
+ id: node_crypto.randomUUID()
520
+ };
521
+ types.logger.debug("[ReasoningProcessor] Sending reasoning message");
522
+ this.onMessage?.(reasoningMessage);
523
+ }
524
+ this.resetState();
525
+ }
526
+ /**
527
+ * Abort the current reasoning section
528
+ */
529
+ abort() {
530
+ types.logger.debug("[ReasoningProcessor] Abort called");
531
+ this.finishCurrentToolCall("canceled");
532
+ this.resetState();
533
+ }
534
+ /**
535
+ * Reset the processor state
536
+ */
537
+ reset() {
538
+ this.finishCurrentToolCall("canceled");
539
+ this.resetState();
540
+ }
541
+ /**
542
+ * Finish current tool call if one is in progress
543
+ */
544
+ finishCurrentToolCall(status) {
545
+ if (this.toolCallStarted && this.currentCallId) {
546
+ const toolResult = {
547
+ type: "tool-call-result",
548
+ callId: this.currentCallId,
549
+ output: {
550
+ content: this.contentBuffer || "",
551
+ status
552
+ },
553
+ id: node_crypto.randomUUID()
554
+ };
555
+ types.logger.debug(`[ReasoningProcessor] Sending tool call result with status: ${status}`);
556
+ this.onMessage?.(toolResult);
557
+ }
558
+ }
559
+ /**
560
+ * Reset internal state
561
+ */
562
+ resetState() {
563
+ this.accumulator = "";
564
+ this.inTitleCapture = false;
565
+ this.titleBuffer = "";
566
+ this.contentBuffer = "";
567
+ this.hasTitle = false;
568
+ this.currentCallId = null;
569
+ this.toolCallStarted = false;
570
+ this.currentTitle = null;
571
+ }
572
+ /**
573
+ * Get the current call ID for tool result matching
574
+ */
575
+ getCurrentCallId() {
576
+ return this.currentCallId;
577
+ }
578
+ /**
579
+ * Check if a tool call has been started
580
+ */
581
+ hasStartedToolCall() {
582
+ return this.toolCallStarted;
583
+ }
584
+ }
585
+
586
+ class DiffProcessor {
587
+ previousDiff = null;
588
+ onMessage = null;
589
+ constructor(onMessage) {
590
+ this.onMessage = onMessage || null;
591
+ }
592
+ /**
593
+ * Process a turn_diff message and check if the unified_diff has changed
594
+ */
595
+ processDiff(unifiedDiff) {
596
+ if (this.previousDiff !== unifiedDiff) {
597
+ types.logger.debug("[DiffProcessor] Unified diff changed, sending CodexDiff tool call");
598
+ const callId = node_crypto.randomUUID();
599
+ const toolCall = {
600
+ type: "tool-call",
601
+ name: "CodexDiff",
602
+ callId,
603
+ input: {
604
+ unified_diff: unifiedDiff
605
+ },
606
+ id: node_crypto.randomUUID()
607
+ };
608
+ this.onMessage?.(toolCall);
609
+ const toolResult = {
610
+ type: "tool-call-result",
611
+ callId,
612
+ output: {
613
+ status: "completed"
614
+ },
615
+ id: node_crypto.randomUUID()
616
+ };
617
+ this.onMessage?.(toolResult);
618
+ }
619
+ this.previousDiff = unifiedDiff;
620
+ types.logger.debug("[DiffProcessor] Updated stored diff");
621
+ }
622
+ /**
623
+ * Reset the processor state (called on task_complete or turn_aborted)
624
+ */
625
+ reset() {
626
+ types.logger.debug("[DiffProcessor] Resetting diff state");
627
+ this.previousDiff = null;
628
+ }
629
+ /**
630
+ * Set the message callback for sending messages directly
631
+ */
632
+ setMessageCallback(callback) {
633
+ this.onMessage = callback;
634
+ }
635
+ /**
636
+ * Get the current diff value
637
+ */
638
+ getCurrentDiff() {
639
+ return this.previousDiff;
640
+ }
641
+ }
642
+
643
+ const CodexDisplay = ({ messageBuffer, logPath, onExit }) => {
644
+ const [messages, setMessages] = React.useState([]);
645
+ const [confirmationMode, setConfirmationMode] = React.useState(false);
646
+ const [actionInProgress, setActionInProgress] = React.useState(false);
647
+ const confirmationTimeoutRef = React.useRef(null);
648
+ const { stdout } = ink.useStdout();
649
+ const terminalWidth = stdout.columns || 80;
650
+ const terminalHeight = stdout.rows || 24;
651
+ React.useEffect(() => {
652
+ setMessages(messageBuffer.getMessages());
653
+ const unsubscribe = messageBuffer.onUpdate((newMessages) => {
654
+ setMessages(newMessages);
655
+ });
656
+ return () => {
657
+ unsubscribe();
658
+ if (confirmationTimeoutRef.current) {
659
+ clearTimeout(confirmationTimeoutRef.current);
660
+ }
661
+ };
662
+ }, [messageBuffer]);
663
+ const resetConfirmation = React.useCallback(() => {
664
+ setConfirmationMode(false);
665
+ if (confirmationTimeoutRef.current) {
666
+ clearTimeout(confirmationTimeoutRef.current);
667
+ confirmationTimeoutRef.current = null;
668
+ }
669
+ }, []);
670
+ const setConfirmationWithTimeout = React.useCallback(() => {
671
+ setConfirmationMode(true);
672
+ if (confirmationTimeoutRef.current) {
673
+ clearTimeout(confirmationTimeoutRef.current);
674
+ }
675
+ confirmationTimeoutRef.current = setTimeout(() => {
676
+ resetConfirmation();
677
+ }, 15e3);
678
+ }, [resetConfirmation]);
679
+ ink.useInput(React.useCallback(async (input, key) => {
680
+ if (actionInProgress) return;
681
+ if (key.ctrl && input === "c") {
682
+ if (confirmationMode) {
683
+ resetConfirmation();
684
+ setActionInProgress(true);
685
+ await new Promise((resolve) => setTimeout(resolve, 100));
686
+ onExit?.();
687
+ } else {
688
+ setConfirmationWithTimeout();
689
+ }
690
+ return;
691
+ }
692
+ if (confirmationMode) {
693
+ resetConfirmation();
694
+ }
695
+ }, [confirmationMode, actionInProgress, onExit, setConfirmationWithTimeout, resetConfirmation]));
696
+ const getMessageColor = (type) => {
697
+ switch (type) {
698
+ case "user":
699
+ return "magenta";
700
+ case "assistant":
701
+ return "cyan";
702
+ case "system":
703
+ return "blue";
704
+ case "tool":
705
+ return "yellow";
706
+ case "result":
707
+ return "green";
708
+ case "status":
709
+ return "gray";
710
+ default:
711
+ return "white";
712
+ }
713
+ };
714
+ const formatMessage = (msg) => {
715
+ const lines = msg.content.split("\n");
716
+ const maxLineLength = terminalWidth - 10;
717
+ return lines.map((line) => {
718
+ if (line.length <= maxLineLength) return line;
719
+ const chunks = [];
720
+ for (let i = 0; i < line.length; i += maxLineLength) {
721
+ chunks.push(line.slice(i, i + maxLineLength));
722
+ }
723
+ return chunks.join("\n");
724
+ }).join("\n");
725
+ };
726
+ return /* @__PURE__ */ React.createElement(ink.Box, { flexDirection: "column", width: terminalWidth, height: terminalHeight }, /* @__PURE__ */ React.createElement(
727
+ ink.Box,
728
+ {
729
+ flexDirection: "column",
730
+ width: terminalWidth,
731
+ height: terminalHeight - 4,
732
+ borderStyle: "round",
733
+ borderColor: "gray",
734
+ paddingX: 1,
735
+ overflow: "hidden"
736
+ },
737
+ /* @__PURE__ */ React.createElement(ink.Box, { flexDirection: "column", marginBottom: 1 }, /* @__PURE__ */ React.createElement(ink.Text, { color: "gray", bold: true }, "\u{1F916} Codex Agent Messages"), /* @__PURE__ */ React.createElement(ink.Text, { color: "gray", dimColor: true }, "\u2500".repeat(Math.min(terminalWidth - 4, 60)))),
738
+ /* @__PURE__ */ React.createElement(ink.Box, { flexDirection: "column", height: terminalHeight - 10, overflow: "hidden" }, messages.length === 0 ? /* @__PURE__ */ React.createElement(ink.Text, { color: "gray", dimColor: true }, "Waiting for messages...") : (
739
+ // Show only the last messages that fit in the available space
740
+ messages.slice(-Math.max(1, terminalHeight - 10)).map((msg) => /* @__PURE__ */ React.createElement(ink.Box, { key: msg.id, flexDirection: "column", marginBottom: 1 }, /* @__PURE__ */ React.createElement(ink.Text, { color: getMessageColor(msg.type), dimColor: true }, formatMessage(msg))))
741
+ ))
742
+ ), /* @__PURE__ */ React.createElement(
743
+ ink.Box,
744
+ {
745
+ width: terminalWidth,
746
+ borderStyle: "round",
747
+ borderColor: actionInProgress ? "gray" : confirmationMode ? "red" : "green",
748
+ paddingX: 2,
749
+ justifyContent: "center",
750
+ alignItems: "center",
751
+ flexDirection: "column"
752
+ },
753
+ /* @__PURE__ */ React.createElement(ink.Box, { flexDirection: "column", alignItems: "center" }, actionInProgress ? /* @__PURE__ */ React.createElement(ink.Text, { color: "gray", bold: true }, "Exiting agent...") : confirmationMode ? /* @__PURE__ */ React.createElement(ink.Text, { color: "red", bold: true }, "\u26A0\uFE0F Press Ctrl-C again to exit the agent") : /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(ink.Text, { color: "green", bold: true }, "\u{1F916} Codex Agent Running \u2022 Ctrl-C to exit")), process.env.DEBUG && logPath && /* @__PURE__ */ React.createElement(ink.Text, { color: "gray", dimColor: true }, "Debug logs: ", logPath))
754
+ ));
755
+ };
756
+
757
+ function emitReadyIfIdle({ pending, queueSize, shouldExit, sendReady, notify }) {
758
+ if (shouldExit) {
759
+ return false;
760
+ }
761
+ if (pending) {
762
+ return false;
763
+ }
764
+ if (queueSize() > 0) {
765
+ return false;
766
+ }
767
+ sendReady();
768
+ notify?.();
769
+ return true;
770
+ }
771
+ async function runCodex(opts) {
772
+ const sessionTag = node_crypto.randomUUID();
773
+ const api = await types.ApiClient.create(opts.credentials);
774
+ types.logger.debug(`[codex] Starting with options: startedBy=${opts.startedBy || "terminal"}`);
775
+ const settings = await types.readSettings();
776
+ let machineId = settings?.machineId;
777
+ if (!machineId) {
778
+ console.error(`[START] No machine ID found in settings, which is unexpected since authAndSetupMachineIfNeeded should have created it. Please report this issue on https://github.com/slopus/happy-cli/issues`);
779
+ process.exit(1);
780
+ }
781
+ types.logger.debug(`Using machineId: ${machineId}`);
782
+ await api.getOrCreateMachine({
783
+ machineId,
784
+ metadata: index.initialMachineMetadata
785
+ });
786
+ let state = {
787
+ controlledByUser: false
788
+ };
789
+ let metadata = {
790
+ path: process.cwd(),
791
+ host: os.hostname(),
792
+ version: types.packageJson.version,
793
+ os: os.platform(),
794
+ machineId,
795
+ homeDir: os.homedir(),
796
+ happyHomeDir: types.configuration.happyHomeDir,
797
+ happyLibDir: types.projectPath(),
798
+ happyToolsDir: node_path.resolve(types.projectPath(), "tools", "unpacked"),
799
+ startedFromDaemon: opts.startedBy === "daemon",
800
+ hostPid: process.pid,
801
+ startedBy: opts.startedBy || "terminal",
802
+ // Initialize lifecycle state
803
+ lifecycleState: "running",
804
+ lifecycleStateSince: Date.now(),
805
+ flavor: "codex"
806
+ };
807
+ const response = await api.getOrCreateSession({ tag: sessionTag, metadata, state });
808
+ const session = api.sessionSyncClient(response);
809
+ try {
810
+ types.logger.debug(`[START] Reporting session ${response.id} to daemon`);
811
+ const result = await index.notifyDaemonSessionStarted(response.id, metadata);
812
+ if (result.error) {
813
+ types.logger.debug(`[START] Failed to report to daemon (may not be running):`, result.error);
814
+ } else {
815
+ types.logger.debug(`[START] Reported session ${response.id} to daemon`);
816
+ }
817
+ } catch (error) {
818
+ types.logger.debug("[START] Failed to report to daemon (may not be running):", error);
819
+ }
820
+ const messageQueue = new index.MessageQueue2((mode) => index.hashObject({
821
+ permissionMode: mode.permissionMode,
822
+ model: mode.model
823
+ }));
824
+ let currentPermissionMode = void 0;
825
+ let currentModel = void 0;
826
+ session.onUserMessage((message) => {
827
+ let messagePermissionMode = currentPermissionMode;
828
+ if (message.meta?.permissionMode) {
829
+ const validModes = ["default", "read-only", "safe-yolo", "yolo"];
830
+ if (validModes.includes(message.meta.permissionMode)) {
831
+ messagePermissionMode = message.meta.permissionMode;
832
+ currentPermissionMode = messagePermissionMode;
833
+ types.logger.debug(`[Codex] Permission mode updated from user message to: ${currentPermissionMode}`);
834
+ } else {
835
+ types.logger.debug(`[Codex] Invalid permission mode received: ${message.meta.permissionMode}`);
836
+ }
837
+ } else {
838
+ types.logger.debug(`[Codex] User message received with no permission mode override, using current: ${currentPermissionMode ?? "default (effective)"}`);
839
+ }
840
+ let messageModel = currentModel;
841
+ if (message.meta?.hasOwnProperty("model")) {
842
+ messageModel = message.meta.model || void 0;
843
+ currentModel = messageModel;
844
+ types.logger.debug(`[Codex] Model updated from user message: ${messageModel || "reset to default"}`);
845
+ } else {
846
+ types.logger.debug(`[Codex] User message received with no model override, using current: ${currentModel || "default"}`);
847
+ }
848
+ const enhancedMode = {
849
+ permissionMode: messagePermissionMode || "default",
850
+ model: messageModel
851
+ };
852
+ messageQueue.push(message.content.text, enhancedMode);
853
+ });
854
+ let thinking = false;
855
+ session.keepAlive(thinking, "remote");
856
+ const keepAliveInterval = setInterval(() => {
857
+ session.keepAlive(thinking, "remote");
858
+ }, 2e3);
859
+ const sendReady = () => {
860
+ session.sendSessionEvent({ type: "ready" });
861
+ try {
862
+ api.push().sendToAllDevices(
863
+ "It's ready!",
864
+ "Codex is waiting for your command",
865
+ { sessionId: session.sessionId }
866
+ );
867
+ } catch (pushError) {
868
+ types.logger.debug("[Codex] Failed to send ready push", pushError);
869
+ }
870
+ };
871
+ function logActiveHandles(tag) {
872
+ if (!process.env.DEBUG) return;
873
+ const anyProc = process;
874
+ const handles = typeof anyProc._getActiveHandles === "function" ? anyProc._getActiveHandles() : [];
875
+ const requests = typeof anyProc._getActiveRequests === "function" ? anyProc._getActiveRequests() : [];
876
+ types.logger.debug(`[codex][handles] ${tag}: handles=${handles.length} requests=${requests.length}`);
877
+ try {
878
+ const kinds = handles.map((h) => h && h.constructor ? h.constructor.name : typeof h);
879
+ types.logger.debug(`[codex][handles] kinds=${JSON.stringify(kinds)}`);
880
+ } catch {
881
+ }
882
+ }
883
+ let abortController = new AbortController();
884
+ let shouldExit = false;
885
+ let storedSessionIdForResume = null;
886
+ async function handleAbort() {
887
+ types.logger.debug("[Codex] Abort requested - stopping current task");
888
+ try {
889
+ if (client.hasActiveSession()) {
890
+ storedSessionIdForResume = client.storeSessionForResume();
891
+ types.logger.debug("[Codex] Stored session for resume:", storedSessionIdForResume);
892
+ }
893
+ abortController.abort();
894
+ messageQueue.reset();
895
+ permissionHandler.reset();
896
+ reasoningProcessor.abort();
897
+ diffProcessor.reset();
898
+ types.logger.debug("[Codex] Abort completed - session remains active");
899
+ } catch (error) {
900
+ types.logger.debug("[Codex] Error during abort:", error);
901
+ } finally {
902
+ abortController = new AbortController();
903
+ }
904
+ }
905
+ const handleKillSession = async () => {
906
+ types.logger.debug("[Codex] Kill session requested - terminating process");
907
+ await handleAbort();
908
+ types.logger.debug("[Codex] Abort completed, proceeding with termination");
909
+ try {
910
+ if (session) {
911
+ session.updateMetadata((currentMetadata) => ({
912
+ ...currentMetadata,
913
+ lifecycleState: "archived",
914
+ lifecycleStateSince: Date.now(),
915
+ archivedBy: "cli",
916
+ archiveReason: "User terminated"
917
+ }));
918
+ session.sendSessionDeath();
919
+ await session.flush();
920
+ await session.close();
921
+ }
922
+ index.stopCaffeinate();
923
+ happyServer.stop();
924
+ types.logger.debug("[Codex] Session termination complete, exiting");
925
+ process.exit(0);
926
+ } catch (error) {
927
+ types.logger.debug("[Codex] Error during session termination:", error);
928
+ process.exit(1);
929
+ }
930
+ };
931
+ session.rpcHandlerManager.registerHandler("abort", handleAbort);
932
+ index.registerKillSessionHandler(session.rpcHandlerManager, handleKillSession);
933
+ const messageBuffer = new index.MessageBuffer();
934
+ const hasTTY = process.stdout.isTTY && process.stdin.isTTY;
935
+ let inkInstance = null;
936
+ if (hasTTY) {
937
+ console.clear();
938
+ inkInstance = ink.render(React.createElement(CodexDisplay, {
939
+ messageBuffer,
940
+ logPath: process.env.DEBUG ? types.logger.getLogPath() : void 0,
941
+ onExit: async () => {
942
+ types.logger.debug("[codex]: Exiting agent via Ctrl-C");
943
+ shouldExit = true;
944
+ await handleAbort();
945
+ }
946
+ }), {
947
+ exitOnCtrlC: false,
948
+ patchConsole: false
949
+ });
950
+ }
951
+ if (hasTTY) {
952
+ process.stdin.resume();
953
+ if (process.stdin.isTTY) {
954
+ process.stdin.setRawMode(true);
955
+ }
956
+ process.stdin.setEncoding("utf8");
957
+ }
958
+ const client = new CodexMcpClient();
959
+ function findCodexResumeFile(sessionId) {
960
+ if (!sessionId) return null;
961
+ try {
962
+ let collectFilesRecursive2 = function(dir, acc = []) {
963
+ let entries;
964
+ try {
965
+ entries = fs.readdirSync(dir, { withFileTypes: true });
966
+ } catch {
967
+ return acc;
968
+ }
969
+ for (const entry of entries) {
970
+ const full = node_path.join(dir, entry.name);
971
+ if (entry.isDirectory()) {
972
+ collectFilesRecursive2(full, acc);
973
+ } else if (entry.isFile()) {
974
+ acc.push(full);
975
+ }
976
+ }
977
+ return acc;
978
+ };
979
+ var collectFilesRecursive = collectFilesRecursive2;
980
+ const codexHomeDir = process.env.CODEX_HOME || node_path.join(os.homedir(), ".codex");
981
+ const rootDir = node_path.join(codexHomeDir, "sessions");
982
+ const candidates = collectFilesRecursive2(rootDir).filter((full) => full.endsWith(`-${sessionId}.jsonl`)).filter((full) => {
983
+ try {
984
+ return fs.statSync(full).isFile();
985
+ } catch {
986
+ return false;
987
+ }
988
+ }).sort((a, b) => {
989
+ const sa = fs.statSync(a).mtimeMs;
990
+ const sb = fs.statSync(b).mtimeMs;
991
+ return sb - sa;
992
+ });
993
+ return candidates[0] || null;
994
+ } catch {
995
+ return null;
996
+ }
997
+ }
998
+ const permissionHandler = new CodexPermissionHandler(session);
999
+ const reasoningProcessor = new ReasoningProcessor((message) => {
1000
+ session.sendCodexMessage(message);
1001
+ });
1002
+ const diffProcessor = new DiffProcessor((message) => {
1003
+ session.sendCodexMessage(message);
1004
+ });
1005
+ client.setPermissionHandler(permissionHandler);
1006
+ client.setHandler((msg) => {
1007
+ types.logger.debug(`[Codex] MCP message: ${JSON.stringify(msg)}`);
1008
+ if (msg.type === "agent_message") {
1009
+ messageBuffer.addMessage(msg.message, "assistant");
1010
+ } else if (msg.type === "agent_reasoning_delta") ; else if (msg.type === "agent_reasoning") {
1011
+ messageBuffer.addMessage(`[Thinking] ${msg.text.substring(0, 100)}...`, "system");
1012
+ } else if (msg.type === "exec_command_begin") {
1013
+ messageBuffer.addMessage(`Executing: ${msg.command}`, "tool");
1014
+ } else if (msg.type === "exec_command_end") {
1015
+ const output = msg.output || msg.error || "Command completed";
1016
+ const truncatedOutput = output.substring(0, 200);
1017
+ messageBuffer.addMessage(
1018
+ `Result: ${truncatedOutput}${output.length > 200 ? "..." : ""}`,
1019
+ "result"
1020
+ );
1021
+ } else if (msg.type === "task_started") {
1022
+ messageBuffer.addMessage("Starting task...", "status");
1023
+ } else if (msg.type === "task_complete") {
1024
+ messageBuffer.addMessage("Task completed", "status");
1025
+ sendReady();
1026
+ } else if (msg.type === "turn_aborted") {
1027
+ messageBuffer.addMessage("Turn aborted", "status");
1028
+ sendReady();
1029
+ }
1030
+ if (msg.type === "task_started") {
1031
+ if (!thinking) {
1032
+ types.logger.debug("thinking started");
1033
+ thinking = true;
1034
+ session.keepAlive(thinking, "remote");
1035
+ }
1036
+ }
1037
+ if (msg.type === "task_complete" || msg.type === "turn_aborted") {
1038
+ if (thinking) {
1039
+ types.logger.debug("thinking completed");
1040
+ thinking = false;
1041
+ session.keepAlive(thinking, "remote");
1042
+ }
1043
+ diffProcessor.reset();
1044
+ }
1045
+ if (msg.type === "agent_reasoning_section_break") {
1046
+ reasoningProcessor.handleSectionBreak();
1047
+ }
1048
+ if (msg.type === "agent_reasoning_delta") {
1049
+ reasoningProcessor.processDelta(msg.delta);
1050
+ }
1051
+ if (msg.type === "agent_reasoning") {
1052
+ reasoningProcessor.complete(msg.text);
1053
+ }
1054
+ if (msg.type === "agent_message") {
1055
+ session.sendCodexMessage({
1056
+ type: "message",
1057
+ message: msg.message,
1058
+ id: node_crypto.randomUUID()
1059
+ });
1060
+ }
1061
+ if (msg.type === "exec_command_begin" || msg.type === "exec_approval_request") {
1062
+ let { call_id, type, ...inputs } = msg;
1063
+ session.sendCodexMessage({
1064
+ type: "tool-call",
1065
+ name: "CodexBash",
1066
+ callId: call_id,
1067
+ input: inputs,
1068
+ id: node_crypto.randomUUID()
1069
+ });
1070
+ }
1071
+ if (msg.type === "exec_command_end") {
1072
+ let { call_id, type, ...output } = msg;
1073
+ session.sendCodexMessage({
1074
+ type: "tool-call-result",
1075
+ callId: call_id,
1076
+ output,
1077
+ id: node_crypto.randomUUID()
1078
+ });
1079
+ }
1080
+ if (msg.type === "token_count") {
1081
+ session.sendCodexMessage({
1082
+ ...msg,
1083
+ id: node_crypto.randomUUID()
1084
+ });
1085
+ }
1086
+ if (msg.type === "patch_apply_begin") {
1087
+ let { call_id, auto_approved, changes } = msg;
1088
+ const changeCount = Object.keys(changes).length;
1089
+ const filesMsg = changeCount === 1 ? "1 file" : `${changeCount} files`;
1090
+ messageBuffer.addMessage(`Modifying ${filesMsg}...`, "tool");
1091
+ session.sendCodexMessage({
1092
+ type: "tool-call",
1093
+ name: "CodexPatch",
1094
+ callId: call_id,
1095
+ input: {
1096
+ auto_approved,
1097
+ changes
1098
+ },
1099
+ id: node_crypto.randomUUID()
1100
+ });
1101
+ }
1102
+ if (msg.type === "patch_apply_end") {
1103
+ let { call_id, stdout, stderr, success } = msg;
1104
+ if (success) {
1105
+ const message = stdout || "Files modified successfully";
1106
+ messageBuffer.addMessage(message.substring(0, 200), "result");
1107
+ } else {
1108
+ const errorMsg = stderr || "Failed to modify files";
1109
+ messageBuffer.addMessage(`Error: ${errorMsg.substring(0, 200)}`, "result");
1110
+ }
1111
+ session.sendCodexMessage({
1112
+ type: "tool-call-result",
1113
+ callId: call_id,
1114
+ output: {
1115
+ stdout,
1116
+ stderr,
1117
+ success
1118
+ },
1119
+ id: node_crypto.randomUUID()
1120
+ });
1121
+ }
1122
+ if (msg.type === "turn_diff") {
1123
+ if (msg.unified_diff) {
1124
+ diffProcessor.processDiff(msg.unified_diff);
1125
+ }
1126
+ }
1127
+ });
1128
+ const happyServer = await index.startHappyServer(session);
1129
+ const bridgeCommand = node_path.join(types.projectPath(), "bin", "happy-mcp.mjs");
1130
+ const mcpServers = {
1131
+ happy: {
1132
+ command: bridgeCommand,
1133
+ args: ["--url", happyServer.url]
1134
+ }
1135
+ };
1136
+ let first = true;
1137
+ try {
1138
+ types.logger.debug("[codex]: client.connect begin");
1139
+ await client.connect();
1140
+ types.logger.debug("[codex]: client.connect done");
1141
+ let wasCreated = false;
1142
+ let currentModeHash = null;
1143
+ let pending = null;
1144
+ let nextExperimentalResume = null;
1145
+ while (!shouldExit) {
1146
+ logActiveHandles("loop-top");
1147
+ let message = pending;
1148
+ pending = null;
1149
+ if (!message) {
1150
+ const waitSignal = abortController.signal;
1151
+ const batch = await messageQueue.waitForMessagesAndGetAsString(waitSignal);
1152
+ if (!batch) {
1153
+ if (waitSignal.aborted && !shouldExit) {
1154
+ types.logger.debug("[codex]: Wait aborted while idle; ignoring and continuing");
1155
+ continue;
1156
+ }
1157
+ types.logger.debug(`[codex]: batch=${!!batch}, shouldExit=${shouldExit}`);
1158
+ break;
1159
+ }
1160
+ message = batch;
1161
+ }
1162
+ if (!message) {
1163
+ break;
1164
+ }
1165
+ if (wasCreated && currentModeHash && message.hash !== currentModeHash) {
1166
+ types.logger.debug("[Codex] Mode changed \u2013 restarting Codex session");
1167
+ messageBuffer.addMessage("\u2550".repeat(40), "status");
1168
+ messageBuffer.addMessage("Starting new Codex session (mode changed)...", "status");
1169
+ try {
1170
+ const prevSessionId = client.getSessionId();
1171
+ nextExperimentalResume = findCodexResumeFile(prevSessionId);
1172
+ if (nextExperimentalResume) {
1173
+ types.logger.debug(`[Codex] Found resume file for session ${prevSessionId}: ${nextExperimentalResume}`);
1174
+ messageBuffer.addMessage("Resuming previous context\u2026", "status");
1175
+ } else {
1176
+ types.logger.debug("[Codex] No resume file found for previous session");
1177
+ }
1178
+ } catch (e) {
1179
+ types.logger.debug("[Codex] Error while searching resume file", e);
1180
+ }
1181
+ client.clearSession();
1182
+ wasCreated = false;
1183
+ currentModeHash = null;
1184
+ pending = message;
1185
+ permissionHandler.reset();
1186
+ reasoningProcessor.abort();
1187
+ diffProcessor.reset();
1188
+ thinking = false;
1189
+ session.keepAlive(thinking, "remote");
1190
+ continue;
1191
+ }
1192
+ messageBuffer.addMessage(message.message, "user");
1193
+ currentModeHash = message.hash;
1194
+ try {
1195
+ const approvalPolicy = (() => {
1196
+ switch (message.mode.permissionMode) {
1197
+ case "default":
1198
+ return "untrusted";
1199
+ case "read-only":
1200
+ return "never";
1201
+ case "safe-yolo":
1202
+ return "on-failure";
1203
+ case "yolo":
1204
+ return "on-failure";
1205
+ }
1206
+ })();
1207
+ const sandbox = (() => {
1208
+ switch (message.mode.permissionMode) {
1209
+ case "default":
1210
+ return "workspace-write";
1211
+ case "read-only":
1212
+ return "read-only";
1213
+ case "safe-yolo":
1214
+ return "workspace-write";
1215
+ case "yolo":
1216
+ return "danger-full-access";
1217
+ }
1218
+ })();
1219
+ if (!wasCreated) {
1220
+ const startConfig = {
1221
+ prompt: first ? message.message + "\n\n" + index.trimIdent(`Based on this message, call functions.happy__change_title to change chat session title that would represent the current task. If chat idea would change dramatically - call this function again to update the title.`) : message.message,
1222
+ sandbox,
1223
+ "approval-policy": approvalPolicy,
1224
+ config: { mcp_servers: mcpServers }
1225
+ };
1226
+ if (message.mode.model) {
1227
+ startConfig.model = message.mode.model;
1228
+ }
1229
+ let resumeFile = null;
1230
+ if (nextExperimentalResume) {
1231
+ resumeFile = nextExperimentalResume;
1232
+ nextExperimentalResume = null;
1233
+ types.logger.debug("[Codex] Using resume file from mode change:", resumeFile);
1234
+ } else if (storedSessionIdForResume) {
1235
+ const abortResumeFile = findCodexResumeFile(storedSessionIdForResume);
1236
+ if (abortResumeFile) {
1237
+ resumeFile = abortResumeFile;
1238
+ types.logger.debug("[Codex] Using resume file from aborted session:", resumeFile);
1239
+ messageBuffer.addMessage("Resuming from aborted session...", "status");
1240
+ }
1241
+ storedSessionIdForResume = null;
1242
+ }
1243
+ if (resumeFile) {
1244
+ startConfig.config.experimental_resume = resumeFile;
1245
+ }
1246
+ await client.startSession(
1247
+ startConfig,
1248
+ { signal: abortController.signal }
1249
+ );
1250
+ wasCreated = true;
1251
+ first = false;
1252
+ } else {
1253
+ const response2 = await client.continueSession(
1254
+ message.message,
1255
+ { signal: abortController.signal }
1256
+ );
1257
+ types.logger.debug("[Codex] continueSession response:", response2);
1258
+ }
1259
+ } catch (error) {
1260
+ types.logger.warn("Error in codex session:", error);
1261
+ const isAbortError = error instanceof Error && error.name === "AbortError";
1262
+ if (isAbortError) {
1263
+ messageBuffer.addMessage("Aborted by user", "status");
1264
+ session.sendSessionEvent({ type: "message", message: "Aborted by user" });
1265
+ wasCreated = false;
1266
+ currentModeHash = null;
1267
+ types.logger.debug("[Codex] Marked session as not created after abort for proper resume");
1268
+ } else {
1269
+ messageBuffer.addMessage("Process exited unexpectedly", "status");
1270
+ session.sendSessionEvent({ type: "message", message: "Process exited unexpectedly" });
1271
+ if (client.hasActiveSession()) {
1272
+ storedSessionIdForResume = client.storeSessionForResume();
1273
+ types.logger.debug("[Codex] Stored session after unexpected error:", storedSessionIdForResume);
1274
+ }
1275
+ }
1276
+ } finally {
1277
+ permissionHandler.reset();
1278
+ reasoningProcessor.abort();
1279
+ diffProcessor.reset();
1280
+ thinking = false;
1281
+ session.keepAlive(thinking, "remote");
1282
+ emitReadyIfIdle({
1283
+ pending,
1284
+ queueSize: () => messageQueue.size(),
1285
+ shouldExit,
1286
+ sendReady
1287
+ });
1288
+ logActiveHandles("after-turn");
1289
+ }
1290
+ }
1291
+ } finally {
1292
+ types.logger.debug("[codex]: Final cleanup start");
1293
+ logActiveHandles("cleanup-start");
1294
+ try {
1295
+ types.logger.debug("[codex]: sendSessionDeath");
1296
+ session.sendSessionDeath();
1297
+ types.logger.debug("[codex]: flush begin");
1298
+ await session.flush();
1299
+ types.logger.debug("[codex]: flush done");
1300
+ types.logger.debug("[codex]: session.close begin");
1301
+ await session.close();
1302
+ types.logger.debug("[codex]: session.close done");
1303
+ } catch (e) {
1304
+ types.logger.debug("[codex]: Error while closing session", e);
1305
+ }
1306
+ types.logger.debug("[codex]: client.disconnect begin");
1307
+ await client.disconnect();
1308
+ types.logger.debug("[codex]: client.disconnect done");
1309
+ types.logger.debug("[codex]: happyServer.stop");
1310
+ happyServer.stop();
1311
+ if (process.stdin.isTTY) {
1312
+ types.logger.debug("[codex]: setRawMode(false)");
1313
+ try {
1314
+ process.stdin.setRawMode(false);
1315
+ } catch {
1316
+ }
1317
+ }
1318
+ if (hasTTY) {
1319
+ types.logger.debug("[codex]: stdin.pause()");
1320
+ try {
1321
+ process.stdin.pause();
1322
+ } catch {
1323
+ }
1324
+ }
1325
+ types.logger.debug("[codex]: clearInterval(keepAlive)");
1326
+ clearInterval(keepAliveInterval);
1327
+ if (inkInstance) {
1328
+ types.logger.debug("[codex]: inkInstance.unmount()");
1329
+ inkInstance.unmount();
1330
+ }
1331
+ messageBuffer.clear();
1332
+ logActiveHandles("cleanup-end");
1333
+ types.logger.debug("[codex]: Final cleanup completed");
1334
+ }
1335
+ }
1336
+
1337
+ exports.emitReadyIfIdle = emitReadyIfIdle;
1338
+ exports.runCodex = runCodex;