zenflo 0.11.2

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