@bitkyc08/opencodex 2.52.0 → 2.53.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.
- package/gui/dist/assets/index-BBOZWGB6.css +1 -0
- package/gui/dist/assets/index-BlO4Yl6q.js +128 -0
- package/gui/dist/index.html +2 -2
- package/native/remote-workspace-helper/Cargo.lock +130 -0
- package/native/remote-workspace-helper/Cargo.toml +24 -0
- package/native/remote-workspace-helper/src/main.rs +49 -0
- package/native/remote-workspace-helper/src/protocol.rs +246 -0
- package/native/remote-workspace-helper/src/sandbox/macos.rs +19 -0
- package/native/remote-workspace-helper/src/sandbox/mod.rs +77 -0
- package/native/remote-workspace-helper/src/sandbox/windows.rs +15 -0
- package/package.json +6 -1
- package/src/adapters/anthropic-image-normalize.ts +30 -2
- package/src/adapters/anthropic.ts +1 -1
- package/src/adapters/base.ts +8 -2
- package/src/adapters/cursor/cursor-errors.ts +12 -0
- package/src/adapters/cursor/thread-continuity.ts +93 -0
- package/src/adapters/cursor.ts +104 -73
- package/src/adapters/devin/cloud-direct/chat.ts +312 -23
- package/src/adapters/devin/cloud-direct/metadata.ts +31 -2
- package/src/adapters/devin/live-models.ts +70 -3
- package/src/adapters/devin.ts +281 -21
- package/src/adapters/google-wire-compiler.ts +14 -6
- package/src/adapters/google.ts +22 -8
- package/src/adapters/kiro/adapter.ts +316 -0
- package/src/adapters/kiro/conversation.ts +136 -0
- package/src/adapters/kiro/payload.ts +432 -0
- package/src/adapters/kiro/reasoning.ts +56 -0
- package/src/adapters/kiro/stream.ts +1153 -0
- package/src/adapters/kiro/usage.ts +223 -0
- package/src/adapters/kiro/wire.ts +76 -0
- package/src/adapters/kiro.ts +8 -2319
- package/src/adapters/mimo-free.ts +1 -1
- package/src/adapters/openai-chat-images.ts +101 -0
- package/src/adapters/openai-chat.ts +201 -181
- package/src/adapters/openai-responses.ts +92 -224
- package/src/adapters/registry.ts +0 -7
- package/src/adapters/run-turn-queue.ts +13 -6
- package/src/bridge.ts +14 -15
- package/src/chat/inbound.ts +29 -4
- package/src/chat/outbound.ts +145 -107
- package/src/claude/desktop-profile.ts +4 -6
- package/src/cli/account-api.ts +14 -0
- package/src/cli/account-extended.ts +1 -1
- package/src/cli/account-history.ts +60 -0
- package/src/cli/account-main.ts +80 -0
- package/src/cli/account.ts +11 -3
- package/src/cli/capabilities.ts +113 -0
- package/src/cli/catalog.ts +109 -0
- package/src/cli/dispatch.ts +9 -0
- package/src/cli/help.ts +2 -0
- package/src/cli/index.ts +2 -2
- package/src/cli/observe.ts +28 -1
- package/src/cli/opencode.ts +42 -8
- package/src/cli/provider-runtime.ts +11 -1
- package/src/cli/provider.ts +22 -2
- package/src/cli/registry.ts +21 -0
- package/src/cli/remote-workspace.ts +154 -0
- package/src/cli/status.ts +39 -7
- package/src/cli/usage-report.ts +14 -2
- package/src/client/hub-client.ts +34 -0
- package/src/client/hub-state.ts +9 -1
- package/src/codex/account-store.ts +78 -0
- package/src/codex/auth-api.ts +81 -54
- package/src/codex/auth-context.ts +45 -16
- package/src/codex/catalog/effort.ts +1 -1
- package/src/codex/catalog/metadata.ts +3 -6
- package/src/codex/catalog/native-models.ts +4 -4
- package/src/codex/catalog/parsing.ts +2 -20
- package/src/codex/catalog/provider-fetch.ts +10 -1
- package/src/codex/catalog/remote.ts +233 -0
- package/src/codex/catalog/sync.ts +403 -35
- package/src/codex/convergence.ts +1 -1
- package/src/codex/history-manifest.ts +36 -0
- package/src/codex/history-provider.ts +32 -5
- package/src/codex/inject.ts +9 -0
- package/src/codex/main-account.ts +113 -0
- package/src/codex/main-device-reauth-api.ts +89 -0
- package/src/codex/main-device-reauth.ts +217 -0
- package/src/codex/native-residue.ts +9 -2
- package/src/codex/quota-auto-refresh.ts +3 -2
- package/src/codex/quota-capacity.ts +98 -0
- package/src/codex/quota-history.ts +160 -0
- package/src/codex/quota-types.ts +8 -0
- package/src/codex/quota.ts +118 -91
- package/src/codex/refresh.ts +2 -1
- package/src/codex/routing.ts +90 -17
- package/src/codex/sync.ts +33 -4
- package/src/combos/request.ts +19 -1
- package/src/config/multi-agent-surface.ts +61 -0
- package/src/config/provider-validation.ts +176 -0
- package/src/config.ts +213 -11
- package/src/generated/compatibility-version.json +436 -168
- package/src/images/loop.ts +119 -36
- package/src/lib/admission.ts +12 -6
- package/src/lib/redact.ts +7 -0
- package/src/lib/translator-budget.ts +4 -3
- package/src/lib/windows-atomic-replace.ts +1 -0
- package/src/lib/windows-elevation.ts +1 -1
- package/src/oauth/chatgpt-device.ts +62 -5
- package/src/oauth/devin/cli-import.ts +130 -0
- package/src/oauth/devin.ts +63 -8
- package/src/oauth/index.ts +29 -14
- package/src/oauth/kiro.ts +18 -6
- package/src/oauth/login-cli.ts +9 -1
- package/src/oauth/meta-muse-device.ts +464 -0
- package/src/oauth/meta-muse.ts +123 -32
- package/src/oauth/pool-kernel.ts +9 -0
- package/src/oauth/pool-settings-capability.ts +2 -2
- package/src/oauth/store.ts +57 -0
- package/src/oauth/types.ts +31 -0
- package/src/providers/derive.ts +13 -3
- package/src/providers/devin-cli-authmode-migration.ts +57 -35
- package/src/providers/devin-provider-merge-migration.ts +240 -0
- package/src/providers/muse-key-quota.ts +117 -0
- package/src/providers/muse-subscription-usage.ts +14 -2
- package/src/providers/openai-sidecar.ts +25 -3
- package/src/providers/opencode-zen-rate-limit.ts +58 -0
- package/src/providers/provider-id-rewrite.ts +20 -5
- package/src/providers/quota-types.ts +12 -0
- package/src/providers/quota.ts +143 -102
- package/src/providers/reasoning-metadata.ts +543 -0
- package/src/providers/registry.ts +80 -49
- package/src/reasoning-effort.ts +26 -2
- package/src/remote/hub-usage.ts +32 -0
- package/src/remote-control/index.ts +192 -41
- package/src/remote-control/workspace-activation.ts +9 -0
- package/src/remote-control/workspace-agent-connection.ts +366 -0
- package/src/remote-control/workspace-claude-runtime.ts +243 -0
- package/src/remote-control/workspace-codex-runtime.ts +531 -0
- package/src/remote-control/workspace-codex-sandbox.ts +115 -0
- package/src/remote-control/workspace-command-runner.ts +748 -0
- package/src/remote-control/workspace-coordinator.ts +231 -0
- package/src/remote-control/workspace-device.ts +585 -0
- package/src/remote-control/workspace-executable.ts +43 -0
- package/src/remote-control/workspace-executor.ts +397 -0
- package/src/remote-control/workspace-hub.ts +519 -0
- package/src/remote-control/workspace-pi-runtime.ts +382 -0
- package/src/remote-control/workspace-process.ts +129 -0
- package/src/remote-control/workspace-rpc.ts +304 -0
- package/src/remote-control/workspace-runtime.ts +60 -0
- package/src/remote-control/workspace-secret-store.ts +39 -0
- package/src/remote-control/workspace-sessions.ts +799 -0
- package/src/remote-control/workspace-tool-bridge.ts +192 -0
- package/src/responses/code-mode-helper-compat.ts +22 -3
- package/src/responses/hosted-tool-policy.ts +0 -1
- package/src/responses/muse-tool-name-alias.ts +379 -0
- package/src/responses/plaintext-v2-agent-messages.ts +902 -0
- package/src/router.ts +7 -0
- package/src/routing/compatibility/behavior.ts +0 -1
- package/src/server/audio-client.ts +64 -0
- package/src/server/audio-dictation.ts +91 -0
- package/src/server/audio-live.ts +185 -0
- package/src/server/audio-transcriptions.ts +183 -0
- package/src/server/audio-upstream.ts +153 -0
- package/src/server/auth-cors.ts +61 -2
- package/src/server/chat-completions.ts +1 -1
- package/src/server/chat-native-sse.ts +92 -48
- package/src/server/chat-native.ts +37 -15
- package/src/server/hub-usage.ts +57 -0
- package/src/server/images.ts +4 -0
- package/src/server/index.ts +722 -57
- package/src/server/lifecycle.ts +5 -6
- package/src/server/live-call-bindings.ts +60 -0
- package/src/server/live.ts +12 -1
- package/src/server/management/agent-settings-routes.ts +25 -4
- package/src/server/management/api-access.ts +37 -0
- package/src/server/management/api-key-usage.ts +7 -2
- package/src/server/management/config-routes.ts +1 -18
- package/src/server/management/context.ts +15 -0
- package/src/server/management/logs-usage-routes.ts +2 -0
- package/src/server/management/oauth-account-routes.ts +39 -12
- package/src/server/management/provider-routes.ts +125 -2
- package/src/server/management/remote-workspace-routes.ts +140 -0
- package/src/server/management/route-registry.ts +15 -0
- package/src/server/management/usage-aggregate-cache.ts +14 -15
- package/src/server/management/usage-summary-cache.ts +2 -0
- package/src/server/management-api.ts +23 -0
- package/src/server/ports.ts +17 -0
- package/src/server/relay-eager.ts +4 -1
- package/src/server/relay.ts +70 -10
- package/src/server/request-decompress.ts +6 -3
- package/src/server/responses/agent-task-recovery.ts +25 -32
- package/src/server/responses/codex-auth-error.ts +11 -0
- package/src/server/responses/codex-ws-exchange.ts +52 -3
- package/src/server/responses/codex-ws-wire.ts +55 -0
- package/src/server/responses/compact.ts +9 -1
- package/src/server/responses/core.ts +337 -73
- package/src/server/responses/encrypted-payload.ts +45 -2
- package/src/server/responses/ws-upstream.ts +4 -1
- package/src/server/responses-self-named-namespace-scrub.ts +1 -3
- package/src/server/responses-undeclared-tool-guard.ts +1 -1
- package/src/server/search.ts +3 -0
- package/src/server/sse-payload-rewrite.ts +136 -51
- package/src/server/ws-bridge.ts +35 -1
- package/src/service/cli.ts +372 -0
- package/src/service/diagnostics.ts +340 -0
- package/src/service/guards.ts +303 -0
- package/src/service/health.ts +222 -0
- package/src/service/launchd.ts +853 -0
- package/src/service/orchestration.ts +617 -0
- package/src/service/repair.ts +334 -0
- package/src/service/state.ts +363 -0
- package/src/service/systemd.ts +229 -0
- package/src/service/windows-ops.ts +690 -0
- package/src/service/windows-scheduler.ts +769 -0
- package/src/service/windows-taskxml.ts +613 -0
- package/src/service.ts +22 -5550
- package/src/storage/cleanup/db.ts +258 -0
- package/src/storage/cleanup/execute.ts +358 -0
- package/src/storage/cleanup/paths.ts +189 -0
- package/src/storage/cleanup/pending.ts +140 -0
- package/src/storage/cleanup/preview.ts +292 -0
- package/src/storage/cleanup/reconcile.ts +347 -0
- package/src/storage/cleanup/restore.ts +932 -0
- package/src/storage/cleanup/satellite.ts +474 -0
- package/src/storage/cleanup/staging.ts +129 -0
- package/src/storage/cleanup/types.ts +98 -0
- package/src/storage/cleanup.ts +49 -3127
- package/src/types/accounts.ts +2 -0
- package/src/types/config.ts +13 -12
- package/src/types/provider.ts +37 -0
- package/src/types/request.ts +2 -0
- package/src/types/tools.ts +17 -5
- package/src/types.ts +1 -0
- package/src/usage/expected-prices.ts +127 -0
- package/src/usage/log.ts +58 -1
- package/src/vision/eligibility.ts +13 -2
- package/src/web-search/loop.ts +56 -3
- package/gui/dist/assets/index-CWXut3rG.js +0 -115
- package/gui/dist/assets/index-EdoPnm9_.css +0 -1
- package/src/adapters/devin-cli/acp.ts +0 -204
- package/src/adapters/devin-cli/adapter.ts +0 -345
- package/src/adapters/devin-cli/binary.ts +0 -69
- package/src/adapters/devin-cli/models.ts +0 -57
- package/src/oauth/devin-cli.ts +0 -149
- package/src/server/responses-reasoning-summary-rewrite.ts +0 -178
|
@@ -0,0 +1,769 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { findLiveProxy } from "../server/proxy-liveness";
|
|
3
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
4
|
+
import { join, resolve } from "node:path";
|
|
5
|
+
import { randomUUID } from "node:crypto";
|
|
6
|
+
import { ELEVATION_REQUEST_TIMEOUT_MS, OCX_ELEVATED_PROTOCOL_FAILED, raceWithTimeout, resolveTrustedWindowsSchtasksExe, startElevatedSchtasksCreateAndRun, runWindowsElevated, toWindowsSchtasksError, WindowsElevationError, type ElevatedSchedulerOutcome, type ElevatedSchtasksCreateAndRunExecution, type ElevatedSchtasksCreateAndRunResult } from "../lib/windows-elevation";
|
|
7
|
+
import { statusWinswRaw } from "../lib/winsw";
|
|
8
|
+
import { isTestHomeGuardArmed } from "../lib/test-home-guard";
|
|
9
|
+
import { TASK, windowsServiceScriptPath, windowsLauncherVbsPath, windowsTaskXmlPath, writeServiceInstallState } from "./state";
|
|
10
|
+
import { buildWindowsSchtasksCreateArgs, windowsTaskRegistrationOwnedByAttempt, windowsTaskRegistrationHealthy } from "./windows-taskxml";
|
|
11
|
+
import type { ExpectedWindowsTaskUserId } from "./windows-taskxml";
|
|
12
|
+
import { win32 } from "node:path";
|
|
13
|
+
import { WINSW_SERVICE_ID } from "../lib/winsw";
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Decode schtasks stdout. `/query /xml` emits UTF-16LE (often with BOM) because the
|
|
17
|
+
* registered task document is UTF-16; reading that as UTF-8 makes every health check
|
|
18
|
+
* fail ("registration present but unhealthy") and rolls back a successful elevated create.
|
|
19
|
+
*/
|
|
20
|
+
export function decodeSchtasksOutput(buffer: Buffer): string {
|
|
21
|
+
if (buffer.length === 0) return "";
|
|
22
|
+
const bomUtf16Le = buffer.length >= 2 && buffer[0] === 0xff && buffer[1] === 0xfe;
|
|
23
|
+
const bomUtf16Be = buffer.length >= 2 && buffer[0] === 0xfe && buffer[1] === 0xff;
|
|
24
|
+
const looksUtf16Le = buffer.length >= 4
|
|
25
|
+
&& buffer[1] === 0x00
|
|
26
|
+
&& buffer[3] === 0x00
|
|
27
|
+
&& buffer[0] !== 0x00;
|
|
28
|
+
if (bomUtf16Le || looksUtf16Le) {
|
|
29
|
+
return buffer.toString("utf16le").replace(/^\uFEFF/, "").trim();
|
|
30
|
+
}
|
|
31
|
+
if (bomUtf16Be) {
|
|
32
|
+
// Swap pairs then decode as utf16le.
|
|
33
|
+
const swapped = Buffer.alloc(buffer.length - 2);
|
|
34
|
+
for (let i = 2; i + 1 < buffer.length; i += 2) {
|
|
35
|
+
swapped[i - 2] = buffer[i + 1]!;
|
|
36
|
+
swapped[i - 1] = buffer[i]!;
|
|
37
|
+
}
|
|
38
|
+
return swapped.toString("utf16le").trim();
|
|
39
|
+
}
|
|
40
|
+
return buffer.toString("utf8").replace(/^\uFEFF/, "").trim();
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function runFile(file: string, args: string[]): string {
|
|
44
|
+
const buffer = execFileSync(file, args, {
|
|
45
|
+
encoding: "buffer",
|
|
46
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
47
|
+
windowsHide: true,
|
|
48
|
+
}) as Buffer;
|
|
49
|
+
return decodeSchtasksOutput(buffer);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function windowsSchtasks(): string {
|
|
53
|
+
return resolveTrustedWindowsSchtasksExe();
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function windowsWscript(): string {
|
|
57
|
+
const candidate = join(process.env.SystemRoot ?? "C:\\Windows", "System32", "wscript.exe");
|
|
58
|
+
return existsSync(candidate) ? candidate : "wscript.exe";
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
let querySchtasksForTests: ((args: string[]) => string) | null = null;
|
|
62
|
+
|
|
63
|
+
export function querySchtasks(args: string[]): string {
|
|
64
|
+
// The repository preload isolates HOME and OPENCODEX_HOME, but Task Scheduler is
|
|
65
|
+
// machine-global. A partially-faked service test once fell through here and replaced the
|
|
66
|
+
// user's real `opencodex-proxy` task with a launcher inside its temporary test home; the
|
|
67
|
+
// test passed and cleanup deleted that launcher. Queries are observation-only, but every
|
|
68
|
+
// other operation must be injected while the explicit test-home guard is armed.
|
|
69
|
+
if (
|
|
70
|
+
isTestHomeGuardArmed()
|
|
71
|
+
&& args[0]?.trim().toLowerCase() !== "/query"
|
|
72
|
+
) {
|
|
73
|
+
throw new Error(
|
|
74
|
+
"refusing to mutate the machine-global Windows Task Scheduler from an armed test process; "
|
|
75
|
+
+ "inject the scheduler operation instead of calling the live manager.",
|
|
76
|
+
);
|
|
77
|
+
}
|
|
78
|
+
if (querySchtasksForTests) return querySchtasksForTests(args);
|
|
79
|
+
return runFile(windowsSchtasks(), args);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Test-only seam for Task Scheduler query used by presence probes. */
|
|
83
|
+
export function setQuerySchtasksForTests(next: ((args: string[]) => string) | null): void {
|
|
84
|
+
querySchtasksForTests = next;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export function schtasks(args: string[]): string {
|
|
88
|
+
try {
|
|
89
|
+
return querySchtasks(args);
|
|
90
|
+
} catch (error) {
|
|
91
|
+
throw toWindowsSchtasksError(error, args);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Tri-state Task Scheduler presence: never treat a failed query as proven absence. */
|
|
96
|
+
export type WindowsSchedulerTaskProbe =
|
|
97
|
+
| { status: "present" }
|
|
98
|
+
| { status: "absent" }
|
|
99
|
+
| { status: "unknown"; detail: string };
|
|
100
|
+
|
|
101
|
+
export type WindowsSchedulerProxyProbe =
|
|
102
|
+
| { status: "running"; port: number }
|
|
103
|
+
| { status: "not-running" }
|
|
104
|
+
| { status: "unknown" };
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Render Task Scheduler status without exposing localized `schtasks` table output.
|
|
108
|
+
* The task probe answers installation state; the identity-checked health probe answers
|
|
109
|
+
* runtime state. Keep probe details out of this user-facing line because they can contain
|
|
110
|
+
* incorrectly decoded, locale-specific command output.
|
|
111
|
+
*/
|
|
112
|
+
export function formatWindowsSchedulerServiceStatus(
|
|
113
|
+
task: WindowsSchedulerTaskProbe,
|
|
114
|
+
proxy: WindowsSchedulerProxyProbe,
|
|
115
|
+
): string {
|
|
116
|
+
if (task.status === "present") {
|
|
117
|
+
if (proxy.status === "running") {
|
|
118
|
+
return `✅ service installed (Task Scheduler); OpenCodex proxy running on port ${proxy.port}.`;
|
|
119
|
+
}
|
|
120
|
+
if (proxy.status === "not-running") {
|
|
121
|
+
return "⚠️ service installed (Task Scheduler); OpenCodex proxy not running.";
|
|
122
|
+
}
|
|
123
|
+
return "⚠️ service installed (Task Scheduler); OpenCodex proxy status unknown.";
|
|
124
|
+
}
|
|
125
|
+
if (task.status === "absent") {
|
|
126
|
+
if (proxy.status === "running") {
|
|
127
|
+
return `❌ service not installed (Task Scheduler); OpenCodex proxy is running independently on port ${proxy.port}.`;
|
|
128
|
+
}
|
|
129
|
+
if (proxy.status === "unknown") {
|
|
130
|
+
return "❌ service not installed (Task Scheduler); OpenCodex proxy status unknown.";
|
|
131
|
+
}
|
|
132
|
+
return "❌ service not installed (Task Scheduler).";
|
|
133
|
+
}
|
|
134
|
+
if (proxy.status === "running") {
|
|
135
|
+
return `⚠️ Task Scheduler registration unknown; OpenCodex proxy running on port ${proxy.port}.`;
|
|
136
|
+
}
|
|
137
|
+
if (proxy.status === "not-running") {
|
|
138
|
+
return "⚠️ service status unknown (Task Scheduler query failed); OpenCodex proxy not running.";
|
|
139
|
+
}
|
|
140
|
+
return "⚠️ service status unknown (Task Scheduler and proxy checks failed).";
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export async function inspectWindowsSchedulerServiceStatus(io: {
|
|
144
|
+
probeTask?: () => WindowsSchedulerTaskProbe;
|
|
145
|
+
findProxy?: () => Promise<{ port: number } | null>;
|
|
146
|
+
} = {}): Promise<string> {
|
|
147
|
+
let task: WindowsSchedulerTaskProbe;
|
|
148
|
+
try {
|
|
149
|
+
task = (io.probeTask ?? probeWindowsSchedulerTask)();
|
|
150
|
+
} catch (error) {
|
|
151
|
+
task = { status: "unknown", detail: schtasksErrorDetail(error) };
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
let proxy: WindowsSchedulerProxyProbe;
|
|
155
|
+
try {
|
|
156
|
+
const live = await (io.findProxy ?? findLiveProxy)();
|
|
157
|
+
proxy = live ? { status: "running", port: live.port } : { status: "not-running" };
|
|
158
|
+
} catch {
|
|
159
|
+
proxy = { status: "unknown" };
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
return formatWindowsSchedulerServiceStatus(task, proxy);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
export function schtasksErrorDetail(error: unknown): string {
|
|
166
|
+
return error instanceof Error ? error.message : String(error);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** True when a schtasks CSV listing line refers to the given task name. */
|
|
170
|
+
export function windowsSchedulerCsvIncludesTask(csv: string, taskName: string): boolean {
|
|
171
|
+
const needle = taskName.toLowerCase();
|
|
172
|
+
for (const line of csv.split(/\r?\n/)) {
|
|
173
|
+
const lower = line.toLowerCase();
|
|
174
|
+
if (!lower.includes(needle)) continue;
|
|
175
|
+
// Prefer exact CSV field matches ("\TaskName" / "TaskName") before a substring hit.
|
|
176
|
+
if (
|
|
177
|
+
lower.includes(`"\\${needle}"`)
|
|
178
|
+
|| lower.includes(`"${needle}"`)
|
|
179
|
+
|| new RegExp(`(^|[,\\\\])${needle.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}([,"]|$)`).test(lower)
|
|
180
|
+
) {
|
|
181
|
+
return true;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
return false;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Probe whether the OpenCodex Task Scheduler task exists.
|
|
189
|
+
* Query failures fall back to a CSV listing before concluding absence; if both
|
|
190
|
+
* fail, returns `unknown` so callers can fail closed instead of releasing locks.
|
|
191
|
+
*/
|
|
192
|
+
export function probeWindowsSchedulerTask(taskName = TASK): WindowsSchedulerTaskProbe {
|
|
193
|
+
if (process.platform !== "win32") return { status: "absent" };
|
|
194
|
+
|
|
195
|
+
let queryFailure: string | null = null;
|
|
196
|
+
try {
|
|
197
|
+
const out = querySchtasks(["/query", "/tn", taskName]);
|
|
198
|
+
if (out.includes(taskName)) return { status: "present" };
|
|
199
|
+
} catch (error) {
|
|
200
|
+
queryFailure = schtasksErrorDetail(error);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
try {
|
|
204
|
+
const csv = querySchtasks(["/query", "/fo", "CSV"]);
|
|
205
|
+
if (windowsSchedulerCsvIncludesTask(csv, taskName)) return { status: "present" };
|
|
206
|
+
return { status: "absent" };
|
|
207
|
+
} catch (error) {
|
|
208
|
+
const listDetail = schtasksErrorDetail(error);
|
|
209
|
+
const detail = queryFailure
|
|
210
|
+
? `Specific query failed (${queryFailure}); CSV listing also failed (${listDetail}).`
|
|
211
|
+
: `Task query did not confirm presence and CSV listing failed (${listDetail}).`;
|
|
212
|
+
return { status: "unknown", detail };
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** True when the Task Scheduler registration for the default proxy task is proven present. */
|
|
217
|
+
export function windowsSchedulerTaskInstalled(taskName = TASK): boolean {
|
|
218
|
+
return probeWindowsSchedulerTask(taskName).status === "present";
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
export interface WindowsSchedulerInstallVerification {
|
|
222
|
+
taskInstalled: boolean;
|
|
223
|
+
registrationHealthy: boolean;
|
|
224
|
+
/** Well-formed XML that is PUBLISHED but policy-violating — permanent, never
|
|
225
|
+
* worth a settle retry (vs an empty/unreadable view, which is publication
|
|
226
|
+
* lag and transient). */
|
|
227
|
+
registrationInvalid: boolean;
|
|
228
|
+
assetsHealthy: boolean;
|
|
229
|
+
nativeServiceAbsent: boolean;
|
|
230
|
+
/** True when SCM probe failed; not a proven WinSW presence. */
|
|
231
|
+
nativeStatusUnknown: boolean;
|
|
232
|
+
conflict: boolean;
|
|
233
|
+
ok: boolean;
|
|
234
|
+
detail: string;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** Pure postcondition evaluation for an elevated scheduler install. */
|
|
238
|
+
export function evaluateWindowsSchedulerInstallVerification(inputs: {
|
|
239
|
+
taskInstalled: boolean;
|
|
240
|
+
xml: string;
|
|
241
|
+
assetsExist: boolean;
|
|
242
|
+
nativeStatus: "started" | "stopped" | "nonexistent" | "unknown";
|
|
243
|
+
wscript?: string;
|
|
244
|
+
launcher?: string;
|
|
245
|
+
expectedUserId?: ExpectedWindowsTaskUserId | null;
|
|
246
|
+
}): WindowsSchedulerInstallVerification {
|
|
247
|
+
const registrationHealthy = inputs.xml.length > 0
|
|
248
|
+
&& windowsTaskRegistrationHealthy(inputs.xml, inputs.wscript, inputs.launcher, inputs.expectedUserId);
|
|
249
|
+
// Permanent invalidity: the XML IS published but violates the registration
|
|
250
|
+
// contract — no amount of settling changes it. Empty/unreadable XML stays
|
|
251
|
+
// transient (publication lag).
|
|
252
|
+
const registrationInvalid = inputs.taskInstalled && inputs.xml.length > 0 && !registrationHealthy;
|
|
253
|
+
const assetsHealthy = inputs.assetsExist;
|
|
254
|
+
const nativeServiceAbsent = inputs.nativeStatus === "nonexistent";
|
|
255
|
+
const nativeStatusUnknown = inputs.nativeStatus === "unknown";
|
|
256
|
+
// Only treat proven WinSW presence as a backend conflict — never "unknown".
|
|
257
|
+
const conflict = inputs.taskInstalled
|
|
258
|
+
&& (inputs.nativeStatus === "started" || inputs.nativeStatus === "stopped");
|
|
259
|
+
const ok = inputs.taskInstalled && registrationHealthy && assetsHealthy && nativeServiceAbsent && !conflict;
|
|
260
|
+
const detail = !inputs.taskInstalled
|
|
261
|
+
? "Task Scheduler task is not installed."
|
|
262
|
+
: conflict
|
|
263
|
+
? `CONFLICT: Task Scheduler and native WinSW (${WINSW_SERVICE_ID}) are both present.`
|
|
264
|
+
: !assetsHealthy
|
|
265
|
+
? "Required scheduler service assets are missing."
|
|
266
|
+
: !registrationHealthy
|
|
267
|
+
? (inputs.xml.trim()
|
|
268
|
+
? "Task Scheduler registration is present but unhealthy."
|
|
269
|
+
: "Task Scheduler task is present but its XML could not be read.")
|
|
270
|
+
: nativeStatusUnknown
|
|
271
|
+
? "The Task Scheduler task was created, but OpenCodex could not verify that the native WinSW service is absent."
|
|
272
|
+
: "ok";
|
|
273
|
+
return {
|
|
274
|
+
taskInstalled: inputs.taskInstalled,
|
|
275
|
+
registrationHealthy,
|
|
276
|
+
registrationInvalid,
|
|
277
|
+
assetsHealthy,
|
|
278
|
+
nativeServiceAbsent,
|
|
279
|
+
nativeStatusUnknown,
|
|
280
|
+
conflict,
|
|
281
|
+
ok,
|
|
282
|
+
detail,
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/** Conflict-free postcondition check for an elevated scheduler install. */
|
|
287
|
+
export function verifyWindowsSchedulerInstall(taskName = TASK): WindowsSchedulerInstallVerification {
|
|
288
|
+
const taskInstalled = windowsSchedulerTaskInstalled(taskName);
|
|
289
|
+
let xml = "";
|
|
290
|
+
if (taskInstalled) {
|
|
291
|
+
try { xml = querySchtasks(["/query", "/tn", taskName, "/xml"]); } catch { xml = ""; }
|
|
292
|
+
}
|
|
293
|
+
// After elevated create, non-elevated `/query /xml` can fail or return empty while the
|
|
294
|
+
// task is still listed. Fall back to the on-disk document we registered.
|
|
295
|
+
if (taskInstalled && !xml.trim()) {
|
|
296
|
+
const diskPath = windowsTaskXmlPath();
|
|
297
|
+
if (existsSync(diskPath)) {
|
|
298
|
+
try { xml = decodeSchtasksOutput(readFileSync(diskPath)); } catch { /* keep empty */ }
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
return evaluateWindowsSchedulerInstallVerification({
|
|
302
|
+
taskInstalled,
|
|
303
|
+
xml,
|
|
304
|
+
assetsExist: [windowsServiceScriptPath(), windowsLauncherVbsPath(), windowsTaskXmlPath()].every(existsSync),
|
|
305
|
+
nativeStatus: statusWinswRaw(),
|
|
306
|
+
});
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
async function elevateSchtasks(args: string[]): Promise<void> {
|
|
310
|
+
const exitCode = await runWindowsElevated(windowsSchtasks(), args);
|
|
311
|
+
if (exitCode !== 0) {
|
|
312
|
+
throw new Error(`Background service install failed with exit code ${exitCode}.`);
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
export interface WindowsSchedulerRollbackDeps {
|
|
317
|
+
queryXml?: () => string;
|
|
318
|
+
deleteTask?: () => Promise<void>;
|
|
319
|
+
probe?: () => WindowsSchedulerTaskProbe;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
export async function rollbackWindowsSchedulerTaskOwnedByAttempt(
|
|
323
|
+
attemptNonce: string,
|
|
324
|
+
taskName = TASK,
|
|
325
|
+
deps: WindowsSchedulerRollbackDeps = {},
|
|
326
|
+
): Promise<string | null> {
|
|
327
|
+
let registeredXml = "";
|
|
328
|
+
try {
|
|
329
|
+
registeredXml = (deps.queryXml ?? (() => querySchtasks(["/query", "/tn", taskName, "/xml"])))();
|
|
330
|
+
} catch (error) {
|
|
331
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
332
|
+
return `Task Scheduler task ${taskName} ownership could not be proven: ${detail}. Residual scheduler state: task ${taskName} presence is unknown; no rollback deletion was attempted.`;
|
|
333
|
+
}
|
|
334
|
+
if (!registeredXml.trim()) {
|
|
335
|
+
return `Task Scheduler task ${taskName} ownership could not be proven because its live XML was empty. Residual scheduler state: task ${taskName} presence is unknown; no rollback deletion was attempted.`;
|
|
336
|
+
}
|
|
337
|
+
if (!windowsTaskRegistrationOwnedByAttempt(registeredXml, attemptNonce)) {
|
|
338
|
+
return `Task Scheduler task ${taskName} ownership could not be proven because its attempt nonce does not match. Residual scheduler state: task ${taskName} remains registered; no rollback deletion was attempted.`;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
try {
|
|
342
|
+
await (deps.deleteTask ?? (() => elevateSchtasks(["/delete", "/tn", taskName, "/f"])))();
|
|
343
|
+
} catch (error) {
|
|
344
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
345
|
+
return `Rollback deletion failed: ${detail}. Residual scheduler state: task ${taskName} may remain registered.`;
|
|
346
|
+
}
|
|
347
|
+
const probe = (deps.probe ?? (() => resolveWindowsSchedulerTaskProbe(taskName)))();
|
|
348
|
+
if (probe.status === "absent") return null;
|
|
349
|
+
if (probe.status === "unknown") {
|
|
350
|
+
return `Task Scheduler task ${taskName} presence could not be verified after rollback: ${probe.detail}. Residual scheduler state: task presence is unknown.`;
|
|
351
|
+
}
|
|
352
|
+
return `Residual scheduler state: task ${taskName} is still present after rollback.`;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
// Legacy dashboard finalization creates and runs in one elevated child, whose protocol
|
|
356
|
+
// performs its own rollback before returning. This fallback remains for indeterminate
|
|
357
|
+
// protocol outcomes that predate the staged CLI transaction.
|
|
358
|
+
async function rollbackElevatedSchedulerTask(taskName = TASK): Promise<string | null> {
|
|
359
|
+
try {
|
|
360
|
+
await elevateSchtasks(["/delete", "/tn", taskName, "/f"]);
|
|
361
|
+
} catch (error) {
|
|
362
|
+
return error instanceof Error ? error.message : String(error);
|
|
363
|
+
}
|
|
364
|
+
const probe = resolveWindowsSchedulerTaskProbe(taskName);
|
|
365
|
+
if (probe.status === "absent") return null;
|
|
366
|
+
if (probe.status === "unknown") {
|
|
367
|
+
return `Task Scheduler task ${taskName} presence could not be verified after rollback: ${probe.detail}`;
|
|
368
|
+
}
|
|
369
|
+
return `Task Scheduler task ${taskName} is still present after rollback.`;
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
type ElevateCreateAndRunStart = (
|
|
373
|
+
schtasksPath: string,
|
|
374
|
+
createArgs: string[],
|
|
375
|
+
runArgs: string[],
|
|
376
|
+
deleteArgs: string[],
|
|
377
|
+
) => ElevatedSchtasksCreateAndRunExecution;
|
|
378
|
+
|
|
379
|
+
type FinalizeHooks = {
|
|
380
|
+
startElevateCreateAndRun?: ElevateCreateAndRunStart;
|
|
381
|
+
/** Legacy sync hook used by older tests — wraps a resolved result as an execution. */
|
|
382
|
+
elevateCreateAndRun?: (
|
|
383
|
+
schtasksPath: string,
|
|
384
|
+
createArgs: string[],
|
|
385
|
+
runArgs: string[],
|
|
386
|
+
deleteArgs: string[],
|
|
387
|
+
) => Promise<ElevatedSchtasksCreateAndRunResult>;
|
|
388
|
+
verify?: () => WindowsSchedulerInstallVerification;
|
|
389
|
+
writeInstallState?: () => void;
|
|
390
|
+
/** Preferred tri-state probe for security-sensitive reconciliation. */
|
|
391
|
+
probeTask?: () => WindowsSchedulerTaskProbe;
|
|
392
|
+
/** Legacy boolean hook; mapped to present/absent when probeTask is unset. */
|
|
393
|
+
taskInstalled?: () => boolean;
|
|
394
|
+
/** Defense-in-depth: late reconciliation must still own this attempt. */
|
|
395
|
+
stillOwnsAttempt?: (attemptId: string) => boolean;
|
|
396
|
+
requestTimeoutMs?: number;
|
|
397
|
+
/** Test-only seam for the post-create settle backoff; real installs use a timer. */
|
|
398
|
+
settleDelay?: (ms: number) => Promise<void>;
|
|
399
|
+
};
|
|
400
|
+
|
|
401
|
+
let finalizeHooks: FinalizeHooks | null = null;
|
|
402
|
+
|
|
403
|
+
function resolveWindowsSchedulerTaskProbe(taskName = TASK): WindowsSchedulerTaskProbe {
|
|
404
|
+
if (finalizeHooks?.probeTask) return finalizeHooks.probeTask();
|
|
405
|
+
if (finalizeHooks?.taskInstalled) {
|
|
406
|
+
return finalizeHooks.taskInstalled() ? { status: "present" } : { status: "absent" };
|
|
407
|
+
}
|
|
408
|
+
return probeWindowsSchedulerTask(taskName);
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/** Test-only hooks for elevated create+run finalization. */
|
|
412
|
+
export function setFinalizeWindowsSchedulerHooksForTests(hooks: FinalizeHooks | null): void {
|
|
413
|
+
finalizeHooks = hooks;
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
function throwPartialInstall(parts: string[]): never {
|
|
417
|
+
throw new Error(parts.filter(Boolean).join(" "));
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/**
|
|
421
|
+
* Reconcile an unrecognized elevated exit when we cannot trust the phase code.
|
|
422
|
+
* Never invent a create-vs-run classification; inspect actual task state first.
|
|
423
|
+
* An unverifiable probe must fail closed (partial / blocked), never release.
|
|
424
|
+
*/
|
|
425
|
+
async function reconcileUnknownElevatedOutcome(exitCode: number): Promise<void> {
|
|
426
|
+
const probe = resolveWindowsSchedulerTaskProbe();
|
|
427
|
+
const parts = [
|
|
428
|
+
"The elevated Task Scheduler operation returned an unknown result.",
|
|
429
|
+
`Exit code: ${exitCode}.`,
|
|
430
|
+
"OpenCodex could not prove whether task creation completed, so installation state was not written.",
|
|
431
|
+
];
|
|
432
|
+
if (probe.status === "unknown") {
|
|
433
|
+
parts.push(`Task Scheduler presence could not be verified: ${probe.detail}`);
|
|
434
|
+
parts.push("A partial Task Scheduler backend may remain.");
|
|
435
|
+
throwPartialInstall(parts);
|
|
436
|
+
}
|
|
437
|
+
if (probe.status === "absent") {
|
|
438
|
+
parts.push("No OpenCodex Task Scheduler task was found after the elevated operation.");
|
|
439
|
+
throwPartialInstall(parts);
|
|
440
|
+
}
|
|
441
|
+
parts.push("A Task Scheduler task is present; attempting cleanup.");
|
|
442
|
+
const rollbackError = await rollbackElevatedSchedulerTask();
|
|
443
|
+
if (rollbackError) {
|
|
444
|
+
parts.push(`Cleanup also failed: ${rollbackError}`);
|
|
445
|
+
parts.push(`Remove the task manually with 'schtasks /delete /tn ${TASK} /f' if it remains.`);
|
|
446
|
+
} else {
|
|
447
|
+
parts.push("The elevated Task Scheduler task was removed.");
|
|
448
|
+
}
|
|
449
|
+
throwPartialInstall(parts);
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
type ApplyElevatedOptions = {
|
|
453
|
+
attemptId: string;
|
|
454
|
+
writeOnSuccess: boolean;
|
|
455
|
+
stillOwnsAttempt?: (attemptId: string) => boolean;
|
|
456
|
+
};
|
|
457
|
+
|
|
458
|
+
function attemptStillOwned(options: ApplyElevatedOptions): boolean {
|
|
459
|
+
const check = options.stillOwnsAttempt ?? finalizeHooks?.stillOwnsAttempt;
|
|
460
|
+
return !check || check(options.attemptId);
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
/**
|
|
464
|
+
* Bounded post-create backoff, 1.1s total. Task Scheduler's non-elevated view can
|
|
465
|
+
* lag an elevated `/create` by a few hundred milliseconds, so a single verification
|
|
466
|
+
* would roll back a task that is merely not visible yet.
|
|
467
|
+
*/
|
|
468
|
+
export const SCHEDULER_SETTLE_DELAYS_MS = [50, 150, 300, 600] as const;
|
|
469
|
+
|
|
470
|
+
/**
|
|
471
|
+
* Whether a failed verification is still worth re-checking after a short delay.
|
|
472
|
+
*
|
|
473
|
+
* Retrying is confined to states that a lagging scheduler view actually produces:
|
|
474
|
+
* the task is not visible yet, or it is visible but its registration has not been
|
|
475
|
+
* published in full. Everything else keeps its existing fail-closed meaning and is
|
|
476
|
+
* rejected here so no delay can turn it into a pass:
|
|
477
|
+
*
|
|
478
|
+
* - a proven conflict (both backends present) is a real dual-backend install;
|
|
479
|
+
* - missing assets are missing on disk, which no amount of waiting creates;
|
|
480
|
+
* - a WinSW service that is proven present (`started`/`stopped`) is never absent
|
|
481
|
+
* later. This is checked independently of `conflict`, which only becomes true
|
|
482
|
+
* once the task itself is visible — while the task is still invisible the pair
|
|
483
|
+
* is `conflict: false` with `nativeServiceAbsent: false`, and that must not retry;
|
|
484
|
+
* - unknown SCM status is unproven rather than transient, and has its own
|
|
485
|
+
* task-preserving branch below.
|
|
486
|
+
*/
|
|
487
|
+
/** Exported for tests: the transient-vs-permanent settle decision. */
|
|
488
|
+
export function schedulerVerificationMaySettle(v: WindowsSchedulerInstallVerification): boolean {
|
|
489
|
+
if (v.ok) return false;
|
|
490
|
+
if (v.conflict) return false;
|
|
491
|
+
if (!v.assetsHealthy) return false;
|
|
492
|
+
if (!v.nativeServiceAbsent) return false;
|
|
493
|
+
// A published-but-invalid registration is permanent: no delay repairs it.
|
|
494
|
+
if (v.registrationInvalid) return false;
|
|
495
|
+
return !v.taskInstalled || !v.registrationHealthy;
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
export function settleDelay(ms: number): Promise<void> {
|
|
499
|
+
const hook = finalizeHooks?.settleDelay;
|
|
500
|
+
if (hook) return hook(ms);
|
|
501
|
+
return new Promise(resolve => setTimeout(resolve, ms));
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
/**
|
|
505
|
+
* Verify the elevated install, re-checking only while the failure looks like a
|
|
506
|
+
* scheduler view that has not caught up yet. Returns `null` when this attempt lost
|
|
507
|
+
* ownership mid-settle: a newer attempt owns the task, so this one must neither
|
|
508
|
+
* write install state nor roll anything back.
|
|
509
|
+
*/
|
|
510
|
+
async function verifyWindowsSchedulerInstallAfterSettle(
|
|
511
|
+
options: ApplyElevatedOptions,
|
|
512
|
+
): Promise<WindowsSchedulerInstallVerification | null> {
|
|
513
|
+
const verify = finalizeHooks?.verify ?? verifyWindowsSchedulerInstall;
|
|
514
|
+
let verification = verify();
|
|
515
|
+
for (const delayMs of SCHEDULER_SETTLE_DELAYS_MS) {
|
|
516
|
+
if (!schedulerVerificationMaySettle(verification)) break;
|
|
517
|
+
if (!attemptStillOwned(options)) return null;
|
|
518
|
+
await settleDelay(delayMs);
|
|
519
|
+
if (!attemptStillOwned(options)) return null;
|
|
520
|
+
verification = verify();
|
|
521
|
+
}
|
|
522
|
+
return verification;
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
async function applyElevatedSchedulerResult(
|
|
526
|
+
result: ElevatedSchtasksCreateAndRunResult,
|
|
527
|
+
options: ApplyElevatedOptions,
|
|
528
|
+
): Promise<void> {
|
|
529
|
+
if (!attemptStillOwned(options)) {
|
|
530
|
+
return;
|
|
531
|
+
}
|
|
532
|
+
const outcome: ElevatedSchedulerOutcome = result.outcome;
|
|
533
|
+
|
|
534
|
+
if (outcome === "create-failed") {
|
|
535
|
+
throw new Error("Elevated schtasks /create failed. The Task Scheduler task was not registered.");
|
|
536
|
+
}
|
|
537
|
+
if (outcome === "run-failed-rolled-back") {
|
|
538
|
+
throw new Error(
|
|
539
|
+
"Elevated schtasks /run failed after the task was registered. The elevated process rolled the task back. Installation state was not written.",
|
|
540
|
+
);
|
|
541
|
+
}
|
|
542
|
+
if (outcome === "run-failed-rollback-failed") {
|
|
543
|
+
throwPartialInstall([
|
|
544
|
+
"Elevated schtasks /run failed after the task was registered, and elevated rollback also failed.",
|
|
545
|
+
"A partial Task Scheduler backend may remain.",
|
|
546
|
+
`Remove the task manually with 'schtasks /delete /tn ${TASK} /f' if present.`,
|
|
547
|
+
"Installation state was not written.",
|
|
548
|
+
]);
|
|
549
|
+
}
|
|
550
|
+
if (outcome !== "success") {
|
|
551
|
+
await reconcileUnknownElevatedOutcome(result.exitCode);
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
const verification = await verifyWindowsSchedulerInstallAfterSettle(options);
|
|
555
|
+
// Ownership moved to a newer attempt while settling; that attempt owns the outcome.
|
|
556
|
+
if (!verification) return;
|
|
557
|
+
if (!verification.ok) {
|
|
558
|
+
// Preserve a healthy elevated task when WinSW absence cannot be proven (unknown SCM status).
|
|
559
|
+
// Unknown is not a confirmed dual-backend conflict; install state is still withheld.
|
|
560
|
+
const preserveElevatedTask = verification.taskInstalled
|
|
561
|
+
&& verification.registrationHealthy
|
|
562
|
+
&& verification.assetsHealthy
|
|
563
|
+
&& !verification.conflict
|
|
564
|
+
&& verification.nativeStatusUnknown;
|
|
565
|
+
if (preserveElevatedTask) {
|
|
566
|
+
throwPartialInstall([
|
|
567
|
+
"Elevated Task Scheduler registration did not produce a conflict-free install.",
|
|
568
|
+
verification.detail,
|
|
569
|
+
"The elevated Task Scheduler task was left in place because native WinSW status could not be verified.",
|
|
570
|
+
"Installation state was not written.",
|
|
571
|
+
]);
|
|
572
|
+
}
|
|
573
|
+
// Rollback deletes a real task, so it needs the same ownership fence as the
|
|
574
|
+
// state write below: a stale attempt must never delete a newer attempt's task.
|
|
575
|
+
if (!attemptStillOwned(options)) return;
|
|
576
|
+
const rollbackError = await rollbackElevatedSchedulerTask();
|
|
577
|
+
const parts = [
|
|
578
|
+
"Elevated Task Scheduler registration did not produce a conflict-free install.",
|
|
579
|
+
verification.detail,
|
|
580
|
+
];
|
|
581
|
+
if (rollbackError) {
|
|
582
|
+
parts.push(`Rollback also failed: ${rollbackError}`);
|
|
583
|
+
parts.push(`Remove the task manually with 'schtasks /delete /tn ${TASK} /f' and the native service with 'sc delete ${WINSW_SERVICE_ID}' if present.`);
|
|
584
|
+
} else {
|
|
585
|
+
parts.push("The elevated Task Scheduler task was rolled back.");
|
|
586
|
+
}
|
|
587
|
+
parts.push("Installation state was not written.");
|
|
588
|
+
throwPartialInstall(parts);
|
|
589
|
+
}
|
|
590
|
+
if (options.writeOnSuccess) {
|
|
591
|
+
if (!attemptStillOwned(options)) {
|
|
592
|
+
return;
|
|
593
|
+
}
|
|
594
|
+
(finalizeHooks?.writeInstallState ?? (() => writeServiceInstallState("scheduler")))();
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
/** Outcome of late reconciliation after a request-level elevation timeout. */
|
|
599
|
+
export type ElevatedReconciliationOutcome =
|
|
600
|
+
| "released"
|
|
601
|
+
| "blocked-partial";
|
|
602
|
+
|
|
603
|
+
export type FinalizeWindowsSchedulerResult =
|
|
604
|
+
| { kind: "done" }
|
|
605
|
+
| {
|
|
606
|
+
kind: "indeterminate";
|
|
607
|
+
attemptId: string;
|
|
608
|
+
/** Settles after the elevated transaction finishes and late reconciliation runs. */
|
|
609
|
+
reconciliation: Promise<ElevatedReconciliationOutcome>;
|
|
610
|
+
};
|
|
611
|
+
|
|
612
|
+
export type FinalizeWindowsSchedulerOptions = {
|
|
613
|
+
attemptId?: string;
|
|
614
|
+
stillOwnsAttempt?: (attemptId: string) => boolean;
|
|
615
|
+
requestTimeoutMs?: number;
|
|
616
|
+
};
|
|
617
|
+
|
|
618
|
+
function startElevateExecution(
|
|
619
|
+
schtasksPath: string,
|
|
620
|
+
createArgs: string[],
|
|
621
|
+
runArgs: string[],
|
|
622
|
+
deleteArgs: string[],
|
|
623
|
+
): ElevatedSchtasksCreateAndRunExecution {
|
|
624
|
+
if (finalizeHooks?.startElevateCreateAndRun) {
|
|
625
|
+
return finalizeHooks.startElevateCreateAndRun(schtasksPath, createArgs, runArgs, deleteArgs);
|
|
626
|
+
}
|
|
627
|
+
if (finalizeHooks?.elevateCreateAndRun) {
|
|
628
|
+
const completion = finalizeHooks.elevateCreateAndRun(schtasksPath, createArgs, runArgs, deleteArgs);
|
|
629
|
+
return { completion, launcherPid: null };
|
|
630
|
+
}
|
|
631
|
+
return startElevatedSchtasksCreateAndRun(schtasksPath, createArgs, runArgs, deleteArgs);
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
function isPartialInstallError(error: unknown): boolean {
|
|
635
|
+
if (!(error instanceof Error)) return false;
|
|
636
|
+
return /partial Task Scheduler/i.test(error.message)
|
|
637
|
+
|| /Cleanup also failed/i.test(error.message)
|
|
638
|
+
|| /left in place because native WinSW status could not be verified/i.test(error.message)
|
|
639
|
+
|| /Task Scheduler presence could not be verified/i.test(error.message);
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
/**
|
|
643
|
+
* Re-register the scheduler task with elevation after a non-elevated install wrote assets.
|
|
644
|
+
*
|
|
645
|
+
* Request timeout does not kill the elevated launcher. On timeout this returns
|
|
646
|
+
* `indeterminate` and keeps reconciling the eventual protocol result.
|
|
647
|
+
*/
|
|
648
|
+
export async function finalizeWindowsSchedulerServiceRegistration(
|
|
649
|
+
script = windowsServiceScriptPath(),
|
|
650
|
+
options?: FinalizeWindowsSchedulerOptions,
|
|
651
|
+
): Promise<FinalizeWindowsSchedulerResult> {
|
|
652
|
+
if (process.platform !== "win32") {
|
|
653
|
+
throw new Error("Windows scheduler registration is only supported on Windows.");
|
|
654
|
+
}
|
|
655
|
+
const attemptId = options?.attemptId ?? randomUUID();
|
|
656
|
+
const stillOwnsAttempt = options?.stillOwnsAttempt ?? finalizeHooks?.stillOwnsAttempt;
|
|
657
|
+
const createArgs = buildWindowsSchtasksCreateArgs(script);
|
|
658
|
+
const runArgs = ["/run", "/tn", TASK];
|
|
659
|
+
const deleteArgs = ["/delete", "/tn", TASK, "/f"];
|
|
660
|
+
const started = startElevateExecution(windowsSchtasks(), createArgs, runArgs, deleteArgs);
|
|
661
|
+
const timeoutMs = options?.requestTimeoutMs
|
|
662
|
+
?? finalizeHooks?.requestTimeoutMs
|
|
663
|
+
?? ELEVATION_REQUEST_TIMEOUT_MS;
|
|
664
|
+
const applyOpts: ApplyElevatedOptions = { attemptId, writeOnSuccess: true, stillOwnsAttempt };
|
|
665
|
+
|
|
666
|
+
let raced: { status: "completed"; value: ElevatedSchtasksCreateAndRunResult } | { status: "timed-out" };
|
|
667
|
+
try {
|
|
668
|
+
raced = await raceWithTimeout(started.completion, timeoutMs);
|
|
669
|
+
} catch (error) {
|
|
670
|
+
// Cancellation / launch failure / signal before or instead of a protocol result.
|
|
671
|
+
// Signal after Start-Process may leave an elevated child; reconcile conservatively.
|
|
672
|
+
if (error instanceof WindowsElevationError && error.reason === "terminated") {
|
|
673
|
+
try {
|
|
674
|
+
await reconcileUnknownElevatedOutcome(OCX_ELEVATED_PROTOCOL_FAILED);
|
|
675
|
+
} catch (reconcileError) {
|
|
676
|
+
// Prefer the reconciliation detail (partial install / cleanup guidance) over the
|
|
677
|
+
// generic signal message so callers can block retries when a task remains.
|
|
678
|
+
throw reconcileError;
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
throw error;
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
if (raced.status === "completed") {
|
|
685
|
+
await applyElevatedSchedulerResult(raced.value, applyOpts);
|
|
686
|
+
return { kind: "done" };
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
const reconciliation = (async (): Promise<ElevatedReconciliationOutcome> => {
|
|
690
|
+
try {
|
|
691
|
+
const result = await started.completion;
|
|
692
|
+
await applyElevatedSchedulerResult(result, applyOpts);
|
|
693
|
+
return "released";
|
|
694
|
+
} catch (error) {
|
|
695
|
+
if (error instanceof WindowsElevationError && error.reason === "cancelled") {
|
|
696
|
+
return "released";
|
|
697
|
+
}
|
|
698
|
+
if (error instanceof WindowsElevationError && error.reason === "launch-failed") {
|
|
699
|
+
return "released";
|
|
700
|
+
}
|
|
701
|
+
if (error instanceof WindowsElevationError && error.reason === "terminated") {
|
|
702
|
+
try {
|
|
703
|
+
await reconcileUnknownElevatedOutcome(OCX_ELEVATED_PROTOCOL_FAILED);
|
|
704
|
+
return "released";
|
|
705
|
+
} catch (reconcileError) {
|
|
706
|
+
return isPartialInstallError(reconcileError) ? "blocked-partial" : "released";
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
// applyElevatedSchedulerResult failures are expected (create/run/conflict); swallow for background.
|
|
710
|
+
if (isPartialInstallError(error)) {
|
|
711
|
+
return "blocked-partial";
|
|
712
|
+
}
|
|
713
|
+
return "released";
|
|
714
|
+
}
|
|
715
|
+
})();
|
|
716
|
+
|
|
717
|
+
return { kind: "indeterminate", attemptId, reconciliation };
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
/**
|
|
721
|
+
* Pure post-restart / pre-install advisory check. Does not mutate state.
|
|
722
|
+
* A process-local indeterminate lock cannot survive restart — callers must inspect reality.
|
|
723
|
+
*/
|
|
724
|
+
export function evaluateSchedulerInstallRestartReconciliation(inputs: {
|
|
725
|
+
taskInstalled: boolean;
|
|
726
|
+
registrationHealthy: boolean;
|
|
727
|
+
assetsHealthy: boolean;
|
|
728
|
+
nativeStatus: "started" | "stopped" | "nonexistent" | "unknown";
|
|
729
|
+
installStateBackend: "scheduler" | "native" | null;
|
|
730
|
+
}): {
|
|
731
|
+
status: "healthy" | "orphan-task" | "stale-install-state" | "conflict" | "unhealthy" | "unverified";
|
|
732
|
+
detail: string;
|
|
733
|
+
} {
|
|
734
|
+
const conflict = inputs.taskInstalled
|
|
735
|
+
&& (inputs.nativeStatus === "started" || inputs.nativeStatus === "stopped");
|
|
736
|
+
if (conflict) {
|
|
737
|
+
return {
|
|
738
|
+
status: "conflict",
|
|
739
|
+
detail: `CONFLICT: Task Scheduler and native WinSW (${WINSW_SERVICE_ID}) are both present.`,
|
|
740
|
+
};
|
|
741
|
+
}
|
|
742
|
+
if (inputs.taskInstalled && inputs.nativeStatus === "unknown") {
|
|
743
|
+
return {
|
|
744
|
+
status: "unverified",
|
|
745
|
+
detail: "The Task Scheduler task exists, but native WinSW status could not be verified.",
|
|
746
|
+
};
|
|
747
|
+
}
|
|
748
|
+
if (inputs.taskInstalled && (!inputs.registrationHealthy || !inputs.assetsHealthy)) {
|
|
749
|
+
return {
|
|
750
|
+
status: "unhealthy",
|
|
751
|
+
detail: !inputs.assetsHealthy
|
|
752
|
+
? "Required scheduler service assets are missing."
|
|
753
|
+
: "Task Scheduler registration is present but unhealthy.",
|
|
754
|
+
};
|
|
755
|
+
}
|
|
756
|
+
if (inputs.taskInstalled && inputs.installStateBackend !== "scheduler") {
|
|
757
|
+
return {
|
|
758
|
+
status: "orphan-task",
|
|
759
|
+
detail: "A Task Scheduler task is present without matching scheduler install state.",
|
|
760
|
+
};
|
|
761
|
+
}
|
|
762
|
+
if (!inputs.taskInstalled && inputs.installStateBackend === "scheduler") {
|
|
763
|
+
return {
|
|
764
|
+
status: "stale-install-state",
|
|
765
|
+
detail: "Scheduler install state is present but the Task Scheduler task is absent.",
|
|
766
|
+
};
|
|
767
|
+
}
|
|
768
|
+
return { status: "healthy", detail: "ok" };
|
|
769
|
+
}
|