@bitkyc08/opencodex 2.7.41 → 2.7.42

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.
Files changed (80) hide show
  1. package/README.md +4 -0
  2. package/gui/dist/assets/index-Bl_VBGoI.js +65 -0
  3. package/gui/dist/assets/index-DfVGuN88.css +1 -0
  4. package/gui/dist/index.html +2 -2
  5. package/package.json +1 -1
  6. package/src/adapters/base.ts +6 -0
  7. package/src/adapters/kiro-constants.ts +6 -2
  8. package/src/adapters/kiro-retry.ts +175 -10
  9. package/src/adapters/kiro.ts +172 -85
  10. package/src/adapters/mimo-free.ts +1 -0
  11. package/src/adapters/openai-chat.ts +30 -4
  12. package/src/adapters/openai-responses.ts +90 -12
  13. package/src/bridge.ts +91 -43
  14. package/src/claude/desktop-3p-paths.ts +84 -0
  15. package/src/claude/desktop-3p.ts +29 -2
  16. package/src/cli/access.ts +108 -0
  17. package/src/cli/account-auth.ts +223 -0
  18. package/src/cli/account.ts +9 -1
  19. package/src/cli/agent.ts +184 -0
  20. package/src/cli/combo.ts +119 -0
  21. package/src/cli/config-command.ts +145 -0
  22. package/src/cli/debug.ts +20 -8
  23. package/src/cli/doctor.ts +45 -8
  24. package/src/cli/help.ts +65 -13
  25. package/src/cli/index.ts +108 -7
  26. package/src/cli/integrations.ts +142 -0
  27. package/src/cli/models-runtime.ts +212 -0
  28. package/src/cli/models.ts +9 -10
  29. package/src/cli/observe.ts +117 -0
  30. package/src/cli/provider-runtime.ts +152 -0
  31. package/src/cli/provider.ts +23 -1
  32. package/src/cli/runtime-api.ts +325 -0
  33. package/src/cli/star-prompt.ts +3 -3
  34. package/src/cli/status.ts +17 -0
  35. package/src/cli/system-command.ts +112 -0
  36. package/src/codex/auth-api.ts +3 -2
  37. package/src/codex/catalog/aggregation.ts +113 -18
  38. package/src/codex/catalog/provider-fetch.ts +24 -13
  39. package/src/codex/catalog/sync.ts +20 -8
  40. package/src/codex/catalog.ts +2 -1
  41. package/src/codex/refresh.ts +10 -3
  42. package/src/codex/routing.ts +21 -32
  43. package/src/codex/sync.ts +17 -0
  44. package/src/config.ts +48 -0
  45. package/src/generated/jawcode-model-metadata.ts +2 -1
  46. package/src/grok/inject.ts +184 -4
  47. package/src/grok/status.ts +33 -0
  48. package/src/lib/retry-after.ts +55 -0
  49. package/src/lib/windows-elevation.ts +627 -0
  50. package/src/providers/openai-sidecar.ts +46 -2
  51. package/src/providers/registry.ts +52 -0
  52. package/src/server/auth-cors.ts +6 -0
  53. package/src/server/chat-completions.ts +6 -1
  54. package/src/server/claude-messages.ts +20 -1
  55. package/src/server/images.ts +14 -7
  56. package/src/server/management/agent-settings-routes.ts +10 -4
  57. package/src/server/management/combo-routes.ts +0 -1
  58. package/src/server/management/config-routes.ts +0 -1
  59. package/src/server/management/logs-usage-routes.ts +94 -0
  60. package/src/server/management/model-routes.ts +0 -1
  61. package/src/server/management/oauth-account-routes.ts +0 -1
  62. package/src/server/management/provider-routes.ts +0 -1
  63. package/src/server/management/shared.ts +0 -1
  64. package/src/server/management/system-routes.ts +27 -15
  65. package/src/server/management-api.ts +0 -1
  66. package/src/server/memory-watchdog.ts +54 -10
  67. package/src/server/request-log-conversation.ts +168 -0
  68. package/src/server/request-log.ts +122 -2
  69. package/src/server/responses/core.ts +76 -13
  70. package/src/server/responses/passthrough-error.ts +38 -13
  71. package/src/server/startup-action-control.ts +266 -15
  72. package/src/service.ts +512 -3
  73. package/src/storage/cleanup.ts +1538 -0
  74. package/src/storage/scanner.ts +4 -1
  75. package/src/types.ts +16 -0
  76. package/src/update/job.ts +229 -25
  77. package/src/usage/log.ts +39 -0
  78. package/src/web-search/loop.ts +8 -1
  79. package/gui/dist/assets/index-B2J4t3te.css +0 -1
  80. package/gui/dist/assets/index-BmvM6wRb.js +0 -65
package/src/service.ts CHANGED
@@ -17,6 +17,20 @@ import { isWslRuntime } from "./codex/home";
17
17
  import { durableBunPath, durableBunRuntime } from "./lib/bun-runtime";
18
18
  import { isProcessAlive, stopProxy } from "./lib/process-control";
19
19
  import { serviceApiTokenFilePath } from "./lib/service-secrets";
20
+ import { randomUUID } from "node:crypto";
21
+ import {
22
+ ELEVATION_REQUEST_TIMEOUT_MS,
23
+ OCX_ELEVATED_PROTOCOL_FAILED,
24
+ raceWithTimeout,
25
+ resolveTrustedWindowsSchtasksExe,
26
+ startElevatedSchtasksCreateAndRun,
27
+ runWindowsElevated,
28
+ toWindowsSchtasksError,
29
+ WindowsElevationError,
30
+ type ElevatedSchedulerOutcome,
31
+ type ElevatedSchtasksCreateAndRunExecution,
32
+ type ElevatedSchtasksCreateAndRunResult,
33
+ } from "./lib/windows-elevation";
20
34
  import { defaultWinswEntry, installWinswService, startWinswService, stopWinswService, statusWinswRaw, uninstallWinswService, winswStatusSummary, WINSW_SERVICE_ID, WINSW_SHA256, WINSW_VERSION } from "./lib/winsw";
21
35
  import { hardenSecretDir, hardenSecretPath } from "./lib/windows-secret-acl";
22
36
  import { windowsEnvIndirectBatchPathList, windowsEnvIndirectBatchValue } from "./lib/win-paths";
@@ -342,8 +356,7 @@ function runFile(file: string, args: string[]): string {
342
356
  }
343
357
 
344
358
  function windowsSchtasks(): string {
345
- const candidate = join(process.env.SystemRoot ?? "C:\\Windows", "System32", "schtasks.exe");
346
- return existsSync(candidate) ? candidate : "schtasks.exe";
359
+ return resolveTrustedWindowsSchtasksExe();
347
360
  }
348
361
 
349
362
  function windowsWscript(): string {
@@ -351,10 +364,506 @@ function windowsWscript(): string {
351
364
  return existsSync(candidate) ? candidate : "wscript.exe";
352
365
  }
353
366
 
354
- function schtasks(args: string[]): string {
367
+ let querySchtasksForTests: ((args: string[]) => string) | null = null;
368
+
369
+ function querySchtasks(args: string[]): string {
370
+ if (querySchtasksForTests) return querySchtasksForTests(args);
355
371
  return runFile(windowsSchtasks(), args);
356
372
  }
357
373
 
374
+ /** Test-only seam for Task Scheduler query used by presence probes. */
375
+ export function setQuerySchtasksForTests(next: ((args: string[]) => string) | null): void {
376
+ querySchtasksForTests = next;
377
+ }
378
+
379
+ function schtasks(args: string[]): string {
380
+ try {
381
+ return querySchtasks(args);
382
+ } catch (error) {
383
+ throw toWindowsSchtasksError(error, args);
384
+ }
385
+ }
386
+
387
+ /** Tri-state Task Scheduler presence: never treat a failed query as proven absence. */
388
+ export type WindowsSchedulerTaskProbe =
389
+ | { status: "present" }
390
+ | { status: "absent" }
391
+ | { status: "unknown"; detail: string };
392
+
393
+ function schtasksErrorDetail(error: unknown): string {
394
+ return error instanceof Error ? error.message : String(error);
395
+ }
396
+
397
+ /** True when a schtasks CSV listing line refers to the given task name. */
398
+ export function windowsSchedulerCsvIncludesTask(csv: string, taskName: string): boolean {
399
+ const needle = taskName.toLowerCase();
400
+ for (const line of csv.split(/\r?\n/)) {
401
+ const lower = line.toLowerCase();
402
+ if (!lower.includes(needle)) continue;
403
+ // Prefer exact CSV field matches ("\TaskName" / "TaskName") before a substring hit.
404
+ if (
405
+ lower.includes(`"\\${needle}"`)
406
+ || lower.includes(`"${needle}"`)
407
+ || new RegExp(`(^|[,\\\\])${needle.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}([,"]|$)`).test(lower)
408
+ ) {
409
+ return true;
410
+ }
411
+ }
412
+ return false;
413
+ }
414
+
415
+ /**
416
+ * Probe whether the OpenCodex Task Scheduler task exists.
417
+ * Query failures fall back to a CSV listing before concluding absence; if both
418
+ * fail, returns `unknown` so callers can fail closed instead of releasing locks.
419
+ */
420
+ export function probeWindowsSchedulerTask(taskName = TASK): WindowsSchedulerTaskProbe {
421
+ if (process.platform !== "win32") return { status: "absent" };
422
+
423
+ let queryFailure: string | null = null;
424
+ try {
425
+ const out = querySchtasks(["/query", "/tn", taskName]);
426
+ if (out.includes(taskName)) return { status: "present" };
427
+ } catch (error) {
428
+ queryFailure = schtasksErrorDetail(error);
429
+ }
430
+
431
+ try {
432
+ const csv = querySchtasks(["/query", "/fo", "CSV"]);
433
+ if (windowsSchedulerCsvIncludesTask(csv, taskName)) return { status: "present" };
434
+ return { status: "absent" };
435
+ } catch (error) {
436
+ const listDetail = schtasksErrorDetail(error);
437
+ const detail = queryFailure
438
+ ? `Specific query failed (${queryFailure}); CSV listing also failed (${listDetail}).`
439
+ : `Task query did not confirm presence and CSV listing failed (${listDetail}).`;
440
+ return { status: "unknown", detail };
441
+ }
442
+ }
443
+
444
+ /** True when the Task Scheduler registration for the default proxy task is proven present. */
445
+ export function windowsSchedulerTaskInstalled(taskName = TASK): boolean {
446
+ return probeWindowsSchedulerTask(taskName).status === "present";
447
+ }
448
+
449
+ export interface WindowsSchedulerInstallVerification {
450
+ taskInstalled: boolean;
451
+ registrationHealthy: boolean;
452
+ assetsHealthy: boolean;
453
+ nativeServiceAbsent: boolean;
454
+ /** True when SCM probe failed; not a proven WinSW presence. */
455
+ nativeStatusUnknown: boolean;
456
+ conflict: boolean;
457
+ ok: boolean;
458
+ detail: string;
459
+ }
460
+
461
+ /** Pure postcondition evaluation for an elevated scheduler install. */
462
+ export function evaluateWindowsSchedulerInstallVerification(inputs: {
463
+ taskInstalled: boolean;
464
+ xml: string;
465
+ assetsExist: boolean;
466
+ nativeStatus: "started" | "stopped" | "nonexistent" | "unknown";
467
+ wscript?: string;
468
+ launcher?: string;
469
+ }): WindowsSchedulerInstallVerification {
470
+ const registrationHealthy = inputs.xml.length > 0
471
+ && windowsTaskRegistrationHealthy(inputs.xml, inputs.wscript, inputs.launcher);
472
+ const assetsHealthy = inputs.assetsExist;
473
+ const nativeServiceAbsent = inputs.nativeStatus === "nonexistent";
474
+ const nativeStatusUnknown = inputs.nativeStatus === "unknown";
475
+ // Only treat proven WinSW presence as a backend conflict — never "unknown".
476
+ const conflict = inputs.taskInstalled
477
+ && (inputs.nativeStatus === "started" || inputs.nativeStatus === "stopped");
478
+ const ok = inputs.taskInstalled && registrationHealthy && assetsHealthy && nativeServiceAbsent && !conflict;
479
+ const detail = !inputs.taskInstalled
480
+ ? "Task Scheduler task is not installed."
481
+ : conflict
482
+ ? `CONFLICT: Task Scheduler and native WinSW (${WINSW_SERVICE_ID}) are both present.`
483
+ : !assetsHealthy
484
+ ? "Required scheduler service assets are missing."
485
+ : !registrationHealthy
486
+ ? "Task Scheduler registration is present but unhealthy."
487
+ : nativeStatusUnknown
488
+ ? "The Task Scheduler task was created, but OpenCodex could not verify that the native WinSW service is absent."
489
+ : "ok";
490
+ return {
491
+ taskInstalled: inputs.taskInstalled,
492
+ registrationHealthy,
493
+ assetsHealthy,
494
+ nativeServiceAbsent,
495
+ nativeStatusUnknown,
496
+ conflict,
497
+ ok,
498
+ detail,
499
+ };
500
+ }
501
+
502
+ /** Conflict-free postcondition check for an elevated scheduler install. */
503
+ export function verifyWindowsSchedulerInstall(taskName = TASK): WindowsSchedulerInstallVerification {
504
+ const taskInstalled = windowsSchedulerTaskInstalled(taskName);
505
+ const xml = taskInstalled ? (() => {
506
+ try { return querySchtasks(["/query", "/tn", taskName, "/xml"]); } catch { return ""; }
507
+ })() : "";
508
+ return evaluateWindowsSchedulerInstallVerification({
509
+ taskInstalled,
510
+ xml,
511
+ assetsExist: [windowsServiceScriptPath(), windowsLauncherVbsPath(), windowsTaskXmlPath()].every(existsSync),
512
+ nativeStatus: statusWinswRaw(),
513
+ });
514
+ }
515
+
516
+ async function elevateSchtasks(args: string[]): Promise<void> {
517
+ const exitCode = await runWindowsElevated(windowsSchtasks(), args);
518
+ if (exitCode !== 0) {
519
+ throw new Error(`Background service install failed with exit code ${exitCode}.`);
520
+ }
521
+ }
522
+
523
+ async function rollbackElevatedSchedulerTask(taskName = TASK): Promise<string | null> {
524
+ try {
525
+ await elevateSchtasks(["/delete", "/tn", taskName, "/f"]);
526
+ } catch (error) {
527
+ return error instanceof Error ? error.message : String(error);
528
+ }
529
+ const probe = resolveWindowsSchedulerTaskProbe(taskName);
530
+ if (probe.status === "absent") return null;
531
+ if (probe.status === "unknown") {
532
+ return `Task Scheduler task ${taskName} presence could not be verified after rollback: ${probe.detail}`;
533
+ }
534
+ return `Task Scheduler task ${taskName} is still present after rollback.`;
535
+ }
536
+
537
+ type ElevateCreateAndRunStart = (
538
+ schtasksPath: string,
539
+ createArgs: string[],
540
+ runArgs: string[],
541
+ deleteArgs: string[],
542
+ ) => ElevatedSchtasksCreateAndRunExecution;
543
+
544
+ type FinalizeHooks = {
545
+ startElevateCreateAndRun?: ElevateCreateAndRunStart;
546
+ /** Legacy sync hook used by older tests — wraps a resolved result as an execution. */
547
+ elevateCreateAndRun?: (
548
+ schtasksPath: string,
549
+ createArgs: string[],
550
+ runArgs: string[],
551
+ deleteArgs: string[],
552
+ ) => Promise<ElevatedSchtasksCreateAndRunResult>;
553
+ verify?: () => WindowsSchedulerInstallVerification;
554
+ writeInstallState?: () => void;
555
+ /** Preferred tri-state probe for security-sensitive reconciliation. */
556
+ probeTask?: () => WindowsSchedulerTaskProbe;
557
+ /** Legacy boolean hook; mapped to present/absent when probeTask is unset. */
558
+ taskInstalled?: () => boolean;
559
+ /** Defense-in-depth: late reconciliation must still own this attempt. */
560
+ stillOwnsAttempt?: (attemptId: string) => boolean;
561
+ requestTimeoutMs?: number;
562
+ };
563
+
564
+ let finalizeHooks: FinalizeHooks | null = null;
565
+
566
+ function resolveWindowsSchedulerTaskProbe(taskName = TASK): WindowsSchedulerTaskProbe {
567
+ if (finalizeHooks?.probeTask) return finalizeHooks.probeTask();
568
+ if (finalizeHooks?.taskInstalled) {
569
+ return finalizeHooks.taskInstalled() ? { status: "present" } : { status: "absent" };
570
+ }
571
+ return probeWindowsSchedulerTask(taskName);
572
+ }
573
+
574
+ /** Test-only hooks for elevated create+run finalization. */
575
+ export function setFinalizeWindowsSchedulerHooksForTests(hooks: FinalizeHooks | null): void {
576
+ finalizeHooks = hooks;
577
+ }
578
+
579
+ function throwPartialInstall(parts: string[]): never {
580
+ throw new Error(parts.filter(Boolean).join(" "));
581
+ }
582
+
583
+ /**
584
+ * Reconcile an unrecognized elevated exit when we cannot trust the phase code.
585
+ * Never invent a create-vs-run classification; inspect actual task state first.
586
+ * An unverifiable probe must fail closed (partial / blocked), never release.
587
+ */
588
+ async function reconcileUnknownElevatedOutcome(exitCode: number): Promise<void> {
589
+ const probe = resolveWindowsSchedulerTaskProbe();
590
+ const parts = [
591
+ "The elevated Task Scheduler operation returned an unknown result.",
592
+ `Exit code: ${exitCode}.`,
593
+ "OpenCodex could not prove whether task creation completed, so installation state was not written.",
594
+ ];
595
+ if (probe.status === "unknown") {
596
+ parts.push(`Task Scheduler presence could not be verified: ${probe.detail}`);
597
+ parts.push("A partial Task Scheduler backend may remain.");
598
+ throwPartialInstall(parts);
599
+ }
600
+ if (probe.status === "absent") {
601
+ parts.push("No OpenCodex Task Scheduler task was found after the elevated operation.");
602
+ throwPartialInstall(parts);
603
+ }
604
+ parts.push("A Task Scheduler task is present; attempting cleanup.");
605
+ const rollbackError = await rollbackElevatedSchedulerTask();
606
+ if (rollbackError) {
607
+ parts.push(`Cleanup also failed: ${rollbackError}`);
608
+ parts.push(`Remove the task manually with 'schtasks /delete /tn ${TASK} /f' if it remains.`);
609
+ } else {
610
+ parts.push("The elevated Task Scheduler task was removed.");
611
+ }
612
+ throwPartialInstall(parts);
613
+ }
614
+
615
+ type ApplyElevatedOptions = {
616
+ attemptId: string;
617
+ writeOnSuccess: boolean;
618
+ stillOwnsAttempt?: (attemptId: string) => boolean;
619
+ };
620
+
621
+ function attemptStillOwned(options: ApplyElevatedOptions): boolean {
622
+ const check = options.stillOwnsAttempt ?? finalizeHooks?.stillOwnsAttempt;
623
+ return !check || check(options.attemptId);
624
+ }
625
+
626
+ async function applyElevatedSchedulerResult(
627
+ result: ElevatedSchtasksCreateAndRunResult,
628
+ options: ApplyElevatedOptions,
629
+ ): Promise<void> {
630
+ if (!attemptStillOwned(options)) {
631
+ return;
632
+ }
633
+ const outcome: ElevatedSchedulerOutcome = result.outcome;
634
+
635
+ if (outcome === "create-failed") {
636
+ throw new Error("Elevated schtasks /create failed. The Task Scheduler task was not registered.");
637
+ }
638
+ if (outcome === "run-failed-rolled-back") {
639
+ throw new Error(
640
+ "Elevated schtasks /run failed after the task was registered. The elevated process rolled the task back. Installation state was not written.",
641
+ );
642
+ }
643
+ if (outcome === "run-failed-rollback-failed") {
644
+ throwPartialInstall([
645
+ "Elevated schtasks /run failed after the task was registered, and elevated rollback also failed.",
646
+ "A partial Task Scheduler backend may remain.",
647
+ `Remove the task manually with 'schtasks /delete /tn ${TASK} /f' if present.`,
648
+ "Installation state was not written.",
649
+ ]);
650
+ }
651
+ if (outcome !== "success") {
652
+ await reconcileUnknownElevatedOutcome(result.exitCode);
653
+ }
654
+
655
+ const verification = (finalizeHooks?.verify ?? verifyWindowsSchedulerInstall)();
656
+ if (!verification.ok) {
657
+ // Preserve a healthy elevated task when WinSW absence cannot be proven (unknown SCM status).
658
+ // Unknown is not a confirmed dual-backend conflict; install state is still withheld.
659
+ const preserveElevatedTask = verification.taskInstalled
660
+ && verification.registrationHealthy
661
+ && verification.assetsHealthy
662
+ && !verification.conflict
663
+ && verification.nativeStatusUnknown;
664
+ if (preserveElevatedTask) {
665
+ throwPartialInstall([
666
+ "Elevated Task Scheduler registration did not produce a conflict-free install.",
667
+ verification.detail,
668
+ "The elevated Task Scheduler task was left in place because native WinSW status could not be verified.",
669
+ "Installation state was not written.",
670
+ ]);
671
+ }
672
+ const rollbackError = await rollbackElevatedSchedulerTask();
673
+ const parts = [
674
+ "Elevated Task Scheduler registration did not produce a conflict-free install.",
675
+ verification.detail,
676
+ ];
677
+ if (rollbackError) {
678
+ parts.push(`Rollback also failed: ${rollbackError}`);
679
+ parts.push(`Remove the task manually with 'schtasks /delete /tn ${TASK} /f' and the native service with 'sc delete ${WINSW_SERVICE_ID}' if present.`);
680
+ } else {
681
+ parts.push("The elevated Task Scheduler task was rolled back.");
682
+ }
683
+ parts.push("Installation state was not written.");
684
+ throwPartialInstall(parts);
685
+ }
686
+ if (options.writeOnSuccess) {
687
+ if (!attemptStillOwned(options)) {
688
+ return;
689
+ }
690
+ (finalizeHooks?.writeInstallState ?? (() => writeServiceInstallState("scheduler")))();
691
+ }
692
+ }
693
+
694
+ /** Outcome of late reconciliation after a request-level elevation timeout. */
695
+ export type ElevatedReconciliationOutcome =
696
+ | "released"
697
+ | "blocked-partial";
698
+
699
+ export type FinalizeWindowsSchedulerResult =
700
+ | { kind: "done" }
701
+ | {
702
+ kind: "indeterminate";
703
+ attemptId: string;
704
+ /** Settles after the elevated transaction finishes and late reconciliation runs. */
705
+ reconciliation: Promise<ElevatedReconciliationOutcome>;
706
+ };
707
+
708
+ export type FinalizeWindowsSchedulerOptions = {
709
+ attemptId?: string;
710
+ stillOwnsAttempt?: (attemptId: string) => boolean;
711
+ requestTimeoutMs?: number;
712
+ };
713
+
714
+ function startElevateExecution(
715
+ schtasksPath: string,
716
+ createArgs: string[],
717
+ runArgs: string[],
718
+ deleteArgs: string[],
719
+ ): ElevatedSchtasksCreateAndRunExecution {
720
+ if (finalizeHooks?.startElevateCreateAndRun) {
721
+ return finalizeHooks.startElevateCreateAndRun(schtasksPath, createArgs, runArgs, deleteArgs);
722
+ }
723
+ if (finalizeHooks?.elevateCreateAndRun) {
724
+ const completion = finalizeHooks.elevateCreateAndRun(schtasksPath, createArgs, runArgs, deleteArgs);
725
+ return { completion, launcherPid: null };
726
+ }
727
+ return startElevatedSchtasksCreateAndRun(schtasksPath, createArgs, runArgs, deleteArgs);
728
+ }
729
+
730
+ function isPartialInstallError(error: unknown): boolean {
731
+ if (!(error instanceof Error)) return false;
732
+ return /partial Task Scheduler/i.test(error.message)
733
+ || /Cleanup also failed/i.test(error.message)
734
+ || /left in place because native WinSW status could not be verified/i.test(error.message)
735
+ || /Task Scheduler presence could not be verified/i.test(error.message);
736
+ }
737
+
738
+ /**
739
+ * Re-register the scheduler task with elevation after a non-elevated install wrote assets.
740
+ *
741
+ * Request timeout does not kill the elevated launcher. On timeout this returns
742
+ * `indeterminate` and keeps reconciling the eventual protocol result.
743
+ */
744
+ export async function finalizeWindowsSchedulerServiceRegistration(
745
+ script = windowsServiceScriptPath(),
746
+ options?: FinalizeWindowsSchedulerOptions,
747
+ ): Promise<FinalizeWindowsSchedulerResult> {
748
+ if (process.platform !== "win32") {
749
+ throw new Error("Windows scheduler registration is only supported on Windows.");
750
+ }
751
+ const attemptId = options?.attemptId ?? randomUUID();
752
+ const stillOwnsAttempt = options?.stillOwnsAttempt ?? finalizeHooks?.stillOwnsAttempt;
753
+ const createArgs = buildWindowsSchtasksCreateArgs(script);
754
+ const runArgs = ["/run", "/tn", TASK];
755
+ const deleteArgs = ["/delete", "/tn", TASK, "/f"];
756
+ const started = startElevateExecution(windowsSchtasks(), createArgs, runArgs, deleteArgs);
757
+ const timeoutMs = options?.requestTimeoutMs
758
+ ?? finalizeHooks?.requestTimeoutMs
759
+ ?? ELEVATION_REQUEST_TIMEOUT_MS;
760
+ const applyOpts: ApplyElevatedOptions = { attemptId, writeOnSuccess: true, stillOwnsAttempt };
761
+
762
+ let raced: { status: "completed"; value: ElevatedSchtasksCreateAndRunResult } | { status: "timed-out" };
763
+ try {
764
+ raced = await raceWithTimeout(started.completion, timeoutMs);
765
+ } catch (error) {
766
+ // Cancellation / launch failure / signal before or instead of a protocol result.
767
+ // Signal after Start-Process may leave an elevated child; reconcile conservatively.
768
+ if (error instanceof WindowsElevationError && error.reason === "terminated") {
769
+ try {
770
+ await reconcileUnknownElevatedOutcome(OCX_ELEVATED_PROTOCOL_FAILED);
771
+ } catch (reconcileError) {
772
+ // Prefer the reconciliation detail (partial install / cleanup guidance) over the
773
+ // generic signal message so callers can block retries when a task remains.
774
+ throw reconcileError;
775
+ }
776
+ }
777
+ throw error;
778
+ }
779
+
780
+ if (raced.status === "completed") {
781
+ await applyElevatedSchedulerResult(raced.value, applyOpts);
782
+ return { kind: "done" };
783
+ }
784
+
785
+ const reconciliation = (async (): Promise<ElevatedReconciliationOutcome> => {
786
+ try {
787
+ const result = await started.completion;
788
+ await applyElevatedSchedulerResult(result, applyOpts);
789
+ return "released";
790
+ } catch (error) {
791
+ if (error instanceof WindowsElevationError && error.reason === "cancelled") {
792
+ return "released";
793
+ }
794
+ if (error instanceof WindowsElevationError && error.reason === "launch-failed") {
795
+ return "released";
796
+ }
797
+ if (error instanceof WindowsElevationError && error.reason === "terminated") {
798
+ try {
799
+ await reconcileUnknownElevatedOutcome(OCX_ELEVATED_PROTOCOL_FAILED);
800
+ return "released";
801
+ } catch (reconcileError) {
802
+ return isPartialInstallError(reconcileError) ? "blocked-partial" : "released";
803
+ }
804
+ }
805
+ // applyElevatedSchedulerResult failures are expected (create/run/conflict); swallow for background.
806
+ if (isPartialInstallError(error)) {
807
+ return "blocked-partial";
808
+ }
809
+ return "released";
810
+ }
811
+ })();
812
+
813
+ return { kind: "indeterminate", attemptId, reconciliation };
814
+ }
815
+
816
+ /**
817
+ * Pure post-restart / pre-install advisory check. Does not mutate state.
818
+ * A process-local indeterminate lock cannot survive restart — callers must inspect reality.
819
+ */
820
+ export function evaluateSchedulerInstallRestartReconciliation(inputs: {
821
+ taskInstalled: boolean;
822
+ registrationHealthy: boolean;
823
+ assetsHealthy: boolean;
824
+ nativeStatus: "started" | "stopped" | "nonexistent" | "unknown";
825
+ installStateBackend: "scheduler" | "native" | null;
826
+ }): {
827
+ status: "healthy" | "orphan-task" | "stale-install-state" | "conflict" | "unhealthy" | "unverified";
828
+ detail: string;
829
+ } {
830
+ const conflict = inputs.taskInstalled
831
+ && (inputs.nativeStatus === "started" || inputs.nativeStatus === "stopped");
832
+ if (conflict) {
833
+ return {
834
+ status: "conflict",
835
+ detail: `CONFLICT: Task Scheduler and native WinSW (${WINSW_SERVICE_ID}) are both present.`,
836
+ };
837
+ }
838
+ if (inputs.taskInstalled && inputs.nativeStatus === "unknown") {
839
+ return {
840
+ status: "unverified",
841
+ detail: "The Task Scheduler task exists, but native WinSW status could not be verified.",
842
+ };
843
+ }
844
+ if (inputs.taskInstalled && (!inputs.registrationHealthy || !inputs.assetsHealthy)) {
845
+ return {
846
+ status: "unhealthy",
847
+ detail: !inputs.assetsHealthy
848
+ ? "Required scheduler service assets are missing."
849
+ : "Task Scheduler registration is present but unhealthy.",
850
+ };
851
+ }
852
+ if (inputs.taskInstalled && inputs.installStateBackend !== "scheduler") {
853
+ return {
854
+ status: "orphan-task",
855
+ detail: "A Task Scheduler task is present without matching scheduler install state.",
856
+ };
857
+ }
858
+ if (!inputs.taskInstalled && inputs.installStateBackend === "scheduler") {
859
+ return {
860
+ status: "stale-install-state",
861
+ detail: "Scheduler install state is present but the Task Scheduler task is absent.",
862
+ };
863
+ }
864
+ return { status: "healthy", detail: "ok" };
865
+ }
866
+
358
867
  function windowsBatchValue(value: string): string {
359
868
  return value
360
869
  .replace(/%/g, "%%")