apex-code 0.0.1-alpha.2 → 0.0.1-alpha.4

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 (56) hide show
  1. package/CHANGELOG.md +47 -1
  2. package/README.md +7 -3
  3. package/dist/cli.d.ts.map +1 -1
  4. package/dist/cli.js +9 -0
  5. package/dist/cli.js.map +1 -1
  6. package/dist/core/sandbox/child-entry.d.ts.map +1 -1
  7. package/dist/core/sandbox/child-entry.js +4 -0
  8. package/dist/core/sandbox/child-entry.js.map +1 -1
  9. package/dist/core/sandbox/cli-launch.d.ts +10 -1
  10. package/dist/core/sandbox/cli-launch.d.ts.map +1 -1
  11. package/dist/core/sandbox/cli-launch.js +50 -4
  12. package/dist/core/sandbox/cli-launch.js.map +1 -1
  13. package/dist/core/sandbox/cli-supervisor.d.ts +2 -0
  14. package/dist/core/sandbox/cli-supervisor.d.ts.map +1 -1
  15. package/dist/core/sandbox/cli-supervisor.js +1 -0
  16. package/dist/core/sandbox/cli-supervisor.js.map +1 -1
  17. package/dist/core/sandbox/default-hosts.d.ts +28 -0
  18. package/dist/core/sandbox/default-hosts.d.ts.map +1 -0
  19. package/dist/core/sandbox/default-hosts.js +69 -0
  20. package/dist/core/sandbox/default-hosts.js.map +1 -0
  21. package/dist/core/sandbox/linux-backend.d.ts +16 -0
  22. package/dist/core/sandbox/linux-backend.d.ts.map +1 -1
  23. package/dist/core/sandbox/linux-backend.js +60 -11
  24. package/dist/core/sandbox/linux-backend.js.map +1 -1
  25. package/dist/core/sandbox/macos-backend.d.ts +7 -0
  26. package/dist/core/sandbox/macos-backend.d.ts.map +1 -1
  27. package/dist/core/sandbox/macos-backend.js +17 -9
  28. package/dist/core/sandbox/macos-backend.js.map +1 -1
  29. package/dist/core/sandbox/network-refusal.d.ts +24 -0
  30. package/dist/core/sandbox/network-refusal.d.ts.map +1 -0
  31. package/dist/core/sandbox/network-refusal.js +72 -0
  32. package/dist/core/sandbox/network-refusal.js.map +1 -0
  33. package/dist/core/sandbox/supervisor.d.ts +9 -0
  34. package/dist/core/sandbox/supervisor.d.ts.map +1 -1
  35. package/dist/core/sandbox/supervisor.js.map +1 -1
  36. package/dist/core/session-share.d.ts +15 -0
  37. package/dist/core/session-share.d.ts.map +1 -1
  38. package/dist/core/session-share.js +23 -0
  39. package/dist/core/session-share.js.map +1 -1
  40. package/dist/core/settings-manager.d.ts +5 -0
  41. package/dist/core/settings-manager.d.ts.map +1 -1
  42. package/dist/core/settings-manager.js.map +1 -1
  43. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  44. package/dist/modes/interactive/interactive-mode.js +3 -3
  45. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  46. package/dist/utils/tools-manager.d.ts +28 -1
  47. package/dist/utils/tools-manager.d.ts.map +1 -1
  48. package/dist/utils/tools-manager.js +68 -5
  49. package/dist/utils/tools-manager.js.map +1 -1
  50. package/dist/utils/version-check.d.ts +2 -0
  51. package/dist/utils/version-check.d.ts.map +1 -1
  52. package/dist/utils/version-check.js +2 -0
  53. package/dist/utils/version-check.js.map +1 -1
  54. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  55. package/npm-shrinkwrap.json +5 -5
  56. package/package.json +2 -2
@@ -1,4 +1,6 @@
1
- export declare function getToolPath(tool: "fd" | "rg"): string | null;
1
+ export declare function getToolPath(tool: "fd" | "rg", options?: {
2
+ toolsDirectory?: string;
3
+ }): string | null;
2
4
  export interface ManagedToolArtifact {
3
5
  version: string;
4
6
  url: string;
@@ -31,5 +33,30 @@ export interface InstallManagedToolArchiveOptions {
31
33
  * is written to `destination`.
32
34
  */
33
35
  export declare function installManagedToolArchive(options: InstallManagedToolArchiveOptions): Promise<string>;
36
+ export interface HostToolBinary {
37
+ /** File name the child looks for in its own tools directory ("fd", "rg", "fd.exe"). */
38
+ name: string;
39
+ /** Absolute host path to the executable backing that name. */
40
+ path: string;
41
+ }
42
+ /**
43
+ * Absolute host path for a managed tool, or undefined when it is installed nowhere.
44
+ *
45
+ * `getToolPath` may return a bare command name because its caller spawns through PATH.
46
+ * A sandboxed child has no such luxury: its PATH still lists host directories that the
47
+ * OS boundary has already replaced, so the supervisor must resolve a real path here and
48
+ * project it in (ADR 0017, and the sandbox spec's tool-projection amendment).
49
+ */
50
+ export declare function resolveHostToolBinary(tool: "fd" | "rg", options?: {
51
+ toolsDirectory?: string;
52
+ pathValue?: string;
53
+ platform?: NodeJS.Platform;
54
+ }): string | undefined;
55
+ /**
56
+ * Install any missing managed tool on the host, then report absolute paths for the ones
57
+ * that exist. Downloading here rather than inside the child means one install serves every
58
+ * workspace, and it happens on the side of the boundary that still has network access.
59
+ */
60
+ export declare function prepareHostToolBinaries(silent?: boolean): Promise<HostToolBinary[]>;
34
61
  export declare function ensureTool(tool: "fd" | "rg", silent?: boolean): Promise<string | undefined>;
35
62
  //# sourceMappingURL=tools-manager.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"tools-manager.d.ts","sourceRoot":"","sources":["../../src/utils/tools-manager.ts"],"names":[],"mappings":"AAqEA,wBAAgB,WAAW,CAAC,IAAI,EAAE,IAAI,GAAG,IAAI,GAAG,MAAM,GAAG,IAAI,CAmB5D;AA6GD,MAAM,WAAW,mBAAmB;IACnC,OAAO,EAAE,MAAM,CAAC;IAChB,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,EAAE,MAAM,CAAC;IACf,aAAa,EAAE,MAAM,CAAC;IACtB,kFAAkF;IAClF,QAAQ,EAAE,MAAM,CAAC;IACjB,UAAU,EAAE,MAAM,CAAC;IACnB,WAAW,EAAE,QAAQ,GAAG,KAAK,CAAC;CAC9B;AAED,oFAAoF;AACpF,wBAAgB,0BAA0B,CAAC,OAAO,EAAE;IACnD,IAAI,EAAE,IAAI,GAAG,IAAI,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC,QAAQ,GAAG,MAAM,CAAC;IACnC,YAAY,EAAE,MAAM,CAAC;CACrB,GAAG,mBAAmB,CAetB;AAmJD,MAAM,WAAW,gCAAgC;IAChD,WAAW,EAAE,MAAM,CAAC;IACpB,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,EAAE,MAAM,CAAC;IACnB,WAAW,EAAE,QAAQ,GAAG,KAAK,CAAC;IAC9B,cAAc,EAAE,MAAM,CAAC;IACvB,QAAQ,EAAE,MAAM,CAAC;CACjB;AAED;;;;;;GAMG;AACH,wBAAsB,yBAAyB,CAAC,OAAO,EAAE,gCAAgC,GAAG,OAAO,CAAC,MAAM,CAAC,CAiD1G;AA2CD,wBAAsB,UAAU,CAAC,IAAI,EAAE,IAAI,GAAG,IAAI,EAAE,MAAM,GAAE,OAAe,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CA2CxG","sourcesContent":["import chalk from \"chalk\";\nimport { type SpawnSyncReturns, spawnSync } from \"child_process\";\nimport { createHash } from \"crypto\";\nimport {\n\tchmodSync,\n\tcreateReadStream,\n\tcreateWriteStream,\n\texistsSync,\n\tmkdirSync,\n\treaddirSync,\n\trenameSync,\n\trmSync,\n\tstatSync,\n} from \"fs\";\nimport { arch, platform } from \"os\";\nimport { basename, join, relative, resolve as resolvePath } from \"path\";\nimport { Readable } from \"stream\";\nimport { pipeline } from \"stream/promises\";\nimport { getBinDir } from \"../config.ts\";\nimport { getApexEnvironment } from \"../core/environment.ts\";\nimport { fetchWithRetry } from \"./management-http.ts\";\n\nconst TOOLS_DIR = getBinDir();\nconst DOWNLOAD_TIMEOUT_MS = 120_000;\n\nfunction isOfflineModeEnabled(): boolean {\n\tconst value = getApexEnvironment(\"APEX_CODE_OFFLINE\");\n\tif (!value) return false;\n\treturn value === \"1\" || value.toLowerCase() === \"true\" || value.toLowerCase() === \"yes\";\n}\n\ninterface ToolConfig {\n\tname: string;\n\trepo: string; // GitHub repo (e.g., \"sharkdp/fd\")\n\tbinaryName: string; // Name of the binary inside the archive\n\tsystemBinaryNames?: string[]; // Alternative system command names to try before downloading\n\ttagPrefix: string; // Prefix for tags (e.g., \"v\" for v1.0.0, \"\" for 1.0.0)\n}\n\n// Per-platform/architecture asset names live in MANAGED_TOOL_PINS (ADR 0017) as the\n// single reviewed source of truth, not derived here.\nconst TOOLS: Record<string, ToolConfig> = {\n\tfd: {\n\t\tname: \"fd\",\n\t\trepo: \"sharkdp/fd\",\n\t\tbinaryName: \"fd\",\n\t\tsystemBinaryNames: [\"fd\", \"fdfind\"],\n\t\ttagPrefix: \"v\",\n\t},\n\trg: {\n\t\tname: \"ripgrep\",\n\t\trepo: \"BurntSushi/ripgrep\",\n\t\tbinaryName: \"rg\",\n\t\ttagPrefix: \"\",\n\t},\n};\n\n// Check if a command exists in PATH by trying to run it\nfunction commandExists(cmd: string): boolean {\n\ttry {\n\t\tconst result = spawnSync(cmd, [\"--version\"], { stdio: \"pipe\" });\n\t\t// Check for ENOENT error (command not found)\n\t\treturn result.error === undefined || result.error === null;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n// Get the path to a tool (system-wide or in our tools dir)\nexport function getToolPath(tool: \"fd\" | \"rg\"): string | null {\n\tconst config = TOOLS[tool];\n\tif (!config) return null;\n\n\t// Check our tools directory first\n\tconst localPath = join(TOOLS_DIR, config.binaryName + (platform() === \"win32\" ? \".exe\" : \"\"));\n\tif (existsSync(localPath)) {\n\t\treturn localPath;\n\t}\n\n\t// Check system PATH - if found, just return the command name (it's in PATH)\n\tconst systemBinaryNames = config.systemBinaryNames ?? [config.binaryName];\n\tfor (const systemBinaryName of systemBinaryNames) {\n\t\tif (commandExists(systemBinaryName)) {\n\t\t\treturn systemBinaryName;\n\t\t}\n\t}\n\n\treturn null;\n}\n\n/**\n * Reviewed, pinned release metadata for auto-downloaded executable tools (ADR 0017).\n * Never resolved from a mutable \"latest\" API call. Updating a version, asset name, or\n * digest here is itself the reviewed change that authorizes installing a new release.\n *\n * Every digest and byte size below was established by downloading the artifact,\n * computing its SHA-256 locally, and cross-checking that value against the\n * upstream-published digest (ripgrep's own `.sha256` release sidecars; GitHub's own\n * per-asset `digest` field for both projects) — not invented, and not taken from a\n * single unverified source.\n */\ninterface ManagedToolPin {\n\tversion: string;\n\tassetName: string;\n\tsha256: string;\n\texpectedBytes: number;\n\tarchiveKind: \"tar.gz\" | \"zip\";\n}\n\nconst MANAGED_TOOL_PINS: Record<\"fd\" | \"rg\", Partial<Record<string, ManagedToolPin>>> = {\n\trg: {\n\t\t\"linux:x64\": {\n\t\t\tversion: \"14.1.1\",\n\t\t\tassetName: \"ripgrep-14.1.1-x86_64-unknown-linux-musl.tar.gz\",\n\t\t\tsha256: \"4cf9f2741e6c465ffdb7c26f38056a59e2a2544b51f7cc128ef28337eeae4d8e\",\n\t\t\texpectedBytes: 2566310,\n\t\t\tarchiveKind: \"tar.gz\",\n\t\t},\n\t\t\"linux:arm64\": {\n\t\t\tversion: \"14.1.1\",\n\t\t\tassetName: \"ripgrep-14.1.1-aarch64-unknown-linux-gnu.tar.gz\",\n\t\t\tsha256: \"c827481c4ff4ea10c9dc7a4022c8de5db34a5737cb74484d62eb94a95841ab2f\",\n\t\t\texpectedBytes: 2047405,\n\t\t\tarchiveKind: \"tar.gz\",\n\t\t},\n\t\t\"darwin:x64\": {\n\t\t\tversion: \"14.1.1\",\n\t\t\tassetName: \"ripgrep-14.1.1-x86_64-apple-darwin.tar.gz\",\n\t\t\tsha256: \"fc87e78f7cb3fea12d69072e7ef3b21509754717b746368fd40d88963630e2b3\",\n\t\t\texpectedBytes: 2082672,\n\t\t\tarchiveKind: \"tar.gz\",\n\t\t},\n\t\t\"darwin:arm64\": {\n\t\t\tversion: \"14.1.1\",\n\t\t\tassetName: \"ripgrep-14.1.1-aarch64-apple-darwin.tar.gz\",\n\t\t\tsha256: \"24ad76777745fbff131c8fbc466742b011f925bfa4fffa2ded6def23b5b937be\",\n\t\t\texpectedBytes: 1787248,\n\t\t\tarchiveKind: \"tar.gz\",\n\t\t},\n\t\t\"win32:x64\": {\n\t\t\tversion: \"14.1.1\",\n\t\t\tassetName: \"ripgrep-14.1.1-x86_64-pc-windows-msvc.zip\",\n\t\t\tsha256: \"d0f534024c42afd6cb4d38907c25cd2b249b79bbe6cc1dbee8e3e37c2b6e25a1\",\n\t\t\texpectedBytes: 2058893,\n\t\t\tarchiveKind: \"zip\",\n\t\t},\n\t\t// No upstream win32/arm64 ripgrep release asset exists at 14.1.1; resolution\n\t\t// fails closed for that combination rather than constructing a URL that 404s.\n\t},\n\tfd: {\n\t\t\"linux:x64\": {\n\t\t\tversion: \"10.4.2\",\n\t\t\tassetName: \"fd-v10.4.2-x86_64-unknown-linux-gnu.tar.gz\",\n\t\t\tsha256: \"def59805cd14b5651b68990855f426ad087f3b96881296d963910431ba3143c8\",\n\t\t\texpectedBytes: 1700779,\n\t\t\tarchiveKind: \"tar.gz\",\n\t\t},\n\t\t\"linux:arm64\": {\n\t\t\tversion: \"10.4.2\",\n\t\t\tassetName: \"fd-v10.4.2-aarch64-unknown-linux-gnu.tar.gz\",\n\t\t\tsha256: \"6c51f7c5446b3338b1e401ff15dc194c590bb2fa64fd43ff3278300f073adec5\",\n\t\t\texpectedBytes: 1559490,\n\t\t\tarchiveKind: \"tar.gz\",\n\t\t},\n\t\t// Upstream stopped shipping an Intel macOS fd binary after 10.3.0 (see\n\t\t// 7afd80d78, \"pin fd for macos x64\"); preserved here rather than special-cased.\n\t\t\"darwin:x64\": {\n\t\t\tversion: \"10.3.0\",\n\t\t\tassetName: \"fd-v10.3.0-x86_64-apple-darwin.tar.gz\",\n\t\t\tsha256: \"50d30f13fe3d5914b14c4fff5abcbd4d0cdab4b855970a6956f4f006c17117a3\",\n\t\t\texpectedBytes: 1430203,\n\t\t\tarchiveKind: \"tar.gz\",\n\t\t},\n\t\t\"darwin:arm64\": {\n\t\t\tversion: \"10.4.2\",\n\t\t\tassetName: \"fd-v10.4.2-aarch64-apple-darwin.tar.gz\",\n\t\t\tsha256: \"623dc0afc81b92e4d4606b380d7bc91916ba7b97814263e554d50923a39e480a\",\n\t\t\texpectedBytes: 1328933,\n\t\t\tarchiveKind: \"tar.gz\",\n\t\t},\n\t\t\"win32:x64\": {\n\t\t\tversion: \"10.4.2\",\n\t\t\tassetName: \"fd-v10.4.2-x86_64-pc-windows-msvc.zip\",\n\t\t\tsha256: \"b2816e506390a89941c63c9187d58a3cc10e9a55f2ef0685f9ea0eccaf7c98c8\",\n\t\t\texpectedBytes: 1525898,\n\t\t\tarchiveKind: \"zip\",\n\t\t},\n\t\t\"win32:arm64\": {\n\t\t\tversion: \"10.4.2\",\n\t\t\tassetName: \"fd-v10.4.2-aarch64-pc-windows-msvc.zip\",\n\t\t\tsha256: \"4f9110c2d5b33a7f760bfa5510f4c113d828109f7277d421b1053a9943c0fc92\",\n\t\t\texpectedBytes: 1370473,\n\t\t\tarchiveKind: \"zip\",\n\t\t},\n\t},\n};\n\nexport interface ManagedToolArtifact {\n\tversion: string;\n\turl: string;\n\tsha256: string;\n\texpectedBytes: number;\n\t/** Bounded download ceiling (ADR 0017): four times the reviewed expected size. */\n\tmaxBytes: number;\n\tbinaryName: string;\n\tarchiveKind: \"tar.gz\" | \"zip\";\n}\n\n/** Resolve reviewed, pinned metadata for a managed tool. Never queries \"latest\". */\nexport function resolveManagedToolArtifact(options: {\n\ttool: \"fd\" | \"rg\";\n\tplatform: NodeJS.Platform | string;\n\tarchitecture: string;\n}): ManagedToolArtifact {\n\tconst config = TOOLS[options.tool];\n\tconst pin = MANAGED_TOOL_PINS[options.tool]?.[`${options.platform}:${options.architecture}`];\n\tif (!config || !pin) {\n\t\tthrow new Error(`No reviewed pinned artifact for ${options.tool} on ${options.platform}/${options.architecture}`);\n\t}\n\treturn {\n\t\tversion: pin.version,\n\t\turl: `https://github.com/${config.repo}/releases/download/${config.tagPrefix}${pin.version}/${pin.assetName}`,\n\t\tsha256: pin.sha256,\n\t\texpectedBytes: pin.expectedBytes,\n\t\tmaxBytes: pin.expectedBytes * 4,\n\t\tbinaryName: config.binaryName,\n\t\tarchiveKind: pin.archiveKind,\n\t};\n}\n\n// Download a file from URL, aborting if the declared or received size exceeds the\n// bounded ceiling (ADR 0017) rather than writing an unbounded stream to disk.\nasync function downloadFile(url: string, dest: string, maxBytes: number): Promise<void> {\n\tconst response = await fetchWithRetry(url, undefined, { timeoutMs: DOWNLOAD_TIMEOUT_MS });\n\n\tif (!response.ok) {\n\t\tthrow new Error(`Failed to download: ${response.status}`);\n\t}\n\n\tif (!response.body) {\n\t\tthrow new Error(\"No response body\");\n\t}\n\n\tconst declaredLength = Number(response.headers.get(\"content-length\") ?? Number.NaN);\n\tif (Number.isFinite(declaredLength) && declaredLength > maxBytes) {\n\t\tthrow new Error(`Refusing download: declared size ${declaredLength} exceeds bounded limit ${maxBytes}`);\n\t}\n\n\tlet received = 0;\n\tconst source = Readable.fromWeb(response.body as any);\n\tsource.on(\"data\", (chunk: Buffer) => {\n\t\treceived += chunk.length;\n\t\tif (received > maxBytes) {\n\t\t\tsource.destroy(new Error(`Refusing download: exceeded bounded limit ${maxBytes} bytes`));\n\t\t}\n\t});\n\n\tconst fileStream = createWriteStream(dest);\n\ttry {\n\t\tawait pipeline(source, fileStream);\n\t} catch (error) {\n\t\trmSync(dest, { force: true });\n\t\tthrow error;\n\t}\n}\n\nfunction findBinaryRecursively(rootDir: string, binaryFileName: string): string | null {\n\tconst stack: string[] = [rootDir];\n\n\twhile (stack.length > 0) {\n\t\tconst currentDir = stack.pop();\n\t\tif (!currentDir) continue;\n\n\t\tconst entries = readdirSync(currentDir, { withFileTypes: true });\n\t\tfor (const entry of entries) {\n\t\t\tconst fullPath = join(currentDir, entry.name);\n\t\t\tif (entry.isFile() && entry.name === binaryFileName) {\n\t\t\t\treturn fullPath;\n\t\t\t}\n\t\t\tif (entry.isDirectory()) {\n\t\t\t\tstack.push(fullPath);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn null;\n}\n\nfunction formatSpawnFailure(result: SpawnSyncReturns<Buffer>): string {\n\tif (result.error?.message) {\n\t\treturn result.error.message;\n\t}\n\tconst stderr = result.stderr?.toString().trim();\n\tif (stderr) {\n\t\treturn stderr;\n\t}\n\tconst stdout = result.stdout?.toString().trim();\n\tif (stdout) {\n\t\treturn stdout;\n\t}\n\treturn `exit status ${result.status ?? \"unknown\"}`;\n}\n\nfunction runExtractionCommand(command: string, args: string[]): string | null {\n\tconst result = spawnSync(command, args, { stdio: \"pipe\" });\n\tif (!result.error && result.status === 0) {\n\t\treturn null;\n\t}\n\treturn `${command}: ${formatSpawnFailure(result)}`;\n}\n\nfunction extractTarGzArchive(archivePath: string, extractDir: string, assetName: string): void {\n\tconst failure = runExtractionCommand(\"tar\", [\"xzf\", archivePath, \"-C\", extractDir]);\n\tif (failure) {\n\t\tthrow new Error(`Failed to extract ${assetName}: ${failure}`);\n\t}\n}\n\nfunction getWindowsTarCommand(): string {\n\tconst systemRoot = process.env.SystemRoot ?? process.env.WINDIR;\n\tif (systemRoot) {\n\t\tconst systemTar = join(systemRoot, \"System32\", \"tar.exe\");\n\t\tif (existsSync(systemTar)) {\n\t\t\treturn systemTar;\n\t\t}\n\t}\n\treturn \"tar.exe\";\n}\n\nfunction extractZipArchive(archivePath: string, extractDir: string, assetName: string): void {\n\tconst failures: string[] = [];\n\n\tif (platform() === \"win32\") {\n\t\t// Windows ships bsdtar as tar.exe, which supports zip files. Prefer the\n\t\t// System32 binary over Git Bash's GNU tar, which does not handle zip archives.\n\t\tconst tarFailure = runExtractionCommand(getWindowsTarCommand(), [\"xf\", archivePath, \"-C\", extractDir]);\n\t\tif (!tarFailure) return;\n\t\tfailures.push(tarFailure);\n\n\t\tconst script =\n\t\t\t\"& { param($archive, $destination) $ErrorActionPreference = 'Stop'; Expand-Archive -LiteralPath $archive -DestinationPath $destination -Force }\";\n\t\tconst powershellFailure = runExtractionCommand(\"powershell.exe\", [\n\t\t\t\"-NoLogo\",\n\t\t\t\"-NoProfile\",\n\t\t\t\"-NonInteractive\",\n\t\t\t\"-ExecutionPolicy\",\n\t\t\t\"Bypass\",\n\t\t\t\"-Command\",\n\t\t\tscript,\n\t\t\tarchivePath,\n\t\t\textractDir,\n\t\t]);\n\t\tif (!powershellFailure) return;\n\t\tfailures.push(powershellFailure);\n\t} else {\n\t\tconst unzipFailure = runExtractionCommand(\"unzip\", [\"-q\", archivePath, \"-d\", extractDir]);\n\t\tif (!unzipFailure) return;\n\t\tfailures.push(unzipFailure);\n\n\t\tconst tarFailure = runExtractionCommand(\"tar\", [\"xf\", archivePath, \"-C\", extractDir]);\n\t\tif (!tarFailure) return;\n\t\tfailures.push(tarFailure);\n\t}\n\n\tthrow new Error(`Failed to extract ${assetName}: ${failures.join(\"; \")}`);\n}\n\nasync function sha256File(path: string): Promise<string> {\n\tconst hash = createHash(\"sha256\");\n\tfor await (const chunk of createReadStream(path)) {\n\t\thash.update(chunk as Buffer);\n\t}\n\treturn hash.digest(\"hex\");\n}\n\nexport interface InstallManagedToolArchiveOptions {\n\tarchivePath: string;\n\tdestination: string;\n\tbinaryName: string;\n\tarchiveKind: \"tar.gz\" | \"zip\";\n\texpectedSha256: string;\n\tmaxBytes: number;\n}\n\n/**\n * Verify a downloaded tool archive against its pinned digest, extract it into a\n * per-install quarantine directory, confirm the located binary did not escape that\n * quarantine, and only then atomically promote it into the live tools directory\n * (ADR 0017). Rejects a digest mismatch or an out-of-bounds archive before anything\n * is written to `destination`.\n */\nexport async function installManagedToolArchive(options: InstallManagedToolArchiveOptions): Promise<string> {\n\tconst { archivePath, destination, binaryName, archiveKind, expectedSha256, maxBytes } = options;\n\n\tconst { size } = statSync(archivePath);\n\tif (size > maxBytes) {\n\t\tthrow new Error(`Refusing install: archive size ${size} exceeds bounded limit ${maxBytes}`);\n\t}\n\n\tconst actualSha256 = await sha256File(archivePath);\n\tif (actualSha256.toLowerCase() !== expectedSha256.toLowerCase()) {\n\t\tthrow new Error(`Refusing install: digest mismatch for ${basename(archivePath)}`);\n\t}\n\n\tmkdirSync(destination, { recursive: true });\n\tconst quarantineDirectory = join(\n\t\tdestination,\n\t\t`.quarantine_${process.pid}_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`,\n\t);\n\tmkdirSync(quarantineDirectory, { recursive: true });\n\n\ttry {\n\t\tconst assetName = basename(archivePath);\n\t\tif (archiveKind === \"tar.gz\") {\n\t\t\textractTarGzArchive(archivePath, quarantineDirectory, assetName);\n\t\t} else {\n\t\t\textractZipArchive(archivePath, quarantineDirectory, assetName);\n\t\t}\n\n\t\tconst binaryFileName = binaryName + (platform() === \"win32\" ? \".exe\" : \"\");\n\t\tconst extractedBinary = findBinaryRecursively(quarantineDirectory, binaryFileName);\n\t\tif (!extractedBinary) {\n\t\t\tthrow new Error(`Binary not found in verified archive: expected ${binaryFileName}`);\n\t\t}\n\n\t\tconst resolvedBinary = resolvePath(extractedBinary);\n\t\tconst containmentPath = relative(resolvePath(quarantineDirectory), resolvedBinary);\n\t\tif (containmentPath.startsWith(\"..\") || resolvePath(containmentPath) === containmentPath) {\n\t\t\tthrow new Error(`Refusing install: archive entry escaped its quarantine directory: ${extractedBinary}`);\n\t\t}\n\n\t\tconst finalPath = join(destination, binaryFileName);\n\t\trenameSync(resolvedBinary, finalPath);\n\t\tif (platform() !== \"win32\") {\n\t\t\tchmodSync(finalPath, 0o755);\n\t\t}\n\t\treturn finalPath;\n\t} finally {\n\t\trmSync(quarantineDirectory, { recursive: true, force: true });\n\t}\n}\n\n// Download and install a tool from reviewed, pinned metadata (ADR 0017): bounded\n// download, digest verification, quarantine extraction, then atomic promotion.\nasync function downloadTool(tool: \"fd\" | \"rg\"): Promise<string> {\n\tconst plat = platform();\n\tconst architecture = arch();\n\tconst artifact = resolveManagedToolArtifact({ tool, platform: plat, architecture });\n\n\tmkdirSync(TOOLS_DIR, { recursive: true });\n\n\t// Unique download filename: fd and rg downloads can run concurrently during\n\t// startup, so sharing a fixed path causes races.\n\tconst archivePath = join(\n\t\tTOOLS_DIR,\n\t\t`download_${artifact.binaryName}_${process.pid}_${Date.now()}_${Math.random().toString(36).slice(2, 10)}${\n\t\t\tartifact.archiveKind === \"zip\" ? \".zip\" : \".tar.gz\"\n\t\t}`,\n\t);\n\n\ttry {\n\t\tawait downloadFile(artifact.url, archivePath, artifact.maxBytes);\n\t\treturn await installManagedToolArchive({\n\t\t\tarchivePath,\n\t\t\tdestination: TOOLS_DIR,\n\t\t\tbinaryName: artifact.binaryName,\n\t\t\tarchiveKind: artifact.archiveKind,\n\t\t\texpectedSha256: artifact.sha256,\n\t\t\tmaxBytes: artifact.maxBytes,\n\t\t});\n\t} finally {\n\t\trmSync(archivePath, { force: true });\n\t}\n}\n\n// Termux package names for tools\nconst TERMUX_PACKAGES: Record<string, string> = {\n\tfd: \"fd\",\n\trg: \"ripgrep\",\n};\n\n// Ensure a tool is available, downloading if necessary\n// Returns the path to the tool, or null if unavailable\nexport async function ensureTool(tool: \"fd\" | \"rg\", silent: boolean = false): Promise<string | undefined> {\n\tconst existingPath = getToolPath(tool);\n\tif (existingPath) {\n\t\treturn existingPath;\n\t}\n\n\tconst config = TOOLS[tool];\n\tif (!config) return undefined;\n\n\tif (isOfflineModeEnabled()) {\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.yellow(`${config.name} not found. Offline mode enabled, skipping download.`));\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t// On Android/Termux, Linux binaries don't work due to Bionic libc incompatibility.\n\t// Users must install via pkg.\n\tif (platform() === \"android\") {\n\t\tconst pkgName = TERMUX_PACKAGES[tool] ?? tool;\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.yellow(`${config.name} not found. Install with: pkg install ${pkgName}`));\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t// Tool not found - download it\n\tif (!silent) {\n\t\tconsole.log(chalk.dim(`${config.name} not found. Downloading...`));\n\t}\n\n\ttry {\n\t\tconst path = await downloadTool(tool);\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.dim(`${config.name} installed to ${path}`));\n\t\t}\n\t\treturn path;\n\t} catch (e) {\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.yellow(`Failed to download ${config.name}: ${e instanceof Error ? e.message : e}`));\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AgB,qBAAqB,CACpC,IAAI,EAAE,IAAI,GAAG,IAAI,EACjB,OAAO,GAAE;IAAE,cAAc,CAAC,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,EAAE,MAAM,CAAC,QAAQ,CAAA;CAAO,GACvF,MAAM,GAAG,SAAS,CA0BpB;AAED;;;;GAIG;AACH,wBAAsB,uBAAuB,CAAC,MAAM,GAAE,OAAe,GAAG,OAAO,CAAC,cAAc,EAAE,CAAC,CAUhG;AAUD,wBAAsB,UAAU,CAAC,IAAI,EAAE,IAAI,GAAG,IAAI,EAAE,MAAM,GAAE,OAAe,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CA2CxG","sourcesContent":["import chalk from \"chalk\";\nimport { type SpawnSyncReturns, spawnSync } from \"child_process\";\nimport { createHash } from \"crypto\";\nimport {\n\tchmodSync,\n\tcreateReadStream,\n\tcreateWriteStream,\n\texistsSync,\n\tmkdirSync,\n\treaddirSync,\n\trenameSync,\n\trmSync,\n\tstatSync,\n} from \"fs\";\nimport { arch, platform } from \"os\";\nimport { basename, join, relative, resolve as resolvePath } from \"path\";\nimport { Readable } from \"stream\";\nimport { pipeline } from \"stream/promises\";\nimport { getBinDir } from \"../config.ts\";\nimport { getApexEnvironment } from \"../core/environment.ts\";\nimport { fetchWithRetry } from \"./management-http.ts\";\n\nconst TOOLS_DIR = getBinDir();\nconst DOWNLOAD_TIMEOUT_MS = 120_000;\n\nfunction isOfflineModeEnabled(): boolean {\n\tconst value = getApexEnvironment(\"APEX_CODE_OFFLINE\");\n\tif (!value) return false;\n\treturn value === \"1\" || value.toLowerCase() === \"true\" || value.toLowerCase() === \"yes\";\n}\n\ninterface ToolConfig {\n\tname: string;\n\trepo: string; // GitHub repo (e.g., \"sharkdp/fd\")\n\tbinaryName: string; // Name of the binary inside the archive\n\tsystemBinaryNames?: string[]; // Alternative system command names to try before downloading\n\ttagPrefix: string; // Prefix for tags (e.g., \"v\" for v1.0.0, \"\" for 1.0.0)\n}\n\n// Per-platform/architecture asset names live in MANAGED_TOOL_PINS (ADR 0017) as the\n// single reviewed source of truth, not derived here.\nconst TOOLS: Record<string, ToolConfig> = {\n\tfd: {\n\t\tname: \"fd\",\n\t\trepo: \"sharkdp/fd\",\n\t\tbinaryName: \"fd\",\n\t\tsystemBinaryNames: [\"fd\", \"fdfind\"],\n\t\ttagPrefix: \"v\",\n\t},\n\trg: {\n\t\tname: \"ripgrep\",\n\t\trepo: \"BurntSushi/ripgrep\",\n\t\tbinaryName: \"rg\",\n\t\ttagPrefix: \"\",\n\t},\n};\n\n// Check if a command exists in PATH by trying to run it\nfunction commandExists(cmd: string): boolean {\n\ttry {\n\t\tconst result = spawnSync(cmd, [\"--version\"], { stdio: \"pipe\" });\n\t\t// Check for ENOENT error (command not found)\n\t\treturn result.error === undefined || result.error === null;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n// Get the path to a tool (system-wide or in our tools dir)\nexport function getToolPath(tool: \"fd\" | \"rg\", options: { toolsDirectory?: string } = {}): string | null {\n\tconst config = TOOLS[tool];\n\tif (!config) return null;\n\n\t// Check our tools directory first. Existence alone is not enough: the sandbox\n\t// projects host tools by bind-mounting over a file here, and bwrap leaves that\n\t// mountpoint behind as an empty, non-executable stub once the namespace is gone.\n\tconst managedPath = join(\n\t\toptions.toolsDirectory ?? TOOLS_DIR,\n\t\tconfig.binaryName + (platform() === \"win32\" ? \".exe\" : \"\"),\n\t);\n\tif (isExecutableFile(managedPath, platform())) {\n\t\treturn managedPath;\n\t}\n\n\t// Check system PATH - if found, just return the command name (it's in PATH)\n\tconst systemBinaryNames = config.systemBinaryNames ?? [config.binaryName];\n\tfor (const systemBinaryName of systemBinaryNames) {\n\t\tif (commandExists(systemBinaryName)) {\n\t\t\treturn systemBinaryName;\n\t\t}\n\t}\n\n\treturn null;\n}\n\n/**\n * Reviewed, pinned release metadata for auto-downloaded executable tools (ADR 0017).\n * Never resolved from a mutable \"latest\" API call. Updating a version, asset name, or\n * digest here is itself the reviewed change that authorizes installing a new release.\n *\n * Every digest and byte size below was established by downloading the artifact,\n * computing its SHA-256 locally, and cross-checking that value against the\n * upstream-published digest (ripgrep's own `.sha256` release sidecars; GitHub's own\n * per-asset `digest` field for both projects) — not invented, and not taken from a\n * single unverified source.\n */\ninterface ManagedToolPin {\n\tversion: string;\n\tassetName: string;\n\tsha256: string;\n\texpectedBytes: number;\n\tarchiveKind: \"tar.gz\" | \"zip\";\n}\n\nconst MANAGED_TOOL_PINS: Record<\"fd\" | \"rg\", Partial<Record<string, ManagedToolPin>>> = {\n\trg: {\n\t\t\"linux:x64\": {\n\t\t\tversion: \"14.1.1\",\n\t\t\tassetName: \"ripgrep-14.1.1-x86_64-unknown-linux-musl.tar.gz\",\n\t\t\tsha256: \"4cf9f2741e6c465ffdb7c26f38056a59e2a2544b51f7cc128ef28337eeae4d8e\",\n\t\t\texpectedBytes: 2566310,\n\t\t\tarchiveKind: \"tar.gz\",\n\t\t},\n\t\t\"linux:arm64\": {\n\t\t\tversion: \"14.1.1\",\n\t\t\tassetName: \"ripgrep-14.1.1-aarch64-unknown-linux-gnu.tar.gz\",\n\t\t\tsha256: \"c827481c4ff4ea10c9dc7a4022c8de5db34a5737cb74484d62eb94a95841ab2f\",\n\t\t\texpectedBytes: 2047405,\n\t\t\tarchiveKind: \"tar.gz\",\n\t\t},\n\t\t\"darwin:x64\": {\n\t\t\tversion: \"14.1.1\",\n\t\t\tassetName: \"ripgrep-14.1.1-x86_64-apple-darwin.tar.gz\",\n\t\t\tsha256: \"fc87e78f7cb3fea12d69072e7ef3b21509754717b746368fd40d88963630e2b3\",\n\t\t\texpectedBytes: 2082672,\n\t\t\tarchiveKind: \"tar.gz\",\n\t\t},\n\t\t\"darwin:arm64\": {\n\t\t\tversion: \"14.1.1\",\n\t\t\tassetName: \"ripgrep-14.1.1-aarch64-apple-darwin.tar.gz\",\n\t\t\tsha256: \"24ad76777745fbff131c8fbc466742b011f925bfa4fffa2ded6def23b5b937be\",\n\t\t\texpectedBytes: 1787248,\n\t\t\tarchiveKind: \"tar.gz\",\n\t\t},\n\t\t\"win32:x64\": {\n\t\t\tversion: \"14.1.1\",\n\t\t\tassetName: \"ripgrep-14.1.1-x86_64-pc-windows-msvc.zip\",\n\t\t\tsha256: \"d0f534024c42afd6cb4d38907c25cd2b249b79bbe6cc1dbee8e3e37c2b6e25a1\",\n\t\t\texpectedBytes: 2058893,\n\t\t\tarchiveKind: \"zip\",\n\t\t},\n\t\t// No upstream win32/arm64 ripgrep release asset exists at 14.1.1; resolution\n\t\t// fails closed for that combination rather than constructing a URL that 404s.\n\t},\n\tfd: {\n\t\t\"linux:x64\": {\n\t\t\tversion: \"10.4.2\",\n\t\t\tassetName: \"fd-v10.4.2-x86_64-unknown-linux-gnu.tar.gz\",\n\t\t\tsha256: \"def59805cd14b5651b68990855f426ad087f3b96881296d963910431ba3143c8\",\n\t\t\texpectedBytes: 1700779,\n\t\t\tarchiveKind: \"tar.gz\",\n\t\t},\n\t\t\"linux:arm64\": {\n\t\t\tversion: \"10.4.2\",\n\t\t\tassetName: \"fd-v10.4.2-aarch64-unknown-linux-gnu.tar.gz\",\n\t\t\tsha256: \"6c51f7c5446b3338b1e401ff15dc194c590bb2fa64fd43ff3278300f073adec5\",\n\t\t\texpectedBytes: 1559490,\n\t\t\tarchiveKind: \"tar.gz\",\n\t\t},\n\t\t// Upstream stopped shipping an Intel macOS fd binary after 10.3.0 (see\n\t\t// 7afd80d78, \"pin fd for macos x64\"); preserved here rather than special-cased.\n\t\t\"darwin:x64\": {\n\t\t\tversion: \"10.3.0\",\n\t\t\tassetName: \"fd-v10.3.0-x86_64-apple-darwin.tar.gz\",\n\t\t\tsha256: \"50d30f13fe3d5914b14c4fff5abcbd4d0cdab4b855970a6956f4f006c17117a3\",\n\t\t\texpectedBytes: 1430203,\n\t\t\tarchiveKind: \"tar.gz\",\n\t\t},\n\t\t\"darwin:arm64\": {\n\t\t\tversion: \"10.4.2\",\n\t\t\tassetName: \"fd-v10.4.2-aarch64-apple-darwin.tar.gz\",\n\t\t\tsha256: \"623dc0afc81b92e4d4606b380d7bc91916ba7b97814263e554d50923a39e480a\",\n\t\t\texpectedBytes: 1328933,\n\t\t\tarchiveKind: \"tar.gz\",\n\t\t},\n\t\t\"win32:x64\": {\n\t\t\tversion: \"10.4.2\",\n\t\t\tassetName: \"fd-v10.4.2-x86_64-pc-windows-msvc.zip\",\n\t\t\tsha256: \"b2816e506390a89941c63c9187d58a3cc10e9a55f2ef0685f9ea0eccaf7c98c8\",\n\t\t\texpectedBytes: 1525898,\n\t\t\tarchiveKind: \"zip\",\n\t\t},\n\t\t\"win32:arm64\": {\n\t\t\tversion: \"10.4.2\",\n\t\t\tassetName: \"fd-v10.4.2-aarch64-pc-windows-msvc.zip\",\n\t\t\tsha256: \"4f9110c2d5b33a7f760bfa5510f4c113d828109f7277d421b1053a9943c0fc92\",\n\t\t\texpectedBytes: 1370473,\n\t\t\tarchiveKind: \"zip\",\n\t\t},\n\t},\n};\n\nexport interface ManagedToolArtifact {\n\tversion: string;\n\turl: string;\n\tsha256: string;\n\texpectedBytes: number;\n\t/** Bounded download ceiling (ADR 0017): four times the reviewed expected size. */\n\tmaxBytes: number;\n\tbinaryName: string;\n\tarchiveKind: \"tar.gz\" | \"zip\";\n}\n\n/** Resolve reviewed, pinned metadata for a managed tool. Never queries \"latest\". */\nexport function resolveManagedToolArtifact(options: {\n\ttool: \"fd\" | \"rg\";\n\tplatform: NodeJS.Platform | string;\n\tarchitecture: string;\n}): ManagedToolArtifact {\n\tconst config = TOOLS[options.tool];\n\tconst pin = MANAGED_TOOL_PINS[options.tool]?.[`${options.platform}:${options.architecture}`];\n\tif (!config || !pin) {\n\t\tthrow new Error(`No reviewed pinned artifact for ${options.tool} on ${options.platform}/${options.architecture}`);\n\t}\n\treturn {\n\t\tversion: pin.version,\n\t\turl: `https://github.com/${config.repo}/releases/download/${config.tagPrefix}${pin.version}/${pin.assetName}`,\n\t\tsha256: pin.sha256,\n\t\texpectedBytes: pin.expectedBytes,\n\t\tmaxBytes: pin.expectedBytes * 4,\n\t\tbinaryName: config.binaryName,\n\t\tarchiveKind: pin.archiveKind,\n\t};\n}\n\n// Download a file from URL, aborting if the declared or received size exceeds the\n// bounded ceiling (ADR 0017) rather than writing an unbounded stream to disk.\nasync function downloadFile(url: string, dest: string, maxBytes: number): Promise<void> {\n\tconst response = await fetchWithRetry(url, undefined, { timeoutMs: DOWNLOAD_TIMEOUT_MS });\n\n\tif (!response.ok) {\n\t\tthrow new Error(`Failed to download: ${response.status}`);\n\t}\n\n\tif (!response.body) {\n\t\tthrow new Error(\"No response body\");\n\t}\n\n\tconst declaredLength = Number(response.headers.get(\"content-length\") ?? Number.NaN);\n\tif (Number.isFinite(declaredLength) && declaredLength > maxBytes) {\n\t\tthrow new Error(`Refusing download: declared size ${declaredLength} exceeds bounded limit ${maxBytes}`);\n\t}\n\n\tlet received = 0;\n\tconst source = Readable.fromWeb(response.body as any);\n\tsource.on(\"data\", (chunk: Buffer) => {\n\t\treceived += chunk.length;\n\t\tif (received > maxBytes) {\n\t\t\tsource.destroy(new Error(`Refusing download: exceeded bounded limit ${maxBytes} bytes`));\n\t\t}\n\t});\n\n\tconst fileStream = createWriteStream(dest);\n\ttry {\n\t\tawait pipeline(source, fileStream);\n\t} catch (error) {\n\t\trmSync(dest, { force: true });\n\t\tthrow error;\n\t}\n}\n\nfunction findBinaryRecursively(rootDir: string, binaryFileName: string): string | null {\n\tconst stack: string[] = [rootDir];\n\n\twhile (stack.length > 0) {\n\t\tconst currentDir = stack.pop();\n\t\tif (!currentDir) continue;\n\n\t\tconst entries = readdirSync(currentDir, { withFileTypes: true });\n\t\tfor (const entry of entries) {\n\t\t\tconst fullPath = join(currentDir, entry.name);\n\t\t\tif (entry.isFile() && entry.name === binaryFileName) {\n\t\t\t\treturn fullPath;\n\t\t\t}\n\t\t\tif (entry.isDirectory()) {\n\t\t\t\tstack.push(fullPath);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn null;\n}\n\nfunction formatSpawnFailure(result: SpawnSyncReturns<Buffer>): string {\n\tif (result.error?.message) {\n\t\treturn result.error.message;\n\t}\n\tconst stderr = result.stderr?.toString().trim();\n\tif (stderr) {\n\t\treturn stderr;\n\t}\n\tconst stdout = result.stdout?.toString().trim();\n\tif (stdout) {\n\t\treturn stdout;\n\t}\n\treturn `exit status ${result.status ?? \"unknown\"}`;\n}\n\nfunction runExtractionCommand(command: string, args: string[]): string | null {\n\tconst result = spawnSync(command, args, { stdio: \"pipe\" });\n\tif (!result.error && result.status === 0) {\n\t\treturn null;\n\t}\n\treturn `${command}: ${formatSpawnFailure(result)}`;\n}\n\nfunction extractTarGzArchive(archivePath: string, extractDir: string, assetName: string): void {\n\tconst failure = runExtractionCommand(\"tar\", [\"xzf\", archivePath, \"-C\", extractDir]);\n\tif (failure) {\n\t\tthrow new Error(`Failed to extract ${assetName}: ${failure}`);\n\t}\n}\n\nfunction getWindowsTarCommand(): string {\n\tconst systemRoot = process.env.SystemRoot ?? process.env.WINDIR;\n\tif (systemRoot) {\n\t\tconst systemTar = join(systemRoot, \"System32\", \"tar.exe\");\n\t\tif (existsSync(systemTar)) {\n\t\t\treturn systemTar;\n\t\t}\n\t}\n\treturn \"tar.exe\";\n}\n\nfunction extractZipArchive(archivePath: string, extractDir: string, assetName: string): void {\n\tconst failures: string[] = [];\n\n\tif (platform() === \"win32\") {\n\t\t// Windows ships bsdtar as tar.exe, which supports zip files. Prefer the\n\t\t// System32 binary over Git Bash's GNU tar, which does not handle zip archives.\n\t\tconst tarFailure = runExtractionCommand(getWindowsTarCommand(), [\"xf\", archivePath, \"-C\", extractDir]);\n\t\tif (!tarFailure) return;\n\t\tfailures.push(tarFailure);\n\n\t\tconst script =\n\t\t\t\"& { param($archive, $destination) $ErrorActionPreference = 'Stop'; Expand-Archive -LiteralPath $archive -DestinationPath $destination -Force }\";\n\t\tconst powershellFailure = runExtractionCommand(\"powershell.exe\", [\n\t\t\t\"-NoLogo\",\n\t\t\t\"-NoProfile\",\n\t\t\t\"-NonInteractive\",\n\t\t\t\"-ExecutionPolicy\",\n\t\t\t\"Bypass\",\n\t\t\t\"-Command\",\n\t\t\tscript,\n\t\t\tarchivePath,\n\t\t\textractDir,\n\t\t]);\n\t\tif (!powershellFailure) return;\n\t\tfailures.push(powershellFailure);\n\t} else {\n\t\tconst unzipFailure = runExtractionCommand(\"unzip\", [\"-q\", archivePath, \"-d\", extractDir]);\n\t\tif (!unzipFailure) return;\n\t\tfailures.push(unzipFailure);\n\n\t\tconst tarFailure = runExtractionCommand(\"tar\", [\"xf\", archivePath, \"-C\", extractDir]);\n\t\tif (!tarFailure) return;\n\t\tfailures.push(tarFailure);\n\t}\n\n\tthrow new Error(`Failed to extract ${assetName}: ${failures.join(\"; \")}`);\n}\n\nasync function sha256File(path: string): Promise<string> {\n\tconst hash = createHash(\"sha256\");\n\tfor await (const chunk of createReadStream(path)) {\n\t\thash.update(chunk as Buffer);\n\t}\n\treturn hash.digest(\"hex\");\n}\n\nexport interface InstallManagedToolArchiveOptions {\n\tarchivePath: string;\n\tdestination: string;\n\tbinaryName: string;\n\tarchiveKind: \"tar.gz\" | \"zip\";\n\texpectedSha256: string;\n\tmaxBytes: number;\n}\n\n/**\n * Verify a downloaded tool archive against its pinned digest, extract it into a\n * per-install quarantine directory, confirm the located binary did not escape that\n * quarantine, and only then atomically promote it into the live tools directory\n * (ADR 0017). Rejects a digest mismatch or an out-of-bounds archive before anything\n * is written to `destination`.\n */\nexport async function installManagedToolArchive(options: InstallManagedToolArchiveOptions): Promise<string> {\n\tconst { archivePath, destination, binaryName, archiveKind, expectedSha256, maxBytes } = options;\n\n\tconst { size } = statSync(archivePath);\n\tif (size > maxBytes) {\n\t\tthrow new Error(`Refusing install: archive size ${size} exceeds bounded limit ${maxBytes}`);\n\t}\n\n\tconst actualSha256 = await sha256File(archivePath);\n\tif (actualSha256.toLowerCase() !== expectedSha256.toLowerCase()) {\n\t\tthrow new Error(`Refusing install: digest mismatch for ${basename(archivePath)}`);\n\t}\n\n\tmkdirSync(destination, { recursive: true });\n\tconst quarantineDirectory = join(\n\t\tdestination,\n\t\t`.quarantine_${process.pid}_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`,\n\t);\n\tmkdirSync(quarantineDirectory, { recursive: true });\n\n\ttry {\n\t\tconst assetName = basename(archivePath);\n\t\tif (archiveKind === \"tar.gz\") {\n\t\t\textractTarGzArchive(archivePath, quarantineDirectory, assetName);\n\t\t} else {\n\t\t\textractZipArchive(archivePath, quarantineDirectory, assetName);\n\t\t}\n\n\t\tconst binaryFileName = binaryName + (platform() === \"win32\" ? \".exe\" : \"\");\n\t\tconst extractedBinary = findBinaryRecursively(quarantineDirectory, binaryFileName);\n\t\tif (!extractedBinary) {\n\t\t\tthrow new Error(`Binary not found in verified archive: expected ${binaryFileName}`);\n\t\t}\n\n\t\tconst resolvedBinary = resolvePath(extractedBinary);\n\t\tconst containmentPath = relative(resolvePath(quarantineDirectory), resolvedBinary);\n\t\tif (containmentPath.startsWith(\"..\") || resolvePath(containmentPath) === containmentPath) {\n\t\t\tthrow new Error(`Refusing install: archive entry escaped its quarantine directory: ${extractedBinary}`);\n\t\t}\n\n\t\tconst finalPath = join(destination, binaryFileName);\n\t\trenameSync(resolvedBinary, finalPath);\n\t\tif (platform() !== \"win32\") {\n\t\t\tchmodSync(finalPath, 0o755);\n\t\t}\n\t\treturn finalPath;\n\t} finally {\n\t\trmSync(quarantineDirectory, { recursive: true, force: true });\n\t}\n}\n\n// Download and install a tool from reviewed, pinned metadata (ADR 0017): bounded\n// download, digest verification, quarantine extraction, then atomic promotion.\nasync function downloadTool(tool: \"fd\" | \"rg\"): Promise<string> {\n\tconst plat = platform();\n\tconst architecture = arch();\n\tconst artifact = resolveManagedToolArtifact({ tool, platform: plat, architecture });\n\n\tmkdirSync(TOOLS_DIR, { recursive: true });\n\n\t// Unique download filename: fd and rg downloads can run concurrently during\n\t// startup, so sharing a fixed path causes races.\n\tconst archivePath = join(\n\t\tTOOLS_DIR,\n\t\t`download_${artifact.binaryName}_${process.pid}_${Date.now()}_${Math.random().toString(36).slice(2, 10)}${\n\t\t\tartifact.archiveKind === \"zip\" ? \".zip\" : \".tar.gz\"\n\t\t}`,\n\t);\n\n\ttry {\n\t\tawait downloadFile(artifact.url, archivePath, artifact.maxBytes);\n\t\treturn await installManagedToolArchive({\n\t\t\tarchivePath,\n\t\t\tdestination: TOOLS_DIR,\n\t\t\tbinaryName: artifact.binaryName,\n\t\t\tarchiveKind: artifact.archiveKind,\n\t\t\texpectedSha256: artifact.sha256,\n\t\t\tmaxBytes: artifact.maxBytes,\n\t\t});\n\t} finally {\n\t\trmSync(archivePath, { force: true });\n\t}\n}\n\nexport interface HostToolBinary {\n\t/** File name the child looks for in its own tools directory (\"fd\", \"rg\", \"fd.exe\"). */\n\tname: string;\n\t/** Absolute host path to the executable backing that name. */\n\tpath: string;\n}\n\nfunction isExecutableFile(candidate: string, targetPlatform: NodeJS.Platform): boolean {\n\ttry {\n\t\tconst stats = statSync(candidate);\n\t\tif (!stats.isFile()) return false;\n\t\t// Windows has no POSIX execute bit; presence of the file is the only signal.\n\t\treturn targetPlatform === \"win32\" || (stats.mode & 0o111) !== 0;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/**\n * Absolute host path for a managed tool, or undefined when it is installed nowhere.\n *\n * `getToolPath` may return a bare command name because its caller spawns through PATH.\n * A sandboxed child has no such luxury: its PATH still lists host directories that the\n * OS boundary has already replaced, so the supervisor must resolve a real path here and\n * project it in (ADR 0017, and the sandbox spec's tool-projection amendment).\n */\nexport function resolveHostToolBinary(\n\ttool: \"fd\" | \"rg\",\n\toptions: { toolsDirectory?: string; pathValue?: string; platform?: NodeJS.Platform } = {},\n): string | undefined {\n\tconst config = TOOLS[tool];\n\tif (!config) return undefined;\n\n\tconst targetPlatform = options.platform ?? platform();\n\tconst executableSuffix = targetPlatform === \"win32\" ? \".exe\" : \"\";\n\tconst managedPath = join(options.toolsDirectory ?? TOOLS_DIR, config.binaryName + executableSuffix);\n\tif (isExecutableFile(managedPath, targetPlatform)) {\n\t\treturn managedPath;\n\t}\n\n\tconst pathEntries = (options.pathValue ?? process.env.PATH ?? \"\")\n\t\t.split(targetPlatform === \"win32\" ? \";\" : \":\")\n\t\t.filter((entry) => entry.length > 0);\n\t// Preference runs by name first, matching getToolPath: a real `fd` anywhere on PATH\n\t// beats a `fdfind` alias, rather than whichever directory happens to come first.\n\tfor (const systemBinaryName of config.systemBinaryNames ?? [config.binaryName]) {\n\t\tfor (const entry of pathEntries) {\n\t\t\tconst candidate = join(entry, systemBinaryName + executableSuffix);\n\t\t\tif (isExecutableFile(candidate, targetPlatform)) {\n\t\t\t\treturn candidate;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn undefined;\n}\n\n/**\n * Install any missing managed tool on the host, then report absolute paths for the ones\n * that exist. Downloading here rather than inside the child means one install serves every\n * workspace, and it happens on the side of the boundary that still has network access.\n */\nexport async function prepareHostToolBinaries(silent: boolean = false): Promise<HostToolBinary[]> {\n\tconst binaries: HostToolBinary[] = [];\n\tfor (const tool of [\"fd\", \"rg\"] as const) {\n\t\tawait ensureTool(tool, silent);\n\t\tconst hostPath = resolveHostToolBinary(tool);\n\t\tif (hostPath) {\n\t\t\tbinaries.push({ name: TOOLS[tool].binaryName + (platform() === \"win32\" ? \".exe\" : \"\"), path: hostPath });\n\t\t}\n\t}\n\treturn binaries;\n}\n\n// Termux package names for tools\nconst TERMUX_PACKAGES: Record<string, string> = {\n\tfd: \"fd\",\n\trg: \"ripgrep\",\n};\n\n// Ensure a tool is available, downloading if necessary\n// Returns the path to the tool, or null if unavailable\nexport async function ensureTool(tool: \"fd\" | \"rg\", silent: boolean = false): Promise<string | undefined> {\n\tconst existingPath = getToolPath(tool);\n\tif (existingPath) {\n\t\treturn existingPath;\n\t}\n\n\tconst config = TOOLS[tool];\n\tif (!config) return undefined;\n\n\tif (isOfflineModeEnabled()) {\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.yellow(`${config.name} not found. Offline mode enabled, skipping download.`));\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t// On Android/Termux, Linux binaries don't work due to Bionic libc incompatibility.\n\t// Users must install via pkg.\n\tif (platform() === \"android\") {\n\t\tconst pkgName = TERMUX_PACKAGES[tool] ?? tool;\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.yellow(`${config.name} not found. Install with: pkg install ${pkgName}`));\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t// Tool not found - download it\n\tif (!silent) {\n\t\tconsole.log(chalk.dim(`${config.name} not found. Downloading...`));\n\t}\n\n\ttry {\n\t\tconst path = await downloadTool(tool);\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.dim(`${config.name} installed to ${path}`));\n\t\t}\n\t\treturn path;\n\t} catch (e) {\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.yellow(`Failed to download ${config.name}: ${e instanceof Error ? e.message : e}`));\n\t\t}\n\t\treturn undefined;\n\t}\n}\n"]}
@@ -46,14 +46,16 @@ function commandExists(cmd) {
46
46
  }
47
47
  }
48
48
  // Get the path to a tool (system-wide or in our tools dir)
49
- export function getToolPath(tool) {
49
+ export function getToolPath(tool, options = {}) {
50
50
  const config = TOOLS[tool];
51
51
  if (!config)
52
52
  return null;
53
- // Check our tools directory first
54
- const localPath = join(TOOLS_DIR, config.binaryName + (platform() === "win32" ? ".exe" : ""));
55
- if (existsSync(localPath)) {
56
- return localPath;
53
+ // Check our tools directory first. Existence alone is not enough: the sandbox
54
+ // projects host tools by bind-mounting over a file here, and bwrap leaves that
55
+ // mountpoint behind as an empty, non-executable stub once the namespace is gone.
56
+ const managedPath = join(options.toolsDirectory ?? TOOLS_DIR, config.binaryName + (platform() === "win32" ? ".exe" : ""));
57
+ if (isExecutableFile(managedPath, platform())) {
58
+ return managedPath;
57
59
  }
58
60
  // Check system PATH - if found, just return the command name (it's in PATH)
59
61
  const systemBinaryNames = config.systemBinaryNames ?? [config.binaryName];
@@ -373,6 +375,67 @@ async function downloadTool(tool) {
373
375
  rmSync(archivePath, { force: true });
374
376
  }
375
377
  }
378
+ function isExecutableFile(candidate, targetPlatform) {
379
+ try {
380
+ const stats = statSync(candidate);
381
+ if (!stats.isFile())
382
+ return false;
383
+ // Windows has no POSIX execute bit; presence of the file is the only signal.
384
+ return targetPlatform === "win32" || (stats.mode & 0o111) !== 0;
385
+ }
386
+ catch {
387
+ return false;
388
+ }
389
+ }
390
+ /**
391
+ * Absolute host path for a managed tool, or undefined when it is installed nowhere.
392
+ *
393
+ * `getToolPath` may return a bare command name because its caller spawns through PATH.
394
+ * A sandboxed child has no such luxury: its PATH still lists host directories that the
395
+ * OS boundary has already replaced, so the supervisor must resolve a real path here and
396
+ * project it in (ADR 0017, and the sandbox spec's tool-projection amendment).
397
+ */
398
+ export function resolveHostToolBinary(tool, options = {}) {
399
+ const config = TOOLS[tool];
400
+ if (!config)
401
+ return undefined;
402
+ const targetPlatform = options.platform ?? platform();
403
+ const executableSuffix = targetPlatform === "win32" ? ".exe" : "";
404
+ const managedPath = join(options.toolsDirectory ?? TOOLS_DIR, config.binaryName + executableSuffix);
405
+ if (isExecutableFile(managedPath, targetPlatform)) {
406
+ return managedPath;
407
+ }
408
+ const pathEntries = (options.pathValue ?? process.env.PATH ?? "")
409
+ .split(targetPlatform === "win32" ? ";" : ":")
410
+ .filter((entry) => entry.length > 0);
411
+ // Preference runs by name first, matching getToolPath: a real `fd` anywhere on PATH
412
+ // beats a `fdfind` alias, rather than whichever directory happens to come first.
413
+ for (const systemBinaryName of config.systemBinaryNames ?? [config.binaryName]) {
414
+ for (const entry of pathEntries) {
415
+ const candidate = join(entry, systemBinaryName + executableSuffix);
416
+ if (isExecutableFile(candidate, targetPlatform)) {
417
+ return candidate;
418
+ }
419
+ }
420
+ }
421
+ return undefined;
422
+ }
423
+ /**
424
+ * Install any missing managed tool on the host, then report absolute paths for the ones
425
+ * that exist. Downloading here rather than inside the child means one install serves every
426
+ * workspace, and it happens on the side of the boundary that still has network access.
427
+ */
428
+ export async function prepareHostToolBinaries(silent = false) {
429
+ const binaries = [];
430
+ for (const tool of ["fd", "rg"]) {
431
+ await ensureTool(tool, silent);
432
+ const hostPath = resolveHostToolBinary(tool);
433
+ if (hostPath) {
434
+ binaries.push({ name: TOOLS[tool].binaryName + (platform() === "win32" ? ".exe" : ""), path: hostPath });
435
+ }
436
+ }
437
+ return binaries;
438
+ }
376
439
  // Termux package names for tools
377
440
  const TERMUX_PACKAGES = {
378
441
  fd: "fd",
@@ -1 +1 @@
1
- {"version":3,"file":"tools-manager.js","sourceRoot":"","sources":["../../src/utils/tools-manager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAyB,SAAS,EAAE,MAAM,eAAe,CAAC;AACjE,OAAO,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AACpC,OAAO,EACN,SAAS,EACT,gBAAgB,EAChB,iBAAiB,EACjB,UAAU,EACV,SAAS,EACT,WAAW,EACX,UAAU,EACV,MAAM,EACN,QAAQ,GACR,MAAM,IAAI,CAAC;AACZ,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,IAAI,CAAC;AACpC,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,IAAI,WAAW,EAAE,MAAM,MAAM,CAAC;AACxE,OAAO,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAC;AAClC,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAC5D,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAEtD,MAAM,SAAS,GAAG,SAAS,EAAE,CAAC;AAC9B,MAAM,mBAAmB,GAAG,OAAO,CAAC;AAEpC,SAAS,oBAAoB,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C,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;QACvG,CAAC;QACD,OAAO,SAAS,CAAC;IAClB,CAAC;AAAA,CACD","sourcesContent":["import chalk from \"chalk\";\nimport { type SpawnSyncReturns, spawnSync } from \"child_process\";\nimport { createHash } from \"crypto\";\nimport {\n\tchmodSync,\n\tcreateReadStream,\n\tcreateWriteStream,\n\texistsSync,\n\tmkdirSync,\n\treaddirSync,\n\trenameSync,\n\trmSync,\n\tstatSync,\n} from \"fs\";\nimport { arch, platform } from \"os\";\nimport { basename, join, relative, resolve as resolvePath } from \"path\";\nimport { Readable } from \"stream\";\nimport { pipeline } from \"stream/promises\";\nimport { getBinDir } from \"../config.ts\";\nimport { getApexEnvironment } from \"../core/environment.ts\";\nimport { fetchWithRetry } from \"./management-http.ts\";\n\nconst TOOLS_DIR = getBinDir();\nconst DOWNLOAD_TIMEOUT_MS = 120_000;\n\nfunction isOfflineModeEnabled(): boolean {\n\tconst value = getApexEnvironment(\"APEX_CODE_OFFLINE\");\n\tif (!value) return false;\n\treturn value === \"1\" || value.toLowerCase() === \"true\" || value.toLowerCase() === \"yes\";\n}\n\ninterface ToolConfig {\n\tname: string;\n\trepo: string; // GitHub repo (e.g., \"sharkdp/fd\")\n\tbinaryName: string; // Name of the binary inside the archive\n\tsystemBinaryNames?: string[]; // Alternative system command names to try before downloading\n\ttagPrefix: string; // Prefix for tags (e.g., \"v\" for v1.0.0, \"\" for 1.0.0)\n}\n\n// Per-platform/architecture asset names live in MANAGED_TOOL_PINS (ADR 0017) as the\n// single reviewed source of truth, not derived here.\nconst TOOLS: Record<string, ToolConfig> = {\n\tfd: {\n\t\tname: \"fd\",\n\t\trepo: \"sharkdp/fd\",\n\t\tbinaryName: \"fd\",\n\t\tsystemBinaryNames: [\"fd\", \"fdfind\"],\n\t\ttagPrefix: \"v\",\n\t},\n\trg: {\n\t\tname: \"ripgrep\",\n\t\trepo: \"BurntSushi/ripgrep\",\n\t\tbinaryName: \"rg\",\n\t\ttagPrefix: \"\",\n\t},\n};\n\n// Check if a command exists in PATH by trying to run it\nfunction commandExists(cmd: string): boolean {\n\ttry {\n\t\tconst result = spawnSync(cmd, [\"--version\"], { stdio: \"pipe\" });\n\t\t// Check for ENOENT error (command not found)\n\t\treturn result.error === undefined || result.error === null;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n// Get the path to a tool (system-wide or in our tools dir)\nexport function getToolPath(tool: \"fd\" | \"rg\"): string | null {\n\tconst config = TOOLS[tool];\n\tif (!config) return null;\n\n\t// Check our tools directory first\n\tconst localPath = join(TOOLS_DIR, config.binaryName + (platform() === \"win32\" ? \".exe\" : \"\"));\n\tif (existsSync(localPath)) {\n\t\treturn localPath;\n\t}\n\n\t// Check system PATH - if found, just return the command name (it's in PATH)\n\tconst systemBinaryNames = config.systemBinaryNames ?? [config.binaryName];\n\tfor (const systemBinaryName of systemBinaryNames) {\n\t\tif (commandExists(systemBinaryName)) {\n\t\t\treturn systemBinaryName;\n\t\t}\n\t}\n\n\treturn null;\n}\n\n/**\n * Reviewed, pinned release metadata for auto-downloaded executable tools (ADR 0017).\n * Never resolved from a mutable \"latest\" API call. Updating a version, asset name, or\n * digest here is itself the reviewed change that authorizes installing a new release.\n *\n * Every digest and byte size below was established by downloading the artifact,\n * computing its SHA-256 locally, and cross-checking that value against the\n * upstream-published digest (ripgrep's own `.sha256` release sidecars; GitHub's own\n * per-asset `digest` field for both projects) — not invented, and not taken from a\n * single unverified source.\n */\ninterface ManagedToolPin {\n\tversion: string;\n\tassetName: string;\n\tsha256: string;\n\texpectedBytes: number;\n\tarchiveKind: \"tar.gz\" | \"zip\";\n}\n\nconst MANAGED_TOOL_PINS: Record<\"fd\" | \"rg\", Partial<Record<string, ManagedToolPin>>> = {\n\trg: {\n\t\t\"linux:x64\": {\n\t\t\tversion: \"14.1.1\",\n\t\t\tassetName: \"ripgrep-14.1.1-x86_64-unknown-linux-musl.tar.gz\",\n\t\t\tsha256: \"4cf9f2741e6c465ffdb7c26f38056a59e2a2544b51f7cc128ef28337eeae4d8e\",\n\t\t\texpectedBytes: 2566310,\n\t\t\tarchiveKind: \"tar.gz\",\n\t\t},\n\t\t\"linux:arm64\": {\n\t\t\tversion: \"14.1.1\",\n\t\t\tassetName: \"ripgrep-14.1.1-aarch64-unknown-linux-gnu.tar.gz\",\n\t\t\tsha256: \"c827481c4ff4ea10c9dc7a4022c8de5db34a5737cb74484d62eb94a95841ab2f\",\n\t\t\texpectedBytes: 2047405,\n\t\t\tarchiveKind: \"tar.gz\",\n\t\t},\n\t\t\"darwin:x64\": {\n\t\t\tversion: \"14.1.1\",\n\t\t\tassetName: \"ripgrep-14.1.1-x86_64-apple-darwin.tar.gz\",\n\t\t\tsha256: \"fc87e78f7cb3fea12d69072e7ef3b21509754717b746368fd40d88963630e2b3\",\n\t\t\texpectedBytes: 2082672,\n\t\t\tarchiveKind: \"tar.gz\",\n\t\t},\n\t\t\"darwin:arm64\": {\n\t\t\tversion: \"14.1.1\",\n\t\t\tassetName: \"ripgrep-14.1.1-aarch64-apple-darwin.tar.gz\",\n\t\t\tsha256: \"24ad76777745fbff131c8fbc466742b011f925bfa4fffa2ded6def23b5b937be\",\n\t\t\texpectedBytes: 1787248,\n\t\t\tarchiveKind: \"tar.gz\",\n\t\t},\n\t\t\"win32:x64\": {\n\t\t\tversion: \"14.1.1\",\n\t\t\tassetName: \"ripgrep-14.1.1-x86_64-pc-windows-msvc.zip\",\n\t\t\tsha256: \"d0f534024c42afd6cb4d38907c25cd2b249b79bbe6cc1dbee8e3e37c2b6e25a1\",\n\t\t\texpectedBytes: 2058893,\n\t\t\tarchiveKind: \"zip\",\n\t\t},\n\t\t// No upstream win32/arm64 ripgrep release asset exists at 14.1.1; resolution\n\t\t// fails closed for that combination rather than constructing a URL that 404s.\n\t},\n\tfd: {\n\t\t\"linux:x64\": {\n\t\t\tversion: \"10.4.2\",\n\t\t\tassetName: \"fd-v10.4.2-x86_64-unknown-linux-gnu.tar.gz\",\n\t\t\tsha256: \"def59805cd14b5651b68990855f426ad087f3b96881296d963910431ba3143c8\",\n\t\t\texpectedBytes: 1700779,\n\t\t\tarchiveKind: \"tar.gz\",\n\t\t},\n\t\t\"linux:arm64\": {\n\t\t\tversion: \"10.4.2\",\n\t\t\tassetName: \"fd-v10.4.2-aarch64-unknown-linux-gnu.tar.gz\",\n\t\t\tsha256: \"6c51f7c5446b3338b1e401ff15dc194c590bb2fa64fd43ff3278300f073adec5\",\n\t\t\texpectedBytes: 1559490,\n\t\t\tarchiveKind: \"tar.gz\",\n\t\t},\n\t\t// Upstream stopped shipping an Intel macOS fd binary after 10.3.0 (see\n\t\t// 7afd80d78, \"pin fd for macos x64\"); preserved here rather than special-cased.\n\t\t\"darwin:x64\": {\n\t\t\tversion: \"10.3.0\",\n\t\t\tassetName: \"fd-v10.3.0-x86_64-apple-darwin.tar.gz\",\n\t\t\tsha256: \"50d30f13fe3d5914b14c4fff5abcbd4d0cdab4b855970a6956f4f006c17117a3\",\n\t\t\texpectedBytes: 1430203,\n\t\t\tarchiveKind: \"tar.gz\",\n\t\t},\n\t\t\"darwin:arm64\": {\n\t\t\tversion: \"10.4.2\",\n\t\t\tassetName: \"fd-v10.4.2-aarch64-apple-darwin.tar.gz\",\n\t\t\tsha256: \"623dc0afc81b92e4d4606b380d7bc91916ba7b97814263e554d50923a39e480a\",\n\t\t\texpectedBytes: 1328933,\n\t\t\tarchiveKind: \"tar.gz\",\n\t\t},\n\t\t\"win32:x64\": {\n\t\t\tversion: \"10.4.2\",\n\t\t\tassetName: \"fd-v10.4.2-x86_64-pc-windows-msvc.zip\",\n\t\t\tsha256: \"b2816e506390a89941c63c9187d58a3cc10e9a55f2ef0685f9ea0eccaf7c98c8\",\n\t\t\texpectedBytes: 1525898,\n\t\t\tarchiveKind: \"zip\",\n\t\t},\n\t\t\"win32:arm64\": {\n\t\t\tversion: \"10.4.2\",\n\t\t\tassetName: \"fd-v10.4.2-aarch64-pc-windows-msvc.zip\",\n\t\t\tsha256: \"4f9110c2d5b33a7f760bfa5510f4c113d828109f7277d421b1053a9943c0fc92\",\n\t\t\texpectedBytes: 1370473,\n\t\t\tarchiveKind: \"zip\",\n\t\t},\n\t},\n};\n\nexport interface ManagedToolArtifact {\n\tversion: string;\n\turl: string;\n\tsha256: string;\n\texpectedBytes: number;\n\t/** Bounded download ceiling (ADR 0017): four times the reviewed expected size. */\n\tmaxBytes: number;\n\tbinaryName: string;\n\tarchiveKind: \"tar.gz\" | \"zip\";\n}\n\n/** Resolve reviewed, pinned metadata for a managed tool. Never queries \"latest\". */\nexport function resolveManagedToolArtifact(options: {\n\ttool: \"fd\" | \"rg\";\n\tplatform: NodeJS.Platform | string;\n\tarchitecture: string;\n}): ManagedToolArtifact {\n\tconst config = TOOLS[options.tool];\n\tconst pin = MANAGED_TOOL_PINS[options.tool]?.[`${options.platform}:${options.architecture}`];\n\tif (!config || !pin) {\n\t\tthrow new Error(`No reviewed pinned artifact for ${options.tool} on ${options.platform}/${options.architecture}`);\n\t}\n\treturn {\n\t\tversion: pin.version,\n\t\turl: `https://github.com/${config.repo}/releases/download/${config.tagPrefix}${pin.version}/${pin.assetName}`,\n\t\tsha256: pin.sha256,\n\t\texpectedBytes: pin.expectedBytes,\n\t\tmaxBytes: pin.expectedBytes * 4,\n\t\tbinaryName: config.binaryName,\n\t\tarchiveKind: pin.archiveKind,\n\t};\n}\n\n// Download a file from URL, aborting if the declared or received size exceeds the\n// bounded ceiling (ADR 0017) rather than writing an unbounded stream to disk.\nasync function downloadFile(url: string, dest: string, maxBytes: number): Promise<void> {\n\tconst response = await fetchWithRetry(url, undefined, { timeoutMs: DOWNLOAD_TIMEOUT_MS });\n\n\tif (!response.ok) {\n\t\tthrow new Error(`Failed to download: ${response.status}`);\n\t}\n\n\tif (!response.body) {\n\t\tthrow new Error(\"No response body\");\n\t}\n\n\tconst declaredLength = Number(response.headers.get(\"content-length\") ?? Number.NaN);\n\tif (Number.isFinite(declaredLength) && declaredLength > maxBytes) {\n\t\tthrow new Error(`Refusing download: declared size ${declaredLength} exceeds bounded limit ${maxBytes}`);\n\t}\n\n\tlet received = 0;\n\tconst source = Readable.fromWeb(response.body as any);\n\tsource.on(\"data\", (chunk: Buffer) => {\n\t\treceived += chunk.length;\n\t\tif (received > maxBytes) {\n\t\t\tsource.destroy(new Error(`Refusing download: exceeded bounded limit ${maxBytes} bytes`));\n\t\t}\n\t});\n\n\tconst fileStream = createWriteStream(dest);\n\ttry {\n\t\tawait pipeline(source, fileStream);\n\t} catch (error) {\n\t\trmSync(dest, { force: true });\n\t\tthrow error;\n\t}\n}\n\nfunction findBinaryRecursively(rootDir: string, binaryFileName: string): string | null {\n\tconst stack: string[] = [rootDir];\n\n\twhile (stack.length > 0) {\n\t\tconst currentDir = stack.pop();\n\t\tif (!currentDir) continue;\n\n\t\tconst entries = readdirSync(currentDir, { withFileTypes: true });\n\t\tfor (const entry of entries) {\n\t\t\tconst fullPath = join(currentDir, entry.name);\n\t\t\tif (entry.isFile() && entry.name === binaryFileName) {\n\t\t\t\treturn fullPath;\n\t\t\t}\n\t\t\tif (entry.isDirectory()) {\n\t\t\t\tstack.push(fullPath);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn null;\n}\n\nfunction formatSpawnFailure(result: SpawnSyncReturns<Buffer>): string {\n\tif (result.error?.message) {\n\t\treturn result.error.message;\n\t}\n\tconst stderr = result.stderr?.toString().trim();\n\tif (stderr) {\n\t\treturn stderr;\n\t}\n\tconst stdout = result.stdout?.toString().trim();\n\tif (stdout) {\n\t\treturn stdout;\n\t}\n\treturn `exit status ${result.status ?? \"unknown\"}`;\n}\n\nfunction runExtractionCommand(command: string, args: string[]): string | null {\n\tconst result = spawnSync(command, args, { stdio: \"pipe\" });\n\tif (!result.error && result.status === 0) {\n\t\treturn null;\n\t}\n\treturn `${command}: ${formatSpawnFailure(result)}`;\n}\n\nfunction extractTarGzArchive(archivePath: string, extractDir: string, assetName: string): void {\n\tconst failure = runExtractionCommand(\"tar\", [\"xzf\", archivePath, \"-C\", extractDir]);\n\tif (failure) {\n\t\tthrow new Error(`Failed to extract ${assetName}: ${failure}`);\n\t}\n}\n\nfunction getWindowsTarCommand(): string {\n\tconst systemRoot = process.env.SystemRoot ?? process.env.WINDIR;\n\tif (systemRoot) {\n\t\tconst systemTar = join(systemRoot, \"System32\", \"tar.exe\");\n\t\tif (existsSync(systemTar)) {\n\t\t\treturn systemTar;\n\t\t}\n\t}\n\treturn \"tar.exe\";\n}\n\nfunction extractZipArchive(archivePath: string, extractDir: string, assetName: string): void {\n\tconst failures: string[] = [];\n\n\tif (platform() === \"win32\") {\n\t\t// Windows ships bsdtar as tar.exe, which supports zip files. Prefer the\n\t\t// System32 binary over Git Bash's GNU tar, which does not handle zip archives.\n\t\tconst tarFailure = runExtractionCommand(getWindowsTarCommand(), [\"xf\", archivePath, \"-C\", extractDir]);\n\t\tif (!tarFailure) return;\n\t\tfailures.push(tarFailure);\n\n\t\tconst script =\n\t\t\t\"& { param($archive, $destination) $ErrorActionPreference = 'Stop'; Expand-Archive -LiteralPath $archive -DestinationPath $destination -Force }\";\n\t\tconst powershellFailure = runExtractionCommand(\"powershell.exe\", [\n\t\t\t\"-NoLogo\",\n\t\t\t\"-NoProfile\",\n\t\t\t\"-NonInteractive\",\n\t\t\t\"-ExecutionPolicy\",\n\t\t\t\"Bypass\",\n\t\t\t\"-Command\",\n\t\t\tscript,\n\t\t\tarchivePath,\n\t\t\textractDir,\n\t\t]);\n\t\tif (!powershellFailure) return;\n\t\tfailures.push(powershellFailure);\n\t} else {\n\t\tconst unzipFailure = runExtractionCommand(\"unzip\", [\"-q\", archivePath, \"-d\", extractDir]);\n\t\tif (!unzipFailure) return;\n\t\tfailures.push(unzipFailure);\n\n\t\tconst tarFailure = runExtractionCommand(\"tar\", [\"xf\", archivePath, \"-C\", extractDir]);\n\t\tif (!tarFailure) return;\n\t\tfailures.push(tarFailure);\n\t}\n\n\tthrow new Error(`Failed to extract ${assetName}: ${failures.join(\"; \")}`);\n}\n\nasync function sha256File(path: string): Promise<string> {\n\tconst hash = createHash(\"sha256\");\n\tfor await (const chunk of createReadStream(path)) {\n\t\thash.update(chunk as Buffer);\n\t}\n\treturn hash.digest(\"hex\");\n}\n\nexport interface InstallManagedToolArchiveOptions {\n\tarchivePath: string;\n\tdestination: string;\n\tbinaryName: string;\n\tarchiveKind: \"tar.gz\" | \"zip\";\n\texpectedSha256: string;\n\tmaxBytes: number;\n}\n\n/**\n * Verify a downloaded tool archive against its pinned digest, extract it into a\n * per-install quarantine directory, confirm the located binary did not escape that\n * quarantine, and only then atomically promote it into the live tools directory\n * (ADR 0017). Rejects a digest mismatch or an out-of-bounds archive before anything\n * is written to `destination`.\n */\nexport async function installManagedToolArchive(options: InstallManagedToolArchiveOptions): Promise<string> {\n\tconst { archivePath, destination, binaryName, archiveKind, expectedSha256, maxBytes } = options;\n\n\tconst { size } = statSync(archivePath);\n\tif (size > maxBytes) {\n\t\tthrow new Error(`Refusing install: archive size ${size} exceeds bounded limit ${maxBytes}`);\n\t}\n\n\tconst actualSha256 = await sha256File(archivePath);\n\tif (actualSha256.toLowerCase() !== expectedSha256.toLowerCase()) {\n\t\tthrow new Error(`Refusing install: digest mismatch for ${basename(archivePath)}`);\n\t}\n\n\tmkdirSync(destination, { recursive: true });\n\tconst quarantineDirectory = join(\n\t\tdestination,\n\t\t`.quarantine_${process.pid}_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`,\n\t);\n\tmkdirSync(quarantineDirectory, { recursive: true });\n\n\ttry {\n\t\tconst assetName = basename(archivePath);\n\t\tif (archiveKind === \"tar.gz\") {\n\t\t\textractTarGzArchive(archivePath, quarantineDirectory, assetName);\n\t\t} else {\n\t\t\textractZipArchive(archivePath, quarantineDirectory, assetName);\n\t\t}\n\n\t\tconst binaryFileName = binaryName + (platform() === \"win32\" ? \".exe\" : \"\");\n\t\tconst extractedBinary = findBinaryRecursively(quarantineDirectory, binaryFileName);\n\t\tif (!extractedBinary) {\n\t\t\tthrow new Error(`Binary not found in verified archive: expected ${binaryFileName}`);\n\t\t}\n\n\t\tconst resolvedBinary = resolvePath(extractedBinary);\n\t\tconst containmentPath = relative(resolvePath(quarantineDirectory), resolvedBinary);\n\t\tif (containmentPath.startsWith(\"..\") || resolvePath(containmentPath) === containmentPath) {\n\t\t\tthrow new Error(`Refusing install: archive entry escaped its quarantine directory: ${extractedBinary}`);\n\t\t}\n\n\t\tconst finalPath = join(destination, binaryFileName);\n\t\trenameSync(resolvedBinary, finalPath);\n\t\tif (platform() !== \"win32\") {\n\t\t\tchmodSync(finalPath, 0o755);\n\t\t}\n\t\treturn finalPath;\n\t} finally {\n\t\trmSync(quarantineDirectory, { recursive: true, force: true });\n\t}\n}\n\n// Download and install a tool from reviewed, pinned metadata (ADR 0017): bounded\n// download, digest verification, quarantine extraction, then atomic promotion.\nasync function downloadTool(tool: \"fd\" | \"rg\"): Promise<string> {\n\tconst plat = platform();\n\tconst architecture = arch();\n\tconst artifact = resolveManagedToolArtifact({ tool, platform: plat, architecture });\n\n\tmkdirSync(TOOLS_DIR, { recursive: true });\n\n\t// Unique download filename: fd and rg downloads can run concurrently during\n\t// startup, so sharing a fixed path causes races.\n\tconst archivePath = join(\n\t\tTOOLS_DIR,\n\t\t`download_${artifact.binaryName}_${process.pid}_${Date.now()}_${Math.random().toString(36).slice(2, 10)}${\n\t\t\tartifact.archiveKind === \"zip\" ? \".zip\" : \".tar.gz\"\n\t\t}`,\n\t);\n\n\ttry {\n\t\tawait downloadFile(artifact.url, archivePath, artifact.maxBytes);\n\t\treturn await installManagedToolArchive({\n\t\t\tarchivePath,\n\t\t\tdestination: TOOLS_DIR,\n\t\t\tbinaryName: artifact.binaryName,\n\t\t\tarchiveKind: artifact.archiveKind,\n\t\t\texpectedSha256: artifact.sha256,\n\t\t\tmaxBytes: artifact.maxBytes,\n\t\t});\n\t} finally {\n\t\trmSync(archivePath, { force: true });\n\t}\n}\n\n// Termux package names for tools\nconst TERMUX_PACKAGES: Record<string, string> = {\n\tfd: \"fd\",\n\trg: \"ripgrep\",\n};\n\n// Ensure a tool is available, downloading if necessary\n// Returns the path to the tool, or null if unavailable\nexport async function ensureTool(tool: \"fd\" | \"rg\", silent: boolean = false): Promise<string | undefined> {\n\tconst existingPath = getToolPath(tool);\n\tif (existingPath) {\n\t\treturn existingPath;\n\t}\n\n\tconst config = TOOLS[tool];\n\tif (!config) return undefined;\n\n\tif (isOfflineModeEnabled()) {\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.yellow(`${config.name} not found. Offline mode enabled, skipping download.`));\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t// On Android/Termux, Linux binaries don't work due to Bionic libc incompatibility.\n\t// Users must install via pkg.\n\tif (platform() === \"android\") {\n\t\tconst pkgName = TERMUX_PACKAGES[tool] ?? tool;\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.yellow(`${config.name} not found. Install with: pkg install ${pkgName}`));\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t// Tool not found - download it\n\tif (!silent) {\n\t\tconsole.log(chalk.dim(`${config.name} not found. Downloading...`));\n\t}\n\n\ttry {\n\t\tconst path = await downloadTool(tool);\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.dim(`${config.name} installed to ${path}`));\n\t\t}\n\t\treturn path;\n\t} catch (e) {\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.yellow(`Failed to download ${config.name}: ${e instanceof Error ? e.message : e}`));\n\t\t}\n\t\treturn undefined;\n\t}\n}\n"]}
1
+ {"version":3,"file":"tools-manager.js","sourceRoot":"","sources":["../../src/utils/tools-manager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAyB,SAAS,EAAE,MAAM,eAAe,CAAC;AACjE,OAAO,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AACpC,OAAO,EACN,SAAS,EACT,gBAAgB,EAChB,iBAAiB,EACjB,UAAU,EACV,SAAS,EACT,WAAW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AC,CAAC,CAAC;IACpE,CAAC;IAED,IAAI,CAAC;QACJ,MAAM,IAAI,GAAG,MAAM,YAAY,CAAC,IAAI,CAAC,CAAC;QACtC,IAAI,CAAC,MAAM,EAAE,CAAC;YACb,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,MAAM,CAAC,IAAI,iBAAiB,IAAI,EAAE,CAAC,CAAC,CAAC;QAC/D,CAAC;QACD,OAAO,IAAI,CAAC;IACb,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACZ,IAAI,CAAC,MAAM,EAAE,CAAC;YACb,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,MAAM,CAAC,sBAAsB,MAAM,CAAC,IAAI,KAAK,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;QACvG,CAAC;QACD,OAAO,SAAS,CAAC;IAClB,CAAC;AAAA,CACD","sourcesContent":["import chalk from \"chalk\";\nimport { type SpawnSyncReturns, spawnSync } from \"child_process\";\nimport { createHash } from \"crypto\";\nimport {\n\tchmodSync,\n\tcreateReadStream,\n\tcreateWriteStream,\n\texistsSync,\n\tmkdirSync,\n\treaddirSync,\n\trenameSync,\n\trmSync,\n\tstatSync,\n} from \"fs\";\nimport { arch, platform } from \"os\";\nimport { basename, join, relative, resolve as resolvePath } from \"path\";\nimport { Readable } from \"stream\";\nimport { pipeline } from \"stream/promises\";\nimport { getBinDir } from \"../config.ts\";\nimport { getApexEnvironment } from \"../core/environment.ts\";\nimport { fetchWithRetry } from \"./management-http.ts\";\n\nconst TOOLS_DIR = getBinDir();\nconst DOWNLOAD_TIMEOUT_MS = 120_000;\n\nfunction isOfflineModeEnabled(): boolean {\n\tconst value = getApexEnvironment(\"APEX_CODE_OFFLINE\");\n\tif (!value) return false;\n\treturn value === \"1\" || value.toLowerCase() === \"true\" || value.toLowerCase() === \"yes\";\n}\n\ninterface ToolConfig {\n\tname: string;\n\trepo: string; // GitHub repo (e.g., \"sharkdp/fd\")\n\tbinaryName: string; // Name of the binary inside the archive\n\tsystemBinaryNames?: string[]; // Alternative system command names to try before downloading\n\ttagPrefix: string; // Prefix for tags (e.g., \"v\" for v1.0.0, \"\" for 1.0.0)\n}\n\n// Per-platform/architecture asset names live in MANAGED_TOOL_PINS (ADR 0017) as the\n// single reviewed source of truth, not derived here.\nconst TOOLS: Record<string, ToolConfig> = {\n\tfd: {\n\t\tname: \"fd\",\n\t\trepo: \"sharkdp/fd\",\n\t\tbinaryName: \"fd\",\n\t\tsystemBinaryNames: [\"fd\", \"fdfind\"],\n\t\ttagPrefix: \"v\",\n\t},\n\trg: {\n\t\tname: \"ripgrep\",\n\t\trepo: \"BurntSushi/ripgrep\",\n\t\tbinaryName: \"rg\",\n\t\ttagPrefix: \"\",\n\t},\n};\n\n// Check if a command exists in PATH by trying to run it\nfunction commandExists(cmd: string): boolean {\n\ttry {\n\t\tconst result = spawnSync(cmd, [\"--version\"], { stdio: \"pipe\" });\n\t\t// Check for ENOENT error (command not found)\n\t\treturn result.error === undefined || result.error === null;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n// Get the path to a tool (system-wide or in our tools dir)\nexport function getToolPath(tool: \"fd\" | \"rg\", options: { toolsDirectory?: string } = {}): string | null {\n\tconst config = TOOLS[tool];\n\tif (!config) return null;\n\n\t// Check our tools directory first. Existence alone is not enough: the sandbox\n\t// projects host tools by bind-mounting over a file here, and bwrap leaves that\n\t// mountpoint behind as an empty, non-executable stub once the namespace is gone.\n\tconst managedPath = join(\n\t\toptions.toolsDirectory ?? TOOLS_DIR,\n\t\tconfig.binaryName + (platform() === \"win32\" ? \".exe\" : \"\"),\n\t);\n\tif (isExecutableFile(managedPath, platform())) {\n\t\treturn managedPath;\n\t}\n\n\t// Check system PATH - if found, just return the command name (it's in PATH)\n\tconst systemBinaryNames = config.systemBinaryNames ?? [config.binaryName];\n\tfor (const systemBinaryName of systemBinaryNames) {\n\t\tif (commandExists(systemBinaryName)) {\n\t\t\treturn systemBinaryName;\n\t\t}\n\t}\n\n\treturn null;\n}\n\n/**\n * Reviewed, pinned release metadata for auto-downloaded executable tools (ADR 0017).\n * Never resolved from a mutable \"latest\" API call. Updating a version, asset name, or\n * digest here is itself the reviewed change that authorizes installing a new release.\n *\n * Every digest and byte size below was established by downloading the artifact,\n * computing its SHA-256 locally, and cross-checking that value against the\n * upstream-published digest (ripgrep's own `.sha256` release sidecars; GitHub's own\n * per-asset `digest` field for both projects) — not invented, and not taken from a\n * single unverified source.\n */\ninterface ManagedToolPin {\n\tversion: string;\n\tassetName: string;\n\tsha256: string;\n\texpectedBytes: number;\n\tarchiveKind: \"tar.gz\" | \"zip\";\n}\n\nconst MANAGED_TOOL_PINS: Record<\"fd\" | \"rg\", Partial<Record<string, ManagedToolPin>>> = {\n\trg: {\n\t\t\"linux:x64\": {\n\t\t\tversion: \"14.1.1\",\n\t\t\tassetName: \"ripgrep-14.1.1-x86_64-unknown-linux-musl.tar.gz\",\n\t\t\tsha256: \"4cf9f2741e6c465ffdb7c26f38056a59e2a2544b51f7cc128ef28337eeae4d8e\",\n\t\t\texpectedBytes: 2566310,\n\t\t\tarchiveKind: \"tar.gz\",\n\t\t},\n\t\t\"linux:arm64\": {\n\t\t\tversion: \"14.1.1\",\n\t\t\tassetName: \"ripgrep-14.1.1-aarch64-unknown-linux-gnu.tar.gz\",\n\t\t\tsha256: \"c827481c4ff4ea10c9dc7a4022c8de5db34a5737cb74484d62eb94a95841ab2f\",\n\t\t\texpectedBytes: 2047405,\n\t\t\tarchiveKind: \"tar.gz\",\n\t\t},\n\t\t\"darwin:x64\": {\n\t\t\tversion: \"14.1.1\",\n\t\t\tassetName: \"ripgrep-14.1.1-x86_64-apple-darwin.tar.gz\",\n\t\t\tsha256: \"fc87e78f7cb3fea12d69072e7ef3b21509754717b746368fd40d88963630e2b3\",\n\t\t\texpectedBytes: 2082672,\n\t\t\tarchiveKind: \"tar.gz\",\n\t\t},\n\t\t\"darwin:arm64\": {\n\t\t\tversion: \"14.1.1\",\n\t\t\tassetName: \"ripgrep-14.1.1-aarch64-apple-darwin.tar.gz\",\n\t\t\tsha256: \"24ad76777745fbff131c8fbc466742b011f925bfa4fffa2ded6def23b5b937be\",\n\t\t\texpectedBytes: 1787248,\n\t\t\tarchiveKind: \"tar.gz\",\n\t\t},\n\t\t\"win32:x64\": {\n\t\t\tversion: \"14.1.1\",\n\t\t\tassetName: \"ripgrep-14.1.1-x86_64-pc-windows-msvc.zip\",\n\t\t\tsha256: \"d0f534024c42afd6cb4d38907c25cd2b249b79bbe6cc1dbee8e3e37c2b6e25a1\",\n\t\t\texpectedBytes: 2058893,\n\t\t\tarchiveKind: \"zip\",\n\t\t},\n\t\t// No upstream win32/arm64 ripgrep release asset exists at 14.1.1; resolution\n\t\t// fails closed for that combination rather than constructing a URL that 404s.\n\t},\n\tfd: {\n\t\t\"linux:x64\": {\n\t\t\tversion: \"10.4.2\",\n\t\t\tassetName: \"fd-v10.4.2-x86_64-unknown-linux-gnu.tar.gz\",\n\t\t\tsha256: \"def59805cd14b5651b68990855f426ad087f3b96881296d963910431ba3143c8\",\n\t\t\texpectedBytes: 1700779,\n\t\t\tarchiveKind: \"tar.gz\",\n\t\t},\n\t\t\"linux:arm64\": {\n\t\t\tversion: \"10.4.2\",\n\t\t\tassetName: \"fd-v10.4.2-aarch64-unknown-linux-gnu.tar.gz\",\n\t\t\tsha256: \"6c51f7c5446b3338b1e401ff15dc194c590bb2fa64fd43ff3278300f073adec5\",\n\t\t\texpectedBytes: 1559490,\n\t\t\tarchiveKind: \"tar.gz\",\n\t\t},\n\t\t// Upstream stopped shipping an Intel macOS fd binary after 10.3.0 (see\n\t\t// 7afd80d78, \"pin fd for macos x64\"); preserved here rather than special-cased.\n\t\t\"darwin:x64\": {\n\t\t\tversion: \"10.3.0\",\n\t\t\tassetName: \"fd-v10.3.0-x86_64-apple-darwin.tar.gz\",\n\t\t\tsha256: \"50d30f13fe3d5914b14c4fff5abcbd4d0cdab4b855970a6956f4f006c17117a3\",\n\t\t\texpectedBytes: 1430203,\n\t\t\tarchiveKind: \"tar.gz\",\n\t\t},\n\t\t\"darwin:arm64\": {\n\t\t\tversion: \"10.4.2\",\n\t\t\tassetName: \"fd-v10.4.2-aarch64-apple-darwin.tar.gz\",\n\t\t\tsha256: \"623dc0afc81b92e4d4606b380d7bc91916ba7b97814263e554d50923a39e480a\",\n\t\t\texpectedBytes: 1328933,\n\t\t\tarchiveKind: \"tar.gz\",\n\t\t},\n\t\t\"win32:x64\": {\n\t\t\tversion: \"10.4.2\",\n\t\t\tassetName: \"fd-v10.4.2-x86_64-pc-windows-msvc.zip\",\n\t\t\tsha256: \"b2816e506390a89941c63c9187d58a3cc10e9a55f2ef0685f9ea0eccaf7c98c8\",\n\t\t\texpectedBytes: 1525898,\n\t\t\tarchiveKind: \"zip\",\n\t\t},\n\t\t\"win32:arm64\": {\n\t\t\tversion: \"10.4.2\",\n\t\t\tassetName: \"fd-v10.4.2-aarch64-pc-windows-msvc.zip\",\n\t\t\tsha256: \"4f9110c2d5b33a7f760bfa5510f4c113d828109f7277d421b1053a9943c0fc92\",\n\t\t\texpectedBytes: 1370473,\n\t\t\tarchiveKind: \"zip\",\n\t\t},\n\t},\n};\n\nexport interface ManagedToolArtifact {\n\tversion: string;\n\turl: string;\n\tsha256: string;\n\texpectedBytes: number;\n\t/** Bounded download ceiling (ADR 0017): four times the reviewed expected size. */\n\tmaxBytes: number;\n\tbinaryName: string;\n\tarchiveKind: \"tar.gz\" | \"zip\";\n}\n\n/** Resolve reviewed, pinned metadata for a managed tool. Never queries \"latest\". */\nexport function resolveManagedToolArtifact(options: {\n\ttool: \"fd\" | \"rg\";\n\tplatform: NodeJS.Platform | string;\n\tarchitecture: string;\n}): ManagedToolArtifact {\n\tconst config = TOOLS[options.tool];\n\tconst pin = MANAGED_TOOL_PINS[options.tool]?.[`${options.platform}:${options.architecture}`];\n\tif (!config || !pin) {\n\t\tthrow new Error(`No reviewed pinned artifact for ${options.tool} on ${options.platform}/${options.architecture}`);\n\t}\n\treturn {\n\t\tversion: pin.version,\n\t\turl: `https://github.com/${config.repo}/releases/download/${config.tagPrefix}${pin.version}/${pin.assetName}`,\n\t\tsha256: pin.sha256,\n\t\texpectedBytes: pin.expectedBytes,\n\t\tmaxBytes: pin.expectedBytes * 4,\n\t\tbinaryName: config.binaryName,\n\t\tarchiveKind: pin.archiveKind,\n\t};\n}\n\n// Download a file from URL, aborting if the declared or received size exceeds the\n// bounded ceiling (ADR 0017) rather than writing an unbounded stream to disk.\nasync function downloadFile(url: string, dest: string, maxBytes: number): Promise<void> {\n\tconst response = await fetchWithRetry(url, undefined, { timeoutMs: DOWNLOAD_TIMEOUT_MS });\n\n\tif (!response.ok) {\n\t\tthrow new Error(`Failed to download: ${response.status}`);\n\t}\n\n\tif (!response.body) {\n\t\tthrow new Error(\"No response body\");\n\t}\n\n\tconst declaredLength = Number(response.headers.get(\"content-length\") ?? Number.NaN);\n\tif (Number.isFinite(declaredLength) && declaredLength > maxBytes) {\n\t\tthrow new Error(`Refusing download: declared size ${declaredLength} exceeds bounded limit ${maxBytes}`);\n\t}\n\n\tlet received = 0;\n\tconst source = Readable.fromWeb(response.body as any);\n\tsource.on(\"data\", (chunk: Buffer) => {\n\t\treceived += chunk.length;\n\t\tif (received > maxBytes) {\n\t\t\tsource.destroy(new Error(`Refusing download: exceeded bounded limit ${maxBytes} bytes`));\n\t\t}\n\t});\n\n\tconst fileStream = createWriteStream(dest);\n\ttry {\n\t\tawait pipeline(source, fileStream);\n\t} catch (error) {\n\t\trmSync(dest, { force: true });\n\t\tthrow error;\n\t}\n}\n\nfunction findBinaryRecursively(rootDir: string, binaryFileName: string): string | null {\n\tconst stack: string[] = [rootDir];\n\n\twhile (stack.length > 0) {\n\t\tconst currentDir = stack.pop();\n\t\tif (!currentDir) continue;\n\n\t\tconst entries = readdirSync(currentDir, { withFileTypes: true });\n\t\tfor (const entry of entries) {\n\t\t\tconst fullPath = join(currentDir, entry.name);\n\t\t\tif (entry.isFile() && entry.name === binaryFileName) {\n\t\t\t\treturn fullPath;\n\t\t\t}\n\t\t\tif (entry.isDirectory()) {\n\t\t\t\tstack.push(fullPath);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn null;\n}\n\nfunction formatSpawnFailure(result: SpawnSyncReturns<Buffer>): string {\n\tif (result.error?.message) {\n\t\treturn result.error.message;\n\t}\n\tconst stderr = result.stderr?.toString().trim();\n\tif (stderr) {\n\t\treturn stderr;\n\t}\n\tconst stdout = result.stdout?.toString().trim();\n\tif (stdout) {\n\t\treturn stdout;\n\t}\n\treturn `exit status ${result.status ?? \"unknown\"}`;\n}\n\nfunction runExtractionCommand(command: string, args: string[]): string | null {\n\tconst result = spawnSync(command, args, { stdio: \"pipe\" });\n\tif (!result.error && result.status === 0) {\n\t\treturn null;\n\t}\n\treturn `${command}: ${formatSpawnFailure(result)}`;\n}\n\nfunction extractTarGzArchive(archivePath: string, extractDir: string, assetName: string): void {\n\tconst failure = runExtractionCommand(\"tar\", [\"xzf\", archivePath, \"-C\", extractDir]);\n\tif (failure) {\n\t\tthrow new Error(`Failed to extract ${assetName}: ${failure}`);\n\t}\n}\n\nfunction getWindowsTarCommand(): string {\n\tconst systemRoot = process.env.SystemRoot ?? process.env.WINDIR;\n\tif (systemRoot) {\n\t\tconst systemTar = join(systemRoot, \"System32\", \"tar.exe\");\n\t\tif (existsSync(systemTar)) {\n\t\t\treturn systemTar;\n\t\t}\n\t}\n\treturn \"tar.exe\";\n}\n\nfunction extractZipArchive(archivePath: string, extractDir: string, assetName: string): void {\n\tconst failures: string[] = [];\n\n\tif (platform() === \"win32\") {\n\t\t// Windows ships bsdtar as tar.exe, which supports zip files. Prefer the\n\t\t// System32 binary over Git Bash's GNU tar, which does not handle zip archives.\n\t\tconst tarFailure = runExtractionCommand(getWindowsTarCommand(), [\"xf\", archivePath, \"-C\", extractDir]);\n\t\tif (!tarFailure) return;\n\t\tfailures.push(tarFailure);\n\n\t\tconst script =\n\t\t\t\"& { param($archive, $destination) $ErrorActionPreference = 'Stop'; Expand-Archive -LiteralPath $archive -DestinationPath $destination -Force }\";\n\t\tconst powershellFailure = runExtractionCommand(\"powershell.exe\", [\n\t\t\t\"-NoLogo\",\n\t\t\t\"-NoProfile\",\n\t\t\t\"-NonInteractive\",\n\t\t\t\"-ExecutionPolicy\",\n\t\t\t\"Bypass\",\n\t\t\t\"-Command\",\n\t\t\tscript,\n\t\t\tarchivePath,\n\t\t\textractDir,\n\t\t]);\n\t\tif (!powershellFailure) return;\n\t\tfailures.push(powershellFailure);\n\t} else {\n\t\tconst unzipFailure = runExtractionCommand(\"unzip\", [\"-q\", archivePath, \"-d\", extractDir]);\n\t\tif (!unzipFailure) return;\n\t\tfailures.push(unzipFailure);\n\n\t\tconst tarFailure = runExtractionCommand(\"tar\", [\"xf\", archivePath, \"-C\", extractDir]);\n\t\tif (!tarFailure) return;\n\t\tfailures.push(tarFailure);\n\t}\n\n\tthrow new Error(`Failed to extract ${assetName}: ${failures.join(\"; \")}`);\n}\n\nasync function sha256File(path: string): Promise<string> {\n\tconst hash = createHash(\"sha256\");\n\tfor await (const chunk of createReadStream(path)) {\n\t\thash.update(chunk as Buffer);\n\t}\n\treturn hash.digest(\"hex\");\n}\n\nexport interface InstallManagedToolArchiveOptions {\n\tarchivePath: string;\n\tdestination: string;\n\tbinaryName: string;\n\tarchiveKind: \"tar.gz\" | \"zip\";\n\texpectedSha256: string;\n\tmaxBytes: number;\n}\n\n/**\n * Verify a downloaded tool archive against its pinned digest, extract it into a\n * per-install quarantine directory, confirm the located binary did not escape that\n * quarantine, and only then atomically promote it into the live tools directory\n * (ADR 0017). Rejects a digest mismatch or an out-of-bounds archive before anything\n * is written to `destination`.\n */\nexport async function installManagedToolArchive(options: InstallManagedToolArchiveOptions): Promise<string> {\n\tconst { archivePath, destination, binaryName, archiveKind, expectedSha256, maxBytes } = options;\n\n\tconst { size } = statSync(archivePath);\n\tif (size > maxBytes) {\n\t\tthrow new Error(`Refusing install: archive size ${size} exceeds bounded limit ${maxBytes}`);\n\t}\n\n\tconst actualSha256 = await sha256File(archivePath);\n\tif (actualSha256.toLowerCase() !== expectedSha256.toLowerCase()) {\n\t\tthrow new Error(`Refusing install: digest mismatch for ${basename(archivePath)}`);\n\t}\n\n\tmkdirSync(destination, { recursive: true });\n\tconst quarantineDirectory = join(\n\t\tdestination,\n\t\t`.quarantine_${process.pid}_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`,\n\t);\n\tmkdirSync(quarantineDirectory, { recursive: true });\n\n\ttry {\n\t\tconst assetName = basename(archivePath);\n\t\tif (archiveKind === \"tar.gz\") {\n\t\t\textractTarGzArchive(archivePath, quarantineDirectory, assetName);\n\t\t} else {\n\t\t\textractZipArchive(archivePath, quarantineDirectory, assetName);\n\t\t}\n\n\t\tconst binaryFileName = binaryName + (platform() === \"win32\" ? \".exe\" : \"\");\n\t\tconst extractedBinary = findBinaryRecursively(quarantineDirectory, binaryFileName);\n\t\tif (!extractedBinary) {\n\t\t\tthrow new Error(`Binary not found in verified archive: expected ${binaryFileName}`);\n\t\t}\n\n\t\tconst resolvedBinary = resolvePath(extractedBinary);\n\t\tconst containmentPath = relative(resolvePath(quarantineDirectory), resolvedBinary);\n\t\tif (containmentPath.startsWith(\"..\") || resolvePath(containmentPath) === containmentPath) {\n\t\t\tthrow new Error(`Refusing install: archive entry escaped its quarantine directory: ${extractedBinary}`);\n\t\t}\n\n\t\tconst finalPath = join(destination, binaryFileName);\n\t\trenameSync(resolvedBinary, finalPath);\n\t\tif (platform() !== \"win32\") {\n\t\t\tchmodSync(finalPath, 0o755);\n\t\t}\n\t\treturn finalPath;\n\t} finally {\n\t\trmSync(quarantineDirectory, { recursive: true, force: true });\n\t}\n}\n\n// Download and install a tool from reviewed, pinned metadata (ADR 0017): bounded\n// download, digest verification, quarantine extraction, then atomic promotion.\nasync function downloadTool(tool: \"fd\" | \"rg\"): Promise<string> {\n\tconst plat = platform();\n\tconst architecture = arch();\n\tconst artifact = resolveManagedToolArtifact({ tool, platform: plat, architecture });\n\n\tmkdirSync(TOOLS_DIR, { recursive: true });\n\n\t// Unique download filename: fd and rg downloads can run concurrently during\n\t// startup, so sharing a fixed path causes races.\n\tconst archivePath = join(\n\t\tTOOLS_DIR,\n\t\t`download_${artifact.binaryName}_${process.pid}_${Date.now()}_${Math.random().toString(36).slice(2, 10)}${\n\t\t\tartifact.archiveKind === \"zip\" ? \".zip\" : \".tar.gz\"\n\t\t}`,\n\t);\n\n\ttry {\n\t\tawait downloadFile(artifact.url, archivePath, artifact.maxBytes);\n\t\treturn await installManagedToolArchive({\n\t\t\tarchivePath,\n\t\t\tdestination: TOOLS_DIR,\n\t\t\tbinaryName: artifact.binaryName,\n\t\t\tarchiveKind: artifact.archiveKind,\n\t\t\texpectedSha256: artifact.sha256,\n\t\t\tmaxBytes: artifact.maxBytes,\n\t\t});\n\t} finally {\n\t\trmSync(archivePath, { force: true });\n\t}\n}\n\nexport interface HostToolBinary {\n\t/** File name the child looks for in its own tools directory (\"fd\", \"rg\", \"fd.exe\"). */\n\tname: string;\n\t/** Absolute host path to the executable backing that name. */\n\tpath: string;\n}\n\nfunction isExecutableFile(candidate: string, targetPlatform: NodeJS.Platform): boolean {\n\ttry {\n\t\tconst stats = statSync(candidate);\n\t\tif (!stats.isFile()) return false;\n\t\t// Windows has no POSIX execute bit; presence of the file is the only signal.\n\t\treturn targetPlatform === \"win32\" || (stats.mode & 0o111) !== 0;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/**\n * Absolute host path for a managed tool, or undefined when it is installed nowhere.\n *\n * `getToolPath` may return a bare command name because its caller spawns through PATH.\n * A sandboxed child has no such luxury: its PATH still lists host directories that the\n * OS boundary has already replaced, so the supervisor must resolve a real path here and\n * project it in (ADR 0017, and the sandbox spec's tool-projection amendment).\n */\nexport function resolveHostToolBinary(\n\ttool: \"fd\" | \"rg\",\n\toptions: { toolsDirectory?: string; pathValue?: string; platform?: NodeJS.Platform } = {},\n): string | undefined {\n\tconst config = TOOLS[tool];\n\tif (!config) return undefined;\n\n\tconst targetPlatform = options.platform ?? platform();\n\tconst executableSuffix = targetPlatform === \"win32\" ? \".exe\" : \"\";\n\tconst managedPath = join(options.toolsDirectory ?? TOOLS_DIR, config.binaryName + executableSuffix);\n\tif (isExecutableFile(managedPath, targetPlatform)) {\n\t\treturn managedPath;\n\t}\n\n\tconst pathEntries = (options.pathValue ?? process.env.PATH ?? \"\")\n\t\t.split(targetPlatform === \"win32\" ? \";\" : \":\")\n\t\t.filter((entry) => entry.length > 0);\n\t// Preference runs by name first, matching getToolPath: a real `fd` anywhere on PATH\n\t// beats a `fdfind` alias, rather than whichever directory happens to come first.\n\tfor (const systemBinaryName of config.systemBinaryNames ?? [config.binaryName]) {\n\t\tfor (const entry of pathEntries) {\n\t\t\tconst candidate = join(entry, systemBinaryName + executableSuffix);\n\t\t\tif (isExecutableFile(candidate, targetPlatform)) {\n\t\t\t\treturn candidate;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn undefined;\n}\n\n/**\n * Install any missing managed tool on the host, then report absolute paths for the ones\n * that exist. Downloading here rather than inside the child means one install serves every\n * workspace, and it happens on the side of the boundary that still has network access.\n */\nexport async function prepareHostToolBinaries(silent: boolean = false): Promise<HostToolBinary[]> {\n\tconst binaries: HostToolBinary[] = [];\n\tfor (const tool of [\"fd\", \"rg\"] as const) {\n\t\tawait ensureTool(tool, silent);\n\t\tconst hostPath = resolveHostToolBinary(tool);\n\t\tif (hostPath) {\n\t\t\tbinaries.push({ name: TOOLS[tool].binaryName + (platform() === \"win32\" ? \".exe\" : \"\"), path: hostPath });\n\t\t}\n\t}\n\treturn binaries;\n}\n\n// Termux package names for tools\nconst TERMUX_PACKAGES: Record<string, string> = {\n\tfd: \"fd\",\n\trg: \"ripgrep\",\n};\n\n// Ensure a tool is available, downloading if necessary\n// Returns the path to the tool, or null if unavailable\nexport async function ensureTool(tool: \"fd\" | \"rg\", silent: boolean = false): Promise<string | undefined> {\n\tconst existingPath = getToolPath(tool);\n\tif (existingPath) {\n\t\treturn existingPath;\n\t}\n\n\tconst config = TOOLS[tool];\n\tif (!config) return undefined;\n\n\tif (isOfflineModeEnabled()) {\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.yellow(`${config.name} not found. Offline mode enabled, skipping download.`));\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t// On Android/Termux, Linux binaries don't work due to Bionic libc incompatibility.\n\t// Users must install via pkg.\n\tif (platform() === \"android\") {\n\t\tconst pkgName = TERMUX_PACKAGES[tool] ?? tool;\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.yellow(`${config.name} not found. Install with: pkg install ${pkgName}`));\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t// Tool not found - download it\n\tif (!silent) {\n\t\tconsole.log(chalk.dim(`${config.name} not found. Downloading...`));\n\t}\n\n\ttry {\n\t\tconst path = await downloadTool(tool);\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.dim(`${config.name} installed to ${path}`));\n\t\t}\n\t\treturn path;\n\t} catch (e) {\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.yellow(`Failed to download ${config.name}: ${e instanceof Error ? e.message : e}`));\n\t\t}\n\t\treturn undefined;\n\t}\n}\n"]}
@@ -1,3 +1,5 @@
1
+ /** Exported so the sandbox's default allowlist cannot drift from the URL used here. */
2
+ export declare const VERSION_CHECK_HOST: string;
1
3
  export interface LatestApexCodeRelease {
2
4
  version: string;
3
5
  packageName?: string;
@@ -1 +1 @@
1
- {"version":3,"file":"version-check.d.ts","sourceRoot":"","sources":["../../src/utils/version-check.ts"],"names":[],"mappings":"AAeA,MAAM,WAAW,qBAAqB;IACrC,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,IAAI,CAAC,EAAE,MAAM,CAAC;CACd;AAED,sFAAsF;AACtF,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAiB9D;AAED,wBAAgB,sBAAsB,CAAC,WAAW,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAOpG;AAED,wBAAgB,qBAAqB,CAAC,gBAAgB,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM,GAAG,OAAO,CAM/F;AAED,wBAAsB,wBAAwB,CAC7C,cAAc,EAAE,MAAM,EACtB,OAAO,GAAE;IAAE,SAAS,CAAC,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,OAAO,CAAA;CAAO,GACnD,OAAO,CAAC,qBAAqB,GAAG,SAAS,CAAC,CAiC5C;AAED,wBAAsB,wBAAwB,CAC7C,cAAc,EAAE,MAAM,EACtB,OAAO,GAAE;IAAE,SAAS,CAAC,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,OAAO,CAAA;CAAO,GACnD,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAE7B;AAED,wBAAsB,0BAA0B,CAAC,cAAc,EAAE,MAAM,GAAG,OAAO,CAAC,qBAAqB,GAAG,SAAS,CAAC,CAYnH","sourcesContent":["import { compare, valid } from \"semver\";\nimport { PACKAGE_NAME } from \"../config.ts\";\nimport { getApexEnvironment } from \"../core/environment.ts\";\nimport { getApexCodeUserAgent } from \"./apex-code-user-agent.ts\";\nimport { fetchWithRetry } from \"./management-http.ts\";\n\n/**\n * npm's own per-tag registry endpoint, not a custom API this project would need to\n * host and operate. Compares against the \"next\" dist-tag rather than \"latest\": the\n * README documents `npm install --global apex-code@next` as the install channel\n * this pre-alpha project actually ships through.\n */\nconst LATEST_VERSION_URL = `https://registry.npmjs.org/${PACKAGE_NAME}/next`;\nconst DEFAULT_VERSION_CHECK_TIMEOUT_MS = 10000;\n\nexport interface LatestApexCodeRelease {\n\tversion: string;\n\tpackageName?: string;\n\tnote?: string;\n}\n\n/** Include useful errno details hidden behind Node's generic \"fetch failed\" error. */\nexport function formatVersionCheckError(error: unknown): string {\n\tconst rootMessage = error instanceof Error && error.message ? error.message : String(error);\n\tconst cause = error instanceof Error ? error.cause : undefined;\n\tconst causes = cause instanceof AggregateError ? cause.errors : cause === undefined ? [] : [cause];\n\tconst codes = causes\n\t\t.map((value) =>\n\t\t\ttypeof value === \"object\" && value !== null && \"code\" in value && typeof value.code === \"string\"\n\t\t\t\t? value.code\n\t\t\t\t: undefined,\n\t\t)\n\t\t.filter((code): code is string => code !== undefined);\n\n\tif (codes.length > 0) return `${rootMessage} (${[...new Set(codes)].join(\", \")})`;\n\tconst causeMessage = causes.find(\n\t\t(value): value is Error => value instanceof Error && Boolean(value.message),\n\t)?.message;\n\treturn causeMessage ? `${rootMessage} (cause: ${causeMessage})` : rootMessage;\n}\n\nexport function comparePackageVersions(leftVersion: string, rightVersion: string): number | undefined {\n\tconst left = valid(leftVersion.trim());\n\tconst right = valid(rightVersion.trim());\n\tif (!left || !right) {\n\t\treturn undefined;\n\t}\n\treturn compare(left, right);\n}\n\nexport function isNewerPackageVersion(candidateVersion: string, currentVersion: string): boolean {\n\tconst comparison = comparePackageVersions(candidateVersion, currentVersion);\n\tif (comparison !== undefined) {\n\t\treturn comparison > 0;\n\t}\n\treturn candidateVersion.trim() !== currentVersion.trim();\n}\n\nexport async function getLatestApexCodeRelease(\n\tcurrentVersion: string,\n\toptions: { timeoutMs?: number; retry?: boolean } = {},\n): Promise<LatestApexCodeRelease | undefined> {\n\tif (getApexEnvironment(\"APEX_CODE_OFFLINE\")) return undefined;\n\n\tconst response = await fetchWithRetry(\n\t\tLATEST_VERSION_URL,\n\t\t{\n\t\t\theaders: {\n\t\t\t\t\"User-Agent\": getApexCodeUserAgent(currentVersion),\n\t\t\t\taccept: \"application/json\",\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tmaxRetries: options.retry ? 2 : 0,\n\t\t\ttimeoutMs: options.timeoutMs ?? DEFAULT_VERSION_CHECK_TIMEOUT_MS,\n\t\t},\n\t);\n\tif (!response.ok) return undefined;\n\n\t// npm's per-tag registry endpoint returns the full package manifest for that\n\t// version; \"packageName\"/\"note\" have no npm-registry equivalent and are left\n\t// undefined -- callers already treat both as optional with sensible fallbacks.\n\tconst data = (await response.json()) as {\n\t\tname?: unknown;\n\t\tversion?: unknown;\n\t};\n\tif (typeof data.version !== \"string\" || !data.version.trim()) {\n\t\treturn undefined;\n\t}\n\tconst packageName = typeof data.name === \"string\" && data.name.trim() ? data.name.trim() : undefined;\n\treturn {\n\t\tversion: data.version.trim(),\n\t\t...(packageName && packageName !== PACKAGE_NAME ? { packageName } : {}),\n\t};\n}\n\nexport async function getLatestApexCodeVersion(\n\tcurrentVersion: string,\n\toptions: { timeoutMs?: number; retry?: boolean } = {},\n): Promise<string | undefined> {\n\treturn (await getLatestApexCodeRelease(currentVersion, options))?.version;\n}\n\nexport async function checkForNewApexCodeVersion(currentVersion: string): Promise<LatestApexCodeRelease | undefined> {\n\tif (getApexEnvironment(\"APEX_CODE_SKIP_VERSION_CHECK\")) return undefined;\n\n\ttry {\n\t\tconst latestRelease = await getLatestApexCodeRelease(currentVersion);\n\t\tif (latestRelease && isNewerPackageVersion(latestRelease.version, currentVersion)) {\n\t\t\treturn latestRelease;\n\t\t}\n\t\treturn undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n"]}
1
+ {"version":3,"file":"version-check.d.ts","sourceRoot":"","sources":["../../src/utils/version-check.ts"],"names":[],"mappings":"AAaA,uFAAuF;AACvF,eAAO,MAAM,kBAAkB,QAAmC,CAAC;AAGnE,MAAM,WAAW,qBAAqB;IACrC,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,IAAI,CAAC,EAAE,MAAM,CAAC;CACd;AAED,sFAAsF;AACtF,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAiB9D;AAED,wBAAgB,sBAAsB,CAAC,WAAW,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAOpG;AAED,wBAAgB,qBAAqB,CAAC,gBAAgB,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM,GAAG,OAAO,CAM/F;AAED,wBAAsB,wBAAwB,CAC7C,cAAc,EAAE,MAAM,EACtB,OAAO,GAAE;IAAE,SAAS,CAAC,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,OAAO,CAAA;CAAO,GACnD,OAAO,CAAC,qBAAqB,GAAG,SAAS,CAAC,CAiC5C;AAED,wBAAsB,wBAAwB,CAC7C,cAAc,EAAE,MAAM,EACtB,OAAO,GAAE;IAAE,SAAS,CAAC,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,OAAO,CAAA;CAAO,GACnD,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAE7B;AAED,wBAAsB,0BAA0B,CAAC,cAAc,EAAE,MAAM,GAAG,OAAO,CAAC,qBAAqB,GAAG,SAAS,CAAC,CAYnH","sourcesContent":["import { compare, valid } from \"semver\";\nimport { PACKAGE_NAME } from \"../config.ts\";\nimport { getApexEnvironment } from \"../core/environment.ts\";\nimport { getApexCodeUserAgent } from \"./apex-code-user-agent.ts\";\nimport { fetchWithRetry } from \"./management-http.ts\";\n\n/**\n * npm's own per-tag registry endpoint, not a custom API this project would need to\n * host and operate. Compares against the \"next\" dist-tag rather than \"latest\": the\n * README documents `npm install --global apex-code@next` as the install channel\n * this pre-alpha project actually ships through.\n */\nconst LATEST_VERSION_URL = `https://registry.npmjs.org/${PACKAGE_NAME}/next`;\n/** Exported so the sandbox's default allowlist cannot drift from the URL used here. */\nexport const VERSION_CHECK_HOST = new URL(LATEST_VERSION_URL).host;\nconst DEFAULT_VERSION_CHECK_TIMEOUT_MS = 10000;\n\nexport interface LatestApexCodeRelease {\n\tversion: string;\n\tpackageName?: string;\n\tnote?: string;\n}\n\n/** Include useful errno details hidden behind Node's generic \"fetch failed\" error. */\nexport function formatVersionCheckError(error: unknown): string {\n\tconst rootMessage = error instanceof Error && error.message ? error.message : String(error);\n\tconst cause = error instanceof Error ? error.cause : undefined;\n\tconst causes = cause instanceof AggregateError ? cause.errors : cause === undefined ? [] : [cause];\n\tconst codes = causes\n\t\t.map((value) =>\n\t\t\ttypeof value === \"object\" && value !== null && \"code\" in value && typeof value.code === \"string\"\n\t\t\t\t? value.code\n\t\t\t\t: undefined,\n\t\t)\n\t\t.filter((code): code is string => code !== undefined);\n\n\tif (codes.length > 0) return `${rootMessage} (${[...new Set(codes)].join(\", \")})`;\n\tconst causeMessage = causes.find(\n\t\t(value): value is Error => value instanceof Error && Boolean(value.message),\n\t)?.message;\n\treturn causeMessage ? `${rootMessage} (cause: ${causeMessage})` : rootMessage;\n}\n\nexport function comparePackageVersions(leftVersion: string, rightVersion: string): number | undefined {\n\tconst left = valid(leftVersion.trim());\n\tconst right = valid(rightVersion.trim());\n\tif (!left || !right) {\n\t\treturn undefined;\n\t}\n\treturn compare(left, right);\n}\n\nexport function isNewerPackageVersion(candidateVersion: string, currentVersion: string): boolean {\n\tconst comparison = comparePackageVersions(candidateVersion, currentVersion);\n\tif (comparison !== undefined) {\n\t\treturn comparison > 0;\n\t}\n\treturn candidateVersion.trim() !== currentVersion.trim();\n}\n\nexport async function getLatestApexCodeRelease(\n\tcurrentVersion: string,\n\toptions: { timeoutMs?: number; retry?: boolean } = {},\n): Promise<LatestApexCodeRelease | undefined> {\n\tif (getApexEnvironment(\"APEX_CODE_OFFLINE\")) return undefined;\n\n\tconst response = await fetchWithRetry(\n\t\tLATEST_VERSION_URL,\n\t\t{\n\t\t\theaders: {\n\t\t\t\t\"User-Agent\": getApexCodeUserAgent(currentVersion),\n\t\t\t\taccept: \"application/json\",\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tmaxRetries: options.retry ? 2 : 0,\n\t\t\ttimeoutMs: options.timeoutMs ?? DEFAULT_VERSION_CHECK_TIMEOUT_MS,\n\t\t},\n\t);\n\tif (!response.ok) return undefined;\n\n\t// npm's per-tag registry endpoint returns the full package manifest for that\n\t// version; \"packageName\"/\"note\" have no npm-registry equivalent and are left\n\t// undefined -- callers already treat both as optional with sensible fallbacks.\n\tconst data = (await response.json()) as {\n\t\tname?: unknown;\n\t\tversion?: unknown;\n\t};\n\tif (typeof data.version !== \"string\" || !data.version.trim()) {\n\t\treturn undefined;\n\t}\n\tconst packageName = typeof data.name === \"string\" && data.name.trim() ? data.name.trim() : undefined;\n\treturn {\n\t\tversion: data.version.trim(),\n\t\t...(packageName && packageName !== PACKAGE_NAME ? { packageName } : {}),\n\t};\n}\n\nexport async function getLatestApexCodeVersion(\n\tcurrentVersion: string,\n\toptions: { timeoutMs?: number; retry?: boolean } = {},\n): Promise<string | undefined> {\n\treturn (await getLatestApexCodeRelease(currentVersion, options))?.version;\n}\n\nexport async function checkForNewApexCodeVersion(currentVersion: string): Promise<LatestApexCodeRelease | undefined> {\n\tif (getApexEnvironment(\"APEX_CODE_SKIP_VERSION_CHECK\")) return undefined;\n\n\ttry {\n\t\tconst latestRelease = await getLatestApexCodeRelease(currentVersion);\n\t\tif (latestRelease && isNewerPackageVersion(latestRelease.version, currentVersion)) {\n\t\t\treturn latestRelease;\n\t\t}\n\t\treturn undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n"]}
@@ -10,6 +10,8 @@ import { fetchWithRetry } from "./management-http.js";
10
10
  * this pre-alpha project actually ships through.
11
11
  */
12
12
  const LATEST_VERSION_URL = `https://registry.npmjs.org/${PACKAGE_NAME}/next`;
13
+ /** Exported so the sandbox's default allowlist cannot drift from the URL used here. */
14
+ export const VERSION_CHECK_HOST = new URL(LATEST_VERSION_URL).host;
13
15
  const DEFAULT_VERSION_CHECK_TIMEOUT_MS = 10000;
14
16
  /** Include useful errno details hidden behind Node's generic "fetch failed" error. */
15
17
  export function formatVersionCheckError(error) {
@@ -1 +1 @@
1
- {"version":3,"file":"version-check.js","sourceRoot":"","sources":["../../src/utils/version-check.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,Q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C;IACpH,IAAI,kBAAkB,CAAC,8BAA8B,CAAC;QAAE,OAAO,SAAS,CAAC;IAEzE,IAAI,CAAC;QACJ,MAAM,aAAa,GAAG,MAAM,wBAAwB,CAAC,cAAc,CAAC,CAAC;QACrE,IAAI,aAAa,IAAI,qBAAqB,CAAC,aAAa,CAAC,OAAO,EAAE,cAAc,CAAC,EAAE,CAAC;YACnF,OAAO,aAAa,CAAC;QACtB,CAAC;QACD,OAAO,SAAS,CAAC;IAClB,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,SAAS,CAAC;IAClB,CAAC;AAAA,CACD","sourcesContent":["import { compare, valid } from \"semver\";\nimport { PACKAGE_NAME } from \"../config.ts\";\nimport { getApexEnvironment } from \"../core/environment.ts\";\nimport { getApexCodeUserAgent } from \"./apex-code-user-agent.ts\";\nimport { fetchWithRetry } from \"./management-http.ts\";\n\n/**\n * npm's own per-tag registry endpoint, not a custom API this project would need to\n * host and operate. Compares against the \"next\" dist-tag rather than \"latest\": the\n * README documents `npm install --global apex-code@next` as the install channel\n * this pre-alpha project actually ships through.\n */\nconst LATEST_VERSION_URL = `https://registry.npmjs.org/${PACKAGE_NAME}/next`;\nconst DEFAULT_VERSION_CHECK_TIMEOUT_MS = 10000;\n\nexport interface LatestApexCodeRelease {\n\tversion: string;\n\tpackageName?: string;\n\tnote?: string;\n}\n\n/** Include useful errno details hidden behind Node's generic \"fetch failed\" error. */\nexport function formatVersionCheckError(error: unknown): string {\n\tconst rootMessage = error instanceof Error && error.message ? error.message : String(error);\n\tconst cause = error instanceof Error ? error.cause : undefined;\n\tconst causes = cause instanceof AggregateError ? cause.errors : cause === undefined ? [] : [cause];\n\tconst codes = causes\n\t\t.map((value) =>\n\t\t\ttypeof value === \"object\" && value !== null && \"code\" in value && typeof value.code === \"string\"\n\t\t\t\t? value.code\n\t\t\t\t: undefined,\n\t\t)\n\t\t.filter((code): code is string => code !== undefined);\n\n\tif (codes.length > 0) return `${rootMessage} (${[...new Set(codes)].join(\", \")})`;\n\tconst causeMessage = causes.find(\n\t\t(value): value is Error => value instanceof Error && Boolean(value.message),\n\t)?.message;\n\treturn causeMessage ? `${rootMessage} (cause: ${causeMessage})` : rootMessage;\n}\n\nexport function comparePackageVersions(leftVersion: string, rightVersion: string): number | undefined {\n\tconst left = valid(leftVersion.trim());\n\tconst right = valid(rightVersion.trim());\n\tif (!left || !right) {\n\t\treturn undefined;\n\t}\n\treturn compare(left, right);\n}\n\nexport function isNewerPackageVersion(candidateVersion: string, currentVersion: string): boolean {\n\tconst comparison = comparePackageVersions(candidateVersion, currentVersion);\n\tif (comparison !== undefined) {\n\t\treturn comparison > 0;\n\t}\n\treturn candidateVersion.trim() !== currentVersion.trim();\n}\n\nexport async function getLatestApexCodeRelease(\n\tcurrentVersion: string,\n\toptions: { timeoutMs?: number; retry?: boolean } = {},\n): Promise<LatestApexCodeRelease | undefined> {\n\tif (getApexEnvironment(\"APEX_CODE_OFFLINE\")) return undefined;\n\n\tconst response = await fetchWithRetry(\n\t\tLATEST_VERSION_URL,\n\t\t{\n\t\t\theaders: {\n\t\t\t\t\"User-Agent\": getApexCodeUserAgent(currentVersion),\n\t\t\t\taccept: \"application/json\",\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tmaxRetries: options.retry ? 2 : 0,\n\t\t\ttimeoutMs: options.timeoutMs ?? DEFAULT_VERSION_CHECK_TIMEOUT_MS,\n\t\t},\n\t);\n\tif (!response.ok) return undefined;\n\n\t// npm's per-tag registry endpoint returns the full package manifest for that\n\t// version; \"packageName\"/\"note\" have no npm-registry equivalent and are left\n\t// undefined -- callers already treat both as optional with sensible fallbacks.\n\tconst data = (await response.json()) as {\n\t\tname?: unknown;\n\t\tversion?: unknown;\n\t};\n\tif (typeof data.version !== \"string\" || !data.version.trim()) {\n\t\treturn undefined;\n\t}\n\tconst packageName = typeof data.name === \"string\" && data.name.trim() ? data.name.trim() : undefined;\n\treturn {\n\t\tversion: data.version.trim(),\n\t\t...(packageName && packageName !== PACKAGE_NAME ? { packageName } : {}),\n\t};\n}\n\nexport async function getLatestApexCodeVersion(\n\tcurrentVersion: string,\n\toptions: { timeoutMs?: number; retry?: boolean } = {},\n): Promise<string | undefined> {\n\treturn (await getLatestApexCodeRelease(currentVersion, options))?.version;\n}\n\nexport async function checkForNewApexCodeVersion(currentVersion: string): Promise<LatestApexCodeRelease | undefined> {\n\tif (getApexEnvironment(\"APEX_CODE_SKIP_VERSION_CHECK\")) return undefined;\n\n\ttry {\n\t\tconst latestRelease = await getLatestApexCodeRelease(currentVersion);\n\t\tif (latestRelease && isNewerPackageVersion(latestRelease.version, currentVersion)) {\n\t\t\treturn latestRelease;\n\t\t}\n\t\treturn undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n"]}
1
+ {"version":3,"file":"version-check.js","sourceRoot":"","sources":["../../src/utils/version-check.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,QAAQ,CAAC;AACxC,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAC5D,OAAO,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AACjE,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAEtD;;;;;GAKG;AACH,MAAM,kBAAkB,GAAG,8BAA8B,YAAY,OAAO,CAAC;AAC7E,uFAAuF;AACvF,MAAM,CAAC,MAAM,kBAAkB,GAAG,IAAI,GAAG,CAAC,kBAAkB,CAAC,CAAC,IAAI,CAAC;AACnE,MAAM,gCAAgC,GAAG,KAAK,CAAC;AAQ/C,sFAAsF;AACtF,MAAM,UAAU,uBAAuB,CAAC,KAAc,EAAU;IAC/D,MAAM,WAAW,GAAG,KAAK,YAAY,KAAK,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IA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AI,EAAE,EAAE,CAAC;QAC9D,OAAO,SAAS,CAAC;IAClB,CAAC;IACD,MAAM,WAAW,GAAG,OAAO,IAAI,CAAC,IAAI,KAAK,QAAQ,IAAI,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC;IACrG,OAAO;QACN,OAAO,EAAE,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE;QAC5B,GAAG,CAAC,WAAW,IAAI,WAAW,KAAK,YAAY,CAAC,CAAC,CAAC,EAAE,WAAW,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KACvE,CAAC;AAAA,CACF;AAED,MAAM,CAAC,KAAK,UAAU,wBAAwB,CAC7C,cAAsB,EACtB,OAAO,GAA4C,EAAE,EACvB;IAC9B,OAAO,CAAC,MAAM,wBAAwB,CAAC,cAAc,EAAE,OAAO,CAAC,CAAC,EAAE,OAAO,CAAC;AAAA,CAC1E;AAED,MAAM,CAAC,KAAK,UAAU,0BAA0B,CAAC,cAAsB,EAA8C;IACpH,IAAI,kBAAkB,CAAC,8BAA8B,CAAC;QAAE,OAAO,SAAS,CAAC;IAEzE,IAAI,CAAC;QACJ,MAAM,aAAa,GAAG,MAAM,wBAAwB,CAAC,cAAc,CAAC,CAAC;QACrE,IAAI,aAAa,IAAI,qBAAqB,CAAC,aAAa,CAAC,OAAO,EAAE,cAAc,CAAC,EAAE,CAAC;YACnF,OAAO,aAAa,CAAC;QACtB,CAAC;QACD,OAAO,SAAS,CAAC;IAClB,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,SAAS,CAAC;IAClB,CAAC;AAAA,CACD","sourcesContent":["import { compare, valid } from \"semver\";\nimport { PACKAGE_NAME } from \"../config.ts\";\nimport { getApexEnvironment } from \"../core/environment.ts\";\nimport { getApexCodeUserAgent } from \"./apex-code-user-agent.ts\";\nimport { fetchWithRetry } from \"./management-http.ts\";\n\n/**\n * npm's own per-tag registry endpoint, not a custom API this project would need to\n * host and operate. Compares against the \"next\" dist-tag rather than \"latest\": the\n * README documents `npm install --global apex-code@next` as the install channel\n * this pre-alpha project actually ships through.\n */\nconst LATEST_VERSION_URL = `https://registry.npmjs.org/${PACKAGE_NAME}/next`;\n/** Exported so the sandbox's default allowlist cannot drift from the URL used here. */\nexport const VERSION_CHECK_HOST = new URL(LATEST_VERSION_URL).host;\nconst DEFAULT_VERSION_CHECK_TIMEOUT_MS = 10000;\n\nexport interface LatestApexCodeRelease {\n\tversion: string;\n\tpackageName?: string;\n\tnote?: string;\n}\n\n/** Include useful errno details hidden behind Node's generic \"fetch failed\" error. */\nexport function formatVersionCheckError(error: unknown): string {\n\tconst rootMessage = error instanceof Error && error.message ? error.message : String(error);\n\tconst cause = error instanceof Error ? error.cause : undefined;\n\tconst causes = cause instanceof AggregateError ? cause.errors : cause === undefined ? [] : [cause];\n\tconst codes = causes\n\t\t.map((value) =>\n\t\t\ttypeof value === \"object\" && value !== null && \"code\" in value && typeof value.code === \"string\"\n\t\t\t\t? value.code\n\t\t\t\t: undefined,\n\t\t)\n\t\t.filter((code): code is string => code !== undefined);\n\n\tif (codes.length > 0) return `${rootMessage} (${[...new Set(codes)].join(\", \")})`;\n\tconst causeMessage = causes.find(\n\t\t(value): value is Error => value instanceof Error && Boolean(value.message),\n\t)?.message;\n\treturn causeMessage ? `${rootMessage} (cause: ${causeMessage})` : rootMessage;\n}\n\nexport function comparePackageVersions(leftVersion: string, rightVersion: string): number | undefined {\n\tconst left = valid(leftVersion.trim());\n\tconst right = valid(rightVersion.trim());\n\tif (!left || !right) {\n\t\treturn undefined;\n\t}\n\treturn compare(left, right);\n}\n\nexport function isNewerPackageVersion(candidateVersion: string, currentVersion: string): boolean {\n\tconst comparison = comparePackageVersions(candidateVersion, currentVersion);\n\tif (comparison !== undefined) {\n\t\treturn comparison > 0;\n\t}\n\treturn candidateVersion.trim() !== currentVersion.trim();\n}\n\nexport async function getLatestApexCodeRelease(\n\tcurrentVersion: string,\n\toptions: { timeoutMs?: number; retry?: boolean } = {},\n): Promise<LatestApexCodeRelease | undefined> {\n\tif (getApexEnvironment(\"APEX_CODE_OFFLINE\")) return undefined;\n\n\tconst response = await fetchWithRetry(\n\t\tLATEST_VERSION_URL,\n\t\t{\n\t\t\theaders: {\n\t\t\t\t\"User-Agent\": getApexCodeUserAgent(currentVersion),\n\t\t\t\taccept: \"application/json\",\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tmaxRetries: options.retry ? 2 : 0,\n\t\t\ttimeoutMs: options.timeoutMs ?? DEFAULT_VERSION_CHECK_TIMEOUT_MS,\n\t\t},\n\t);\n\tif (!response.ok) return undefined;\n\n\t// npm's per-tag registry endpoint returns the full package manifest for that\n\t// version; \"packageName\"/\"note\" have no npm-registry equivalent and are left\n\t// undefined -- callers already treat both as optional with sensible fallbacks.\n\tconst data = (await response.json()) as {\n\t\tname?: unknown;\n\t\tversion?: unknown;\n\t};\n\tif (typeof data.version !== \"string\" || !data.version.trim()) {\n\t\treturn undefined;\n\t}\n\tconst packageName = typeof data.name === \"string\" && data.name.trim() ? data.name.trim() : undefined;\n\treturn {\n\t\tversion: data.version.trim(),\n\t\t...(packageName && packageName !== PACKAGE_NAME ? { packageName } : {}),\n\t};\n}\n\nexport async function getLatestApexCodeVersion(\n\tcurrentVersion: string,\n\toptions: { timeoutMs?: number; retry?: boolean } = {},\n): Promise<string | undefined> {\n\treturn (await getLatestApexCodeRelease(currentVersion, options))?.version;\n}\n\nexport async function checkForNewApexCodeVersion(currentVersion: string): Promise<LatestApexCodeRelease | undefined> {\n\tif (getApexEnvironment(\"APEX_CODE_SKIP_VERSION_CHECK\")) return undefined;\n\n\ttry {\n\t\tconst latestRelease = await getLatestApexCodeRelease(currentVersion);\n\t\tif (latestRelease && isNewerPackageVersion(latestRelease.version, currentVersion)) {\n\t\t\treturn latestRelease;\n\t\t}\n\t\treturn undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n"]}
@@ -14,6 +14,6 @@
14
14
  ]
15
15
  },
16
16
  "dependencies": {
17
- "@anthropic-ai/sdk": "0.52.0"
17
+ "@anthropic-ai/sdk": "0.91.1"
18
18
  }
19
19
  }
@@ -1,15 +1,15 @@
1
1
  {
2
2
  "name": "apex-code",
3
- "version": "0.0.1-alpha.2",
3
+ "version": "0.0.1-alpha.4",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "apex-code",
9
- "version": "0.0.1-alpha.2",
9
+ "version": "0.0.1-alpha.4",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
- "apex-code-agent-core": "0.0.1-alpha.2",
12
+ "apex-code-agent-core": "0.0.1-alpha.4",
13
13
  "@earendil-works/pi-ai": "^0.84.1",
14
14
  "@earendil-works/pi-client": "^0.84.1",
15
15
  "@earendil-works/pi-protocol": "^0.84.1",
@@ -998,8 +998,8 @@
998
998
  }
999
999
  },
1000
1000
  "node_modules/apex-code-agent-core": {
1001
- "version": "0.0.1-alpha.2",
1002
- "resolved": "https://registry.npmjs.org/apex-code-agent-core/-/apex-code-agent-core-0.0.1-alpha.2.tgz",
1001
+ "version": "0.0.1-alpha.4",
1002
+ "resolved": "https://registry.npmjs.org/apex-code-agent-core/-/apex-code-agent-core-0.0.1-alpha.4.tgz",
1003
1003
  "license": "MIT",
1004
1004
  "dependencies": {
1005
1005
  "@earendil-works/pi-ai": "^0.84.1",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "apex-code",
3
- "version": "0.0.1-alpha.2",
3
+ "version": "0.0.1-alpha.4",
4
4
  "description": "Coding agent CLI with read, bash, edit, write tools and session management",
5
5
  "type": "module",
6
6
  "piConfig": {
@@ -43,7 +43,7 @@
43
43
  "prepublishOnly": "npm run clean && npm run build && npm run shrinkwrap"
44
44
  },
45
45
  "dependencies": {
46
- "apex-code-agent-core": "0.0.1-alpha.2",
46
+ "apex-code-agent-core": "0.0.1-alpha.4",
47
47
  "@earendil-works/pi-ai": "^0.84.1",
48
48
  "@earendil-works/pi-client": "^0.84.1",
49
49
  "@earendil-works/pi-protocol": "^0.84.1",