agentroam 0.2.0-preview.8 → 0.2.0-preview.81
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/README.md +61 -15
- package/bin/agentroam.mjs +10 -1
- package/bin/cli-progress.d.mts +9 -0
- package/bin/cli-progress.mjs +65 -0
- package/bin/desktop-download.mjs +69 -0
- package/bin/node-preflight.mjs +171 -0
- package/bin/node-runtime-policy.json +4 -0
- package/bin/runtime-policy.d.mts +5 -0
- package/bin/runtime-policy.mjs +37 -0
- package/dist/abort.js +25 -0
- package/dist/args.js +136 -5
- package/dist/cli.js +295 -44
- package/dist/cloudflared/bundled-asset.js +3 -2
- package/dist/cloudflared/manifest.js +2 -2
- package/dist/codex-desktop-command.js +70 -0
- package/dist/codex-desktop-force-stop.js +46 -0
- package/dist/codex-desktop-idle-guard.js +15 -0
- package/dist/codex-desktop-preflight.js +63 -0
- package/dist/codex-desktop-probe.js +152 -0
- package/dist/codex-desktop-setup.js +154 -0
- package/dist/codex-desktop-status.js +85 -0
- package/dist/codex-desktop-windows.js +122 -0
- package/dist/codex-runtime-manager.js +368 -0
- package/dist/codex-sharing.js +155 -0
- package/dist/codex-windows-backend-host.js +59 -0
- package/dist/codex-windows-backend.js +120 -0
- package/dist/desktop-authorization-prompt.js +84 -0
- package/dist/desktop-authorization.js +177 -0
- package/dist/device-pairing.js +228 -0
- package/dist/error-log.js +113 -0
- package/dist/instance-takeover.js +143 -0
- package/dist/local-desktop-url.js +8 -0
- package/dist/local-service-request.js +69 -0
- package/dist/mesh/mesh-command.js +51 -0
- package/dist/mesh/mesh-config.js +95 -0
- package/dist/mesh/mesh-payload.js +20 -0
- package/dist/mesh/mesh-runtime.js +101 -0
- package/dist/native-runtime.js +68 -0
- package/dist/network.js +46 -3
- package/dist/node-runtime-manager.js +251 -0
- package/dist/opencode-runtime-manager.js +260 -0
- package/dist/platform-packages.js +18 -5
- package/dist/platform.js +6 -4
- package/dist/power/sleep-inhibitor.js +161 -0
- package/dist/runtime-manager.js +139 -19
- package/dist/self-hosted-relay.json +1 -0
- package/dist/service/launcher-cleanup.js +79 -0
- package/dist/service/macos-launch-agent.js +288 -0
- package/dist/service/runtime-state.js +43 -0
- package/dist/service/service-command.js +226 -0
- package/dist/service/service-controller.js +29 -0
- package/dist/service/service-files.js +78 -0
- package/dist/service/windows-service-host.js +59 -0
- package/dist/service/windows-task-service.js +289 -0
- package/dist/startup-lock.js +81 -0
- package/dist/tailscale/bundled-asset.js +43 -0
- package/dist/tailscale/daemon-manager.js +112 -0
- package/dist/tailscale/installer.js +131 -0
- package/dist/tailscale/manifest.js +15 -0
- package/dist/tailscale/tailnet-cli.js +101 -0
- package/dist/todo-mcp-command.js +27 -0
- package/dist/tunnel/cloudflare-provider.js +4 -1
- package/dist/tunnel/public-readiness.js +76 -50
- package/dist/tunnel/relay-orchestrator.js +53 -19
- package/dist/tunnel/self-hosted-provider.js +147 -0
- package/dist/tunnel/tunnel-controller.js +232 -0
- package/dist/unlock-service.js +105 -0
- package/dist/update/update-channel.js +38 -0
- package/dist/update/update-command.js +97 -0
- package/dist/update/update-install.js +34 -0
- package/dist/update/update-state.js +43 -0
- package/dist/update/update-worker.js +82 -0
- package/install/README.md +55 -0
- package/install/codex-shared-watchdog.sh +16 -0
- package/install/install-agentroam.ps1 +358 -0
- package/install/install-agentroam.sh +457 -0
- package/install/install-manifest.json +15 -0
- package/install/start-codex-desktop-shared.sh +152 -0
- package/install/write-relay-default.mjs +6 -0
- package/package.json +15 -10
- package/dist/args.test.js +0 -27
- package/dist/cloudflared/bundled-asset.test.js +0 -76
- package/dist/cloudflared/installer.test.js +0 -95
- package/dist/native-runtime.test.js +0 -19
- package/dist/network.test.js +0 -20
- package/dist/pairing.js +0 -2
- package/dist/platform-packages.test.js +0 -75
- package/dist/platform.test.js +0 -3
- package/dist/port.test.js +0 -3
- package/dist/process-supervisor.test.js +0 -42
- package/dist/tunnel/cloudflare-provider.test.js +0 -33
- package/dist/tunnel/pinggy-provider.test.js +0 -40
- package/dist/tunnel/proxy-settings.test.js +0 -111
- package/dist/tunnel/public-readiness.test.js +0 -104
- package/dist/tunnel/relay-orchestrator.test.js +0 -72
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { promisify } from "node:util";
|
|
3
|
+
import { withDesktopRpc } from "./codex-desktop-probe.js";
|
|
4
|
+
import { ensureWindowsBackend, readWindowsBackend, WINDOWS_CODEX_TASK } from "./codex-windows-backend.js";
|
|
5
|
+
const executeFile = promisify(execFile);
|
|
6
|
+
export function windowsSharingEndpoint(environment) {
|
|
7
|
+
const endpoint = environment.AGENT_CODEX_DESKTOP_WS_URL || environment.CODEX_APP_SERVER_WS_URL;
|
|
8
|
+
if (!endpoint)
|
|
9
|
+
return null;
|
|
10
|
+
const url = new URL(endpoint);
|
|
11
|
+
if (url.protocol !== "ws:" || !["127.0.0.1", "localhost", "[::1]"].includes(url.hostname)
|
|
12
|
+
|| url.username || url.password || url.search || url.hash)
|
|
13
|
+
throw new Error("Windows 共享后端必须使用无凭据的本机 WebSocket 地址。");
|
|
14
|
+
return url.href;
|
|
15
|
+
}
|
|
16
|
+
export function powershellLiteral(value) { return `'${value.replaceAll("'", "''")}'`; }
|
|
17
|
+
export async function runWindowsCodexDesktop(options, context = {}) {
|
|
18
|
+
const environment = { ...(context.environment ?? process.env) };
|
|
19
|
+
const log = context.log ?? console.log;
|
|
20
|
+
const execute = context.execute ?? executeFile;
|
|
21
|
+
const run = (script) => execute("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", `$ErrorActionPreference='Stop'; ${script}`], { env: environment, encoding: "utf8", timeout: 15_000, maxBuffer: 1024 * 1024, windowsHide: true });
|
|
22
|
+
const report = { state: "unsupported", configured: false, autoStart: false, daemonReachable: false,
|
|
23
|
+
message: "Windows 共享后台尚未就绪;已保留 Codex,不会强制重启。" };
|
|
24
|
+
let endpoint = windowsSharingEndpoint(environment);
|
|
25
|
+
if (!endpoint) {
|
|
26
|
+
const config = options.desktopSharingStatus || options.desktopDryRun
|
|
27
|
+
? await (context.readBackend ?? readWindowsBackend)()
|
|
28
|
+
: await (context.backend ?? ensureWindowsBackend)(options.dataDir, { environment, execute });
|
|
29
|
+
if (config) {
|
|
30
|
+
endpoint = config.endpoint;
|
|
31
|
+
environment.CODEX_HOME = config.codexHome;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
if (!endpoint) {
|
|
35
|
+
report.state = "failed";
|
|
36
|
+
report.message = "Windows 共享后台尚未配置,请运行安装或点击检查并修复。";
|
|
37
|
+
log(JSON.stringify(report));
|
|
38
|
+
return report;
|
|
39
|
+
}
|
|
40
|
+
environment.AGENT_CODEX_DESKTOP_WS_URL = endpoint;
|
|
41
|
+
let binary = environment.CODEX_DESKTOP_APP;
|
|
42
|
+
if (!binary) {
|
|
43
|
+
const { stdout } = await run(`$candidates=@(); $sid=[System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value; Get-CimInstance Win32_Process | Where-Object { $_.Name -in @('Codex.exe','ChatGPT.exe') -and $_.CommandLine -notmatch '--type=' } | ForEach-Object { if ((Invoke-CimMethod -InputObject $_ -MethodName GetOwnerSid).Sid -eq $sid) { $candidates += $_.ExecutablePath } }; Get-AppxPackage | Where-Object { $_.Name -match 'OpenAI.*(Codex|ChatGPT)' } | ForEach-Object { $root=$_.InstallLocation; $manifest=Get-AppxPackageManifest $_; $manifest.Package.Applications.Application | ForEach-Object { if ($_.Executable) { $candidates += Join-Path $root $_.Executable } } }; $candidates += @((Join-Path $env:LOCALAPPDATA 'Programs\\Codex\\Codex.exe'),(Join-Path $env:LOCALAPPDATA 'Programs\\ChatGPT\\ChatGPT.exe')); foreach($candidate in ($candidates | Select-Object -Unique)) { if ($candidate -and (Test-Path -LiteralPath $candidate -PathType Leaf) -and [IO.Path]::GetFileName($candidate) -in @('Codex.exe','ChatGPT.exe')) { $signature=Get-AuthenticodeSignature -LiteralPath $candidate; if ($signature.Status -eq 'Valid' -and $signature.SignerCertificate.Subject -match 'OpenAI') { Write-Output $candidate; break } } }`);
|
|
44
|
+
binary = stdout.trim() || undefined;
|
|
45
|
+
}
|
|
46
|
+
if (!binary || !/^[A-Za-z]:\\.*\.exe$/i.test(binary)) {
|
|
47
|
+
report.state = "not-installed";
|
|
48
|
+
report.message = "未找到当前用户安装的官方 Codex 桌面端;不会结束其他程序。";
|
|
49
|
+
log(JSON.stringify(report));
|
|
50
|
+
return report;
|
|
51
|
+
}
|
|
52
|
+
const encodedBinary = powershellLiteral(binary);
|
|
53
|
+
const { stdout: supported } = await run(`$signature=Get-AuthenticodeSignature -LiteralPath ${encodedBinary}; if ($signature.Status -ne 'Valid' -or $signature.SignerCertificate.Subject -notmatch 'OpenAI') { throw 'Not an official signed Desktop executable' }; $archive=Join-Path (Split-Path ${encodedBinary}) 'resources\\app.asar'; if (Test-Path -LiteralPath $archive) { $text=[Text.Encoding]::UTF8.GetString([IO.File]::ReadAllBytes($archive)); if ($text.Contains('CODEX_APP_SERVER_WS_URL')) { 'supported' } }`);
|
|
54
|
+
if (supported.trim() !== "supported") {
|
|
55
|
+
report.message = "当前 Windows 官方桌面版本未提供可确认的共享连接能力,已保留进程。";
|
|
56
|
+
log(JSON.stringify(report));
|
|
57
|
+
return report;
|
|
58
|
+
}
|
|
59
|
+
const processes = async () => {
|
|
60
|
+
const { stdout } = await run(`$sid=[System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value; @((Get-CimInstance Win32_Process | Where-Object { $_.ExecutablePath -eq ${encodedBinary} -and $_.CommandLine -notmatch '--type=' -and (Invoke-CimMethod -InputObject $_ -MethodName GetOwnerSid).Sid -eq $sid }) | Select-Object ProcessId,@{Name='CreationDate';Expression={$_.CreationDate.ToString('o')}},ExecutablePath) | ConvertTo-Json -Compress`);
|
|
61
|
+
const rows = JSON.parse(stdout.trim() || "[]");
|
|
62
|
+
return (Array.isArray(rows) ? rows : [rows]);
|
|
63
|
+
};
|
|
64
|
+
const initial = await processes();
|
|
65
|
+
if (initial.length > 1)
|
|
66
|
+
throw new Error("检测到多个 Codex 桌面实例,无法安全确定重启目标。");
|
|
67
|
+
report.backendEndpoint = endpoint;
|
|
68
|
+
const { stdout: task } = await run(`$task=Get-ScheduledTask -TaskName '${WINDOWS_CODEX_TASK}' -ErrorAction SilentlyContinue; if ($task -and $task.State -eq 'Running') { 'running' }`);
|
|
69
|
+
report.autoStart = task.trim() === "running";
|
|
70
|
+
report.state = initial.length ? "independent" : "stopped";
|
|
71
|
+
if (!options.desktopDryRun) {
|
|
72
|
+
await (context.probe ?? (async (url) => { await withDesktopRpc(url, async (request) => { await request("config/read", { includeLayers: false }); }); }))(endpoint);
|
|
73
|
+
report.daemonReachable = true;
|
|
74
|
+
}
|
|
75
|
+
const { stdout: defaults } = await run(`[Environment]::GetEnvironmentVariable('CODEX_APP_SERVER_WS_URL','User')`);
|
|
76
|
+
report.configured = defaults.trim() === endpoint;
|
|
77
|
+
if (initial.length && report.daemonReachable) {
|
|
78
|
+
const port = new URL(endpoint).port || "80";
|
|
79
|
+
const { stdout } = await run(`$listeners=@(Get-NetTCPConnection -State Listen -LocalPort ${port} -ErrorAction SilentlyContinue); if ($listeners.Count -eq 0 -or @($listeners | Where-Object { $_.LocalAddress -notin @('127.0.0.1','::1') -or $_.OwningProcess -eq ${initial[0].ProcessId} }).Count -gt 0) { throw 'Shared endpoint ownership unavailable' }; $ids=@(${initial[0].ProcessId}); $family=@(Get-CimInstance Win32_Process | Where-Object { $_.ExecutablePath -eq ${encodedBinary} }); do { $added=@($family | Where-Object { $_.ParentProcessId -in $ids -and $_.ProcessId -notin $ids } | ForEach-Object { $_.ProcessId }); $ids += $added } while ($added.Count -gt 0); @(Get-NetTCPConnection -State Established -ErrorAction SilentlyContinue | Where-Object { $_.OwningProcess -in $ids -and $_.RemotePort -eq ${port} -and $_.RemoteAddress -in @('127.0.0.1','::1') }).Count`);
|
|
80
|
+
if (Number(stdout.trim()) > 0)
|
|
81
|
+
report.state = "shared";
|
|
82
|
+
}
|
|
83
|
+
report.message = report.state === "shared" ? "Codex 已连接配置的共享后台。" : report.state === "stopped" ? "共享后端可用;Codex 桌面保持关闭。" : "Codex 未连接共享后台;Windows 暂无法可靠判断桌面任务,切换前需要确认强制重启。";
|
|
84
|
+
if (options.desktopDryRun) {
|
|
85
|
+
log(JSON.stringify({ ...report, message: "Dry run: 未写配置、未启动或结束任何进程。" }));
|
|
86
|
+
return report;
|
|
87
|
+
}
|
|
88
|
+
if (options.desktopSharingStatus) {
|
|
89
|
+
log(JSON.stringify(report));
|
|
90
|
+
return report;
|
|
91
|
+
}
|
|
92
|
+
await run(`[Environment]::SetEnvironmentVariable('CODEX_APP_SERVER_WS_URL',${powershellLiteral(endpoint)},'User'); [Environment]::SetEnvironmentVariable('CODEX_APP_SERVER_FORCE_CLI','0','User')`);
|
|
93
|
+
await run(`Add-Type -Namespace AgentRoam -Name EnvironmentBroadcast -MemberDefinition '[DllImport("user32.dll", CharSet=CharSet.Unicode, SetLastError=true)] public static extern IntPtr SendMessageTimeout(IntPtr hWnd, uint Msg, UIntPtr wParam, string lParam, uint flags, uint timeout, out UIntPtr result);'; $result=[UIntPtr]::Zero; [AgentRoam.EnvironmentBroadcast]::SendMessageTimeout([IntPtr]0xffff,0x1a,[UIntPtr]::Zero,'Environment',2,3000,[ref]$result) | Out-Null`);
|
|
94
|
+
report.configured = true;
|
|
95
|
+
if (options.desktopRepair || report.state === "shared") {
|
|
96
|
+
log(JSON.stringify(report));
|
|
97
|
+
return report;
|
|
98
|
+
}
|
|
99
|
+
if (options.desktopSetup && report.state === "stopped") {
|
|
100
|
+
log(JSON.stringify(report));
|
|
101
|
+
return report;
|
|
102
|
+
}
|
|
103
|
+
if (initial.length && !options.desktopRestart) {
|
|
104
|
+
if (options.desktopSetup && environment.AGENTROAM_CODEX_DESKTOP_NONINTERACTIVE === "1") {
|
|
105
|
+
log(JSON.stringify({ codexSharingAction: "confirmation-required" }));
|
|
106
|
+
log(JSON.stringify(report));
|
|
107
|
+
return report;
|
|
108
|
+
}
|
|
109
|
+
throw new Error("Windows 桌面任务状态无法确认。请确认中断风险后使用 --restart;不会自动结束进程。");
|
|
110
|
+
}
|
|
111
|
+
if (initial.length) {
|
|
112
|
+
const target = initial[0];
|
|
113
|
+
if (!Number.isSafeInteger(target.ProcessId) || target.ProcessId <= 1)
|
|
114
|
+
throw new Error("无效的桌面 PID");
|
|
115
|
+
await run(`$target=Get-CimInstance Win32_Process -Filter 'ProcessId=${target.ProcessId}'; if (!$target -or $target.ExecutablePath -ne ${encodedBinary} -or $target.CreationDate.ToString('o') -ne ${powershellLiteral(String(target.CreationDate))}) { throw 'Desktop process identity changed' }; $sid=[System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value; if ((Invoke-CimMethod -InputObject $target -MethodName GetOwnerSid).Sid -ne $sid) { throw 'Desktop user changed' }; $root=(Split-Path ${encodedBinary}) + '\\'; $private=@(Get-CimInstance Win32_Process | Where-Object { $_.ParentProcessId -eq ${target.ProcessId} -and $_.ExecutablePath -and $_.ExecutablePath.StartsWith($root,[StringComparison]::OrdinalIgnoreCase) -and $_.Name -eq 'codex.exe' -and $_.CommandLine -match '\\sapp-server(?:\\s|$)' -and $_.CommandLine -notmatch '\\s(proxy|daemon)(?:\\s|$)|--managed-daemon' }); foreach($child in $private) { $live=Get-CimInstance Win32_Process -Filter "ProcessId=$($child.ProcessId)"; if (!$live -or $live.CreationDate -ne $child.CreationDate -or $live.ParentProcessId -ne ${target.ProcessId} -or $live.ExecutablePath -ne $child.ExecutablePath) { throw 'Private backend identity changed' }; Stop-Process -Id $child.ProcessId -Force }; Stop-Process -Id ${target.ProcessId} -Force; Wait-Process -Id ${target.ProcessId} -Timeout 10 -ErrorAction SilentlyContinue; if (Get-Process -Id ${target.ProcessId} -ErrorAction SilentlyContinue) { throw 'Desktop did not exit' }`);
|
|
116
|
+
}
|
|
117
|
+
await run(`$env:CODEX_APP_SERVER_WS_URL=${powershellLiteral(endpoint)}; ${environment.CODEX_HOME ? `$env:CODEX_HOME=${powershellLiteral(environment.CODEX_HOME)}; ` : ''}$env:CODEX_APP_SERVER_FORCE_CLI='0'; Start-Process -FilePath ${encodedBinary}`);
|
|
118
|
+
report.state = "failed";
|
|
119
|
+
report.message = "已请求共享启动;请刷新并验证实际连接,尚不能确认共享成功。";
|
|
120
|
+
log(JSON.stringify(report));
|
|
121
|
+
return report;
|
|
122
|
+
}
|
|
@@ -0,0 +1,368 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { constants } from "node:fs";
|
|
3
|
+
import { access, chmod, mkdir, mkdtemp, open, readdir, rename, rm, stat, } from "node:fs/promises";
|
|
4
|
+
import { delimiter, dirname, isAbsolute, relative, resolve, win32 } from "node:path";
|
|
5
|
+
import { promisify } from "node:util";
|
|
6
|
+
import { withAbortSignal } from "./abort.js";
|
|
7
|
+
const execFileAsync = promisify(execFile);
|
|
8
|
+
// Fresh installs follow npm's latest stable release; existing installs have an independent floor.
|
|
9
|
+
export const CODEX_RUNTIME_TAG = "latest";
|
|
10
|
+
export const CODEX_MINIMUM_VERSION = "0.153.0";
|
|
11
|
+
const CODEX_PACKAGE = `@openai/codex@${CODEX_RUNTIME_TAG}`;
|
|
12
|
+
const NPM_REGISTRY = "https://registry.npmjs.org";
|
|
13
|
+
export const CODEX_INSTALL_TIMEOUT_MS = 180_000;
|
|
14
|
+
const DEFAULT_LOCK_WAIT_MS = 190_000;
|
|
15
|
+
export const CODEX_INSTALL_STALE_LOCK_MS = CODEX_INSTALL_TIMEOUT_MS + 5 * 60_000;
|
|
16
|
+
const DEFAULT_STALE_LOCK_MS = CODEX_INSTALL_STALE_LOCK_MS;
|
|
17
|
+
const defaultDependencies = {
|
|
18
|
+
async run(command, args, timeoutMs, signal) {
|
|
19
|
+
try {
|
|
20
|
+
const { stdout, stderr } = await execFileAsync(command, args, {
|
|
21
|
+
encoding: "utf8",
|
|
22
|
+
timeout: timeoutMs,
|
|
23
|
+
signal,
|
|
24
|
+
killSignal: "SIGKILL",
|
|
25
|
+
maxBuffer: 4 * 1024 * 1024,
|
|
26
|
+
windowsHide: true,
|
|
27
|
+
});
|
|
28
|
+
return { stdout, stderr };
|
|
29
|
+
}
|
|
30
|
+
catch (error) {
|
|
31
|
+
const value = error;
|
|
32
|
+
const details = [value.message, value.stderr?.trim(), value.stdout?.trim()]
|
|
33
|
+
.filter(Boolean)
|
|
34
|
+
.join(": ");
|
|
35
|
+
throw new Error(details || "process failed", { cause: error });
|
|
36
|
+
}
|
|
37
|
+
},
|
|
38
|
+
sleep: (delayMs) => new Promise((resolveDelay) => setTimeout(resolveDelay, delayMs)),
|
|
39
|
+
now: () => Date.now(),
|
|
40
|
+
};
|
|
41
|
+
export async function resolveCodexRuntime(options) {
|
|
42
|
+
return options.signal
|
|
43
|
+
? withAbortSignal(() => resolveRuntime(options), options.signal)
|
|
44
|
+
: resolveRuntime(options);
|
|
45
|
+
}
|
|
46
|
+
async function resolveRuntime(options) {
|
|
47
|
+
const environment = options.environment ?? process.env;
|
|
48
|
+
const platform = options.platform ?? process.platform;
|
|
49
|
+
const dependencies = { ...defaultDependencies, ...options.dependencies };
|
|
50
|
+
const signal = options.signal;
|
|
51
|
+
if (signal) {
|
|
52
|
+
const run = dependencies.run;
|
|
53
|
+
const sleep = dependencies.sleep;
|
|
54
|
+
dependencies.run = (command, args, timeoutMs) => withAbortSignal(() => run(command, args, timeoutMs, signal), signal);
|
|
55
|
+
dependencies.sleep = (delayMs) => withAbortSignal(() => sleep(delayMs), signal);
|
|
56
|
+
}
|
|
57
|
+
const explicit = environment.AGENT_CODEX_BIN?.trim();
|
|
58
|
+
if (explicit) {
|
|
59
|
+
const absolute = platform === "win32" ? win32.isAbsolute(explicit) : isAbsolute(explicit);
|
|
60
|
+
if (!absolute) {
|
|
61
|
+
throw new Error("AGENT_CODEX_BIN must be an absolute path");
|
|
62
|
+
}
|
|
63
|
+
return validateCodex(explicit, "explicit", platform, dependencies);
|
|
64
|
+
}
|
|
65
|
+
const global = await findCompatibleGlobalCodex(environment.PATH, platform, dependencies);
|
|
66
|
+
if (global)
|
|
67
|
+
return global;
|
|
68
|
+
const managedParent = resolve(options.dataDir, "runtimes", "codex");
|
|
69
|
+
const managed = await findManagedRuntime(managedParent, options.target, platform, dependencies);
|
|
70
|
+
if (managed)
|
|
71
|
+
return managed;
|
|
72
|
+
signal?.throwIfAborted();
|
|
73
|
+
if (options.installIfMissing === false)
|
|
74
|
+
throw new Error("Codex is not installed; run agentroam doctor to install it.");
|
|
75
|
+
options.onProgress?.(`Installing managed Codex from ${CODEX_PACKAGE}...`);
|
|
76
|
+
return installManagedCodex({
|
|
77
|
+
...options,
|
|
78
|
+
environment,
|
|
79
|
+
platform,
|
|
80
|
+
dependencies,
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
export async function resolveNpmExecutor(options = {}) {
|
|
84
|
+
const environment = options.environment ?? process.env;
|
|
85
|
+
const platform = options.platform ?? process.platform;
|
|
86
|
+
const canAccess = options.canAccess ?? pathAccessible;
|
|
87
|
+
const npmExecPath = environment.npm_execpath?.trim();
|
|
88
|
+
const npmExecPathIsAbsolute = npmExecPath
|
|
89
|
+
&& (platform === "win32" ? win32.isAbsolute(npmExecPath) : isAbsolute(npmExecPath));
|
|
90
|
+
if (npmExecPath && npmExecPathIsAbsolute && await canAccess(npmExecPath)) {
|
|
91
|
+
return {
|
|
92
|
+
command: options.nodeExecutable ?? process.execPath,
|
|
93
|
+
argsPrefix: [npmExecPath],
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
const nodeExecutable = options.nodeExecutable ?? process.execPath;
|
|
97
|
+
const nodeDirectory = platform === "win32" ? win32.dirname(nodeExecutable) : dirname(nodeExecutable);
|
|
98
|
+
const adjacentNpmCandidates = platform === "win32"
|
|
99
|
+
? [
|
|
100
|
+
win32.resolve(nodeDirectory, "node_modules", "npm", "bin", "npm-cli.js"),
|
|
101
|
+
win32.resolve(nodeDirectory, "..", "node_modules", "npm", "bin", "npm-cli.js"),
|
|
102
|
+
]
|
|
103
|
+
: [
|
|
104
|
+
resolve(nodeDirectory, "..", "lib", "node_modules", "npm", "bin", "npm-cli.js"),
|
|
105
|
+
resolve(nodeDirectory, "lib", "node_modules", "npm", "bin", "npm-cli.js"),
|
|
106
|
+
];
|
|
107
|
+
for (const npmCliPath of adjacentNpmCandidates) {
|
|
108
|
+
if (await canAccess(npmCliPath)) {
|
|
109
|
+
return { command: nodeExecutable, argsPrefix: [npmCliPath] };
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
const names = platform === "win32" ? ["npm.cmd", "npm.exe", "npm"] : ["npm"];
|
|
113
|
+
const pathDelimiter = platform === "win32" ? ";" : delimiter;
|
|
114
|
+
for (const directory of (environment.PATH ?? "").split(pathDelimiter).filter(Boolean)) {
|
|
115
|
+
for (const name of names) {
|
|
116
|
+
const candidate = platform === "win32" ? win32.resolve(directory, name) : resolve(directory, name);
|
|
117
|
+
if (!(await canAccess(candidate)))
|
|
118
|
+
continue;
|
|
119
|
+
if (platform === "win32" && name === "npm.cmd") {
|
|
120
|
+
const npmCliCandidates = [
|
|
121
|
+
win32.resolve(directory, "node_modules", "npm", "bin", "npm-cli.js"),
|
|
122
|
+
win32.resolve(directory, "..", "node_modules", "npm", "bin", "npm-cli.js"),
|
|
123
|
+
];
|
|
124
|
+
for (const npmCliPath of npmCliCandidates) {
|
|
125
|
+
if (await canAccess(npmCliPath)) {
|
|
126
|
+
return {
|
|
127
|
+
command: options.nodeExecutable ?? process.execPath,
|
|
128
|
+
argsPrefix: [npmCliPath],
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
return { command: candidate, argsPrefix: [] };
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
throw new Error("Codex runtime installer unavailable: npm was not found");
|
|
138
|
+
}
|
|
139
|
+
export function managedCodexBinaryCandidates(runtimeRoot, target) {
|
|
140
|
+
const platformInfo = codexPlatformInfo(target);
|
|
141
|
+
const vendorRoot = resolve(runtimeRoot, "node_modules", "@openai", platformInfo.packageName, "vendor", platformInfo.vendorTarget);
|
|
142
|
+
return [
|
|
143
|
+
resolve(vendorRoot, "bin", platformInfo.executable),
|
|
144
|
+
resolve(vendorRoot, "codex", platformInfo.executable),
|
|
145
|
+
resolve(vendorRoot, platformInfo.executable),
|
|
146
|
+
];
|
|
147
|
+
}
|
|
148
|
+
export function parseCodexVersion(output) {
|
|
149
|
+
const match = output.match(/(?:^|\s)(\d+\.\d+\.\d+)(?:\s|$)/);
|
|
150
|
+
return match?.[1] ?? null;
|
|
151
|
+
}
|
|
152
|
+
// Compare numeric components, so 0.153.10 and 0.154.0 both exceed 0.153.2.
|
|
153
|
+
export function isCodexVersionAtLeast(version, minimum) {
|
|
154
|
+
const actual = version.split(".").map(BigInt);
|
|
155
|
+
const required = minimum.split(".").map(BigInt);
|
|
156
|
+
for (let index = 0; index < required.length; index += 1) {
|
|
157
|
+
if (actual[index] !== required[index])
|
|
158
|
+
return actual[index] > required[index];
|
|
159
|
+
}
|
|
160
|
+
return true;
|
|
161
|
+
}
|
|
162
|
+
function meetsCodexMinimum(version) {
|
|
163
|
+
return isCodexVersionAtLeast(version, CODEX_MINIMUM_VERSION);
|
|
164
|
+
}
|
|
165
|
+
async function findCompatibleGlobalCodex(pathValue, platform, dependencies) {
|
|
166
|
+
const names = platform === "win32" ? ["codex.exe", "codex"] : ["codex"];
|
|
167
|
+
const pathDelimiter = platform === "win32" ? ";" : delimiter;
|
|
168
|
+
for (const directory of (pathValue ?? "").split(pathDelimiter).filter(Boolean)) {
|
|
169
|
+
for (const name of names) {
|
|
170
|
+
const candidate = platform === "win32" ? win32.resolve(directory, name) : resolve(directory, name);
|
|
171
|
+
if (!(await pathAccessible(candidate, platform !== "win32")))
|
|
172
|
+
continue;
|
|
173
|
+
try {
|
|
174
|
+
return await validateCodex(candidate, "global", platform, dependencies);
|
|
175
|
+
}
|
|
176
|
+
catch {
|
|
177
|
+
// An incompatible user installation is left untouched; try managed Codex.
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
return null;
|
|
182
|
+
}
|
|
183
|
+
async function installManagedCodex(options) {
|
|
184
|
+
const parent = resolve(options.dataDir, "runtimes", "codex");
|
|
185
|
+
const lockPath = resolve(parent, "install.lock");
|
|
186
|
+
const lockWaitMs = options.lockWaitMs ?? DEFAULT_LOCK_WAIT_MS;
|
|
187
|
+
const staleLockMs = options.staleLockMs ?? DEFAULT_STALE_LOCK_MS;
|
|
188
|
+
await mkdir(parent, { recursive: true });
|
|
189
|
+
const lock = await acquireInstallLock(lockPath, parent, options.target, options.platform, options.dependencies, lockWaitMs, staleLockMs);
|
|
190
|
+
if (lock.completed)
|
|
191
|
+
return lock.completed;
|
|
192
|
+
let temporaryRoot = null;
|
|
193
|
+
try {
|
|
194
|
+
const existing = await findManagedRuntime(parent, options.target, options.platform, options.dependencies);
|
|
195
|
+
if (existing)
|
|
196
|
+
return existing;
|
|
197
|
+
temporaryRoot = await mkdtemp(resolve(parent, `.${CODEX_RUNTIME_TAG}-${process.pid}-`));
|
|
198
|
+
const npm = await resolveNpmExecutor({
|
|
199
|
+
environment: options.environment,
|
|
200
|
+
platform: options.platform,
|
|
201
|
+
nodeExecutable: options.nodeExecutable,
|
|
202
|
+
});
|
|
203
|
+
await options.dependencies.run(npm.command, [
|
|
204
|
+
...npm.argsPrefix,
|
|
205
|
+
"install",
|
|
206
|
+
"--ignore-scripts",
|
|
207
|
+
"--no-audit",
|
|
208
|
+
"--no-fund",
|
|
209
|
+
"--prefer-online",
|
|
210
|
+
`--registry=${NPM_REGISTRY}`,
|
|
211
|
+
"--prefix",
|
|
212
|
+
temporaryRoot,
|
|
213
|
+
CODEX_PACKAGE,
|
|
214
|
+
], CODEX_INSTALL_TIMEOUT_MS);
|
|
215
|
+
const temporary = await validateManagedRuntime(temporaryRoot, options.target, options.platform, options.dependencies);
|
|
216
|
+
if (!temporary) {
|
|
217
|
+
throw new Error(`Codex runtime validation failed after installing ${CODEX_PACKAGE}`);
|
|
218
|
+
}
|
|
219
|
+
const managedRoot = resolve(parent, temporary.version);
|
|
220
|
+
options.signal?.throwIfAborted();
|
|
221
|
+
// An invalid cache for this version must not block a validated replacement.
|
|
222
|
+
await rm(managedRoot, { recursive: true, force: true });
|
|
223
|
+
await rename(temporaryRoot, managedRoot);
|
|
224
|
+
temporaryRoot = null;
|
|
225
|
+
const installed = await validateManagedRuntime(managedRoot, options.target, options.platform, options.dependencies);
|
|
226
|
+
if (!installed)
|
|
227
|
+
throw new Error("Codex runtime validation failed after activation");
|
|
228
|
+
return installed;
|
|
229
|
+
}
|
|
230
|
+
catch (error) {
|
|
231
|
+
options.signal?.throwIfAborted();
|
|
232
|
+
const concurrent = await findManagedRuntime(parent, options.target, options.platform, options.dependencies);
|
|
233
|
+
if (concurrent)
|
|
234
|
+
return concurrent;
|
|
235
|
+
throw new Error(`Unable to install managed Codex from ${CODEX_PACKAGE}: ${describeError(error)}`, {
|
|
236
|
+
cause: error,
|
|
237
|
+
});
|
|
238
|
+
}
|
|
239
|
+
finally {
|
|
240
|
+
if (temporaryRoot)
|
|
241
|
+
await rm(temporaryRoot, { recursive: true, force: true });
|
|
242
|
+
await lock.handle.close().catch(() => undefined);
|
|
243
|
+
await rm(lockPath, { force: true });
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
async function acquireInstallLock(lockPath, managedParent, target, platform, dependencies, waitMs, staleMs) {
|
|
247
|
+
const deadline = dependencies.now() + waitMs;
|
|
248
|
+
while (true) {
|
|
249
|
+
try {
|
|
250
|
+
const handle = await open(lockPath, "wx", 0o600);
|
|
251
|
+
await handle.writeFile(`${process.pid}\n${dependencies.now()}\n`);
|
|
252
|
+
return { handle };
|
|
253
|
+
}
|
|
254
|
+
catch (error) {
|
|
255
|
+
if (error.code !== "EEXIST")
|
|
256
|
+
throw error;
|
|
257
|
+
const completed = await findManagedRuntime(managedParent, target, platform, dependencies);
|
|
258
|
+
if (completed)
|
|
259
|
+
return { completed };
|
|
260
|
+
try {
|
|
261
|
+
const lockStat = await stat(lockPath);
|
|
262
|
+
if (dependencies.now() - lockStat.mtimeMs > staleMs) {
|
|
263
|
+
await rm(lockPath, { force: true });
|
|
264
|
+
continue;
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
catch {
|
|
268
|
+
continue;
|
|
269
|
+
}
|
|
270
|
+
if (dependencies.now() >= deadline) {
|
|
271
|
+
throw new Error(`Timed out waiting for Codex runtime install lock: ${lockPath}`);
|
|
272
|
+
}
|
|
273
|
+
await dependencies.sleep(Math.min(250, Math.max(1, deadline - dependencies.now())));
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
async function findManagedRuntime(parent, target, platform, dependencies) {
|
|
278
|
+
const entries = await readdir(parent, { withFileTypes: true }).catch((error) => {
|
|
279
|
+
if (error.code === "ENOENT")
|
|
280
|
+
return [];
|
|
281
|
+
throw error;
|
|
282
|
+
});
|
|
283
|
+
const versions = entries
|
|
284
|
+
.filter((entry) => entry.isDirectory() && parseCodexVersion(entry.name) === entry.name)
|
|
285
|
+
.map((entry) => entry.name)
|
|
286
|
+
.filter(meetsCodexMinimum)
|
|
287
|
+
.sort((left, right) => left === right ? 0 : isCodexVersionAtLeast(left, right) ? -1 : 1);
|
|
288
|
+
for (const version of versions) {
|
|
289
|
+
const runtime = await validateManagedRuntime(resolve(parent, version), target, platform, dependencies);
|
|
290
|
+
if (runtime?.version === version)
|
|
291
|
+
return runtime;
|
|
292
|
+
}
|
|
293
|
+
return null;
|
|
294
|
+
}
|
|
295
|
+
async function validateManagedRuntime(runtimeRoot, target, platform, dependencies) {
|
|
296
|
+
for (const candidate of managedCodexBinaryCandidates(runtimeRoot, target)) {
|
|
297
|
+
if (!isWithin(runtimeRoot, candidate) || !(await pathAccessible(candidate)))
|
|
298
|
+
continue;
|
|
299
|
+
try {
|
|
300
|
+
if (platform !== "win32")
|
|
301
|
+
await chmod(candidate, 0o755);
|
|
302
|
+
return await validateCodex(candidate, "managed", platform, dependencies);
|
|
303
|
+
}
|
|
304
|
+
catch {
|
|
305
|
+
return null;
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
return null;
|
|
309
|
+
}
|
|
310
|
+
async function validateCodex(executable, source, _platform, dependencies) {
|
|
311
|
+
if (!(await pathAccessible(executable))) {
|
|
312
|
+
throw new Error(`Codex executable not found: ${executable}`);
|
|
313
|
+
}
|
|
314
|
+
const versionResult = await dependencies.run(executable, ["--version"], 5_000);
|
|
315
|
+
const version = parseCodexVersion(`${versionResult.stdout}\n${versionResult.stderr}`);
|
|
316
|
+
if (!version) {
|
|
317
|
+
throw new Error(`Unable to parse a supported stable Codex version from ${executable}`);
|
|
318
|
+
}
|
|
319
|
+
if (!meetsCodexMinimum(version)) {
|
|
320
|
+
throw new Error(`Codex ${version} at ${executable} is incompatible; AgentRoam requires >=${CODEX_MINIMUM_VERSION}`);
|
|
321
|
+
}
|
|
322
|
+
try {
|
|
323
|
+
await dependencies.run(executable, ["app-server", "--help"], 5_000);
|
|
324
|
+
}
|
|
325
|
+
catch (error) {
|
|
326
|
+
throw new Error(`Codex app-server validation failed at ${executable}: ${describeError(error)}`, {
|
|
327
|
+
cause: error,
|
|
328
|
+
});
|
|
329
|
+
}
|
|
330
|
+
return { executable, version, source };
|
|
331
|
+
}
|
|
332
|
+
function codexPlatformInfo(target) {
|
|
333
|
+
if (target === "darwin-arm64") {
|
|
334
|
+
return {
|
|
335
|
+
packageName: "codex-darwin-arm64",
|
|
336
|
+
vendorTarget: "aarch64-apple-darwin",
|
|
337
|
+
executable: "codex",
|
|
338
|
+
};
|
|
339
|
+
}
|
|
340
|
+
if (target === "darwin-amd64") {
|
|
341
|
+
return {
|
|
342
|
+
packageName: "codex-darwin-x64",
|
|
343
|
+
vendorTarget: "x86_64-apple-darwin",
|
|
344
|
+
executable: "codex",
|
|
345
|
+
};
|
|
346
|
+
}
|
|
347
|
+
return {
|
|
348
|
+
packageName: "codex-win32-x64",
|
|
349
|
+
vendorTarget: "x86_64-pc-windows-msvc",
|
|
350
|
+
executable: "codex.exe",
|
|
351
|
+
};
|
|
352
|
+
}
|
|
353
|
+
async function pathAccessible(path, executable = false) {
|
|
354
|
+
try {
|
|
355
|
+
await access(path, executable ? constants.X_OK : constants.F_OK);
|
|
356
|
+
return true;
|
|
357
|
+
}
|
|
358
|
+
catch {
|
|
359
|
+
return false;
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
function isWithin(root, candidate) {
|
|
363
|
+
const fromRoot = relative(resolve(root), resolve(candidate));
|
|
364
|
+
return fromRoot !== "" && !fromRoot.startsWith("..") && !isAbsolute(fromRoot);
|
|
365
|
+
}
|
|
366
|
+
function describeError(error) {
|
|
367
|
+
return error instanceof Error ? error.message : String(error);
|
|
368
|
+
}
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { access, chmod, mkdir, readFile, realpath, rename, rm } from "node:fs/promises";
|
|
3
|
+
import { constants } from "node:fs";
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
import { dirname, resolve } from "node:path";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
import { isDeepStrictEqual, promisify } from "node:util";
|
|
8
|
+
import { resolveCodexRuntime } from "./codex-runtime-manager.js";
|
|
9
|
+
import { inspectCodexDesktop } from "./codex-desktop-status.js";
|
|
10
|
+
import { withDesktopRpc } from "./codex-desktop-probe.js";
|
|
11
|
+
import { detectPlatform } from "./platform.js";
|
|
12
|
+
import { writePrivateText } from "./service/service-files.js";
|
|
13
|
+
const executeFile = promisify(execFile);
|
|
14
|
+
export const CODEX_SHARING_LABEL = "com.agentroam.codex-desktop-shared-env";
|
|
15
|
+
function locations(context) {
|
|
16
|
+
const home = resolve(context.homeDir ?? homedir());
|
|
17
|
+
const environment = context.environment ?? process.env;
|
|
18
|
+
const codexHome = resolve(environment.CODEX_HOME || resolve(home, ".codex"));
|
|
19
|
+
const socketPath = resolve(codexHome, "app-server-control/app-server-control.sock");
|
|
20
|
+
return { home, environment, codexHome, socketPath,
|
|
21
|
+
endpoint: `ws+unix://localhost${encodeURI(socketPath).replaceAll("#", "%23").replaceAll("?", "%3F").replaceAll(":", "%3A")}:/rpc`,
|
|
22
|
+
root: resolve(home, ".agentroam/codex-desktop"),
|
|
23
|
+
plist: resolve(home, "Library/LaunchAgents", `${CODEX_SHARING_LABEL}.plist`),
|
|
24
|
+
target: `gui/${context.uid ?? process.getuid?.() ?? 0}/${CODEX_SHARING_LABEL}`,
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
/** Save defaults and ensure the daemon; never quit Desktop or restart a live backend. */
|
|
28
|
+
export async function configureCodexSharing(options, context = {}) {
|
|
29
|
+
if ((context.platform ?? process.platform) !== "darwin")
|
|
30
|
+
return;
|
|
31
|
+
const paths = locations(context);
|
|
32
|
+
const environment = { ...paths.environment };
|
|
33
|
+
const executable = environment.AGENT_CODEX_BIN || (await resolveCodexRuntime({
|
|
34
|
+
dataDir: options.dataDir, target: detectPlatform(), environment,
|
|
35
|
+
})).executable;
|
|
36
|
+
if (!executable.startsWith("/"))
|
|
37
|
+
throw new Error("Codex 运行文件必须使用绝对路径");
|
|
38
|
+
await access(executable, constants.X_OK);
|
|
39
|
+
const execute = context.execute ?? executeFile;
|
|
40
|
+
const script = resolve(paths.root, "watchdog.sh");
|
|
41
|
+
await writePrivateText(script, await readFile(fileURLToPath(new URL("../install/codex-shared-watchdog.sh", import.meta.url)), "utf8"));
|
|
42
|
+
const args = [script, executable, paths.codexHome, paths.endpoint, environment.PATH || "/usr/bin:/bin:/usr/sbin:/sbin", paths.home];
|
|
43
|
+
const definition = {
|
|
44
|
+
Label: CODEX_SHARING_LABEL, ProgramArguments: ["/bin/bash", ...args],
|
|
45
|
+
RunAtLoad: true, StartInterval: 15, ProcessType: "Background", WorkingDirectory: paths.home,
|
|
46
|
+
StandardOutPath: resolve(paths.root, "watchdog.log"), StandardErrorPath: resolve(paths.root, "watchdog-error.log"),
|
|
47
|
+
};
|
|
48
|
+
const json = `${paths.root}/job.json`;
|
|
49
|
+
const temporary = `${paths.root}/job.plist`;
|
|
50
|
+
const commandOptions = { encoding: "utf8", timeout: 20_000, maxBuffer: 1024 * 1024, signal: context.signal, killSignal: "SIGKILL" };
|
|
51
|
+
// Identical startup calls must not unload/reload an already healthy job.
|
|
52
|
+
let unchanged = false;
|
|
53
|
+
try {
|
|
54
|
+
const current = await execute("/usr/bin/plutil", ["-convert", "json", "-o", "-", paths.plist], commandOptions);
|
|
55
|
+
unchanged = isDeepStrictEqual(JSON.parse(String(current.stdout)), definition);
|
|
56
|
+
}
|
|
57
|
+
catch { /* First install or older definition. */ }
|
|
58
|
+
if (!unchanged) {
|
|
59
|
+
await writePrivateText(json, JSON.stringify(definition));
|
|
60
|
+
try {
|
|
61
|
+
await execute("/usr/bin/plutil", ["-convert", "xml1", "-o", temporary, json], commandOptions);
|
|
62
|
+
await chmod(temporary, 0o600);
|
|
63
|
+
await mkdir(dirname(paths.plist), { recursive: true });
|
|
64
|
+
let loaded = false;
|
|
65
|
+
try {
|
|
66
|
+
await execute("/bin/launchctl", ["print", paths.target], commandOptions);
|
|
67
|
+
loaded = true;
|
|
68
|
+
}
|
|
69
|
+
catch { /* Absent job. */ }
|
|
70
|
+
if (loaded)
|
|
71
|
+
await execute("/bin/launchctl", ["bootout", paths.target], commandOptions);
|
|
72
|
+
await rename(temporary, paths.plist);
|
|
73
|
+
}
|
|
74
|
+
finally {
|
|
75
|
+
await Promise.all([rm(json, { force: true }), rm(temporary, { force: true })]);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
await execute("/bin/launchctl", ["enable", paths.target], commandOptions);
|
|
79
|
+
let loaded = false;
|
|
80
|
+
try {
|
|
81
|
+
await execute("/bin/launchctl", ["print", paths.target], commandOptions);
|
|
82
|
+
loaded = true;
|
|
83
|
+
}
|
|
84
|
+
catch { /* bootstrap below */ }
|
|
85
|
+
if (!loaded)
|
|
86
|
+
await execute("/bin/launchctl", ["bootstrap", paths.target.slice(0, paths.target.lastIndexOf("/")), paths.plist], commandOptions);
|
|
87
|
+
// Make defaults effective now as well as on the next GUI login.
|
|
88
|
+
await execute("/bin/bash", args, { ...commandOptions, env: environment, cwd: paths.home });
|
|
89
|
+
}
|
|
90
|
+
/** Read process/socket evidence; configuration by itself never proves sharing. */
|
|
91
|
+
export async function inspectCodexSharing(context = {}) {
|
|
92
|
+
const result = { state: "failed", configured: false, autoStart: false, daemonReachable: false, message: "共享连接检查失败,请修复后重试。" };
|
|
93
|
+
if ((context.platform ?? process.platform) !== "darwin")
|
|
94
|
+
return { ...result, state: "unsupported", message: "当前系统暂不支持 Codex 桌面共享配置。" };
|
|
95
|
+
const paths = locations(context);
|
|
96
|
+
result.backendEndpoint = paths.endpoint;
|
|
97
|
+
const execute = context.execute ?? executeFile;
|
|
98
|
+
const commandOptions = { encoding: "utf8", timeout: 4_000, maxBuffer: 4 * 1024 * 1024 };
|
|
99
|
+
try {
|
|
100
|
+
const current = await execute("/bin/launchctl", ["getenv", "CODEX_APP_SERVER_WS_URL"], commandOptions).catch(() => ({ stdout: "" }));
|
|
101
|
+
const [force, home] = await Promise.all([
|
|
102
|
+
execute("/bin/launchctl", ["getenv", "CODEX_APP_SERVER_FORCE_CLI"], commandOptions).catch(() => ({ stdout: "" })),
|
|
103
|
+
execute("/bin/launchctl", ["getenv", "CODEX_HOME"], commandOptions).catch(() => ({ stdout: "" })),
|
|
104
|
+
]);
|
|
105
|
+
result.configured = String(current.stdout).trim() === paths.endpoint && String(force.stdout).trim() !== "1"
|
|
106
|
+
&& (String(home.stdout).trim() || resolve(paths.home, ".codex")) === paths.codexHome;
|
|
107
|
+
try {
|
|
108
|
+
const job = await execute("/bin/launchctl", ["print", paths.target], commandOptions);
|
|
109
|
+
const plist = await execute("/usr/bin/plutil", ["-convert", "json", "-o", "-", paths.plist], commandOptions);
|
|
110
|
+
const definition = JSON.parse(String(plist.stdout));
|
|
111
|
+
await access(resolve(paths.root, "watchdog.sh"), constants.R_OK);
|
|
112
|
+
await access(definition.ProgramArguments?.[2] ?? "", constants.X_OK);
|
|
113
|
+
result.autoStart = Boolean(job.stdout) && definition.RunAtLoad === true && definition.StartInterval === 15
|
|
114
|
+
&& definition.ProgramArguments?.[0] === "/bin/bash" && definition.ProgramArguments?.[1] === resolve(paths.root, "watchdog.sh")
|
|
115
|
+
&& definition.ProgramArguments?.[3] === paths.codexHome && definition.ProgramArguments?.[4] === paths.endpoint;
|
|
116
|
+
}
|
|
117
|
+
catch { /* Missing or outdated watchdog. */ }
|
|
118
|
+
try {
|
|
119
|
+
await (context.probe ?? (async (endpoint) => { await withDesktopRpc(endpoint, async (request) => { await request("config/read", { includeLayers: false }); }, 4_000); }))(paths.endpoint);
|
|
120
|
+
result.daemonReachable = true;
|
|
121
|
+
}
|
|
122
|
+
catch { /* Keep checking private Desktop evidence. */ }
|
|
123
|
+
const desktop = await (context.inspect ?? inspectCodexDesktop)(paths.environment);
|
|
124
|
+
if (desktop.status !== "running")
|
|
125
|
+
return { ...result, state: desktop.status, message: desktop.status === "stopped"
|
|
126
|
+
? result.configured && result.autoStart && result.daemonReachable ? "Codex 尚未启动;请使用 头像菜单或 agentroam codex-desktop 启动。普通图标或系统恢复不保证继承共享配置。" : "Codex 尚未启动;请先修复共享配置。" : "尚未安装官方 Codex 桌面端。" };
|
|
127
|
+
const { stdout } = await execute("/bin/ps", ["-axo", "pid=,ppid=,args="], commandOptions);
|
|
128
|
+
const processes = String(stdout).split("\n").flatMap(line => {
|
|
129
|
+
const match = /^\s*(\d+)\s+(\d+)\s+(.+)$/.exec(line);
|
|
130
|
+
return match ? [{ pid: Number(match[1]), parent: Number(match[2]), command: match[3] }] : [];
|
|
131
|
+
});
|
|
132
|
+
if (processes.some(p => p.parent === desktop.pid && /\bapp-server\b/.test(p.command) && !/\b(?:proxy|daemon)\b/.test(p.command))) {
|
|
133
|
+
return { ...result, state: "independent", message: "Codex 正在使用独立后台。请在任务结束时退出,再用 头像菜单或 agentroam codex-desktop 启动;不会自动中断现有会话。" };
|
|
134
|
+
}
|
|
135
|
+
if (!result.daemonReachable)
|
|
136
|
+
return result;
|
|
137
|
+
const socket = await realpath(paths.socketPath);
|
|
138
|
+
// ChatGPT can connect through a bundled helper instead of its main process.
|
|
139
|
+
const desktopPids = new Set([desktop.pid, ...processes.filter(p => p.parent === desktop.pid && p.command.startsWith(`${desktop.appPath}/Contents/`)).map(p => p.pid)]);
|
|
140
|
+
const pids = [...desktopPids, ...processes.filter(p => /\bapp-server\b/.test(p.command) && /\bcodex\b/.test(p.command)).map(p => p.pid)];
|
|
141
|
+
const sockets = await execute("/usr/sbin/lsof", ["-nP", "-a", "-p", [...new Set(pids)].join(","), "-U"], commandOptions);
|
|
142
|
+
const rows = String(sockets.stdout).split("\n").flatMap(line => {
|
|
143
|
+
const match = /^\S+\s+(\d+)\s+\S+\s+\S+\s+unix\s+(0x[\da-f]+)\s+\S+\s+(.*)$/i.exec(line);
|
|
144
|
+
return match ? [{ pid: Number(match[1]), device: match[2], name: match[3].trim() }] : [];
|
|
145
|
+
});
|
|
146
|
+
const devices = new Set(rows.filter(row => !desktopPids.has(row.pid) && row.name === socket).map(row => row.device));
|
|
147
|
+
if (rows.some(row => desktopPids.has(row.pid) && row.name.startsWith("->") && devices.has(row.name.slice(2)))) {
|
|
148
|
+
return { ...result, state: "shared", message: "Codex 已连接共享后台。" };
|
|
149
|
+
}
|
|
150
|
+
return { ...result, message: "共享后台可用,但尚未确认 Codex 连接。请在任务结束时退出,再用 头像菜单或 agentroam codex-desktop 启动。" };
|
|
151
|
+
}
|
|
152
|
+
catch {
|
|
153
|
+
return result;
|
|
154
|
+
}
|
|
155
|
+
}
|