@triflux/remote 10.31.0 → 10.33.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.
@@ -0,0 +1,27 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+
4
+ function defaultLakeRoot() {
5
+ return join(process.cwd(), ".triflux", "lake");
6
+ }
7
+
8
+ /**
9
+ * Read the CTO north-star lake snapshot without affecting runtime control flow.
10
+ * @param {object} [opts]
11
+ * @param {string} [opts.lakeRoot] Directory containing current.json.
12
+ * @returns {object|null}
13
+ */
14
+ export function readCtoSnapshot(opts = {}) {
15
+ try {
16
+ const lakeRoot = opts.lakeRoot || defaultLakeRoot();
17
+ const parsed = JSON.parse(
18
+ readFileSync(join(lakeRoot, "current.json"), "utf8"),
19
+ );
20
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
21
+ return null;
22
+ }
23
+ return parsed;
24
+ } catch {
25
+ return null;
26
+ }
27
+ }
@@ -0,0 +1,607 @@
1
+ import { spawn } from "node:child_process";
2
+ import crypto from "node:crypto";
3
+ import { mkdtemp, rm, stat } from "node:fs/promises";
4
+ import net from "node:net";
5
+ import { tmpdir } from "node:os";
6
+ import { join as pathJoin } from "node:path";
7
+
8
+ import { execute as defaultExecuteCodex } from "@triflux/core/hub/codex-adapter.mjs";
9
+ import { JsonRpcWsUdsClient } from "../workers/lib/jsonrpc-ws-uds.mjs";
10
+ import {
11
+ buildClaudePromptDispatchPayload,
12
+ deriveClaudeDaemonPaths,
13
+ dispatchClaudeDaemonJob,
14
+ teardownClaudeDaemonJob,
15
+ } from "./claude-daemon-control.mjs";
16
+
17
+ const DEFAULT_TIMEOUT_MS = 90_000;
18
+ const DEFAULT_CODEX_APP_SERVER_UDS_TIMEOUT_MS = 120_000;
19
+ const DEFAULT_CODEX_APP_SERVER_UDS_BOOTSTRAP_MS = 12_000;
20
+
21
+ function requireEndpoint(endpoint, name) {
22
+ if (!endpoint || typeof endpoint.ask !== "function") {
23
+ throw new Error(`${name} endpoint with ask(prompt) is required`);
24
+ }
25
+ return endpoint;
26
+ }
27
+
28
+ function turn(endpoint, response, role) {
29
+ return {
30
+ role,
31
+ endpoint: response.endpoint || endpoint.name || role,
32
+ text: response.text || "",
33
+ done: response.done === true,
34
+ meta: response.meta || undefined,
35
+ };
36
+ }
37
+
38
+ function codexLeadPrompt(task) {
39
+ return `Lead as Codex. Create a concise plan for this task, then stop.\n\nTask:\n${task}`;
40
+ }
41
+
42
+ function claudeLeadPrompt(task) {
43
+ return `Lead as Claude. Create a concise plan for this task, then stop.\n\nTask:\n${task}`;
44
+ }
45
+
46
+ function claudeReviewCodexPrompt(task, codexPlan) {
47
+ return `Review Codex's plan for this task. Return risks and one improvement.\n\nTask:\n${task}\n\nCodex plan:\n${codexPlan}`;
48
+ }
49
+
50
+ function codexReviewClaudePrompt(task, claudePlan) {
51
+ return `Review Claude's plan for this task. Return risks and one improvement.\n\nTask:\n${task}\n\nClaude plan:\n${claudePlan}`;
52
+ }
53
+
54
+ function codexFinalPrompt(task, codexPlan, claudeReview) {
55
+ return `Finalize as Codex using Claude's review. Return the final orchestration decision.\n\nTask:\n${task}\n\nCodex plan:\n${codexPlan}\n\nClaude review:\n${claudeReview}`;
56
+ }
57
+
58
+ function claudeFinalPrompt(task, claudePlan, codexReview) {
59
+ return `Finalize as Claude using Codex's review. Return the final orchestration decision.\n\nTask:\n${task}\n\nClaude plan:\n${claudePlan}\n\nCodex review:\n${codexReview}`;
60
+ }
61
+
62
+ function peerPrompt(agentName, task) {
63
+ return `Act as a peer collaborator named ${agentName}. Independently answer this task in a concise way.\n\nTask:\n${task}`;
64
+ }
65
+
66
+ function peerSynthesisPrompt(task, claudeAnswer, codexAnswer) {
67
+ return `Synthesize peer answers from Claude and Codex. Return the agreed next action and conflicts.\n\nTask:\n${task}\n\nClaude answer:\n${claudeAnswer}\n\nCodex answer:\n${codexAnswer}`;
68
+ }
69
+
70
+ export async function runUdsOrchestration({ mode, task, claude, codex } = {}) {
71
+ const selectedMode = mode || "peer";
72
+ const claudeEndpoint = requireEndpoint(claude, "claude");
73
+ const codexEndpoint = requireEndpoint(codex, "codex");
74
+ if (!task || typeof task !== "string") throw new Error("task is required");
75
+
76
+ const turns = [];
77
+ if (selectedMode === "codex-led") {
78
+ const codexPlan = await codexEndpoint.ask(codexLeadPrompt(task), {
79
+ mode: selectedMode,
80
+ phase: "lead",
81
+ });
82
+ turns.push(turn(codexEndpoint, codexPlan, "lead"));
83
+
84
+ const claudeReview = await claudeEndpoint.ask(
85
+ claudeReviewCodexPrompt(task, codexPlan.text),
86
+ { mode: selectedMode, phase: "review" },
87
+ );
88
+ turns.push(turn(claudeEndpoint, claudeReview, "review"));
89
+
90
+ const final = await codexEndpoint.ask(
91
+ codexFinalPrompt(task, codexPlan.text, claudeReview.text),
92
+ { mode: selectedMode, phase: "final" },
93
+ );
94
+ turns.push(turn(codexEndpoint, final, "final"));
95
+ return { mode: selectedMode, task, turns, final: turns.at(-1) };
96
+ }
97
+
98
+ if (selectedMode === "claude-led") {
99
+ const claudePlan = await claudeEndpoint.ask(claudeLeadPrompt(task), {
100
+ mode: selectedMode,
101
+ phase: "lead",
102
+ });
103
+ turns.push(turn(claudeEndpoint, claudePlan, "lead"));
104
+
105
+ const codexReview = await codexEndpoint.ask(
106
+ codexReviewClaudePrompt(task, claudePlan.text),
107
+ { mode: selectedMode, phase: "review" },
108
+ );
109
+ turns.push(turn(codexEndpoint, codexReview, "review"));
110
+
111
+ const final = await claudeEndpoint.ask(
112
+ claudeFinalPrompt(task, claudePlan.text, codexReview.text),
113
+ { mode: selectedMode, phase: "final" },
114
+ );
115
+ turns.push(turn(claudeEndpoint, final, "final"));
116
+ return { mode: selectedMode, task, turns, final: turns.at(-1) };
117
+ }
118
+
119
+ if (selectedMode === "peer") {
120
+ const [claudePeer, codexPeer] = await Promise.all([
121
+ claudeEndpoint.ask(peerPrompt("Claude", task), {
122
+ mode: selectedMode,
123
+ phase: "peer",
124
+ }),
125
+ codexEndpoint.ask(peerPrompt("Codex", task), {
126
+ mode: selectedMode,
127
+ phase: "peer",
128
+ }),
129
+ ]);
130
+ turns.push(turn(claudeEndpoint, claudePeer, "peer"));
131
+ turns.push(turn(codexEndpoint, codexPeer, "peer"));
132
+
133
+ const final = await claudeEndpoint.ask(
134
+ peerSynthesisPrompt(task, claudePeer.text, codexPeer.text),
135
+ { mode: selectedMode, phase: "synthesis" },
136
+ );
137
+ turns.push(turn(claudeEndpoint, final, "synthesis"));
138
+ return { mode: selectedMode, task, turns, final: turns.at(-1) };
139
+ }
140
+
141
+ throw new Error(`Unsupported UDS orchestration mode: ${selectedMode}`);
142
+ }
143
+
144
+ function scanMessage(message, marker, state) {
145
+ const scan = (text) => {
146
+ state.streamBytes += Buffer.byteLength(text);
147
+ state.stream.push(text);
148
+ if (/⏺/.test(stripAnsi(text))) state.assistantStarted = true;
149
+ if (state.assistantStarted && text.includes(marker)) {
150
+ state.markerSeen = true;
151
+ }
152
+ };
153
+
154
+ state.messageCount += 1;
155
+ if (message.type === "snapshot") {
156
+ for (const line of message.streamTail || []) scan(line);
157
+ } else if (message.type === "stream" && typeof message.line === "string") {
158
+ scan(message.line);
159
+ } else if (message.type === "state") {
160
+ state.stateCount += 1;
161
+ } else if (message.type === "settled") {
162
+ state.settled = message.outcome || "settled";
163
+ }
164
+ }
165
+
166
+ export function subscribeClaudeUntilMarker(
167
+ controlSock,
168
+ short,
169
+ marker,
170
+ { timeoutMs = DEFAULT_TIMEOUT_MS } = {},
171
+ ) {
172
+ return new Promise((resolve) => {
173
+ const socket = net.connect(controlSock);
174
+ let data = "";
175
+ let finished = false;
176
+ const startedAt = Date.now();
177
+ const state = {
178
+ short,
179
+ marker,
180
+ markerSeen: false,
181
+ settled: null,
182
+ messageCount: 0,
183
+ stateCount: 0,
184
+ streamBytes: 0,
185
+ stream: [],
186
+ assistantStarted: false,
187
+ };
188
+ const timer = setTimeout(() => finish({ timedOut: true }), timeoutMs);
189
+
190
+ function finish(extra = {}) {
191
+ if (finished) return;
192
+ finished = true;
193
+ clearTimeout(timer);
194
+ socket.destroy();
195
+ resolve({ ...state, elapsedMs: Date.now() - startedAt, ...extra });
196
+ }
197
+
198
+ socket.on("error", (error) => finish({ error: error.message }));
199
+ socket.on("connect", () => {
200
+ socket.write(
201
+ `${JSON.stringify({ proto: 1, op: "subscribe", short, tail: 80, marker })}\n`,
202
+ );
203
+ });
204
+ socket.on("data", (chunk) => {
205
+ data += chunk.toString("utf8");
206
+ while (data.includes("\n")) {
207
+ const index = data.indexOf("\n");
208
+ const line = data.slice(0, index).trim();
209
+ data = data.slice(index + 1);
210
+ if (!line) continue;
211
+ try {
212
+ scanMessage(JSON.parse(line), marker, state);
213
+ } catch (_error) {
214
+ state.messageCount += 1;
215
+ }
216
+ if (state.markerSeen || state.settled) finish();
217
+ }
218
+ });
219
+ socket.on("close", () => finish({ closed: true }));
220
+ });
221
+ }
222
+
223
+ export function stripAnsi(text) {
224
+ return String(text)
225
+ .replace(/\x1B\][^\x07]*(?:\x07|\x1B\\)/g, "")
226
+ .replace(/\x1B[78]/g, "")
227
+ .replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g, "");
228
+ }
229
+
230
+ function isClaudeUdsNoiseLine(line) {
231
+ return (
232
+ /Claude Code|Opus|remote-control|Brewed|Baked|Cogitated|Crunched|▐|▛|▜|▝|▘|Max|context/.test(
233
+ line,
234
+ ) ||
235
+ /^[╭╮╰╯│─┌┐└┘├┤┬┴┼\s]+$/.test(line) ||
236
+ /^\s*[❯✳✻]\s*/.test(line)
237
+ );
238
+ }
239
+
240
+ export function extractClaudeUdsText(text, marker) {
241
+ const cleaned = stripAnsi(String(text).replaceAll(marker, "")).replace(
242
+ /\r/g,
243
+ "\n",
244
+ );
245
+ const lines = cleaned
246
+ .split("\n")
247
+ .map((line) => line.trimEnd())
248
+ .filter((line) => line.trim().length > 0);
249
+ const assistantIndex = lines.findLastIndex((line) => /^\s*⏺\s*/.test(line));
250
+ if (assistantIndex >= 0) {
251
+ const useful = lines
252
+ .slice(assistantIndex)
253
+ .map((line, index) => (index === 0 ? line.replace(/^\s*⏺\s*/, "") : line))
254
+ .filter((line) => !isClaudeUdsNoiseLine(line));
255
+ return useful.join("\n").trim();
256
+ }
257
+ const useful = lines.filter((line) => !isClaudeUdsNoiseLine(line));
258
+ return useful.at(-1)?.trim() || cleaned.trim();
259
+ }
260
+
261
+ export function createClaudeUdsEndpoint({
262
+ controlSock,
263
+ daemonPaths = deriveClaudeDaemonPaths(),
264
+ cwd = process.cwd(),
265
+ timeoutMs = DEFAULT_TIMEOUT_MS,
266
+ markerFactory = () =>
267
+ `TFX_UDS_ORCH_DONE_${crypto.randomBytes(6).toString("hex")}`,
268
+ shortFactory,
269
+ sessionIdFactory,
270
+ dispatchDaemonJob = dispatchClaudeDaemonJob,
271
+ teardownDaemonJob = teardownClaudeDaemonJob,
272
+ } = {}) {
273
+ const sock = controlSock || daemonPaths.controlSock;
274
+ return {
275
+ name: "claude-uds",
276
+ async ask(prompt, meta = {}) {
277
+ const marker = markerFactory();
278
+ const wrappedPrompt = `${prompt}\n\nWhen finished, print this exact completion marker on its own line: ${marker}`;
279
+ const name =
280
+ meta.name ||
281
+ `tfx uds ${meta.mode || "orchestration"} ${meta.phase || "ask"}`;
282
+ const payload = buildClaudePromptDispatchPayload({
283
+ short: shortFactory?.(),
284
+ sessionId: sessionIdFactory?.(),
285
+ cwd,
286
+ prompt: wrappedPrompt,
287
+ name,
288
+ });
289
+ const dispatch = await dispatchDaemonJob({
290
+ paths: daemonPaths,
291
+ controlSock: sock,
292
+ payload,
293
+ agent: "claude",
294
+ name,
295
+ cwd,
296
+ dispatchTimeoutMs: 5000,
297
+ });
298
+ const subscription = await subscribeClaudeUntilMarker(
299
+ sock,
300
+ payload.short,
301
+ marker,
302
+ { timeoutMs },
303
+ );
304
+ await teardownDaemonJob({
305
+ controlSock: sock,
306
+ paths: daemonPaths,
307
+ short: payload.short,
308
+ sessionProjectionPath: dispatch.sessionProjectionPath,
309
+ sessionId: payload.sessionId,
310
+ });
311
+ return {
312
+ endpoint: "claude-uds",
313
+ text: extractClaudeUdsText(subscription.stream.join(""), marker),
314
+ done: subscription.markerSeen === true,
315
+ dispatch,
316
+ subscription: {
317
+ markerSeen: subscription.markerSeen,
318
+ elapsedMs: subscription.elapsedMs,
319
+ messageCount: subscription.messageCount,
320
+ streamBytes: subscription.streamBytes,
321
+ timedOut: subscription.timedOut === true,
322
+ settled: subscription.settled,
323
+ },
324
+ cleanup: { ok: true },
325
+ meta: { short: payload.short, marker },
326
+ };
327
+ },
328
+ };
329
+ }
330
+
331
+ export function createCodexExecEndpoint({
332
+ executeCodex = defaultExecuteCodex,
333
+ workdir = process.cwd(),
334
+ timeout = 120_000,
335
+ profile,
336
+ } = {}) {
337
+ return {
338
+ name: "codex",
339
+ async ask(prompt) {
340
+ const result = await executeCodex({ prompt, workdir, timeout, profile });
341
+ if (result?.ok === false) {
342
+ throw new Error(
343
+ `Codex exec failed: ${result.stderr || result.error || "unknown error"}`,
344
+ );
345
+ }
346
+ return {
347
+ endpoint: "codex",
348
+ text: String(
349
+ result?.output ?? result?.stdout ?? result?.text ?? "",
350
+ ).trim(),
351
+ done: true,
352
+ };
353
+ },
354
+ };
355
+ }
356
+
357
+ function extractCodexThreadId(result) {
358
+ if (!result || typeof result !== "object") return null;
359
+ if (typeof result.threadId === "string") return result.threadId;
360
+ if (result.thread && typeof result.thread.id === "string") {
361
+ return result.thread.id;
362
+ }
363
+ return null;
364
+ }
365
+
366
+ async function waitForSocketFile(sockPath, deadlineMs) {
367
+ const start = Date.now();
368
+ while (Date.now() - start < deadlineMs) {
369
+ try {
370
+ if ((await stat(sockPath)).isSocket()) return true;
371
+ } catch {
372
+ /* not bound yet */
373
+ }
374
+ await new Promise((resolve) => setTimeout(resolve, 100));
375
+ }
376
+ return false;
377
+ }
378
+
379
+ /**
380
+ * SIGTERM a child, wait up to graceMs for it to actually exit, then SIGKILL if
381
+ * still alive. Liveness is `exitCode === null && signalCode === null` — NOT
382
+ * `child.killed`, which only means "a signal was sent" and would suppress the
383
+ * SIGKILL fallback when the child ignores SIGTERM.
384
+ * @param {import('node:child_process').ChildProcess} child
385
+ * @param {number} [graceMs]
386
+ */
387
+ async function terminateChild(child, graceMs = 1000) {
388
+ if (child.exitCode !== null || child.signalCode !== null) return;
389
+ const exited = new Promise((resolve) => {
390
+ child.once("exit", () => resolve("exited"));
391
+ });
392
+ try {
393
+ child.kill("SIGTERM");
394
+ } catch {}
395
+ const outcome = await Promise.race([
396
+ exited,
397
+ new Promise((resolve) => setTimeout(() => resolve("timeout"), graceMs)),
398
+ ]);
399
+ if (
400
+ outcome !== "exited" &&
401
+ child.exitCode === null &&
402
+ child.signalCode === null
403
+ ) {
404
+ try {
405
+ child.kill("SIGKILL");
406
+ } catch {}
407
+ }
408
+ }
409
+
410
+ /**
411
+ * Experimental Codex endpoint that drives a real `codex app-server` over its
412
+ * WebSocket-over-Unix-Domain-Socket control plane (the symmetric peer of the
413
+ * Claude daemon `control.sock` path). Same `ask(prompt) -> {endpoint,text,done}`
414
+ * contract as `createCodexExecEndpoint`, so it is a drop-in for
415
+ * `runUdsOrchestration`'s `codex` slot — but it is NOT the default.
416
+ *
417
+ * Two modes:
418
+ * - spawnServer (default): mkdtemp a private socket, spawn
419
+ * `codex app-server --listen unix://PATH`, attach, run one turn, tear down.
420
+ * - attach (socketPath + spawnServer=false): connect to an already-running
421
+ * daemon socket (e.g. $CODEX_HOME/app-server-control/app-server-control.sock).
422
+ *
423
+ * Wire transport proven against codex-cli 0.135.0 — see
424
+ * experiments/native-bridge-feasibility/codex-app-server-uds-smoke.mjs.
425
+ *
426
+ * @param {object} [options]
427
+ * @param {string|null} [options.socketPath] Existing daemon socket to attach to.
428
+ * @param {boolean} [options.spawnServer] Spawn a private app-server (default true).
429
+ * @param {string} [options.codexBin]
430
+ * @param {string} [options.cwd]
431
+ * @param {string} [options.model]
432
+ * @param {number} [options.timeoutMs] Turn timeout.
433
+ * @param {number} [options.bootstrapTimeoutMs] Connect + handshake timeout.
434
+ * @param {(opts: object) => JsonRpcWsUdsClient} [options.clientFactory]
435
+ * @param {(command: string, args: string[], options: object) => import('node:child_process').ChildProcess} [options.spawnFn]
436
+ */
437
+ export function createCodexAppServerUdsEndpoint({
438
+ socketPath = null,
439
+ spawnServer = true,
440
+ codexBin = process.env.CODEX_BIN || "codex",
441
+ cwd = process.cwd(),
442
+ model,
443
+ timeoutMs = DEFAULT_CODEX_APP_SERVER_UDS_TIMEOUT_MS,
444
+ bootstrapTimeoutMs = DEFAULT_CODEX_APP_SERVER_UDS_BOOTSTRAP_MS,
445
+ clientFactory = (opts) => new JsonRpcWsUdsClient(opts),
446
+ spawnFn = spawn,
447
+ } = {}) {
448
+ return {
449
+ name: "codex-app-server-uds",
450
+ async ask(prompt, _meta = {}) {
451
+ if (typeof prompt !== "string" || !prompt.trim()) {
452
+ throw new Error(
453
+ "codex-app-server-uds endpoint requires a non-empty prompt",
454
+ );
455
+ }
456
+
457
+ let dir = null;
458
+ let child = null;
459
+ let client = null;
460
+ let resolvedSock = socketPath;
461
+
462
+ try {
463
+ if (spawnServer && !socketPath) {
464
+ dir = await mkdtemp(pathJoin(tmpdir(), "tfx-codex-appserver-uds-"));
465
+ resolvedSock = pathJoin(dir, "app-server.sock");
466
+ child = spawnFn(
467
+ codexBin,
468
+ ["app-server", "--listen", `unix://${resolvedSock}`],
469
+ { stdio: ["ignore", "pipe", "pipe"], cwd, env: process.env },
470
+ );
471
+ let stderr = "";
472
+ child.stderr?.on("data", (chunk) => {
473
+ stderr += String(chunk);
474
+ if (stderr.length > 8000) stderr = stderr.slice(-8000);
475
+ });
476
+ const earlyExit = new Promise((resolve) => {
477
+ child.once("error", (err) =>
478
+ resolve(`spawn error: ${err.message}`),
479
+ );
480
+ child.once("exit", (code, sig) =>
481
+ resolve(`exited early code=${code} sig=${sig || ""}`),
482
+ );
483
+ });
484
+ const ready = await Promise.race([
485
+ waitForSocketFile(resolvedSock, bootstrapTimeoutMs).then((ok) =>
486
+ ok ? "ready" : "no-socket",
487
+ ),
488
+ earlyExit,
489
+ ]);
490
+ if (ready !== "ready") {
491
+ throw new Error(
492
+ `codex app-server did not bind socket: ${ready}${
493
+ stderr ? ` — ${stderr.slice(-400)}` : ""
494
+ }`,
495
+ );
496
+ }
497
+ }
498
+ if (!resolvedSock) {
499
+ throw new Error(
500
+ "codex-app-server-uds endpoint needs socketPath or spawnServer=true",
501
+ );
502
+ }
503
+
504
+ client = clientFactory({
505
+ socketPath: resolvedSock,
506
+ connectTimeoutMs: bootstrapTimeoutMs,
507
+ });
508
+ await client.connect();
509
+ await client.request(
510
+ "initialize",
511
+ { clientInfo: { name: "triflux-tfx-live", version: "1.0.0" } },
512
+ bootstrapTimeoutMs,
513
+ );
514
+ client.notify("initialized", {});
515
+
516
+ const threadParams = {
517
+ sandbox: "read-only",
518
+ approvalPolicy: "never",
519
+ ephemeral: true,
520
+ };
521
+ if (typeof model === "string" && model) threadParams.model = model;
522
+ if (cwd) threadParams.cwd = cwd;
523
+ const threadStart = await client.request(
524
+ "thread/start",
525
+ threadParams,
526
+ bootstrapTimeoutMs,
527
+ );
528
+ const threadId = extractCodexThreadId(threadStart);
529
+ if (!threadId) {
530
+ throw new Error(
531
+ "codex app-server thread/start returned no thread id",
532
+ );
533
+ }
534
+
535
+ const parts = [];
536
+ let offDelta = () => {};
537
+ let offError = () => {};
538
+ let offDone = () => {};
539
+ const cleanup = () => {
540
+ offDelta();
541
+ offError();
542
+ offDone();
543
+ };
544
+ const completion = new Promise((resolve) => {
545
+ offDelta = client.onNotification(
546
+ "item/agentMessage/delta",
547
+ (params) => {
548
+ if (typeof params?.delta === "string") parts.push(params.delta);
549
+ },
550
+ );
551
+ offError = client.onNotification("error", (params) => {
552
+ cleanup();
553
+ resolve({
554
+ status: "failed",
555
+ message: params?.message || "codex app-server error",
556
+ });
557
+ });
558
+ offDone = client.onNotification("turn/completed", (params) => {
559
+ cleanup();
560
+ resolve({ status: params?.turn?.status || "unknown" });
561
+ });
562
+ });
563
+
564
+ await client.request(
565
+ "turn/start",
566
+ { threadId, input: [{ type: "text", text: prompt }] },
567
+ timeoutMs,
568
+ );
569
+ let timeoutHandle = null;
570
+ const timeoutPromise = new Promise((resolve) => {
571
+ timeoutHandle = setTimeout(() => {
572
+ cleanup();
573
+ resolve({ status: "timeout" });
574
+ }, timeoutMs);
575
+ });
576
+ let settled;
577
+ try {
578
+ settled = await Promise.race([completion, timeoutPromise]);
579
+ } finally {
580
+ // Clear the timer whichever side won, so a completed turn does not
581
+ // keep the event loop alive until timeoutMs.
582
+ if (timeoutHandle) clearTimeout(timeoutHandle);
583
+ }
584
+
585
+ return {
586
+ endpoint: "codex-app-server-uds",
587
+ text: parts.join("").trim(),
588
+ done: settled.status === "completed",
589
+ meta: {
590
+ threadId,
591
+ status: settled.status,
592
+ socketPath: resolvedSock,
593
+ spawned: Boolean(child),
594
+ ...(settled.message ? { error: settled.message } : {}),
595
+ },
596
+ };
597
+ } finally {
598
+ try {
599
+ client?.close();
600
+ } catch {}
601
+ if (child) await terminateChild(child);
602
+ if (dir)
603
+ await rm(dir, { recursive: true, force: true }).catch(() => {});
604
+ }
605
+ },
606
+ };
607
+ }