-
Notifications
You must be signed in to change notification settings - Fork 521
Expand file tree
/
Copy pathservice.ts
More file actions
2170 lines (2021 loc) · 90.4 KB
/
Copy pathservice.ts
File metadata and controls
2170 lines (2021 loc) · 90.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* `ocx service` — run the proxy as a background service that auto-starts on login and
* auto-restarts on crash. macOS → launchd; Windows → Task Scheduler; Linux → systemd user unit.
* The service sets OCX_SERVICE=1 so the proxy's shutdown handler does NOT restore native
* Codex on a service-managed restart (the restarted instance re-injects); explicit stop/uninstall
* restore it via the command.
*/
import { execFileSync, execSync } from "node:child_process";
import { findLiveProxy, SERVICE_STOP_LIVENESS } from "./server/proxy-liveness";
import { chmodSync, existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { expandUserPath, getConfigDir, readPid, removePid, removeRuntimePort, verifyPidIdentity } from "./config";
import { loadConfig } from "./config";
import { restoreNativeCodex } from "./codex/inject";
import { stripGrokConfig } from "./grok/inject";
import { isWslRuntime } from "./codex/home";
import { BUN_RUNTIME_SOURCE_ENV, durableBunPath, durableBunRuntime } from "./lib/bun-runtime";
import { isProcessAlive, stopProxy } from "./lib/process-control";
import { serviceApiTokenFilePath } from "./lib/service-secrets";
import { randomUUID } from "node:crypto";
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";
import { defaultWinswEntry, installWinswService, startWinswService, stopWinswService, statusWinswRaw, uninstallWinswService, winswStatusSummary, WINSW_SERVICE_ID, WINSW_SHA256, WINSW_VERSION } from "./lib/winsw";
import { hardenSecretDir, hardenSecretPath } from "./lib/windows-secret-acl";
import { windowsEnvIndirectBatchPathList, windowsEnvIndirectBatchValue } from "./lib/win-paths";
import { recordOwnedConfigPath } from "./lib/config-ownership";
import { maybeShowStarPrompt } from "./cli/star-prompt";
const LABEL = "com.opencodex.proxy";
const TASK = "opencodex-proxy";
export type ServiceBackend = "scheduler" | "native";
function cliEntry(): { bun: string; cli: string } {
// Bake the bundled Bun (npm global prefix, survives `ocx update`) rather than
// a transient system Bun, so launchd/systemd/schtasks keep resolving even if a
// standalone Bun is later removed. The CLI entry lives at src/cli/index.ts.
return { bun: durableBunPath(), cli: join(import.meta.dir, "cli", "index.ts") };
}
function plistPath(): string {
return join(homedir(), "Library", "LaunchAgents", `${LABEL}.plist`);
}
function logPath(): string {
return join(getConfigDir(), "service.log");
}
export function serviceLogPath(): string {
return logPath();
}
function windowsServiceScriptPath(): string {
return join(getConfigDir(), "opencodex-service.cmd");
}
function windowsLauncherVbsPath(): string {
return join(getConfigDir(), "opencodex-service-launcher.vbs");
}
function windowsTaskXmlPath(): string {
return join(getConfigDir(), "opencodex-service-task.xml");
}
function serviceStatePath(): string {
return join(getConfigDir(), "service-state.json");
}
function defaultOpenCodexHome(): string {
return resolve(join(homedir(), ".opencodex"));
}
function serviceStatePaths(): string[] {
const paths = [serviceStatePath()];
const defaultPath = join(defaultOpenCodexHome(), "service-state.json");
if (normalizePathForCompare(defaultPath) !== normalizePathForCompare(paths[0])) paths.push(defaultPath);
return paths;
}
function currentCodexHome(): string {
const raw = process.env.CODEX_HOME?.trim();
return raw ? resolve(expandUserPath(raw)) : join(homedir(), ".codex");
}
function currentOpenCodexHome(): string {
// getConfigDir() already resolves OPENCODEX_HOME with ~ expansion; keep the
// install-state comparison on the same normalization or `~/...` values falsely
// fail the environment-match check depending on cwd.
return getConfigDir();
}
function normalizePathForCompare(path: string): string {
const resolved = resolve(path);
return process.platform === "win32" ? resolved.toLowerCase() : resolved;
}
export interface ServiceInstallState {
version: 1 | 2;
codexHome: string;
opencodexHome: string;
/** Baked at install; lets status flag paths gone stale after npm prefix/nvm moves. */
bunPath?: string;
cliPath?: string;
/** v2: which Windows backend was chosen at install; absent (v1/legacy) means scheduler. */
backend?: ServiceBackend;
winswVersion?: string;
winswSha256?: string;
}
export function parseServiceInstallState(value: unknown): ServiceInstallState | null {
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
const state = value as Record<string, unknown>;
if (state.version !== 1 && state.version !== 2) return null;
if (typeof state.codexHome !== "string" || state.codexHome.length === 0) return null;
if (typeof state.opencodexHome !== "string" || state.opencodexHome.length === 0) return null;
for (const key of ["bunPath", "cliPath", "winswVersion", "winswSha256"] as const) {
if (state[key] !== undefined && (typeof state[key] !== "string" || state[key].length === 0)) return null;
}
if (state.version === 1) {
if (state.backend !== undefined) return null;
} else if (state.backend !== "scheduler" && state.backend !== "native") {
return null;
}
return state as unknown as ServiceInstallState;
}
function writeServiceInstallState(backend: ServiceBackend = "scheduler"): void {
const { bun, cli } = cliEntry();
const state: ServiceInstallState = {
version: 2,
codexHome: currentCodexHome(),
opencodexHome: currentOpenCodexHome(),
bunPath: bun,
cliPath: cli,
backend,
...(backend === "native" ? { winswVersion: WINSW_VERSION, winswSha256: WINSW_SHA256 } : {}),
};
for (const path of serviceStatePaths()) {
const dir = dirname(path);
recordOwnedConfigPath(getConfigDir(), path);
if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 });
writeFileSync(path, JSON.stringify(state, null, 2) + "\n", { encoding: "utf8", mode: 0o600 });
try { chmodSync(path, 0o600); } catch { /* best-effort */ }
if (process.platform === "win32") hardenSecretPath(path, { required: true });
}
}
function readServiceInstallState(): ServiceInstallState | null {
for (const path of serviceStatePaths()) {
try {
const parsed = parseServiceInstallState(JSON.parse(readFileSync(path, "utf8")));
if (parsed) return parsed;
} catch {
/* try the next known state path */
}
}
return null;
}
/** Single accessor for update/reinstall code — v1/legacy state maps to scheduler. */
export function readServiceBackend(): ServiceBackend {
return readServiceInstallState()?.backend === "native" ? "native" : "scheduler";
}
/** The `ocx` argv that reinstalls the currently-chosen service backend (update paths). */
export function serviceReinstallArgs(): string[] {
return readServiceBackend() === "native" ? ["service", "install", "--native"] : ["service", "install"];
}
/**
* The service was installed under a different CODEX_HOME/OPENCODEX_HOME, so this process may not
* touch it. Distinct from "stop failed": the manager was never even contacted, which means the
* installed service is still live and shared state (native Codex config, the Grok fence) must be
* left alone — tearing it down would strip config out from under a running service.
*/
export class ServiceOwnershipError extends Error {
readonly code = "service-ownership-mismatch" as const;
}
export function isServiceOwnershipError(err: unknown): err is ServiceOwnershipError {
return err instanceof ServiceOwnershipError;
}
/**
* True when no installed service exists, or the installed one belongs to THIS
* CODEX_HOME/OPENCODEX_HOME. Callers use it to decide whether they may tear down shared state
* (native Codex config, the Grok fence) that a foreign service would still be relying on.
*/
export function serviceEnvironmentOwnedHere(): boolean {
try {
assertServiceEnvironmentMatchesInstall();
return true;
} catch (err) {
if (isServiceOwnershipError(err)) return false;
return true; // unrelated failure: fall back to the previous behavior rather than wedging
}
}
export function assertServiceEnvironmentMatchesInstall(): void {
const state = readServiceInstallState();
if (!state) return;
const expected = normalizePathForCompare(state.codexHome);
const actual = normalizePathForCompare(currentCodexHome());
if (expected !== actual) {
throw new ServiceOwnershipError(
`Service was installed with CODEX_HOME=${state.codexHome}, but current CODEX_HOME=${currentCodexHome()}. ` +
"Run the service command from the same Codex home so native Codex restore updates the correct config.",
);
}
const expectedOpenCodexHome = normalizePathForCompare(state.opencodexHome);
const actualOpenCodexHome = normalizePathForCompare(currentOpenCodexHome());
if (expectedOpenCodexHome !== actualOpenCodexHome) {
throw new ServiceOwnershipError(
`Service was installed with OPENCODEX_HOME=${state.opencodexHome}, but current OPENCODEX_HOME=${currentOpenCodexHome()}. ` +
"Run the service command from the same OpenCodex home so service state and secrets match.",
);
}
}
function plistString(value: string): string {
return value
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
function isLoopbackHostname(hostname: string | undefined): boolean {
const normalized = (hostname ?? "127.0.0.1").trim().toLowerCase();
return normalized === "" || normalized === "localhost" || normalized === "127.0.0.1" || normalized === "::1" || normalized === "[::1]";
}
export function assertServiceAuthEnvironment(): void {
const config = loadConfig();
if (isLoopbackHostname(config.hostname)) return;
if (process.env.OPENCODEX_API_AUTH_TOKEN?.trim()) return;
throw new Error(
"OPENCODEX_API_AUTH_TOKEN is required before installing a service for non-loopback hostname. " +
"Set it in the same shell, then rerun `ocx service install`.",
);
}
function writeServiceApiTokenFile(): string | null {
const token = process.env.OPENCODEX_API_AUTH_TOKEN?.trim();
if (!token) return null;
const path = serviceApiTokenFilePath();
const dir = getConfigDir();
recordOwnedConfigPath(dir, path);
if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 });
if (process.platform === "win32") hardenSecretDir(dir, { required: true });
writeFileSync(path, `${token}\n`, { encoding: "utf8", mode: 0o600 });
try { chmodSync(path, 0o600); } catch { /* best-effort */ }
if (process.platform === "win32") hardenSecretPath(path, { required: true });
return path;
}
export function buildPlist(): string {
const { bun, cli } = cliEntry();
const bunRuntime = durableBunRuntime();
const log = logPath();
const path = process.env.PATH ?? "/usr/local/bin:/usr/bin:/bin";
const codexHome = process.env.CODEX_HOME?.trim();
const opencodexHome = process.env.OPENCODEX_HOME?.trim();
const envLines = [
` <key>OCX_SERVICE</key><string>1</string>`,
` <key>${BUN_RUNTIME_SOURCE_ENV}</key><string>${bunRuntime.source}</string>`,
` <key>PATH</key><string>${plistString(path)}</string>`,
codexHome ? ` <key>CODEX_HOME</key><string>${plistString(codexHome)}</string>` : null,
opencodexHome ? ` <key>OPENCODEX_HOME</key><string>${plistString(opencodexHome)}</string>` : null,
].filter((line): line is string => Boolean(line)).join("\n");
const command = buildServiceShellCommand(bun, cli);
return `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key><string>${LABEL}</string>
<key>ProgramArguments</key>
<array>
<string>/bin/sh</string>
<string>-lc</string>
<string>${plistString(command)}</string>
</array>
<key>RunAtLoad</key><true/>
<key>KeepAlive</key><true/>
<key>EnvironmentVariables</key>
<dict>
${envLines}
</dict>
<key>StandardOutPath</key><string>${plistString(log)}</string>
<key>StandardErrorPath</key><string>${plistString(log)}</string>
</dict>
</plist>
`;
}
function shellQuote(value: string): string {
return `'${value.replace(/'/g, "'\\''")}'`;
}
/**
* Listen port baked into service wrappers / WinSW XML.
* Priority: explicit override → OCX_BAKE_PORT (update restart) → config.port → 10100.
* `config.port === 0` means ephemeral for interactive start; services need a stable pin,
* so treat 0 / invalid like unset (default 10100) instead of baking `--port 0`.
*/
export function resolveServiceListenPort(override?: number): number {
if (typeof override === "number" && Number.isFinite(override) && override > 0 && override <= 65535) {
return Math.trunc(override);
}
const baked = process.env.OCX_BAKE_PORT?.trim();
if (baked && /^\d+$/.test(baked)) {
const n = Number(baked);
if (n > 0 && n <= 65535) return n;
}
const configured = loadConfig().port;
if (typeof configured === "number" && configured > 0 && configured <= 65535) return configured;
return 10100;
}
function buildServiceShellCommand(bun: string, cli: string, port = resolveServiceListenPort()): string {
const tokenFile = serviceApiTokenFilePath();
return `if [ -f ${shellQuote(tokenFile)} ]; then OPENCODEX_API_AUTH_TOKEN="$(cat ${shellQuote(tokenFile)})"; export OPENCODEX_API_AUTH_TOKEN; fi; exec ${shellQuote(bun)} ${shellQuote(cli)} start --port ${port}`;
}
function systemdQuote(value: string): string {
return `"${value
.replace(/\\/g, "\\\\")
.replace(/"/g, "\\\"")
.replace(/%/g, "%%")
.replace(/\n/g, "\\n")}"`;
}
function systemdEnvironmentAssignment(name: string, value: string | undefined): string | null {
if (!value) return null;
return `Environment=${systemdQuote(`${name}=${value}`)}`;
}
function systemdOutputTarget(value: string): string {
// StandardOutput/StandardError use output specifiers such as append:/path.
// Quoting the full specifier makes systemd reject it as an invalid output target.
return value.replace(/%/g, "%%").replace(/\n/g, "\\n");
}
function sh(cmd: string): string {
return execSync(cmd, { encoding: "utf8", stdio: ["pipe", "pipe", "pipe"] }).trim();
}
/**
* Decode schtasks stdout. `/query /xml` emits UTF-16LE (often with BOM) because the
* registered task document is UTF-16; reading that as UTF-8 makes every health check
* fail ("registration present but unhealthy") and rolls back a successful elevated create.
*/
export function decodeSchtasksOutput(buffer: Buffer): string {
if (buffer.length === 0) return "";
const bomUtf16Le = buffer.length >= 2 && buffer[0] === 0xff && buffer[1] === 0xfe;
const bomUtf16Be = buffer.length >= 2 && buffer[0] === 0xfe && buffer[1] === 0xff;
const looksUtf16Le = buffer.length >= 4
&& buffer[1] === 0x00
&& buffer[3] === 0x00
&& buffer[0] !== 0x00;
if (bomUtf16Le || looksUtf16Le) {
return buffer.toString("utf16le").replace(/^\uFEFF/, "").trim();
}
if (bomUtf16Be) {
// Swap pairs then decode as utf16le.
const swapped = Buffer.alloc(buffer.length - 2);
for (let i = 2; i + 1 < buffer.length; i += 2) {
swapped[i - 2] = buffer[i + 1]!;
swapped[i - 1] = buffer[i]!;
}
return swapped.toString("utf16le").trim();
}
return buffer.toString("utf8").replace(/^\uFEFF/, "").trim();
}
function runFile(file: string, args: string[]): string {
const buffer = execFileSync(file, args, {
encoding: "buffer",
stdio: ["ignore", "pipe", "pipe"],
windowsHide: true,
}) as Buffer;
return decodeSchtasksOutput(buffer);
}
function windowsSchtasks(): string {
return resolveTrustedWindowsSchtasksExe();
}
function windowsWscript(): string {
const candidate = join(process.env.SystemRoot ?? "C:\\Windows", "System32", "wscript.exe");
return existsSync(candidate) ? candidate : "wscript.exe";
}
let querySchtasksForTests: ((args: string[]) => string) | null = null;
function querySchtasks(args: string[]): string {
if (querySchtasksForTests) return querySchtasksForTests(args);
return runFile(windowsSchtasks(), args);
}
/** Test-only seam for Task Scheduler query used by presence probes. */
export function setQuerySchtasksForTests(next: ((args: string[]) => string) | null): void {
querySchtasksForTests = next;
}
function schtasks(args: string[]): string {
try {
return querySchtasks(args);
} catch (error) {
throw toWindowsSchtasksError(error, args);
}
}
/** Tri-state Task Scheduler presence: never treat a failed query as proven absence. */
export type WindowsSchedulerTaskProbe =
| { status: "present" }
| { status: "absent" }
| { status: "unknown"; detail: string };
export type WindowsSchedulerProxyProbe =
| { status: "running"; port: number }
| { status: "not-running" }
| { status: "unknown" };
/**
* Render Task Scheduler status without exposing localized `schtasks` table output.
* The task probe answers installation state; the identity-checked health probe answers
* runtime state. Keep probe details out of this user-facing line because they can contain
* incorrectly decoded, locale-specific command output.
*/
export function formatWindowsSchedulerServiceStatus(
task: WindowsSchedulerTaskProbe,
proxy: WindowsSchedulerProxyProbe,
): string {
if (task.status === "present") {
if (proxy.status === "running") {
return `✅ service installed (Task Scheduler); OpenCodex proxy running on port ${proxy.port}.`;
}
if (proxy.status === "not-running") {
return "⚠️ service installed (Task Scheduler); OpenCodex proxy not running.";
}
return "⚠️ service installed (Task Scheduler); OpenCodex proxy status unknown.";
}
if (task.status === "absent") {
if (proxy.status === "running") {
return `❌ service not installed (Task Scheduler); OpenCodex proxy is running independently on port ${proxy.port}.`;
}
if (proxy.status === "unknown") {
return "❌ service not installed (Task Scheduler); OpenCodex proxy status unknown.";
}
return "❌ service not installed (Task Scheduler).";
}
if (proxy.status === "running") {
return `⚠️ Task Scheduler registration unknown; OpenCodex proxy running on port ${proxy.port}.`;
}
if (proxy.status === "not-running") {
return "⚠️ service status unknown (Task Scheduler query failed); OpenCodex proxy not running.";
}
return "⚠️ service status unknown (Task Scheduler and proxy checks failed).";
}
export async function inspectWindowsSchedulerServiceStatus(io: {
probeTask?: () => WindowsSchedulerTaskProbe;
findProxy?: () => Promise<{ port: number } | null>;
} = {}): Promise<string> {
let task: WindowsSchedulerTaskProbe;
try {
task = (io.probeTask ?? probeWindowsSchedulerTask)();
} catch (error) {
task = { status: "unknown", detail: schtasksErrorDetail(error) };
}
let proxy: WindowsSchedulerProxyProbe;
try {
const live = await (io.findProxy ?? findLiveProxy)();
proxy = live ? { status: "running", port: live.port } : { status: "not-running" };
} catch {
proxy = { status: "unknown" };
}
return formatWindowsSchedulerServiceStatus(task, proxy);
}
function schtasksErrorDetail(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
/** True when a schtasks CSV listing line refers to the given task name. */
export function windowsSchedulerCsvIncludesTask(csv: string, taskName: string): boolean {
const needle = taskName.toLowerCase();
for (const line of csv.split(/\r?\n/)) {
const lower = line.toLowerCase();
if (!lower.includes(needle)) continue;
// Prefer exact CSV field matches ("\TaskName" / "TaskName") before a substring hit.
if (
lower.includes(`"\\${needle}"`)
|| lower.includes(`"${needle}"`)
|| new RegExp(`(^|[,\\\\])${needle.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}([,"]|$)`).test(lower)
) {
return true;
}
}
return false;
}
/**
* Probe whether the OpenCodex Task Scheduler task exists.
* Query failures fall back to a CSV listing before concluding absence; if both
* fail, returns `unknown` so callers can fail closed instead of releasing locks.
*/
export function probeWindowsSchedulerTask(taskName = TASK): WindowsSchedulerTaskProbe {
if (process.platform !== "win32") return { status: "absent" };
let queryFailure: string | null = null;
try {
const out = querySchtasks(["/query", "/tn", taskName]);
if (out.includes(taskName)) return { status: "present" };
} catch (error) {
queryFailure = schtasksErrorDetail(error);
}
try {
const csv = querySchtasks(["/query", "/fo", "CSV"]);
if (windowsSchedulerCsvIncludesTask(csv, taskName)) return { status: "present" };
return { status: "absent" };
} catch (error) {
const listDetail = schtasksErrorDetail(error);
const detail = queryFailure
? `Specific query failed (${queryFailure}); CSV listing also failed (${listDetail}).`
: `Task query did not confirm presence and CSV listing failed (${listDetail}).`;
return { status: "unknown", detail };
}
}
/** True when the Task Scheduler registration for the default proxy task is proven present. */
export function windowsSchedulerTaskInstalled(taskName = TASK): boolean {
return probeWindowsSchedulerTask(taskName).status === "present";
}
export interface WindowsSchedulerInstallVerification {
taskInstalled: boolean;
registrationHealthy: boolean;
assetsHealthy: boolean;
nativeServiceAbsent: boolean;
/** True when SCM probe failed; not a proven WinSW presence. */
nativeStatusUnknown: boolean;
conflict: boolean;
ok: boolean;
detail: string;
}
/** Pure postcondition evaluation for an elevated scheduler install. */
export function evaluateWindowsSchedulerInstallVerification(inputs: {
taskInstalled: boolean;
xml: string;
assetsExist: boolean;
nativeStatus: "started" | "stopped" | "nonexistent" | "unknown";
wscript?: string;
launcher?: string;
}): WindowsSchedulerInstallVerification {
const registrationHealthy = inputs.xml.length > 0
&& windowsTaskRegistrationHealthy(inputs.xml, inputs.wscript, inputs.launcher);
const assetsHealthy = inputs.assetsExist;
const nativeServiceAbsent = inputs.nativeStatus === "nonexistent";
const nativeStatusUnknown = inputs.nativeStatus === "unknown";
// Only treat proven WinSW presence as a backend conflict — never "unknown".
const conflict = inputs.taskInstalled
&& (inputs.nativeStatus === "started" || inputs.nativeStatus === "stopped");
const ok = inputs.taskInstalled && registrationHealthy && assetsHealthy && nativeServiceAbsent && !conflict;
const detail = !inputs.taskInstalled
? "Task Scheduler task is not installed."
: conflict
? `CONFLICT: Task Scheduler and native WinSW (${WINSW_SERVICE_ID}) are both present.`
: !assetsHealthy
? "Required scheduler service assets are missing."
: !registrationHealthy
? (inputs.xml.trim()
? "Task Scheduler registration is present but unhealthy."
: "Task Scheduler task is present but its XML could not be read.")
: nativeStatusUnknown
? "The Task Scheduler task was created, but OpenCodex could not verify that the native WinSW service is absent."
: "ok";
return {
taskInstalled: inputs.taskInstalled,
registrationHealthy,
assetsHealthy,
nativeServiceAbsent,
nativeStatusUnknown,
conflict,
ok,
detail,
};
}
/** Conflict-free postcondition check for an elevated scheduler install. */
export function verifyWindowsSchedulerInstall(taskName = TASK): WindowsSchedulerInstallVerification {
const taskInstalled = windowsSchedulerTaskInstalled(taskName);
let xml = "";
if (taskInstalled) {
try { xml = querySchtasks(["/query", "/tn", taskName, "/xml"]); } catch { xml = ""; }
}
// After elevated create, non-elevated `/query /xml` can fail or return empty while the
// task is still listed. Fall back to the on-disk document we registered.
if (taskInstalled && !xml.trim()) {
const diskPath = windowsTaskXmlPath();
if (existsSync(diskPath)) {
try { xml = decodeSchtasksOutput(readFileSync(diskPath)); } catch { /* keep empty */ }
}
}
return evaluateWindowsSchedulerInstallVerification({
taskInstalled,
xml,
assetsExist: [windowsServiceScriptPath(), windowsLauncherVbsPath(), windowsTaskXmlPath()].every(existsSync),
nativeStatus: statusWinswRaw(),
});
}
async function elevateSchtasks(args: string[]): Promise<void> {
const exitCode = await runWindowsElevated(windowsSchtasks(), args);
if (exitCode !== 0) {
throw new Error(`Background service install failed with exit code ${exitCode}.`);
}
}
async function rollbackElevatedSchedulerTask(taskName = TASK): Promise<string | null> {
try {
await elevateSchtasks(["/delete", "/tn", taskName, "/f"]);
} catch (error) {
return error instanceof Error ? error.message : String(error);
}
const probe = resolveWindowsSchedulerTaskProbe(taskName);
if (probe.status === "absent") return null;
if (probe.status === "unknown") {
return `Task Scheduler task ${taskName} presence could not be verified after rollback: ${probe.detail}`;
}
return `Task Scheduler task ${taskName} is still present after rollback.`;
}
type ElevateCreateAndRunStart = (
schtasksPath: string,
createArgs: string[],
runArgs: string[],
deleteArgs: string[],
) => ElevatedSchtasksCreateAndRunExecution;
type FinalizeHooks = {
startElevateCreateAndRun?: ElevateCreateAndRunStart;
/** Legacy sync hook used by older tests — wraps a resolved result as an execution. */
elevateCreateAndRun?: (
schtasksPath: string,
createArgs: string[],
runArgs: string[],
deleteArgs: string[],
) => Promise<ElevatedSchtasksCreateAndRunResult>;
verify?: () => WindowsSchedulerInstallVerification;
writeInstallState?: () => void;
/** Preferred tri-state probe for security-sensitive reconciliation. */
probeTask?: () => WindowsSchedulerTaskProbe;
/** Legacy boolean hook; mapped to present/absent when probeTask is unset. */
taskInstalled?: () => boolean;
/** Defense-in-depth: late reconciliation must still own this attempt. */
stillOwnsAttempt?: (attemptId: string) => boolean;
requestTimeoutMs?: number;
};
let finalizeHooks: FinalizeHooks | null = null;
function resolveWindowsSchedulerTaskProbe(taskName = TASK): WindowsSchedulerTaskProbe {
if (finalizeHooks?.probeTask) return finalizeHooks.probeTask();
if (finalizeHooks?.taskInstalled) {
return finalizeHooks.taskInstalled() ? { status: "present" } : { status: "absent" };
}
return probeWindowsSchedulerTask(taskName);
}
/** Test-only hooks for elevated create+run finalization. */
export function setFinalizeWindowsSchedulerHooksForTests(hooks: FinalizeHooks | null): void {
finalizeHooks = hooks;
}
function throwPartialInstall(parts: string[]): never {
throw new Error(parts.filter(Boolean).join(" "));
}
/**
* Reconcile an unrecognized elevated exit when we cannot trust the phase code.
* Never invent a create-vs-run classification; inspect actual task state first.
* An unverifiable probe must fail closed (partial / blocked), never release.
*/
async function reconcileUnknownElevatedOutcome(exitCode: number): Promise<void> {
const probe = resolveWindowsSchedulerTaskProbe();
const parts = [
"The elevated Task Scheduler operation returned an unknown result.",
`Exit code: ${exitCode}.`,
"OpenCodex could not prove whether task creation completed, so installation state was not written.",
];
if (probe.status === "unknown") {
parts.push(`Task Scheduler presence could not be verified: ${probe.detail}`);
parts.push("A partial Task Scheduler backend may remain.");
throwPartialInstall(parts);
}
if (probe.status === "absent") {
parts.push("No OpenCodex Task Scheduler task was found after the elevated operation.");
throwPartialInstall(parts);
}
parts.push("A Task Scheduler task is present; attempting cleanup.");
const rollbackError = await rollbackElevatedSchedulerTask();
if (rollbackError) {
parts.push(`Cleanup also failed: ${rollbackError}`);
parts.push(`Remove the task manually with 'schtasks /delete /tn ${TASK} /f' if it remains.`);
} else {
parts.push("The elevated Task Scheduler task was removed.");
}
throwPartialInstall(parts);
}
type ApplyElevatedOptions = {
attemptId: string;
writeOnSuccess: boolean;
stillOwnsAttempt?: (attemptId: string) => boolean;
};
function attemptStillOwned(options: ApplyElevatedOptions): boolean {
const check = options.stillOwnsAttempt ?? finalizeHooks?.stillOwnsAttempt;
return !check || check(options.attemptId);
}
async function applyElevatedSchedulerResult(
result: ElevatedSchtasksCreateAndRunResult,
options: ApplyElevatedOptions,
): Promise<void> {
if (!attemptStillOwned(options)) {
return;
}
const outcome: ElevatedSchedulerOutcome = result.outcome;
if (outcome === "create-failed") {
throw new Error("Elevated schtasks /create failed. The Task Scheduler task was not registered.");
}
if (outcome === "run-failed-rolled-back") {
throw new Error(
"Elevated schtasks /run failed after the task was registered. The elevated process rolled the task back. Installation state was not written.",
);
}
if (outcome === "run-failed-rollback-failed") {
throwPartialInstall([
"Elevated schtasks /run failed after the task was registered, and elevated rollback also failed.",
"A partial Task Scheduler backend may remain.",
`Remove the task manually with 'schtasks /delete /tn ${TASK} /f' if present.`,
"Installation state was not written.",
]);
}
if (outcome !== "success") {
await reconcileUnknownElevatedOutcome(result.exitCode);
}
const verification = (finalizeHooks?.verify ?? verifyWindowsSchedulerInstall)();
if (!verification.ok) {
// Preserve a healthy elevated task when WinSW absence cannot be proven (unknown SCM status).
// Unknown is not a confirmed dual-backend conflict; install state is still withheld.
const preserveElevatedTask = verification.taskInstalled
&& verification.registrationHealthy
&& verification.assetsHealthy
&& !verification.conflict
&& verification.nativeStatusUnknown;
if (preserveElevatedTask) {
throwPartialInstall([
"Elevated Task Scheduler registration did not produce a conflict-free install.",
verification.detail,
"The elevated Task Scheduler task was left in place because native WinSW status could not be verified.",
"Installation state was not written.",
]);
}
const rollbackError = await rollbackElevatedSchedulerTask();
const parts = [
"Elevated Task Scheduler registration did not produce a conflict-free install.",
verification.detail,
];
if (rollbackError) {
parts.push(`Rollback also failed: ${rollbackError}`);
parts.push(`Remove the task manually with 'schtasks /delete /tn ${TASK} /f' and the native service with 'sc delete ${WINSW_SERVICE_ID}' if present.`);
} else {
parts.push("The elevated Task Scheduler task was rolled back.");
}
parts.push("Installation state was not written.");
throwPartialInstall(parts);
}
if (options.writeOnSuccess) {
if (!attemptStillOwned(options)) {
return;
}
(finalizeHooks?.writeInstallState ?? (() => writeServiceInstallState("scheduler")))();
}
}
/** Outcome of late reconciliation after a request-level elevation timeout. */
export type ElevatedReconciliationOutcome =
| "released"
| "blocked-partial";
export type FinalizeWindowsSchedulerResult =
| { kind: "done" }
| {
kind: "indeterminate";
attemptId: string;
/** Settles after the elevated transaction finishes and late reconciliation runs. */
reconciliation: Promise<ElevatedReconciliationOutcome>;
};
export type FinalizeWindowsSchedulerOptions = {
attemptId?: string;
stillOwnsAttempt?: (attemptId: string) => boolean;
requestTimeoutMs?: number;
};
function startElevateExecution(
schtasksPath: string,
createArgs: string[],
runArgs: string[],
deleteArgs: string[],
): ElevatedSchtasksCreateAndRunExecution {
if (finalizeHooks?.startElevateCreateAndRun) {
return finalizeHooks.startElevateCreateAndRun(schtasksPath, createArgs, runArgs, deleteArgs);
}
if (finalizeHooks?.elevateCreateAndRun) {
const completion = finalizeHooks.elevateCreateAndRun(schtasksPath, createArgs, runArgs, deleteArgs);
return { completion, launcherPid: null };
}
return startElevatedSchtasksCreateAndRun(schtasksPath, createArgs, runArgs, deleteArgs);
}
function isPartialInstallError(error: unknown): boolean {
if (!(error instanceof Error)) return false;
return /partial Task Scheduler/i.test(error.message)
|| /Cleanup also failed/i.test(error.message)
|| /left in place because native WinSW status could not be verified/i.test(error.message)
|| /Task Scheduler presence could not be verified/i.test(error.message);
}
/**
* Re-register the scheduler task with elevation after a non-elevated install wrote assets.
*
* Request timeout does not kill the elevated launcher. On timeout this returns
* `indeterminate` and keeps reconciling the eventual protocol result.
*/
export async function finalizeWindowsSchedulerServiceRegistration(
script = windowsServiceScriptPath(),
options?: FinalizeWindowsSchedulerOptions,
): Promise<FinalizeWindowsSchedulerResult> {
if (process.platform !== "win32") {
throw new Error("Windows scheduler registration is only supported on Windows.");
}
const attemptId = options?.attemptId ?? randomUUID();
const stillOwnsAttempt = options?.stillOwnsAttempt ?? finalizeHooks?.stillOwnsAttempt;
const createArgs = buildWindowsSchtasksCreateArgs(script);
const runArgs = ["/run", "/tn", TASK];
const deleteArgs = ["/delete", "/tn", TASK, "/f"];
const started = startElevateExecution(windowsSchtasks(), createArgs, runArgs, deleteArgs);
const timeoutMs = options?.requestTimeoutMs
?? finalizeHooks?.requestTimeoutMs
?? ELEVATION_REQUEST_TIMEOUT_MS;
const applyOpts: ApplyElevatedOptions = { attemptId, writeOnSuccess: true, stillOwnsAttempt };
let raced: { status: "completed"; value: ElevatedSchtasksCreateAndRunResult } | { status: "timed-out" };
try {
raced = await raceWithTimeout(started.completion, timeoutMs);
} catch (error) {
// Cancellation / launch failure / signal before or instead of a protocol result.
// Signal after Start-Process may leave an elevated child; reconcile conservatively.
if (error instanceof WindowsElevationError && error.reason === "terminated") {
try {
await reconcileUnknownElevatedOutcome(OCX_ELEVATED_PROTOCOL_FAILED);
} catch (reconcileError) {
// Prefer the reconciliation detail (partial install / cleanup guidance) over the
// generic signal message so callers can block retries when a task remains.
throw reconcileError;
}
}
throw error;
}
if (raced.status === "completed") {
await applyElevatedSchedulerResult(raced.value, applyOpts);
return { kind: "done" };
}
const reconciliation = (async (): Promise<ElevatedReconciliationOutcome> => {
try {
const result = await started.completion;
await applyElevatedSchedulerResult(result, applyOpts);
return "released";
} catch (error) {
if (error instanceof WindowsElevationError && error.reason === "cancelled") {
return "released";
}
if (error instanceof WindowsElevationError && error.reason === "launch-failed") {
return "released";
}
if (error instanceof WindowsElevationError && error.reason === "terminated") {
try {
await reconcileUnknownElevatedOutcome(OCX_ELEVATED_PROTOCOL_FAILED);
return "released";
} catch (reconcileError) {
return isPartialInstallError(reconcileError) ? "blocked-partial" : "released";
}
}
// applyElevatedSchedulerResult failures are expected (create/run/conflict); swallow for background.
if (isPartialInstallError(error)) {
return "blocked-partial";
}
return "released";
}
})();
return { kind: "indeterminate", attemptId, reconciliation };
}
/**
* Pure post-restart / pre-install advisory check. Does not mutate state.
* A process-local indeterminate lock cannot survive restart — callers must inspect reality.
*/
export function evaluateSchedulerInstallRestartReconciliation(inputs: {
taskInstalled: boolean;
registrationHealthy: boolean;
assetsHealthy: boolean;
nativeStatus: "started" | "stopped" | "nonexistent" | "unknown";
installStateBackend: "scheduler" | "native" | null;
}): {
status: "healthy" | "orphan-task" | "stale-install-state" | "conflict" | "unhealthy" | "unverified";
detail: string;
} {
const conflict = inputs.taskInstalled
&& (inputs.nativeStatus === "started" || inputs.nativeStatus === "stopped");
if (conflict) {
return {
status: "conflict",
detail: `CONFLICT: Task Scheduler and native WinSW (${WINSW_SERVICE_ID}) are both present.`,
};
}
if (inputs.taskInstalled && inputs.nativeStatus === "unknown") {
return {
status: "unverified",
detail: "The Task Scheduler task exists, but native WinSW status could not be verified.",
};
}
if (inputs.taskInstalled && (!inputs.registrationHealthy || !inputs.assetsHealthy)) {
return {
status: "unhealthy",
detail: !inputs.assetsHealthy
? "Required scheduler service assets are missing."
: "Task Scheduler registration is present but unhealthy.",
};
}
if (inputs.taskInstalled && inputs.installStateBackend !== "scheduler") {
return {
status: "orphan-task",
detail: "A Task Scheduler task is present without matching scheduler install state.",
};
}
if (!inputs.taskInstalled && inputs.installStateBackend === "scheduler") {
return {
status: "stale-install-state",
detail: "Scheduler install state is present but the Task Scheduler task is absent.",
};
}
return { status: "healthy", detail: "ok" };
}
function windowsBatchValue(value: string): string {
return value
.replace(/%/g, "%%")
.replace(/\^/g, "^^")
.replace(/"/g, "")
.replace(/[\r\n]/g, "");
}
type WindowsBatchValueKind = "raw" | "path" | "pathList";
function windowsBatchSet(name: string, value: string | undefined, kind: WindowsBatchValueKind = "raw"): string | null {
if (!value) return null;
const rendered =
kind === "path" ? windowsEnvIndirectBatchValue(value, windowsBatchValue)
: kind === "pathList" ? windowsEnvIndirectBatchPathList(value, windowsBatchValue)
: windowsBatchValue(value);
return `set "${name}=${rendered}"`;
}