Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 3 additions & 8 deletions docs-site/src/content/docs/es/reference/cli/lifecycle.md
Original file line number Diff line number Diff line change
Expand Up @@ -106,16 +106,11 @@ Una salida proxy sola no confirma que la restauración compartida Codex / Grok t
En Windows, `ocx stop` detiene una tarea registrada del Programador de tareas o un servicio nativo WinSW mediante una parada verificada. Primero finaliza la tarea y después solo los procesos envoltorios `wscript.exe` y `cmd.exe` que puede vincular a esta instalación (el lanzador o script de servicio de este directorio, una cadena de procesos padres que conduce al proxy o al servicio del Programador de tareas, y una hora de inicio registrada), y espera a que terminen. Solo entonces detiene el proxy de forma controlada. Después confirma que el puerto permanezca libre unos seis segundos y que ningún envoltorio se haya reiniciado, para impedir que un bucle de reinicio vuelva a iniciar el proxy tras una parada exitosa.

OpenCodex verifica que la tarea programada inicie esta instalación con tu cuenta de Windows
y comprueba las cuentas de sus desencadenadores y de cada instancia en ejecución antes de detenerla. Una tarea deshabilitada
y comprueba la cuenta de cada instancia en ejecución antes de detenerla. Una tarea deshabilitada
de tu cuenta se considera inactiva si no tiene instancias en ejecución. Si hay una tarea en cola,
OpenCodex no confirma la parada. Si la comprobación falla,
revisa el lanzador, las cuentas de los desencadenadores y la cuenta de ejecución en el Programador
de tareas. Finalizar sus instancias no repara el registro. Repara un registro que te pertenezca
o contacta con su propietario o administrador. La parada rechaza nuevas acciones al vencer
su límite de tiempo, cancela el proceso auxiliar de parada y conserva los cambios confirmados
en el resultado, incluso si la verificación final sigue pendiente.
Si se envía la autorización y el auxiliar no responde antes del plazo, la CLI indica
que no pudo leer el estado del servicio (`state-unknown`) y marca la parada como fallida.
revisa el lanzador y la cuenta de ejecución en el Programador de tareas y detén la tarea desde
la sesión de esa cuenta.

OpenCodex solo finaliza directamente un envoltorio si comprueba que pertenece a tu cuenta.
Ignora los envoltorios que pertenecen a otro usuario. Si no puede verificar el propietario
Expand Down
11 changes: 3 additions & 8 deletions docs-site/src/content/docs/reference/cli/lifecycle.md
Original file line number Diff line number Diff line change
Expand Up @@ -180,15 +180,10 @@ for about six seconds and that no wrapper started again, so a wrapper's restart
the proxy back behind a successful stop.

OpenCodex verifies that the scheduled task launches this installation under your Windows account
and checks the account for its triggers and each running instance before stopping it. An owned, disabled task with
and checks the account for each running instance before stopping it. An owned, disabled task with
no running instances counts as idle. A queued task prevents OpenCodex from confirming the stop.
If verification fails, check the launcher, trigger accounts and run-as account in Task Scheduler.
Ending its running instances does not repair its registration. Repair a registration you own,
or contact its owner or administrator. The stop refuses further actions once its time limit has
passed, cancels the owned stop helper, and retains confirmed changes in its result even if
final verification is still pending when the time limit expires.
If the helper has not answered by the deadline after approval was sent, the CLI reports that
it could not read the service state (`state-unknown`) and marks the stop as failed.
If verification fails, check the launcher and run-as account in Task Scheduler and stop the task
from its owning session.

OpenCodex terminates a wrapper directly only after verifying that it belongs to your account.
It ignores wrappers proven to belong to another user. If it cannot verify the owner of a wrapper
Expand Down
2 changes: 1 addition & 1 deletion scripts/test-layout/layout.json
Original file line number Diff line number Diff line change
Expand Up @@ -1933,7 +1933,7 @@
"windows-elevation-spawn.test.ts": "windows",
"windows-elevation.test.ts": "windows",
"windows-guarded-manager.test.ts": "windows", "windows-checked-stop.test.ts": "windows", "windows-stop-binding.test.ts": "windows", "windows-checked-stop-live.test.ts": "windows", "windows-service-stop-wiring.test.ts": "windows",
"windows-popup-fix.test.ts": "windows", "windows-stop-confirm.test.ts": "windows", "windows-process-evidence.test.ts": "windows", "windows-stop-boundary.test.ts": "windows", "windows-stop-callers.test.ts": "windows", "windows-stop-ocx-stop.test.ts": "windows",
"windows-popup-fix.test.ts": "windows", "windows-stop-confirm.test.ts": "windows", "windows-process-evidence.test.ts": "windows", "windows-stop-callers.test.ts": "windows", "windows-stop-ocx-stop.test.ts": "windows",
"windows-process-priority.test.ts": "windows",
"windows-scheduler-errors.test.ts": "windows", "windows-scheduler-install-verification.test.ts": "windows",
"windows-lifecycle-root-acl.test.ts": "windows",
Expand Down
127 changes: 25 additions & 102 deletions src/service/windows-checked-stop-live.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import { parseListenPidsFromNetstat, type ListenPidScan } from "../server/port-r
import { dropWindowsTcpRowsForLocalPort } from "../server/windows-tcp-drop";
import { TASK, windowsLauncherVbsPath, windowsServiceScriptPath } from "./state";
import { ancestorWrapperPids } from "./windows-guarded-manager";
import type { WindowsCheckedStopDeps, WindowsTaskEndResult, WindowsWinswScmState, WindowsWinswStopResult } from "./windows-checked-stop";
import type { WindowsCheckedStopDeps, WindowsWinswScmState, WindowsWinswStopResult } from "./windows-checked-stop";
import {
openWindowsProcessWatch,
readScheduleServicePid,
Expand All @@ -42,45 +42,19 @@ import type { WindowsListenerIdentity, WindowsPortSample, WindowsStopConfirmDeps
import { windowsSchedulerCsvIncludesTask } from "./windows-scheduler";
import { WINDOWS_TASK_INSTANCE_STOP_SCRIPT, verifyWindowsTaskStopProof } from "./windows-task-instance-stop";

// Only a missing task after connecting to the local root folder establishes absence.
const TASK_REGISTRATION_SCRIPT = String.raw`
$ErrorActionPreference = 'Stop'
try {
$service = [Activator]::CreateInstance([type]::GetTypeFromProgID('Schedule.Service', $true))
$service.Connect()
$folder = $service.GetFolder('\')
} catch { 'unknown'; return }
try {
$task = $folder.GetTask('${TASK}')
if ($null -ne $task) { 'present' } else { 'unknown' }
} catch {
if ($_.Exception.GetBaseException().HResult -eq -2147024894) { 'absent' } else { 'unknown' }
}`;

export interface WindowsStopCommandResult {
status: number | null;
/** Captured from the spawned process handle. Bun's child exit status can contain only the low byte. */
windowsExitCode?: number;
stdout: string;
stderr: string;
timedOut: boolean;
}

export interface WindowsStopCommandControl {
remainingMs?: () => number;
signal?: AbortSignal;
/** Approval was dispatched; a cap cannot assume no mutation before the helper answers. */
onDispatch?: () => void;
onMutation?: () => void;
}

/** One spawned helper; tests inject it, production runs execFile with a hard timeout. */
export type WindowsStopCommandRunner = (
program: "schtasks" | "sc" | "powershell",
args: string[],
timeoutMs: number,
authorizeProof?: (line: string) => boolean | Promise<boolean>,
control?: WindowsStopCommandControl,
) => Promise<WindowsStopCommandResult>;

function programPath(program: "schtasks" | "sc" | "powershell"): string {
Expand All @@ -91,12 +65,11 @@ function programPath(program: "schtasks" | "sc" | "powershell"): string {
return file;
}

export const liveWindowsStopCommandRunner: WindowsStopCommandRunner = (program, args, timeoutMs, authorizeProof, control) => new Promise(resolve => {
export const liveWindowsStopCommandRunner: WindowsStopCommandRunner = (program, args, timeoutMs, authorizeProof) => new Promise(resolve => {
// execFile reads a 0 timeout as "no timeout": a deadline-derived fraction is floored, and a
// timeout that floors to 0 spawns nothing.
const timeout = Math.floor(Math.min(timeoutMs, control?.remainingMs?.() ?? Infinity));
const deadline = performance.now() + timeout;
if (!(timeout > 0) || control?.signal?.aborted) {
const timeout = Math.floor(timeoutMs);
if (!(timeout > 0)) {
resolve({ status: null, stdout: "", stderr: "", timedOut: true });
return;
}
Expand All @@ -110,64 +83,36 @@ export const liveWindowsStopCommandRunner: WindowsStopCommandRunner = (program,
return;
}
let file: string;
let native: WindowsProcessNativeApi | null;
let readExitCode: (() => number | null) | null = null;
try {
file = programPath(program);
native = program === "schtasks" && args.includes("/hresult") ? windowsProcessNative() : null;
} catch (error) {
resolve({ status: null, stdout: "", stderr: error instanceof Error ? error.message : String(error), timedOut: false });
return;
}
const spawnTimeout = Math.floor(Math.min(deadline - performance.now(), control?.remainingMs?.() ?? Infinity));
if (!(spawnTimeout > 0) || control?.signal?.aborted) {
resolve({ status: null, stdout: "", stderr: "", timedOut: true });
return;
}
const helper = execFile(file, args, { encoding: "buffer", timeout: spawnTimeout, windowsHide: true, maxBuffer: 1024 * 1024, signal: control?.signal },
const helper = execFile(file, args, { encoding: "buffer", timeout, windowsHide: true, maxBuffer: 1024 * 1024 },
(error, stdout, stderr) => {
const text = (value: Buffer | string | undefined): string =>
value === undefined ? "" : typeof value === "string" ? value : decodeWindowsTextBytes(value);
const failure = error as (NodeJS.ErrnoException & { killed?: boolean; signal?: string | null; code?: number | string }) | null;
const windowsExitCode = readExitCode?.();
resolve({
status: failure ? (typeof failure.code === "number" ? failure.code : null) : 0,
...(windowsExitCode == null || failure?.killed ? {} : { windowsExitCode }),
stdout: text(stdout),
stderr: text(stderr),
timedOut: control?.signal?.aborted === true || !!failure?.killed && failure.signal !== null,
timedOut: !!failure?.killed && failure.signal !== null,
});
});
if (helper.pid !== undefined) readExitCode = native?.captureChildExitCode?.(helper.pid) ?? null;
if (authorizeProof) {
let pending = "", progressLine = "", authorized = false;
helper.stdout?.on("data", (chunk: Buffer) => {
progressLine += chunk.toString("latin1");
let end: number;
while ((end = progressLine.indexOf("\n")) >= 0) {
const line = progressLine.slice(0, end).replace(/\r$/, "");
progressLine = progressLine.slice(end + 1);
if (authorized && line === "stop-attempted") control?.onMutation?.();
}
});
let pending = "";
const onProof = async (chunk: Buffer): Promise<void> => {
pending += chunk.toString("latin1");
const end = pending.indexOf("\n");
if (end < 0) return;
const proofReceivedAt = performance.now();
helper.stdout?.off("data", onProof);
let approved = false;
try {
approved = await authorizeProof(pending.slice(0, end).replace(/\r$/, ""));
} catch { /* An authorizer failure leaves stdin unapproved. */ }
const now = performance.now();
const remaining = Math.floor(Math.min(deadline - now, control?.remainingMs?.() ?? Infinity));
authorized = approved && remaining > 0 && control?.signal?.aborted !== true;
// The helper started its stopwatch before sending proof. Measuring from receipt here
// gives it a conservative cutoff on that clock, even if our reply sits unread.
const stopBeforeMs = Math.floor(now - proofReceivedAt + remaining);
if (authorized && helper.stdin && !helper.stdin.destroyed && !helper.stdin.writableEnded) control?.onDispatch?.();
helper.stdin?.end(authorized ? `stop-before ${stopBeforeMs}\n` : "\n");
helper.stdin?.end(approved ? "stop\n" : "\n");
};
helper.stdin?.on("error", () => { /* execFile reports the helper's exit or timeout. */ });
helper.stdout?.on("data", onProof);
Expand Down Expand Up @@ -280,9 +225,6 @@ export interface WindowsCheckedStopLiveOptions {
scQcRun?: (timeoutMs: number) => Promise<WindowsStopCommandResult>;
/** The outer cap, checked before a manager stop and again after Scheduler proof. */
gate?: () => boolean;
/** Share the outer monotonic deadline and cancellation with manager helpers. */
remainingMs?: () => number;
signal?: AbortSignal;
snapshot?: (timeoutMs: number) => Promise<readonly WindowsStopProcessEntry[] | null>;
}

Expand Down Expand Up @@ -325,23 +267,12 @@ export function windowsCheckedStopLiveDeps(options: WindowsCheckedStopLiveOption
canonicalPaths: windowsStopCanonicalPaths(),
childPid: windowsStopChildPid(),
async probeScheduler(timeoutMs) {
const deadline = performance.now() + timeoutMs;
const unknown = { status: "unknown", detail: "the Task Scheduler query did not answer" } as const;
const direct = await run("schtasks", ["/query", "/tn", `\\${TASK}`, "/fo", "CSV", "/nh", "/hresult"], timeoutMs);
if (direct.timedOut || performance.now() >= deadline) return unknown;
if (direct.status === 0 && (direct.windowsExitCode ?? 0) === 0
&& direct.stdout.trimStart().toLowerCase().startsWith(`"\\${TASK}",`)) return { status: "present" };
if (direct.windowsExitCode !== undefined) {
const missing = 0x80070002; // HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND)
const statusAgrees = direct.status === 2 || (direct.status !== null && (direct.status >>> 0) === missing);
return direct.windowsExitCode === missing && statusAgrees ? { status: "absent" } : unknown;
}
const remaining = wholeTimeoutMs(deadline - performance.now());
if (remaining === null) return unknown;
const probe = await run("powershell", ["-NoProfile", "-NonInteractive", "-Command", TASK_REGISTRATION_SCRIPT], remaining);
if (probe.timedOut || probe.status !== 0 || performance.now() >= deadline) return unknown;
const status = probe.stdout.trim();
return status === "present" || status === "absent" ? { status } : unknown;
const started = Date.now();
const direct = await run("schtasks", ["/query", "/tn", TASK], timeoutMs);
if (direct.status === 0 && direct.stdout.includes(TASK)) return { status: "present" };
const listing = await run("schtasks", ["/query", "/fo", "CSV"], Math.max(1, timeoutMs - (Date.now() - started)));
if (listing.status !== 0 || listing.timedOut) return { status: "unknown", detail: "the Task Scheduler query did not answer" };
return windowsSchedulerCsvIncludesTask(listing.stdout, TASK) ? { status: "present" } : { status: "absent" };
Comment thread
lidge-jun marked this conversation as resolved.
Resolved
},
async probeWinsw(timeoutMs) {
// One cap covers both reads: the ownership query gets only what the state query left.
Expand All @@ -363,15 +294,13 @@ export function windowsCheckedStopLiveDeps(options: WindowsCheckedStopLiveOption
const whole = wholeTimeoutMs(timeoutMs);
return whole === null ? null : readScheduleServicePid({ timeoutMs: whole });
},
async endTask(timeoutMs, authorize, mutation) {
const finish = (verdict: WindowsTaskEndResult, attempted: boolean) => { mutation?.(attempted, false); return verdict; };
timeoutMs = Math.min(timeoutMs, options.remainingMs?.() ?? Infinity);
if (!gate() || !(timeoutMs >= 1) || options.signal?.aborted) return finish("failed", false);
async endTask(timeoutMs, authorize) {
if (!gate()) return "failed";
const deadline = performance.now() + Math.floor(timeoutMs);
const withinDeadline = () => performance.now() < deadline && gate();
const launcher = windowsLauncherVbsPath();
const script = Buffer.from(WINDOWS_TASK_INSTANCE_STOP_SCRIPT, "utf16le").toString("base64");
let approved = false, dispatched = false, observedMutation = false;
let approved = false;
let refusal: { cause: unknown } | undefined;
const ended = await run("powershell", ["-NoProfile", "-NoLogo", "-NonInteractive", "-EncodedCommand", script], timeoutMs,
async line => {
Expand All @@ -384,18 +313,13 @@ export function windowsCheckedStopLiveDeps(options: WindowsCheckedStopLiveOption
}
approved = withinDeadline();
return approved;
}, { remainingMs: options.remainingMs, signal: options.signal, onDispatch: () => { dispatched = true; mutation?.(false, true); }, onMutation: () => {
observedMutation = true;
mutation?.(true, false);
} });
});
if (refusal) throw refusal.cause;
const lines = ended.stdout.trim().split(/\r?\n/);
const attempted = observedMutation || lines.includes("stop-attempted");
if (ended.timedOut || ended.status !== 0) return finish("failed", attempted || dispatched);
const verdict = lines.at(-1);
if (verdict === "unverified-registration" || verdict === "denied") return finish(verdict, attempted);
if (approved && (verdict === "ended" || verdict === "not-running")) return finish(verdict, attempted || verdict === "ended");
return finish("failed", attempted || dispatched && verdict !== "failed");
if (ended.timedOut || ended.status !== 0) return "failed";
const verdict = ended.stdout.trim().split(/\r?\n/).at(-1);
if (verdict === "unverified-registration" || verdict === "denied") return verdict;
if (approved && (verdict === "ended" || verdict === "not-running")) return verdict;
return "failed";
},
async taskState(timeoutMs) {
const started = Date.now();
Expand All @@ -414,16 +338,15 @@ export function windowsCheckedStopLiveDeps(options: WindowsCheckedStopLiveOption
},
async winswStop(timeoutMs) {
if (!gate()) return "failed";
return classifyScStop(await run("sc", ["stop", WINSW_SERVICE_ID], timeoutMs, undefined,
{ remainingMs: options.remainingMs, signal: options.signal }));
return classifyScStop(await run("sc", ["stop", WINSW_SERVICE_ID], timeoutMs));
},
winswState: scQuery,
proxyAlive: () => {
const pid = windowsStopChildPid();
return pid === null ? false : isProcessAlive(pid);
},
openWatch: (pid, startTime) => openWindowsProcessWatch(pid, startTime),
terminate: (pid, startTime, timeoutMs) => gate() ? windowsStopTerminate(pid, startTime, timeoutMs) : { status: "unavailable" },
terminate: (pid, startTime, timeoutMs) => windowsStopTerminate(pid, startTime, timeoutMs),
};
}

Expand Down
Loading
Loading