@triflux/remote 10.53.0 → 10.55.0

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/hub/team/backend.mjs +10 -3
  2. package/hub/team/cli/commands/start/index.mjs +0 -2
  3. package/hub/team/handoff.mjs +1 -1
  4. package/hub/team/headless.mjs +41 -57
  5. package/hub/team/intervention.mjs +6 -4
  6. package/hub/team/nativeProxy.mjs +2 -48
  7. package/hub/team/pane.mjs +31 -18
  8. package/hub/team/psmux.mjs +36 -20
  9. package/hub/team/remote-session.mjs +66 -56
  10. package/hub/team/retry-state-machine.mjs +1 -1
  11. package/hub/team/session.mjs +80 -59
  12. package/hub/team/terminal-opener.mjs +5 -19
  13. package/hub/team/tui-viewer.mjs +2 -2
  14. package/hub/team/tui.mjs +0 -6
  15. package/hub/workers/factory.mjs +1 -10
  16. package/hub/workers/interface.mjs +0 -7
  17. package/package.json +2 -6
  18. package/scripts/lib/backup-rotation.mjs +60 -0
  19. package/scripts/lib/codex-profile-config.mjs +20 -7
  20. package/scripts/lib/codex-recovery.sh +2 -3
  21. package/scripts/lib/install-blob-history.json +3196 -0
  22. package/scripts/lib/install-retire.mjs +203 -0
  23. package/scripts/lib/legacy-hook-cleanup.mjs +148 -13
  24. package/scripts/lib/legacy-mcp-cleanup.mjs +405 -104
  25. package/scripts/lib/machine-profile.mjs +2 -2
  26. package/scripts/lib/mcp-filter.mjs +1 -42
  27. package/scripts/lib/mcp-guard-engine.mjs +198 -19
  28. package/scripts/lib/mcp-manifest.mjs +0 -40
  29. package/scripts/lib/process-utils.mjs +19 -0
  30. package/scripts/lib/stable-node.mjs +35 -0
  31. package/scripts/lib/test-env.mjs +20 -0
  32. package/cto/brief.mjs +0 -73
  33. package/cto/collect.mjs +0 -490
  34. package/cto/current.schema.json +0 -148
  35. package/cto/events.mjs +0 -208
  36. package/cto/hygiene.mjs +0 -320
  37. package/cto/lake-root.mjs +0 -127
  38. package/cto/status.mjs +0 -124
  39. package/hub/lib/cto-env.mjs +0 -1
  40. package/hub/team/notify.mjs +0 -385
  41. package/hub/team/process-cleanup.mjs +0 -386
  42. package/hub/team/routing.mjs +0 -249
  43. package/hub/team/staleState.mjs +0 -403
  44. package/hub/team/worker-signal.mjs +0 -263
  45. package/hub/team/worker-signal.types.d.ts +0 -52
  46. package/hub/workers/codex-mcp.mjs +0 -853
  47. package/scripts/lib/remote-spawn-transfer.mjs +0 -226
@@ -1,853 +0,0 @@
1
- // hub/workers/codex-mcp.mjs — Codex MCP 서버 래퍼
2
- import { appendFileSync, readFileSync } from "node:fs";
3
- import { homedir } from "node:os";
4
- import { join } from "node:path";
5
- import process from "node:process";
6
- import { fileURLToPath } from "node:url";
7
-
8
- import { Client } from "@modelcontextprotocol/sdk/client/index.js";
9
- import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
10
-
11
- import { normalizeCodexProfileName } from "../../scripts/lib/codex-profile-config.mjs";
12
- import {
13
- CODEX_MCP_EXECUTION_EXIT_CODE,
14
- CODEX_MCP_TRANSPORT_EXIT_CODE,
15
- } from "@triflux/core/hub/cli-adapter-base.mjs";
16
- import { withRetry } from "./worker-utils.mjs";
17
-
18
- const REQUIRED_TOOLS = ["codex", "codex-reply"];
19
-
20
- export { CODEX_MCP_EXECUTION_EXIT_CODE, CODEX_MCP_TRANSPORT_EXIT_CODE };
21
- export const DEFAULT_CODEX_MCP_TIMEOUT_MS = 10 * 60 * 1000;
22
- export const DEFAULT_CODEX_MCP_BOOTSTRAP_TIMEOUT_MS = 120 * 1000;
23
- export const DEFAULT_CODEX_MCP_SHUTDOWN_TIMEOUT_MS = 2_000;
24
-
25
- /**
26
- * Codex MCP transport/bootstrap 계층 오류
27
- */
28
- export class CodexMcpTransportError extends Error {
29
- /**
30
- * @param {string} message
31
- * @param {object} [options]
32
- * @param {unknown} [options.cause]
33
- * @param {string} [options.stderr]
34
- */
35
- constructor(message, options = {}) {
36
- super(message, { cause: options.cause });
37
- this.name = "CodexMcpTransportError";
38
- this.stderr = options.stderr || "";
39
- }
40
- }
41
-
42
- function cloneEnv(env = process.env) {
43
- return Object.fromEntries(
44
- Object.entries(env).filter(([, value]) => typeof value === "string"),
45
- );
46
- }
47
-
48
- async function closeWithin(label, closeFn, timeoutMs) {
49
- let timer = null;
50
- try {
51
- const timeout = new Promise((resolve) => {
52
- timer = setTimeout(() => {
53
- resolve({ timedOut: true });
54
- }, timeoutMs);
55
- });
56
- const closed = Promise.resolve()
57
- .then(closeFn)
58
- .then(() => ({ timedOut: false }));
59
- const result = await Promise.race([closed, timeout]);
60
- if (result.timedOut) {
61
- console.error(
62
- `[codex-mcp] WARNING: ${label} did not close within ${timeoutMs}ms; continuing shutdown.`,
63
- );
64
- }
65
- return result;
66
- } catch (error) {
67
- console.error(
68
- `[codex-mcp] WARNING: ${label} close failed: ${error instanceof Error ? error.message : String(error)}`,
69
- );
70
- return { timedOut: false };
71
- } finally {
72
- if (timer) clearTimeout(timer);
73
- }
74
- }
75
-
76
- function collectTextContent(content = []) {
77
- return content
78
- .filter((item) => item?.type === "text" && typeof item.text === "string")
79
- .map((item) => item.text)
80
- .join("\n")
81
- .trim();
82
- }
83
-
84
- function normalizeStructuredContent(structuredContent, fallbackText = "") {
85
- if (!structuredContent || typeof structuredContent !== "object") {
86
- return { threadId: null, content: fallbackText };
87
- }
88
-
89
- const threadId =
90
- typeof structuredContent.threadId === "string"
91
- ? structuredContent.threadId
92
- : null;
93
- const content =
94
- typeof structuredContent.content === "string"
95
- ? structuredContent.content
96
- : fallbackText;
97
-
98
- return { threadId, content };
99
- }
100
-
101
- /**
102
- * Read a top-level TOML scalar (`key = "value"` / `key = 'value'` /
103
- * `key = value`), tolerating an inline `# comment` and surrounding whitespace.
104
- * Returns the trimmed value, or null when the key is absent/empty. Intentionally
105
- * tiny — the per-profile files only carry `model` + `model_reasoning_effort`.
106
- *
107
- * @param {string} raw
108
- * @param {string} key
109
- * @returns {string|null}
110
- */
111
- function readTomlScalar(raw, key) {
112
- const re = new RegExp(
113
- `^\\s*${key}\\s*=\\s*(?:"([^"\\n]*)"|'([^'\\n]*)'|([^#\\n]*?))\\s*(?:#.*)?$`,
114
- "m",
115
- );
116
- const match = raw.match(re);
117
- if (!match) return null;
118
- const value = (match[1] ?? match[2] ?? match[3] ?? "").trim();
119
- return value || null;
120
- }
121
-
122
- /**
123
- * Resolve a Codex effort profile name (e.g. "gpt61_sol_high") to its concrete
124
- * `model` + reasoning effort. SSOT = the per-profile file written by
125
- * `tfx setup` at `~/.codex/<profile>.config.toml`. Falls back to deriving the
126
- * effort from the `<...>_<effort>` naming convention when the file is absent.
127
- *
128
- * codex 0.137 removed `profile` from the Codex MCP tool schema, so we translate
129
- * the profile into the still-accepted `model` + `config` fields instead of
130
- * forwarding `profile` (which now hard-fails with "unknown field `profile`").
131
- *
132
- * @param {string} profileName
133
- * @returns {{ model: string|null, reasoningEffort: string|null }}
134
- */
135
- export function resolveCodexProfileConfig(profileName) {
136
- const result = { model: null, reasoningEffort: null };
137
- if (typeof profileName !== "string" || !profileName) return result;
138
- const normalizedProfileName = normalizeCodexProfileName(profileName);
139
- if (!normalizedProfileName) return result;
140
-
141
- const codexHome = process.env.CODEX_HOME || join(homedir(), ".codex");
142
- try {
143
- const raw = readFileSync(
144
- join(codexHome, `${normalizedProfileName}.config.toml`),
145
- "utf8",
146
- );
147
- result.model = readTomlScalar(raw, "model");
148
- result.reasoningEffort = readTomlScalar(raw, "model_reasoning_effort");
149
- } catch {
150
- // Profile file absent (non-file alias). Derive effort from the naming
151
- // convention; leave model unset so codex uses its config.toml default.
152
- const suffix = /_(ultra|max|xhigh|high|med|medium|low)$/.exec(
153
- normalizedProfileName,
154
- );
155
- if (suffix) {
156
- const map = {
157
- ultra: "ultra",
158
- max: "max",
159
- xhigh: "xhigh",
160
- high: "high",
161
- med: "medium",
162
- medium: "medium",
163
- low: "low",
164
- };
165
- result.reasoningEffort = map[suffix[1]] || null;
166
- }
167
- }
168
- return result;
169
- }
170
-
171
- export function buildCodexArguments(prompt, opts = {}) {
172
- const args = { prompt };
173
-
174
- if (typeof opts.cwd === "string" && opts.cwd) args.cwd = opts.cwd;
175
- if (typeof opts.model === "string" && opts.model) args.model = opts.model;
176
- // NOTE: `profile` is intentionally NOT forwarded as a Codex tool argument.
177
- // codex 0.137 dropped it from the tool schema; it is resolved into
178
- // `model` + `config.model_reasoning_effort` just before return (see below).
179
- if (typeof opts.approvalPolicy === "string" && opts.approvalPolicy) {
180
- args["approval-policy"] = opts.approvalPolicy;
181
- }
182
- if (typeof opts.sandbox === "string" && opts.sandbox)
183
- args.sandbox = opts.sandbox;
184
- if (opts.config && typeof opts.config === "object") args.config = opts.config;
185
- if (typeof opts.baseInstructions === "string" && opts.baseInstructions) {
186
- args["base-instructions"] = opts.baseInstructions;
187
- }
188
- if (
189
- typeof opts.developerInstructions === "string" &&
190
- opts.developerInstructions
191
- ) {
192
- args["developer-instructions"] = opts.developerInstructions;
193
- }
194
- if (typeof opts.compactPrompt === "string" && opts.compactPrompt) {
195
- args["compact-prompt"] = opts.compactPrompt;
196
- }
197
-
198
- // Map the effort profile to model + reasoning effort instead of forwarding the
199
- // (0.137-rejected) `profile` field. Explicit opts.model wins over the profile;
200
- // profile effort merges on top of any opts.config.
201
- if (typeof opts.profile === "string" && opts.profile) {
202
- const resolved = resolveCodexProfileConfig(opts.profile);
203
- const profileDerivedUltra =
204
- resolved.reasoningEffort?.toLowerCase() === "ultra";
205
- if (typeof args.model !== "string") {
206
- if (profileDerivedUltra) args.model = "gpt-6-astra";
207
- else if (resolved.model) args.model = resolved.model;
208
- }
209
- if (resolved.reasoningEffort) {
210
- args.config = {
211
- ...(args.config || {}),
212
- model_reasoning_effort: profileDerivedUltra
213
- ? "max"
214
- : resolved.reasoningEffort,
215
- };
216
- }
217
- }
218
- if (typeof opts.reasoningEffort === "string" && opts.reasoningEffort) {
219
- args.config = {
220
- ...(args.config || {}),
221
- model_reasoning_effort: opts.reasoningEffort,
222
- };
223
- }
224
-
225
- return args;
226
- }
227
-
228
- function pickToolName(threadId) {
229
- return threadId ? "codex-reply" : "codex";
230
- }
231
-
232
- function withTimeout(promise, timeoutMs, message) {
233
- if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
234
- return promise;
235
- }
236
-
237
- let timer;
238
- const timeoutPromise = new Promise((_, reject) => {
239
- timer = setTimeout(() => {
240
- reject(new Error(message));
241
- }, timeoutMs);
242
- timer.unref?.();
243
- });
244
-
245
- return Promise.race([promise, timeoutPromise]).finally(() => {
246
- clearTimeout(timer);
247
- });
248
- }
249
-
250
- // Known noise-only output patterns from codex MCP that indicate transport failure
251
- // despite exitCode=0. Each entry is matched after trim() against the full output
252
- // string. Length cap is applied separately to avoid masking real responses that
253
- // happen to contain a noise substring as a header line.
254
- const NOISE_ONLY_OUTPUT_PATTERNS = Object.freeze([
255
- /^MCP issues detected\.\s*Run \/mcp list for status\.?$/i,
256
- ]);
257
- const NOISE_ONLY_MAX_BYTES = 256;
258
-
259
- function isNoiseOnlyOutput(text) {
260
- if (typeof text !== "string") return false;
261
- const trimmed = text.trim();
262
- if (!trimmed || trimmed.length > NOISE_ONLY_MAX_BYTES) return false;
263
- return NOISE_ONLY_OUTPUT_PATTERNS.some((pattern) => pattern.test(trimmed));
264
- }
265
-
266
- // MCP tool responses are completion-buffered, so stdout cannot distinguish an
267
- // active long-running call from a stuck one. The SDK delivers only genuine
268
- // `notifications/progress` callbacks here; append one record per event for
269
- // tfx-route's per-run heartbeat sidecar. This is intentionally best-effort:
270
- // inability to write observability data must never change tool execution.
271
- function recordMcpProgress(activityFile) {
272
- if (typeof activityFile !== "string" || !activityFile) return;
273
- try {
274
- appendFileSync(activityFile, "progress\n");
275
- } catch {
276
- // The route's liveness file is diagnostic only. A missing/readonly file
277
- // must leave the normal MCP request path untouched.
278
- }
279
- }
280
-
281
- function watchBootstrapClose(transport) {
282
- let active = true;
283
- const promise = new Promise((_, reject) => {
284
- const priorClose = transport.onclose;
285
- transport.onclose = () => {
286
- priorClose?.();
287
- if (active) {
288
- reject(new Error("Codex MCP transport closed during bootstrap"));
289
- }
290
- };
291
-
292
- const priorError = transport.onerror;
293
- transport.onerror = (error) => {
294
- priorError?.(error);
295
- if (active) {
296
- reject(error instanceof Error ? error : new Error(String(error)));
297
- }
298
- };
299
- });
300
-
301
- return {
302
- promise,
303
- stop() {
304
- active = false;
305
- },
306
- };
307
- }
308
-
309
- function watchBootstrapProcessExit(transport) {
310
- let active = true;
311
- let timer = null;
312
- let child = null;
313
-
314
- const promise = new Promise((_, reject) => {
315
- const rejectClosed = (code, signal) => {
316
- if (!active) return;
317
- const suffix = signal ? `signal ${signal}` : `exit ${code}`;
318
- reject(
319
- new Error(`Codex MCP transport closed during bootstrap (${suffix})`),
320
- );
321
- };
322
-
323
- timer = setInterval(() => {
324
- child = transport._process;
325
- if (!child) return;
326
- clearInterval(timer);
327
- timer = null;
328
- if (child.exitCode !== null || child.signalCode !== null) {
329
- rejectClosed(child.exitCode, child.signalCode);
330
- return;
331
- }
332
- child.once("close", rejectClosed);
333
- }, 10);
334
- });
335
-
336
- return {
337
- promise,
338
- stop() {
339
- active = false;
340
- if (timer) clearInterval(timer);
341
- child?.off?.("close", () => {});
342
- },
343
- };
344
- }
345
-
346
- function normalizeRetryOptions(retryOptions) {
347
- if (!retryOptions || typeof retryOptions !== "object") {
348
- return Object.freeze({});
349
- }
350
- return Object.freeze({ ...retryOptions });
351
- }
352
-
353
- function isCodexRetryable(error) {
354
- return (
355
- error instanceof CodexMcpTransportError ||
356
- error?.code === "ETIMEDOUT" ||
357
- error?.cause?.code === "ETIMEDOUT"
358
- );
359
- }
360
-
361
- function detectWorkerCategory(error, fallbackCategory = "transient") {
362
- const combined =
363
- `${error?.message || ""}\n${error?.stderr || ""}`.toLowerCase();
364
-
365
- if (error?.code === "INVALID_INPUT") return "input";
366
- if (
367
- /(unauthorized|forbidden|auth|login|token|credential|apikey|api key)/i.test(
368
- combined,
369
- )
370
- ) {
371
- return "auth";
372
- }
373
- if (
374
- /(config|unknown option|invalid option|missing|필수 mcp 도구 누락)/i.test(
375
- combined,
376
- )
377
- ) {
378
- return "config";
379
- }
380
-
381
- return fallbackCategory;
382
- }
383
-
384
- function buildCodexErrorInfo(error, attempts) {
385
- const retryable = isCodexRetryable(error);
386
- const code =
387
- error instanceof CodexMcpTransportError
388
- ? "CODEX_TRANSPORT_ERROR"
389
- : error?.code || "CODEX_EXECUTION_ERROR";
390
- const category = detectWorkerCategory(
391
- error,
392
- retryable ? "transient" : "config",
393
- );
394
-
395
- let recovery =
396
- "Review the Codex worker error output and retry after correcting the issue.";
397
- if (code === "INVALID_INPUT") {
398
- recovery = "Provide a non-empty prompt before invoking the Codex worker.";
399
- } else if (retryable) {
400
- recovery = "Retry after reconnecting the Codex MCP transport.";
401
- } else if (category === "auth") {
402
- recovery = "Refresh the Codex authentication state and retry.";
403
- } else if (category === "config") {
404
- recovery = "Check the Codex MCP configuration and available tools.";
405
- }
406
-
407
- return Object.freeze({
408
- code,
409
- retryable,
410
- attempts,
411
- category,
412
- recovery,
413
- });
414
- }
415
-
416
- /**
417
- * Codex MCP 워커
418
- */
419
- export class CodexMcpWorker {
420
- type = "codex";
421
-
422
- /**
423
- * @param {object} [options]
424
- * @param {string} [options.command]
425
- * @param {string[]} [options.args]
426
- * @param {string} [options.cwd]
427
- * @param {Record<string, string>} [options.env]
428
- * @param {{ name: string, version: string }} [options.clientInfo]
429
- * @param {number} [options.bootstrapTimeoutMs]
430
- */
431
- constructor(options = {}) {
432
- this.command = options.command || process.env.CODEX_BIN || "codex";
433
- this.args =
434
- Array.isArray(options.args) && options.args.length
435
- ? [...options.args]
436
- : ["mcp-server"];
437
- this.cwd = options.cwd || process.cwd();
438
- this.env = cloneEnv({ ...cloneEnv(process.env), ...cloneEnv(options.env) });
439
- this.clientInfo = options.clientInfo || {
440
- name: "triflux-codex-mcp",
441
- version: "1.0.0",
442
- };
443
- this.bootstrapTimeoutMs = Number.isFinite(options.bootstrapTimeoutMs)
444
- ? options.bootstrapTimeoutMs
445
- : DEFAULT_CODEX_MCP_BOOTSTRAP_TIMEOUT_MS;
446
- this.retryOptions = normalizeRetryOptions(options.retryOptions);
447
- this.activityFile =
448
- typeof options.activityFile === "string"
449
- ? options.activityFile
450
- : this.env.TFX_CODEX_MCP_ACTIVITY_FILE || "";
451
-
452
- this.client = null;
453
- this.transport = null;
454
- this.ready = false;
455
- this.availableTools = new Set();
456
- this.threadIds = new Map();
457
- this.serverStderr = "";
458
- }
459
-
460
- isReady() {
461
- return this.ready;
462
- }
463
-
464
- getThreadId(sessionKey) {
465
- return this.threadIds.get(sessionKey) || null;
466
- }
467
-
468
- setThreadId(sessionKey, threadId) {
469
- if (!sessionKey || !threadId) return;
470
- this.threadIds.set(sessionKey, threadId);
471
- }
472
-
473
- clearThread(sessionKey) {
474
- if (!sessionKey) return;
475
- this.threadIds.delete(sessionKey);
476
- }
477
-
478
- async start() {
479
- if (this.ready && this.client && this.transport) return;
480
-
481
- await this.stop();
482
-
483
- const transport = new StdioClientTransport({
484
- command: this.command,
485
- args: this.args,
486
- cwd: this.cwd,
487
- env: this.env,
488
- stderr: "pipe",
489
- });
490
- const client = new Client(this.clientInfo, { capabilities: {} });
491
-
492
- this.serverStderr = "";
493
- transport.stderr?.on("data", (chunk) => {
494
- this.serverStderr += String(chunk);
495
- if (this.serverStderr.length > 16000) {
496
- this.serverStderr = this.serverStderr.slice(-16000);
497
- }
498
- });
499
-
500
- try {
501
- const bootstrapClose = watchBootstrapClose(transport);
502
- const bootstrapProcessExit = watchBootstrapProcessExit(transport);
503
- await withTimeout(
504
- Promise.race([
505
- (async () => {
506
- await client.connect(transport);
507
- const tools = await client.listTools(undefined, {
508
- timeout: this.bootstrapTimeoutMs,
509
- });
510
- this.availableTools = new Set(tools.tools.map((tool) => tool.name));
511
-
512
- for (const requiredTool of REQUIRED_TOOLS) {
513
- if (!this.availableTools.has(requiredTool)) {
514
- throw new Error(`필수 MCP 도구 누락: ${requiredTool}`);
515
- }
516
- }
517
- })(),
518
- bootstrapClose.promise,
519
- bootstrapProcessExit.promise,
520
- ]).finally(() => {
521
- bootstrapClose.stop();
522
- bootstrapProcessExit.stop();
523
- }),
524
- this.bootstrapTimeoutMs,
525
- `Codex MCP bootstrap timeout (${this.bootstrapTimeoutMs}ms)`,
526
- );
527
- } catch (error) {
528
- await client.close().catch(() => {});
529
- transport.stderr?.destroy?.();
530
- throw new CodexMcpTransportError(
531
- `Codex MCP 연결 실패: ${error instanceof Error ? error.message : String(error)}`,
532
- { cause: error, stderr: this.serverStderr.trim() },
533
- );
534
- }
535
-
536
- this.client = client;
537
- this.transport = transport;
538
- this.ready = true;
539
- }
540
-
541
- async stop(options = {}) {
542
- this.ready = false;
543
- this.availableTools.clear();
544
-
545
- const client = this.client;
546
- const transport = this.transport;
547
- this.transport = null;
548
- this.client = null;
549
-
550
- const shutdownTimeoutMs = Number.isFinite(options.shutdownTimeoutMs)
551
- ? options.shutdownTimeoutMs
552
- : DEFAULT_CODEX_MCP_SHUTDOWN_TIMEOUT_MS;
553
-
554
- let clientCloseTimedOut = false;
555
- if (client) {
556
- const result = await closeWithin(
557
- "client.close",
558
- () => client.close(),
559
- shutdownTimeoutMs,
560
- );
561
- clientCloseTimedOut = Boolean(result.timedOut);
562
- }
563
-
564
- if (transport && (!client || clientCloseTimedOut)) {
565
- await closeWithin(
566
- "transport.close",
567
- () => transport.close(),
568
- shutdownTimeoutMs,
569
- );
570
- }
571
-
572
- transport?.stderr?.destroy?.();
573
- }
574
-
575
- /**
576
- * @param {string} prompt
577
- * @param {import('./interface.mjs').WorkerExecuteOptions} [opts]
578
- * @returns {Promise<import('./interface.mjs').WorkerResult>}
579
- */
580
- async execute(prompt, opts = {}) {
581
- if (typeof prompt !== "string" || !prompt.trim()) {
582
- return {
583
- output: "prompt는 비어 있을 수 없습니다.",
584
- exitCode: CODEX_MCP_EXECUTION_EXIT_CODE,
585
- threadId: null,
586
- sessionKey: opts.sessionKey || null,
587
- error: buildCodexErrorInfo(
588
- { code: "INVALID_INPUT", message: "prompt는 비어 있을 수 없습니다." },
589
- 0,
590
- ),
591
- raw: null,
592
- };
593
- }
594
-
595
- const sessionKey =
596
- typeof opts.sessionKey === "string" && opts.sessionKey
597
- ? opts.sessionKey
598
- : null;
599
-
600
- if (opts.resetSession && sessionKey) {
601
- this.clearThread(sessionKey);
602
- }
603
-
604
- const threadId =
605
- typeof opts.threadId === "string" && opts.threadId
606
- ? opts.threadId
607
- : sessionKey
608
- ? this.getThreadId(sessionKey)
609
- : null;
610
- const timeoutMs = Number.isFinite(opts.timeoutMs)
611
- ? opts.timeoutMs
612
- : DEFAULT_CODEX_MCP_TIMEOUT_MS;
613
- let attempts = 0;
614
- let activeThreadId = threadId;
615
-
616
- try {
617
- const { rawResult, normalized } = await withRetry(
618
- async () => {
619
- attempts += 1;
620
- if (attempts === 1) {
621
- await this.start();
622
- } else {
623
- await this.stop();
624
- await this.start();
625
- }
626
-
627
- const toolName = pickToolName(activeThreadId);
628
- const toolArguments =
629
- toolName === "codex-reply"
630
- ? { prompt, threadId: activeThreadId }
631
- : buildCodexArguments(prompt, opts);
632
-
633
- const nextRawResult = await this.client.callTool(
634
- { name: toolName, arguments: toolArguments },
635
- undefined,
636
- {
637
- timeout: timeoutMs,
638
- ...(this.activityFile
639
- ? { onprogress: () => recordMcpProgress(this.activityFile) }
640
- : {}),
641
- },
642
- );
643
-
644
- const textContent = collectTextContent(nextRawResult.content);
645
- const nextNormalized = normalizeStructuredContent(
646
- nextRawResult.structuredContent,
647
- textContent,
648
- );
649
- activeThreadId = nextNormalized.threadId || activeThreadId;
650
-
651
- return { rawResult: nextRawResult, normalized: nextNormalized };
652
- },
653
- {
654
- ...this.retryOptions,
655
- shouldRetry: (error) => isCodexRetryable(error),
656
- },
657
- );
658
-
659
- if (sessionKey && normalized.threadId) {
660
- this.setThreadId(sessionKey, normalized.threadId);
661
- }
662
-
663
- if (rawResult.isError) {
664
- return {
665
- output: normalized.content,
666
- exitCode: CODEX_MCP_EXECUTION_EXIT_CODE,
667
- threadId: normalized.threadId,
668
- sessionKey,
669
- error: buildCodexErrorInfo(
670
- { code: "CODEX_TOOL_ERROR", message: normalized.content },
671
- attempts,
672
- ),
673
- raw: rawResult,
674
- };
675
- }
676
-
677
- return {
678
- output: normalized.content,
679
- exitCode: 0,
680
- threadId: normalized.threadId,
681
- sessionKey,
682
- raw: rawResult,
683
- };
684
- } catch (error) {
685
- await this.stop().catch(() => {});
686
- return {
687
- output: error instanceof Error ? error.message : String(error),
688
- exitCode: CODEX_MCP_EXECUTION_EXIT_CODE,
689
- threadId: activeThreadId,
690
- sessionKey,
691
- error: buildCodexErrorInfo(error, attempts || 1),
692
- raw: null,
693
- };
694
- }
695
- }
696
- }
697
-
698
- export function createCodexMcpWorker(options = {}) {
699
- return new CodexMcpWorker(options);
700
- }
701
-
702
- function parseCliArgs(argv) {
703
- const options = {
704
- command: process.env.CODEX_BIN || "codex",
705
- cwd: process.cwd(),
706
- timeoutMs: DEFAULT_CODEX_MCP_TIMEOUT_MS,
707
- };
708
-
709
- for (let i = 0; i < argv.length; i += 1) {
710
- const token = argv[i];
711
- const next = () => {
712
- const value = argv[i + 1];
713
- if (value === undefined) {
714
- throw new Error(`${token} 값이 필요합니다.`);
715
- }
716
- i += 1;
717
- return value;
718
- };
719
-
720
- switch (token) {
721
- case "--prompt":
722
- options.prompt = next();
723
- break;
724
- case "--thread-id":
725
- options.threadId = next();
726
- break;
727
- case "--session-key":
728
- options.sessionKey = next();
729
- break;
730
- case "--cwd":
731
- options.cwd = next();
732
- break;
733
- case "--profile":
734
- options.profile = next();
735
- break;
736
- case "--model":
737
- options.model = next();
738
- break;
739
- case "--reasoning-effort":
740
- options.reasoningEffort = next();
741
- break;
742
- case "--approval-policy":
743
- options.approvalPolicy = next();
744
- break;
745
- case "--sandbox":
746
- options.sandbox = next();
747
- break;
748
- case "--base-instructions":
749
- options.baseInstructions = next();
750
- break;
751
- case "--developer-instructions":
752
- options.developerInstructions = next();
753
- break;
754
- case "--compact-prompt":
755
- options.compactPrompt = next();
756
- break;
757
- case "--timeout-ms":
758
- options.timeoutMs = Number.parseInt(next(), 10);
759
- break;
760
- case "--config-json":
761
- options.config = JSON.parse(next());
762
- break;
763
- case "--codex-command":
764
- options.command = next();
765
- break;
766
- case "--reset-session":
767
- options.resetSession = true;
768
- break;
769
- default:
770
- throw new Error(`알 수 없는 옵션: ${token}`);
771
- }
772
- }
773
-
774
- if (typeof options.prompt !== "string" || !options.prompt) {
775
- throw new Error("--prompt는 필수입니다.");
776
- }
777
-
778
- return options;
779
- }
780
-
781
- export async function runCodexMcpCli(argv = process.argv.slice(2)) {
782
- let options;
783
- try {
784
- options = parseCliArgs(argv);
785
- } catch (error) {
786
- console.error(
787
- `[codex-mcp] ${error instanceof Error ? error.message : String(error)}`,
788
- );
789
- process.exitCode = 64;
790
- return;
791
- }
792
-
793
- const worker = new CodexMcpWorker({
794
- command: options.command,
795
- cwd: options.cwd,
796
- retryOptions: { maxAttempts: 1 },
797
- });
798
-
799
- try {
800
- const result = await worker.execute(options.prompt, options);
801
- const hasOutput =
802
- typeof result.output === "string" && result.output.trim().length > 0;
803
- const noiseOnly = hasOutput && isNoiseOnlyOutput(result.output);
804
- if (hasOutput) {
805
- process.stdout.write(result.output);
806
- if (!result.output.endsWith("\n")) {
807
- process.stdout.write("\n");
808
- }
809
- }
810
- // Silent-success regression guard (codex 0.124.0+):
811
- // codex MCP can return exitCode=0 with empty/whitespace `output` when the
812
- // result-extraction path fails to read the assistant content from the MCP
813
- // response. Without this guard, tfx-route.sh sees STDOUT_LOG=0 bytes and
814
- // treats it as success — caller gets nothing back.
815
- // Promote to a transport failure so the wrapper falls back to `codex exec`.
816
- //
817
- // Noise-only guard (codex 0.125.0+, P2 swarm signature):
818
- // codex MCP can also return exitCode=0 with a short noise-only message like
819
- // "MCP issues detected. Run /mcp list for status." (~48 bytes) instead of
820
- // an actual response payload. trim().length > 0 passes the empty-output
821
- // check, so the previous guard misses this case. Pattern-match known noise
822
- // strings under a small length cap and promote to transport failure too.
823
- if (result.error?.code === "CODEX_TRANSPORT_ERROR") {
824
- process.exitCode = CODEX_MCP_TRANSPORT_EXIT_CODE;
825
- } else if (!hasOutput && result.exitCode === 0) {
826
- console.error(
827
- "[codex-mcp] WARNING: empty output with exit 0 — treating as transport failure (codex 0.124.0 silent-flush regression). Wrapper will fall back to exec path.",
828
- );
829
- process.exitCode = CODEX_MCP_TRANSPORT_EXIT_CODE;
830
- } else if (noiseOnly && result.exitCode === 0) {
831
- console.error(
832
- "[codex-mcp] WARNING: noise-only output (codex MCP error string without payload) with exit 0 — treating as transport failure. Wrapper will fall back to exec path.",
833
- );
834
- process.exitCode = CODEX_MCP_TRANSPORT_EXIT_CODE;
835
- } else {
836
- process.exitCode = result.exitCode;
837
- }
838
- } catch (error) {
839
- const lines = [error instanceof Error ? error.message : String(error)];
840
- if (error instanceof CodexMcpTransportError && error.stderr) {
841
- lines.push(error.stderr);
842
- }
843
- console.error(`[codex-mcp] ${lines.join("\n")}`);
844
- process.exitCode = CODEX_MCP_TRANSPORT_EXIT_CODE;
845
- } finally {
846
- await worker.stop();
847
- }
848
- }
849
-
850
- if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
851
- await runCodexMcpCli();
852
- process.exit(process.exitCode ?? 0);
853
- }