happy-coder 0.10.0-2 → 0.10.0-4

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