import { retainedLaunchWarning } from "./native-cli-retained.ts"; import { resolve } from "node:path"; import type { NativeCliEntryContext } from "./native-cli-entry-types.ts"; import type { ControlClient } from "../../hub/control-client.ts"; import type { JcodeTuiBinding, JcodeTuiState } from "../jcode.ts"; import { JCODE_HEADLESS_AFTER_RECOVERY } from "../jcode.ts"; import { bundleInStatus, rosterInStatus } from "../../hub/status-roster.ts"; const WAITING = "jcode's TUI opens after its first hub turn; send it work, or Ctrl-C"; /** * #1085: what to tell the person for each cause class the daemon returns as `code`. Fixed text: the daemon's reply carries a code, never a path or id, and nothing else is echoed. * A session that was loaded from a record (`resumed`, crash or controlled recovery) is running headless: the way back to its TUI is stop, then start. */ export function jcodeTuiCauseMessage(code: unknown, resumed = false): string | undefined { // The cause sentence is per class (AC1). The next step is per class too, except that a session loaded from a record is // running headless from recovery, whatever refused the TUI: its way back is always stop, then start (AC2). const recoveredStep = `${JCODE_HEADLESS_AFTER_RECOVERY}`; const step = (own: string) => resumed ? recoveredStep : own; switch (code) { case "launch_changed": return `Jcode was restarted while ahub jcode was starting its TUI; ${step("run ahub jcode again")}`; case "server_not_running": return `Jcode's owned server is not running; ${step("run ahub stop jcode, then ahub jcode")}`; case "socket_changed": return `Jcode's private socket was replaced by another process; ${step("run ahub stop jcode, then ahub jcode")}`; case "session_unknown": return `Jcode has not reported a session yet; ${step("wait for it to attach, then run ahub jcode again")}`; case "session_proof_refused": return `Jcode's saved session failed the hub's safety check (not a plain file, too large, or another session); ${step("run ahub stop jcode, then ahub jcode for a new session")}`; case "hub_busy": return "the hub is stopping, recovering or changing its roster; wait for ahub status to settle, then run ahub jcode again"; case "not_running": return "Jcode is not running under this hub; run ahub jcode again"; case "mcp_stale": return "the project's Jcode MCP entry is missing or stale; run ahub jcode again to rewrite it"; default: return undefined; } } /** Names the cause class the daemon returned (#1085). An older daemon sends no code: the caller's generic message stands. */ function refuseTuiCause(reply: { ok?: unknown; code?: unknown; resumed?: unknown }, fail: NativeCliEntryContext["fail"]): void { if (reply.ok) return; const message = jcodeTuiCauseMessage(reply.code, reply.resumed === true); if (message) fail(message); } /** The daemon names the one session option that differs from the attached saved session (#559 N2, #574). */ function refuseNamedOption(reply: { ok?: unknown; option?: unknown }, fail: NativeCliEntryContext["fail"]): void { if (!reply.ok && typeof reply.option === "string" && ["--session-id", "--model", "--provider-profile"].includes(reply.option)) fail(`Jcode is already running with a different ${reply.option}; run ahub jcode without it, or stop jcode first`); } export async function waitForJcodeTui(hub: ControlClient, fail: NativeCliEntryContext["fail"], signal: AbortSignal, options: Record, first?: JcodeTuiState): Promise | undefined> { let binding: JcodeTuiBinding | undefined = first?.binding, announced = false, current = first; while (!signal.aborted) { if (!current) { const reply = await hub.request({ t: "native_tui_launch", peer: "jcode", binding, args: options }); if (signal.aborted) return; refuseNamedOption(reply, fail); refuseTuiCause(reply, fail); if (!reply.ok || !reply.binding || !["waiting", "ready"].includes(reply.state)) fail("Jcode launch changed or its native saved session is unavailable; retry from a terminal"); current = reply as JcodeTuiState; } if (binding && (binding.launchId !== current.binding.launchId || binding.sessionId !== current.binding.sessionId)) fail("Jcode launch changed while waiting"); binding = current.binding; if (current.state === "ready") return current; if (!announced) { console.log(WAITING); announced = true; } await new Promise(resolve => { const finish = () => { clearTimeout(timer); signal.removeEventListener("abort", finish); resolve(); }; const timer = setTimeout(finish, 200); signal.addEventListener("abort", finish, { once: true }); if (signal.aborted) finish(); }); current = undefined; } } export async function runJcodeEntry(ctx: NativeCliEntryContext): Promise { const { args, cwd, stateDir, cliDir, unattendedEnv, connect, fail, takeFlags } = ctx; const { launcherPreview, qwenSessionId, configureJcodeMcp, readControl, startModeOf } = ctx.helpers; const print = args.includes("--print-command"); if (args.includes("--dry-run") || print) { // Pure previews never create a native store or start a session. Only a person may resolve an existing private tuple. if (!print || args.includes("--dry-run") || !ctx.person) { try { return console.log(JSON.stringify(launcherPreview("jcode", args, cwd, stateDir, unattendedEnv), null, 2)); } catch { fail("cannot preview Jcode launch: invalid arguments or configuration (details withheld)"); } } } const { one, rest } = takeFlags(args.filter(arg => arg !== "--print-command"), ["--mode", "--model", "--provider-profile", "--session-id"], []); if (rest.length || (one["--mode"] !== undefined && !["headless", "tui"].includes(one["--mode"]))) fail("usage: ahub jcode [--mode tui|headless] [--model ] [--provider-profile ] [--session-id ]"); if (one["--session-id"] !== undefined && !qwenSessionId(one["--session-id"])) fail("invalid Jcode session identity"); const control = readControl(stateDir); // #685: `--as ` selects an extra Jcode instance; every request below names it, never the base peer. const peer = ctx.instance ?? "jcode"; const mode = one["--mode"] ?? (ctx.instance ? "headless" : control?.startModes?.jcode ?? startModeOf(ctx.projectConfig().peers, "jcode")); if (ctx.instance && mode === "tui") fail(`${peer} is an extra Jcode instance: it runs headless on its own private server (ahub jcode --as ${peer}); the TUI belongs to the base jcode`); if (print && (mode === "headless" || !control?.features?.includes("native_tui_launch"))) { try { return console.log(JSON.stringify(launcherPreview("jcode", args, cwd, stateDir, unattendedEnv), null, 2)); } catch { return fail("cannot preview Jcode launch: invalid arguments or configuration (details withheld)"); } } if (mode === "tui" && !ctx.person) fail("Jcode's private TUI is person-only; run ahub jcode in your terminal"); const hub = await connect(), abort = new AbortController(); let interrupted = false; const interruptedWait = () => { if (abort.signal.aborted && !interrupted) fail("hub connection closed while waiting for Jcode; retry from a terminal"); return abort.signal.aborted; }; const interrupt = () => { interrupted = true; abort.abort(); hub.close(); process.exitCode = 130; }; process.once("SIGINT", interrupt); const oldClose = hub.onClose; hub.onClose = (code, reason) => { if (!abort.signal.aborted) abort.abort(); oldClose?.(code, reason); }; try { const snapshot = (await hub.request({ t: "status" })).status; const rostered = rosterInStatus(snapshot, peer); if (rostered === undefined) fail(`cannot read ${peer}'s roster membership from the running hub; upgrade or restart it, then retry (nothing was started)`); if (!rostered) fail(`${peer} is off roster; add it with ahub roster add ${peer}`); const warning = retainedLaunchWarning(snapshot, peer, ctx.definition); if (warning) console.error(warning); const options = { model: one["--model"], providerProfile: one["--provider-profile"], sessionId: one["--session-id"] }; if (print) { if (!hub.features.includes("native_tui_launch") || mode !== "tui") return console.log(JSON.stringify(launcherPreview("jcode", args, cwd, stateDir, unattendedEnv), null, 2)); const reply = await hub.request({ t: "native_tui_launch", peer: "jcode", args: options }); refuseNamedOption(reply, fail); refuseTuiCause(reply, fail); if (!reply.ok || reply.state !== "ready") fail("Jcode's selected native session is not saved and ready; run ahub jcode to wait for its first hub turn"); return console.log(JSON.stringify(reply.launch, null, 2)); } if (mode === "tui") { if (!hub.features.includes("native_tui_launch")) fail("the running hub does not support Jcode TUI launch; upgrade it before retrying"); if (!process.stdin.isTTY || !process.stdout.isTTY) { if (one["--mode"] || Object.values(options).some(value => value !== undefined)) fail("run ahub jcode with these options in a terminal"); const reply = await hub.request({ t: "peer_start", peer: "jcode" }); if (!reply.ok) fail(reply.error); console.log(reply.command ?? "Jcode terminal requested"); return; } } const written = configureJcodeMcp(cwd, stateDir, bundleInStatus(snapshot) ?? resolve(cliDir, "../../plugins/agent-hub/server.js")); if (written.tracked) console.error(".jcode/mcp.json is tracked; review this local machine-path change before committing it"); const reply = await hub.request({ t: "start", peer, args: { mode, ...options }, operationId: process.env.AGENTHUB_RECOVERY_OPERATION }, 65_000); if (interruptedWait()) return; if (!reply.ok) fail(reply.error); if (mode === "headless") { console.log(reply.already ? `${peer} is already attached` : `${peer} attached (headless); native policy unmanaged, NO hub sandbox`); return; } const ready = await waitForJcodeTui(hub, fail, abort.signal, options); if (interruptedWait() || !ready) return; // No managed terminal record: Jcode's controlled recovery is refused at plan time, so, like Kimi's TUI, it has // no terminal recovery adapter (#564). const confirmed = await hub.request({ t: "native_tui_launch", peer: "jcode", binding: ready.binding, args: options }); if (interruptedWait()) return; refuseTuiCause(confirmed, fail); if (!confirmed.ok || confirmed.state !== "ready") fail("Jcode launch changed before its terminal opened"); // ponytail: jcode 0.98.1's top-level TUI spawns a shared server (no --temporary-server or --owner-pid) when nothing // answers on the dialed socket at startup, and on its reload-handoff reconnect. A hub stop or an owned-server crash // between the confirm reply above and that check can leave an unowned jcode server on the private socket under the // person's JCODE_HOME. No native flag prevents it; revisit if upstream adds an owner flag (#559 N2). ctx.execWithEnv(confirmed.launch.cmd, confirmed.launch.args, { ...ctx.helpers.childEnv(), ...confirmed.launch.env }); } finally { process.removeListener("SIGINT", interrupt); hub.onClose = oldClose; hub.close(); } }