codex-supervisor-mcp 0.13.5 → 0.13.6
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.
- package/package.json +18 -63
- package/src/{acceptance.js → app/acceptance.js} +54 -68
- package/src/app/cancel.js +60 -0
- package/src/{cleanup-plan.js → app/cleanup-plan.js} +11 -12
- package/src/app/compose.js +7 -0
- package/src/{context-compiler.js → app/context-compiler.js} +7 -13
- package/src/app/dispatch.js +396 -0
- package/src/app/followup.js +98 -0
- package/src/app/land-chain.js +124 -0
- package/src/app/landing.js +357 -0
- package/src/app/ownership.js +57 -0
- package/src/app/rebase.js +216 -0
- package/src/app/resume.js +164 -0
- package/src/app/run-state.js +26 -0
- package/src/app/settled.js +28 -0
- package/src/{side-chat.js → app/side-chat.js} +79 -265
- package/src/app/sse.js +20 -0
- package/src/app/start-run.js +77 -0
- package/src/app/verify-push.js +119 -0
- package/src/app/worktree-setup.js +176 -0
- package/src/{acceptance-baseline.js → domain/acceptance-baseline.js} +2 -1
- package/src/domain/acceptance-spec.js +30 -0
- package/src/domain/command-outcome.js +6 -0
- package/src/{overview-delta.js → domain/overview-delta.js} +5 -1
- package/src/domain/side-turn-view.js +73 -0
- package/src/{worker-preflight.js → domain/worker-preflight.js} +1 -1
- package/src/infra/git.js +30 -0
- package/src/infra/process.js +59 -0
- package/src/{sandbox-roots.js → infra/sandbox-roots.js} +2 -1
- package/src/{skill-sync.js → infra/skill-sync.js} +1 -1
- package/src/infra/store/db.js +265 -0
- package/src/infra/store/events.js +146 -0
- package/src/infra/store/facts.js +338 -0
- package/src/infra/store/reconcile.js +172 -0
- package/src/infra/store/records.js +160 -0
- package/src/infra/store/runner-readers.js +16 -0
- package/src/infra/store/schema.js +306 -0
- package/src/infra/store/sessions.js +138 -0
- package/src/infra/store/tasks.js +307 -0
- package/src/{auto-update-worker.js → infra/update/auto-update-worker.js} +4 -4
- package/src/{auto-update.js → infra/update/auto-update.js} +3 -3
- package/src/{update-check.js → infra/update/update-check.js} +4 -4
- package/src/{workspace-kind.js → infra/workspace-kind.js} +5 -7
- package/src/{worktree.js → infra/worktree.js} +56 -41
- package/src/{acceptance-cli.js → interface/bin/acceptance-cli.js} +7 -3
- package/src/{cleanup.js → interface/bin/cleanup.js} +3 -2
- package/src/{monitor.jsx → interface/bin/monitor.jsx} +4 -1
- package/src/{setup.js → interface/bin/setup.js} +7 -6
- package/src/{stage.js → interface/bin/stage.js} +1 -1
- package/src/{web-server.js → interface/bin/web-server.js} +2 -2
- package/src/interface/mcp/meta.js +7 -0
- package/src/interface/mcp/result.js +34 -0
- package/src/interface/mcp/schemas.js +24 -0
- package/src/interface/mcp/server.js +94 -0
- package/src/interface/mcp/tools/delivery.js +197 -0
- package/src/interface/mcp/tools/dispatch.js +267 -0
- package/src/interface/mcp/tools/facts.js +239 -0
- package/src/interface/mcp/tools/overview.js +202 -0
- package/src/interface/mcp/tools/poll.js +62 -0
- package/src/interface/mcp/tools/results.js +270 -0
- package/src/interface/mcp/tools/review.js +135 -0
- package/src/interface/mcp/tools/wait.js +145 -0
- package/src/interface/mcp/update-state.js +34 -0
- package/src/interface/mcp/views/overview.js +183 -0
- package/src/interface/mcp/views/task.js +223 -0
- package/src/interface/web/app.js +226 -0
- package/src/interface/web/views.js +224 -0
- package/src/mcp-server.js +3 -2223
- package/src/run-host/entry.js +23 -0
- package/src/run-host/finalize.js +236 -0
- package/src/run-host/launch.js +63 -0
- package/src/run-host/live-run.js +73 -0
- package/src/run-host/outcome-facts.js +61 -0
- package/src/run-host/streams.js +76 -0
- package/src/run-host/track.js +128 -0
- package/src/{runner-adapter.js → runners/codex/adapter.js} +6 -6
- package/src/runners/codex/chat-chunks.js +97 -0
- package/src/{event-parser.js → runners/codex/event-parser.js} +57 -55
- package/src/{goal-store.js → runners/codex/goal-store.js} +2 -2
- package/src/{mcp-config.js → runners/codex/mcp-config.js} +1 -1
- package/src/codex-runner.js +0 -1586
- package/src/landing.js +0 -507
- package/src/task-store.js +0 -1800
- package/src/web-app.js +0 -425
- /package/src/{failure-class.js → domain/failure-class.js} +0 -0
- /package/src/{owned-changes.js → domain/owned-changes.js} +0 -0
- /package/src/{prompt.js → domain/prompt.js} +0 -0
- /package/src/{status.js → domain/status.js} +0 -0
- /package/src/{thread-health.js → domain/thread-health.js} +0 -0
- /package/src/{truncate.js → domain/truncate.js} +0 -0
- /package/src/{worker-changes.js → domain/worker-changes.js} +0 -0
- /package/src/{worker-env.js → domain/worker-env.js} +0 -0
- /package/src/{worker-report.js → domain/worker-report.js} +0 -0
- /package/src/{worker-report.schema.json → domain/worker-report.schema.json} +0 -0
- /package/src/{bin-resolver.js → infra/bin-resolver.js} +0 -0
- /package/src/{cleanup-hint.js → infra/cleanup-hint.js} +0 -0
- /package/src/{external-output.js → infra/external-output.js} +0 -0
- /package/src/{handoff.js → infra/handoff.js} +0 -0
- /package/src/{paths.js → infra/paths.js} +0 -0
- /package/src/{stage-store.js → infra/stage-store.js} +0 -0
- /package/src/{tool-guard.js → runners/codex/tool-guard.js} +0 -0
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import "./compose.js";
|
|
2
|
+
import { frameWorkerPrompt } from "../domain/prompt.js";
|
|
3
|
+
import { ACTIVE_STATUSES } from "../domain/status.js";
|
|
4
|
+
import { buildHandoff } from "../infra/handoff.js";
|
|
5
|
+
import { appendTaskEvent } from "../infra/store/events.js";
|
|
6
|
+
import { getSession } from "../infra/store/sessions.js";
|
|
7
|
+
import { claimTaskRun, getTask, readTasks, releaseTaskRun, upsertTask } from "../infra/store/tasks.js";
|
|
8
|
+
import { codexRunner } from "../runners/codex/adapter.js";
|
|
9
|
+
import { readNativeGoalState } from "../runners/codex/goal-store.js";
|
|
10
|
+
import { DEFAULT_ACCEPTANCE_TIMEOUT_MS, normalizeAcceptance } from "./acceptance.js";
|
|
11
|
+
import { isPidAlive } from "./cancel.js";
|
|
12
|
+
import { rebaseWorktree } from "./rebase.js";
|
|
13
|
+
import { processes } from "./run-state.js";
|
|
14
|
+
import { startTrackedRun } from "./start-run.js";
|
|
15
|
+
import { exists, resolveCommit } from "./worktree-setup.js";
|
|
16
|
+
import { appendFile } from "node:fs/promises";
|
|
17
|
+
|
|
18
|
+
// Continue the *same* Codex session. The worktree, thread id, ownership and
|
|
19
|
+
// goal are all inherited from the original task, and the row is reused so one
|
|
20
|
+
// logical piece of work stays one row.
|
|
21
|
+
//
|
|
22
|
+
// `rebaseOnto` names a ref, resolved in the project directory (HEAD, main, a
|
|
23
|
+
// sha): the worktree is moved onto it first so the worker continues on
|
|
24
|
+
// current code, and base_commit is recorded before the worker starts so a
|
|
25
|
+
// spawn failure cannot leave the row describing the old base. A rebase that
|
|
26
|
+
// does not go through puts the worktree back and throws with the file list;
|
|
27
|
+
// the worker is not started. Refused while the worker is still running.
|
|
28
|
+
function coded(code, message, details = undefined) {
|
|
29
|
+
const error = new Error(message);
|
|
30
|
+
error.code = code;
|
|
31
|
+
if (details !== undefined) error.details = details;
|
|
32
|
+
return error;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// `acceptance` replaces the stored commands when given; an empty list
|
|
36
|
+
// clears them. Left out, the stored commands stay.
|
|
37
|
+
async function refreshAcceptance(task, session, acceptance) {
|
|
38
|
+
const inheritedAcceptance = task.session_policy_revision == null ? task.acceptance : task.acceptance_local;
|
|
39
|
+
const localAcceptance = acceptance === undefined ? inheritedAcceptance : normalizeAcceptance(acceptance);
|
|
40
|
+
if (acceptance === undefined && !session) return task;
|
|
41
|
+
const commands = normalizeAcceptance([...(session?.default_acceptance ?? []), ...(localAcceptance ?? [])]);
|
|
42
|
+
const updated = {
|
|
43
|
+
...task,
|
|
44
|
+
acceptance: commands,
|
|
45
|
+
acceptance_local: localAcceptance,
|
|
46
|
+
session_policy_revision: session?.policy_revision ?? null,
|
|
47
|
+
acceptance_timeout_ms: commands ? (task.acceptance_timeout_ms ?? DEFAULT_ACCEPTANCE_TIMEOUT_MS) : null,
|
|
48
|
+
updated_at: new Date().toISOString()
|
|
49
|
+
};
|
|
50
|
+
await upsertTask(updated);
|
|
51
|
+
return updated;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// Moves the worktree onto a newer base before the worker continues. A conflict
|
|
55
|
+
// is thrown back with the details and no worker is started.
|
|
56
|
+
async function rebaseBeforeResume(task, rebaseOnto) {
|
|
57
|
+
if (ACTIVE_STATUSES.has(task.status) || processes.has(task.id)) {
|
|
58
|
+
throw coded("worker_active", `task ${task.id} is still ${task.status}; wait for it to settle (or cancel it) before rebasing its worktree`);
|
|
59
|
+
}
|
|
60
|
+
if (!task.worktree_path) throw coded("no_worktree", `task ${task.id} ran in place and has no worktree to rebase`);
|
|
61
|
+
let ontoCommit;
|
|
62
|
+
try {
|
|
63
|
+
ontoCommit = resolveCommit(task.project_root, rebaseOnto);
|
|
64
|
+
} catch {
|
|
65
|
+
throw coded("invalid_rebase_onto", `rebaseOnto "${rebaseOnto}" does not resolve to a commit in ${task.project_root}`);
|
|
66
|
+
}
|
|
67
|
+
const rebase = rebaseWorktree(task, ontoCommit);
|
|
68
|
+
if (rebase.error) throw coded(rebase.error, rebase.reason, rebase);
|
|
69
|
+
if (rebase.noop || rebase.base_commit === task.base_commit) return { task, rebase };
|
|
70
|
+
const moved = { ...task, base_commit: rebase.base_commit, updated_at: new Date().toISOString() };
|
|
71
|
+
await upsertTask(moved);
|
|
72
|
+
return { task: moved, rebase };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// Only a thread with no native goal, or one explicitly stored as complete,
|
|
76
|
+
// can safely resume with a structured output schema. Paused, blocked,
|
|
77
|
+
// usage-limited and budget-limited goals are not complete; Codex can still
|
|
78
|
+
// activate their goal turn and reject the incompatible schema.
|
|
79
|
+
function resumeAllowsOutputSchema(threadId) {
|
|
80
|
+
const goalRead = readNativeGoalState(threadId);
|
|
81
|
+
return ["missing_goal", "missing_database"].includes(goalRead.state)
|
|
82
|
+
|| (goalRead.state === "available" && goalRead.goal?.storage_status === "complete");
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
async function resumeClaimed(claimed, { prompt, rebaseOnto, acceptance }) {
|
|
86
|
+
const session = claimed.session_id ? await getSession(claimed.session_id) : null;
|
|
87
|
+
if (session?.approval_state === "waiting_user") throw coded("session_waiting_user", "session is waiting for user approval; do not resume");
|
|
88
|
+
let task = await refreshAcceptance(claimed, session, acceptance);
|
|
89
|
+
if (!task.thread_id) {
|
|
90
|
+
throw new Error(
|
|
91
|
+
`task ${task.id} has no Codex thread_id recorded. Only workers created by this version of codex-supervisor-mcp can be resumed; use create_codex_followup_worker otherwise.`
|
|
92
|
+
);
|
|
93
|
+
}
|
|
94
|
+
let rebase = null;
|
|
95
|
+
if (rebaseOnto) ({ task, rebase } = await rebaseBeforeResume(task, rebaseOnto));
|
|
96
|
+
|
|
97
|
+
const cwd = (await exists(task.cwd)) ? task.cwd : task.project_root;
|
|
98
|
+
const args = codexRunner.resumeArgs(task);
|
|
99
|
+
const outputSchema = resumeAllowsOutputSchema(task.thread_id);
|
|
100
|
+
const started = await startTrackedRun({
|
|
101
|
+
record: { ...task, resumed_from: task.resumed_from ?? task.id },
|
|
102
|
+
args,
|
|
103
|
+
prompt: frameWorkerPrompt(prompt, {
|
|
104
|
+
objective: task.goal_objective ?? task.title ?? task.id,
|
|
105
|
+
resume: true
|
|
106
|
+
}, { acceptance: task.acceptance, outputSchema }),
|
|
107
|
+
logPath: task.run_log,
|
|
108
|
+
outputSchema,
|
|
109
|
+
spawnOptions: { cwd }
|
|
110
|
+
});
|
|
111
|
+
return rebase ? { ...started.record, rebase } : started.record;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export async function resumeCodexWorker({ taskId, prompt, rebaseOnto = null, acceptance = undefined, context = undefined }) {
|
|
115
|
+
if (!prompt || typeof prompt !== "string") throw new Error("prompt is required");
|
|
116
|
+
let task = await getTask(taskId);
|
|
117
|
+
if (!task) throw new Error(`task not found: ${taskId}`);
|
|
118
|
+
if (task.guard_policy?.maxTotalMs && Date.now() - Date.parse(task.created_at) >= task.guard_policy.maxTotalMs) {
|
|
119
|
+
throw coded("time_quota_exceeded", "total time quota exceeded; inspect partial work and explicitly dispatch a revised budget");
|
|
120
|
+
}
|
|
121
|
+
if (context !== undefined) {
|
|
122
|
+
await buildHandoff({ context });
|
|
123
|
+
task = { ...task, input_context: { ...task.input_context, context } };
|
|
124
|
+
}
|
|
125
|
+
const claim = await claimTaskRun(taskId, task.run_count ?? 0);
|
|
126
|
+
if (!claim) throw coded("worker_active", `task ${taskId} is active or already claimed by another dispatcher; wait for it to settle`);
|
|
127
|
+
try {
|
|
128
|
+
return await resumeClaimed(task, { prompt, rebaseOnto, acceptance });
|
|
129
|
+
} finally {
|
|
130
|
+
await releaseTaskRun(taskId, claim);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export async function recoverEligibleRuns() {
|
|
135
|
+
const recovered = [];
|
|
136
|
+
for (const task of await readTasks()) {
|
|
137
|
+
if (task.guard_policy?.preflight) continue;
|
|
138
|
+
if ((task.run_count ?? 0) !== 1 || !task.thread_id
|
|
139
|
+
|| !(task.run_evidence?.run === 1 || (task.run_host_pid && task.started_at)) || !task.guard_policy
|
|
140
|
+
|| !(task.status === "lost" || task.attention_reason === "no_work" || task.attention_reason === "invalid_report")
|
|
141
|
+
|| ["blocked", "paused", "budget_limited", "usage_limited"].includes(task.goal_status)
|
|
142
|
+
|| /401|403|unauthori[sz]ed|not logged|permission denied|approval|rate.?limit|429/i.test(task.error ?? "")
|
|
143
|
+
|| /time_limit|quota/.test(`${task.attention_reason ?? ""} ${task.error ?? ""}`)
|
|
144
|
+
|| await isPidAlive(task.pid) || await isPidAlive(task.run_host_pid)) continue;
|
|
145
|
+
const session = task.session_id ? await getSession(task.session_id) : null;
|
|
146
|
+
if (session?.approval_state === "waiting_user") continue;
|
|
147
|
+
try {
|
|
148
|
+
const result = await resumeCodexWorker({ taskId: task.id,
|
|
149
|
+
prompt: task.attention_reason === "invalid_report"
|
|
150
|
+
? "Your run finished, but the final message was not the required bare JSON report. Do not redo the work and do not edit files: reply with ONLY the JSON object with result (string), verification (string[]) and not_done (string[]), describing what you already did. No code fences, nothing before or after it."
|
|
151
|
+
: `One automatic recovery after ${task.attention_reason ?? task.status}. Original task: ${task.prompt}\nContinue from files already present; do not repeat completed edits. Make concrete progress, run declared checks, and report remaining blockers accurately. This is the only automatic retry.` });
|
|
152
|
+
const event = { type: "supervisor.recovery", automatic: true, from_run: 1, to_run: result.run_count,
|
|
153
|
+
reason: task.attention_reason ?? task.status, started_at: new Date().toISOString() };
|
|
154
|
+
await appendTaskEvent(task.id, event);
|
|
155
|
+
await appendFile(task.run_log, `${JSON.stringify(event)}\n`);
|
|
156
|
+
recovered.push({ id: task.id, run: result.run_count, reason: event.reason });
|
|
157
|
+
} catch (error) {
|
|
158
|
+
if (!["worker_active", "session_waiting_user"].includes(error.code)) {
|
|
159
|
+
await appendTaskEvent(task.id, { type: "supervisor.recovery_refused", reason: error.code ?? "resume_failed" });
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
return recovered;
|
|
164
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
|
|
2
|
+
export const processes = new Map();
|
|
3
|
+
// taskId -> control object of an acceptance run in progress ({ kill, cancelled }).
|
|
4
|
+
export const acceptanceRuns = new Map();
|
|
5
|
+
export const cancelledTasks = new Set();
|
|
6
|
+
export const allowedReasoningEfforts = new Set(["minimal", "low", "medium", "high"]);
|
|
7
|
+
export const MAX_RUN_HOST_PROMPT_BYTES = 4 * 1024 * 1024;
|
|
8
|
+
export const RUN_HOST_STARTUP_TIMEOUT_MS = process.platform === "win32" ? 120000 : 30000;
|
|
9
|
+
export const WORKTREE_LOCK_TIMEOUT_MS = 120000;
|
|
10
|
+
|
|
11
|
+
export function failedStart(record, reason) {
|
|
12
|
+
const now = new Date().toISOString();
|
|
13
|
+
return {
|
|
14
|
+
ok: false,
|
|
15
|
+
record: {
|
|
16
|
+
...record,
|
|
17
|
+
status: "failed",
|
|
18
|
+
phase: null,
|
|
19
|
+
pid: null,
|
|
20
|
+
error: reason,
|
|
21
|
+
attention_reason: "start_failed",
|
|
22
|
+
completed_at: now,
|
|
23
|
+
updated_at: now
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import "./compose.js";
|
|
2
|
+
import { readPreflightResult } from "../domain/worker-preflight.js";
|
|
3
|
+
import { TERMINAL_STATUSES } from "../domain/status.js";
|
|
4
|
+
import { isPidAlive } from "../infra/store/tasks.js";
|
|
5
|
+
|
|
6
|
+
// A terminal status is written in two steps. Codex's turn.completed event
|
|
7
|
+
// flips status to completed while the process is still alive and exit_code is
|
|
8
|
+
// still null; the process exit then writes exit_code. A wait that returned on
|
|
9
|
+
// the first step handed the caller a snapshot with exit_code: null, and the
|
|
10
|
+
// next read said 0 - two answers for one worker. A row counts as settled once
|
|
11
|
+
// the exit is recorded, or once nobody is left to record it.
|
|
12
|
+
export function isSettled(task) {
|
|
13
|
+
if (!TERMINAL_STATUSES.has(task.status)) return false;
|
|
14
|
+
if (task.attention_reason === "start_failed") return true;
|
|
15
|
+
if (task.guard_policy?.preflight && readPreflightResult(task).status === "passed") return true;
|
|
16
|
+
if (task.status !== "completed" && task.status !== "failed") return true;
|
|
17
|
+
// Acceptance is running in the supervisor process that owned the worker;
|
|
18
|
+
// the codex pid is already dead, so that process is what to wait on.
|
|
19
|
+
if (task.acceptance_results?.status === "running") return !isPidAlive(task.acceptance_results.supervisor_pid);
|
|
20
|
+
if (["interrupted", "cancelled"].includes(task.acceptance_results?.status)) {
|
|
21
|
+
return task.exit_code !== null && task.exit_code !== undefined;
|
|
22
|
+
}
|
|
23
|
+
if (task.exit_code !== null && task.exit_code !== undefined) return true;
|
|
24
|
+
// A dead Codex pid does not prove that its owner's close handler finished
|
|
25
|
+
// draining the stream and writing the exit status. Leave the half-written
|
|
26
|
+
// row for reconciliation after a short grace period, never return it.
|
|
27
|
+
return false;
|
|
28
|
+
}
|
|
@@ -22,19 +22,14 @@
|
|
|
22
22
|
// turn failed / timed out / stopped error on the turn, session still usable
|
|
23
23
|
// board restarted mid-turn ........ turn marked interrupted
|
|
24
24
|
// session ended ................... fork deleted, history cleared
|
|
25
|
+
import "./compose.js";
|
|
26
|
+
import { answerOf, partsFromChunks, turnView } from "../domain/side-turn-view.js";
|
|
27
|
+
import { closeSideSession, getSideSession, insertSideTurn, interruptRunningSideTurns, openSideSession, readSideTurns, setSideSessionFork, updateSideTurn } from "../infra/store/sessions.js";
|
|
28
|
+
import { codexRunner } from "../runners/codex/adapter.js";
|
|
29
|
+
import { chunksFor } from "../runners/codex/chat-chunks.js";
|
|
30
|
+
import { codexConfigText, disableMcpServerArgs } from "../runners/codex/mcp-config.js";
|
|
31
|
+
import { endStream, sseHead, writeChunk } from "./sse.js";
|
|
25
32
|
import { randomUUID } from "node:crypto";
|
|
26
|
-
import { codexConfigText, disableMcpServerArgs } from "./mcp-config.js";
|
|
27
|
-
import { codexRunner } from "./runner-adapter.js";
|
|
28
|
-
import {
|
|
29
|
-
closeSideSession,
|
|
30
|
-
getSideSession,
|
|
31
|
-
insertSideTurn,
|
|
32
|
-
interruptRunningSideTurns,
|
|
33
|
-
openSideSession,
|
|
34
|
-
readSideTurns,
|
|
35
|
-
setSideSessionFork,
|
|
36
|
-
updateSideTurn
|
|
37
|
-
} from "./task-store.js";
|
|
38
33
|
|
|
39
34
|
const TURN_TIMEOUT_MS = 10 * 60 * 1000;
|
|
40
35
|
|
|
@@ -90,7 +85,6 @@ export async function prepareSideSession(task, { fresh = false } = {}) {
|
|
|
90
85
|
}
|
|
91
86
|
return { session, refreshed };
|
|
92
87
|
}
|
|
93
|
-
const OUTPUT_CLIP = 4000;
|
|
94
88
|
|
|
95
89
|
// taskId -> { turnId, child, chunks, watchers: Set<res>, startedAt, question, state }
|
|
96
90
|
const running = new Map();
|
|
@@ -102,168 +96,6 @@ async function sweepOnce() {
|
|
|
102
96
|
await interruptRunningSideTurns();
|
|
103
97
|
}
|
|
104
98
|
|
|
105
|
-
function clip(text, max = OUTPUT_CLIP) {
|
|
106
|
-
if (typeof text !== "string") return text ?? null;
|
|
107
|
-
return text.length <= max ? text : `${text.slice(0, max)}\n…(${text.length - max} more characters)`;
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
// ---- Codex event -> UI message stream chunks
|
|
111
|
-
|
|
112
|
-
function chunksFor(event, state) {
|
|
113
|
-
const item = event.item ?? {};
|
|
114
|
-
const out = [];
|
|
115
|
-
switch (event.type) {
|
|
116
|
-
case "thread.started":
|
|
117
|
-
if (event.thread_id) out.push({ type: "data-session", data: { fork_thread_id: event.thread_id } });
|
|
118
|
-
break;
|
|
119
|
-
case "turn.started":
|
|
120
|
-
out.push({ type: "start-step" });
|
|
121
|
-
break;
|
|
122
|
-
case "item.started":
|
|
123
|
-
case "item.updated":
|
|
124
|
-
if (item.type === "command_execution" && !state.toolsSeen.has(item.id)) {
|
|
125
|
-
state.toolsSeen.add(item.id);
|
|
126
|
-
out.push({ type: "tool-input-available", toolCallId: item.id, toolName: "shell", input: { command: item.command ?? "" } });
|
|
127
|
-
}
|
|
128
|
-
break;
|
|
129
|
-
case "item.completed":
|
|
130
|
-
switch (item.type) {
|
|
131
|
-
case "reasoning": {
|
|
132
|
-
const id = `r-${item.id}`;
|
|
133
|
-
out.push({ type: "reasoning-start", id }, { type: "reasoning-delta", id, delta: item.text ?? "" }, { type: "reasoning-end", id });
|
|
134
|
-
break;
|
|
135
|
-
}
|
|
136
|
-
case "agent_message": {
|
|
137
|
-
const id = `t-${item.id}`;
|
|
138
|
-
out.push({ type: "text-start", id }, { type: "text-delta", id, delta: item.text ?? "" }, { type: "text-end", id });
|
|
139
|
-
break;
|
|
140
|
-
}
|
|
141
|
-
case "command_execution":
|
|
142
|
-
if (!state.toolsSeen.has(item.id)) {
|
|
143
|
-
state.toolsSeen.add(item.id);
|
|
144
|
-
out.push({ type: "tool-input-available", toolCallId: item.id, toolName: "shell", input: { command: item.command ?? "" } });
|
|
145
|
-
}
|
|
146
|
-
out.push({
|
|
147
|
-
type: "tool-output-available",
|
|
148
|
-
toolCallId: item.id,
|
|
149
|
-
output: { exit_code: item.exit_code ?? null, status: item.status ?? null, output: clip(item.aggregated_output ?? "") }
|
|
150
|
-
});
|
|
151
|
-
break;
|
|
152
|
-
case "file_change":
|
|
153
|
-
out.push(
|
|
154
|
-
{ type: "tool-input-available", toolCallId: item.id, toolName: "edit", input: { changes: item.changes ?? [] } },
|
|
155
|
-
{ type: "tool-output-available", toolCallId: item.id, output: { status: item.status ?? "completed" } }
|
|
156
|
-
);
|
|
157
|
-
break;
|
|
158
|
-
case "web_search":
|
|
159
|
-
case "mcp_tool_call":
|
|
160
|
-
out.push(
|
|
161
|
-
{ type: "tool-input-available", toolCallId: item.id, toolName: item.type, input: { ...item, id: undefined, type: undefined } },
|
|
162
|
-
{ type: "tool-output-available", toolCallId: item.id, output: { status: item.status ?? "completed" } }
|
|
163
|
-
);
|
|
164
|
-
break;
|
|
165
|
-
case "error":
|
|
166
|
-
// Startup notices (unknown config keys, missing model metadata) come
|
|
167
|
-
// through as error items. They are not the answer failing.
|
|
168
|
-
out.push({ type: "data-notice", data: { message: item.message ?? item.text ?? "" } });
|
|
169
|
-
break;
|
|
170
|
-
default:
|
|
171
|
-
break;
|
|
172
|
-
}
|
|
173
|
-
break;
|
|
174
|
-
case "turn.completed":
|
|
175
|
-
out.push({ type: "finish-step" });
|
|
176
|
-
if (event.usage) {
|
|
177
|
-
out.push({ type: "data-usage", data: event.usage });
|
|
178
|
-
state.usage = event.usage;
|
|
179
|
-
}
|
|
180
|
-
state.completed = true;
|
|
181
|
-
break;
|
|
182
|
-
case "turn.failed":
|
|
183
|
-
out.push({ type: "error", errorText: event.error?.message ?? event.error ?? event.message ?? "Codex turn failed" });
|
|
184
|
-
state.failed = true;
|
|
185
|
-
break;
|
|
186
|
-
case "error":
|
|
187
|
-
out.push({ type: "data-notice", data: { message: event.message ?? event.error ?? "" } });
|
|
188
|
-
break;
|
|
189
|
-
default:
|
|
190
|
-
break;
|
|
191
|
-
}
|
|
192
|
-
return out;
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
// ---- stream plumbing
|
|
196
|
-
|
|
197
|
-
function sseHead(res) {
|
|
198
|
-
res.writeHead(200, {
|
|
199
|
-
"content-type": "text/event-stream; charset=utf-8",
|
|
200
|
-
"cache-control": "no-cache, no-transform",
|
|
201
|
-
connection: "keep-alive",
|
|
202
|
-
"x-vercel-ai-ui-message-stream": "v1",
|
|
203
|
-
"x-accel-buffering": "no"
|
|
204
|
-
});
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
function writeChunk(res, chunk) {
|
|
208
|
-
if (!res.writableEnded) res.write(`data: ${JSON.stringify(chunk)}\n\n`);
|
|
209
|
-
}
|
|
210
|
-
|
|
211
|
-
function endStream(res) {
|
|
212
|
-
if (!res.writableEnded) res.end("data: [DONE]\n\n");
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
// Chunks of a turn, assembled into the UIMessage parts the page shows for a
|
|
216
|
-
// finished (or interrupted) turn. The page rebuilds history from this.
|
|
217
|
-
export function partsFromChunks(chunks) {
|
|
218
|
-
const parts = [];
|
|
219
|
-
const open = new Map(); // id -> part for text / reasoning
|
|
220
|
-
const tools = new Map(); // toolCallId -> part
|
|
221
|
-
for (const c of chunks) {
|
|
222
|
-
switch (c.type) {
|
|
223
|
-
case "text-start":
|
|
224
|
-
open.set(c.id, { type: "text", text: "", state: "streaming" });
|
|
225
|
-
parts.push(open.get(c.id));
|
|
226
|
-
break;
|
|
227
|
-
case "text-delta":
|
|
228
|
-
if (open.has(c.id)) open.get(c.id).text += c.delta ?? "";
|
|
229
|
-
break;
|
|
230
|
-
case "text-end":
|
|
231
|
-
if (open.has(c.id)) open.get(c.id).state = "done";
|
|
232
|
-
break;
|
|
233
|
-
case "reasoning-start":
|
|
234
|
-
open.set(c.id, { type: "reasoning", text: "", state: "streaming" });
|
|
235
|
-
parts.push(open.get(c.id));
|
|
236
|
-
break;
|
|
237
|
-
case "reasoning-delta":
|
|
238
|
-
if (open.has(c.id)) open.get(c.id).text += c.delta ?? "";
|
|
239
|
-
break;
|
|
240
|
-
case "reasoning-end":
|
|
241
|
-
if (open.has(c.id)) open.get(c.id).state = "done";
|
|
242
|
-
break;
|
|
243
|
-
case "tool-input-available": {
|
|
244
|
-
const part = { type: `tool-${c.toolName}`, toolCallId: c.toolCallId, state: "input-available", input: c.input };
|
|
245
|
-
tools.set(c.toolCallId, part);
|
|
246
|
-
parts.push(part);
|
|
247
|
-
break;
|
|
248
|
-
}
|
|
249
|
-
case "tool-output-available":
|
|
250
|
-
if (tools.has(c.toolCallId)) {
|
|
251
|
-
tools.get(c.toolCallId).state = "output-available";
|
|
252
|
-
tools.get(c.toolCallId).output = c.output;
|
|
253
|
-
}
|
|
254
|
-
break;
|
|
255
|
-
case "data-notice":
|
|
256
|
-
case "data-usage":
|
|
257
|
-
case "data-session":
|
|
258
|
-
parts.push({ type: c.type, data: c.data });
|
|
259
|
-
break;
|
|
260
|
-
default:
|
|
261
|
-
break;
|
|
262
|
-
}
|
|
263
|
-
}
|
|
264
|
-
return parts;
|
|
265
|
-
}
|
|
266
|
-
|
|
267
99
|
// ---- public API
|
|
268
100
|
|
|
269
101
|
export async function sideSessionState(taskId) {
|
|
@@ -307,67 +139,48 @@ export function attachToTurn(taskId, res) {
|
|
|
307
139
|
return true;
|
|
308
140
|
}
|
|
309
141
|
|
|
310
|
-
|
|
311
|
-
// turn has ended, however it ended.
|
|
312
|
-
export async function runSideTurn({ task, text, res = null, fresh = false }) {
|
|
313
|
-
await sweepOnce();
|
|
314
|
-
if (!task.thread_id) throw Object.assign(new Error("this worker recorded no thread_id, so there is no Codex thread to fork"), { code: "no_thread" });
|
|
315
|
-
if (running.has(task.id)) throw Object.assign(new Error("a side turn is already running for this worker"), { code: "busy" });
|
|
316
|
-
const target = codexRunner.resolveTarget();
|
|
317
|
-
if (target.error) throw Object.assign(new Error(target.error), { code: "codex_missing" });
|
|
318
|
-
|
|
319
|
-
const { session, refreshed } = await prepareSideSession(task, { fresh });
|
|
320
|
-
|
|
142
|
+
function startSideChild(target, task, session) {
|
|
321
143
|
const args = codexRunner.forkSideArgs({ forkThreadId: session.fork_thread_id, workerThreadId: task.thread_id, model: task.model });
|
|
322
144
|
args.splice(-2, 0, ...sideTurnConfigArgs(codexConfigText()));
|
|
323
|
-
|
|
324
145
|
const cwd = task.worktree_path || task.project_root || process.cwd();
|
|
325
|
-
|
|
146
|
+
return codexRunner.start(target, args, {
|
|
326
147
|
cwd,
|
|
327
148
|
stdio: ["pipe", "pipe", "pipe"],
|
|
328
149
|
env: { ...process.env, NO_COLOR: "1" },
|
|
329
150
|
windowsHide: true
|
|
330
151
|
});
|
|
152
|
+
}
|
|
331
153
|
|
|
154
|
+
// The in-memory side of a running turn: its chunks so far, who is watching,
|
|
155
|
+
// and how it was stopped. Chunks are written through to the store in batches.
|
|
156
|
+
async function openLiveTurn(task, text, child) {
|
|
332
157
|
const turnId = `turn-${Date.now()}-${randomUUID().slice(0, 8)}`;
|
|
333
158
|
const startedAt = new Date().toISOString();
|
|
334
|
-
const
|
|
335
|
-
|
|
336
|
-
await insertSideTurn({ id: turnId, task_id: task.id, question: text, status: "running", chunks: [], started_at: startedAt });
|
|
337
|
-
|
|
338
|
-
let persistTimer = null;
|
|
159
|
+
const state = { toolsSeen: new Set(), completed: false, failed: false, usage: null };
|
|
160
|
+
const live = { turnId, child, chunks: [], watchers: new Set(), startedAt, question: text, state, stderr: "", stoppedBy: null, persistTimer: null };
|
|
339
161
|
const persistSoon = () => {
|
|
340
|
-
if (persistTimer) return;
|
|
341
|
-
persistTimer = setTimeout(() => {
|
|
342
|
-
persistTimer = null;
|
|
162
|
+
if (live.persistTimer) return;
|
|
163
|
+
live.persistTimer = setTimeout(() => {
|
|
164
|
+
live.persistTimer = null;
|
|
343
165
|
updateSideTurn(turnId, { chunks: live.chunks }).catch(() => {});
|
|
344
166
|
}, 250);
|
|
345
167
|
};
|
|
346
|
-
|
|
168
|
+
live.broadcast = (chunk) => {
|
|
347
169
|
live.chunks.push(chunk);
|
|
348
170
|
for (const w of live.watchers) writeChunk(w, chunk);
|
|
349
171
|
persistSoon();
|
|
350
172
|
};
|
|
351
|
-
|
|
352
|
-
if (res) {
|
|
353
|
-
sseHead(res);
|
|
354
|
-
live.watchers.add(res);
|
|
355
|
-
res.on("close", () => live.watchers.delete(res));
|
|
356
|
-
}
|
|
357
|
-
broadcast({ type: "start", messageId: turnId });
|
|
358
|
-
|
|
359
|
-
let rest = "";
|
|
360
|
-
let stderr = "";
|
|
361
|
-
let stoppedBy = null;
|
|
362
|
-
const timer = setTimeout(() => {
|
|
363
|
-
stoppedBy = "timeout";
|
|
364
|
-
codexRunner.cancelChild(child);
|
|
365
|
-
}, TURN_TIMEOUT_MS);
|
|
366
173
|
live.stop = (reason) => {
|
|
367
|
-
stoppedBy = reason;
|
|
174
|
+
live.stoppedBy = reason;
|
|
368
175
|
codexRunner.cancelChild(child);
|
|
369
176
|
};
|
|
177
|
+
running.set(task.id, live);
|
|
178
|
+
await insertSideTurn({ id: turnId, task_id: task.id, question: text, status: "running", chunks: [], started_at: startedAt });
|
|
179
|
+
return live;
|
|
180
|
+
}
|
|
370
181
|
|
|
182
|
+
function pipeSideOutput(child, live, session, taskId) {
|
|
183
|
+
let rest = "";
|
|
371
184
|
child.stdout.setEncoding("utf8");
|
|
372
185
|
child.stdout.on("data", (chunk) => {
|
|
373
186
|
rest += chunk;
|
|
@@ -384,78 +197,79 @@ export async function runSideTurn({ task, text, res = null, fresh = false }) {
|
|
|
384
197
|
}
|
|
385
198
|
if (event.type === "thread.started" && !session.fork_thread_id && event.thread_id) {
|
|
386
199
|
session.fork_thread_id = event.thread_id;
|
|
387
|
-
setSideSessionFork(
|
|
200
|
+
setSideSessionFork(taskId, event.thread_id).catch(() => {});
|
|
388
201
|
}
|
|
389
|
-
for (const part of chunksFor(event, live.state)) broadcast(part);
|
|
202
|
+
for (const part of chunksFor(event, live.state)) live.broadcast(part);
|
|
390
203
|
}
|
|
391
204
|
});
|
|
392
205
|
child.stderr.setEncoding("utf8");
|
|
393
206
|
child.stderr.on("data", (chunk) => {
|
|
394
|
-
stderr = (stderr + chunk).slice(-4000);
|
|
207
|
+
live.stderr = (live.stderr + chunk).slice(-4000);
|
|
395
208
|
});
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// How the turn ended, and the error to show when it did not complete.
|
|
212
|
+
function sideTurnOutcome(live, code, signal) {
|
|
213
|
+
if (live.state.failed) return { status: "failed", error: live.chunks.find((c) => c.type === "error")?.errorText ?? "Codex turn failed", announce: false };
|
|
214
|
+
if (live.state.completed) return { status: "completed", error: null, announce: false };
|
|
215
|
+
if (live.stoppedBy === "timeout") {
|
|
216
|
+
return { status: "timed_out", error: `the side turn ran past ${TURN_TIMEOUT_MS / 60000} minutes and was stopped`, announce: true };
|
|
217
|
+
}
|
|
218
|
+
if (live.stoppedBy) return { status: "stopped", error: "stopped", announce: true };
|
|
219
|
+
const tail = live.stderr.trim().split("\n").filter((l) => !l.includes("rmcp::transport")).slice(-3).join("\n");
|
|
220
|
+
const why = signal ? `stopped by ${signal}` : `codex exited with code ${code}`;
|
|
221
|
+
return { status: "failed", error: tail ? `${why}: ${tail}` : why, announce: true };
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
async function settleSideTurn(live, taskId, code, signal) {
|
|
225
|
+
if (live.persistTimer) clearTimeout(live.persistTimer);
|
|
226
|
+
const { status, error, announce } = sideTurnOutcome(live, code, signal);
|
|
227
|
+
if (announce) live.broadcast({ type: "error", errorText: error });
|
|
228
|
+
live.broadcast({ type: "finish" });
|
|
229
|
+
for (const w of live.watchers) endStream(w);
|
|
230
|
+
live.watchers.clear();
|
|
231
|
+
running.delete(taskId);
|
|
232
|
+
await updateSideTurn(live.turnId, { status, chunks: live.chunks, usage: live.state.usage, error, ended_at: new Date().toISOString() }).catch(() => {});
|
|
233
|
+
return status;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// Start a turn. `res` (optional) becomes the first watcher. Resolves when the
|
|
237
|
+
// turn has ended, however it ended.
|
|
238
|
+
export async function runSideTurn({ task, text, res = null, fresh = false }) {
|
|
239
|
+
await sweepOnce();
|
|
240
|
+
if (!task.thread_id) throw Object.assign(new Error("this worker recorded no thread_id, so there is no Codex thread to fork"), { code: "no_thread" });
|
|
241
|
+
if (running.has(task.id)) throw Object.assign(new Error("a side turn is already running for this worker"), { code: "busy" });
|
|
242
|
+
const target = codexRunner.resolveTarget();
|
|
243
|
+
if (target.error) throw Object.assign(new Error(target.error), { code: "codex_missing" });
|
|
244
|
+
|
|
245
|
+
const { session, refreshed } = await prepareSideSession(task, { fresh });
|
|
246
|
+
const child = startSideChild(target, task, session);
|
|
247
|
+
const live = await openLiveTurn(task, text, child);
|
|
248
|
+
if (res) {
|
|
249
|
+
sseHead(res);
|
|
250
|
+
live.watchers.add(res);
|
|
251
|
+
res.on("close", () => live.watchers.delete(res));
|
|
252
|
+
}
|
|
253
|
+
live.broadcast({ type: "start", messageId: live.turnId });
|
|
254
|
+
const timer = setTimeout(() => live.stop("timeout"), TURN_TIMEOUT_MS);
|
|
255
|
+
pipeSideOutput(child, live, session, task.id);
|
|
396
256
|
child.stdin.on("error", () => {});
|
|
397
257
|
child.stdin.end(sideQuestionText(text));
|
|
398
258
|
|
|
399
259
|
return new Promise((resolve) => {
|
|
400
260
|
const finish = async (code, signal) => {
|
|
401
261
|
clearTimeout(timer);
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
let error = null;
|
|
405
|
-
if (live.state.failed) {
|
|
406
|
-
status = "failed";
|
|
407
|
-
error = live.chunks.find((c) => c.type === "error")?.errorText ?? "Codex turn failed";
|
|
408
|
-
} else if (!live.state.completed) {
|
|
409
|
-
if (stoppedBy === "timeout") {
|
|
410
|
-
status = "timed_out";
|
|
411
|
-
error = `the side turn ran past ${TURN_TIMEOUT_MS / 60000} minutes and was stopped`;
|
|
412
|
-
} else if (stoppedBy) {
|
|
413
|
-
status = "stopped";
|
|
414
|
-
error = "stopped";
|
|
415
|
-
} else {
|
|
416
|
-
status = "failed";
|
|
417
|
-
const tail = stderr.trim().split("\n").filter((l) => !l.includes("rmcp::transport")).slice(-3).join("\n");
|
|
418
|
-
const why = signal ? `stopped by ${signal}` : `codex exited with code ${code}`;
|
|
419
|
-
error = tail ? `${why}: ${tail}` : why;
|
|
420
|
-
}
|
|
421
|
-
broadcast({ type: "error", errorText: error });
|
|
422
|
-
}
|
|
423
|
-
broadcast({ type: "finish" });
|
|
424
|
-
for (const w of live.watchers) endStream(w);
|
|
425
|
-
live.watchers.clear();
|
|
426
|
-
running.delete(task.id);
|
|
427
|
-
await updateSideTurn(turnId, { status, chunks: live.chunks, usage: live.state.usage, error, ended_at: new Date().toISOString() }).catch(() => {});
|
|
428
|
-
resolve({ status, turnId, forkThreadId: session.fork_thread_id, refreshed });
|
|
262
|
+
const status = await settleSideTurn(live, task.id, code, signal);
|
|
263
|
+
resolve({ status, turnId: live.turnId, forkThreadId: session.fork_thread_id, refreshed });
|
|
429
264
|
};
|
|
430
265
|
child.on("error", (error) => {
|
|
431
|
-
stderr += `\nfailed to start codex: ${error.message}`;
|
|
266
|
+
live.stderr += `\nfailed to start codex: ${error.message}`;
|
|
432
267
|
finish(-1, null);
|
|
433
268
|
});
|
|
434
269
|
child.on("exit", finish);
|
|
435
270
|
});
|
|
436
271
|
}
|
|
437
272
|
|
|
438
|
-
// The answer of a turn, as the text parts joined; null while nothing has
|
|
439
|
-
// been said yet.
|
|
440
|
-
function answerOf(turn) {
|
|
441
|
-
const parts = partsFromChunks(turn.chunks ?? []);
|
|
442
|
-
const text = parts.filter((p) => p.type === "text").map((p) => p.text).join("\n").trim();
|
|
443
|
-
return text || null;
|
|
444
|
-
}
|
|
445
|
-
|
|
446
|
-
function turnView(turn) {
|
|
447
|
-
return {
|
|
448
|
-
turn_id: turn.id,
|
|
449
|
-
question: turn.question,
|
|
450
|
-
status: turn.status,
|
|
451
|
-
answer: answerOf(turn),
|
|
452
|
-
usage: turn.usage ?? null,
|
|
453
|
-
error: turn.error ?? null,
|
|
454
|
-
started_at: turn.started_at ?? null,
|
|
455
|
-
ended_at: turn.ended_at ?? null
|
|
456
|
-
};
|
|
457
|
-
}
|
|
458
|
-
|
|
459
273
|
// The newest side turn of a worker, for a caller that asked earlier and
|
|
460
274
|
// comes back for the answer. Null when nothing was ever asked.
|
|
461
275
|
export async function latestSideTurn(taskId) {
|
package/src/app/sse.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// Server-sent events plumbing for the side chat stream.
|
|
2
|
+
// ---- stream plumbing
|
|
3
|
+
|
|
4
|
+
export function sseHead(res) {
|
|
5
|
+
res.writeHead(200, {
|
|
6
|
+
"content-type": "text/event-stream; charset=utf-8",
|
|
7
|
+
"cache-control": "no-cache, no-transform",
|
|
8
|
+
connection: "keep-alive",
|
|
9
|
+
"x-vercel-ai-ui-message-stream": "v1",
|
|
10
|
+
"x-accel-buffering": "no"
|
|
11
|
+
});
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function writeChunk(res, chunk) {
|
|
15
|
+
if (!res.writableEnded) res.write(`data: ${JSON.stringify(chunk)}\n\n`);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function endStream(res) {
|
|
19
|
+
if (!res.writableEnded) res.end("data: [DONE]\n\n");
|
|
20
|
+
}
|